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
scheduled-workflows.ts7.8 KB · 266 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
/**
 * Scheduled workflows — fires `on: schedule` triggers from the autopilot
 * tick.
 *
 * Pipeline (per tick, default every 5 minutes via src/lib/autopilot.ts):
 *
 *   1. Select all non-disabled workflows whose serialised `parsed` JSON
 *      includes a non-empty `schedules` array. (Cheap LIKE filter — DB
 *      doesn't natively know about JSON keys here, and we want to avoid
 *      pulling all workflows on every tick.)
 *   2. For each workflow:
 *        - Look up the latest schedule-triggered run (event="schedule").
 *          That row's queuedAt is the `since` boundary; absent → use
 *          (now - 6 minutes), so a freshly-imported workflow doesn't
 *          back-fire for hours of crons.
 *        - For each cron string, parse via src/lib/cron.ts and ask
 *          `cronFiredBetween(since, now)`. The first cron that fired
 *          wins — we enqueue exactly one run per workflow per tick.
 *   3. enqueueRun(...) with event="schedule", ref=defaultBranch,
 *      commitSha=resolved-default-branch-HEAD. The existing runner
 *      (src/lib/workflow-runner.ts) picks it up exactly like a manual
 *      run.
 *
 * Fail-open: every step swallows DB errors and returns a result object
 * so the autopilot ticker never wedges. Returns a per-call summary so
 * callers (e.g. the admin dashboard) can show "last tick fired N runs."
 *
 * Safety guard: caps each tick at MAX_RUNS_PER_TICK so a misconfigured
 * cron and an empty schedule-runs table cannot stampede the queue.
 */

import { and, desc, eq, isNull, sql } from "drizzle-orm";
import { db } from "../db";
import {
  workflowRuns,
  workflows,
  repositories,
} from "../db/schema";
import { parseCron, cronFiredBetween } from "./cron";
import { enqueueRun } from "./workflow-runner";
import { resolveRef, getDefaultBranch } from "../git/repository";

export const MAX_RUNS_PER_TICK = 50;
const SINCE_FALLBACK_MS = 6 * 60_000; // 6 min — slightly > default 5-min tick

export type ScheduledTickResult = {
  considered: number;
  fired: number;
  errors: number;
};

type WorkflowRow = {
  id: string;
  repositoryId: string;
  parsed: string;
};

/**
 * Parse the `parsed` JSON column and return the cron expressions, or [].
 * Defensive — never throws.
 */
export function schedulesFromParsedJson(parsedJson: string): string[] {
  try {
    const obj = JSON.parse(parsedJson || "{}");
    const out = Array.isArray(obj?.schedules) ? obj.schedules : [];
    return out.filter((s: unknown): s is string => typeof s === "string" && s.trim().length > 0);
  } catch {
    return [];
  }
}

/**
 * Pure decision helper — given a workflow's schedules + last fire wall +
 * current wall, return the first cron that should fire (or null).
 * Exposed for unit tests so the cron→fire wiring is verifiable without
 * a DB.
 */
export function firstCronToFire(
  schedules: string[],
  since: Date,
  until: Date
): string | null {
  for (const expr of schedules) {
    const parsed = parseCron(expr);
    if (!parsed.ok) continue;
    if (cronFiredBetween(parsed.cron, since, until)) return expr;
  }
  return null;
}

async function lastScheduleRunQueuedAt(
  workflowId: string
): Promise<Date | null> {
  try {
    const [row] = await db
      .select({ queuedAt: workflowRuns.queuedAt })
      .from(workflowRuns)
      .where(
        and(
          eq(workflowRuns.workflowId, workflowId),
          eq(workflowRuns.event, "schedule")
        )
      )
      .orderBy(desc(workflowRuns.queuedAt))
      .limit(1);
    return row ? new Date(row.queuedAt) : null;
  } catch {
    return null;
  }
}

