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
autopilot-spec-to-pr.ts8.9 KB · 305 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
/**
 * Autopilot task — spec-to-PR loop.
 *
 * Every tick, walk every repo the owner-user maintains and look at the
 * files under `.gluecron/specs/*.md`. For each spec whose front-matter is
 * `status: ready` AND that does not yet have an open PR pointing at the
 * same spec path, dispatch `runSpecToPr`.
 *
 * Mirrors the dependency-injection shape of `ai-build-tasks.ts`:
 *   - `findCandidates` — surface ready specs across enabled repos.
 *   - `hasOpenLinkedPr`  — short-circuit if a previous tick already opened a PR.
 *   - `dispatcher`     — runs `runSpecToPr`. Tests inject a stub.
 *
 * Skip rules (graceful no-ops):
 *   - `AUTOPILOT_DISABLED=1` short-circuits the task entirely.
 *   - Missing `ANTHROPIC_API_KEY` short-circuits (the dispatcher would also
 *     refuse, but skipping here saves a DB round-trip per tick).
 *   - Repos flagged as archived are filtered out at the SQL layer.
 *
 * Never throws. Per-repo failures are logged and swallowed so one broken
 * spec can't wedge the autopilot tick.
 */

import { and, eq, like } from "drizzle-orm";
import { join } from "path";
import { db } from "../db";
import { pullRequests, repositories, users } from "../db/schema";
import { getBlob, getTreeRecursive } from "../git/repository";
import {
  AI_SPEC_PR_MARKER,
  parseFrontMatter,
  runSpecToPr,
  type RunSpecToPrResult,
} from "./spec-to-pr";

/** Hard cap to bound work per tick on big multi-tenant deployments. */
const DEFAULT_MAX_SPECS_PER_TICK = 10;
/** Per-repo cap so one busy repo can't starve the rest. */
const DEFAULT_MAX_SPECS_PER_REPO = 3;

export interface SpecToPrCandidate {
  repositoryId: string;
  ownerName: string;
  repoName: string;
  defaultBranch: string;
  /** Path inside the repo, e.g. `.gluecron/specs/foo.md`. */
  specPath: string;
}

export interface SpecToPrDispatcher {
  (args: {
    repositoryId: string;
    specPath: string;
    baseSha?: string;
  }): Promise<RunSpecToPrResult>;
}

export interface SpecToPrTaskDeps {
  /** Inject candidate finder (defaults walk every enabled repo). */
  findCandidates?: (
    limit: number,
    perRepoLimit: number
  ) => Promise<SpecToPrCandidate[]>;
  /** Inject the dedup check (looks for any PR body referencing the spec path). */
  hasOpenLinkedPr?: (
    repositoryId: string,
    specPath: string
  ) => Promise<boolean>;
  /** Inject the dispatcher (real one calls `runSpecToPr`). */
  dispatcher?: SpecToPrDispatcher;
  /** Override the per-tick cap. */
  maxSpecsPerTick?: number;
  /** Override the per-repo cap. */
  maxSpecsPerRepo?: number;
}

export interface SpecToPrTaskSummary {
  considered: number;
  dispatched: number;
  skipped: number;
  failed: number;
}

/**
 * Default candidate finder. For every non-archived repo (capped via
 * `limit`), list `.gluecron/specs/*.md` on the default branch, parse each
 * file's front-matter, and surface specs whose status is `ready`.
 *
 * We intentionally cap the per-repo result at `perRepoLimit` so one repo
 * with hundreds of ready specs can't monopolise the tick.
 */
async function defaultFindCandidates(
  limit: number,
  perRepoLimit: number
): Promise<SpecToPrCandidate[]> {
  let repoRows: Array<{
    id: string;
    name: string;
    defaultBranch: string;
    ownerName: string | null;
  }>;
  try {
    repoRows = await db
      .select({
        id: repositories.id,
        name: repositories.name,
        defaultBranch: repositories.defaultBranch,
        ownerName: users.username,
      })
      .from(repositories)
      .innerJoin(users, eq(users.id, repositories.ownerId))
      .where(eq(repositories.isArchived, false))
      .limit(200);
  } catch (err) {
    console.error("[autopilot] spec-to-pr: repo query failed:", err);
    return [];
  }

  const out: SpecToPrCandidate[] = [];
  for (const repo of repoRows) {
    if (out.length >= limit) break;
    if (!repo.ownerName) continue;
    const defaultBranch = repo.defaultBranch || "main";
    let specPaths: string[] = [];
    try {
      const tree = await getTreeRecursive(repo.ownerName, repo.name, defaultBranch, 5000);
      if (!tree) continue;
      specPaths = tree.tree
        .filter(
          (e) =>
            e.type === "blob" &&
            e.path.startsWith(".gluecron/specs/") &&
            e.path.toLowerCase().endsWith(".md")
        )
        .map((e) => e.path)
        .slice(0, perRepoLimit * 5); // headroom — we'll filter by status next
    } catch (err) {
      console.warn(
        `[autopilot] spec-to-pr: tree scan failed for ${repo.ownerName}/${repo.name}:`,
        err instanceof Error ? err.message : err
      );
      continue;
    }

    let perRepo = 0;
    for (const path of specPaths) {
      if (perRepo >= perRepoLimit) break;
      if (out.length >= limit) break;
      try {
        const blob = await getBlob(
          repo.ownerName,
          repo.name,
          defaultBranch,
          path
        );
        if (!blob || blob.isBinary) continue;
        const parsed = parseFrontMatter(blob.content);
        const status = (parsed.frontMatter.status || "").toLowerCase();
        if (status !== "ready") continue;
        out.push({
          repositoryId: repo.id,
          ownerName: repo.ownerName,
          repoName: repo.name,
          defaultBranch,
          specPath: path,
        });
        perRepo += 1;
      } catch (err) {
        console.warn(
          `[autopilot] spec-to-pr: blob read failed for ${repo.ownerName}/${repo.name}:${path}:`,
          err instanceof Error ? err.message : err
        );
      }
    }
  }

  return out;
}

