fix: add code queue pr preflight

This commit is contained in:
Codex
2026-05-20 20:48:10 +00:00
parent e8b3c3ef32
commit 6c51512d64
10 changed files with 344 additions and 9 deletions
@@ -0,0 +1,130 @@
import { codexPrPreflightQueryForTest } from "./src/code-queue";
type JsonRecord = Record<string, unknown>;
function assertCondition(condition: unknown, message: string, detail: unknown = {}): void {
if (!condition) throw new Error(`${message}: ${JSON.stringify(detail)}`);
}
function asRecord(value: unknown): JsonRecord {
assertCondition(typeof value === "object" && value !== null && !Array.isArray(value), "expected JSON object", { value });
return value as JsonRecord;
}
function fixtureRuntimePreflight(tokenPresent: boolean): JsonRecord {
return {
ok: tokenPresent,
checkedAt: "2026-05-20T00:00:00.000Z",
cwd: "/workspace/unidesk",
pid: 123,
ports: {
codex: { ok: true, commandPath: "/usr/local/bin/codex", version: "codex 0.128.0", errors: [] },
opencode: { ok: true, commandPath: "/usr/local/bin/opencode", version: "opencode 1.14.48", errors: [] },
},
pullRequestDelivery: {
ok: tokenPresent,
checkedAt: "2026-05-20T00:00:00.000Z",
tools: {
git: { ok: true, path: "/usr/bin/git", version: "git version 2.43.0" },
gh: { ok: true, path: "/usr/bin/gh", version: "gh version 2.45.0" },
hub: { ok: false, path: null, version: null },
jq: { ok: true, path: "/usr/bin/jq", version: "jq-1.7" },
ssh: { ok: true, path: "/usr/bin/ssh", version: "OpenSSH_9.6" },
curl: { ok: true, path: "/usr/bin/curl", version: "curl 8.5.0" },
},
credentials: {
ghTokenPresent: tokenPresent,
githubTokenPresent: false,
ghHostPresent: false,
githubApiUrlPresent: false,
ghRepoPresent: false,
sshAuthSockPresent: false,
gitAskpassPresent: false,
ghHostsConfigPresent: false,
gitCredentialsPresent: false,
},
githubContext: {
host: "github.com",
apiBaseUrl: "https://api.github.com",
repo: "pikasTech/unidesk",
issueProbeNumber: 20,
},
egress: {
proxy: { selectedProxyHost: "d601-provider-egress-proxy.unidesk.svc.cluster.local", selectedProxyPort: "18789", selectedProxyHostResolvable: true },
githubDefault: { command: "preflight", args: ["github-default-network"], ok: true, exitCode: 0, signal: null, error: null, stdout: "skipped", stderr: "" },
apiDefault: { command: "preflight", args: ["github-api-default-network"], ok: true, exitCode: 0, signal: null, error: null, stdout: "skipped", stderr: "" },
issueApi: null,
},
git: {
insideWorktree: true,
branch: "master",
head: "abc1234",
originMaster: "abc1234",
remoteOrigin: "git@github.com:pikasTech/unidesk.git",
home: "/root",
homeWritable: true,
knownHostsPresent: true,
privateKeyPresent: true,
},
limitations: tokenPresent ? [] : ["GH_TOKEN/GITHUB_TOKEN is not present; gh cannot create PRs unless another gh credential store is mounted"],
risks: [],
},
};
}
function fixtureResponse(tokenPresent: boolean): JsonRecord {
return {
ok: true,
status: 200,
body: {
ok: true,
runtimePreflight: fixtureRuntimePreflight(tokenPresent),
},
};
}
export function runCodeQueuePrPreflightContract(): JsonRecord {
let observedPath = "";
const missing = codexPrPreflightQueryForTest(["--remote", "--issue", "35"], (path) => {
observedPath = path;
return fixtureResponse(false);
});
assertCondition(
observedPath === "/api/microservices/code-queue/proxy/api/runtime-preflight?remote=1&issue=35",
"PR preflight should route to the stable code-queue runtime preflight path",
{ observedPath },
);
assertCondition(asRecord(missing).ok === false, "missing token preflight should set top-level ok=false", missing);
const missingPreflight = asRecord(asRecord(missing).preflight);
assertCondition(missingPreflight.ok === false, "missing token preflight should fail", missingPreflight);
assertCondition(missingPreflight.runnerDisposition === "infra-blocked", "missing token must be infra-blocked", missingPreflight);
const missingTokenCoverage = asRecord(missingPreflight.tokenCoverage);
assertCondition(missingTokenCoverage.ok === false, "tokenCoverage should fail when no env token is present", missingTokenCoverage);
assertCondition(Array.isArray(missingTokenCoverage.missing) && missingTokenCoverage.missing.includes("GH_TOKEN") && missingTokenCoverage.missing.includes("GITHUB_TOKEN"), "tokenCoverage should name both accepted env keys", missingTokenCoverage);
assertCondition(!JSON.stringify(missing).includes("contract-token"), "preflight output must not leak token values", missing);
const ready = codexPrPreflightQueryForTest(["--remote", "--push-dry-run", "--push-dry-run-ref", "refs/heads/probe/test"], (path) => {
assertCondition(path === "/api/microservices/code-queue/proxy/api/runtime-preflight?remote=1&pushDryRun=1&pushDryRunRef=refs%2Fheads%2Fprobe%2Ftest", "push dry-run options should map to query string", { path });
return fixtureResponse(true);
});
const readyPreflight = asRecord(asRecord(ready).preflight);
assertCondition(asRecord(ready).ok === true, "token-ready preflight should set top-level ok=true", ready);
assertCondition(readyPreflight.ok === true, "token-ready preflight should pass fixture", readyPreflight);
assertCondition(readyPreflight.runnerDisposition === "ready", "ready preflight should report ready disposition", readyPreflight);
const readyTokenCoverage = asRecord(readyPreflight.tokenCoverage);
assertCondition(readyTokenCoverage.source === "GH_TOKEN", "ready token source should be redacted to key name only", readyTokenCoverage);
return {
ok: true,
checks: [
"stable runtime-preflight proxy path",
"missing GitHub token is infra-blocked",
"token key names are reported without values",
"push dry-run options are forwarded",
],
};
}
if (import.meta.main) {
process.stdout.write(`${JSON.stringify(runCodeQueuePrPreflightContract(), null, 2)}\n`);
}
+3
View File
@@ -281,6 +281,7 @@ export function runChecks(config: UniDeskConfig, options: CheckOptions = default
fileItem("scripts/code-queue-liveness-diagnostics-test.ts"),
fileItem("scripts/src/code-queue-liveness-fixtures.ts"),
fileItem("scripts/code-queue-trace-summary-contract-test.ts"),
fileItem("scripts/code-queue-pr-preflight-contract-test.ts"),
fileItem("scripts/src/ci.ts"),
fileItem("scripts/src/e2e.ts"),
fileItem("scripts/code-queue-prompt-observation-test.ts"),
@@ -299,6 +300,7 @@ export function runChecks(config: UniDeskConfig, options: CheckOptions = default
items.push(commandItem("code-queue:prompt-observation-contract", ["bun", "scripts/code-queue-prompt-observation-test.ts"], 30_000));
items.push(commandItem("code-queue:issue3-diagnostics-and-image-preflight", ["bun", "scripts/code-queue-issue3-regression-test.ts"], 30_000));
items.push(commandItem("code-queue:trace-summary-contract", ["bun", "scripts/code-queue-trace-summary-contract-test.ts"], 30_000));
items.push(commandItem("code-queue:pr-preflight-contract", ["bun", "scripts/code-queue-pr-preflight-contract-test.ts"], 30_000));
items.push(commandItem("code-queue:active-run-heartbeat-visible", ["bun", "scripts/code-queue-liveness-diagnostics-test.ts", "--only", "code-queue:active-run-heartbeat-visible"], 30_000));
items.push(commandItem("code-queue:trace-gap-not-stale", ["bun", "scripts/code-queue-liveness-diagnostics-test.ts", "--only", "code-queue:trace-gap-not-stale"], 30_000));
items.push(commandItem("code-queue:stale-active-owner-expired", ["bun", "scripts/code-queue-liveness-diagnostics-test.ts", "--only", "code-queue:stale-active-owner-expired"], 30_000));
@@ -313,6 +315,7 @@ export function runChecks(config: UniDeskConfig, options: CheckOptions = default
items.push(skippedItem("code-queue:prompt-observation-contract", "prompt observation contract is opt-in with script checks", "--scripts-typecheck or --full"));
items.push(skippedItem("code-queue:issue3-diagnostics-and-image-preflight", "Code Queue issue #3 regression fixtures are opt-in with script checks", "--scripts-typecheck or --full"));
items.push(skippedItem("code-queue:trace-summary-contract", "Code Queue trace summary contract is opt-in with script checks", "--scripts-typecheck or --full"));
items.push(skippedItem("code-queue:pr-preflight-contract", "Code Queue PR preflight contract is opt-in with script checks", "--scripts-typecheck or --full"));
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"));
+192 -1
View File
@@ -147,6 +147,14 @@ interface CodexQueuesOptions {
limitExplicit: boolean;
}
interface CodexPrPreflightOptions {
remote: boolean;
pushDryRun: boolean;
pushDryRunRef: string | undefined;
issueNumber: number | null;
full: boolean;
}
type CodexRequestInit = { method?: string; body?: unknown };
type CodexResponseFetcher = (path: string, init?: CodexRequestInit) => unknown;
type AsyncCodexResponseFetcher = (path: string, init?: CodexRequestInit) => Promise<unknown>;
@@ -994,6 +1002,20 @@ function parseQueuesOptions(args: string[]): CodexQueuesOptions {
};
}
function parsePrPreflightOptions(args: string[]): CodexPrPreflightOptions {
assertKnownOptions(args, {
flags: ["--remote", "--push-dry-run", "--pushDryRun", "--full", "--raw"],
valueOptions: ["--push-dry-run-ref", "--pushDryRunRef", "--issue", "--issue-number", "--issueNumber"],
}, "codex pr-preflight");
return {
remote: hasFlag(args, "--remote"),
pushDryRun: hasFlag(args, "--push-dry-run") || hasFlag(args, "--pushDryRun"),
pushDryRunRef: optionValue(args, ["--push-dry-run-ref", "--pushDryRunRef"]),
issueNumber: nullablePositiveNumberOption(args, ["--issue", "--issue-number", "--issueNumber"]),
full: hasFlag(args, "--full") || hasFlag(args, "--raw"),
};
}
function parseJudgeOptions(args: string[]): CodexJudgeOptions {
assertKnownOptions(args, {
flags: ["--dry-run", "--no-call", "--include-prompt"],
@@ -1959,6 +1981,174 @@ function codeQueueDevReady(): unknown {
};
}
function compactCommandProbe(value: unknown): Record<string, unknown> | null {
const probe = asRecord(value);
if (probe === null) return null;
return {
command: probe.command ?? null,
args: Array.isArray(probe.args) ? probe.args : [],
ok: probe.ok ?? false,
exitCode: probe.exitCode ?? null,
signal: probe.signal ?? null,
error: probe.error ?? null,
stdout: typeof probe.stdout === "string" ? textView(probe.stdout, false, 1200) : null,
stderr: typeof probe.stderr === "string" ? textView(probe.stderr, false, 1200) : null,
};
}
function compactToolStatus(value: unknown): Record<string, unknown> {
const tool = asRecord(value) ?? {};
return {
ok: tool.ok ?? false,
path: tool.path ?? null,
version: tool.version ?? null,
};
}
function compactAgentPortStatus(value: unknown): Record<string, unknown> {
const port = asRecord(value) ?? {};
return {
ok: port.ok ?? false,
commandPath: port.commandPath ?? null,
version: port.version ?? null,
errors: Array.isArray(port.errors) ? port.errors : [],
};
}
function tokenCoverageStatus(credentials: Record<string, unknown>): Record<string, unknown> {
const ghTokenPresent = credentials.ghTokenPresent === true;
const githubTokenPresent = credentials.githubTokenPresent === true;
const anyEnvToken = ghTokenPresent || githubTokenPresent;
const anyGhCredentialStore = credentials.ghHostsConfigPresent === true || credentials.gitCredentialsPresent === true;
return {
ok: anyEnvToken,
source: ghTokenPresent ? "GH_TOKEN" : githubTokenPresent ? "GITHUB_TOKEN" : null,
ghTokenPresent,
githubTokenPresent,
ghCredentialStorePresent: anyGhCredentialStore,
runnerDisposition: anyEnvToken ? "ready" : "infra-blocked",
missing: anyEnvToken ? [] : ["GH_TOKEN", "GITHUB_TOKEN"],
scope: "scheduler-runner-env",
note: anyEnvToken
? "scheduler has a GitHub env token that can be forwarded to provider dev containers through CODE_QUEUE_REMOTE_CODEX_ENV_KEYS"
: "scheduler is missing GH_TOKEN/GITHUB_TOKEN; provider dev containers cannot receive a GitHub token even though CODE_QUEUE_REMOTE_CODEX_ENV_KEYS includes those keys",
};
}
function compactPrRuntimePreflight(preflight: Record<string, unknown>, options: CodexPrPreflightOptions): Record<string, unknown> {
const pull = asRecord(preflight.pullRequestDelivery) ?? {};
const tools = asRecord(pull.tools) ?? {};
const credentials = asRecord(pull.credentials) ?? {};
const git = asRecord(pull.git) ?? {};
const githubContext = asRecord(pull.githubContext) ?? {};
const egress = asRecord(pull.egress) ?? {};
const proxy = asRecord(egress.proxy) ?? {};
const remote = asRecord(pull.remote);
const ports = asRecord(preflight.ports) ?? {};
const tokenCoverage = tokenCoverageStatus(credentials);
const limitations = Array.isArray(pull.limitations) ? pull.limitations.map(String) : [];
const risks = Array.isArray(pull.risks) ? pull.risks.map(String) : [];
const ok = preflight.ok === true && tokenCoverage.ok === true;
const result: Record<string, unknown> = {
ok,
checkedAt: preflight.checkedAt ?? pull.checkedAt ?? null,
runner: {
serviceId: "code-queue",
plane: "D601 k3s scheduler/runner",
queueScope: "all queues executed by the scheduler, including default",
cwd: preflight.cwd ?? null,
pid: preflight.pid ?? null,
},
tokenCoverage,
tools: {
git: compactToolStatus(tools.git),
gh: compactToolStatus(tools.gh),
hub: compactToolStatus(tools.hub),
jq: compactToolStatus(tools.jq),
ssh: compactToolStatus(tools.ssh),
curl: compactToolStatus(tools.curl),
},
agentPorts: {
codex: compactAgentPortStatus(ports.codex),
opencode: compactAgentPortStatus(ports.opencode),
},
git: {
insideWorktree: git.insideWorktree ?? false,
branch: git.branch ?? null,
head: git.head ?? null,
originMaster: git.originMaster ?? null,
remoteOrigin: git.remoteOrigin ?? null,
home: git.home ?? null,
homeWritable: git.homeWritable ?? false,
knownHostsPresent: git.knownHostsPresent ?? false,
privateKeyPresent: git.privateKeyPresent ?? false,
},
githubContext: {
host: githubContext.host ?? null,
apiBaseUrl: githubContext.apiBaseUrl ?? null,
repo: githubContext.repo ?? null,
issueProbeNumber: githubContext.issueProbeNumber ?? null,
},
egress: {
proxy: {
selectedProxyHost: proxy.selectedProxyHost ?? null,
selectedProxyPort: proxy.selectedProxyPort ?? null,
selectedProxyHostResolvable: proxy.selectedProxyHostResolvable ?? null,
},
githubDefault: compactCommandProbe(egress.githubDefault),
apiDefault: compactCommandProbe(egress.apiDefault),
issueApi: compactCommandProbe(egress.issueApi),
},
remote: remote === null ? null : {
gitLsRemote: compactCommandProbe(remote.gitLsRemote),
gitHttpsLsRemote: compactCommandProbe(remote.gitHttpsLsRemote),
githubSshAuthenticated: remote.githubSshAuthenticated ?? false,
ghAuthStatus: compactCommandProbe(remote.ghAuthStatus),
ghRepoView: compactCommandProbe(remote.ghRepoView),
ghIssueView: compactCommandProbe(remote.ghIssueView),
ghPrReadOnly: compactCommandProbe(remote.ghPrReadOnly),
},
pushDryRun: compactCommandProbe(pull.pushDryRun),
limitations,
risks,
runnerDisposition: ok ? "ready" : "infra-blocked",
recoveryHint: ok
? "Runner PR workflow has env-token coverage for the scheduler."
: "Inject GH_TOKEN or GITHUB_TOKEN into the Code Queue scheduler runtime secret for the target queue, then rerun this preflight before creating a PR.",
commands: {
local: "bun scripts/cli.ts gh auth status --repo pikasTech/unidesk",
runner: "bun scripts/cli.ts codex pr-preflight --remote",
runnerPushDryRun: "bun scripts/cli.ts codex pr-preflight --remote --push-dry-run --push-dry-run-ref refs/heads/probe/code-queue-pr-capability",
rawProxy: "bun scripts/cli.ts microservice proxy code-queue /api/runtime-preflight?remote=1 --raw",
},
};
if (options.full) result.rawRuntimePreflight = preflight;
return result;
}
function codeQueuePrPreflight(optionArgs: string[] = [], fetcher: CodexResponseFetcher = coreInternalFetch): unknown {
const options = parsePrPreflightOptions(optionArgs);
const path = codeQueueProxyPath(`/api/runtime-preflight${queryString({
remote: options.remote ? 1 : undefined,
pushDryRun: options.pushDryRun ? 1 : undefined,
pushDryRunRef: options.pushDryRunRef,
issue: options.issueNumber,
})}`);
const response = unwrapCodexResponse(fetcher(path));
const preflight = asRecord(response.body.runtimePreflight);
if (preflight === null) throw new Error("Code Queue runtime-preflight response did not include runtimePreflight");
const compact = compactPrRuntimePreflight(preflight, options);
return {
ok: compact.ok,
upstream: response.upstream,
preflight: compact,
};
}
export function codexPrPreflightQueryForTest(optionArgs: string[], fetcher: CodexResponseFetcher): unknown {
return codeQueuePrPreflight(optionArgs, fetcher);
}
function codexSubmitTask(args: string[]): unknown {
const options = parseSubmitOptions(args);
const payload = submitPayload(options);
@@ -2069,6 +2259,7 @@ export async function runCodeQueueCommand(_config: UniDeskConfig, args: string[]
assertKnownOptions(args.slice(1), {}, `codex ${action}`);
return codeQueueDevReady();
}
if (action === "pr-preflight" || action === "runtime-preflight") return codeQueuePrPreflight(args.slice(1));
if (action === "output") {
const taskId = requireTaskId(taskIdArg, "codex output");
return codexOutputQuery(taskId, args.slice(2));
@@ -2103,5 +2294,5 @@ export async function runCodeQueueCommand(_config: UniDeskConfig, args: string[]
const taskId = requireTaskId(taskIdArg, "codex steer");
return codexSteerTask(taskId, args.slice(2));
}
throw new Error("codex command must be one of: submit, enqueue, task, summary, show, tasks, overview, output, judge, read, mark-read, dev-ready, health, queues, queue list, queue create, queue merge, move, steer, interrupt, cancel");
throw new Error("codex command must be one of: submit, enqueue, task, summary, show, tasks, overview, output, judge, read, mark-read, dev-ready, health, pr-preflight, runtime-preflight, queues, queue list, queue create, queue merge, move, steer, interrupt, cancel");
}
+3 -1
View File
@@ -49,6 +49,7 @@ export function rootHelp(): unknown {
{ command: "schedule upsert-pgdata-backup [--time HH:MM] [--remote-base /SERVER_DATA/UNIDESK_PG_DATA]", description: "Create or update the daily PGDATA physical backup task that uploads monthly rotated archives to Baidu Netdisk." },
{ command: "codex deploy <commitId> [--provider-id D601] [--timeout-ms N]", description: "Disabled legacy Code Queue deploy path; use the dev-only artifact consumer instead." },
{ command: "codex submit [prompt] [--prompt-file path|--prompt-stdin] [--queue queueId] [--provider-id id] [--cwd path] [--model model] [--execution-mode mode] [--max-attempts N] [--reference-task-id id] [--dry-run]", description: "Submit a Code Queue task through backend-core -> code-queue proxy; --dry-run shows the structured request without enqueueing." },
{ command: "codex pr-preflight [--remote] [--push-dry-run --push-dry-run-ref refs/heads/probe/<name>] [--issue N]", description: "Read-only PR admission check against the D601 scheduler/runner token, GitHub egress, repo visibility, and optional push dry-run." },
{ command: "codex task <taskId> [--detail] [--trace --tail|--from-start|--after-seq N|--before-seq N --limit N] [--full]", description: "Fetch the bounded review view by default: original prompt, final response, and drill-down commands; detail and trace are opt-in." },
{ command: "codex tasks [--view supervisor|full] [--queue id] [--status status[,status]] [--unread|--unread-only] [--limit N] [--before-id id]", description: "Show the bounded supervisor view by default: running, unread terminal, recent completed, queued, diagnostics, and drill-down commands." },
{ command: "codex output <taskId> [--tail|--from-start|--after-seq N|--before-seq N --limit N] [--full-text]", description: "Fetch paged raw Code Queue output records by seq when a trace row has omitted command/output text." },
@@ -204,7 +205,7 @@ function scheduleHelp(): unknown {
function codexHelp(): unknown {
return {
command: "codex deploy|submit|task|tasks|output|read|dev-ready|judge|steer|interrupt|cancel|queues|queue|move",
command: "codex deploy|submit|task|tasks|output|read|dev-ready|pr-preflight|judge|steer|interrupt|cancel|queues|queue|move",
output: "json",
usage: [
"bun scripts/cli.ts codex deploy <commitId> # disabled legacy deployment entry",
@@ -214,6 +215,7 @@ function codexHelp(): unknown {
"bun scripts/cli.ts codex output <taskId> [--tail|--from-start|--after-seq N|--before-seq N --limit N] [--full-text]",
"bun scripts/cli.ts codex read <taskId>",
"bun scripts/cli.ts codex dev-ready",
"bun scripts/cli.ts codex pr-preflight [--remote] [--push-dry-run --push-dry-run-ref refs/heads/probe/<name>] [--issue N]",
"bun scripts/cli.ts codex judge <taskId> --attempt N [--dry-run] [--include-prompt]",
"bun scripts/cli.ts codex steer <taskId> [prompt|--prompt-file path|--prompt-stdin] [--dry-run]",
"bun scripts/cli.ts codex interrupt|cancel <taskId>",