docs: add code queue PR preflight template
This commit is contained in:
@@ -0,0 +1,229 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
type JsonRecord = Record<string, unknown>;
|
||||
|
||||
interface CliResult {
|
||||
status: number | null;
|
||||
ok: boolean;
|
||||
json: JsonRecord | null;
|
||||
stdoutBytes: number;
|
||||
stderrBytes: number;
|
||||
stdoutPreview?: string;
|
||||
stderrPreview?: string;
|
||||
}
|
||||
|
||||
const DEFAULT_REPO = "pikasTech/unidesk";
|
||||
const DEFAULT_BASE = "master";
|
||||
const DEFAULT_HEAD = "code-queue/pr-preflight-example";
|
||||
const DEFAULT_COMMENT_PR = "1";
|
||||
const PREVIEW_CHARS = 400;
|
||||
|
||||
function optionValue(args: string[], name: string, defaultValue: string): string {
|
||||
const index = args.indexOf(name);
|
||||
if (index === -1) return defaultValue;
|
||||
const value = args[index + 1];
|
||||
if (value === undefined || value.length === 0 || value.startsWith("--")) throw new Error(`${name} requires a value`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function secrets(): string[] {
|
||||
return [process.env.GH_TOKEN, process.env.GITHUB_TOKEN].filter((value): value is string => value !== undefined && value.length > 0);
|
||||
}
|
||||
|
||||
function redactText(text: string): string {
|
||||
let redacted = text;
|
||||
for (const secret of secrets()) {
|
||||
redacted = redacted.split(secret).join("<redacted>");
|
||||
}
|
||||
return redacted;
|
||||
}
|
||||
|
||||
function redactUnknown(value: unknown): unknown {
|
||||
if (typeof value === "string") return redactText(value);
|
||||
if (Array.isArray(value)) return value.map(redactUnknown);
|
||||
if (typeof value === "object" && value !== null) {
|
||||
const entries = Object.entries(value).map(([key, entry]) => [key, redactUnknown(entry)]);
|
||||
return Object.fromEntries(entries);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function preview(text: string): string {
|
||||
return redactText(text.length > PREVIEW_CHARS ? `${text.slice(0, PREVIEW_CHARS)}...` : text);
|
||||
}
|
||||
|
||||
function runCli(args: string[]): CliResult {
|
||||
const result = spawnSync("bun", ["scripts/cli.ts", ...args], {
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
encoding: "utf8",
|
||||
timeout: 30_000,
|
||||
});
|
||||
const stdout = result.stdout ?? "";
|
||||
const stderr = result.stderr ?? "";
|
||||
let json: JsonRecord | null = null;
|
||||
try {
|
||||
json = redactUnknown(JSON.parse(stdout) as unknown) as JsonRecord;
|
||||
} catch {
|
||||
json = null;
|
||||
}
|
||||
return {
|
||||
status: result.status,
|
||||
ok: result.status === 0 && json?.ok === true,
|
||||
json,
|
||||
stdoutBytes: Buffer.byteLength(stdout),
|
||||
stderrBytes: Buffer.byteLength(stderr),
|
||||
...(json === null && stdout.length > 0 ? { stdoutPreview: preview(stdout) } : {}),
|
||||
...(stderr.length > 0 ? { stderrPreview: preview(stderr) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function dataOf(result: CliResult): JsonRecord | null {
|
||||
const data = result.json?.data;
|
||||
return typeof data === "object" && data !== null && !Array.isArray(data) ? data as JsonRecord : null;
|
||||
}
|
||||
|
||||
function envTokenProbe(): JsonRecord {
|
||||
if (process.env.GH_TOKEN && process.env.GH_TOKEN.length > 0) return { ok: true, present: true, source: "GH_TOKEN" };
|
||||
if (process.env.GITHUB_TOKEN && process.env.GITHUB_TOKEN.length > 0) return { ok: true, present: true, source: "GITHUB_TOKEN" };
|
||||
return {
|
||||
ok: false,
|
||||
present: false,
|
||||
source: null,
|
||||
message: "Runner PR workflow requires GH_TOKEN or GITHUB_TOKEN in the environment; token values must never be printed.",
|
||||
};
|
||||
}
|
||||
|
||||
function dryRunSummary(result: CliResult): JsonRecord {
|
||||
const data = dataOf(result);
|
||||
return {
|
||||
ok: result.ok,
|
||||
status: result.status,
|
||||
stdoutBytes: result.stdoutBytes,
|
||||
stderrBytes: result.stderrBytes,
|
||||
...(data === null ? {} : {
|
||||
command: data.command,
|
||||
dryRun: data.dryRun,
|
||||
planned: data.planned,
|
||||
repo: data.repo,
|
||||
base: data.base,
|
||||
head: data.head,
|
||||
issueNumber: data.issueNumber,
|
||||
bodyChars: data.bodyChars,
|
||||
request: data.request,
|
||||
}),
|
||||
...(result.stdoutPreview === undefined ? {} : { stdoutPreview: result.stdoutPreview }),
|
||||
...(result.stderrPreview === undefined ? {} : { stderrPreview: result.stderrPreview }),
|
||||
};
|
||||
}
|
||||
|
||||
function main(): void {
|
||||
const args = process.argv.slice(2);
|
||||
if (args.includes("--help") || args.includes("-h")) {
|
||||
process.stdout.write(`${JSON.stringify({
|
||||
ok: true,
|
||||
command: "code-queue-pr-preflight-example",
|
||||
usage: "bun scripts/code-queue-pr-preflight-example.ts [--repo owner/name] [--base branch] [--head branch] [--comment-pr number]",
|
||||
note: "Read-only/dry-run runner preflight. It checks GH_TOKEN/GITHUB_TOKEN presence, GitHub REST egress and repo visibility through gh auth status, then exercises PR create/comment dry-run paths without creating or merging a PR.",
|
||||
}, null, 2)}\n`);
|
||||
return;
|
||||
}
|
||||
|
||||
const repo = optionValue(args, "--repo", DEFAULT_REPO);
|
||||
const base = optionValue(args, "--base", DEFAULT_BASE);
|
||||
const head = optionValue(args, "--head", process.env.CODE_QUEUE_HEAD_BRANCH ?? DEFAULT_HEAD);
|
||||
const commentPr = optionValue(args, "--comment-pr", DEFAULT_COMMENT_PR);
|
||||
const tmp = mkdtempSync(join(tmpdir(), "unidesk-pr-preflight-"));
|
||||
const bodyFile = join(tmp, "body.md");
|
||||
writeFileSync(bodyFile, [
|
||||
"# Code Queue PR preflight",
|
||||
"",
|
||||
"This file is used only for local dry-run planning.",
|
||||
"",
|
||||
].join("\n"), "utf8");
|
||||
|
||||
try {
|
||||
const token = envTokenProbe();
|
||||
const auth = runCli(["gh", "auth", "status", "--repo", repo]);
|
||||
const createDryRun = runCli([
|
||||
"gh",
|
||||
"pr",
|
||||
"create",
|
||||
"--repo",
|
||||
repo,
|
||||
"--title",
|
||||
"Code Queue PR preflight dry run",
|
||||
"--body-file",
|
||||
bodyFile,
|
||||
"--base",
|
||||
base,
|
||||
"--head",
|
||||
head,
|
||||
"--dry-run",
|
||||
]);
|
||||
const commentDryRun = runCli([
|
||||
"gh",
|
||||
"pr",
|
||||
"comment",
|
||||
commentPr,
|
||||
"--repo",
|
||||
repo,
|
||||
"--body-file",
|
||||
bodyFile,
|
||||
"--dry-run",
|
||||
]);
|
||||
const authData = dataOf(auth);
|
||||
const ok = token.ok === true && auth.ok && createDryRun.ok && commentDryRun.ok;
|
||||
process.stdout.write(`${JSON.stringify({
|
||||
ok,
|
||||
command: "code-queue-pr-preflight-example",
|
||||
repo,
|
||||
base,
|
||||
head,
|
||||
commentPr,
|
||||
checks: {
|
||||
envToken: token,
|
||||
githubAuthStatus: {
|
||||
ok: auth.ok,
|
||||
status: auth.status,
|
||||
stdoutBytes: auth.stdoutBytes,
|
||||
stderrBytes: auth.stderrBytes,
|
||||
...(authData === null ? {} : {
|
||||
degraded: authData.degraded,
|
||||
token: authData.token,
|
||||
probes: authData.probes,
|
||||
restFallback: authData.restFallback,
|
||||
}),
|
||||
...(auth.stdoutPreview === undefined ? {} : { stdoutPreview: auth.stdoutPreview }),
|
||||
...(auth.stderrPreview === undefined ? {} : { stderrPreview: auth.stderrPreview }),
|
||||
},
|
||||
prCreateDryRun: dryRunSummary(createDryRun),
|
||||
prCommentDryRun: dryRunSummary(commentDryRun),
|
||||
},
|
||||
safety: {
|
||||
writesRemote: false,
|
||||
createsPullRequest: false,
|
||||
commentsPullRequest: false,
|
||||
mergesPullRequest: false,
|
||||
tokenValuesPrinted: false,
|
||||
},
|
||||
}, null, 2)}\n`);
|
||||
if (!ok) process.exitCode = 1;
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
main();
|
||||
} catch (error) {
|
||||
process.stdout.write(`${JSON.stringify({
|
||||
ok: false,
|
||||
command: "code-queue-pr-preflight-example",
|
||||
error: redactText(error instanceof Error ? error.message : String(error)),
|
||||
}, null, 2)}\n`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
@@ -7,16 +7,16 @@ import { tmpdir } from "node:os";
|
||||
|
||||
type JsonRecord = Record<string, unknown>;
|
||||
|
||||
function assertCondition(condition: unknown, message: string, detail: JsonRecord = {}): void {
|
||||
function assertCondition(condition: unknown, message: string, detail: unknown = {}): void {
|
||||
if (!condition) throw new Error(`${message}: ${JSON.stringify(detail)}`);
|
||||
}
|
||||
|
||||
function runCli(args: string[], env: Record<string, string> = {}): Promise<{ status: number | null; stdout: string; stderr: string; json: JsonRecord | null }> {
|
||||
function runBun(args: string[], env: Record<string, string> = {}): Promise<{ status: number | null; stdout: string; stderr: string; json: JsonRecord | null }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn("bun", ["scripts/cli.ts", ...args], {
|
||||
cwd: process.cwd(),
|
||||
env: { ...process.env, ...env },
|
||||
});
|
||||
const child = spawn("bun", args, {
|
||||
cwd: process.cwd(),
|
||||
env: { ...process.env, ...env },
|
||||
});
|
||||
const stdoutChunks: Buffer[] = [];
|
||||
const stderrChunks: Buffer[] = [];
|
||||
child.stdout.on("data", (chunk) => stdoutChunks.push(Buffer.from(chunk)));
|
||||
@@ -40,6 +40,10 @@ function runCli(args: string[], env: Record<string, string> = {}): Promise<{ sta
|
||||
});
|
||||
}
|
||||
|
||||
function runCli(args: string[], env: Record<string, string> = {}): Promise<{ status: number | null; stdout: string; stderr: string; json: JsonRecord | null }> {
|
||||
return runBun(["scripts/cli.ts", ...args], env);
|
||||
}
|
||||
|
||||
interface MockRequest {
|
||||
method: string;
|
||||
url: string;
|
||||
@@ -79,10 +83,18 @@ async function startMockGitHub(): Promise<{ baseUrl: string; requests: MockReque
|
||||
const server = createServer(async (req, res) => {
|
||||
const body = await collectBody(req);
|
||||
requests.push({ method: req.method ?? "", url: req.url ?? "", body });
|
||||
if (req.method === "GET" && req.url === "/rate_limit") {
|
||||
sendJson(res, 200, { resources: { core: { limit: 5000, remaining: 4999 } } });
|
||||
return;
|
||||
}
|
||||
if (req.method === "GET" && req.url === "/repos/pikasTech/unidesk") {
|
||||
sendJson(res, 200, { id: 1, full_name: "pikasTech/unidesk", private: true, default_branch: "master", permissions: { pull: true, push: true } });
|
||||
return;
|
||||
}
|
||||
if (req.method === "GET" && req.url === "/repos/pikasTech/unidesk/issues?per_page=1&state=all") {
|
||||
sendJson(res, 200, []);
|
||||
return;
|
||||
}
|
||||
if (req.method === "GET" && req.url === "/repos/pikasTech/unidesk/pulls?state=all&per_page=4") {
|
||||
sendJson(res, 200, [pullRequest]);
|
||||
return;
|
||||
@@ -154,6 +166,34 @@ export async function runGhCliPrContract(): Promise<JsonRecord> {
|
||||
assertCondition(pullRequest.number === 42 && pullRequest.url === "https://github.com/pikasTech/unidesk/pull/42", "pr view should expose PR details", viewData);
|
||||
const selected = viewData.json as JsonRecord;
|
||||
assertCondition(selected.body === "PR body" && selected.title === "contract PR", "pr view --json should select fields", viewData);
|
||||
|
||||
const preflight = await runBun([
|
||||
"scripts/code-queue-pr-preflight-example.ts",
|
||||
"--repo",
|
||||
"pikasTech/unidesk",
|
||||
"--base",
|
||||
"master",
|
||||
"--head",
|
||||
"feature/pr-contract",
|
||||
"--comment-pr",
|
||||
"42",
|
||||
], env);
|
||||
assertCondition(preflight.status === 0, "PR preflight example should succeed against mock GitHub", preflight.json ?? { stdout: preflight.stdout });
|
||||
assertCondition(preflight.json?.ok === true, "PR preflight example should report ok=true", preflight.json ?? {});
|
||||
assertCondition(!preflight.stdout.includes("contract-token"), "PR preflight example must not print token values", { stdout: preflight.stdout });
|
||||
assertCondition(typeof preflight.json?.checks === "object" && preflight.json.checks !== null && !Array.isArray(preflight.json.checks), "PR preflight should expose checks", preflight.json ?? {});
|
||||
const preflightChecks = preflight.json?.checks as JsonRecord;
|
||||
const envToken = preflightChecks.envToken as JsonRecord;
|
||||
assertCondition(envToken.present === true && envToken.source === "GH_TOKEN", "PR preflight should require env token source", envToken);
|
||||
const authStatus = preflightChecks.githubAuthStatus as JsonRecord;
|
||||
assertCondition(authStatus.ok === true, "PR preflight should prove GitHub REST egress and repo visibility", authStatus);
|
||||
const preflightCreate = preflightChecks.prCreateDryRun as JsonRecord;
|
||||
const preflightComment = preflightChecks.prCommentDryRun as JsonRecord;
|
||||
assertCondition(preflightCreate.ok === true && preflightCreate.dryRun === true && preflightCreate.planned === true, "PR preflight create must stay dry-run", preflightCreate);
|
||||
assertCondition(preflightComment.ok === true && preflightComment.dryRun === true && preflightComment.planned === true, "PR preflight comment must stay dry-run", preflightComment);
|
||||
assertCondition(mock.requests.some((request) => request.method === "GET" && request.url === "/rate_limit"), "PR preflight should probe REST egress", mock.requests);
|
||||
assertCondition(mock.requests.some((request) => request.method === "GET" && request.url === "/repos/pikasTech/unidesk"), "PR preflight should probe repo visibility", mock.requests);
|
||||
assertCondition(mock.requests.every((request) => request.method === "GET"), "initial mock phase should remain read-only", mock.requests);
|
||||
} finally {
|
||||
await mock.close();
|
||||
}
|
||||
|
||||
@@ -284,6 +284,8 @@ export function runChecks(config: UniDeskConfig, options: CheckOptions = default
|
||||
fileItem("scripts/src/ci.ts"),
|
||||
fileItem("scripts/src/e2e.ts"),
|
||||
fileItem("scripts/code-queue-prompt-observation-test.ts"),
|
||||
fileItem("scripts/gh-cli-pr-contract-test.ts"),
|
||||
fileItem("scripts/code-queue-pr-preflight-example.ts"),
|
||||
fileItem("scripts/schedule-cli-contract-test.ts"),
|
||||
fileItem("scripts/src/artifact-registry.ts"),
|
||||
fileItem("src/components/microservices/k3sctl-adapter/k3s/ci/unidesk-ci.pipeline.yaml"),
|
||||
@@ -303,6 +305,7 @@ export function runChecks(config: UniDeskConfig, options: CheckOptions = default
|
||||
items.push(commandItem("code-queue:oa-publisher-degraded-visible", ["bun", "scripts/code-queue-liveness-diagnostics-test.ts", "--only", "code-queue:oa-publisher-degraded-visible"], 30_000));
|
||||
items.push(commandItem("baidu-netdisk:artifact-guard-contract", ["bun", "scripts/baidu-netdisk-artifact-guard-contract-test.ts"], 30_000));
|
||||
items.push(commandItem("schedule:cli-contract", ["bun", "scripts/schedule-cli-contract-test.ts"], 30_000));
|
||||
items.push(commandItem("gh:pr-contract", ["bun", "scripts/gh-cli-pr-contract-test.ts"], 30_000));
|
||||
} else {
|
||||
items.push(skippedItem("typescript:scripts", "scripts TypeScript typecheck is opt-in", "--scripts-typecheck or --full"));
|
||||
items.push(skippedItem("code-queue:prompt-observation-contract", "prompt observation contract is opt-in with script checks", "--scripts-typecheck or --full"));
|
||||
@@ -311,6 +314,7 @@ export function runChecks(config: UniDeskConfig, options: CheckOptions = default
|
||||
items.push(skippedItem("code-queue:liveness-diagnostics-fixtures", "Code Queue liveness diagnostics fixtures are opt-in with script checks", "--scripts-typecheck or --full"));
|
||||
items.push(skippedItem("baidu-netdisk:artifact-guard-contract", "Baidu Netdisk artifact guard contract is opt-in with script checks", "--scripts-typecheck or --full"));
|
||||
items.push(skippedItem("schedule:cli-contract", "Schedule CLI contract is opt-in with script checks", "--scripts-typecheck or --full"));
|
||||
items.push(skippedItem("gh:pr-contract", "GitHub PR CLI contract is opt-in with script checks", "--scripts-typecheck or --full"));
|
||||
}
|
||||
if (options.logs) {
|
||||
items.push(unifiedLogRotationItem());
|
||||
|
||||
Reference in New Issue
Block a user