@diffci.com/diffci 0.3.53 → 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.
@@ -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
+ };
@@ -0,0 +1,130 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, lstatSync, mkdtempSync, readdirSync, realpathSync, rmSync, symlinkSync, unlinkSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { dirname, join, resolve } from "node:path";
5
+ const LOCKFILES = ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb"];
6
+ function git(cwd, args, input) {
7
+ const result = spawnSync("git", args, { cwd, input, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, windowsHide: true });
8
+ return { ok: result.status === 0, stdout: (result.stdout ?? "").trim(), stderr: (result.stderr ?? "").trim() };
9
+ }
10
+ /** Root lockfiles whose content in `treeSha` differs from the checkout's file on disk. */
11
+ export function lockfileMismatches(repoPath, treeSha) {
12
+ const mismatched = [];
13
+ for (const lock of LOCKFILES) {
14
+ const onDisk = existsSync(join(repoPath, lock)) ? git(repoPath, ["hash-object", "--", lock]).stdout : "";
15
+ const inTree = git(repoPath, ["rev-parse", "-q", "--verify", `${treeSha}:${lock}`]).stdout;
16
+ // Blob ids, not bytes: Git applies the same line-ending normalization on both sides.
17
+ if ((onDisk || inTree) && onDisk !== inTree)
18
+ mismatched.push(lock);
19
+ }
20
+ return mismatched;
21
+ }
22
+ /** Checkout-relative `node_modules` directories, at most four levels deep, never inside one another. */
23
+ export function dependencyDirectories(repoPath, maxDepth = 4) {
24
+ const found = [];
25
+ const walk = (relative, depth) => {
26
+ let entries;
27
+ try {
28
+ entries = readdirSync(join(repoPath, relative), { withFileTypes: true });
29
+ }
30
+ catch {
31
+ return;
32
+ }
33
+ for (const entry of entries) {
34
+ if (!entry.isDirectory() || entry.name === ".git")
35
+ continue;
36
+ const child = relative ? `${relative}/${entry.name}` : entry.name;
37
+ if (entry.name === "node_modules") {
38
+ found.push(child);
39
+ continue;
40
+ }
41
+ if (depth < maxDepth)
42
+ walk(child, depth + 1);
43
+ }
44
+ };
45
+ walk("", 1);
46
+ return found.sort();
47
+ }
48
+ function removeLink(path) {
49
+ try {
50
+ if (!lstatSync(path).isSymbolicLink())
51
+ return false;
52
+ // A junction is a symbolic link to Node; unlink removes the link, never the target's contents.
53
+ unlinkSync(path);
54
+ return true;
55
+ }
56
+ catch (error) {
57
+ return error.code === "ENOENT";
58
+ }
59
+ }
60
+ export function createIsolatedWorktree(repoPathInput, baseSha, treeSha) {
61
+ const repoPath = resolve(repoPathInput);
62
+ const mismatched = lockfileMismatches(repoPath, treeSha);
63
+ if (mismatched.length) {
64
+ return { error: `${mismatched.join(", ")} in the verified files differs from this checkout's, so its installed dependencies do not match; install dependencies for it, or include the lockfile change the installed dependencies were made from` };
65
+ }
66
+ // The long form of the path: an 8.3 temporary directory (C:\Users\ABCDEF~1) would not match the
67
+ // repository root Git reports inside the worktree.
68
+ const temporary = realpathSync.native(mkdtempSync(join(tmpdir(), "diffci-scoped-")));
69
+ const path = join(temporary, "tree");
70
+ const added = git(repoPath, ["worktree", "add", "--quiet", "--detach", "--no-checkout", path, baseSha]);
71
+ if (!added.ok) {
72
+ rmSync(temporary, { recursive: true, force: true });
73
+ return { error: `could not create a temporary worktree: ${added.stderr.split("\n")[0] ?? "git worktree add failed"}` };
74
+ }
75
+ const linked = [];
76
+ let disposed = false;
77
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
78
+ const onSignal = (signal) => {
79
+ dispose();
80
+ process.exit(signal === "SIGINT" ? 130 : 143);
81
+ };
82
+ const onExit = () => { dispose(); };
83
+ function dispose() {
84
+ if (disposed)
85
+ return true;
86
+ disposed = true;
87
+ for (const signal of signals)
88
+ process.removeListener(signal, onSignal);
89
+ process.removeListener("exit", onExit);
90
+ // Links first: removing the worktree must never reach through a link into the checkout.
91
+ const unlinked = linked.every((relative) => removeLink(join(path, relative)));
92
+ let removed = git(repoPath, ["worktree", "remove", "--force", path]).ok;
93
+ if (!removed && unlinked) {
94
+ try {
95
+ rmSync(path, { recursive: true, force: true, maxRetries: 3 });
96
+ removed = !existsSync(path);
97
+ }
98
+ catch {
99
+ removed = false;
100
+ }
101
+ }
102
+ git(repoPath, ["worktree", "prune"]);
103
+ if (removed) {
104
+ try {
105
+ rmSync(temporary, { recursive: true, force: true });
106
+ }
107
+ catch { /* an empty directory left in the temp folder is harmless */ }
108
+ }
109
+ return removed && unlinked;
110
+ }
111
+ for (const signal of signals)
112
+ process.once(signal, onSignal);
113
+ process.once("exit", onExit);
114
+ const checkout = git(path, ["read-tree", "--reset", "-u", treeSha]);
115
+ if (!checkout.ok) {
116
+ dispose();
117
+ return { error: `could not check out the verified files in the temporary worktree: ${checkout.stderr.split("\n")[0] ?? "git read-tree failed"}` };
118
+ }
119
+ for (const relative of dependencyDirectories(repoPath)) {
120
+ const target = join(path, relative);
121
+ if (!existsSync(dirname(target)) || existsSync(target))
122
+ continue;
123
+ try {
124
+ symlinkSync(join(repoPath, relative), target, "junction");
125
+ linked.push(relative);
126
+ }
127
+ catch { /* a missing dependency link shows up as a failing or unrunnable test, never as a pass */ }
128
+ }
129
+ return { path, linked, dispose };
130
+ }
@@ -2,7 +2,7 @@
2
2
  import { execFile } from "node:child_process";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { StringDecoder } from "node:string_decoder";
