/ opencodehub / src / lib / workflows.ts
Swadhin Biswas Feature/ai code reviewer (#79) · 8/16/2026
cfd400d
241 lines · 10.3 KB
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

import { PipelineRunner } from "./pipeline";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { getDatabase, schema } from "@/db";
import { logger } from "@/lib/logger";
import { eq } from "drizzle-orm";
import path from "path";
import fs from "fs/promises";
import { existsSync } from "fs";
import { getGit } from "@/lib/git";

// Initialize Runner (Singleton-ish for this context)
const runner = new PipelineRunner({
    workDir: path.join(process.cwd(), "data", "runner", "work"),
    artifactsDir: path.join(process.cwd(), "data", "runner", "artifacts"),
    cacheDir: path.join(process.cwd(), "data", "runner", "cache")
});

// Ensure dirs exist
async function ensureDirs() {
    await fs.mkdir(path.join(process.cwd(), "data", "runner", "work"), { recursive: true });
    await fs.mkdir(path.join(process.cwd(), "data", "runner", "artifacts"), { recursive: true });
    await fs.mkdir(path.join(process.cwd(), "data", "runner", "cache"), { recursive: true });
}
ensureDirs();


export async function triggerRepoWorkflows(repoId: string, commitSha: string, ref: string, pusherId: string) {
    logger.info({ repoId, ref, commitSha }, "Checking workflows");

    try {
        // 1. Get Repo Disk Path
        const db = getDatabase() as NodePgDatabase<typeof schema>;
        const repo = await db.query.repositories.findFirst({
            where: eq(schema.repositories.id, repoId)
        });

        if (!repo) return;

        // 2. For cloud storage, we need to resolve the repo path to a local directory
        //    For local storage, diskPath is already local.
        const { resolveRepoPath } = await import("./git-storage");
        const { getGit } = await import("./git");

        let localRepoPath: string;
        try {
            localRepoPath = await resolveRepoPath(repo.diskPath);
        } catch (resolveErr) {
            // If we can't resolve the path (e.g., repo doesn't exist yet in storage), skip workflows
            logger.debug({ err: resolveErr, diskPath: repo.diskPath }, "Could not resolve repo path for workflows, skipping");
            return;
        }

        const git = getGit(localRepoPath);

        // Look for .github/workflows/*.yml in the actual repo content
        // List files in .github/workflows
        const treeInfo = await git.raw(["ls-tree", "-r", "--name-only", commitSha, ".github/workflows"]);
        const workflowFiles = treeInfo.split("\n").filter(f => f.endsWith(".yml") || f.endsWith(".yaml"));

        if (workflowFiles.length === 0) {
            logger.debug("No workflows found");
            return;
        }

        logger.info({ count: workflowFiles.length, files: workflowFiles }, "Found workflows");

        // 3. Process each workflow
        for (const file of workflowFiles) {
            try {
                const content = await git.show([`${commitSha}:${file}`]);

                // Parse manually since PipelineRunner expects a file path usually, 
                // but we can create a temp file or refactor runner.
                // Let's write to a temp file for the runner to parse
                const tempWorkflowPath = path.join("/tmp", `workflow-${crypto.randomUUID()}.yml`);
                await fs.writeFile(tempWorkflowPath, content);

                const config = await runner.parseWorkflow(tempWorkflowPath);
                await fs.unlink(tempWorkflowPath); // Clean up

                // Get changed files by diffing with parent commit
                let changedPaths: string[] = [];
                try {
                    // Get parent commit(s)
                    const parentOutput = await git.raw(["rev-parse", `${commitSha}^`]).catch(() => "");
                    const parentSha = parentOutput.trim();

                    if (parentSha) {
                        // Get diff between parent and current commit
                        const diffOutput = await git.raw([
                            "diff", "--name-only", parentSha, commitSha
                        ]);
                        changedPaths = diffOutput.split("\n").filter(Boolean);
                        logger.debug({ changedPaths, count: changedPaths.length }, "Changed files in push");
                    } else {
                        // Initial commit - all files are new
                        const treeOutput = await git.raw(["ls-tree", "-r", "--name-only", commitSha]);
                        changedPaths = treeOutput.split("\n").filter(Boolean);
                        logger.debug({ changedPaths, count: changedPaths.length }, "Initial commit files");
                    }
                } catch (diffErr) {
                    logger.warn({ err: diffErr }, "Could not get changed paths, skipping path filter");
                }

                // Check Trigger with path filtering
                const shouldRun = runner.shouldTrigger(config, "push", {
                    ref: ref,
                    paths: changedPaths.length > 0 ? changedPaths : undefined,
                });

                if (shouldRun) {
                    logger.info({ workflow: config.name }, "Triggering workflow");

                    // Load repository secrets for injection (encrypted at rest;
                    // decrypted only at dispatch, never logged)
                    let secrets: Record<string, string> = {};
                    try {
                        const { listRepoSecrets } = await import("./workflow-secrets");
                        if (typeof listRepoSecrets === "function") {
                            const found = await listRepoSecrets(repoId);
                            for (const s of found) secrets[s.name] = s.value;
                        }
                    } catch (err) {
                        logger.debug({ err }, "No secrets loaded for workflow");
                    }

                    // Run through the persister so push-triggered runs are
                    // visible in the Actions UI and gated by the merge queue
                    const { persistAndRunWorkflow } = await import("./workflow-run-persister");
                    persistAndRunWorkflow(runner, {
                        repositoryId: repoId,
                        repositoryPath: repo.diskPath,
                        workflowPath: file,
                        workflowName: config.name || file,
                        config,
                        branch: ref.replace("refs/heads/", ""),
                        commit: commitSha,
                        triggeredBy: "push",
                        pusherId: pusherId || undefined,
                        secrets: Object.keys(secrets).length > 0 ? secrets : undefined,
                    }).catch(err => {
                        logger.error({ err, workflow: config.name }, "Workflow failed");
                    });
                } else {
                    logger.debug({ workflow: config.name }, "Skipping workflow (conditions not met)");
                }

            } catch (e) {
                logger.error({ err: e, file }, "Error processing workflow");
            }
        }

    } catch (e) {
        // likely dir doesn't exist
        // console.log("   No .github/workflows directory or error checking.");
    }
}

/**
 * Trigger CI on a merge-queue speculative branch (WS1-09).
 *
 * The speculative branch contains the combined changes of the queued PRs.
 * Workflow triggers are evaluated against the PRs' BASE branch (so branch
 * filters match), while the run is recorded against the spec branch so the
 * result is attributable to the speculative build.
 */
export async function triggerSpecWorkflow(options: {
    repositoryId: string;
    repositoryPath: string;
    specBranch: string;
    baseBranch: string;
    commitSha: string;
}): Promise<{ triggered: number }> {
    const { repositoryId, repositoryPath, specBranch, baseBranch, commitSha } = options;
    const git = getGit(repositoryPath);
    let triggered = 0;

    // List workflow files at the spec head
    let workflowFiles: string[] = [];
    try {
        const treeInfo = await git.raw(["ls-tree", "-r", "--name-only", commitSha, ".github/workflows"]);
        workflowFiles = treeInfo.split("\n").filter((f: string) => f.endsWith(".yml") || f.endsWith(".yaml"));
    } catch {
        return { triggered: 0 };
    }
    if (workflowFiles.length === 0) return { triggered: 0 };

    // Changed files vs base (for path filters)
    let changedPaths: string[] = [];
    try {
        const diffOutput = await git.raw(["diff", "--name-only", `origin/${baseBranch}`, commitSha]);
        changedPaths = diffOutput.split("\n").filter(Boolean);
    } catch {}

    for (const file of workflowFiles) {
        try {
            const content = await git.show([`${commitSha}:${file}`]);
            const tempWorkflowPath = path.join("/tmp", `workflow-${crypto.randomUUID()}.yml`);
            await fs.writeFile(tempWorkflowPath, content);
            const config = await runner.parseWorkflow(tempWorkflowPath);
            await fs.unlink(tempWorkflowPath);

            const shouldRun = runner.shouldTrigger(config, "push", {
                ref: `refs/heads/${baseBranch}`,
                paths: changedPaths.length > 0 ? changedPaths : undefined,
            });
            if (!shouldRun) continue;

            // Load secrets for injection
            let secrets: Record<string, string> = {};
            try {
                const { listRepoSecrets } = await import("./workflow-secrets");
                const found = await listRepoSecrets(repositoryId);
                for (const s of found) secrets[s.name] = s.value;
            } catch {}

            const { persistAndRunWorkflow } = await import("./workflow-run-persister");
            persistAndRunWorkflow(runner, {
                repositoryId,
                repositoryPath,
                workflowPath: file,
                workflowName: config.name || file,
                config,
                branch: specBranch,
                commit: commitSha,
                triggeredBy: "push",
                secrets: Object.keys(secrets).length > 0 ? secrets : undefined,
            }).catch((err) => logger.error({ err, file }, "Speculative workflow failed"));
            triggered++;
        } catch (e) {
            logger.error({ err: e, file }, "Error processing speculative workflow");
        }
    }

    if (triggered > 0) {
        logger.info({ specBranch, triggered }, "Speculative builds triggered");
    }
    return { triggered };
}