@diffci.com/diffci 0.3.52 → 0.3.54

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.
@@ -1,3 +1,4 @@
1
+ import { type VerificationTreeScope } from "./working-tree.js";
1
2
  /** Cheap change discovery, without building the dependency graph. */
2
3
  export declare function agentChangedFiles(repoInput: string): {
3
4
  schema: string;
@@ -47,9 +48,81 @@ export declare function agentSelection(repoInput: string): Promise<{
47
48
  tests_selected: number;
48
49
  command: string | undefined;
49
50
  }>;
51
+ /** The one command that verifies `scope` in isolation, as `diffci_select_tests` returns it. */
52
+ export declare function scopedVerifyCommand(repoPath: string, scope: VerificationTreeScope, version?: string): string;
53
+ /**
54
+ * The plan for HEAD plus only the staged files, or only the named files (2026-11-17), made in the same
55
+ * temporary worktree `verify --staged` / `--paths` verifies in. Its `command` is that one verify
56
+ * command, which runs the gate checks and the selected tests in isolation: the selected test command
57
+ * itself would run in the shared checkout, where other sessions' files could change its result.
58
+ */
59
+ export declare function agentScopedSelection(repoInput: string, scope: VerificationTreeScope): Promise<{
60
+ status: "blocked" | "planned";
61
+ tests_executed: boolean;
62
+ snapshot: {
63
+ base_sha: string;
64
+ tree_sha: string;
65
+ unchanged: boolean;
66
+ };
67
+ changed_files: string[];
68
+ selection: "none";
69
+ selected_tests: string[];
70
+ tests_available: number;
71
+ tests_selected: number;
72
+ command: undefined;
73
+ checks: never[];
74
+ skipped_checks: never[];
75
+ reason: string;
76
+ fallback_reasons: never[];
77
+ analysis_status: string;
78
+ risk_signals: never[];
79
+ required_ci_authoritative: boolean;
80
+ scope: "paths" | "staged";
81
+ isolation: "temporary-worktree";
82
+ excluded_dirty_files: number;
83
+ excluded_dirty_paths: string[];
84
+ schema: string;
85
+ } | {
86
+ command: string | undefined;
87
+ commands: undefined;
88
+ reason: string;
89
+ worktree_command?: string | undefined;
90
+ status: string;
91
+ snapshot: {
92
+ base_sha: string;
93
+ tree_sha: string;
94
+ unchanged: boolean;
95
+ };
96
+ changed_files: string[];
97
+ scope: "paths" | "staged";
98
+ isolation: "temporary-worktree";
99
+ excluded_dirty_files: number;
100
+ excluded_dirty_paths: string[];
101
+ checks: import("./gate-checks.js").PlannedCheck[];
102
+ skipped_checks: {
103
+ id: string;
104
+ reason: string;
105
+ }[];
106
+ fallback_reasons: string[];
107
+ analysis_status: string;
108
+ analysis_mode: "SELECTIVE" | "FULL" | undefined;
109
+ graph_confidence: string | undefined;
110
+ risk_signals: {
111
+ level: string;
112
+ reason: string;
113
+ }[];
114
+ required_ci_authoritative: boolean;
115
+ schema: string;
116
+ tests_executed: boolean;
117
+ selection: "none" | "full" | "selected";
118
+ selected_tests: string[];
119
+ tests_available: number;
120
+ tests_selected: number;
121
+ }>;
122
+ export type AgentScopedSelectionPlan = Awaited<ReturnType<typeof agentScopedSelection>>;
50
123
  /**
51
124
  * One plain sentence ahead of the JSON, naming the exact command to run (2026-10-28). Agents given only
52
125
  * the JSON plan mostly went on to pick their own test files or run the whole suite; the first line is
53
126
  * what they act on, so it says what to run and nothing else.
54
127
  */
55
- export declare function selectionInstruction(plan: AgentSelectionPlan): string;
128
+ export declare function selectionInstruction(plan: AgentSelectionPlan | AgentScopedSelectionPlan): string;
@@ -1,9 +1,14 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { resolve } from "node:path";
2
+ import { readFileSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
3
4
  import { observe } from "./observe.js";
4
5
  import { plannedChecks } from "./gate-checks.js";
5
- import { executableSelection } from "./verify.js";
6
- import { captureWorkingTreeSnapshot } from "./working-tree.js";
6
+ import { hookCommand } from "./hook.js";
7
+ import { detectPackageManager } from "./install.js";
8
+ import { createIsolatedWorktree } from "./isolated-worktree.js";
9
+ import { requireDiffciPackageIdentity } from "./package-identity.js";
10
+ import { executableSelection, scopedChanges } from "./verify.js";
11
+ import { captureScopedTree, captureWorkingTreeSnapshot } from "./working-tree.js";
7
12
  function changedPaths(repoPath, snapshot) {
8
13
  return execFileSync("git", ["diff", "--name-only", "-z", snapshot.baseSha, snapshot.commitSha], {
9
14
  cwd: repoPath, encoding: "utf8", windowsHide: true,
@@ -76,6 +81,85 @@ export async function agentSelection(repoInput) {
76
81
  required_ci_authoritative: true,
77
82
  };
78
83
  }
84
+ /** How this repository runs DiffCI from a shell: its installed binary, or a pinned npx package. */
85
+ function diffciInvocation(repoPath, version) {
86
+ let declared = false;
87
+ try {
88
+ const manifest = JSON.parse(readFileSync(join(repoPath, "package.json"), "utf8"));
89
+ declared = ["dependencies", "devDependencies", "optionalDependencies"].some((field) => Boolean(manifest[field]?.["@diffci.com/diffci"]));
90
+ }
91
+ catch { /* no package.json: the pinned package below */ }
92
+ if (!declared)
93
+ return hookCommand(undefined, version);
94
+ try {
95
+ return hookCommand(detectPackageManager(repoPath), version);
96
+ }
97
+ catch {
98
+ return hookCommand("npm", version);
99
+ }
100
+ }
101
+ /** A path as one shell word in POSIX shells, cmd.exe and PowerShell. */
102
+ function shellPath(path) {
103
+ return /^[A-Za-z0-9_./@+-]+$/.test(path) ? path : `"${path.replace(/"/g, '\\"')}"`;
104
+ }
105
+ /** The one command that verifies `scope` in isolation, as `diffci_select_tests` returns it. */
106
+ export function scopedVerifyCommand(repoPath, scope, version = requireDiffciPackageIdentity().version) {
107
+ const run = diffciInvocation(repoPath, version);
108
+ return scope.kind === "staged"
109
+ ? `${run} verify --staged --json`
110
+ : `${run} verify --json --paths ${scope.paths.map(shellPath).join(" ")}`;
111
+ }
112
+ /**
113
+ * The plan for HEAD plus only the staged files, or only the named files (2026-11-17), made in the same
114
+ * temporary worktree `verify --staged` / `--paths` verifies in. Its `command` is that one verify
115
+ * command, which runs the gate checks and the selected tests in isolation: the selected test command
116
+ * itself would run in the shared checkout, where other sessions' files could change its result.
117
+ */
118
+ export async function agentScopedSelection(repoInput, scope) {
119
+ const repoPath = resolve(repoInput);
120
+ const { scoped, verified, excluded } = scopedChanges(repoPath, scope);
121
+ const scopeFields = {
122
+ scope: scope.kind,
123
+ isolation: "temporary-worktree",
124
+ excluded_dirty_files: excluded.length,
125
+ excluded_dirty_paths: excluded.slice(0, 50).map((change) => change.path),
126
+ };
127
+ const command = scopedVerifyCommand(repoPath, scope);
128
+ const unplanned = (status, reason) => ({
129
+ schema: "diffci.agent-selection.v1", ...scopeFields, status, tests_executed: false,
130
+ snapshot: { base_sha: scoped.baseSha, tree_sha: scoped.treeSha, unchanged: true },
131
+ changed_files: verified.map((change) => change.path), selection: "none", selected_tests: [],
132
+ tests_available: 0, tests_selected: 0, command: undefined, checks: [], skipped_checks: [], reason,
133
+ fallback_reasons: [], analysis_status: "not_needed", risk_signals: [], required_ci_authoritative: true,
134
+ });
135
+ if (!scoped.changed)
136
+ return unplanned("planned", scope.kind === "staged" ? "nothing is staged: the index matches HEAD" : "the given paths do not differ from HEAD");
137
+ const worktree = createIsolatedWorktree(repoPath, scoped.baseSha, scoped.treeSha);
138
+ if ("error" in worktree)
139
+ return unplanned("blocked", worktree.error);
140
+ let plan;
141
+ try {
142
+ plan = await agentSelection(worktree.path);
143
+ }
144
+ finally {
145
+ worktree.dispose();
146
+ }
147
+ const after = captureScopedTree(repoPath, scope);
148
+ const unchanged = plan.snapshot.unchanged && after.baseSha === scoped.baseSha && after.treeSha === scoped.treeSha;
149
+ const ready = unchanged && plan.status === "planned";
150
+ return {
151
+ ...plan,
152
+ ...scopeFields,
153
+ status: ready ? "planned" : "blocked",
154
+ snapshot: { base_sha: scoped.baseSha, tree_sha: scoped.treeSha, unchanged },
155
+ changed_files: verified.map((change) => change.path),
156
+ // What the verify command runs inside the temporary worktree, for reading, not for running here.
157
+ ...(plan.command ? { worktree_command: plan.command } : {}),
158
+ command: ready ? command : undefined,
159
+ commands: undefined,
160
+ reason: unchanged ? plan.reason : `the ${scope.kind === "staged" ? "index" : "given files"} or HEAD changed during analysis; reanalyze`,
161
+ };
162
+ }
79
163
  /**
80
164
  * One plain sentence ahead of the JSON, naming the exact command to run (2026-10-28). Agents given only
81
165
  * the JSON plan mostly went on to pick their own test files or run the whole suite; the first line is
@@ -89,6 +173,13 @@ export function selectionInstruction(plan) {
89
173
  const scope = plan.selection === "selected"
90
174
  ? `DiffCI selected ${plan.tests_selected} of ${plan.tests_available} test files`
91
175
  : `DiffCI requires the full suite (${plan.reason})`;
176
+ if ("isolation" in plan) {
177
+ // One command: it runs the gate checks and the tests in the temporary worktree, where only the
178
+ // scoped files differ from HEAD.
179
+ const what = plan.scope === "staged" ? "HEAD plus your staged files" : "HEAD plus the given files";
180
+ const excluded = plan.excluded_dirty_files ? ` ${plan.excluded_dirty_files} other changed file(s) in this checkout are excluded and stay at their HEAD version.` : "";
181
+ return `${scope} for ${what}.${excluded} Run exactly:\n${plan.command}\nIt runs the gate checks and those tests in a temporary worktree. Do not run the selected tests in this checkout, substitute your own test files, or run the full suite.`;
182
+ }
92
183
  const testCommands = plan.commands && plan.commands.length > 1 ? plan.commands : [plan.command];
93
184
  const all = [...plan.checks.map((check) => check.command), ...testCommands];
94
185
  const skipped = plan.skipped_checks?.length ? ` ${plan.skipped_checks.length} other gate check(s) are not affected by this change.` : "";
@@ -41,7 +41,7 @@
41
41
  import { execFileSync, spawnSync } from "node:child_process";
42
42
  import { closeSync, constants, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, writeFileSync } from "node:fs";
43
43
  import { tmpdir } from "node:os";
44
- import { basename, dirname, join, resolve } from "node:path";
44
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
45
45
  import { observe, isInsideRepository } from "./observe.js";
46
46
  import { resolveObservationAgent } from "./agent-identity.js";
47
47
  import { inferFullCommand, inferComparableSelectedCommand, inferWorkspaceComparison } from "./full-command.js";
@@ -56,7 +56,7 @@ import { formatJobSummary } from "./job-summary.js";
56
56
  import { configureTelemetry, readTelemetryPreference, recordUsage, telemetryNotice } from "./telemetry.js";
57
57
  import { formatFeedbackPrompt, markFeedbackPromptShown, shouldShowFeedbackPrompt } from "./feedback-prompt.js";
58
58
  import { detectSpecificationConflicts, readSpecificationFile } from "./spec-conflicts.js";
59
- import { formatVerificationSummary, verificationExitCode, verifyChanged, verifyRange } from "./verify.js";
59
+ import { formatVerificationSummary, verificationExitCode, verifyChanged, verifyRange, verifyScoped } from "./verify.js";
60
60
  import { startWatch } from "./watch.js";
61
61
  import { captureWorkingTreeSnapshot } from "./working-tree.js";
62
62
  import { decideStop, HOOK_AGENTS, maxAttempts, parseStopPayload, sessionAttempts, stopRepoPath } from "./agent-stop.js";
@@ -86,6 +86,15 @@ function parseArgs(argv) {
86
86
  }
87
87
  const key = token.slice(2);
88
88
  const next = args[i + 1];
89
+ if (key === "paths") {
90
+ // `--paths a b c` takes every value up to the next flag, and repeats add to it; NUL separates
91
+ // them because no path contains one.
92
+ const values = typeof flags.paths === "string" ? flags.paths.split("\0") : [];
93
+ while (args[i + 1] !== undefined && !args[i + 1].startsWith("--"))
94
+ values.push(args[++i]);
95
+ flags.paths = values.length ? values.join("\0") : true;
96
+ continue;
97
+ }
89
98
  if (next !== undefined && !next.startsWith("--")) {
90
99
  flags[key] = next;
91
100
  i++;
@@ -216,6 +225,12 @@ function defaultReportPath(env) {
216
225
  // Quoting the scoped package keeps the same command valid in POSIX shells, cmd.exe, and
217
226
  // PowerShell, where an unquoted leading `@` is parsed as the splatting operator.
218
227
  const PUBLIC_AGENT_DEFAULT_COMMAND = 'npx "@diffci.com/diffci@latest" verify --changed --json';
228
+ /** The pre-commit form of the agent command: the `diffci:verify:staged` script, or `--staged` in place of `--changed`. */
229
+ function stagedCommand(command) {
230
+ if (/ run diffci:verify$/.test(command))
231
+ return `${command}:staged`;
232
+ return command.replace("--changed", "--staged");
233
+ }
219
234
  function agentInstructions(command) {
220
235
  return `# DiffCI Agent Instructions
221
236
 
@@ -233,6 +248,14 @@ Use it instead of choosing test files yourself and instead of re-running the ful
233
248
  - Do not run the full test suite to be safe. DiffCI already falls back to the full suite when it cannot prove a smaller set is enough, and says why in \`reason\`.
234
249
  - When the MCP server is available, \`diffci_select_tests\` returns the one exact \`command\` to run; run that command as given.
235
250
 
251
+ Before a commit, verify what you will commit. Stage your own files by path (\`git add -- <your files>\`), then run:
252
+
253
+ \`\`\`bash
254
+ ${stagedCommand(command)}
255
+ \`\`\`
256
+
257
+ It verifies HEAD plus the staged files only, in a temporary worktree, so other uncommitted work in this checkout (another agent session's, for example) can neither fail nor pass your commit; the receipt lists those files under \`scoped.excluded_dirty_paths\`. \`diffci verify --paths <file...>\` does the same for named files without staging them; pair it with \`git commit -- <file...>\`. With MCP: \`diffci_select_tests\` with \`scope: "staged"\` (or \`scope: "paths"\` and \`paths\`) returns the one command to run.
258
+
236
259
  What this does:
237
260
 
238
261
  - snapshots staged, unstaged, and non-ignored untracked changes;
@@ -570,8 +593,12 @@ ${formatVerificationSummary(report)}`;
570
593
  }
571
594
  async function runVerifyCommand(flags, env) {
572
595
  const changed = flags.changed === true;
573
- if (changed && (flags.base !== undefined || flags.head !== undefined)) {
574
- console.error("diffci verify accepts either --changed or --base/--head, not both");
596
+ const staged = flags.staged === true;
597
+ const scopedPaths = flags.paths !== undefined || flags["paths-from"] !== undefined;
598
+ const range = flags.base !== undefined || flags.head !== undefined;
599
+ const modes = [changed && "--changed", staged && "--staged", scopedPaths && "--paths", range && "--base/--head"].filter(Boolean);
600
+ if (modes.length > 1) {
601
+ console.error(`diffci verify accepts one of --changed, --staged, --paths/--paths-from or --base/--head; got ${modes.join(" and ")}`);
575
602
  return 2;
576
603
  }
577
604
  const policy = flags.policy === true ? "" : stringFlag(flags, "policy");
@@ -579,11 +606,20 @@ async function runVerifyCommand(flags, env) {
579
606
  console.error(`diffci verify --policy accepts only "enforce", got ${JSON.stringify(policy)}`);
580
607
  return 2;
581
608
  }
582
- if (policy !== undefined && changed) {
583
- console.error("diffci verify --policy enforce applies to a commit range, not --changed");
609
+ if (policy !== undefined && (changed || staged || scopedPaths)) {
610
+ console.error(`diffci verify --policy enforce applies to a commit range, not ${modes[0]}`);
584
611
  return 2;
585
612
  }
586
613
  const repoPath = resolve(stringFlag(flags, "repo") ?? env.GITHUB_WORKSPACE ?? process.cwd());
614
+ let paths;
615
+ if (scopedPaths) {
616
+ const read = await scopedPathArguments(flags, repoPath);
617
+ if ("error" in read) {
618
+ console.error(`diffci verify: ${read.error}`);
619
+ return 2;
620
+ }
621
+ paths = read.paths;
622
+ }
587
623
  const out = stringFlag(flags, "out");
588
624
  const reportPath = out ? resolve(out) : undefined;
589
625
  if (reportPath && (reportPath === repoPath || isInsideRepository(repoPath, reportPath))) {
@@ -632,12 +668,22 @@ async function runVerifyCommand(flags, env) {
632
668
  };
633
669
  const report = changed
634
670
  ? await verifyChanged(common)
635
- : await verifyRange({
636
- ...common,
637
- baseOverride: stringFlag(flags, "base"),
638
- headOverride: stringFlag(flags, "head"),
639
- policy,
640
- });
671
+ : staged
672
+ ? await verifyScoped({ ...common, scope: { kind: "staged" } })
673
+ : paths
674
+ ? await verifyScoped({ ...common, scope: { kind: "paths", paths } })
675
+ : await verifyRange({
676
+ ...common,
677
+ baseOverride: stringFlag(flags, "base"),
678
+ headOverride: stringFlag(flags, "head"),
679
+ policy,
680
+ });
681
+ if (changed) {
682
+ const outside = filesOutsideIndex(repoPath);
683
+ if (outside > 0) {
684
+ console.error(`diffci: ${outside} changed file(s) here are not staged and were verified too. If other sessions share this checkout, stage your own files and run \`diffci verify --staged\` (or \`diffci verify --paths <file...>\`) to verify HEAD plus only those, in a temporary worktree.`);
685
+ }
686
+ }
641
687
  await recordUsage("verify", report.verification, identity.version, flags, env, repoPath);
642
688
  if (flags["no-log"] !== true)
643
689
  appendOutcome(repoPath, report, env);
@@ -654,6 +700,66 @@ async function runVerifyCommand(flags, env) {
654
700
  }
655
701
  return verificationExitCode(report);
656
702
  }
703
+ /** Unstaged or untracked (non-ignored) files, for the `--changed` hint. Zero when Git cannot say. */
704
+ function filesOutsideIndex(repoPath) {
705
+ const status = spawnSync("git", ["status", "--porcelain", "-z", "--untracked-files=all"], { cwd: repoPath, encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 });
706
+ if (status.status !== 0)
707
+ return 0;
708
+ const entries = (status.stdout ?? "").split("\0");
709
+ let count = 0;
710
+ for (let i = 0; i < entries.length; i++) {
711
+ const entry = entries[i];
712
+ if (entry.length < 4)
713
+ continue;
714
+ if (entry.startsWith("??") || entry[1] !== " ")
715
+ count++;
716
+ // A rename's source path follows as its own field.
717
+ if (entry[0] === "R" || entry[0] === "C")
718
+ i++;
719
+ }
720
+ return count;
721
+ }
722
+ /**
723
+ * The paths for `--paths a b` and `--paths-from <file|->` (one per line, or NUL-separated), as
724
+ * repository-relative paths. Relative paths are read from the current directory when it is inside the
725
+ * repository, as Git reads them, and from the repository root otherwise.
726
+ */
727
+ async function scopedPathArguments(flags, repoPath) {
728
+ const given = [];
729
+ if (flags.paths === true)
730
+ return { error: "--paths needs at least one file" };
731
+ if (typeof flags.paths === "string")
732
+ given.push(...flags.paths.split("\0"));
733
+ const from = flags["paths-from"];
734
+ if (from === true)
735
+ return { error: "--paths-from needs a file, or - for standard input" };
736
+ if (typeof from === "string") {
737
+ let text;
738
+ try {
739
+ text = from === "-" ? await readStdin() : readFileSync(resolve(from), "utf8");
740
+ }
741
+ catch (error) {
742
+ return { error: `could not read --paths-from ${from}: ${error instanceof Error ? error.message : String(error)}` };
743
+ }
744
+ given.push(...text.split(/\0|\r?\n/));
745
+ }
746
+ const cwd = process.cwd();
747
+ const root = isInsideRepository(repoPath, cwd) || resolve(cwd) === repoPath ? cwd : repoPath;
748
+ const paths = [];
749
+ for (const raw of given) {
750
+ const path = raw.trim();
751
+ if (!path)
752
+ continue;
753
+ const absolute = resolve(root, path);
754
+ const rel = relative(repoPath, absolute);
755
+ if (rel === "" || rel.startsWith("..") || isAbsolute(rel))
756
+ return { error: `${path} is not a file inside ${repoPath}` };
757
+ paths.push(rel.split(sep).join("/"));
758
+ }
759
+ if (paths.length === 0)
760
+ return { error: "--paths/--paths-from named no files" };
761
+ return { paths: [...new Set(paths)] };
762
+ }
657
763
  function runCoverageCommand(flags, env) {
658
764
  const repoPath = resolve(stringFlag(flags, "repo") ?? env.GITHUB_WORKSPACE ?? process.cwd());
659
765
  const command = stringFlag(flags, "command") ?? inferFullCommand(repoPath).command;
@@ -1424,7 +1530,8 @@ Usage:
1424
1530
  diffci watch [--repo <path>] [--checks] [--debounce-ms <ms>] [--no-log]
1425
1531
  diffci agent-stop --agent claude|codex|cursor|copilot (run by the agent stop hooks init installs; reads the hook JSON on stdin)
1426
1532
  diffci mcp
1427
- diffci verify [--changed | --base <sha> --head <sha>] [--policy enforce] [--repo <path>] [--out <file>] [--json]
1533
+ diffci verify [--changed | --staged | --paths <file...> | --paths-from <file|-> | --base <sha> --head <sha>]
1534
+ [--policy enforce] [--repo <path>] [--out <file>] [--json]
1428
1535
  [--redact-paths] [--timeout-ms <ms>] [--baseline-on-failure] [--no-checks | --checks]
1429
1536
  [--share-usage] [--no-send] [--no-log] [--no-reuse] [--no-rank] [--fail-fast]
1430
1537
  [--shard <i/N> [--timings <file>]] [--no-coverage]
@@ -1478,7 +1585,11 @@ verify --changed snapshots staged, unstaged, and non-ignored untracked changes,
1478
1585
  executable verification (or full fallback), and exits zero only when that exact snapshot passes.
1479
1586
  verify first runs the rest of the repository's gate (the check script's lint, typecheck and check-script
1480
1587
  leaves) and stops at the first failure; --no-checks skips them, and they are skipped in CI unless --checks.
1481
- verify without --changed resolves the CI event range (or HEAD^..HEAD locally), requires a clean checkout,
1588
+ verify --staged verifies HEAD plus the index only, and --paths (or --paths-from, one path per line, - for
1589
+ stdin) HEAD plus only those working-tree files, in a temporary worktree with node_modules linked in: other
1590
+ uncommitted files stay at their HEAD version and are listed in the receipt (scoped.excluded_dirty_paths).
1591
+ Use it before a commit when other sessions share the checkout. The pre-push hook reuses a pass of the tree.
1592
+ verify without these flags resolves the CI event range (or HEAD^..HEAD locally), requires a clean checkout,
1482
1593
  and exits zero only when the analyzed head is the commit that actually passed verification.
1483
1594
  check analyzes the change, runs inferred full and selected commands, and shows measured savings.
1484
1595
  plan prints Core's advisory JSON plan for a clean checkout at --head; save it before the full suite runs.
@@ -10,7 +10,7 @@ export interface ObservationEnvironment {
10
10
  [key: string]: string | undefined;
11
11
  }
12
12
  export interface CiEnvironmentFacts {
13
- provider: "github-actions" | "gitlab-ci" | "local" | "unknown";
13
+ provider: "github-actions" | "gitlab-ci" | "azure-pipelines" | "local" | "unknown";
14
14
  ownerName?: string;
15
15
  providerRepositoryId?: string;
16
16
  defaultBranch?: string;
@@ -23,6 +23,8 @@ export interface CiEnvironmentFacts {
23
23
  syntheticTrigger?: boolean;
24
24
  }
25
25
  export declare function readEventPayload(env: ObservationEnvironment): Record<string, unknown> | undefined;
26
+ /** Azure Pipelines sets `TF_BUILD=True` on every agent job. */
27
+ export declare function isAzurePipelines(env: ObservationEnvironment): boolean;
26
28
  export declare function readCiEnvironment(env: ObservationEnvironment): CiEnvironmentFacts;
27
29
  export interface ResolvedCommitRange {
28
30
  baseSha: string;
@@ -65,9 +65,32 @@ function readGitlabEnvironment(env) {
65
65
  syntheticTrigger: event !== undefined && GITLAB_SYNTHETIC_SOURCES.has(event),
66
66
  };
67
67
  }
68
+ /** Azure Pipelines build reasons with no change of their own to analyse (2026-11-17). */
69
+ const AZURE_SYNTHETIC_REASONS = new Set(["Manual", "Schedule", "ResourceTrigger", "BuildCompletion"]);
70
+ /** Azure Pipelines sets `TF_BUILD=True` on every agent job. */
71
+ export function isAzurePipelines(env) {
72
+ return env.TF_BUILD?.toLowerCase() === "true";
73
+ }
74
+ function readAzureEnvironment(env) {
75
+ const event = asString(env.BUILD_REASON);
76
+ return {
77
+ provider: "azure-pipelines",
78
+ ownerName: asString(env.BUILD_REPOSITORY_NAME),
79
+ providerRepositoryId: asString(env.BUILD_REPOSITORY_ID),
80
+ runId: asString(env.BUILD_BUILDID),
81
+ runAttempt: asString(env.SYSTEM_JOBATTEMPT),
82
+ workflow: asString(env.BUILD_DEFINITIONNAME),
83
+ job: asString(env.SYSTEM_JOBDISPLAYNAME),
84
+ event,
85
+ ref: asString(env.BUILD_SOURCEBRANCH),
86
+ syntheticTrigger: event !== undefined && AZURE_SYNTHETIC_REASONS.has(event),
87
+ };
88
+ }
68
89
  export function readCiEnvironment(env) {
69
90
  if (env.GITLAB_CI === "true")
70
91
  return readGitlabEnvironment(env);
92
+ if (isAzurePipelines(env))
93
+ return readAzureEnvironment(env);
71
94
  if (env.GITHUB_ACTIONS !== "true") {
72
95
  return { provider: env.CI === "true" ? "unknown" : "local" };
73
96
  }
@@ -110,8 +133,61 @@ function mergeBase(git, a, b) {
110
133
  const DEEPEN_HINT = "the commit is not in this checkout - add `fetch-depth: 0` to the actions/checkout step in the job that runs DiffCI (this does not affect any other job)";
111
134
  /** GitLab clones 20 commits deep by default, so a long merge request loses its base (2026-11-05). */
112
135
  const GITLAB_DEEPEN_HINT = "the commit is not in this checkout - set `GIT_DEPTH: \"0\"` in the variables of the job that runs DiffCI (this does not affect any other job)";
136
+ /** Azure Pipelines checks out shallow (`fetchDepth: 1`) by default in pipelines created since 2022. */
137
+ const AZURE_DEEPEN_HINT = "the commit is not in this checkout - set `fetchDepth: 0` on the `checkout` step of the job that runs DiffCI (this does not affect any other job)";
113
138
  function deepenHint(env) {
114
- return env.GITLAB_CI === "true" ? GITLAB_DEEPEN_HINT : DEEPEN_HINT;
139
+ if (env.GITLAB_CI === "true")
140
+ return GITLAB_DEEPEN_HINT;
141
+ return isAzurePipelines(env) ? AZURE_DEEPEN_HINT : DEEPEN_HINT;
142
+ }
143
+ /**
144
+ * Azure Pipelines (2026-11-17), for the DiffCIObserve task and the CLI run directly in a pipeline.
145
+ *
146
+ * - A pull request build checks out a merge commit Azure created (`refs/pull/<n>/merge`), like GitHub's
147
+ * merge ref. Its second parent is the source head (`System.PullRequest.SourceCommitId`) and its first
148
+ * parent the target branch tip the merge was made against. The range is the merge base of the two up
149
+ * to the source head, so commits that reached the target branch since are not counted.
150
+ * - Push builds (`IndividualCI`, `BatchedCI`) carry no "before" commit, so the head's parent is used and
151
+ * labelled `head-parent`: a batched build with several commits is described by its last commit only.
152
+ *
153
+ * Returns undefined for build reasons with no range (manual, schedule, ...), which take the generic
154
+ * HEAD^ path with `syntheticTrigger` recorded.
155
+ */
156
+ function resolveAzureRange(env, git) {
157
+ const hint = AZURE_DEEPEN_HINT;
158
+ const reason = env.BUILD_REASON;
159
+ if (reason === "PullRequest") {
160
+ const secondParent = resolveSha(git, "HEAD^2");
161
+ const headSha = asString(env.SYSTEM_PULLREQUEST_SOURCECOMMITID) ?? secondParent;
162
+ if (!headSha)
163
+ return { ok: false, reason: "pull request build carried no System.PullRequest.SourceCommitId and HEAD is not a merge commit" };
164
+ if (!commitExists(git, headSha)) {
165
+ return { ok: false, reason: `pull request head ${headSha.slice(0, 12)} is not present locally: ${hint}` };
166
+ }
167
+ // The target tip: the merge commit's first parent when its second parent is the source head, else
168
+ // the fetched target branch.
169
+ let targetTip = secondParent === headSha ? resolveSha(git, "HEAD^1") : undefined;
170
+ const targetBranch = asString(env.SYSTEM_PULLREQUEST_TARGETBRANCH)?.replace(/^refs\/heads\//, "");
171
+ if (!targetTip && targetBranch)
172
+ targetTip = resolveSha(git, `refs/remotes/origin/${targetBranch}`);
173
+ if (!targetTip) {
174
+ return { ok: false, reason: `the pull request's target branch${targetBranch ? ` ${targetBranch}` : ""} is not present locally: ${hint}` };
175
+ }
176
+ const common = mergeBase(git, targetTip, headSha);
177
+ if (!common)
178
+ return { ok: false, reason: `no merge base between the pull request head and its target branch in this checkout: ${hint}` };
179
+ return { ok: true, range: { baseSha: common, headSha, source: "pull-request-event", mergeBaseSha: common !== targetTip ? common : undefined } };
180
+ }
181
+ if (reason === "IndividualCI" || reason === "BatchedCI") {
182
+ const headSha = asString(env.BUILD_SOURCEVERSION) ?? resolveSha(git, "HEAD");
183
+ if (!headSha)
184
+ return { ok: false, reason: "could not determine the head commit of this build" };
185
+ const parent = resolveSha(git, `${headSha}^`);
186
+ if (!parent)
187
+ return { ok: false, reason: `the head commit has no parent in this checkout: ${hint}` };
188
+ return { ok: true, range: { baseSha: parent, headSha, source: "head-parent" } };
189
+ }
190
+ return undefined;
115
191
  }
116
192
  /**
117
193
  * GitLab's version of the GitHub event handling below (2026-11-05). The traps have different names:
@@ -191,7 +267,7 @@ export function resolveCommitRangeFetchingHistory(options) {
191
267
  if (first.ok)
192
268
  return first;
193
269
  const { env, git } = options;
194
- if (env.GITHUB_ACTIONS !== "true" && env.GITLAB_CI !== "true")
270
+ if (env.GITHUB_ACTIONS !== "true" && env.GITLAB_CI !== "true" && !isAzurePipelines(env))
195
271
  return first;
196
272
  const shallow = git(["rev-parse", "--is-shallow-repository"]);
197
273
  if (!shallow.ok || shallow.stdout.trim() !== "true")
@@ -220,6 +296,11 @@ export function resolveCommitRange(options) {
220
296
  if (gitlab)
221
297
  return gitlab;
222
298
  }
299
+ if (isAzurePipelines(env)) {
300
+ const azure = resolveAzureRange(env, git);
301
+ if (azure)
302
+ return azure;
303
+ }
223
304
  const payload = readEventPayload(env);
224
305
  const event = env.GITHUB_EVENT_NAME;
225
306
  if (event === "pull_request" || event === "pull_request_target") {
@@ -3,6 +3,7 @@ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  const DIFFCI_SCRIPTS = {
5
5
  "diffci:verify": "diffci verify --changed --json",
6
+ "diffci:verify:staged": "diffci verify --staged --json",
6
7
  "diffci:check": "diffci check",
7
8
  "diffci:observe": "diffci observe --no-send",
8
9
  };
@@ -0,0 +1,31 @@
1
+ /**
2
+ * A temporary detached worktree holding exactly one tree (2026-11-17), for `verify --staged` and
3
+ * `verify --paths`: the same isolation the pre-push hook uses (hook.ts, verify_in_worktree), in TypeScript.
4
+ *
5
+ * The worktree's HEAD is the checkout's HEAD and its files are the scoped tree, so the existing
6
+ * working-tree verification runs there unchanged: excluded dirty files in the shared checkout exist only
7
+ * at their HEAD version and can neither break nor rescue the result, at analysis time or at runtime.
8
+ *
9
+ * Dependencies. Each `node_modules` directory of the checkout (four levels deep, as the hook looks) is
10
+ * linked in: a junction on Windows, which needs no privilege, and a symlink elsewhere. Only when every
11
+ * root lockfile in the scoped tree matches the checkout's, by blob id; otherwise the installed
12
+ * dependencies are not the ones the tree asks for, and DiffCI says it cannot verify.
13
+ *
14
+ * Cleanup. `dispose` removes the links first, so removing the worktree can never reach through a link
15
+ * into the real dependencies, then the worktree and its registration. It runs on success, failure and
16
+ * timeout (the caller's `finally`), and on SIGINT, SIGTERM and SIGHUP.
17
+ */
18
+ export interface IsolatedWorktree {
19
+ path: string;
20
+ /** Checkout-relative `node_modules` directories linked into the worktree. */
21
+ linked: string[];
22
+ /** Removes links, the worktree and its registration. False when something could not be removed. */
23
+ dispose(): boolean;
24
+ }
25
+ /** Root lockfiles whose content in `treeSha` differs from the checkout's file on disk. */
26
+ export declare function lockfileMismatches(repoPath: string, treeSha: string): string[];
27
+ /** Checkout-relative `node_modules` directories, at most four levels deep, never inside one another. */
28
+ export declare function dependencyDirectories(repoPath: string, maxDepth?: number): string[];
29
+ export declare function createIsolatedWorktree(repoPathInput: string, baseSha: string, treeSha: string): IsolatedWorktree | {
30
+ error: string;
31
+ };