CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
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 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 | /**
* 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.
*
* 2026 polish: scoped `.specs-*` class system. Eyebrow + display headline +
* subtitle hero, card sections for the form + the "how this works" steps,
* primary CTA on the submit button. All form fields, names, actions, and
* the dynamic-import behaviour are unchanged.
*/
import { Hono } from "hono";
import { and, eq, like } from "drizzle-orm";
import { db } from "../db";
import { repositories, users, issues, pullRequests } 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, getBlob, getTreeRecursive } from "../git/repository";
import {
AI_SPEC_PR_MARKER,
parseFrontMatter,
type SpecStatus,
} from "../lib/spec-to-pr";
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;
});
})();
`;
// ─── Scoped CSS (.specs-*) ─────────────────────────────────────────────────
const specsStyles = `
.specs-wrap { max-width: 1100px; margin: 0 auto; padding: var(--space-5) var(--space-4) var(--space-8); }
/* ─── Header ─── */
.specs-head { margin-bottom: var(--space-5); }
.specs-eyebrow {
display: inline-flex;
align-items: center;
gap: 8px;
text-transform: uppercase;
font-family: var(--font-mono);
font-size: 11px;
letter-spacing: 0.16em;
color: var(--text-muted);
font-weight: 600;
margin-bottom: 10px;
}
.specs-eyebrow-dot {
width: 8px; height: 8px;
border-radius: 9999px;
background: linear-gradient(135deg, #8c6dff, #36c5d6);
box-shadow: 0 0 0 3px rgba(140,109,255,0.18);
}
.specs-pill-experimental {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 2px 8px;
margin-left: 4px;
border-radius: 9999px;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.06em;
background: rgba(251,191,36,0.12);
color: #fde68a;
box-shadow: inset 0 0 0 1px rgba(251,191,36,0.32);
}
.specs-title {
font-family: var(--font-display);
font-size: clamp(26px, 3.6vw, 40px);
font-weight: 800;
letter-spacing: -0.028em;
line-height: 1.05;
margin: 0 0 6px;
color: var(--text-strong);
}
.specs-title-grad {
background-image: linear-gradient(135deg, #a48bff 0%, #8c6dff 50%, #36c5d6 100%);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
color: transparent;
}
.specs-sub {
margin: 0;
font-size: 14px;
color: var(--text-muted);
line-height: 1.5;
max-width: 720px;
}
.specs-sub a { color: var(--accent); text-decoration: none; }
.specs-sub a:hover { text-decoration: underline; }
.specs-sub code {
font-family: var(--font-mono);
font-size: 12px;
background: rgba(255,255,255,0.04);
padding: 1px 6px;
border-radius: 4px;
}
/* ─── Banners ─── */
.specs-banner {
margin-bottom: var(--space-4);
padding: 10px 14px;
border-radius: 10px;
font-size: 13.5px;
border: 1px solid var(--border);
background: rgba(255,255,255,0.025);
color: var(--text);
display: flex;
align-items: flex-start;
gap: 10px;
line-height: 1.45;
}
.specs-banner.is-info {
border-color: rgba(54,197,214,0.40);
background: rgba(54,197,214,0.08);
color: #cffafe;
}
.specs-banner.is-error {
border-color: rgba(248,113,113,0.40);
background: rgba(248,113,113,0.08);
color: #fecaca;
}
.specs-banner-dot {
width: 8px; height: 8px;
border-radius: 9999px;
background: currentColor;
margin-top: 6px;
flex-shrink: 0;
}
.specs-banner a {
color: inherit;
text-decoration: underline;
font-weight: 600;
}
/* ─── Section card ─── */
.specs-section {
margin-bottom: var(--space-5);
background: var(--bg-elevated);
border: 1px solid var(--border);
border-radius: 14px;
overflow: hidden;
position: relative;
}
.specs-section::before {
content: '';
position: absolute;
top: 0; left: 0; right: 0;
height: 2px;
background: linear-gradient(90deg, transparent 0%, #8c6dff 30%, #36c5d6 70%, transparent 100%);
opacity: 0.55;
pointer-events: none;
}
.specs-section-head {
padding: var(--space-4) var(--space-5) var(--space-3);
border-bottom: 1px solid var(--border);
}
.specs-section-title {
margin: 0;
font-family: var(--font-display);
font-size: 16px;
font-weight: 700;
letter-spacing: -0.018em;
color: var(--text-strong);
}
.specs-section-sub {
margin: 6px 0 0;
font-size: 12.5px;
color: var(--text-muted);
line-height: 1.45;
}
.specs-section-body {
padding: var(--space-4) var(--space-5);
}
/* ─── Form fields ─── */
.specs-field { margin-bottom: var(--space-4); }
.specs-field:last-child { margin-bottom: 0; }
.specs-field-label {
display: block;
font-size: 11.5px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--text-muted);
margin-bottom: 6px;
}
.specs-input,
.specs-select,
.specs-textarea {
width: 100%;
box-sizing: border-box;
padding: 10px 12px;
font: inherit;
font-size: 13.5px;
color: var(--text);
background: rgba(255,255,255,0.03);
border: 1px solid var(--border-strong);
border-radius: 10px;
transition: border-color 120ms ease, background 120ms ease, box-shadow 120ms ease;
}
.specs-textarea {
font-family: var(--font-mono);
font-size: 13px;
line-height: 1.55;
resize: vertical;
min-height: 200px;
}
.specs-input:focus,
.specs-select:focus,
.specs-textarea:focus {
outline: none;
border-color: rgba(140,109,255,0.55);
background: rgba(255,255,255,0.05);
box-shadow: 0 0 0 3px rgba(140,109,255,0.18);
}
.specs-select {
appearance: none;
padding-right: 30px;
background-image:
linear-gradient(45deg, transparent 50%, var(--text-muted) 50%),
linear-gradient(135deg, var(--text-muted) 50%, transparent 50%);
background-position: right 12px top 50%, right 7px top 50%;
background-size: 5px 5px, 5px 5px;
background-repeat: no-repeat;
}
.specs-field-hint {
margin-top: 6px;
font-size: 11.5px;
color: var(--text-muted);
line-height: 1.45;
}
/* ─── Buttons ─── */
.specs-actions {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
padding-top: 4px;
}
.specs-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 10px 18px;
border-radius: 10px;
font-size: 13.5px;
font-weight: 600;
text-decoration: none;
border: 1px solid transparent;
cursor: pointer;
font: inherit;
line-height: 1;
white-space: nowrap;
transition: transform 120ms ease, box-shadow 120ms ease, background 120ms ease, border-color 120ms ease, color 120ms ease;
}
.specs-btn-primary {
background: linear-gradient(135deg, #8c6dff 0%, #36c5d6 100%);
color: #ffffff;
box-shadow: 0 6px 18px -6px rgba(140,109,255,0.50), inset 0 1px 0 rgba(255,255,255,0.16);
}
.specs-btn-primary:hover {
transform: translateY(-1px);
box-shadow: 0 10px 24px -8px rgba(140,109,255,0.60), inset 0 1px 0 rgba(255,255,255,0.20);
color: #ffffff;
text-decoration: none;
}
.specs-btn-primary:disabled {
cursor: not-allowed;
opacity: 0.6;
transform: none;
box-shadow: none;
}
.specs-actions-hint {
font-size: 12px;
color: var(--text-muted);
}
/* ─── How-this-works step cards ─── */
.specs-steps {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 10px;
}
.specs-step {
padding: 14px;
background: rgba(255,255,255,0.018);
border: 1px solid var(--border);
border-radius: 11px;
transition: border-color 120ms ease, background 120ms ease;
}
.specs-step:hover {
border-color: var(--border-strong);
background: rgba(255,255,255,0.03);
}
.specs-step-num {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px; height: 24px;
border-radius: 7px;
background: rgba(140,109,255,0.16);
color: #c4b5fd;
box-shadow: inset 0 0 0 1px rgba(140,109,255,0.32);
font-family: var(--font-mono);
font-size: 12px;
font-weight: 700;
margin-bottom: 10px;
}
.specs-step-title {
margin: 0 0 4px;
font-family: var(--font-display);
font-size: 13.5px;
font-weight: 700;
color: var(--text-strong);
letter-spacing: -0.005em;
}
.specs-step-body {
margin: 0;
font-size: 12.5px;
color: var(--text-muted);
line-height: 1.5;
}
.specs-step-body code {
font-family: var(--font-mono);
font-size: 11.5px;
background: rgba(255,255,255,0.04);
padding: 1px 5px;
border-radius: 4px;
color: var(--text);
}
/* ─── 403 / not-found ─── */
.specs-empty {
max-width: 540px;
margin: var(--space-8) auto;
padding: var(--space-6);
text-align: center;
background: var(--bg-elevated);
border: 1px dashed var(--border-strong);
border-radius: 16px;
}
.specs-empty h2 {
font-family: var(--font-display);
font-size: 20px;
margin: 0 0 8px;
color: var(--text-strong);
}
.specs-empty p {
margin: 0;
color: var(--text-muted);
font-size: 13.5px;
}
`;
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 (
<div class="specs-wrap">
<header class="specs-head">
<div class="specs-eyebrow">
<span class="specs-eyebrow-dot" aria-hidden="true" />
Repository · Spec to PR
<span class="specs-pill-experimental">Experimental</span>
</div>
<h1 class="specs-title">
<span class="specs-title-grad">Describe it. Ship a draft.</span>
</h1>
<p class="specs-sub">
Write a feature in plain English. Claude drafts the code changes
and opens a pull request against the branch you pick. Every PR is{" "}
<strong>draft by default</strong> — review every line before merging.
</p>
</header>
{fromIssueNumber && (
<div class="specs-banner is-info" role="status">
<span class="specs-banner-dot" aria-hidden="true" />
<span>
Building from issue{" "}
<a href={`/${ownerName}/${repoName}/issues/${fromIssueNumber}`}>
#{fromIssueNumber}
{fromIssueTitle ? ` — ${fromIssueTitle}` : ""}
</a>
. The spec below has been pre-filled and will auto-close the
issue on merge.
</span>
</div>
)}
{error && (
<div class="specs-banner is-error" role="alert">
<span class="specs-banner-dot" aria-hidden="true" />
<span>{error}</span>
</div>
)}
<section class="specs-section">
<header class="specs-section-head">
<h2 class="specs-section-title">Feature spec</h2>
<p class="specs-section-sub">
One sentence or a paragraph. Be specific about files, behaviour,
or success criteria when you can.
</p>
</header>
<div class="specs-section-body">
<form
method="post"
action={`/${ownerName}/${repoName}/spec`}
id="spec-form"
>
<div class="specs-field">
<label class="specs-field-label" for="spec">What do you want built?</label>
<textarea
class="specs-textarea"
name="spec"
id="spec"
rows={10}
required
placeholder="add a dark mode toggle to the settings page"
>{spec || ""}</textarea>
</div>
<div class="specs-field">
<label class="specs-field-label" for="baseRef">Base branch</label>
<select
class="specs-select"
name="baseRef"
id="baseRef"
value={selectedBase}
>
{branchList.map((b) => (
<option value={b} selected={b === selectedBase}>
{b}
</option>
))}
</select>
<p class="specs-field-hint">
The draft PR will target this branch. Nothing lands without
your approval.
</p>
</div>
<div class="specs-actions">
<button type="submit" class="specs-btn specs-btn-primary">
Generate PR with AI
</button>
<span class="specs-actions-hint">Typically 10-30 seconds.</span>
</div>
</form>
</div>
</section>
<section class="specs-section">
<header class="specs-section-head">
<h2 class="specs-section-title">How this works</h2>
<p class="specs-section-sub">
Three steps from spec to mergeable diff — all observable, all
reversible.
</p>
</header>
<div class="specs-section-body">
<div class="specs-steps">
<div class="specs-step">
<span class="specs-step-num">1</span>
<h3 class="specs-step-title">You write a spec.</h3>
<p class="specs-step-body">
A sentence or a paragraph describing the change you want.
</p>
</div>
<div class="specs-step">
<span class="specs-step-num">2</span>
<h3 class="specs-step-title">Claude drafts the diff.</h3>
<p class="specs-step-body">
We fetch the base branch, run Claude against the repo, and
commit the proposed changes to a new branch.
</p>
</div>
<div class="specs-step">
<span class="specs-step-num">3</span>
<h3 class="specs-step-title">A draft PR opens.</h3>
<p class="specs-step-body">
You review, edit, and merge on your terms. Nothing lands on{" "}
<code>{selectedBase}</code> automatically.
</p>
</div>
</div>
</div>
</section>
<script dangerouslySetInnerHTML={{ __html: DISABLE_ON_SUBMIT_JS }} />
);
}
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(
,
404
);
}
if (!hasWriteAccess(resolved, user.id)) {
return c.html(
,
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(
);
});
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(
,
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(
,
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}`);
});
// ─── GET /specs — dashboard listing all specs across the user's repos ──────
//
// Walks every repo the signed-in user owns, looks at `.gluecron/specs/*.md`
// on the default branch, parses the front-matter for `status:` + `title:`,
// and surfaces a flat list with linked PR (when one exists). Soft-fails on
// any repo that can't be scanned — the dashboard still renders.
interface SpecRow {
ownerName: string;
repoName: string;
specPath: string;
title: string;
status: SpecStatus;
prNumber: number | null;
}
async function collectSpecsForOwner(ownerId: string): Promise<SpecRow[]> {
let owner: { username: string } | undefined;
try {
const [row] = await db
.select({ username: users.username })
.from(users)
.where(eq(users.id, ownerId))
.limit(1);
owner = row;
} catch {
return [];
}
if (!owner) return [];
let repos: Array<{ id: string; name: string; defaultBranch: string }> = [];
try {
repos = await db
.select({
id: repositories.id,
name: repositories.name,
defaultBranch: repositories.defaultBranch,
})
.from(repositories)
.where(
and(eq(repositories.ownerId, ownerId), eq(repositories.isArchived, false))
)
.limit(100);
} catch {
return [];
}
const out: SpecRow[] = [];
for (const repo of repos) {
const branch = repo.defaultBranch || "main";
let paths: string[] = [];
try {
const tree = await getTreeRecursive(owner.username, repo.name, branch, 5000);
if (!tree) continue;
paths = tree.tree
.filter(
(e) =>
e.type === "blob" &&
e.path.startsWith(".gluecron/specs/") &&
e.path.toLowerCase().endsWith(".md")
)
.map((e) => e.path);
} catch {
continue;
}
for (const p of paths) {
let content = "";
try {
const blob = await getBlob(owner.username, repo.name, branch, p);
if (!blob || blob.isBinary) continue;
content = blob.content;
} catch {
continue;
}
const parsed = parseFrontMatter(content);
const title =
(parsed.frontMatter.title && parsed.frontMatter.title.trim()) ||
(p.split("/").pop() || p).replace(/\.md$/i, "");
const statusRaw = (parsed.frontMatter.status || "draft").toLowerCase();
const status: SpecStatus =
statusRaw === "draft" ||
statusRaw === "ready" ||
statusRaw === "building" ||
statusRaw === "shipped" ||
statusRaw === "failed"
? (statusRaw as SpecStatus)
: "draft";
// Best-effort PR lookup: any PR whose body mentions the spec path
// and carries the spec marker. Newest first.
let prNumber: number | null = null;
try {
const [pr] = await db
.select({ number: pullRequests.number })
.from(pullRequests)
.where(
and(
eq(pullRequests.repositoryId, repo.id),
like(pullRequests.body, `%${AI_SPEC_PR_MARKER}%`),
like(pullRequests.body, `%${p}%`)
)
)
.orderBy(pullRequests.createdAt)
.limit(1);
if (pr) prNumber = pr.number;
} catch {
prNumber = null;
}
out.push({
ownerName: owner.username,
repoName: repo.name,
specPath: p,
title,
status,
prNumber,
});
}
}
return out;
}
specs.get("/specs", softAuth, requireAuth, async (c) => {
const user = c.get("user")!;
const rows = await collectSpecsForOwner(user.id);
const byStatus = (s: SpecStatus) => rows.filter((r) => r.status === s);
const statusBadgeColors: Record<SpecStatus, string> = {
draft: "rgba(148,163,184,0.16)",
ready: "rgba(54,197,214,0.18)",
building: "rgba(140,109,255,0.20)",
shipped: "rgba(34,197,94,0.18)",
failed: "rgba(248,113,113,0.18)",
};
return c.html(
);
});
export default specs;
|