5
- import { agentChangedFiles, agentSelection, selectionInstruction } from "./agent-selection.js";
5
+ import { agentChangedFiles, agentScopedSelection, agentSelection, selectionInstruction } from "./agent-selection.js";
6
6
  import { requireDiffciPackageIdentity } from "./package-identity.js";
7
7
  const SERVER_INFO = { name: "diffci-mcp", version: requireDiffciPackageIdentity().version };
8
8
  const tools = [
@@ -12,12 +12,16 @@ const tools = [
12
12
  ? "Reanalyze and verify the current working-tree snapshot with affected tests or conservative full fallback. Required CI remains authoritative."
13
13
  : name === "diffci_changed_files"
14
14
  ? "List staged, unstaged and non-ignored untracked changed paths relative to HEAD, with a snapshot identity. Builds no dependency graph and runs no tests."
15
- : "Inspect current staged, unstaged and non-ignored untracked changes and return a snapshot-bound affected-test plan and fallback reasons. Runs no tests; a plan is not a passing receipt.",
15
+ : "Inspect current staged, unstaged and non-ignored untracked changes and return a snapshot-bound affected-test plan and fallback reasons. Runs no tests; a plan is not a passing receipt. With scope \"staged\" or \"paths\", plans HEAD plus only the index or only the given files in a temporary worktree, and returns the one `diffci verify --staged`/`--paths` command to run; use it before a commit when other sessions share the checkout.",
16
16
  inputSchema: {
17
17
  type: "object",
18
18
  properties: {
19
19
  repo: { type: "string", description: "Absolute repository path; defaults to server working directory. Always pass the edited repository when using a plugin." },
20
20
  ...(name === "diffci_run_affected_tests" ? { timeoutMs: { type: "number", minimum: 0 } } : {}),
21
+ ...(name === "diffci_select_tests" || name === "diffci_explain_selection" ? {
22
+ scope: { type: "string", enum: ["working-tree", "staged", "paths"], description: "working-tree (default): every uncommitted change. staged: HEAD plus the index only. paths: HEAD plus only `paths`." },
23
+ paths: { type: "array", items: { type: "string" }, description: "Repository-relative files for scope \"paths\"." },
24
+ } : {}),
21
25
  },
22
26
  additionalProperties: false,
23
27
  },
@@ -241,7 +245,10 @@ async function handle(request) {
241
245
  const properties = tool.inputSchema.properties;
242
246
  for (const [key, value] of Object.entries(args)) {
243
247
  const property = properties[key];
244
- if (!property || typeof value !== property.type || (key === "timeoutMs" && (!Number.isFinite(value) || value < 0))) {
248
+ const typed = property?.type === "array"
249
+ ? Array.isArray(value) && value.every((item) => typeof item === "string" && item.trim() !== "")
250
+ : property !== undefined && typeof value === property.type && (!property.enum || property.enum.includes(value));
251
+ if (!typed || (key === "timeoutMs" && (!Number.isFinite(value) || value < 0))) {
245
252
  failure(id, -32602, `invalid argument: ${key}`);
246
253
  return;
247
254
  }
@@ -253,7 +260,15 @@ async function handle(request) {
253
260
  success(id, { content: [{ type: "text", text: JSON.stringify(changes) }], structuredContent: changes, isError: changes.status === "blocked" });
254
261
  return;
255
262
  }
256
- const plan = await agentSelection(repo);
263
+ const scope = stringArg(args, "scope") ?? "working-tree";
264
+ const paths = Array.isArray(args.paths) ? args.paths : undefined;
265
+ if ((scope === "paths") !== (paths !== undefined && paths.length > 0)) {
266
+ failure(id, -32602, scope === "paths" ? "scope \"paths\" needs a non-empty paths array" : "paths applies only to scope \"paths\"");
267
+ return;
268
+ }
269
+ const plan = scope === "staged" ? await agentScopedSelection(repo, { kind: "staged" })
270
+ : scope === "paths" ? await agentScopedSelection(repo, { kind: "paths", paths: paths.map((path) => path.replace(/\\/g, "/")) })
271
+ : await agentSelection(repo);
257
272
  success(id, { content: [{ type: "text", text: `${selectionInstruction(plan)}\n\n${JSON.stringify(plan)}` }], structuredContent: plan, isError: plan.status === "blocked" });
258
273
  return;
259
274
  }
@@ -40,6 +40,8 @@ export interface ObserveOptions {
40
40
  };
41
41
  /** Opt-in agent identity (src/client/agent-identity.ts); absent means the report carries none. */
42
42
  agent?: ObservationAgent;
43
+ /** Called with the dependency graph once built, for callers that read its edges (scoped verify). */
44
+ onGraph?: (result: DependencyGraphResult) => void;
43
45
  }
44
46
  export declare function makeGitRunner(repoPath: string): GitRunner;
45
47
  /**
@@ -224,6 +224,10 @@ export async function observe(options) {
224
224
  catch { /* caching never fails an observation */ }
225
225
  }
226
226
  markPhase(cachedGraph ? "graphCached" : "graph");
227
+ try {
228
+ options.onGraph?.(graphResult);
229
+ }
230
+ catch { /* a reader of the graph never fails an observation */ }
227
231
  if (graphResult.graph.nodes.length === 0) {
228
232
  return finish("REFUSED", "graph", {
229
233
  reason: "the dependency graph came back empty - DiffCI will not propose a selection from a graph that sees none of this repository" +
@@ -1,13 +1,34 @@
1
+ import type { DependencyGraphResult } from "@diffci.com/core/repo/types";
1
2
  import { type FailureBaseline } from "./failure-baseline.js";
2
3
  import { type EnforcementDecision } from "./enforce-policy.js";
3
4
  import { type CheckResult } from "./gate-checks.js";
4
- import type { ObservationCommitRange, ObservationReport, SelectionReason } from "./report.js";
5
+ import { type ObservationCommitRange, type ObservationReport, type SelectionReason } from "./report.js";
5
6
  import { type ShardSpec, type TimingsFile } from "./test-shards.js";
6
7
  import type { CommandMeasurement } from "./verify-savings.js";
7
- import { type SnapshotChange } from "./working-tree.js";
8
+ import { type SnapshotChange, type VerificationTreeScope, type WorkingTreeSnapshot } from "./working-tree.js";
8
9
  export declare const VERIFICATION_SCHEMA: "diffci.verification.v1";
9
10
  export type VerificationStatus = "passed" | "failed" | "blocked";
10
- export type VerificationScope = "working-tree" | "commit-range";
11
+ /** `staged` and `paths` (2026-11-17) verify HEAD plus only the index, or only the named files, in a temporary worktree. */
12
+ export type VerificationScope = "working-tree" | "commit-range" | "staged" | "paths";
13
+ /** What a `staged` or `paths` receipt covered, and what in the checkout it left out (verifyScoped). */
14
+ export interface ScopedVerification {
15
+ kind: "staged" | "paths";
16
+ /** Always a temporary worktree of HEAD plus the verified files. */
17
+ isolation: "temporary-worktree";
18
+ /** Files that differ from HEAD in the verified tree (digests under --redact-paths). */
19
+ verified_files: string[];
20
+ /** Files in the checkout that differ from the verified tree: other work left out, verified at HEAD. */
21
+ excluded_dirty_files: number;
22
+ /** The first 50 of them. */
23
+ excluded_dirty_paths: string[];
24
+ /** Verified files that import an excluded dirty file, which was verified at its HEAD version. */
25
+ head_version_imports?: Array<{
26
+ file: string;
27
+ imports: string[];
28
+ }>;
29
+ /** Set when the temporary worktree could not be removed; `git worktree prune` after deleting it. */
30
+ cleanup_failed?: string;
31
+ }
11
32
  export interface VerificationReport {
12
33
  schema: typeof VERIFICATION_SCHEMA;
13
34
  schema_version: "1";
@@ -98,6 +119,8 @@ export interface VerificationReport {
98
119
  };
99
120
  /** Tests the coverage map added to the selection (coverage-map.ts), when it added any. */
100
121
  coverage_added?: string[];
122
+ /** Present for `--staged` and `--paths`: the verified files and the excluded dirty ones. */
123
+ scoped?: ScopedVerification;
101
124
  }
102
125
  interface VerifyOptions {
103
126
  repoPath: string;
@@ -122,9 +145,14 @@ interface VerifyOptions {
122
145
  timings?: TimingsFile;
123
146
  /** False ignores the coverage map (`--no-coverage`). */
124
147
  coverage?: boolean;
148
+ /** Receives the dependency graph the analysis built (verifyScoped reads its edges). */
149
+ onGraph?: (result: DependencyGraphResult) => void;
125
150
  }
126
151
  export interface VerifyChangedOptions extends VerifyOptions {
127
152
  }
153
+ export interface VerifyScopedOptions extends VerifyOptions {
154
+ scope: VerificationTreeScope;
155
+ }
128
156
  export interface VerifyRangeOptions extends VerifyOptions {
129
157
  baseOverride?: string;
130
158
  headOverride?: string;
@@ -133,6 +161,22 @@ export interface VerifyRangeOptions extends VerifyOptions {
133
161
  }
134
162
  /** Verify exactly the staged, unstaged, and non-ignored untracked content currently on disk. */
135
163
  export declare function verifyChanged(options: VerifyChangedOptions): Promise<VerificationReport>;
164
+ /**
165
+ * Verify HEAD plus only the staged content (`--staged`) or only the named files (`--paths`), 2026-11-17.
166
+ *
167
+ * The scoped tree is checked out in a temporary worktree of HEAD (isolated-worktree.ts) and verified
168
+ * there exactly as `--changed` verifies a checkout, so every other uncommitted file in this checkout is
169
+ * at its HEAD version for analysis and for the tests: it can neither fail nor rescue the result. The
170
+ * receipt names the verified files and the excluded dirty ones. Its tree is the tree a commit of the
171
+ * staged files has, so the pre-push hook reuses a pass of it (outcome-log.ts, reusablePass).
172
+ */
173
+ /** The scoped tree, the files it changes from HEAD, and the checkout's other changed files (excluded). */
174
+ export declare function scopedChanges(repoPath: string, scope: VerificationTreeScope): {
175
+ scoped: WorkingTreeSnapshot;
176
+ verified: SnapshotChange[];
177
+ excluded: SnapshotChange[];
178
+ };
179
+ export declare function verifyScoped(options: VerifyScopedOptions): Promise<VerificationReport>;
136
180
  /** Verify a real commit range and bind the receipt to the clean commit that was actually executed. */
137
181
  export declare function verifyRange(options: VerifyRangeOptions): Promise<VerificationReport>;
138
182
  export declare function verificationExitCode(report: VerificationReport): number;
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { mkdtempSync, rmSync } from "node:fs";
2
3
  import { tmpdir } from "node:os";
3
4
  import { join, resolve } from "node:path";
@@ -8,12 +9,14 @@ import { collectEnforcementContext, evaluateEnforcement } from "./enforce-policy
8
9
  import { inferFullCommand, inferPlannedCommands, inferSelectedCommand, inferSelectedCommands } from "./full-command.js";
9
10
  import { plannedChecks, runChecks } from "./gate-checks.js";
10
11
  import { makeGitRunner, observe } from "./observe.js";
12
+ import { redactPath } from "./report.js";
13
+ import { createIsolatedWorktree } from "./isolated-worktree.js";
11
14
  import { selectedNodeTests, traceNodeTestFiles, unmatchedNodeTests, unstartedNodeTests } from "./selected-coverage.js";
12
15
  import { outcomeLogPath, readOutcomes, reusablePass } from "./outcome-log.js";
13
16
  import { likelyFailures, rankTests, testHistory } from "./test-ranking.js";
14
17
  import { assignShards } from "./test-shards.js";
15
18
  import { mergeTestFileResults } from "./test-results.js";
16
- import { captureWorkingTreeSnapshot, snapshotChanges } from "./working-tree.js";
19
+ import { captureScopedTree, captureWorkingTreeSnapshot, snapshotChanges } from "./working-tree.js";
17
20
  export const VERIFICATION_SCHEMA = "diffci.verification.v1";
18
21
  function receiptRange(range) {
19
22
  if (!range)
@@ -404,6 +407,7 @@ async function verifyChangedSnapshot(options) {
404
407
  redactPaths: options.redactPaths,
405
408
  reportPath: join(temporaryDirectory, "observation.json"),
406
409
  selectTestPhases: true,
410
+ ...(options.onGraph ? { onGraph: options.onGraph } : {}),
407
411
  });
408
412
  return await executeObservation({ ...options, repoPath }, "working-tree", before, observation);
409
413
  }
@@ -411,6 +415,113 @@ async function verifyChangedSnapshot(options) {
411
415
  rmSync(temporaryDirectory, { recursive: true, force: true });
412
416
  }
413
417
  }
418
+ /**
419
+ * Verify HEAD plus only the staged content (`--staged`) or only the named files (`--paths`), 2026-11-17.
420
+ *
421
+ * The scoped tree is checked out in a temporary worktree of HEAD (isolated-worktree.ts) and verified
422
+ * there exactly as `--changed` verifies a checkout, so every other uncommitted file in this checkout is
423
+ * at its HEAD version for analysis and for the tests: it can neither fail nor rescue the result. The
424
+ * receipt names the verified files and the excluded dirty ones. Its tree is the tree a commit of the
425
+ * staged files has, so the pre-push hook reuses a pass of it (outcome-log.ts, reusablePass).
426
+ */
427
+ /** The scoped tree, the files it changes from HEAD, and the checkout's other changed files (excluded). */
428
+ export function scopedChanges(repoPath, scope) {
429
+ const scoped = captureScopedTree(repoPath, scope);
430
+ const checkout = captureWorkingTreeSnapshot(repoPath);
431
+ return {
432
+ scoped,
433
+ verified: snapshotChanges(repoPath, `${scoped.baseSha}^{tree}`, scoped.treeSha),
434
+ excluded: snapshotChanges(repoPath, scoped.treeSha, checkout.treeSha),
435
+ };
436
+ }
437
+ export async function verifyScoped(options) {
438
+ return stamped(await verifyScopedTree(options), options.version);
439
+ }
440
+ async function verifyScopedTree(options) {
441
+ const repoPath = resolve(options.repoPath);
442
+ const kind = options.scope.kind;
443
+ const shown = (path) => options.redactPaths ? redactPath(path, (input) => createHash("sha256").update(input).digest("hex")) : path;
444
+ let scoped;
445
+ let verified;
446
+ let excluded;
447
+ try {
448
+ ({ scoped, verified, excluded } = scopedChanges(repoPath, options.scope));
449
+ }
450
+ catch (error) {
451
+ const message = error instanceof Error ? error.message : String(error);
452
+ return blocked(unknownSnapshot(), kind, message, { status: "ERROR", stage: "context", fallback_reasons: [], error: message });
453
+ }
454
+ const scopedField = {
455
+ kind,
456
+ isolation: "temporary-worktree",
457
+ verified_files: verified.map((change) => shown(change.path)),
458
+ excluded_dirty_files: excluded.length,
459
+ excluded_dirty_paths: excluded.slice(0, 50).map((change) => shown(change.path)),
460
+ };
461
+ if (!scoped.changed) {
462
+ return {
463
+ ...baseReport(scoped, kind),
464
+ verification: "passed",
465
+ safe_to_continue: true,
466
+ reason: kind === "staged" ? "nothing is staged: the index matches HEAD" : "the given paths do not differ from HEAD",
467
+ changed_files: 0,
468
+ tests_available: 0,
469
+ tests_selected: 0,
470
+ selection: "none",
471
+ snapshot: { ...baseReport(scoped, kind).snapshot, after_base_sha: scoped.baseSha, after_tree_sha: scoped.treeSha, unchanged: true },
472
+ analysis: { status: "not_needed", fallback_reasons: [] },
473
+ required_actions: [],
474
+ scoped: scopedField,
475
+ };
476
+ }
477
+ const worktree = createIsolatedWorktree(repoPath, scoped.baseSha, scoped.treeSha);
478
+ if ("error" in worktree) {
479
+ return { ...blocked(scoped, kind, worktree.error, { status: "not_needed", fallback_reasons: [] }, { changedFiles: verified.length }), scoped: scopedField };
480
+ }
481
+ let forward;
482
+ let inner;
483
+ let cleaned;
484
+ try {
485
+ inner = await verifyChangedSnapshot({ ...options, repoPath: worktree.path, onGraph: (graph) => { forward = graph.graph.forward; } });
486
+ }
487
+ finally {
488
+ cleaned = worktree.dispose();
489
+ }
490
+ if (!cleaned)
491
+ scopedField.cleanup_failed = worktree.path;
492
+ // Excluded dirty files a verified file imports were verified at their HEAD version: say which.
493
+ const excludedPaths = new Set(excluded.map((change) => change.path));
494
+ const imports = forward
495
+ ? verified.flatMap((change) => {
496
+ const targets = (forward[change.path] ?? []).filter((target) => excludedPaths.has(target));
497
+ return targets.length ? [{ file: shown(change.path), imports: [...new Set(targets)].sort().map(shown) }] : [];
498
+ })
499
+ : [];
500
+ if (imports.length)
501
+ scopedField.head_version_imports = imports;
502
+ // The verdict is for the tree captured at the start: HEAD and the scoped files must still be it.
503
+ let after;
504
+ try {
505
+ after = captureScopedTree(repoPath, options.scope);
506
+ }
507
+ catch {
508
+ after = undefined;
509
+ }
510
+ const moved = !after ? "could not re-read the verified files after the run"
511
+ : after.baseSha !== scoped.baseSha ? "HEAD moved while verification was running"
512
+ : after.treeSha !== scoped.treeSha ? (kind === "staged" ? "the index changed while verification was running (another session may have staged files)" : "the given files changed while verification was running")
513
+ : inner.snapshot.before_tree_sha !== scoped.treeSha ? "the temporary worktree did not reproduce the verified files"
514
+ : undefined;
515
+ const importNote = imports.length
516
+ ? `; ${imports.length} verified file(s) import files changed outside the scope, verified at their HEAD version (${imports.slice(0, 3).map((entry) => `${entry.file} -> ${entry.imports.join(", ")}`).join("; ")})`
517
+ : "";
518
+ const report = { ...inner, scope: kind, reason: `${inner.reason}${importNote}`, scoped: scopedField };
519
+ if (moved) {
520
+ const reason = `${moved}; rerun DiffCI for the new ${kind === "staged" ? "index" : "files"}`;
521
+ return { ...report, verification: "blocked", safe_to_continue: false, reason, required_actions: [reason] };
522
+ }
523
+ return report;
524
+ }
414
525
  /** Verify a real commit range and bind the receipt to the clean commit that was actually executed. */
415
526
  export async function verifyRange(options) {
416
527
  return stamped(await verifyCommitRange(options), options.version);
@@ -472,6 +583,15 @@ export function formatVerificationSummary(report) {
472
583
  ];
473
584
  if (report.commit_range)
474
585
  lines.splice(2, 0, ` range: ${report.commit_range.base_sha.slice(0, 12)}..${report.commit_range.head_sha.slice(0, 12)}`);
586
+ const scoped = report.scoped;
587
+ if (scoped) {
588
+ const list = (paths, total) => `${paths.slice(0, 5).join(", ")}${total > 5 ? `, ${total - 5} more` : ""}`;
589
+ lines.splice(2, 0, ` verified files (HEAD + ${scoped.kind === "staged" ? "index" : "given paths"}, temporary worktree): ${scoped.verified_files.length}${scoped.verified_files.length ? ` (${list(scoped.verified_files, scoped.verified_files.length)})` : ""}`);
590
+ if (scoped.excluded_dirty_files)
591
+ lines.splice(3, 0, ` excluded: ${scoped.excluded_dirty_files} other changed file(s) in this checkout, verified at HEAD (${list(scoped.excluded_dirty_paths, scoped.excluded_dirty_files)})`);
592
+ if (scoped.cleanup_failed)
593
+ lines.push(` warning: could not remove the temporary worktree ${scoped.cleanup_failed}; delete it and run git worktree prune`);
594
+ }
475
595
  const lineEndings = report.snapshot.line_ending_only_changes;
476
596
  if (lineEndings?.length) {
477
597
  lines.push(` line endings only: ${lineEndings.length}${lineEndings.length === 20 ? "+" : ""} checked-out file(s) differ from HEAD only by CRLF (${lineEndings.slice(0, 3).join(", ")}${lineEndings.length > 3 ? ", ..." : ""}); verified as checked out`);
@@ -24,5 +24,27 @@ export interface SnapshotChange {
24
24
  * used only by DiffCI's existing commit-to-commit analyzer.
25
25
  */
26
26
  export declare function captureWorkingTreeSnapshot(repoPathInput: string): WorkingTreeSnapshot;
27
+ /** What a scoped verification covers: HEAD plus the index (`--staged`), or HEAD plus these working-tree paths (`--paths`). */
28
+ export type VerificationTreeScope = {
29
+ kind: "staged";
30
+ } | {
31
+ kind: "paths";
32
+ paths: readonly string[];
33
+ };
34
+ /**
35
+ * The tree a scoped verification checks (2026-11-17): HEAD plus only the staged content, or HEAD plus only
36
+ * the named working-tree paths, built in a temporary index like the working-tree snapshot.
37
+ *
38
+ * WHY. Several agent sessions shared one DentalPresence checkout; `verify --changed` before a 3-file commit
39
+ * verified another session's 30 uncommitted files too (341 of 638 test files, about 8 minutes, failed on
40
+ * the other session's code). HEAD plus those 3 files alone selected 12 test files and passed in 12 s.
41
+ *
42
+ * `--staged` reads a copy of the real index, so another session staging at the same moment can never see a
43
+ * half-written index of ours, and ours is never rewritten. `--paths` are literal pathspecs: Next.js route
44
+ * folders such as `app/[slug]` are names, not globs. A path deleted in the working tree is a deletion.
45
+ */
46
+ export declare function captureScopedTree(repoPathInput: string, scope: VerificationTreeScope): WorkingTreeSnapshot;
47
+ /** The tree of HEAD, for comparing a snapshot with the checked-out commit. */
48
+ export declare function headTree(repoPathInput: string): string;
27
49
  /** The paths that differ between two snapshot trees of the same repository. */
28
50
  export declare function snapshotChanges(repoPathInput: string, beforeTreeSha: string, afterTreeSha: string): SnapshotChange[];
@@ -1,5 +1,5 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { mkdtempSync, readFileSync, rmSync } from "node:fs";
2
+ import { copyFileSync, existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join, resolve } from "node:path";
5
5
  function runGit(repoPath, args, env, input) {
@@ -90,6 +90,24 @@ function crlfCheckouts(repoPath, baseTreeSha, indexEnvironment) {
90
90
  * used only by DiffCI's existing commit-to-commit analyzer.
91
91
  */
92
92
  export function captureWorkingTreeSnapshot(repoPathInput) {
93
+ return captureTree(repoPathInput, { kind: "working-tree" });
94
+ }
95
+ /**
96
+ * The tree a scoped verification checks (2026-11-17): HEAD plus only the staged content, or HEAD plus only
97
+ * the named working-tree paths, built in a temporary index like the working-tree snapshot.
98
+ *
99
+ * WHY. Several agent sessions shared one DentalPresence checkout; `verify --changed` before a 3-file commit
100
+ * verified another session's 30 uncommitted files too (341 of 638 test files, about 8 minutes, failed on
101
+ * the other session's code). HEAD plus those 3 files alone selected 12 test files and passed in 12 s.
102
+ *
103
+ * `--staged` reads a copy of the real index, so another session staging at the same moment can never see a
104
+ * half-written index of ours, and ours is never rewritten. `--paths` are literal pathspecs: Next.js route
105
+ * folders such as `app/[slug]` are names, not globs. A path deleted in the working tree is a deletion.
106
+ */
107
+ export function captureScopedTree(repoPathInput, scope) {
108
+ return captureTree(repoPathInput, scope);
109
+ }
110
+ function captureTree(repoPathInput, scope) {
93
111
  const repoPath = resolve(repoPathInput);
94
112
  const baseSha = requireGit(repoPath, ["rev-parse", "--verify", "HEAD^{commit}"], "could not resolve repository HEAD");
95
113
  const baseTreeSha = requireGit(repoPath, ["rev-parse", "--verify", "HEAD^{tree}"], "could not resolve repository HEAD tree");
@@ -100,11 +118,28 @@ export function captureWorkingTreeSnapshot(repoPathInput) {
100
118
  const temporaryIndex = join(temporaryDirectory, "index");
101
119
  const indexEnvironment = { GIT_INDEX_FILE: temporaryIndex };
102
120
  try {
103
- requireGit(repoPath, ["read-tree", baseSha], "could not initialize the verification snapshot", indexEnvironment);
104
- requireGit(repoPath, ["add", "-A", "--", "."], "could not capture the working tree", indexEnvironment);
105
- const lineEndingOnly = crlfCheckouts(repoPath, baseTreeSha, indexEnvironment);
106
- if (lineEndingOnly.length > 0) {
107
- requireGit(repoPath, ["reset", "-q", baseSha, "--pathspec-from-file=-", "--pathspec-file-nul"], "could not leave line-ending-only files out of the snapshot", indexEnvironment, `${lineEndingOnly.join("\0")}\0`);
121
+ let lineEndingOnly = [];
122
+ if (scope.kind === "staged") {
123
+ const indexPath = resolve(repoPath, requireGit(repoPath, ["rev-parse", "--git-path", "index"], "could not locate the repository index"));
124
+ if (existsSync(indexPath))
125
+ copyFileSync(indexPath, temporaryIndex);
126
+ else
127
+ requireGit(repoPath, ["read-tree", baseSha], "could not initialize the verification snapshot", indexEnvironment);
128
+ }
129
+ else {
130
+ requireGit(repoPath, ["read-tree", baseSha], "could not initialize the verification snapshot", indexEnvironment);
131
+ if (scope.kind === "working-tree") {
132
+ requireGit(repoPath, ["add", "-A", "--", "."], "could not capture the working tree", indexEnvironment);
133
+ }
134
+ else {
135
+ if (scope.paths.length === 0)
136
+ throw new Error("--paths needs at least one path");
137
+ requireGit(repoPath, ["--literal-pathspecs", "add", "-A", "--pathspec-from-file=-", "--pathspec-file-nul"], "could not capture the given paths", indexEnvironment, `${scope.paths.join("\0")}\0`);
138
+ }
139
+ lineEndingOnly = crlfCheckouts(repoPath, baseTreeSha, indexEnvironment);
140
+ if (lineEndingOnly.length > 0) {
141
+ requireGit(repoPath, ["reset", "-q", baseSha, "--pathspec-from-file=-", "--pathspec-file-nul"], "could not leave line-ending-only files out of the snapshot", indexEnvironment, `${lineEndingOnly.join("\0")}\0`);
142
+ }
108
143
  }
109
144
  const treeSha = requireGit(repoPath, ["write-tree"], "could not write the verification tree", indexEnvironment);
110
145
  const identityEnvironment = {
@@ -122,6 +157,10 @@ export function captureWorkingTreeSnapshot(repoPathInput) {
122
157
  rmSync(temporaryDirectory, { recursive: true, force: true });
123
158
  }
124
159
  }
160
+ /** The tree of HEAD, for comparing a snapshot with the checked-out commit. */
161
+ export function headTree(repoPathInput) {
162
+ return requireGit(resolve(repoPathInput), ["rev-parse", "--verify", "HEAD^{tree}"], "could not resolve repository HEAD tree");
163
+ }
125
164
  /** The paths that differ between two snapshot trees of the same repository. */
126
165
  export function snapshotChanges(repoPathInput, beforeTreeSha, afterTreeSha) {
127
166
  if (beforeTreeSha === afterTreeSha)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diffci.com/diffci",
3
- "version": "0.3.53",
3
+ "version": "0.3.54",
4
4
  "description": "Verification for AI coding agents: runs the tests and checks a change affects, with full fallback and a receipt",
5
5
  "keywords": [
6
6
  "ci",