forgedock 1.60.0 → 1.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/config-schema.mjs +44 -1
- package/bin/engine/runlog.mjs +52 -0
- package/bin/engine-cli.mjs +9 -4
- package/bin/env/bench.mjs +38 -0
- package/bin/env/cli.mjs +134 -0
- package/bin/env/env.mjs +339 -0
- package/bin/forgedock.mjs +32 -3
- package/bin/help-text.mjs +2 -0
- package/bin/lean/ci-budget.mjs +3 -1
- package/bin/lean/ci-classify.mjs +74 -0
- package/bin/lean/ci-classify.test.mjs +147 -0
- package/bin/lean/ci-emit.mjs +175 -0
- package/bin/lean/ci-emit.test.mjs +177 -0
- package/bin/lean/ci-preflight.mjs +183 -0
- package/bin/lean/ci-preflight.test.mjs +122 -0
- package/bin/lean/ci-runner-health.mjs +213 -0
- package/bin/lean/ci-runner-health.test.mjs +113 -0
- package/bin/lean/ci-watch.mjs +79 -0
- package/bin/lean/ci-watch.test.mjs +80 -0
- package/bin/lean/conformance.mjs +7 -1
- package/bin/lean/conformance.test.mjs +7 -1
- package/bin/lean/depcache.mjs +38 -8
- package/bin/lean/deploy-stages.mjs +514 -0
- package/bin/lean/deploy-stages.test.mjs +580 -0
- package/bin/lean/effects.mjs +50 -0
- package/bin/lean/execution.mjs +8 -1
- package/bin/lean/lean.mjs +61 -12
- package/bin/lean/lean.test.mjs +87 -0
- package/bin/lean/preflight.mjs +62 -1
- package/bin/lean/preflight.test.mjs +30 -1
- package/bin/lean/release-deploy.mjs +12 -6
- package/bin/lean/release-flakes.mjs +16 -0
- package/bin/lean/release-flakes.test.mjs +15 -0
- package/bin/lean/release-gates.mjs +24 -1
- package/bin/lean/release-ledger.mjs +21 -0
- package/bin/lean/release-minutes-timing.test.mjs +57 -0
- package/bin/lean/release-minutes.mjs +98 -0
- package/bin/lean/release-promote.mjs +444 -0
- package/bin/lean/release-promote.test.mjs +470 -0
- package/bin/lean/release-rollback.mjs +14 -6
- package/bin/lean/release.mjs +31 -2
- package/bin/lean/sandbox-remote.mjs +11 -3
- package/bin/lean/testengine-recall.mjs +82 -0
- package/bin/lean/testengine-recall.test.mjs +103 -0
- package/bin/lean/testengine-shard.mjs +150 -0
- package/bin/lean/testengine-shard.test.mjs +111 -0
- package/bin/lean/testengine.mjs +486 -0
- package/bin/lean/testengine.test.mjs +303 -0
- package/bin/lean/validate-catalog.mjs +16 -0
- package/bin/lean/validate-catalog.test.mjs +14 -1
- package/bin/lean/verify-settle.test.mjs +156 -0
- package/bin/lean/verify.mjs +98 -3
- package/bin/pool/agent.mjs +65 -6
- package/bin/pool/ci-events.mjs +183 -0
- package/bin/pool/ci-events.test.mjs +143 -0
- package/bin/pool/docker.mjs +7 -0
- package/bin/pool/lane-tools.mjs +32 -0
- package/bin/pool/router.mjs +21 -1
- package/bin/pool/warm.mjs +14 -3
- package/bin/stats/ci-awareness.mjs +66 -0
- package/bin/stats/index.mjs +44 -3
- package/bin/stats/release-ledger.test.mjs +226 -0
- package/bin/stats/release.mjs +365 -1
- package/bin/stats/stats.test.mjs +36 -0
- package/docs/CI.md +31 -0
- package/docs/CONFIG.md +235 -2
- package/docs/ENV-LIBRARY.md +172 -0
- package/docs/STATS.md +43 -0
- package/docs/ci-events.md +88 -0
- package/docs/test-engine.md +98 -0
- package/package.json +1 -1
- package/pool/README.md +1 -0
- package/pool/image/entrypoint.sh +15 -3
- package/pool/services/docker-compose.yml +53 -0
- package/pool/services/git-mirror.sh +22 -0
- package/scripts/acceptance-red-green.sh +5 -2
- package/scripts/acceptance-red-green.test.sh +11 -0
- package/templates/github-actions/forge-env/action.yml +65 -0
package/bin/lean/effects.mjs
CHANGED
|
@@ -287,6 +287,31 @@ export function makeHostProbe() {
|
|
|
287
287
|
};
|
|
288
288
|
}
|
|
289
289
|
|
|
290
|
+
/**
|
|
291
|
+
* #5718: the read and cancel seams of CI runs, on any `gh(args)` runner (the lane io and `forgedock ci cancel-superseded` share them).
|
|
292
|
+
* `checkSuites(sha)`: [{id, status, conclusion, app}] (status queued | in_progress | completed), for verify.settle.
|
|
293
|
+
* `branchRuns(branch)`: the queued and running runs, [{id, headSha, status, event, actor, createdAt}], for verify.cancel_superseded.
|
|
294
|
+
* `viewerLogin()`: the login this process acts as; an installation token has no user, so a bot sets FORGE_BOT_LOGIN.
|
|
295
|
+
*/
|
|
296
|
+
export function ciRunSeams({ gh, repo }) {
|
|
297
|
+
const rows = (out) => String(out ?? "").split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l));
|
|
298
|
+
return {
|
|
299
|
+
async checkSuites(sha) { return rows(await gh(["api", "--paginate", `repos/${repo}/commits/${sha}/check-suites`, "--jq", ".check_suites[] | {id, status, conclusion, app: .app.slug} | @json"])); },
|
|
300
|
+
async branchRuns(branch) {
|
|
301
|
+
const jq = ".workflow_runs[] | {id, headSha: .head_sha, status, event, actor: (.triggering_actor.login // .actor.login // null), createdAt: .created_at} | @json";
|
|
302
|
+
const out = [];
|
|
303
|
+
for (const status of ["queued", "in_progress"]) out.push(...rows(await gh(["api", "--paginate", `repos/${repo}/actions/runs?branch=${encodeURIComponent(branch)}&status=${status}&per_page=100`, "--jq", jq])));
|
|
304
|
+
return out;
|
|
305
|
+
},
|
|
306
|
+
async cancelRun(id) { await gh(["api", "-X", "POST", `repos/${repo}/actions/runs/${id}/cancel`]); },
|
|
307
|
+
async viewerLogin() {
|
|
308
|
+
const env = String(process.env.FORGE_BOT_LOGIN ?? "").trim();
|
|
309
|
+
if (env) return env;
|
|
310
|
+
try { return String(await gh(["api", "user", "--jq", ".login"])).trim() || null; } catch { return null; }
|
|
311
|
+
},
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
|
|
290
315
|
/**
|
|
291
316
|
* Required status checks for `lane` (#4158): the union of classic branch protection (contexts + checks) and the
|
|
292
317
|
* repository rulesets that apply to the branch (`rules/branches/{lane}`, type required_status_checks). Each source
|
|
@@ -449,6 +474,30 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
|
|
|
449
474
|
async rerunFailedJobs(runId) {
|
|
450
475
|
await run("gh")(["run", "rerun", String(runId), "--failed", "-R", repo]);
|
|
451
476
|
},
|
|
477
|
+
/** #5692: Actions runs of a head sha, newest first: [{id, status, conclusion}]. */
|
|
478
|
+
async runsForSha(sha) {
|
|
479
|
+
const j = JSON.parse(await run("gh")(["api", `repos/${repo}/actions/runs?head_sha=${encodeURIComponent(sha)}`]) || "{}");
|
|
480
|
+
return (j.workflow_runs ?? []).map((r) => ({ id: r.id, status: r.status, conclusion: r.conclusion ?? null }));
|
|
481
|
+
},
|
|
482
|
+
/** #5692: jobs of one run with their steps: [{id, name, status, conclusion, steps:[{name, status, conclusion, completed_at}]}]. */
|
|
483
|
+
async jobsOf(runId) {
|
|
484
|
+
const j = JSON.parse(await run("gh")(["api", `repos/${repo}/actions/runs/${encodeURIComponent(String(runId))}/jobs?per_page=100`]) || "{}");
|
|
485
|
+
return (j.jobs ?? []).map((x) => ({ id: x.id, name: x.name, status: x.status, conclusion: x.conclusion ?? null,
|
|
486
|
+
steps: (x.steps ?? []).map((s) => ({ name: s.name, status: s.status, conclusion: s.conclusion ?? null, completed_at: s.completed_at ?? null })) }));
|
|
487
|
+
},
|
|
488
|
+
/** #5692: `gh run cancel <id>`; throws when it cannot. */
|
|
489
|
+
async cancelRun(runId) { await run("gh")(["run", "cancel", String(runId), "-R", repo]); },
|
|
490
|
+
/** #5692: router long-poll GET /ci/events (FORGEDOCK_CI_EVENTS_URL + FORGEDOCK_CI_TOKEN); null when unconfigured or unreachable. */
|
|
491
|
+
async ciEventsWait({ repo: r = repo, sha, pr, since = 0, waitS = 0 }) {
|
|
492
|
+
const base = process.env.FORGEDOCK_CI_EVENTS_URL || process.env.FORGE_CI_EVENTS_URL;
|
|
493
|
+
if (!base) return null;
|
|
494
|
+
try {
|
|
495
|
+
const u = new URL(base);
|
|
496
|
+
u.search = new URLSearchParams({ repo: r, ...(sha ? { sha } : { pr: String(pr) }), since: String(since), wait: String(waitS) }).toString();
|
|
497
|
+
const res = await fetch(u, { headers: process.env.FORGEDOCK_CI_TOKEN ? { authorization: `Bearer ${process.env.FORGEDOCK_CI_TOKEN}` } : {}, signal: AbortSignal.timeout((waitS + 10) * 1000) });
|
|
498
|
+
return res.ok ? await res.json() : null;
|
|
499
|
+
} catch { return null; }
|
|
500
|
+
},
|
|
452
501
|
/** Check runs on a commit (push-triggered CI): [{name, state: success|failure|pending, url, id, conclusion}], same mapping as checkStates; `id` orders attempts (#4387). */
|
|
453
502
|
async commitChecks(sha) {
|
|
454
503
|
const out = String(await run("gh")(["api", "--paginate", `repos/${repo}/commits/${sha}/check-runs`, "--jq", ".check_runs[] | {id, name, status, conclusion, url: .html_url} | @json"]));
|
|
@@ -458,6 +507,7 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
|
|
|
458
507
|
return { name: c.name, state, url: c.url ?? null, id: c.id ?? null, conclusion: c.status === "completed" ? String(c.conclusion ?? "").toLowerCase() || null : null }; // #4387 id orders attempts; #4403 raw conclusion (skipped = not run)
|
|
459
508
|
});
|
|
460
509
|
},
|
|
510
|
+
...ciRunSeams({ gh: run("gh"), repo }), // #5718: checkSuites, branchRuns, cancelRun, viewerLogin
|
|
461
511
|
/**
|
|
462
512
|
* #4270 verify.check_run: one completed check run on `sha` (`gh api -X POST repos/<repo>/check-runs`, JSON on stdin).
|
|
463
513
|
* Needs a token allowed to create check runs (GitHub App, checks:write). Resolves {id, html_url}; throws on failure.
|
package/bin/lean/execution.mjs
CHANGED
|
@@ -53,6 +53,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
|
|
|
53
53
|
import { readFile, readdir } from "node:fs/promises";
|
|
54
54
|
import { cpus, homedir, loadavg } from "node:os";
|
|
55
55
|
import { dirname, join } from "node:path";
|
|
56
|
+
import { mergeRemoteLog } from "../engine/runlog.mjs";
|
|
56
57
|
import { promisify } from "node:util";
|
|
57
58
|
import { isLaneAlive, launchLane, writeAtomic } from "./batch.mjs";
|
|
58
59
|
import { schedDir } from "./sched.mjs";
|
|
@@ -486,7 +487,13 @@ export function containerProvider({ batch, repo, image, gitDir, cacheDir = `${ho
|
|
|
486
487
|
try { s = String(await docker(["inspect", "-f", "{{.State.Status}}", h.id])).trim(); } catch { return "gone"; }
|
|
487
488
|
return ["running", "created", "restarting"].includes(s) ? "running" : "exited";
|
|
488
489
|
},
|
|
489
|
-
async fetchResult(h) {
|
|
490
|
+
async fetchResult(h) {
|
|
491
|
+
const r = readJson(batch.resultFile(h?.issue));
|
|
492
|
+
if (!r || typeof r !== "object" || !r.runLog) return r;
|
|
493
|
+
const { runLog, ...rest } = r; // #5697: merge the lane's exported run log into the host run log
|
|
494
|
+
mergeRemoteLog(process.env.FORGE_RUNS_DIR || join(homedir(), ".forge", "runs"), h.issue, runLog, { repo });
|
|
495
|
+
return rest;
|
|
496
|
+
},
|
|
490
497
|
async teardown(h) {
|
|
491
498
|
try { await docker(["rm", "-f", h.id]); return true; } catch (e) {
|
|
492
499
|
if (/no such container/i.test(errText(e))) return true;
|
package/bin/lean/lean.mjs
CHANGED
|
@@ -30,7 +30,7 @@ import { matchBaselines, baselineFailures, foldRegression } from "./baselines.mj
|
|
|
30
30
|
import { readRollouts, detectNewOffKeys, rolloutModes, liveDeferralBlocks } from "./activation.mjs";
|
|
31
31
|
import { toolMisses } from "./toolplace.mjs";
|
|
32
32
|
import { hasRecipe, installLaneTools } from "../pool/lane-tools.mjs";
|
|
33
|
-
import { testRunnerProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract, declaredEnv, depInstallFailures, testRunSummary, projectBinDirs, withLocalBins } from "./preflight.mjs";
|
|
33
|
+
import { testRunnerProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract, declaredEnv, depInstallFailures, testRunSummary, projectBinDirs, withLocalBins, manifestDepOwner } from "./preflight.mjs";
|
|
34
34
|
import { resolveLane, isDefaultLane, isShippedLane, DEFAULT_STAGING_BRANCH } from "./lane.mjs";
|
|
35
35
|
import { splitGate, rationaleLine } from "./decompose.mjs";
|
|
36
36
|
import { ceilingFor, predictRestart, handoffFacts, NARROW_NOTE } from "./ceiling.mjs";
|
|
@@ -81,7 +81,9 @@ import { unjustified } from "./enumerating.mjs";
|
|
|
81
81
|
import { applyEnumerating, renameDuplicates, verifyApplied } from "./mechfix.mjs"; // #5348
|
|
82
82
|
import { addLaneWorktree, DEFAULT_SPARSE_MAX_KB } from "./worktree.mjs";
|
|
83
83
|
import { claimWarm, refillWarm, warmTreeCount, NO_HOOKS } from "./warmtree.mjs";
|
|
84
|
-
import {
|
|
84
|
+
import { ciSignal, cancelDecision, eventLog } from "./ci-watch.mjs";
|
|
85
|
+
import { classifyCiFailure } from "./ci-classify.mjs";
|
|
86
|
+
import { parseVerify, runCiVerify, collectFailedLogs, capLogs, VERIFY_MODES, VERIFY_CHECK_NAME, verifyReport, ciGate, rerunFailedOnce, rerunTarget, splitFlaky, cancelSuperseded } from "./verify.mjs";
|
|
85
87
|
import { e2eSpecs, e2eWanted, uiInteractiveChanged, ownFailures, runE2eGate, fakedPaths, NO_TRIGGER } from "./e2e.mjs";
|
|
86
88
|
import { transferToEpic } from "./acceptance.mjs";
|
|
87
89
|
import { laneBackendId } from "./limits.mjs";
|
|
@@ -111,7 +113,7 @@ import { makePostRun } from "./postrun.mjs";
|
|
|
111
113
|
import { ensureSignedOff, salvageBranch, dropSalvageTracking } from "./signoff.mjs";
|
|
112
114
|
import { reconcileCheckpoints } from "./checkpoint-reconcile.mjs";
|
|
113
115
|
import { createLedger, flattenPhases } from "./phaseledger.mjs";
|
|
114
|
-
import { DEFAULT_CATALOG_SOURCES, deriveCatalog, mergeRecipes, rewriteMissed, isDriftFailure } from "./validate-catalog.mjs";
|
|
116
|
+
import { DEFAULT_CATALOG_SOURCES, deriveCatalog, mergeRecipes, rewriteMissed, isDriftFailure, rewriteSubprojectVenv } from "./validate-catalog.mjs";
|
|
115
117
|
import { runLightStep, runLightTests, lightBuildPrompt, upgradeNote, renderLiteReceipt } from "./lightlane.mjs";
|
|
116
118
|
|
|
117
119
|
/**
|
|
@@ -260,6 +262,7 @@ const defaultCredExec = (args) => {
|
|
|
260
262
|
* @param {string} [o.reviewerModel] default claude-sonnet-5-5
|
|
261
263
|
* @param {string} [o.fixModel] model of fresh fix-round sessions (#4363, forge.yaml lean.fix_model); default the reviewer model
|
|
262
264
|
* @param {object} [o.builderRouting] forge.yaml lean.builder_routing/builder_mid_model (#4394): {mode: on (default)|off, midModel}
|
|
265
|
+
* @param {object|string} [o.ci] forge.yaml ci block or bare `fail_fast` policy (#5692): `deterministic` cancels the run on a downstream-class CI event; default off
|
|
263
266
|
* @param {string} [o.followupsDefaultMilestone] forge.yaml followups.default_milestone (#4664): milestone of deferred follow-ups whose parent's milestone has shipped and has no next one
|
|
264
267
|
* @param {string} [o.followupsRollupLabel] forge.yaml followups.rollup_issue_label (#5078): a repo's own open issue with this label is the post-deploy rollup when no marked one is open
|
|
265
268
|
* @param {string} [o.sequenceRegenerate] forge.yaml lean.sequence.regenerate (#4386): snapshot generator for a schema-changing renumbered migration
|
|
@@ -1879,6 +1882,13 @@ export async function runCore(o) {
|
|
|
1879
1882
|
await git(["add", "--", CHECKS_FILE]); await git(["commit", "--no-verify", "-m", "chore(forge): generated post-deploy checks for production-only e2e requirements (#5468)"]);
|
|
1880
1883
|
} catch (e) { T.anomalies.push(`generated post-deploy checks not committed: ${String(e?.message ?? e).slice(0, 160)}`); }
|
|
1881
1884
|
}
|
|
1885
|
+
let freezeTracked = []; // #5683: tracked paths, for the sub-project venv rewrite at freeze
|
|
1886
|
+
/** #5683: name -> the sub-project dir whose tracked manifest declares it (a project dependency, not a host tool), else null. */
|
|
1887
|
+
async function depOwnerOf() {
|
|
1888
|
+
const files = String(await git(["ls-files"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean), texts = new Map();
|
|
1889
|
+
for (const f of files) if (/(^|\/)(package\.json|pyproject\.toml|requirements[\w.-]*\.txt)$/.test(f) && !f.split("/").includes("node_modules")) texts.set(f, String(await io.fs.read(`${wt}/${f}`).catch(() => "")));
|
|
1890
|
+
return { files, owner: (name) => manifestDepOwner(name, files, (f) => texts.get(f) ?? "") };
|
|
1891
|
+
}
|
|
1882
1892
|
function freezeRewrites(c) {
|
|
1883
1893
|
const r = applyValidateRecipes(c, validateRecipes);
|
|
1884
1894
|
const pd = (id, cmd) => { const to = rewriteProjectDirCommand(cmd); if (to !== cmd) T.decisions.push(`project-dir rewrite of ${id}: \`${cmd}\` -> \`${to}\``); return to; };
|
|
@@ -1888,6 +1898,9 @@ export async function runCore(o) {
|
|
|
1888
1898
|
if (t && typeof t === "object" && typeof t.command === "string") r.contract = { ...r.contract, repro_test: { ...t, command: pd("repro_test", t.command) } };
|
|
1889
1899
|
}
|
|
1890
1900
|
for (const x of r.applied) T.decisions.push(`validate recipe rewrote ${x.id}: \`${x.from}\` -> \`${x.to}\``);
|
|
1901
|
+
const vr = rewriteSubprojectVenv(r.contract, freezeTracked, (rel) => existsSync(join(wt, rel))); // #5683
|
|
1902
|
+
r.contract = vr.contract;
|
|
1903
|
+
for (const x of vr.applied) T.decisions.push(`sub-project venv rewrite of ${x.id}: \`${x.from}\` -> \`${x.to}\``);
|
|
1891
1904
|
r.contract = foldRegression(r.contract); // #5448: the blast-radius regression set runs as validate G# entries
|
|
1892
1905
|
const e = autoPostDeployE2e(r.contract); // #5468: production-only e2e/manual rows become post-deploy with a generated check
|
|
1893
1906
|
for (const x of e.converted) { if (x.check) genChecks[x.check] = x.entry; T.decisions.push(`Production-only e2e/manual requirement ${x.id} frozen as post-deploy with ${x.check ? `generated check ${x.check}` : "no check (production observation window)"}`); }
|
|
@@ -2257,6 +2270,7 @@ export async function runCore(o) {
|
|
|
2257
2270
|
return o.contract;
|
|
2258
2271
|
};
|
|
2259
2272
|
let contract = dropScope(await readContract());
|
|
2273
|
+
freezeTracked = (await depOwnerOf()).files;
|
|
2260
2274
|
contract = freezeRewrites(contract);
|
|
2261
2275
|
await persistGenChecks();
|
|
2262
2276
|
await refreshIssue("contract validation");
|
|
@@ -2343,8 +2357,11 @@ export async function runCore(o) {
|
|
|
2343
2357
|
if (designRoute.blocked) return await needsHuman(`Design gate (forge.yaml design.gate: blocking): ${designRoute.reason}.\n\nRun /design on #${issue}; a FORGE:DESIGN_SPEC comment or the \`${designConfig.specLabel}\` label lifts the hold.`, OUTCOME_CODES.DESIGN_SPEC_REQUIRED, { ask: `Run /design for #${issue} (${designRoute.pages.slice(0, 3).join(", ")})` });
|
|
2344
2358
|
}
|
|
2345
2359
|
{ // #5447: the test plan's declared env is checked on the host the lane runs on before building; a missing runner is provisioned once, else the lane ends env.tool_missing (the orchestrator re-places it on a host that has it)
|
|
2346
|
-
const
|
|
2360
|
+
const deps5683 = await depOwnerOf(), projEnv = () => { const e = laneEnv(); const d = projectBinDirs(wt, deps5683.files); if (d.length) e.PATH = withLocalBins(e.PATH ?? process.env.PATH ?? "", d); return e; };
|
|
2361
|
+
const projDeps = declaredEnv(frozen).filter((t) => deps5683.owner(t) !== null); // #5683: a sub-project's declared dependency is prepared and resolved through its bin dirs, never a host tool
|
|
2362
|
+
const probeEnv = async () => { const miss = []; for (const t of declaredEnv(frozen)) { if (deps5683.owner(t) !== null) continue; const r = io.runCommand ? await io.runCommand({ command: t === "pytest" ? "python3 -m pytest --version" : `command -v ${t} >/dev/null || { test -d node_modules/${t} && ! test -e node_modules/.bin/${t}; } || ls -d .venv/lib/python*/site-packages/${t} >/dev/null 2>&1`, cwd: wt, timeoutMs: 30000, env: projEnv() }).catch(() => ({ rc: 1 })) : { rc: 0 }; if ((r?.rc ?? 0) !== 0) miss.push(t); } return miss; };
|
|
2347
2363
|
let envMiss = await probeEnv();
|
|
2364
|
+
if (projDeps.length && io.deps?.prepare) { try { await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined }); ev({ event: "TESTPLAN_ENV_PROJECT_DEPS", names: projDeps }); } catch { /* the install gate reports failures */ } }
|
|
2348
2365
|
if (envMiss.length) {
|
|
2349
2366
|
try {
|
|
2350
2367
|
if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined });
|
|
@@ -2370,12 +2387,15 @@ export async function runCore(o) {
|
|
|
2370
2387
|
const hn = contractHostNeeds(frozen, o.hostCaps && { ...o.hostCaps, hostCapabilities: (o.hostCaps.hostCapabilities ?? []).filter((c) => !relayed.has(c)) });
|
|
2371
2388
|
if (hn.caps.length) return await needsHuman(`Remote sandbox lacks host capability ${hn.caps.join(", ")}, which the frozen contract's validate command(s) ${hn.ids.join(", ")} need.\n\nThe dispatching host has it; the lane is recovered locally with the frozen contract.`, OUTCOME_CODES.ENV_CAPABILITY_REMOTE);
|
|
2372
2389
|
// #5331: a tool the sandbox itself lacks (probed where the lane runs) ends the lane before the builder implements; the tool-missing recovery places it on the host (orchestrate placeOf)
|
|
2373
|
-
|
|
2390
|
+
const remoteDeps = await depOwnerOf(); // #5683: a tool that is a tracked manifest dependency is prepared in the sandbox, never a lane_tools recipe or a host tool
|
|
2391
|
+
const ownedDep = (t) => remoteDeps.owner(t) !== null, notOwned = (m) => ({ ...m, tools: m.tools.filter((t) => !ownedDep(t)) });
|
|
2392
|
+
let tm0 = toolMisses(planMisses ?? await preflightValidates(frozen).catch(() => [])), tm = notOwned(tm0);
|
|
2393
|
+
if (tm0.tools.length && !tm.tools.length) { try { if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined }); ev({ event: "REMOTE_PROJECT_DEPS", tools: tm0.tools }); } catch { /* the install gate reports failures */ } }
|
|
2374
2394
|
if (tm.tools.length) { // #5423: provision the sandbox once (nested lockfiles, pytest) and re-probe before giving the lane up
|
|
2375
2395
|
try {
|
|
2376
2396
|
if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined });
|
|
2377
2397
|
if (tm.tools.includes("pytest") && io.runCommand) await io.runCommand({ command: "python3 -m pip install --user --quiet pytest", cwd: wt, timeoutMs: 180000, env: laneEnv() });
|
|
2378
|
-
tm = toolMisses(await preflightValidates(frozen).catch(() => []));
|
|
2398
|
+
tm = notOwned(toolMisses(await preflightValidates(frozen).catch(() => [])));
|
|
2379
2399
|
ev({ event: "REMOTE_PROVISIONED", remaining: tm.tools });
|
|
2380
2400
|
} catch { /* keep the original miss */ }
|
|
2381
2401
|
}
|
|
@@ -2385,7 +2405,7 @@ export async function runCore(o) {
|
|
|
2385
2405
|
const ins = await installLaneTools(withRecipe, { run: (a) => io.runCommand({ command: a.command, cwd: wt, timeoutMs: a.timeoutMs, env: laneEnv() }), root: process.getuid?.() === 0 });
|
|
2386
2406
|
ev({ event: "REMOTE_TOOLS_INSTALLED", tools: withRecipe, ok: ins.ok });
|
|
2387
2407
|
if (!ins.ok) return await needsHuman(`Installing ${ins.tool} in the remote sandbox failed (execution.lane_tools recipe); not re-placed on the host. Install stderr tail:\n${ins.stderrTail}`, OUTCOME_CODES.ENV_TOOL_MISSING);
|
|
2388
|
-
tm = toolMisses(await preflightValidates(frozen).catch(() => []));
|
|
2408
|
+
tm = notOwned(toolMisses(await preflightValidates(frozen).catch(() => [])));
|
|
2389
2409
|
ev({ event: "REMOTE_PROVISIONED", remaining: tm.tools });
|
|
2390
2410
|
}
|
|
2391
2411
|
if (noRecipe.length && tm.tools.some((t) => noRecipe.includes(t))) return await needsHuman(`Remote sandbox lacks ${noRecipe.join(", ")}, and no lane_tools recipe exists for ${noRecipe.length > 1 ? "them" : "it"}. Add it to \`execution.lane_tools\` in forge.yaml once a recipe exists, or add a recipe for ${noRecipe.join(", ")} in bin/pool/lane-tools.mjs (RECIPES).`, OUTCOME_CODES.ENV_TOOL_MISSING);
|
|
@@ -2808,7 +2828,12 @@ export async function runCore(o) {
|
|
|
2808
2828
|
files = await changedFiles();
|
|
2809
2829
|
if (ciGateNames === undefined) ciGateNames = vcfg.workflow ? null : await ciGate({ io, lane, mergeWait, verify: vcfg });
|
|
2810
2830
|
const verifyArgs = { io, branch, head, changedFiles: files, verify: vcfg, ciMaxMinutes, now, sleep, random, exclude: ciSeenRuns, gate: ciGateNames,
|
|
2811
|
-
push: () => gitPush(["push", "-u", "origin", branch])
|
|
2831
|
+
push: !vcfg.cancelSuperseded || vcfg.cancelSuperseded === "off" ? () => gitPush(["push", "-u", "origin", branch]) : async () => { // #5718: runs of the head this push replaces are cancelled
|
|
2832
|
+
const pushedAt = now(); await gitPush(["push", "-u", "origin", branch]);
|
|
2833
|
+
const c = await cancelSuperseded({ io, branch, head, mode: vcfg.cancelSuperseded, pushedAt });
|
|
2834
|
+
if (c.cancelled.length || c.failed.length) ev({ event: "CI_SUPERSEDED_CANCEL", head, cancelled: c.cancelled, failed: c.failed });
|
|
2835
|
+
},
|
|
2836
|
+
onSettle: (rec) => ev({ event: "CI_SETTLE", head, ...rec }), // #5718: verify.settle shadow/condition record
|
|
2812
2837
|
onPoll: async () => { await renew(); onProgress({ event: "phase_paused", phase: "verify", detail: `CI verification pending on ${branch}` }); } };
|
|
2813
2838
|
let v = await runCiVerify(verifyArgs);
|
|
2814
2839
|
if (v.runId != null) ciSeenRuns.push(v.runId);
|
|
@@ -3662,15 +3687,15 @@ export async function runCore(o) {
|
|
|
3662
3687
|
* logs, shared with ciVerify's verify.max_rounds budget; the fixed head is re-reviewed and pushed, then the wait restarts.
|
|
3663
3688
|
* Returns null to wait again, or a terminal result (rounds exhausted, no session, no new commit, review failure).
|
|
3664
3689
|
*/
|
|
3665
|
-
async function mergeFixRound(checks) {
|
|
3690
|
+
async function mergeFixRound(checks, ctx = null) { // ctx: a CI event (#5692) that started the round before its check completed
|
|
3666
3691
|
// #4586: the failed runs are rerun once per head before a round is counted; the red check is waited out until the rerun reports (bounded).
|
|
3667
3692
|
const rkey = `merge:${localHead}`, rerun = ciReruns.get(rkey);
|
|
3668
|
-
if (!rerun && !isSplit) {
|
|
3693
|
+
if (!rerun && !isSplit && !ctx) { // a still-running run cannot be rerun (#5692)
|
|
3669
3694
|
const rr = await rerunFailedOnce({ io, v: { failedChecks: checks, failures: checks.map((c) => ({ job: c.name })) } });
|
|
3670
3695
|
ciReruns.set(rkey, { rr, urls: new Map(checks.map((c) => [c.name, c.url ?? null])), waits: 0 });
|
|
3671
3696
|
ev({ event: "CI_FLAKE_RERUN", trigger: "merge", head: localHead, runs: rr.runs, jobs: rr.jobs, result: rr.ok ? "rerun-started" : "rerun-failed", detail: rr.detail });
|
|
3672
3697
|
if (rr.ok) { await sleep(20000); return null; }
|
|
3673
|
-
} else if (rerun?.rr.ok && rerun.waits < 20 && checks.every((c) => (c.url ?? null) === rerun.urls.get(c.name))) {
|
|
3698
|
+
} else if (!ctx && rerun?.rr.ok && rerun.waits < 20 && checks.every((c) => (c.url ?? null) === rerun.urls.get(c.name))) {
|
|
3674
3699
|
rerun.waits++; await sleep(20000); return null; // still the attempt that was rerun
|
|
3675
3700
|
}
|
|
3676
3701
|
const flakyNames = checks.filter((c) => vcfg.flaky?.includes(c.name)).map((c) => c.name);
|
|
@@ -3682,6 +3707,7 @@ export async function runCore(o) {
|
|
|
3682
3707
|
return await needsHuman(`Required check(s) failed on PR #${pr}: ${jobs.join(", ")}${ciRounds ? ` (after ${ciRounds} CI fix round(s))` : ""}`, OUTCOME_CODES.CI_RED);
|
|
3683
3708
|
}
|
|
3684
3709
|
const failures = await collectFailedLogs(io, checks);
|
|
3710
|
+
if (ctx && failures.length) failures[0] = { ...failures[0], log: [eventLog(ctx), failures[0].log].filter(Boolean).join("\n") };
|
|
3685
3711
|
ciRounds++;
|
|
3686
3712
|
T.decisions.push(`Required check(s) failed on PR #${pr} (${jobs.join(", ")}); builder resumed with the failed logs (round ${ciRounds}/${vcfg.maxRounds})`);
|
|
3687
3713
|
ev({ event: "CI_FIX_ROUND", trigger: "merge", round: ciRounds, jobs, pr });
|
|
@@ -3798,6 +3824,21 @@ export async function runCore(o) {
|
|
|
3798
3824
|
} else {
|
|
3799
3825
|
let startedAt = now();
|
|
3800
3826
|
let pollIndex = 0, gateHead = null, conflicted = false, notStartedLogged = false;
|
|
3827
|
+
// #5692: step-granular CI awareness. An event only starts a fix round early; the merge gate below is still the check states.
|
|
3828
|
+
const watching = policy !== "all" && !isSplit && Boolean(io.ciEventsWait || io.runsForSha);
|
|
3829
|
+
let sig = null, sigHead = null;
|
|
3830
|
+
const never = new Promise(() => {});
|
|
3831
|
+
const onCiEvent = async (e) => {
|
|
3832
|
+
const cls = e.class ?? classifyCiFailure({ step: e.step, lines: e.lines, test: e.test }).class;
|
|
3833
|
+
if (cls === "infra" || cls === "flaky-suspect") return null; // left to the check poll and its rerun
|
|
3834
|
+
const d = cancelDecision({ ...e, class: cls }, o.ci ?? o.failFast);
|
|
3835
|
+
ev({ event: "CI_AWARE", pr, head: localHead, source: e.source ?? "router", job: e.job ?? null, step: e.step ?? null, class: cls, event_ts: e.ts ?? null, aware_ts: new Date(now()).toISOString() });
|
|
3836
|
+
if (d.action === "cancel" && e.run_id && io.cancelRun) {
|
|
3837
|
+
let ok = true; try { await io.cancelRun(e.run_id); } catch { ok = false; }
|
|
3838
|
+
ev({ event: "CI_FAIL_FAST", pr, run: e.run_id, class: cls, cancelled: ok, reason: d.reason });
|
|
3839
|
+
}
|
|
3840
|
+
return await mergeFixRound([{ name: e.job ?? e.step ?? "ci", url: e.run_id ? `https://github.com/${repo}/actions/runs/${e.run_id}` : null }], e);
|
|
3841
|
+
};
|
|
3801
3842
|
for (;;) {
|
|
3802
3843
|
await renew();
|
|
3803
3844
|
let states = [];
|
|
@@ -3839,8 +3880,16 @@ export async function runCore(o) {
|
|
|
3839
3880
|
return await finish("ci-pending", `PR #${pr} still waiting on CI after ${ciMaxMinutes} min`, { pr });
|
|
3840
3881
|
}
|
|
3841
3882
|
onProgress({ event: "phase_paused", phase: "merge", detail: `CI pending on PR #${pr}` });
|
|
3842
|
-
await sleep(ciPollDelayMs(pollIndex++, random));
|
|
3883
|
+
if (!watching) { await sleep(ciPollDelayMs(pollIndex++, random)); continue; }
|
|
3884
|
+
if (sigHead !== localHead) { sig?.stop(); sig = ciSignal({ repo, sha: localHead, pr, io, sleep, now }); sigHead = localHead; }
|
|
3885
|
+
const evt = await Promise.race([sig.next().then((v) => v ?? never), sleep(ciPollDelayMs(pollIndex++, random)).then(() => null)]);
|
|
3886
|
+
if (evt) {
|
|
3887
|
+
const r = await onCiEvent(evt);
|
|
3888
|
+
if (r) { sig.stop(); return r; }
|
|
3889
|
+
startedAt = now(); pollIndex = 0; // a fix round (or none): the head gets the full wait budget
|
|
3890
|
+
}
|
|
3843
3891
|
}
|
|
3892
|
+
sig?.stop();
|
|
3844
3893
|
if (conflicted) {
|
|
3845
3894
|
const r = await baseSync("PR became conflicting while waiting for CI"); if (r) return r;
|
|
3846
3895
|
continue; // wait again on the synced head with a fresh budget
|
package/bin/lean/lean.test.mjs
CHANGED
|
@@ -2828,6 +2828,67 @@ describe("merge_wait policy", () => {
|
|
|
2828
2828
|
assert.ok(traj(w)[0].includes("carried forward across the CI fix round"));
|
|
2829
2829
|
});
|
|
2830
2830
|
|
|
2831
|
+
describe("#5692 CI events start the fix round before the check completes", () => {
|
|
2832
|
+
/** `build` stays pending until the builder's fix lands; `evts` is what the router has for the head. */
|
|
2833
|
+
const evWorld = (evts) => {
|
|
2834
|
+
const w = world(); w.cancelled = []; w.polls = 0;
|
|
2835
|
+
const sleep = w.io.sleep; w.io.sleep = async (ms) => (ms === WAIT ? sleep(ms) : new Promise((r) => setTimeout(r, 25))); // poll sleeps lose the race to a ready event
|
|
2836
|
+
w.io.requiredChecks = async () => ["build"];
|
|
2837
|
+
w.io.checkStates = async () => { w.polls++; return [{ name: "build", state: w.fixed ? "success" : "pending", url: RUN(77, 1) }]; };
|
|
2838
|
+
w.io.failedLogs = async () => { w.fixed = true; return "log"; };
|
|
2839
|
+
w.io.cancelRun = async (id) => { w.cancelled.push(id); };
|
|
2840
|
+
let sent = false;
|
|
2841
|
+
w.io.ciEventsWait = async () => (sent ? new Promise(() => {}) : (sent = true, { events: evts, next: evts.length }));
|
|
2842
|
+
return w;
|
|
2843
|
+
};
|
|
2844
|
+
const STEP = { seq: 1, type: "step_failed", job: "build", step: "pnpm test", run_id: "77", lines: ["FAIL boom.test.ts"], ts: "2026-11-15T10:00:00Z" };
|
|
2845
|
+
const SETUP = { ...STEP, step: "pnpm install", lines: ["ERR_PNPM_OUTDATED_LOCKFILE frozen-lockfile"] };
|
|
2846
|
+
const V1 = { ...parseVerify({}), maxRounds: 1 };
|
|
2847
|
+
|
|
2848
|
+
it("a step_failed while the check is still pending starts the fix round with the event lines, and merges only once the check is green", async () => {
|
|
2849
|
+
const w = evWorld([STEP]), p = fixPrompts(w), dir = tmpDir("core-");
|
|
2850
|
+
const r = await run(w, { dir, verify: V1 });
|
|
2851
|
+
assert.equal(r.terminalReason, "merged", r.reason);
|
|
2852
|
+
assert.equal(p.length, 1); assert.match(p[0], /FAIL boom\.test\.ts/); assert.match(p[0], /step: pnpm test/);
|
|
2853
|
+
assert.deepEqual(events(dir, "CI_FIX_ROUND").map((e) => e.trigger), ["merge"]);
|
|
2854
|
+
const aware = events(dir, "CI_AWARE"); assert.equal(aware.length, 1); assert.equal(aware[0].event_ts, "2026-11-15T10:00:00Z"); assert.equal(aware[0].source, "router");
|
|
2855
|
+
});
|
|
2856
|
+
it("fake clock: the fix round starts within 30 s of the step_failed while the check is still pending", async () => {
|
|
2857
|
+
const w = evWorld([STEP]), dir = tmpDir("core-");
|
|
2858
|
+
let pendingAtRound = null, sent = false;
|
|
2859
|
+
w.io.ciEventsWait = async () => (sent ? new Promise(() => {}) : (sent = true, { events: [{ ...STEP, ts: new Date(w.clock).toISOString() }], next: 1 })); // the step fails when the watcher starts
|
|
2860
|
+
w.io.sleep = async (ms) => { await new Promise((r) => setImmediate(r)); w.clock += ms; }; // fake clock; a sleep elapses as a macrotask, so a ready event wins the race before time passes
|
|
2861
|
+
w.io.failedLogs = async () => { pendingAtRound = !w.fixed; w.fixed = true; return "log"; };
|
|
2862
|
+
const r = await run(w, { dir, verify: V1 });
|
|
2863
|
+
assert.equal(r.terminalReason, "merged", r.reason); assert.equal(pendingAtRound, true, "round began while the check was pending");
|
|
2864
|
+
const a = events(dir, "CI_AWARE")[0], lag = Date.parse(a.aware_ts) - Date.parse(a.event_ts);
|
|
2865
|
+
assert.ok(lag >= 0 && lag <= 30000, `awareness lag ${lag} ms`);
|
|
2866
|
+
});
|
|
2867
|
+
it("merge gating unchanged: an event for a non-actionable class never merges while the required check is pending", async () => {
|
|
2868
|
+
const w = evWorld([{ ...STEP, lines: ["ECONNRESET registry.npmjs.org"], class: "infra" }]), dir = tmpDir("core-");
|
|
2869
|
+
let greenAt = null; w.io.checkStates = async () => { w.polls++; if (w.polls === 4) greenAt = w.merges.length; return [{ name: "build", state: w.polls >= 4 ? "success" : "pending", url: RUN(77, 1) }]; };
|
|
2870
|
+
const r = await run(w, { dir, verify: V1 });
|
|
2871
|
+
assert.equal(r.terminalReason, "merged", r.reason);
|
|
2872
|
+
assert.equal(greenAt, 0, "nothing merged before the check turned green"); assert.equal(w.merges.length, 1);
|
|
2873
|
+
assert.equal(events(dir, "CI_FIX_ROUND").length, 0);
|
|
2874
|
+
});
|
|
2875
|
+
it("a pending check at the wait budget never merges on events alone", async () => {
|
|
2876
|
+
const w = evWorld([{ ...STEP, class: "infra" }]); w.io.checkStates = async () => [{ name: "build", state: "pending", url: RUN(77, 1) }];
|
|
2877
|
+
const r = await run(w, { dir: tmpDir("core-"), verify: V1, ciMaxMinutes: 0 });
|
|
2878
|
+
assert.equal(r.terminalReason, "ci-pending"); assert.equal(w.merges.length, 0);
|
|
2879
|
+
});
|
|
2880
|
+
it("cancels the run only for a downstream class under fail_fast deterministic", async () => {
|
|
2881
|
+
const on = evWorld([SETUP]); await run(on, { dir: tmpDir("core-"), verify: V1, ci: { fail_fast: "deterministic" } });
|
|
2882
|
+
assert.deepEqual(on.cancelled, ["77"]);
|
|
2883
|
+
const dir = tmpDir("core-"), on2 = evWorld([SETUP]); await run(on2, { dir, verify: V1, ci: "deterministic" });
|
|
2884
|
+
assert.deepEqual(events(dir, "CI_FAIL_FAST").map((e) => [e.class, e.cancelled]), [["deterministic-setup", true]]);
|
|
2885
|
+
const off = evWorld([SETUP]); await run(off, { dir: tmpDir("core-"), verify: V1 });
|
|
2886
|
+
assert.deepEqual(off.cancelled, [], "policy off");
|
|
2887
|
+
const code = evWorld([STEP]); await run(code, { dir: tmpDir("core-"), verify: V1, ci: { fail_fast: "deterministic" } });
|
|
2888
|
+
assert.deepEqual(code.cancelled, [], "code class");
|
|
2889
|
+
});
|
|
2890
|
+
});
|
|
2891
|
+
|
|
2831
2892
|
it("a rerun that reports a new attempt still red goes to the fix round and reaches the builder", async () => {
|
|
2832
2893
|
const w = redBuild("failure", RUN(77, 2)); const p = fixPrompts(w), n = waits(w), dir = tmpDir("core-");
|
|
2833
2894
|
await run(w, { dir, verify: { ...parseVerify({}), maxRounds: 1 } });
|
|
@@ -8894,3 +8955,29 @@ describe("#5592 (8) comment and label spam", () => {
|
|
|
8894
8955
|
assert.ok(w.edits.some((e) => e.join(" ") === "issue edit 7 -R o/r --remove-label parked:ci.red"));
|
|
8895
8956
|
});
|
|
8896
8957
|
});
|
|
8958
|
+
|
|
8959
|
+
describe("#5683 monorepo sub-project dependencies are not host tools", () => {
|
|
8960
|
+
const pkg = JSON.stringify({ devDependencies: { vitest: "^1", vite: "^5" } });
|
|
8961
|
+
const withWeb = (w) => { const g = w.io.git; w.io.git = async (a, ...r) => (a[0] === "ls-files" && !a.includes(".forge-lean/") ? `${await g(a, ...r)}\nweb/package.json` : g(a, ...r)); w.files[`${WT}/web/package.json`] = pkg; return w; };
|
|
8962
|
+
const planEnv = (env) => ({ ...CONTRACT, test_plan: [{ requirement: "R1", proof: "the runner resolves", level: "unit", level_reason: "cheapest level that observes it", repro: "no-repro", reason: "env-only", command: "node --test test/foo.test.js", env }] });
|
|
8963
|
+
const hostMiss = (w) => { w.io.runCommand = async ({ command }) => (/command -v/.test(command) ? { rc: 1, output: "" } : { rc: 0, output: "" }); };
|
|
8964
|
+
it("monorepo sub-project env name is not a host tool: prepared, never env.tool_missing; a real host tool still is", async () => {
|
|
8965
|
+
const w = withWeb(world({ contract: planEnv(["vitest"]) })); let prepared = 0;
|
|
8966
|
+
w.io.deps = { prepare: async () => { prepared++; return []; } }; hostMiss(w);
|
|
8967
|
+
const ok = await run(w, { conformance: "enforce" });
|
|
8968
|
+
assert.notEqual(ok.code, OUTCOME_CODES.ENV_TOOL_MISSING); assert.ok(prepared >= 1);
|
|
8969
|
+
const h = withWeb(world({ contract: planEnv(["psql"]) })); h.io.deps = { prepare: async () => [] }; hostMiss(h);
|
|
8970
|
+
assert.equal((await run(h, { conformance: "enforce" })).code, OUTCOME_CODES.ENV_TOOL_MISSING);
|
|
8971
|
+
});
|
|
8972
|
+
it("monorepo sub-project remote name skips recipe branch; a manifest-less tool still hits it", async () => {
|
|
8973
|
+
const remote = { placement: { where: "remote", reason: "mode remote" } };
|
|
8974
|
+
const withTool = (tool) => ({ ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: `${tool} check x` }] });
|
|
8975
|
+
const probing = (w, tool) => { w.io.probeCommand = async (a) => ({ rc: new RegExp(tool).test(JSON.stringify(a)) ? 127 : 0, output: "" }); };
|
|
8976
|
+
const w = withWeb(world({ contract: withTool("vite") })); probing(w, "vite"); let prepared = 0; w.io.deps = { prepare: async () => { prepared++; return []; } };
|
|
8977
|
+
const r = await run(w, { dir: tmpDir("lean-5683a-"), ...remote });
|
|
8978
|
+
assert.notEqual(r.code, "env.tool_missing"); assert.ok(prepared >= 1);
|
|
8979
|
+
assert.doesNotMatch(w.comments.map((c) => c.body ?? c).join("\n"), /no lane_tools recipe/);
|
|
8980
|
+
const h = withWeb(world({ contract: withTool("zzcheck") })); probing(h, "zzcheck");
|
|
8981
|
+
assert.equal((await run(h, { dir: tmpDir("lean-5683b-"), ...remote })).code, "env.tool_missing");
|
|
8982
|
+
});
|
|
8983
|
+
});
|
package/bin/lean/preflight.mjs
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { builtinModules } from "node:module";
|
|
13
13
|
import { existsSync } from "node:fs";
|
|
14
|
-
import { join, dirname, delimiter } from "node:path";
|
|
14
|
+
import { join, dirname, delimiter, relative } from "node:path";
|
|
15
15
|
import { missingTool } from "./conformance.mjs";
|
|
16
16
|
|
|
17
17
|
export const PREFLIGHT_CAP = 20;
|
|
@@ -345,3 +345,64 @@ export function projectBinDirs(wt, files = [], { exists = existsSync, cap = 24 }
|
|
|
345
345
|
|
|
346
346
|
/** #5592: `base` PATH with the project-local executable dirs appended (never ahead of what the lane already resolves). */
|
|
347
347
|
export const withLocalBins = (base, dirs) => [...String(base ?? "").split(delimiter).filter(Boolean), ...dirs.filter((d) => !String(base ?? "").split(delimiter).includes(d))].join(delimiter);
|
|
348
|
+
|
|
349
|
+
const PY_MANIFESTS = new Set(["pyproject.toml", "poetry.lock", "uv.lock", "requirements.txt"]);
|
|
350
|
+
const normPy = (n) => String(n).toLowerCase().replace(/[-_.]+/g, "-");
|
|
351
|
+
const reEsc = (n) => String(n).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
352
|
+
/** #5683: does manifest text `text` (package.json, pyproject.toml, a requirements file) declare `name` as a dependency? */
|
|
353
|
+
function manifestDeclares(base, text, name) {
|
|
354
|
+
if (base === "package.json") {
|
|
355
|
+
try { const j = JSON.parse(text); return ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].some((k) => j?.[k] && Object.hasOwn(j[k], name)); } catch { return false; }
|
|
356
|
+
}
|
|
357
|
+
const n = reEsc(normPy(name)).replace(/-/g, "[-_.]+");
|
|
358
|
+
if (base === "pyproject.toml") return new RegExp(`["']\\s*${n}(?:\\[[^\\]]*\\])?\\s*(?:[<>=!~;@ ,]|["'])|^\\s*${n}\\s*=`, "im").test(text);
|
|
359
|
+
return new RegExp(`^\\s*${n}(?:\\[[^\\]]*\\])?\\s*(?:[<>=!~;@#]|$)`, "im").test(text);
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* #5683: the sub-project dir whose tracked manifest (package.json deps/devDeps/peerDeps, pyproject dependencies, a requirements
|
|
363
|
+
* file) declares `name`, or null. A declared test-plan env name that has an owner is a project dependency the lane prepares
|
|
364
|
+
* (deps.prepare), never a host tool or a lane_tools recipe. `files`: tracked paths; `readFile(path)`: manifest text. Pure.
|
|
365
|
+
*/
|
|
366
|
+
export function manifestDepOwner(name, files = [], readFile = () => "") {
|
|
367
|
+
for (const f of files) {
|
|
368
|
+
const parts = String(f).split("/"), base = parts[parts.length - 1];
|
|
369
|
+
if (parts.includes("node_modules") || !(base === "package.json" || base === "pyproject.toml" || /^requirements[\w.-]*\.txt$/.test(base))) continue;
|
|
370
|
+
let text = ""; try { text = String(readFile(f) ?? ""); } catch { continue; }
|
|
371
|
+
if (manifestDeclares(base.startsWith("requirements") ? "requirements.txt" : base, text, name)) return dirname(f);
|
|
372
|
+
}
|
|
373
|
+
return null;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** nearest ancestor dir (of `dir`, up to the root ".") holding a tracked Python manifest, or null. */
|
|
377
|
+
function nearestPyProject(dir, files) {
|
|
378
|
+
const have = new Set(files.filter((f) => PY_MANIFESTS.has(String(f).split("/").pop()) || /(^|\/)requirements[\w.-]*\.txt$/.test(f)).map((f) => dirname(f)));
|
|
379
|
+
for (let d = dir; ; d = dirname(d)) { if (have.has(d)) return d; if (d === "." || d === "/") return null; }
|
|
380
|
+
}
|
|
381
|
+
const PYTEST_SEG = /^(\s*(?:[A-Za-z_]\w*=\S*\s+)*)(?:python3?(?:\.\d+)?\s+-m\s+pytest|pytest)\b/;
|
|
382
|
+
/**
|
|
383
|
+
* #5683: a bare `python -m pytest` / `pytest` in a sub-project that has a tracked Python manifest and an in-project `.venv`
|
|
384
|
+
* runs through that venv's interpreter. The sub-project is the `cd X &&` directory, else the nearest manifest of the first
|
|
385
|
+
* test path, else the root. `exists(rel)`: repo-relative path check. Unchanged when no manifest or venv applies. Pure.
|
|
386
|
+
*/
|
|
387
|
+
export function venvPythonRewrite(command, files = [], exists = () => false) {
|
|
388
|
+
const parts = String(command ?? "").split(/(&&|\|\||;|\||\n)/);
|
|
389
|
+
let cwd = ".", changed = false;
|
|
390
|
+
const out = parts.map((seg, i) => {
|
|
391
|
+
if (i % 2) return seg;
|
|
392
|
+
const cd = /^\s*cd\s+(?:"([^"]+)"|'([^']+)'|(\S+))\s*$/.exec(seg);
|
|
393
|
+
if (cd) { const t = (cd[1] ?? cd[2] ?? cd[3]).replace(/^\.\//, "").replace(/\/+$/, ""); cwd = t.startsWith("/") || t.startsWith("$") || t.startsWith("..") ? "?" : join(cwd === "?" ? "." : cwd, t) || "."; return seg; }
|
|
394
|
+
const m = PYTEST_SEG.exec(seg);
|
|
395
|
+
if (!m || cwd === "?") return seg;
|
|
396
|
+
const rest = seg.slice(m[0].length);
|
|
397
|
+
const tp = rest.split(/\s+/).map((x) => x.replace(/::.*$/, "").replace(/^\.\//, "")).find((x) => x && !x.startsWith("-") && /[\w-]\/|\.py$/.test(x) && !x.startsWith("/"));
|
|
398
|
+
const origin = cwd !== "." ? cwd : tp ? dirname(tp) : ".";
|
|
399
|
+
const proj = nearestPyProject(origin, files);
|
|
400
|
+
if (proj === null) return seg;
|
|
401
|
+
const venv = join(proj, ".venv/bin/python");
|
|
402
|
+
if (!exists(venv)) return seg;
|
|
403
|
+
const rel = cwd === "." ? venv : relative(cwd, venv);
|
|
404
|
+
changed = true;
|
|
405
|
+
return `${m[1]}${rel} -m pytest${rest}`;
|
|
406
|
+
});
|
|
407
|
+
return changed ? out.join("") : String(command ?? "");
|
|
408
|
+
}
|
|
@@ -4,7 +4,7 @@ import { describe, it } from "node:test";
|
|
|
4
4
|
import assert from "node:assert/strict";
|
|
5
5
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
6
6
|
import { join } from "node:path";
|
|
7
|
-
import { testRunnerProblems, shellSegments, pythonImports, nodeImports, preflightProbes, preflightProblems, runProbeMiss, unsetEnvVars, runPreflight, knownToContract, contractCommands, depInstallFailures, testRunSummary, projectBinDirs, withLocalBins } from "./preflight.mjs";
|
|
7
|
+
import { manifestDepOwner, venvPythonRewrite, testRunnerProblems, shellSegments, pythonImports, nodeImports, preflightProbes, preflightProblems, runProbeMiss, unsetEnvVars, runPreflight, knownToContract, contractCommands, depInstallFailures, testRunSummary, projectBinDirs, withLocalBins } from "./preflight.mjs";
|
|
8
8
|
import { runCheckCommand } from "./effects.mjs";
|
|
9
9
|
import { repoTracks } from "./conformance.mjs";
|
|
10
10
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
@@ -194,3 +194,32 @@ describe("project-local executables (#5592 3d/9)", () => {
|
|
|
194
194
|
assert.equal(withLocalBins("/a:/b", ["/c", "/a"]), "/a:/b:/c");
|
|
195
195
|
});
|
|
196
196
|
});
|
|
197
|
+
|
|
198
|
+
describe("#5683 sub-project manifest deps and venv python", () => {
|
|
199
|
+
const files = ["package.json", "web/package.json", "services/api/pyproject.toml", "shared/content/pyproject.toml", "tools/requirements-dev.txt"];
|
|
200
|
+
const texts = { "web/package.json": JSON.stringify({ devDependencies: { vitest: "^1", vite: "^5" } }), "services/api/pyproject.toml": 'dependencies = ["Fast_Api>=1", "httpx"]\n[dependency-groups]\ndev = ["pytest>=8"]', "tools/requirements-dev.txt": "# dev\nruff==0.4\nblack[jupyter]>=24\n" };
|
|
201
|
+
const read = (f) => texts[f] ?? "";
|
|
202
|
+
it("manifestDepOwner resolves vitest to web", () => {
|
|
203
|
+
assert.equal(manifestDepOwner("vitest", files, read), "web");
|
|
204
|
+
assert.equal(manifestDepOwner("vite", files, read), "web");
|
|
205
|
+
assert.equal(manifestDepOwner("pytest", files, read), "services/api");
|
|
206
|
+
assert.equal(manifestDepOwner("fast-api", files, read), "services/api");
|
|
207
|
+
assert.equal(manifestDepOwner("black", files, read), "tools");
|
|
208
|
+
});
|
|
209
|
+
it("manifestDepOwner null for host tools", () => {
|
|
210
|
+
for (const t of ["psql", "promtool", "ruf"]) assert.equal(manifestDepOwner(t, files, read), null);
|
|
211
|
+
assert.equal(manifestDepOwner("vitest", ["web/node_modules/x/package.json"], () => texts["web/package.json"]), null);
|
|
212
|
+
});
|
|
213
|
+
const exists = (p) => ["services/api/.venv/bin/python", "shared/content/.venv/bin/python"].includes(p);
|
|
214
|
+
it("venvPythonRewrite uses sub-project venv", () => {
|
|
215
|
+
assert.equal(venvPythonRewrite("pytest -q", ["pyproject.toml"], (p) => p === ".venv/bin/python"), ".venv/bin/python -m pytest -q");
|
|
216
|
+
assert.equal(venvPythonRewrite("python -m pytest tests/x.py", files, exists), "python -m pytest tests/x.py");
|
|
217
|
+
assert.equal(venvPythonRewrite("cd services/api && .venv/bin/python -m pytest t.py", files, exists), "cd services/api && .venv/bin/python -m pytest t.py");
|
|
218
|
+
assert.equal(venvPythonRewrite("cd services/api && python -m pytest t.py", files, () => false), "cd services/api && python -m pytest t.py");
|
|
219
|
+
});
|
|
220
|
+
it("venvPythonRewrite cd prefix and nearest manifest", () => {
|
|
221
|
+
assert.equal(venvPythonRewrite("cd services/api && python -m pytest tests/x.py -q", files, exists), "cd services/api && .venv/bin/python -m pytest tests/x.py -q");
|
|
222
|
+
assert.equal(venvPythonRewrite("python3 -m pytest shared/content/tests/t.py::a", files, exists), "shared/content/.venv/bin/python -m pytest shared/content/tests/t.py::a");
|
|
223
|
+
assert.equal(venvPythonRewrite("cd web && pytest", files, exists), "cd web && pytest");
|
|
224
|
+
});
|
|
225
|
+
});
|
|
@@ -8,11 +8,14 @@
|
|
|
8
8
|
* `{blocked}`, never a throw. The engine never sets a break-glass input and never reruns a deploy while a freeze is set (I26);
|
|
9
9
|
* a run that concluded `success` while live is not the merge sha (or the expected digests) is a failed deploy (I28); no deploy
|
|
10
10
|
* starts without a recorded rollback target (I9). Rationale: devdocs/decisions/5560-release-deploy.md.
|
|
11
|
+
* With forge.yaml `deploy.engine.enabled` (`ctx.config.deployEngine`, #5712) the step records the rollback target as above and then
|
|
12
|
+
* hands over to the stage machine in deploy-stages.mjs; without it nothing below changes.
|
|
11
13
|
*/
|
|
12
14
|
import { fenced } from "./release-fence.mjs";
|
|
13
15
|
import { buildDispatchArgs } from "./release-control.mjs";
|
|
14
16
|
import { INFRA_SIGNATURES } from "./release-flakes.mjs";
|
|
15
17
|
import { verifyStep, verifyConfigured } from "./release-verify.mjs";
|
|
18
|
+
import { engineOn, runStages } from "./deploy-stages.mjs";
|
|
16
19
|
|
|
17
20
|
export const BOUNDS = { pollMs: 10_000, runPollMs: 20_000, defaultStageS: 3600, rerunMax: 2, maxAttempts: 3 };
|
|
18
21
|
const json = (s) => JSON.parse(String(s || "null"));
|
|
@@ -44,7 +47,7 @@ export async function readTarget(io, cmd) {
|
|
|
44
47
|
}
|
|
45
48
|
|
|
46
49
|
/** The freeze variable's value ("" when unset or unreadable-as-absent). A gh failure means unset: `gh variable get` exits non-zero for a missing variable. */
|
|
47
|
-
async function freezeValue(io, repo, name) {
|
|
50
|
+
export async function freezeValue(io, repo, name) {
|
|
48
51
|
if (!name) return "";
|
|
49
52
|
try { return String(await io.gh(["variable", "get", name, "--repo", repo])).trim(); } catch { return ""; }
|
|
50
53
|
}
|
|
@@ -145,12 +148,14 @@ const stageS = (d) => (typeof d.stage_timeout_s === "number" ? d.stage_timeout_s
|
|
|
145
148
|
/** @returns {Promise<{skipped: true}|{live: true, merge, run, reruns}|{blocked: true, reason, hold?}|{stopped: true, why}>} */
|
|
146
149
|
export async function deployStep(ctx) {
|
|
147
150
|
const { io, repo, state } = ctx;
|
|
148
|
-
const
|
|
149
|
-
|
|
151
|
+
const engine = engineOn(ctx.config.deployEngine); // #5712: the stage machine; off = everything below as before
|
|
152
|
+
const d = engine ? { live_release_command: ctx.config.deployEngine.live_release_command, ...(ctx.config.deploy ?? {}) } : ctx.config.deploy;
|
|
153
|
+
if (!engine && state.deploy?.engine) return { ...blocked("this release is being deployed by the deploy engine, which is not enabled here; resume it on a host whose forge.yaml has deploy.engine.enabled (the workflow pipeline is never started over a staged deploy)"), hold: { kind: "deploy-engine", label: "needs-agent" } };
|
|
154
|
+
if (!engine && (!d?.pipelines || !Object.keys(d.pipelines).length)) return { skipped: true };
|
|
150
155
|
const b = { ...BOUNDS, ...(ctx.config.deployBounds ?? {}) };
|
|
151
|
-
const pipe = d.pipelines[ctx.config.deployPipeline ?? "full"] ?? Object.values(d.pipelines)[0];
|
|
152
|
-
if (!pipe?.workflow) return blocked("deploy.pipelines has no workflow for this release");
|
|
153
|
-
let sha = state.steps["post-merge"]?.result?.merge ?? null;
|
|
156
|
+
const pipe = d.pipelines?.[ctx.config.deployPipeline ?? "full"] ?? Object.values(d.pipelines ?? {})[0];
|
|
157
|
+
if (!engine && !pipe?.workflow) return blocked("deploy.pipelines has no workflow for this release");
|
|
158
|
+
let sha = (engine ? ctx.config.deploySha : null) ?? state.steps["post-merge"]?.result?.merge ?? null;
|
|
154
159
|
if (!sha) {
|
|
155
160
|
const pr = state.steps["release-pr"]?.result?.pr;
|
|
156
161
|
const v = json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "state,mergeCommit"]));
|
|
@@ -171,6 +176,7 @@ export async function deployStep(ctx) {
|
|
|
171
176
|
st.target = target; st.expected = expected; st.merge = sha; st.freezeBefore = await freezeValue(io, repo, d.freeze_variable); st.phase = "DEPLOYING";
|
|
172
177
|
ctx.save();
|
|
173
178
|
}
|
|
179
|
+
if (engine) return runStages(ctx, sha, d);
|
|
174
180
|
|
|
175
181
|
await reconcile(ctx, d, pipe, sha);
|
|
176
182
|
if (st.phase !== "LIVE_CHECKED" && st.phase !== "LIVE") {
|
|
@@ -99,6 +99,22 @@ export function repeatedFlakes(flakes, cfg, now = Date.now()) {
|
|
|
99
99
|
return [...groups.values()].filter((g) => g.count >= cfg.quarantineAfter);
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
+
/**
|
|
103
|
+
* Quarantine report for the test engine (#5710): the targets `repeatedFlakes` finds, each still run. `mode` `report`
|
|
104
|
+
* (default) keeps every one blocking; `non-blocking` is the repo's opt-in, and never applies to an unskippable class
|
|
105
|
+
* (as a check name, or as a path segment of the test file); `off` reports nothing.
|
|
106
|
+
* @returns {{target, check, test, count, evidence, blocking: boolean, why: string}[]}
|
|
107
|
+
*/
|
|
108
|
+
export function quarantineReport(flakes, { mode = "report", quarantineAfter = 3, windowDays = 14, unskippable = UNSKIPPABLE_CLASSES } = {}, now = Date.now()) {
|
|
109
|
+
if (mode === "off") return [];
|
|
110
|
+
return repeatedFlakes(flakes, { quarantineAfter, windowDays }, now).map((g) => {
|
|
111
|
+
const locked = isUnskippable(g.target, unskippable) || unskippable.some((c) => String(g.test ?? "").split("/").includes(c));
|
|
112
|
+
const blocking = mode !== "non-blocking" || locked;
|
|
113
|
+
const why = locked ? "unskippable class: stays blocking" : blocking ? "report only: still blocking" : "non-blocking by the repo's opt-in: still run";
|
|
114
|
+
return { ...g, blocking, why };
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
102
118
|
const markerFor = (target) => `<!-- ${FLAKE_MARKER} target=${target} -->`;
|
|
103
119
|
|
|
104
120
|
/** The open `flake` issue of `target`, else a new one (label `flake`, evidence). @returns {{issue, created}|null} null for an unskippable target. */
|
|
@@ -114,3 +114,18 @@ describe("release flakes (#5568)", () => {
|
|
|
114
114
|
assert.deepEqual(none, { reran: [], skipped: [] }); // no ci.rerun_budget_min: no rerun
|
|
115
115
|
});
|
|
116
116
|
});
|
|
117
|
+
|
|
118
|
+
describe("quarantineReport (#5710)", async () => {
|
|
119
|
+
const { quarantineReport, flakeEntry: fe } = await import("./release-flakes.mjs");
|
|
120
|
+
const now = Date.parse("2026-11-15T00:00:00Z");
|
|
121
|
+
const flips = (check, test, n) => Array.from({ length: n }, (_, i) => fe({ check, test, kind: "flip", sha: `s${i}`, runIds: [i], at: new Date(now - i * 3_600_000).toISOString() }));
|
|
122
|
+
it("reports repeated flakes as quarantined and still blocking by default", () => {
|
|
123
|
+
const q = quarantineReport([...flips("tests", "t/a.test.js", 3), ...flips("tests", "t/b.test.js", 2)], {}, now);
|
|
124
|
+
assert.deepEqual(q.map((x) => [x.target, x.count, x.blocking]), [["tests:t/a.test.js", 3, true]]);
|
|
125
|
+
});
|
|
126
|
+
it("non-blocking is opt-in and never reaches an unskippable class; off is empty", () => {
|
|
127
|
+
const all = [...flips("tests", "t/a.test.js", 3), ...flips("migration:up", null, 3), ...flips("tests", "suite/backup-restore/test_x.py", 3)];
|
|
128
|
+
assert.deepEqual(quarantineReport(all, { mode: "non-blocking" }, now).map((x) => x.blocking), [false, true, true]);
|
|
129
|
+
assert.deepEqual(quarantineReport(all, { mode: "off" }, now), []);
|
|
130
|
+
});
|
|
131
|
+
});
|