/**
 * Default dedup check. We look for any PR (open or otherwise) whose body
 * embeds the spec path; the autopilot writes the spec path into the PR
 * body so this is a reliable signal.
 */
async function defaultHasOpenLinkedPr(
  repositoryId: string,
  specPath: string
): Promise<boolean> {
  try {
    const rows = await db
      .select({ id: pullRequests.id })
      .from(pullRequests)
      .where(
        and(
          eq(pullRequests.repositoryId, repositoryId),
          like(pullRequests.body, `%${AI_SPEC_PR_MARKER}%`),
          like(pullRequests.body, `%${specPath}%`)
        )
      )
      .limit(1);
    return rows.length > 0;
  } catch {
    return false;
  }
}

/** Default dispatcher just calls `runSpecToPr`. */
async function defaultDispatcher(args: {
  repositoryId: string;
  specPath: string;
  baseSha?: string;
}): Promise<RunSpecToPrResult> {
  try {
    return await runSpecToPr(args);
  } catch (err) {
    return {
      ok: false,
      error: err instanceof Error ? err.message : String(err),
    };
  }
}

/**
 * One iteration of the spec-to-pr loop. Returns a counts summary suitable
 * for the autopilot tick log. Never throws.
 */
export async function runSpecToPrTaskOnce(
  deps: SpecToPrTaskDeps = {}
): Promise<SpecToPrTaskSummary> {
  // Graceful gates — keep the work-skip cheap.
  if (process.env.AUTOPILOT_DISABLED === "1") {
    return { considered: 0, dispatched: 0, skipped: 0, failed: 0 };
  }
  if (!process.env.ANTHROPIC_API_KEY) {
    return { considered: 0, dispatched: 0, skipped: 0, failed: 0 };
  }

  const limit = deps.maxSpecsPerTick ?? DEFAULT_MAX_SPECS_PER_TICK;
  const perRepoLimit = deps.maxSpecsPerRepo ?? DEFAULT_MAX_SPECS_PER_REPO;
  const findCandidates = deps.findCandidates ?? defaultFindCandidates;
  const hasOpenLinkedPr = deps.hasOpenLinkedPr ?? defaultHasOpenLinkedPr;
  const dispatcher = deps.dispatcher ?? defaultDispatcher;

  let candidates: SpecToPrCandidate[] = [];
  try {
    candidates = await findCandidates(limit, perRepoLimit);
  } catch (err) {
    console.error("[autopilot] spec-to-pr: findCandidates threw:", err);
    return { considered: 0, dispatched: 0, skipped: 0, failed: 0 };
  }

  let dispatched = 0;
  let skipped = 0;
  let failed = 0;

  for (const cand of candidates) {
    try {
      if (await hasOpenLinkedPr(cand.repositoryId, cand.specPath)) {
        skipped += 1;
        continue;
      }
      const result = await dispatcher({
        repositoryId: cand.repositoryId,
        specPath: cand.specPath,
      });
      if (result.ok) {
        dispatched += 1;
      } else {
        failed += 1;
        console.warn(
          `[autopilot] spec-to-pr: dispatch failed for ${cand.ownerName}/${cand.repoName}:${cand.specPath}: ${result.error}`
        );
      }
    } catch (err) {
      failed += 1;
      console.error(
        `[autopilot] spec-to-pr: per-spec failure for ${cand.specPath}:`,
        err
      );
    }
  }

  return {
    considered: candidates.length,
    dispatched,
    skipped,
    failed,
  };
}

// Re-export the disk-path helper so callers can build the same paths the
// task computes internally — useful in admin tooling / observability.
export function repoDiskPath(ownerName: string, repoName: string): string {
  const base = process.env.GIT_REPOS_PATH || "./repos";
  return join(base, ownerName, `${repoName}.git`);
}

/** Test-only exports. */
export const __test = {
  defaultFindCandidates,
  defaultHasOpenLinkedPr,
  defaultDispatcher,
  DEFAULT_MAX_SPECS_PER_TICK,
  DEFAULT_MAX_SPECS_PER_REPO,
};