import { appendFileSync, readFileSync, realpathSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { matchesGlob } from "node:path";
import { fileURLToPath } from "node:url";
import { documentationInput, productInputs } from "./ci-inputs.mjs";
import { mergeDiff } from "./ci-diff.mjs";
const releaseNote = /^releases\/(beta\/)?v[^/]+\.md$/;
const validPath = (file) => typeof file === "string" && file.length > 0
&& !file.startsWith("/") && !file.split("/").includes("..") && !file.includes("\0");
export const HOSTED_SHARD_COUNTS = {
"ci:server": 8,
"ci:chat": 1,
"ci:workspaces-a": 1,
"ci:workspaces-b": 1,
"ci:serialized": 4,
"ci:e2e": 4,
"ci:runner-e2e-support": 2,
"ci:runner-package": 3,
};
const packageLanePattern = /--package-lane=\d+\/\d+/;
const labelFractionPattern = /\(\d+\/\d+\)/;
export function compactHostedEntries(entries, hostedShardCounts = HOSTED_SHARD_COUNTS) {
const segments = [];
const byKey = new Map();
for (const entry of entries) {
const isSharded = Number.isInteger(entry.shard_count) && entry.shard_count > 1;
const isPackageLane = !isSharded && typeof entry.command === "string" && packageLanePattern.test(entry.command);
if (!isSharded && !isPackageLane) {
segments.push({ kind: "single", entry });
continue;
}
const key = isSharded ? `shard:${entry.task}:${entry.group ?? ""}` : `package-lane:${entry.task}`;
let segment = byKey.get(key);
if (!segment) {
segment = { kind: isSharded ? "shard" : "package-lane", task: entry.task, entries: [] };
byKey.set(key, segment);
segments.push(segment);
}
segment.entries.push(entry);
}
const compact = [];
for (const segment of segments) {
if (segment.kind === "single") {
compact.push(segment.entry);
continue;
}
const awsCount = segment.entries.length;
const configured = hostedShardCounts[segment.task];
const target = Number.isInteger(configured) && configured >= 1 ? configured : Math.floor(awsCount / 2);
const hostedCount = Math.min(awsCount, Math.max(1, target));
const template = segment.entries[0];
for (let index = 0; index < hostedCount; index += 1) {
const entry = { ...template };
if (segment.kind === "shard") {
entry.shard_index = index;
entry.shard_count = hostedCount;
if (entry.shard_label) entry.shard_label = `${index + 1}/${hostedCount}`;
if (entry.group_label) entry.group_label = entry.group_label.replace(labelFractionPattern, `(${index + 1}/${hostedCount})`);
} else {
entry.command = entry.command.replace(packageLanePattern, `--package-lane=${index + 1}/${hostedCount}`);
if (entry.lane_label) entry.lane_label = entry.lane_label.replace(labelFractionPattern, `(${index + 1}/${hostedCount})`);
}
compact.push(entry);
}
}
return compact;
}
function validateGlobs(globs) {
if (!Array.isArray(globs) || globs.some((glob) => !validPath(glob) || /[!{}[\]?$\\]/.test(glob))) {
throw new Error("Unsupported task input pattern");
}
}
export function comparisonPaths(comparison) {
if (!Array.isArray(comparison?.files) || comparison.files.length === 0 || comparison.files.length >= 300) {
throw new Error("Missing, empty, or possibly truncated comparison");
}
return comparison.files.flatMap((file) => {
if (!validPath(file.filename) || (file.status === "renamed" && !validPath(file.previous_filename))
|| (file.previous_filename !== undefined && !validPath(file.previous_filename))) {
throw new Error("Malformed changed file");
}
return file.previous_filename ? [file.previous_filename, file.filename] : [file.filename];
});
}
export function planTasks({ config, lanes, paths, mode = "enabled", forceReason = null }) {
if (!["enabled", "shadow", "full"].includes(mode)) throw new Error("Invalid CI mode");
validateGlobs(config.globalDependencies);
const tasks = config.tasks;
const inputs = new Map();
function taskInputs(name, parents = []) {
if (inputs.has(name)) return inputs.get(name);
if (parents.includes(name)) throw new Error("Cyclic task graph");
const task = tasks[`//#${name}`];
if (!task) throw new Error(`Missing task: ${name}`);
validateGlobs(task.inputs);
const all = [...task.inputs];
for (const dependency of task.dependsOn ?? []) {
if (!dependency.startsWith("//#")) throw new Error("Unsupported task dependency");
all.push(...taskInputs(dependency.slice(3), [...parents, name]));
}
inputs.set(name, [...new Set(all)]);
return inputs.get(name);
}
for (const entries of Object.values(lanes)) {
if (!Array.isArray(entries) || !entries.length) throw new Error("Empty CI lane");
for (const entry of entries) taskInputs(entry.task);
}
let forceScope = forceReason ? "all" : null;
const setForce = (reason, scope = "all") => {
if (!forceReason) {
forceReason = reason;
forceScope = scope;
} else if (scope === "all") {
forceScope = "all";
}
};
const changed = [...new Set(paths)];
if (!changed.length || changed.some((file) => !validPath(file))) setForce("Missing or invalid diff", "all");
const matches = (file, globs) => globs.some((glob) => matchesGlob(file, glob));
const sourceChanges = productInputs(changed);
const globalChanges = sourceChanges.filter((file) => matches(file, config.globalDependencies));
if (globalChanges.length) setForce(`Global CI input changed: ${globalChanges[0]}`, "global");
const unknown = sourceChanges.filter((file) => !releaseNote.test(file)
&& !matches(file, config.globalDependencies) && ![...inputs.values()].some((globs) => matches(file, globs)));
if (unknown.length) setForce(`Unclassified path: ${unknown[0]}`, "all");
if (mode === "full") setForce("Full CI requested", "all");
const taskForceOnGlobal = new Map();
for (const entries of Object.values(lanes)) {
for (const entry of entries) {
if (entry.forceOnGlobalInputs === false) taskForceOnGlobal.set(entry.task, false);
}
}
const reasons = Object.fromEntries([...inputs].map(([task, globs]) => {
const direct = sourceChanges.filter((file) => matches(file, globs));
const forced = forceScope === "all" || (forceScope === "global" && taskForceOnGlobal.get(task) !== false);
return [task, forced ? [forceReason] : direct];
}));
// This uncached lane owns the repository-wide CLI guidance check.
if (reasons["ci:typecheck"]) reasons["ci:typecheck"].push(...changed.filter((file) => documentationInput(file) === "guidance"));
const jobs = Object.fromEntries(Object.entries(lanes).map(([job, entries]) => {
const affected = entries.filter((entry) => reasons[entry.task].length > 0);
const selected = mode === "shadow" ? entries : affected;
const hostedAll = compactHostedEntries(entries);
const hostedSelected = compactHostedEntries(selected);
const hosted = hostedAll.length < entries.length
? {
hosted_matrix: { include: selected.length ? hostedSelected : hostedAll },
hosted_selected: hostedSelected.length,
hosted_total: hostedAll.length,
}
: {};
return [job, { run: selected.length > 0, matrix: { include: selected.length ? selected : entries },
selected: selected.length, proposed: affected.length, total: entries.length, ...hosted }];
}));
return { version: 1, mode, forceReason, changed, documentation: changed.filter(documentationInput), reasons, jobs };
}
export function planSummary(plan) {
const rows = Object.entries(plan.jobs).map(([job, lane]) => {
const scheduled = lane.hosted_total !== undefined
? `${lane.selected}/${lane.total} (hosted: ${lane.hosted_selected}/${lane.hosted_total})`
: `${lane.selected}/${lane.total}`;
return `| ${job} | ${lane.proposed}/${lane.total} | ${scheduled} |`;
});
return ["### Incremental CI", "", `Mode: **${plan.mode}**${plan.forceReason ? ` — ${plan.forceReason}` : ""}`,
...(plan.diff ? [`Diff: \`${plan.diff.base}\` → \`${plan.diff.head}\` (complete Git tree comparison)`, ""] : []),
`Documentation inputs: ${(plan.documentation ?? []).join(", ") || "none"}`,
"", "| Suite | Affected jobs | Scheduled jobs |", "| --- | ---: | ---: |", ...rows,
"", "Selection reasons
", "", "```json", JSON.stringify(plan.reasons, null, 2),
"```", " ", ""].join("\n");
}
if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
try {
const config = JSON.parse(readFileSync(process.env.CI_TASK_CONFIG ?? "turbo.json", "utf8"));
const lanes = JSON.parse(readFileSync(process.env.CI_TASK_MATRIX ?? ".github/ci-task-matrix.json", "utf8"));
let paths = [], diff, forceReason = process.env.CI_FORCE_REASON || null;
try {
if (process.env.CI_DIFF_REPOSITORY) {
const result = mergeDiff(process.env.EVENT_MERGE_SHA, process.env.EVENT_HEAD_SHA, process.env.CI_DIFF_REPOSITORY);
paths = result.changed;
diff = result.diff;
} else if (process.env.CI_COMPARISON) {
paths = comparisonPaths(JSON.parse(readFileSync(process.env.CI_COMPARISON, "utf8")));
} else {
const [base, head = "HEAD"] = process.argv.slice(2);
if (!base) throw new Error("Usage: ci-plan.mjs [head]");
paths = execFileSync("git", ["diff", "--no-renames", "--name-only", "-z", `${base}...${head}`, "--"],
{ encoding: "utf8" }).split("\0").filter(Boolean);
}
} catch (error) { forceReason ??= `Diff unavailable: ${error.message}`; }
const plan = planTasks({ config, lanes, paths, mode: process.env.CI_INCREMENTAL_MODE || "enabled", forceReason });
if (diff) plan.diff = diff;
if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `plan=${JSON.stringify(plan)}\n`);
else console.log(JSON.stringify(plan, null, 2));
if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, planSummary(plan));
} catch (error) {
console.error(`Incremental CI unavailable; selecting full CI: ${error.message}`);
if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, "plan=\n");
else process.exitCode = 1;
}
}