From 5c49a9c77606240586c6629d007e1a3cd6db5a32 Mon Sep 17 00:00:00 2001 From: Emmanuel Mawulolo Tagbor Date: Thu, 26 Nov 2026 09:25:26 +0000 Subject: [PATCH 1/3] Recognize explicit tox environments and nox sessions in Python workflow checks Signed-off-by: Emmanuel Mawulolo Tagbor --- docs/design/affected-checks.md | 23 ++++ .../diffci-cli/src/client/agent-selection.ts | 7 + .../diffci-cli/src/client/failure-baseline.ts | 17 ++- packages/diffci-cli/src/client/gate-checks.ts | 48 ++++++- .../src/client/python-session-files.ts | 94 ++++++++++++++ packages/diffci-cli/src/client/verify.ts | 5 +- .../tests/client/gate-checks.test.ts | 9 ++ .../tests/client/python-session-files.test.ts | 93 ++++++++++++++ .../client/verify-check-baseline.test.ts | 18 +++ release-files.json | 4 + src/planner/nox-sessions.ts | 48 +++++++ src/planner/python-checks.ts | 121 +++++++++++++++--- src/planner/tox-environments.ts | 80 ++++++++++++ tests/planner/python-checks.test.ts | 109 ++++++++++++++++ 14 files changed, 647 insertions(+), 29 deletions(-) create mode 100644 packages/diffci-cli/src/client/python-session-files.ts create mode 100644 packages/diffci-cli/tests/client/python-session-files.test.ts create mode 100644 src/planner/nox-sessions.ts create mode 100644 src/planner/tox-environments.ts diff --git a/docs/design/affected-checks.md b/docs/design/affected-checks.md index 44ac40f9..9941784c 100644 --- a/docs/design/affected-checks.md +++ b/docs/design/affected-checks.md @@ -116,3 +116,26 @@ Anything not read with certainty adds nothing. A Python-only check (a direct cal recipe only calls Python tools, directly or through a repository script) is skipped when no Python file, Python configuration, the Makefile or one of its scripts, or a workflow changed. Every other check runs as written. The CLI skips a check whose program is not installed and says so: CI still runs it. + +### Named tox environments and nox sessions + +A single root-level Actions command such as `tox -e lint,type` or `nox -s lint types` can contribute +one check. Discovery reads the root `tox.ini` or `noxfile.py` as text. Verification runs the original +command when every selected name resolves and every command in its body is understood. + +- Tox environments must skip installing the project and explicitly allow the external check tools. + A named section can inherit commands from `[testenv]`. +- Nox sessions use `@nox.session(python=False)` or `@nox.session(venv_backend="none")`. The complete + module must consist of `import nox` and literal session definitions using only `session.run(...)`. +- Supported commands are `ruff format --check`, `ruff check --no-fix --no-fix-only` and + `mypy --config-file= src` with literal paths. The empty mypy config disables config-driven plugins + and report writers. Ruff accepts `--isolated`. Without it, Ruff can check extra file extensions, so + its session runs on any change. Even isolated checks run on ignore-file changes and when Git cannot + rule out symlinked inputs. + +An ordinary `actions/checkout` step or another supported session may precede the command. Earlier +setup scripts or custom actions could change the runner environment or generate a different configuration. +Those cases, conditional steps, changed working directories, environment overrides, dependencies, hooks and +dynamic declarations leave the session to CI. The CLI also leaves tox to CI on Windows, where it +cannot establish which user configuration the runner will load. Existing test selection and full-suite +fallback apply independently of these checks. diff --git a/packages/diffci-cli/src/client/agent-selection.ts b/packages/diffci-cli/src/client/agent-selection.ts index 6816fd24..74e168a5 100644 --- a/packages/diffci-cli/src/client/agent-selection.ts +++ b/packages/diffci-cli/src/client/agent-selection.ts @@ -3,6 +3,7 @@ import { readFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { observe } from "./observe.js"; import { plannedChecks } from "./gate-checks.js"; +import { canHandOffNox } from "./python-session-files.js"; import { hookCommand } from "./hook.js"; import { detectPackageManager } from "./install.js"; import { createIsolatedWorktree } from "./isolated-worktree.js"; @@ -62,6 +63,12 @@ export async function agentSelection(repoInput: string) { } const ready = unchanged && (!before.changed || Boolean(command)); const planned = ready && before.changed ? plannedChecks(repoPath, { baseSha: before.baseSha, headSha: before.commitSha }) : []; + for (const check of planned) { + if (check.decision !== "SKIP" && check.command.startsWith("nox -s ") && !canHandOffNox(repoPath)) { + check.decision = "SKIP"; + check.reason = "a bare Nox invocation could load cached bytecode; diffci verify isolates its Python cache"; + } + } const checks = planned.filter((check) => check.decision !== "SKIP"); return { schema: "diffci.agent-selection.v1", scope: "working-tree", diff --git a/packages/diffci-cli/src/client/failure-baseline.ts b/packages/diffci-cli/src/client/failure-baseline.ts index 9cbb702d..903cda0b 100644 --- a/packages/diffci-cli/src/client/failure-baseline.ts +++ b/packages/diffci-cli/src/client/failure-baseline.ts @@ -4,6 +4,7 @@ import { tmpdir } from "node:os"; import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path"; import { measureCommands } from "./command-batches.js"; +import { isPythonSession, readPythonSessionFile, withSessionEnvironment } from "./python-session-files.js"; /** * Did this change introduce the failures, or were they already there? (2026-10-21.) @@ -127,10 +128,22 @@ export interface CheckBaseline { base_execution?: { exit_code: number | null; wall_ms: number; timed_out: boolean }; } -export function checkAtBaseline(input: { repoPath: string; baseSha: string; headSha: string; command: string; timeoutMs: number }): CheckBaseline { +export function checkAtBaseline(input: { + repoPath: string; baseSha: string; headSha: string; command: string; timeoutMs: number; + canRunSession?: (directory: string, command: string) => boolean; +}): CheckBaseline { const report = (status: CheckBaseline["status"], reason: string, extra: Partial = {}): CheckBaseline => ({ status, base_sha: input.baseSha, reason, ...extra }); const run = withBaseTree(input, (directory): CheckBaseline => { - const execution = measureCommands([input.command], { cwd: directory, timeoutMs: input.timeoutMs, tailBytes: 0 }); + if (isPythonSession(input.command)) { + if (!input.canRunSession?.(directory, input.command)) return report("unknown", "the workflow session could not be confirmed at the base commit"); + const file = input.command.startsWith("tox ") ? "tox.ini" : "noxfile.py"; + const baseFile = readPythonSessionFile(directory, file); + if (!baseFile || readPythonSessionFile(input.repoPath, file) !== baseFile) { + return report("unknown", "the workflow session configuration differs between the base and head"); + } + } + const execution = withSessionEnvironment(input.command, (env) => measureCommands([input.command], { cwd: directory, timeoutMs: input.timeoutMs, tailBytes: 0, env })); + if (!execution) return report("unknown", "a private Python bytecode cache could not be prepared for the base run"); const baseExecution = { exit_code: execution.exitCode, wall_ms: execution.wallMs, timed_out: execution.timedOut }; if (execution.timedOut) return report("unknown", "the base run timed out", { base_execution: baseExecution }); const killed = killedReason(execution); diff --git a/packages/diffci-cli/src/client/gate-checks.ts b/packages/diffci-cli/src/client/gate-checks.ts index 9854ff63..7e397a01 100644 --- a/packages/diffci-cli/src/client/gate-checks.ts +++ b/packages/diffci-cli/src/client/gate-checks.ts @@ -1,10 +1,11 @@ import { execFileSync } from "node:child_process"; -import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; +import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from "node:fs"; import { join } from "node:path"; import { narrowGateChecks, type ChangedPath } from "@diffci.com/core/planner/check-narrowing"; import { discoverGateChecks, workflowGateScripts, type GateCheckKind } from "@diffci.com/core/planner/pipeline-steps"; import { discoverPythonChecks, narrowPythonChecks, type WorkflowFile } from "@diffci.com/core/planner/python-checks"; import type { CheckBaseline } from "./failure-baseline.js"; +import { isPythonSession, readPythonSessionFile, withSessionEnvironment } from "./python-session-files.js"; import { measureCommand } from "./verify-savings.js"; /** One leaf of the repository's gate (`npm run check`), as an agent or verify runs it. */ @@ -85,6 +86,13 @@ function readRepositoryFile(repoPath: string, path: string): string | undefined try { return readFileSync(join(repoPath, path), "utf8"); } catch { return undefined; } } +function treesHaveNoLinks(repoPath: string, change: CheckChange): boolean { + // Symlinks can redirect an input and gitlinks hide the submodule's files. + try { + return [change.baseSha, change.headSha].every((ref) => !/(?:^|\0)(?:120000|160000) /.test(git(repoPath, ["ls-tree", "-r", "-z", ref]))); + } catch { return false; } +} + /** * The checks the repository's gate runs besides its tests (2026-10-29, docs/design/pipeline-impact.md). * Agents ran the tests DiffCI selected and then failed `npm run check` after push; these are the rest of @@ -136,10 +144,26 @@ function packageChecks(repoPath: string, change: CheckChange | undefined, option * program is not installed here is skipped with that reason rather than failed: CI still runs it. */ function pythonChecks(repoPath: string, change: CheckChange | undefined): PlannedCheck[] { - let checks = discoverPythonChecks(workflowFiles(repoPath), (file) => readRepositoryFile(repoPath, file)); + const read = (file: string) => readRepositoryFile(repoPath, file); + // The package's previous Core pin uses only the Makefile reader and discovers no sessions. + const discover: (files: WorkflowFile[], readFile: typeof read, readSession: typeof read) => ReturnType = discoverPythonChecks; + let checks = discover(workflowFiles(repoPath), read, (file) => readPythonSessionFile(repoPath, file)); + // GitHub workflows are files in the repository. A link, including a linked + // parent directory, cannot establish that the workflow declares this session. + checks = checks.filter((check) => { + if (!isPythonSession(check.command)) return true; + try { + return lstatSync(join(repoPath, ".github")).isDirectory() + && lstatSync(join(repoPath, ".github/workflows")).isDirectory() + && lstatSync(join(repoPath, check.script)).isFile(); + } catch { return false; } + }); if (checks.length === 0) return []; if (change) { - try { checks = narrowPythonChecks(checks, changedPaths(repoPath, change)); } + // Older Core releases accept only the first two arguments and discover no sessions. + const narrow: (found: typeof checks, changes: ChangedPath[], regular: () => boolean) => typeof checks = narrowPythonChecks; + let regular: boolean | undefined; + try { checks = narrow(checks, changedPaths(repoPath, change), () => regular ??= treesHaveNoLinks(repoPath, change)); } catch { /* The change could not be read: every check runs as discovered. */ } } return checks.map((check) => { @@ -155,6 +179,14 @@ function pythonChecks(repoPath: string, change: CheckChange | undefined): Planne }); } +/** An earlier gate check, or a different commit in a baseline export, can + * change what a session name runs. Read its actual workflow and config again. */ +export function canRunPythonSession(repoPath: string, command: string): boolean { + if (!isPythonSession(command)) return true; + try { return pythonChecks(repoPath, undefined).some((check) => check.command === command && check.decision === "RUN"); } + catch { return false; } +} + /** Runs checks in order and stops at the first failure, as the gate's `&&` chain would. SKIP checks * are recorded as skipped and not run. `baseline` reruns a failed check at the base commit; one that * fails there too is recorded in `preexisting` and the run goes on, so a check that was already red @@ -177,7 +209,15 @@ export function runChecks( results.push({ ...check, status: "not_run" }); continue; } - const measurement = measureCommand(check.command, { ...options, timeoutMs: remaining }); + if (!canRunPythonSession(options.cwd, check.command)) { + results.push({ ...check, decision: "SKIP", status: "skipped", reason: "the workflow session could not be confirmed before execution; CI runs it" }); + continue; + } + const measurement = withSessionEnvironment(check.command, (env) => measureCommand(check.command, { ...options, env, timeoutMs: remaining })); + if (!measurement) { + results.push({ ...check, decision: "SKIP", status: "skipped", reason: "a private Python bytecode cache could not be prepared; CI runs this session" }); + continue; + } const status = measurement.timedOut ? "timed_out" : measurement.exitCode === 0 && measurement.signal === null ? "passed" : "failed"; const result: CheckResult = { ...check, status, exit_code: measurement.exitCode, wall_ms: measurement.wallMs }; results.push(result); diff --git a/packages/diffci-cli/src/client/python-session-files.ts b/packages/diffci-cli/src/client/python-session-files.ts new file mode 100644 index 00000000..2a0e4504 --- /dev/null +++ b/packages/diffci-cli/src/client/python-session-files.ts @@ -0,0 +1,94 @@ +import { closeSync, constants, fstatSync, lstatSync, mkdtempSync, openSync, readdirSync, readSync, realpathSync, rmSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; +import { delimiter, dirname, isAbsolute, join } from "node:path"; + +/** Absent, readable text, or an entry we could not verify. */ +function readInput(path: string): string | null | undefined { + let fd: number | undefined; + try { + const entry = lstatSync(path, { throwIfNoEntry: false }); + if (!entry) return undefined; + if (!entry.isFile() || entry.size > 64 * 1024) return null; + fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW); + const opened = fstatSync(fd); + if (!opened.isFile() || opened.dev !== entry.dev || opened.ino !== entry.ino || opened.size !== entry.size) return null; + const bytes = Buffer.alloc(entry.size + 1); + return readSync(fd, bytes, 0, bytes.length, 0) === entry.size ? bytes.subarray(0, entry.size).toString("utf8") : null; + } catch { + return null; + } finally { + if (fd !== undefined) closeSync(fd); + } +} + +function absent(path: string): boolean { + try { return lstatSync(path, { throwIfNoEntry: false }) === undefined; } catch { return false; } +} + +function pathIsUnambiguous(repoPath: string, env: NodeJS.ProcessEnv): boolean { + const path = env.PATH ?? env.Path; + if (path !== undefined && path.split(delimiter).some((dir) => !isAbsolute(dir))) return false; + if (process.platform !== "win32") return true; + // cmd.exe and Windows program lookup can search the current directory before PATH. + const extensions = (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";"); + return extensions.every((extension) => /^\.[a-z\d]+$/i.test(extension)) + && ["nox", "ruff", "mypy"].every((tool) => ["", ...extensions].every((ext) => absent(join(repoPath, tool + ext)))); +} + +function toxConfigIsLocal(repoPath: string, env: NodeJS.ProcessEnv): boolean { + // tox 4 reads CLI defaults from its user config. tox 3 searches pyproject.toml + // before tox.ini, including parent directories. A quoted TOML key may use escapes. + const home = env.HOME || homedir(); + // On Windows, platformdirs looks up a known folder through the registry or + // shell. LOCALAPPDATA alone does not establish the path used by Python. + if (process.platform === "win32" || !isAbsolute(home) || (env.XDG_CONFIG_HOME && !isAbsolute(env.XDG_CONFIG_HOME))) return false; + const configDirs = [join(home, ".config"), join(home, "Library/Application Support")]; + if (env.XDG_CONFIG_HOME) configDirs.push(env.XDG_CONFIG_HOME); + if (configDirs.some((dir) => !absent(join(dir, "tox/config.ini")))) return false; + let dir: string; + try { dir = realpathSync(repoPath); } catch { return false; } + for (; ; dir = dirname(dir)) { + const source = readInput(join(dir, "pyproject.toml")); + if (source === null || (source !== undefined && /legacy_tox_ini|\\/.test(source))) return false; + if (dirname(dir) === dir) return true; + } +} + +/** Return a marker for an inline plugin, including an unreadable or dangling link. + * Discovery only needs to know whether its absence can be established. */ +export function readPythonSessionFile(repoPath: string, file: string, env: NodeJS.ProcessEnv = process.env): string | undefined { + if (file === "toxfile.py" || file === "☣.py") return absent(join(repoPath, file)) ? undefined : ""; + const tox = file === "tox.ini"; + if (!tox && file !== "noxfile.py") return undefined; + // These override the leaf check's write destination or its module search paths. + if (["RUFF_OUTPUT_FILE", "RUFF_CACHE_DIR", "MYPY_CACHE_DIR", "MYPYPATH", "MYPY_TEST_PREFIX"].some((key) => env[key] !== undefined)) return undefined; + if (Object.keys(env).some((key) => tox ? /^TOX/i.test(key) : /^NOX/i.test(key) && key.toUpperCase() !== "NOX_CURRENT_SESSION")) return undefined; + const source = readInput(join(repoPath, file)); + if (!source || !pathIsUnambiguous(repoPath, env) || (tox && !toxConfigIsLocal(repoPath, env))) return undefined; + return source; +} + +export function isPythonSession(command: string): boolean { + return /^(?:tox -e |nox -s )/.test(command); +} + +/** A caller handing the bare Nox command to another process cannot isolate + * its Python cache. Only hand it out when there is no cached noxfile to load. */ +export function canHandOffNox(repoPath: string): boolean { + if (process.env.PYTHONPYCACHEPREFIX || !absent(join(repoPath, "noxfile.pyc"))) return false; + const cache = join(repoPath, "__pycache__"); + try { + const entry = lstatSync(cache, { throwIfNoEntry: false }); + return !entry || (entry.isDirectory() && !readdirSync(cache).some((name) => /^noxfile\..*\.pyc$/i.test(name))); + } catch { return false; } +} + +/** Nox loads Python source through the interpreter's bytecode cache. Use the + * source we just checked even if a previous checkout left a cached noxfile. */ +export function withSessionEnvironment(command: string, run: (env?: Record) => T): T | undefined { + if (!command.startsWith("nox -s ")) return run(); + let cache: string; + try { cache = mkdtempSync(join(realpathSync(tmpdir()), "diffci-nox-cache-")); } catch { return undefined; } + try { return run({ PYTHONPYCACHEPREFIX: cache, PYTHONDONTWRITEBYTECODE: "1" }); } + finally { rmSync(cache, { recursive: true, force: true }); } +} diff --git a/packages/diffci-cli/src/client/verify.ts b/packages/diffci-cli/src/client/verify.ts index cb3cca63..35bdd883 100644 --- a/packages/diffci-cli/src/client/verify.ts +++ b/packages/diffci-cli/src/client/verify.ts @@ -11,7 +11,7 @@ import { coverageAdditions, readCoverageMap } from "./coverage-map.js"; import { checkAtBaseline, compareWithBaseline, type CheckBaseline, type FailureBaseline } from "./failure-baseline.js"; import { collectEnforcementContext, evaluateEnforcement, type EnforcementDecision } from "./enforce-policy.js"; import { inferFullCommand, inferPlannedCommands, inferSelectedCommand, inferSelectedCommands } from "./full-command.js"; -import { plannedChecks, runChecks, type CheckResult, type PlannedCheck } from "./gate-checks.js"; +import { canRunPythonSession, plannedChecks, runChecks, type CheckResult, type PlannedCheck } from "./gate-checks.js"; import { makeGitRunner, observe, separateProjectReason } from "./observe.js"; import { redactPath, type ObservationCommitRange, type ObservationReport, type SelectionReason } from "./report.js"; import { createIsolatedWorktree } from "./isolated-worktree.js"; @@ -414,7 +414,8 @@ async function executeWithPolicy( // With no time left the base rerun would get a 0ms limit, which means none: report it as unknown instead. ? (check: { command: string }, remainingMs: number): CheckBaseline => remainingMs <= 0 ? { status: "unknown", base_sha: checkBase, reason: "the time limit ran out before the base run" } - : checkAtBaseline({ repoPath: options.repoPath, baseSha: checkBase, headSha: checkHead, command: check.command, timeoutMs: remainingMs }) + : checkAtBaseline({ repoPath: options.repoPath, baseSha: checkBase, headSha: checkHead, command: check.command, + timeoutMs: remainingMs, canRunSession: canRunPythonSession }) : undefined; const checkRun = options.skipChecks ? undefined : runChecks(planned, { cwd: options.repoPath, timeoutMs: options.timeoutMs, tailBytes: options.tailBytes, baseline: checkBaseline }); const checks = checkRun?.results.length ? checkRun.results : undefined; diff --git a/packages/diffci-cli/tests/client/gate-checks.test.ts b/packages/diffci-cli/tests/client/gate-checks.test.ts index 090484f9..ccb9ac5a 100644 --- a/packages/diffci-cli/tests/client/gate-checks.test.ts +++ b/packages/diffci-cli/tests/client/gate-checks.test.ts @@ -79,6 +79,15 @@ test("checks stop at the first failure", () => { } finally { rmSync(dir, { recursive: true, force: true }); } }); +test("verify declines a previously planned session when its workflow is gone", (t) => { + const dir = repo({}); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const run = runChecks([{ id: "lint", command: "nox -s lint", kind: "lint", decision: "RUN", reason: "planned" }], + { cwd: dir, timeoutMs: 60_000, tailBytes: 0 }); + assert.equal(run.results[0].status, "skipped"); + assert.match(run.results[0].reason, /could not be confirmed/); +}); + test("the MCP instruction puts the gate checks before the tests", () => { const plan = { status: "planned", selection: "selected", tests_selected: 3, tests_available: 580, diff --git a/packages/diffci-cli/tests/client/python-session-files.test.ts b/packages/diffci-cli/tests/client/python-session-files.test.ts new file mode 100644 index 00000000..4a8467c9 --- /dev/null +++ b/packages/diffci-cli/tests/client/python-session-files.test.ts @@ -0,0 +1,93 @@ +import assert from "node:assert/strict"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { delimiter, join } from "node:path"; +import { test } from "node:test"; +import { canHandOffNox, readPythonSessionFile, withSessionEnvironment } from "../../src/client/python-session-files.js"; + +test("session discovery reads bounded regular files and declines runner overrides", (t) => { + const repo = mkdtempSync(join(tmpdir(), "diffci-session-inputs-")); + t.after(() => rmSync(repo, { recursive: true, force: true })); + const config = join(repo, "noxfile.py"); + const read = (env: NodeJS.ProcessEnv = {}) => readPythonSessionFile(repo, "noxfile.py", env); + writeFileSync(config, "import nox\n"); + assert.equal(read({ NOX_CURRENT_SESSION: "lint" }), "import nox\n"); + assert.equal(read({ NOXSESSION: "lint" }), undefined); + assert.equal(read({ NOX_DEFAULT_VENV_BACKEND: "none" }), undefined); + assert.equal(read({ PATH: `.${delimiter}${repo}` }), undefined); + assert.equal(read({ PATH: `${repo}${delimiter}` }), undefined); + if (process.platform === "win32") { + writeFileSync(join(repo, "ruff.cmd"), ""); + assert.equal(read({ PATH: repo, PATHEXT: ".CMD" }), undefined); + rmSync(join(repo, "ruff.cmd")); + } + for (const key of ["RUFF_OUTPUT_FILE", "RUFF_CACHE_DIR", "MYPY_CACHE_DIR", "MYPYPATH", "MYPY_TEST_PREFIX"]) { + assert.equal(read({ [key]: "somewhere" }), undefined); + } + assert.equal(read({ RUFF_OUTPUT_FORMAT: "concise", MYPY_FORCE_COLOR: "0" }), "import nox\n"); + if (process.getuid && process.getuid() !== 0) { + chmodSync(config, 0o000); + try { assert.equal(read(), undefined); } finally { chmodSync(config, 0o600); } + } + writeFileSync(config, " ".repeat(64 * 1024 + 1)); + assert.equal(read(), undefined); + rmSync(config); + mkdirSync(config); + assert.equal(read(), undefined); + if (process.platform !== "win32") { + rmSync(config, { recursive: true }); + writeFileSync(join(repo, "other.py"), "import nox\n"); + symlinkSync("other.py", config); + assert.equal(read(), undefined); + for (const plugin of ["toxfile.py", "☣.py"]) { + assert.equal(readPythonSessionFile(repo, plugin), undefined); + symlinkSync("missing.py", join(repo, plugin)); + assert.equal(readPythonSessionFile(repo, plugin), ""); + } + } +}); + +test("tox accepts ordinary pyprojects and declines possible alternative configuration", { skip: process.platform === "win32" }, (t) => { + const parent = mkdtempSync(join(tmpdir(), "diffci-tox-context-")); + t.after(() => rmSync(parent, { recursive: true, force: true })); + const repo = join(parent, "project"); + mkdirSync(repo); + writeFileSync(join(repo, "tox.ini"), "[tox]\n"); + writeFileSync(join(repo, "pyproject.toml"), '[project]\nname = "sample"\n'); + const env = { HOME: parent, XDG_CONFIG_HOME: join(parent, "prefs") }; + assert.equal(readPythonSessionFile(repo, "tox.ini", env), "[tox]\n"); + assert.equal(readPythonSessionFile(repo, "tox.ini", { ...env, TOX_OVERRIDE: "any" }), undefined); + writeFileSync(join(parent, "pyproject.toml"), '[tool.tox]\nlegacy_tox_ini = "[tox]"\n'); + assert.equal(readPythonSessionFile(repo, "tox.ini", env), undefined); + rmSync(join(parent, "pyproject.toml")); + mkdirSync(join(env.XDG_CONFIG_HOME, "tox"), { recursive: true }); + writeFileSync(join(env.XDG_CONFIG_HOME, "tox/config.ini"), "[tox]\n"); + assert.equal(readPythonSessionFile(repo, "tox.ini", env), undefined); +}); + +test("Nox uses a fresh private bytecode cache for each execution and removes it afterwards", () => { + const execute = () => withSessionEnvironment("nox -s lint", (env) => { + assert.ok(env); + assert.equal(env.PYTHONDONTWRITEBYTECODE, "1"); + assert.deepEqual(readdirSync(env.PYTHONPYCACHEPREFIX), []); + return env.PYTHONPYCACHEPREFIX; + }); + const one = execute(); + const two = execute(); + assert.ok(one && two); + assert.notEqual(one, two); + assert.equal(existsSync(one), false); + assert.equal(existsSync(two), false); + assert.equal(withSessionEnvironment("make lint", (env) => env), undefined); +}); + +test("a bare Nox command is handed off only when the checkout has no cached session", (t) => { + const repo = mkdtempSync(join(tmpdir(), "diffci-nox-handoff-")); + t.after(() => rmSync(repo, { recursive: true, force: true })); + const cache = join(repo, "__pycache__"); + mkdirSync(cache); + writeFileSync(join(cache, "other.cpython-312.pyc"), ""); + if (!process.env.PYTHONPYCACHEPREFIX) assert.equal(canHandOffNox(repo), true); + writeFileSync(join(cache, "noxfile.cpython-312.pyc"), ""); + assert.equal(canHandOffNox(repo), false); +}); diff --git a/packages/diffci-cli/tests/client/verify-check-baseline.test.ts b/packages/diffci-cli/tests/client/verify-check-baseline.test.ts index b946e748..2e68d246 100644 --- a/packages/diffci-cli/tests/client/verify-check-baseline.test.ts +++ b/packages/diffci-cli/tests/client/verify-check-baseline.test.ts @@ -38,6 +38,24 @@ function verify(repo: string, base: string, head: string, baselineOnFailure: boo return verifyRange({ repoPath: repo, env: {}, version: "test", timeoutMs: 60_000, tailBytes: 4_000, baseOverride: base, headOverride: head, baselineOnFailure }); } +test("a session the exported base does not declare has no baseline execution", () => { + const { repo, base, head } = fixture("false", 4); + try { + let inspected = false; + const result = checkAtBaseline({ repoPath: repo, baseSha: base, headSha: head, command: "nox -s lint", timeoutMs: 60_000, + canRunSession(directory, command) { + assert.notEqual(directory, repo); + assert.equal(command, "nox -s lint"); + inspected = existsSync(join(directory, "package.json")); + return false; + }, + }); + assert.equal(inspected, true); + assert.equal(result.status, "unknown"); + assert.equal(result.base_execution, undefined); + } finally { rmSync(repo, { recursive: true, force: true }); } +}); + test("a check already failing at the base does not hide a test the change broke", async () => { const { repo, base, head } = fixture("true", 2); try { diff --git a/release-files.json b/release-files.json index 20168dbf..a1bd995d 100644 --- a/release-files.json +++ b/release-files.json @@ -101,6 +101,7 @@ "packages/diffci-cli/src/client/failure-baseline.ts", "packages/diffci-cli/src/client/full-command.ts", "packages/diffci-cli/src/client/gate-checks.ts", + "packages/diffci-cli/src/client/python-session-files.ts", "packages/diffci-cli/src/client/gate.ts", "packages/diffci-cli/src/client/job-summary.ts", "packages/diffci-cli/src/client/install.ts", @@ -165,6 +166,7 @@ "src/measurement.ts", "src/planner/explain.ts", "src/planner/check-narrowing.ts", + "src/planner/nox-sessions.ts", "src/planner/path-baseline.ts", "src/planner/pipeline-steps.ts", "src/planner/python-checks.ts", @@ -173,6 +175,7 @@ "src/planner/script-reads.ts", "src/planner/task-registry.ts", "src/planner/test-command.ts", + "src/planner/tox-environments.ts", "src/planner/type-program.ts", "src/planner/types.ts", "src/repo/adapters/go-test.ts", @@ -415,6 +418,7 @@ "packages/diffci-cli/src/client/test-results.ts", "packages/diffci-cli/tests/client/test-results.test.ts", "packages/diffci-cli/tests/client/python-full-command.test.ts", + "packages/diffci-cli/tests/client/python-session-files.test.ts", "packages/diffci-cli/src/client/test-ranking.ts", "packages/diffci-cli/tests/client/test-ranking.test.ts", "packages/diffci-cli/src/client/test-shards.ts", diff --git a/src/planner/nox-sessions.ts b/src/planner/nox-sessions.ts new file mode 100644 index 00000000..2a74ad60 --- /dev/null +++ b/src/planner/nox-sessions.ts @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: MIT + +const SESSION = /^@nox\.session\( *(?:python *= *False|venv_backend *= *(?:"none"|'none')) *\)$/; +const DEFINITION = /^def ([a-z][a-z0-9_]*)\(session(?:: nox\.Session)?\)(?: -> None)?:$/; +const RESERVED_NAME = /^(?:and|as|assert|async|await|break|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|nonlocal|nox|not|or|pass|raise|return|try|while|with|yield)$/; +const RUN = /^ session\.run\((.*)\)$/; +const WORD = /^(["'])([\w./@:=+-]+)\1$/; + +/** Read the entire root noxfile as literal session declarations. Each session uses + * the current environment and can only call session.run with separately quoted words. */ +export function noxCheckCommands(source: string, sessions: readonly string[]): string[] | undefined { + if (!sessions.length || source.length > 64 * 1024) return undefined; + const text = source.replace(/\r\n/g, "\n"); + // Python encoding cookies and Nox script metadata can change how the file is loaded. + if (/[^\x20-\x7e\n]/.test(text) || /^ *#.*(?:coding[:=]|\/\/\/)/m.test(text)) return undefined; + const lines = text.split("\n").map((line) => line.trimEnd()).filter((line) => line && !line.trimStart().startsWith("#")); + if (lines[0] !== "import nox") return undefined; + + const declarations = new Map(); + let i = 1; + while (i < lines.length) { + if (!SESSION.test(lines[i++]!)) return undefined; + const name = DEFINITION.exec(lines[i++] ?? "")?.[1]; + if (!name || RESERVED_NAME.test(name) || declarations.has(name)) return undefined; + const commands: string[] = []; + while (i < lines.length && lines[i]!.startsWith(" ")) { + const args = RUN.exec(lines[i++]!)?.[1]; + if (!args) return undefined; + const words: string[] = []; + for (const arg of args.split(",")) { + const word = WORD.exec(arg.trim())?.[2]; + if (!word) return undefined; + words.push(word); + } + commands.push(words.join(" ")); + } + if (!commands.length) return undefined; + declarations.set(name, commands); + } + + const selected: string[] = []; + for (const name of sessions) { + const commands = declarations.get(name); + if (!commands) return undefined; + selected.push(...commands); + } + return selected; +} diff --git a/src/planner/python-checks.ts b/src/planner/python-checks.ts index d2288a4e..19f3e37d 100644 --- a/src/planner/python-checks.ts +++ b/src/planner/python-checks.ts @@ -16,7 +16,10 @@ * - a direct `mypy`, `pyright`, `basedpyright`, `pyrefly check`, `ruff check` or `ruff format --check` * call, optionally behind `uv run`, `poetry run`, `pdm run`, `hatch run`, `pipenv run` or `python -m`, * whose every argument is a plain word and none rewrites files or writes output. Before `uv run`, - * --directory and --project take repository-relative paths; --offline and --no-progress take no value. + * --directory and --project take repository-relative paths; --offline and --no-progress take no value; + * - a root-level `tox -e lint,type` or `nox -s lint types` selecting literal environments or sessions. + * Read the configuration as text. Keep the original runner command only if every selected command + * is a supported read-only check. Unknown options, setup, hooks or execution contexts add nothing. * * FAILING CLOSED. Here that means adding nothing: anything not read with certainty is left out, which * is the behaviour before this module. Steps in disabled jobs, steps with expressions in their working @@ -34,7 +37,9 @@ import { posix } from "node:path"; import { parse } from "yaml"; import type { ChangedPath } from "./check-narrowing.js"; +import { noxCheckCommands } from "./nox-sessions.js"; import type { GateCheck } from "./pipeline-steps.js"; +import { toxCheckCommands } from "./tox-environments.js"; export interface PythonCheck extends GateCheck { /** True when the check only runs Python tools, so a change without Python files cannot fail it. */ @@ -72,9 +77,9 @@ function workingDirectory(...levels: unknown[]): string | undefined { for (const level of levels) { const dir = (level as { "working-directory"?: unknown } | undefined)?.["working-directory"]; if (dir === undefined) continue; - return typeof dir === "string" ? normalizeDir(dir) : undefined; + return typeof dir === "string" ? dir : undefined; } - return ""; + return "."; } function disabled(condition: unknown): boolean { @@ -193,30 +198,100 @@ function makeKind(target: string, recipe: readonly string[]): GateCheck["kind"] return "script"; } -/** - * The Python checks CI workflows run, in workflow order. Reads the workflows and, through `read`, the - * Makefiles and scripts they name. Every check starts as RUN. - */ -export function discoverPythonChecks(workflows: readonly WorkflowFile[], read: (path: string) => string | undefined): PythonCheck[] { +// These workflow forms select named declarations in order. A bare runner selects defaults and +// additional arguments can select different sessions, override configuration or invoke another tool. +const NAMED_ENV = /^[a-z][a-z0-9_-]*$/; +const PYTHON_TARGET = /^(?:\.|(?:\.\/)?(?:[\w][\w-]*\/)*[\w][\w-]*(?:\.(?:py|pyi|ipynb))?)$/; + +// Ruff's fix and fix-only settings are independent. Mypy configuration can load plugins +// and request output files. Require the workflow's own arguments to rule out those effects. +const SESSION_TOOLS = [ + { prefix: "ruff check ", required: ["--no-fix", "--no-fix-only"], ruff: true }, + { prefix: "ruff format ", required: ["--check"], ruff: true }, + { prefix: "mypy ", required: ["--config-file="], ruff: false }, +]; + +function sessionCheck(line: string, workflowPath: string, read: (path: string) => string | undefined): PythonCheck | undefined { + const command = line.replace(/[ \t]+/g, " "); + const tox = command.startsWith("tox -e "); + if (!tox && !command.startsWith("nox -s ")) return undefined; + const names = command.slice(7).split(tox ? "," : " "); + if (names.some((name) => !NAMED_ENV.test(name)) || new Set(names).size !== names.length) return undefined; + const config = tox ? "tox.ini" : "noxfile.py"; + const source = read(config); + if (!source || source.length > 64 * 1024) return undefined; + if (tox && (read("toxfile.py") !== undefined || read("☣.py") !== undefined)) return undefined; + const commands = tox ? toxCheckCommands(source, names) : noxCheckCommands(source, names); + if (!commands?.length) return undefined; + const kinds = new Set(); + const triggers = new Set([config]); + let pythonOnly = true; + for (const leaf of commands) { + const call = directToolCall(leaf); + if (!call) return undefined; + const tool = SESSION_TOOLS.find(({ prefix }) => call.command.startsWith(prefix)); + if (!tool) return undefined; + const args = call.command.slice(tool.prefix.length).split(" "); + if (!tool.required.every((flag) => args.includes(flag))) return undefined; + // Ruff configuration may select extra file extensions or extend another arbitrary config. + // Its check-only forms are still safe to run there, but only an isolated call can narrow. + if (tool.ruff && !args.includes("--isolated")) pythonOnly = false; + const paths = args.filter((word) => !tool.required.includes(word) && !(tool.ruff && word === "--isolated")); + if ((!tool.ruff && !paths.length) || !paths.every((path) => PYTHON_TARGET.test(path))) return undefined; + for (const path of paths) triggers.add(posix.normalize(path)); + kinds.add(call.kind); + } + const kind = kinds.size === 1 ? [...kinds][0]! : "script"; + return { id: command, command, kind, script: workflowPath, runsScript: false, pythonOnly, + triggers: [...triggers], decision: "RUN", reason: `run by CI workflow ${workflowPath}` }; +} + +type ReadText = (path: string) => string | undefined; + +/** Discover checks in workflow order. The CLI supplies a separate reader for session configuration + * so its file and environment checks do not change how Makefiles and their scripts are read. */ +export function discoverPythonChecks(workflows: readonly WorkflowFile[], read: ReadText, readSession: ReadText = read): PythonCheck[] { const checks: PythonCheck[] = []; const seen = new Set(); for (const workflow of workflows) { - let doc: { jobs?: unknown; defaults?: { run?: unknown } } | null; + let doc: { jobs?: unknown; env?: unknown; defaults?: { run?: { shell?: unknown } } } | null; try { doc = parse(workflow.text) as typeof doc; } catch { continue; } if (!doc?.jobs || typeof doc.jobs !== "object") continue; for (const job of Object.values(doc.jobs as Record)) { if (!job || typeof job !== "object") continue; - const { steps, if: condition, defaults } = job as { steps?: unknown; if?: unknown; defaults?: { run?: unknown } }; + const { steps, if: condition, defaults } = job as { steps?: unknown; if?: unknown; defaults?: { run?: { shell?: unknown } } }; if (disabled(condition) || !Array.isArray(steps)) continue; + const plainSessionJob = condition === undefined && doc.env === undefined && !("env" in job) + && !("container" in job) && !("services" in job) && !("strategy" in job) && !("continue-on-error" in job) + && defaults?.run?.shell === undefined && doc.defaults?.run?.shell === undefined; + let unknownSessionContext = false; for (const step of steps) { - const { run, if: stepCondition } = (step ?? {}) as { run?: unknown; if?: unknown }; - if (typeof run !== "string" || disabled(stepCondition)) continue; - const dir = workingDirectory(step, defaults?.run, doc.defaults?.run); + const { run, if: stepCondition, env, shell, uses, with: inputs, "continue-on-error": optional } = (step ?? {}) as { + run?: unknown; if?: unknown; env?: unknown; shell?: unknown; uses?: unknown; with?: unknown; "continue-on-error"?: unknown; + }; + if (disabled(stepCondition)) continue; + // An action can change the checkout, runner defaults or environment for later steps. + if (uses !== undefined && !(typeof uses === "string" && /^actions\/checkout@(?:v\d+|[a-f0-9]{40})$/.test(uses) + && inputs === undefined && env === undefined && stepCondition === undefined && optional === undefined)) unknownSessionContext = true; + if (typeof run !== "string") continue; + const canReadSession = !unknownSessionContext && plainSessionJob && stepCondition === undefined + && uses === undefined && env === undefined && shell === undefined && optional === undefined; + // A preceding script could have generated configuration or updated the runner environment. + // Only a session whose complete command list we can read preserves this context. + unknownSessionContext = true; + const rawDir = workingDirectory(step, defaults?.run, doc.defaults?.run); + const dir = rawDir === undefined ? undefined : normalizeDir(rawDir); if (dir === undefined) continue; - const lines = run.replace(/\r\n/g, "\n").split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#")); + const block = run.replace(/\r\n/g, "\n"); + const lines = block.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#")); if (lines.some((line) => CONTEXT_CHANGE.test(line) || line.includes("${{"))) continue; for (const line of lines) { - const check = makeCheck(line, dir, workflow.path, read) ?? (dir === "" ? toolCheck(line, workflow.path) : undefined); + let check = makeCheck(line, dir, workflow.path, read) ?? (dir === "" ? toolCheck(line, workflow.path) : undefined); + if (!check && canReadSession && /^(?:tox|nox)\s/.test(line) && (rawDir === "." || rawDir === "./") + && lines.length === 1 && !block.includes("${{") && !/[^\t\n\x20-\x7e]/.test(block)) { + check = sessionCheck(line, workflow.path, readSession); + if (check) unknownSessionContext = false; + } if (!check || seen.has(check.command)) continue; seen.add(check.command); checks.push(check); @@ -264,13 +339,17 @@ function pythonRelevant(path: string): boolean { return PY_FILE.test(path) || PY_CONFIG.test(posix.basename(path)) || path.startsWith(".github/workflows/"); } -/** Skips Python-only checks for a change with no Python file, Python configuration or trigger in it. */ -export function narrowPythonChecks(checks: readonly PythonCheck[], changes: readonly ChangedPath[]): PythonCheck[] { +/** Skip unrelated changes. A session can read the target of a Python symlink under another + * extension, so it can skip only when the caller has ruled out links in both Git trees. */ +export function narrowPythonChecks(checks: readonly PythonCheck[], changes: readonly ChangedPath[], sessionInputsAreRegular?: () => boolean): PythonCheck[] { return checks.map((check) => { if (!check.pythonOnly) return { ...check, reason: `${check.reason}; not read as Python-only, runs as written` }; - const hit = changes.find((change) => pythonRelevant(change.path) || check.triggers.includes(change.path)); - return hit - ? { ...check, reason: `${check.reason}; ${hit.path} changed` } - : { ...check, decision: "SKIP", reason: `${check.reason}; no changed Python file or Python configuration` }; + // Even isolated Ruff consults nested ignore files when selecting inputs from a directory. + const session = /^(?:tox -e |nox -s )/.test(check.command); + const hit = changes.find(({ path }) => pythonRelevant(path) || check.triggers.includes(path) + || (session && /(?:^|\/)\.(?:gitignore|ignore)$/.test(path))); + if (hit) return { ...check, reason: `${check.reason}; ${hit.path} changed` }; + if (session && !sessionInputsAreRegular?.()) return { ...check, decision: "RUN", reason: `${check.reason}; cannot rule out symlinked Python inputs` }; + return { ...check, decision: "SKIP", reason: `${check.reason}; no changed Python file or Python configuration` }; }); } diff --git a/src/planner/tox-environments.ts b/src/planner/tox-environments.ts new file mode 100644 index 00000000..d843d2cb --- /dev/null +++ b/src/planner/tox-environments.ts @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: MIT +/** The root tox.ini subset used for workflow checks. Only literal names and explicitly + * declared environments are supported. The caller classifies every returned command. */ + +type Section = Map; + +const HEADER = /^\[(tox|testenv(?::[a-z][a-z0-9_-]*)?)\]$/; +const ENV_LIST = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*(?:[ \t]*,[ \t]*[a-zA-Z0-9][a-zA-Z0-9_.-]*)*$/; +const EXTERNAL = /^(?:mypy|pyright|basedpyright|pyrefly|ruff)$/; + +function readToxIni(source: string): Map | undefined { + const text = source.replace(/\r\n/g, "\n"); + if (source.length > 64 * 1024 || /[^\t\n\x20-\x7e]/.test(text)) return undefined; + const sections = new Map(); + let name = ""; + let section: Section | undefined; + let values: string[] | undefined; + for (const raw of text.split("\n")) { + const line = raw.trim(); + if (!line || /^[#;]/.test(line)) continue; + // Substitutions, escaping, inline comments and control characters have separate + // meanings in tox's INI loader. Leave them to CI. + if (/[{}\\#;]/.test(raw)) return undefined; + if (/^[ \t]/.test(raw)) { + if (!values) return undefined; + values.push(line); + continue; + } + const header = HEADER.exec(line); + if (header) { + name = header[1]!; + if (sections.has(name)) return undefined; + section = new Map(); + sections.set(name, section); + values = undefined; + continue; + } + const option = /^([a-z_]+)[ \t]*=[ \t]*(.*)$/.exec(line); + if (!option || !section) return undefined; + const key = option[1] === "envlist" ? "env_list" : option[1]!; + const supported = name === "tox" + ? key === "env_list" || key === "skipsdist" + : ["commands", "skip_install", "allowlist_externals", "description"].includes(key); + if (!supported || section.has(key)) return undefined; + values = option[2] ? [option[2]] : []; + section.set(key, values); + } + for (const section of sections.values()) { + if (section.get("env_list")?.some((line) => !ENV_LIST.test(line))) return undefined; + if (section.get("allowlist_externals")?.some((line) => !EXTERNAL.test(line))) return undefined; + if (section.has("skip_install") && section.get("skip_install")!.join("\n") !== "true") return undefined; + if (section.has("skipsdist") && section.get("skipsdist")!.join("\n") !== "true") return undefined; + } + return sections.has("tox") ? sections : undefined; +} + +/** Read commands without running tox, provisioning dependencies or installing the project. + * A selected environment inherits individual options from [testenv]. It must explicitly + * skip installation and allow the named external check program. */ +export function toxCheckCommands(source: string, environments: readonly string[]): string[] | undefined { + const sections = readToxIni(source); + if (!sections || !environments.length || new Set(environments).size !== environments.length) return undefined; + const skipsPackage = sections.get("tox")!.has("skipsdist"); + const base = sections.get("testenv"); + const commands: string[] = []; + for (const name of environments) { + const env = sections.get(`testenv:${name}`); + if (!env || !(skipsPackage || env.has("skip_install") || base?.has("skip_install"))) return undefined; + const allowed = env.get("allowlist_externals") ?? base?.get("allowlist_externals"); + const lines = env.get("commands") ?? base?.get("commands"); + if (!lines?.length || !allowed) return undefined; + // Inherited command lists can otherwise expand many times across named environments. + if (commands.length + lines.length > 256) return undefined; + for (const line of lines) { + if (!allowed.includes(line.split(/[ \t]/, 1)[0]!)) return undefined; + commands.push(line); + } + } + return commands; +} diff --git a/tests/planner/python-checks.test.ts b/tests/planner/python-checks.test.ts index 7e38f1e9..1aa32a07 100644 --- a/tests/planner/python-checks.test.ts +++ b/tests/planner/python-checks.test.ts @@ -195,3 +195,112 @@ describe("narrowPythonChecks", () => { } }); }); + +describe("tox and nox workflow checks", () => { + // mykrok/mykrok's CI selects lint,type in tox.ini. googleads/google-ads-mcp's CI calls + // nox -s lint with venv_backend="none". The fixtures use preinstalled, read-only tools. + const tox = [ + "[tox]", "envlist = lint,type", "[testenv]", "skip_install = true", + "allowlist_externals =", " ruff", " mypy", + "[testenv:lint]", "commands = ruff check --no-fix --no-fix-only --isolated .", + "[testenv:type]", "commands = mypy --config-file= src", + ].join("\n"); + const nox = [ + "import nox", '@nox.session(venv_backend="none")', "def lint(session: nox.Session) -> None:", + ' session.run("ruff", "format", "--check", "--isolated", ".")', + "@nox.session(python=False)", "def types(session):", " session.run('mypy', '--config-file=', 'src')", + ].join("\n"); + const files = { "tox.ini": tox, "noxfile.py": nox }; + const run = (line: string, config: Record = files) => + discoverPythonChecks(workflow("jobs:\n checks:\n steps:\n - run: " + line), reader(config)); + + it("preserves each explicit selector and classifies the commands it actually selects", () => { + for (const [command, kind] of [ + ["tox -e lint", "lint"], ["tox -e type", "typecheck"], ["tox -e type,lint", "script"], + ["nox -s lint", "format"], ["nox -s types", "typecheck"], ["nox -s types lint", "script"], + ] as const) { + const checks = run(command); + assert.deepEqual(checks.map((c) => [c.command, c.kind, c.pythonOnly]), [[command, kind, true]]); + for (const [path, decision] of [ + ["src/app.py", "RUN"], ["uv.toml", "RUN"], [command.startsWith("tox") ? "tox.ini" : "noxfile.py", "RUN"], + ["src/.gitignore", "RUN"], [".github/workflows/check.yml", "RUN"], ["README.md", "SKIP"], + ] as const) { + assert.equal(narrowPythonChecks(checks, [{ path, status: "modified" }], () => true)[0]?.decision, decision, path); + } + } + }); + + it("accounts for runner configuration when narrowing", () => { + const [check] = run("nox -s lint", { "noxfile.py": nox.replace('"--isolated", ', "") }); + assert.equal(check?.pythonOnly, false); + assert.equal(narrowPythonChecks([check!], [{ path: "docs/guide.txt", status: "modified" }])[0]?.decision, "RUN"); + assert.deepEqual(run("tox -e type", { "tox.ini": tox.replace("mypy --config-file= src", "mypy src") }), []); + assert.deepEqual(run("tox -e lint", { "tox.ini": tox.replace(" --no-fix-only", "") }), []); + const isolated = run("tox -e lint"); + const changes = [{ path: "input.txt", status: "modified" as const }]; + assert.equal(narrowPythonChecks(isolated, changes)[0]?.decision, "RUN"); + assert.equal(narrowPythonChecks(isolated, changes, () => false)[0]?.decision, "RUN"); + }); + + it("requires the entire selection, explicit names and the root execution context", () => { + for (const line of ["tox", "tox -e lint,missing", "tox -e lint,lint", "tox -e lint -- --fix", + "nox", "nox -s missing lint", "nox -s lint lint", "nox -s lint --extra", "nox -s ${{ matrix.session }}"]) { + assert.deepEqual(run(line), [], line); + } + for (const field of ["working-directory: subdir", "shell: custom", "if: github.ref", "env: {MODE: alternate}", "continue-on-error: true"]) { + assert.deepEqual(discoverPythonChecks(workflow("jobs:\n a:\n steps:\n - " + field + "\n run: tox -e type"), reader(files)), []); + } + for (const text of [ + "env: {MODE: alternate}\njobs:\n a:\n steps:\n - run: nox -s lint", + "jobs:\n a:\n defaults:\n run:\n shell: custom\n steps:\n - run: nox -s lint", + "jobs:\n a:\n env: {MODE: local}\n steps:\n - run: tox -e lint", + "jobs:\n a:\n steps:\n - run: |\n prepare\n tox -e lint", + "jobs:\n a:\n steps:\n - run: \"\u00a0nox -s lint\"", + "jobs:\n a:\n steps:\n - run: echo MODE=local >> $GITHUB_ENV\n - run: tox -e lint", + "jobs:\n a:\n steps:\n - run: prepare_config\n - run: nox -s lint", + "jobs:\n a:\n steps:\n - uses: actions/checkout@v4\n with: {path: alternate}\n - run: tox -e lint", + "jobs:\n a:\n steps:\n - run: |\n # ${{ inputs.detail }}\n nox -s lint", + ]) assert.deepEqual(discoverPythonChecks(workflow(text), reader(files)), []); + const checkout = "jobs:\n a:\n steps:\n - uses: actions/checkout@v4\n - run: tox -e type\n - run: nox -s lint"; + assert.deepEqual(discoverPythonChecks(workflow(checkout), reader(files)).map((c) => c.command), ["tox -e type", "nox -s lint"]); + for (const dir of [".", "./", ".\\", "\\.", "", "sub/.."]) { + const text = `defaults:\n run:\n working-directory: '${dir}'\njobs:\n a:\n steps:\n - run: nox -s lint`; + assert.equal(discoverPythonChecks(workflow(text), reader(files)).length, dir === "." || dir === "./" ? 1 : 0, dir); + } + }); + + it("declines ambiguous tox configurations, hooks and mixed commands", () => { + for (const config of [ + tox.replace("skip_install = true", "skip_install = false"), tox.replace("skip_install = true", "deps = mypy"), + tox.replace("[testenv:type]", "[testenv:type]\ncommands_pre = prepare"), + tox.replace("[testenv:type]", "[testenv:type]\ncommands_post = finish"), + tox.replace("[testenv:type]", "[testenv:type]\nchangedir = src"), + tox.replace("[testenv:type]", "[testenv:type]\nsetenv = MODE=local"), + tox.replace("envlist =", "requires = plugin\nenvlist ="), tox.replace("mypy --config-file= src", "mypy {posargs:src}"), + tox.replace(" mypy", " *"), tox + "\n[testenv:lint]\ncommands = ruff format .", + tox + "\n ruff format .", tox.replace("src", "../other"), tox.replace("src", "result.txt"), + ]) assert.deepEqual(run("tox -e lint,type", { "tox.ini": config }), [], config); + for (const plugin of ["toxfile.py", "☣.py"]) assert.deepEqual(run("tox -e type", { ...files, [plugin]: "" }), []); + assert.deepEqual(run("tox -e type", {}), []); + }); + + it("keeps Make script reads independent of session configuration checks", () => { + const text = "jobs:\n a:\n steps:\n - run: tox -e type\n - run: make check"; + const repo = { ...files, Makefile: "check:\n\t./toxfile.py\n", "toxfile.py": "#!/usr/bin/env python3\nimport mypy\n" }; + const checks = discoverPythonChecks(workflow(text), reader(repo), reader({ ...files, "toxfile.py": "" })); + assert.deepEqual(checks.map((c) => [c.command, c.pythonOnly, c.triggers]), [["make check", true, ["Makefile", "toxfile.py"]]]); + assert.equal(narrowPythonChecks(checks, [{ path: "README.md", status: "modified" }])[0]?.decision, "SKIP"); + }); + + it("reads only literal Nox declarations and calls, including the rest of the module", () => { + const call = ' session.run("ruff", "format", "--check", "--isolated", ".")'; + for (const config of [ + nox.replace('venv_backend="none"', ""), nox.replace(call, call + '\n session.run("ruff", "format", ".")'), + nox.replace(call, ' session.install("ruff")\n' + call), nox.replace(call, ' session.chdir("src")\n' + call), + nox.replace(call, ' session.notify("types")\n' + call), nox.replace(call, ' session.run("ruff", "format --check")'), + nox.replace(call, ' session.run("ruff", *session.posargs)'), nox.replace("def types(session):", "def lint(session):"), + nox + "\nconfigure_sessions()", "# coding: latin-1\n" + nox, "# /// script\n# dependencies = ['ruff']\n# ///\n" + nox, + ]) assert.deepEqual(run("nox -s lint", { "noxfile.py": config }), [], config); + assert.deepEqual(run("nox -s lint", {}), []); + }); +}); From 2a29c2710d2365e3ca63cc9894e0f65a2d424cdd Mon Sep 17 00:00:00 2001 From: Emmanuel Mawulolo Tagbor Date: Thu, 26 Nov 2026 10:10:03 +0000 Subject: [PATCH 2/3] Keep Python sessions declared by regular workflows Signed-off-by: Emmanuel Mawulolo Tagbor --- packages/diffci-cli/src/client/gate-checks.ts | 22 +++++++++---------- src/planner/python-checks.ts | 4 +++- tests/planner/python-checks.test.ts | 15 +++++++++++++ 3 files changed, 29 insertions(+), 12 deletions(-) diff --git a/packages/diffci-cli/src/client/gate-checks.ts b/packages/diffci-cli/src/client/gate-checks.ts index 7e397a01..046cb310 100644 --- a/packages/diffci-cli/src/client/gate-checks.ts +++ b/packages/diffci-cli/src/client/gate-checks.ts @@ -86,6 +86,14 @@ function readRepositoryFile(repoPath: string, path: string): string | undefined try { return readFileSync(join(repoPath, path), "utf8"); } catch { return undefined; } } +function regularWorkflow(repoPath: string, path: string): boolean { + try { + return lstatSync(join(repoPath, ".github")).isDirectory() + && lstatSync(join(repoPath, ".github/workflows")).isDirectory() + && lstatSync(join(repoPath, path)).isFile(); + } catch { return false; } +} + function treesHaveNoLinks(repoPath: string, change: CheckChange): boolean { // Symlinks can redirect an input and gitlinks hide the submodule's files. try { @@ -147,17 +155,9 @@ function pythonChecks(repoPath: string, change: CheckChange | undefined): Planne const read = (file: string) => readRepositoryFile(repoPath, file); // The package's previous Core pin uses only the Makefile reader and discovers no sessions. const discover: (files: WorkflowFile[], readFile: typeof read, readSession: typeof read) => ReturnType = discoverPythonChecks; - let checks = discover(workflowFiles(repoPath), read, (file) => readPythonSessionFile(repoPath, file)); - // GitHub workflows are files in the repository. A link, including a linked - // parent directory, cannot establish that the workflow declares this session. - checks = checks.filter((check) => { - if (!isPythonSession(check.command)) return true; - try { - return lstatSync(join(repoPath, ".github")).isDirectory() - && lstatSync(join(repoPath, ".github/workflows")).isDirectory() - && lstatSync(join(repoPath, check.script)).isFile(); - } catch { return false; } - }); + // Exclude linked session declarations before Core keeps the first occurrence of each command. + const files = workflowFiles(repoPath).map((file) => ({ ...file, canDeclareSessions: regularWorkflow(repoPath, file.path) })); + let checks = discover(files, read, (file) => readPythonSessionFile(repoPath, file)); if (checks.length === 0) return []; if (change) { // Older Core releases accept only the first two arguments and discover no sessions. diff --git a/src/planner/python-checks.ts b/src/planner/python-checks.ts index 19f3e37d..d84c2093 100644 --- a/src/planner/python-checks.ts +++ b/src/planner/python-checks.ts @@ -52,6 +52,8 @@ export interface WorkflowFile { /** Repository-relative path, such as `.github/workflows/style.yml`. */ path: string; text: string; + /** False when the CLI cannot establish that this workflow is a regular file under regular directories. */ + canDeclareSessions?: boolean; } const MAKE_LINE = /^make(?:\s+-C\s+([\w./-]+))?\s+([\w.-]+)$/; @@ -261,7 +263,7 @@ export function discoverPythonChecks(workflows: readonly WorkflowFile[], read: R if (!job || typeof job !== "object") continue; const { steps, if: condition, defaults } = job as { steps?: unknown; if?: unknown; defaults?: { run?: { shell?: unknown } } }; if (disabled(condition) || !Array.isArray(steps)) continue; - const plainSessionJob = condition === undefined && doc.env === undefined && !("env" in job) + const plainSessionJob = workflow.canDeclareSessions !== false && condition === undefined && doc.env === undefined && !("env" in job) && !("container" in job) && !("services" in job) && !("strategy" in job) && !("continue-on-error" in job) && defaults?.run?.shell === undefined && doc.defaults?.run?.shell === undefined; let unknownSessionContext = false; diff --git a/tests/planner/python-checks.test.ts b/tests/planner/python-checks.test.ts index 1aa32a07..9ab0f2fb 100644 --- a/tests/planner/python-checks.test.ts +++ b/tests/planner/python-checks.test.ts @@ -214,6 +214,21 @@ describe("tox and nox workflow checks", () => { const run = (line: string, config: Record = files) => discoverPythonChecks(workflow("jobs:\n checks:\n steps:\n - run: " + line), reader(config)); + it("keeps the regular workflow's session when a linked workflow declares the same command", () => { + for (const command of ["tox -e lint,type", "nox -s lint"]) { + const text = `jobs:\n checks:\n steps:\n - run: ${command}\n - run: uv run mypy src`; + const linked = { path: ".github/workflows/alias.yml", text, canDeclareSessions: false }; + const regular = { path: ".github/workflows/checks.yml", text }; + for (const workflows of [[linked, regular], [regular, linked]]) { + const checks = discoverPythonChecks(workflows, reader(files)); + assert.deepEqual(checks.filter((c) => c.command === command).map((c) => c.script), [regular.path]); + assert.deepEqual(checks.filter((c) => c.command === "uv run mypy src").map((c) => c.script), [workflows[0]!.path]); + } + const linkedOnly = discoverPythonChecks([linked], reader(files), () => assert.fail("linked workflow requested a session config")); + assert.deepEqual(linkedOnly.map((c) => c.command), ["uv run mypy src"]); + } + }); + it("preserves each explicit selector and classifies the commands it actually selects", () => { for (const [command, kind] of [ ["tox -e lint", "lint"], ["tox -e type", "typecheck"], ["tox -e type,lint", "script"], From 963aeba6b056d7198d74210814f1028945248d62 Mon Sep 17 00:00:00 2001 From: Emmanuel Mawulolo Tagbor Date: Thu, 26 Nov 2026 13:09:40 +0000 Subject: [PATCH 3/3] Handle Windows PATH padding when planning Nox sessions Signed-off-by: Emmanuel Mawulolo Tagbor --- docs/design/affected-checks.md | 18 ++++++++++++--- .../src/client/python-session-files.ts | 15 +++++++----- .../tests/client/python-session-files.test.ts | 23 ++++++++++++++----- tests/planner/python-checks.test.ts | 17 ++++++++++++++ 4 files changed, 58 insertions(+), 15 deletions(-) diff --git a/docs/design/affected-checks.md b/docs/design/affected-checks.md index 9941784c..89ac46a7 100644 --- a/docs/design/affected-checks.md +++ b/docs/design/affected-checks.md @@ -133,9 +133,21 @@ command when every selected name resolves and every command in its body is under its session runs on any change. Even isolated checks run on ignore-file changes and when Git cannot rule out symlinked inputs. -An ordinary `actions/checkout` step or another supported session may precede the command. Earlier -setup scripts or custom actions could change the runner environment or generate a different configuration. -Those cases, conditional steps, changed working directories, environment overrides, dependencies, hooks and +An `actions/checkout` step with a major tag or full commit SHA and no inputs, or another supported +session, may precede the command. Setup actions and install steps can change the runner environment +or generate a different configuration. Even checkout with `fetch-depth` or a tag such as `v4.2.2` +currently leaves the session to CI. + +The synthetic fixtures model the named invocations in two public workflows. Both real jobs stay in CI. + +- mykrok's `misc` job sets up Python and installs `tox tox-uv` before `tox -e lint,type`. + Its selected environments also install the project's `.[devel]` dependencies. + [Workflow](https://github.com/mykrok/mykrok/blob/dbf46845f0dca094f060a094dccee6eea33ce03f/.github/workflows/ci.yml#L45-L59) · [tox.ini](https://github.com/mykrok/mykrok/blob/dbf46845f0dca094f060a094dccee6eea33ce03f/tox.ini#L17-L25) +- google-ads-mcp's `lint` job sets up Python, upgrades pip and installs `black nox` before + `nox -s lint`. Its session calls a Python helper that builds the Black command at runtime. + [Workflow](https://github.com/googleads/google-ads-mcp/blob/44ca7770519362c8f334875477e1ceb499f8d2dd/.github/workflows/ci.yml#L13-L26) · [noxfile.py](https://github.com/googleads/google-ads-mcp/blob/44ca7770519362c8f334875477e1ceb499f8d2dd/noxfile.py#L42-L71) + +Conditional steps, changed working directories, environment overrides, dependencies, hooks and dynamic declarations leave the session to CI. The CLI also leaves tox to CI on Windows, where it cannot establish which user configuration the runner will load. Existing test selection and full-suite fallback apply independently of these checks. diff --git a/packages/diffci-cli/src/client/python-session-files.ts b/packages/diffci-cli/src/client/python-session-files.ts index 2a0e4504..c1190e98 100644 --- a/packages/diffci-cli/src/client/python-session-files.ts +++ b/packages/diffci-cli/src/client/python-session-files.ts @@ -1,6 +1,6 @@ import { closeSync, constants, fstatSync, lstatSync, mkdtempSync, openSync, readdirSync, readSync, realpathSync, rmSync } from "node:fs"; import { homedir, tmpdir } from "node:os"; -import { delimiter, dirname, isAbsolute, join } from "node:path"; +import { dirname, isAbsolute, join, win32 } from "node:path"; /** Absent, readable text, or an entry we could not verify. */ function readInput(path: string): string | null | undefined { @@ -26,11 +26,14 @@ function absent(path: string): boolean { } function pathIsUnambiguous(repoPath: string, env: NodeJS.ProcessEnv): boolean { - const path = env.PATH ?? env.Path; - if (path !== undefined && path.split(delimiter).some((dir) => !isAbsolute(dir))) return false; - if (process.platform !== "win32") return true; - // cmd.exe and Windows program lookup can search the current directory before PATH. - const extensions = (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";"); + if (process.platform !== "win32") return env.PATH !== undefined && env.PATH.split(":").every(isAbsolute); + + // An empty Windows field can lead Python back to cwd. Require a fully qualified + // search path and check cwd for the shell, the session runner and its leaf tools. + const dirs = (env.PATH ?? env.Path ?? "").split(";").filter(Boolean); + if (!dirs.length || !dirs.every((dir) => win32.isAbsolute(dir) && win32.parse(dir).root.length > 1)) return false; + if (!env.PATHEXT || !["cmd.exe", "cmd.exe.com", "cmd.exe.exe"].every((name) => absent(join(repoPath, name)))) return false; + const extensions = env.PATHEXT.split(";"); return extensions.every((extension) => /^\.[a-z\d]+$/i.test(extension)) && ["nox", "ruff", "mypy"].every((tool) => ["", ...extensions].every((ext) => absent(join(repoPath, tool + ext)))); } diff --git a/packages/diffci-cli/tests/client/python-session-files.test.ts b/packages/diffci-cli/tests/client/python-session-files.test.ts index 4a8467c9..4dcf2047 100644 --- a/packages/diffci-cli/tests/client/python-session-files.test.ts +++ b/packages/diffci-cli/tests/client/python-session-files.test.ts @@ -9,17 +9,28 @@ test("session discovery reads bounded regular files and declines runner override const repo = mkdtempSync(join(tmpdir(), "diffci-session-inputs-")); t.after(() => rmSync(repo, { recursive: true, force: true })); const config = join(repo, "noxfile.py"); - const read = (env: NodeJS.ProcessEnv = {}) => readPythonSessionFile(repo, "noxfile.py", env); + const read = (env: NodeJS.ProcessEnv = {}) => + readPythonSessionFile(repo, "noxfile.py", { PATH: repo, PATHEXT: ".EXE;.CMD", ...env }); writeFileSync(config, "import nox\n"); assert.equal(read({ NOX_CURRENT_SESSION: "lint" }), "import nox\n"); assert.equal(read({ NOXSESSION: "lint" }), undefined); assert.equal(read({ NOX_DEFAULT_VENV_BACKEND: "none" }), undefined); + assert.equal(read({ PATH: undefined }), undefined); + assert.equal(read({ PATH: undefined, Path: repo }), process.platform === "win32" ? "import nox\n" : undefined); assert.equal(read({ PATH: `.${delimiter}${repo}` }), undefined); - assert.equal(read({ PATH: `${repo}${delimiter}` }), undefined); + for (const path of [`${delimiter}${repo}`, `${repo}${delimiter}${delimiter}${repo}`, `${repo}${delimiter}`]) { + assert.equal(read({ PATH: path }), process.platform === "win32" ? "import nox\n" : undefined, path); + } if (process.platform === "win32") { - writeFileSync(join(repo, "ruff.cmd"), ""); - assert.equal(read({ PATH: repo, PATHEXT: ".CMD" }), undefined); - rmSync(join(repo, "ruff.cmd")); + for (const path of ["", ";;", `bin;;${repo}`, `C:bin;${repo}`, `\\bin;${repo}`]) { + assert.equal(read({ PATH: path }), undefined, path); + } + for (const ext of [undefined, "", ".EXE;;.CMD"]) assert.equal(read({ PATH: repo + ";", PATHEXT: ext }), undefined); + for (const name of ["cmd.exe", "cmd.exe.com", "cmd.exe.exe", "nox.exe", "ruff.cmd", "mypy"]) { + writeFileSync(join(repo, name), ""); + assert.equal(read({ PATH: repo + ";" }), undefined, name); + rmSync(join(repo, name)); + } } for (const key of ["RUFF_OUTPUT_FILE", "RUFF_CACHE_DIR", "MYPY_CACHE_DIR", "MYPYPATH", "MYPY_TEST_PREFIX"]) { assert.equal(read({ [key]: "somewhere" }), undefined); @@ -54,7 +65,7 @@ test("tox accepts ordinary pyprojects and declines possible alternative configur mkdirSync(repo); writeFileSync(join(repo, "tox.ini"), "[tox]\n"); writeFileSync(join(repo, "pyproject.toml"), '[project]\nname = "sample"\n'); - const env = { HOME: parent, XDG_CONFIG_HOME: join(parent, "prefs") }; + const env = { HOME: parent, XDG_CONFIG_HOME: join(parent, "prefs"), PATH: repo }; assert.equal(readPythonSessionFile(repo, "tox.ini", env), "[tox]\n"); assert.equal(readPythonSessionFile(repo, "tox.ini", { ...env, TOX_OVERRIDE: "any" }), undefined); writeFileSync(join(parent, "pyproject.toml"), '[tool.tox]\nlegacy_tox_ini = "[tox]"\n'); diff --git a/tests/planner/python-checks.test.ts b/tests/planner/python-checks.test.ts index 9ab0f2fb..109baa4e 100644 --- a/tests/planner/python-checks.test.ts +++ b/tests/planner/python-checks.test.ts @@ -214,6 +214,23 @@ describe("tox and nox workflow checks", () => { const run = (line: string, config: Record = files) => discoverPythonChecks(workflow("jobs:\n checks:\n steps:\n - run: " + line), reader(config)); + it("leaves sessions to CI when their workflow sets up Python and installs tools", () => { + for (const [command, install] of [ + ["tox -e lint,type", "pip install tox tox-uv"], + ["nox -s lint", "python -m pip install --upgrade pip\n pip install black nox"], + ]) { + const checkout = "jobs:\n checks:\n steps:\n - uses: actions/checkout@v4"; + const setup = " - uses: actions/setup-python@v5\n with:\n python-version: '3.12'"; + const installStep = " - run: |\n " + install; + const session = " - run: " + command; + for (const steps of [[setup], [installStep], [setup, installStep]]) { + const text = [checkout, ...steps, session].join("\n"); + assert.deepEqual(discoverPythonChecks(workflow(text), reader(files)), []); + } + assert.deepEqual(discoverPythonChecks(workflow(checkout + "\n" + session), reader(files)).map((c) => c.command), [command]); + } + }); + it("keeps the regular workflow's session when a linked workflow declares the same command", () => { for (const command of ["tox -e lint,type", "nox -s lint"]) { const text = `jobs:\n checks:\n steps:\n - run: ${command}\n - run: uv run mypy src`;