async function loadOwnerAndRepoName(
  repositoryId: string
): Promise<{ ownerName: string; repoName: string; defaultBranch: string } | null> {
  try {
    const [row] = await db
      .select({
        repoName: repositories.name,
        ownerId: repositories.ownerId,
        defaultBranch: repositories.defaultBranch,
      })
      .from(repositories)
      .where(eq(repositories.id, repositoryId))
      .limit(1);
    if (!row) return null;
    // Owner username lookup via the standard repositories.owner_id → users
    // join. Performed lazily to avoid a join on the hot list query.
    const { users } = await import("../db/schema");
    const [owner] = await db
      .select({ username: users.username })
      .from(users)
      .where(eq(users.id, row.ownerId))
      .limit(1);
    if (!owner) return null;
    return {
      ownerName: owner.username,
      repoName: row.repoName,
      defaultBranch: row.defaultBranch || "main",
    };
  } catch {
    return null;
  }
}

/**
 * Walk every non-disabled workflow whose parsed JSON could include a
 * schedules field, decide if any cron fired since the last schedule-run,
 * and enqueue at most one run per workflow per tick.
 */
export async function runScheduledWorkflowsTick(
  now: Date = new Date()
): Promise<ScheduledTickResult> {
  const result: ScheduledTickResult = { considered: 0, fired: 0, errors: 0 };

  let candidates: WorkflowRow[] = [];
  try {
    candidates = await db
      .select({
        id: workflows.id,
        repositoryId: workflows.repositoryId,
        parsed: workflows.parsed,
      })
      .from(workflows)
      .where(
        and(
          eq(workflows.disabled, false),
          // Cheap pre-filter: only workflows whose parsed JSON contains
          // the literal token "schedules" (presence implies non-empty
          // array via the parser contract). This is intentionally a
          // string-LIKE — JSON-aware operators are nice-to-have.
          sql`${workflows.parsed} LIKE '%"schedules"%'`
        )
      );
  } catch {
    candidates = [];
    result.errors += 1;
  }

  // Defensive: if a leaked mock or DB driver returns a non-iterable, coerce
  // to an empty array so `for (const w of candidates)` doesn't throw. This
  // closes the cross-suite test-pollution failure where another test file's
  // mock.module("../db", ...) leaked into this code path.
  if (!Array.isArray(candidates)) {
    candidates = [];
    result.errors += 1;
  }

  for (const w of candidates) {
    if (result.fired >= MAX_RUNS_PER_TICK) break;
    result.considered += 1;

    const schedules = schedulesFromParsedJson(w.parsed);
    if (schedules.length === 0) continue;

    const lastQ = await lastScheduleRunQueuedAt(w.id);
    const since = lastQ
      ? lastQ
      : new Date(now.getTime() - SINCE_FALLBACK_MS);

    const expr = firstCronToFire(schedules, since, now);
    if (!expr) continue;

    const repoMeta = await loadOwnerAndRepoName(w.repositoryId);
    if (!repoMeta) {
      result.errors += 1;
      continue;
    }

    let commitSha: string | null = null;
    try {
      commitSha = await resolveRef(
        repoMeta.ownerName,
        repoMeta.repoName,
        repoMeta.defaultBranch
      );
    } catch {
      commitSha = null;
    }
    if (!commitSha) {
      // Try to recover the default branch via the on-disk repo if the DB
      // value is stale — best-effort. If still unknown, skip.
      try {
        const def = await getDefaultBranch(
          repoMeta.ownerName,
          repoMeta.repoName
        );
        if (def) {
          commitSha = await resolveRef(
            repoMeta.ownerName,
            repoMeta.repoName,
            def
          );
        }
      } catch {
        commitSha = null;
      }
    }
    if (!commitSha) {
      result.errors += 1;
      continue;
    }

    try {
      await enqueueRun({
        workflowId: w.id,
        repositoryId: w.repositoryId,
        event: "schedule",
        ref: `refs/heads/${repoMeta.defaultBranch}`,
        commitSha,
        triggeredBy: null,
      });
      result.fired += 1;
    } catch {
      result.errors += 1;
    }
  }

  return result;
}

/** Test-only exposed internals so DB-less test cases can pin behaviour. */
export const __test = {
  schedulesFromParsedJson,
  firstCronToFire,
  SINCE_FALLBACK_MS,
};