Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions docs/design/affected-checks.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,38 @@ 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 `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.
7 changes: 7 additions & 0 deletions packages/diffci-cli/src/client/agent-selection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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",
Expand Down
17 changes: 15 additions & 2 deletions packages/diffci-cli/src/client/failure-baseline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.)
Expand Down Expand Up @@ -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> = {}): 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);
Expand Down
48 changes: 44 additions & 4 deletions packages/diffci-cli/src/client/gate-checks.ts
Original file line number Diff line number Diff line change
@@ -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. */
Expand Down Expand Up @@ -85,6 +86,21 @@ 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 {
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
Expand Down Expand Up @@ -136,10 +152,18 @@ 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<typeof discoverPythonChecks> = discoverPythonChecks;
// 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) {
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) => {
Expand All @@ -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
Expand All @@ -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);
Expand Down
97 changes: 97 additions & 0 deletions packages/diffci-cli/src/client/python-session-files.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { closeSync, constants, fstatSync, lstatSync, mkdtempSync, openSync, readdirSync, readSync, realpathSync, rmSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
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 {
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 {
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))));
}

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<T>(command: string, run: (env?: Record<string, string>) => 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 }); }
}
5 changes: 3 additions & 2 deletions packages/diffci-cli/src/client/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading