@diffci.com/diffci 0.3.53 → 0.3.55

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.
Files changed (130) hide show
  1. package/dist-client/src/client/agent-selection.d.ts +81 -1
  2. package/dist-client/src/client/agent-selection.js +107 -4
  3. package/dist-client/src/client/agent-setup.js +1 -1
  4. package/dist-client/src/client/cli.js +140 -18
  5. package/dist-client/src/client/command-batches.js +3 -2
  6. package/dist-client/src/client/context.js +32 -2
  7. package/dist-client/src/client/coverage-map.js +6 -1
  8. package/dist-client/src/client/full-command.js +19 -14
  9. package/dist-client/src/client/hook.d.ts +17 -0
  10. package/dist-client/src/client/hook.js +53 -1
  11. package/dist-client/src/client/install.d.ts +6 -0
  12. package/dist-client/src/client/install.js +30 -1
  13. package/dist-client/src/client/isolated-worktree.d.ts +31 -0
  14. package/dist-client/src/client/isolated-worktree.js +130 -0
  15. package/dist-client/src/client/mcp.js +23 -4
  16. package/dist-client/src/client/observe.d.ts +2 -0
  17. package/dist-client/src/client/observe.js +7 -2
  18. package/dist-client/src/client/report.d.ts +1 -1
  19. package/dist-client/src/client/shared-graph-cache.js +4 -2
  20. package/dist-client/src/client/telemetry.js +2 -1
  21. package/dist-client/src/client/usage-signal.d.ts +1 -1
  22. package/dist-client/src/client/verify-savings.d.ts +6 -0
  23. package/dist-client/src/client/verify-savings.js +15 -3
  24. package/dist-client/src/client/verify.d.ts +47 -3
  25. package/dist-client/src/client/verify.js +244 -22
  26. package/dist-client/src/client/working-tree.d.ts +22 -0
  27. package/dist-client/src/client/working-tree.js +45 -6
  28. package/node_modules/@diffci.com/core/README.md +17 -10
  29. package/node_modules/@diffci.com/core/dist/ci-inference/expression.d.ts +5 -0
  30. package/node_modules/@diffci.com/core/dist/ci-inference/expression.js +38 -5
  31. package/node_modules/@diffci.com/core/dist/ci-inference/expression.js.map +1 -1
  32. package/node_modules/@diffci.com/core/dist/ci-inference/infer.js +26 -6
  33. package/node_modules/@diffci.com/core/dist/ci-inference/infer.js.map +1 -1
  34. package/node_modules/@diffci.com/core/dist/ci-inference/jobs.d.ts +2 -1
  35. package/node_modules/@diffci.com/core/dist/ci-inference/jobs.js +7 -2
  36. package/node_modules/@diffci.com/core/dist/ci-inference/jobs.js.map +1 -1
  37. package/node_modules/@diffci.com/core/dist/ci-inference/matrix.js +15 -8
  38. package/node_modules/@diffci.com/core/dist/ci-inference/matrix.js.map +1 -1
  39. package/node_modules/@diffci.com/core/dist/ci-inference/purpose.js +6 -2
  40. package/node_modules/@diffci.com/core/dist/ci-inference/purpose.js.map +1 -1
  41. package/node_modules/@diffci.com/core/dist/ci-inference/resolve.js +19 -4
  42. package/node_modules/@diffci.com/core/dist/ci-inference/resolve.js.map +1 -1
  43. package/node_modules/@diffci.com/core/dist/git/ci-config-paths.js +13 -1
  44. package/node_modules/@diffci.com/core/dist/git/ci-config-paths.js.map +1 -1
  45. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +5 -0
  46. package/node_modules/@diffci.com/core/dist/git/git-diff.js +22 -20
  47. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  48. package/node_modules/@diffci.com/core/dist/planner/check-narrowing.js +22 -1
  49. package/node_modules/@diffci.com/core/dist/planner/check-narrowing.js.map +1 -1
  50. package/node_modules/@diffci.com/core/dist/planner/pipeline-steps.d.ts +6 -0
  51. package/node_modules/@diffci.com/core/dist/planner/pipeline-steps.js +14 -2
  52. package/node_modules/@diffci.com/core/dist/planner/pipeline-steps.js.map +1 -1
  53. package/node_modules/@diffci.com/core/dist/planner/planner.js +65 -14
  54. package/node_modules/@diffci.com/core/dist/planner/planner.js.map +1 -1
  55. package/node_modules/@diffci.com/core/dist/planner/rust-command.js +43 -1
  56. package/node_modules/@diffci.com/core/dist/planner/rust-command.js.map +1 -1
  57. package/node_modules/@diffci.com/core/dist/planner/script-reads.js +5 -2
  58. package/node_modules/@diffci.com/core/dist/planner/script-reads.js.map +1 -1
  59. package/node_modules/@diffci.com/core/dist/planner/test-command.js +17 -2
  60. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  61. package/node_modules/@diffci.com/core/dist/planner/type-program.js +27 -1
  62. package/node_modules/@diffci.com/core/dist/planner/type-program.js.map +1 -1
  63. package/node_modules/@diffci.com/core/dist/repo/adapters/go.js +5 -1
  64. package/node_modules/@diffci.com/core/dist/repo/adapters/go.js.map +1 -1
  65. package/node_modules/@diffci.com/core/dist/repo/adapters/maven.js +21 -2
  66. package/node_modules/@diffci.com/core/dist/repo/adapters/maven.js.map +1 -1
  67. package/node_modules/@diffci.com/core/dist/repo/adapters/python.d.ts +9 -1
  68. package/node_modules/@diffci.com/core/dist/repo/adapters/python.js +158 -14
  69. package/node_modules/@diffci.com/core/dist/repo/adapters/python.js.map +1 -1
  70. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.d.ts +1 -0
  71. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.js +180 -15
  72. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.js.map +1 -1
  73. package/node_modules/@diffci.com/core/dist/repo/adapters/types.d.ts +7 -0
  74. package/node_modules/@diffci.com/core/dist/repo/adapters/types.js.map +1 -1
  75. package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +16 -0
  76. package/node_modules/@diffci.com/core/dist/repo/file-references.js +76 -5
  77. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  78. package/node_modules/@diffci.com/core/dist/repo/graph.js +100 -29
  79. package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
  80. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +7 -0
  81. package/node_modules/@diffci.com/core/dist/repo/impact.js +55 -8
  82. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  83. package/node_modules/@diffci.com/core/dist/repo/layout.js +4 -1
  84. package/node_modules/@diffci.com/core/dist/repo/layout.js.map +1 -1
  85. package/node_modules/@diffci.com/core/dist/repo/runner-universe.js +10 -1
  86. package/node_modules/@diffci.com/core/dist/repo/runner-universe.js.map +1 -1
  87. package/node_modules/@diffci.com/core/dist/repo/script-universe.js +1 -1
  88. package/node_modules/@diffci.com/core/dist/repo/script-universe.js.map +1 -1
  89. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js +5 -1
  90. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js.map +1 -1
  91. package/node_modules/@diffci.com/core/dist/repo/types.d.ts +3 -0
  92. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js +3 -3
  93. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js.map +1 -1
  94. package/node_modules/@diffci.com/core/dist/research/baseline/matcher.js +65 -13
  95. package/node_modules/@diffci.com/core/dist/research/baseline/matcher.js.map +1 -1
  96. package/node_modules/@diffci.com/core/dist/research/baseline/workflow-parser.js +47 -2
  97. package/node_modules/@diffci.com/core/dist/research/baseline/workflow-parser.js.map +1 -1
  98. package/node_modules/@diffci.com/core/package.json +1 -0
  99. package/node_modules/@diffci.com/core/src/ci-inference/expression.ts +38 -5
  100. package/node_modules/@diffci.com/core/src/ci-inference/infer.ts +21 -6
  101. package/node_modules/@diffci.com/core/src/ci-inference/jobs.ts +7 -2
  102. package/node_modules/@diffci.com/core/src/ci-inference/matrix.ts +15 -8
  103. package/node_modules/@diffci.com/core/src/ci-inference/purpose.ts +6 -2
  104. package/node_modules/@diffci.com/core/src/ci-inference/resolve.ts +18 -4
  105. package/node_modules/@diffci.com/core/src/git/ci-config-paths.ts +8 -1
  106. package/node_modules/@diffci.com/core/src/git/git-diff.ts +20 -21
  107. package/node_modules/@diffci.com/core/src/planner/check-narrowing.ts +22 -1
  108. package/node_modules/@diffci.com/core/src/planner/pipeline-steps.ts +13 -2
  109. package/node_modules/@diffci.com/core/src/planner/planner.ts +42 -14
  110. package/node_modules/@diffci.com/core/src/planner/rust-command.ts +37 -1
  111. package/node_modules/@diffci.com/core/src/planner/script-reads.ts +5 -1
  112. package/node_modules/@diffci.com/core/src/planner/test-command.ts +17 -2
  113. package/node_modules/@diffci.com/core/src/planner/type-program.ts +25 -1
  114. package/node_modules/@diffci.com/core/src/repo/adapters/go.ts +5 -1
  115. package/node_modules/@diffci.com/core/src/repo/adapters/maven.ts +20 -2
  116. package/node_modules/@diffci.com/core/src/repo/adapters/python.ts +133 -14
  117. package/node_modules/@diffci.com/core/src/repo/adapters/rust.ts +136 -16
  118. package/node_modules/@diffci.com/core/src/repo/adapters/types.ts +7 -1
  119. package/node_modules/@diffci.com/core/src/repo/file-references.ts +70 -5
  120. package/node_modules/@diffci.com/core/src/repo/graph.ts +81 -20
  121. package/node_modules/@diffci.com/core/src/repo/impact.ts +56 -7
  122. package/node_modules/@diffci.com/core/src/repo/layout.ts +5 -1
  123. package/node_modules/@diffci.com/core/src/repo/runner-universe.ts +11 -1
  124. package/node_modules/@diffci.com/core/src/repo/script-universe.ts +1 -1
  125. package/node_modules/@diffci.com/core/src/repo/test-discovery.ts +4 -1
  126. package/node_modules/@diffci.com/core/src/repo/types.ts +3 -1
  127. package/node_modules/@diffci.com/core/src/repo/workflow-test-steps.ts +3 -3
  128. package/node_modules/@diffci.com/core/src/research/baseline/matcher.ts +43 -13
  129. package/node_modules/@diffci.com/core/src/research/baseline/workflow-parser.ts +44 -2
  130. package/package.json +2 -2
@@ -39,3 +39,20 @@ export declare function isGitRepository(repoPath: string): boolean;
39
39
  /** Writes the hook into the directory Git actually runs hooks from (`core.hooksPath` included, such as
40
40
  * `.husky`). An existing hook DiffCI did not write is kept unless `force` is set. */
41
41
  export declare function installPrePushHook(repoPath: string, command: string, force: boolean): string;
42
+ /** The DiffCI command a managed hook was written for, read from its in-place verify line (every version has it). */
43
+ export declare function hookCommandOf(hook: string): string | undefined;
44
+ /**
45
+ * Keeps an installed DiffCI pre-push hook current (2026-11-17).
46
+ *
47
+ * WHY. Repositories keep the hook `diffci init` wrote first, so hook fixes never reached them. DentalPresence's
48
+ * hook of 8 Nov predated the not-installed fix: pushing from a worktree without node_modules, npx printed a
49
+ * 404, the old hook read it as failing tests and blocked a correct push. The current hook says it could not
50
+ * verify and lets the push through.
51
+ *
52
+ * WHAT. When it differs from the hook this version writes for the same command, a hook with DiffCI's marker is
53
+ * replaced; any other hook is never touched. The new file is written beside it and renamed over it, so a
54
+ * hook another push is running keeps reading the old file. Callers run it only outside the hook's own
55
+ * commands (verify of the working tree, the index or paths, never `verify --base/--head`) and ignore any
56
+ * error. `DIFFCI_HOOK_REFRESH=0` turns it off.
57
+ */
58
+ export declare function refreshPrePushHook(repoPath: string): string | undefined;
@@ -1,5 +1,5 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { dirname, isAbsolute, join, relative } from "node:path";
4
4
  /**
5
5
  * The pre-push hook `diffci init` installs (2026-10-28; on by default since 0.3.24).
@@ -208,3 +208,55 @@ export function installPrePushHook(repoPath, command, force) {
208
208
  catch { /* Git for Windows runs hooks through sh regardless of mode. */ }
209
209
  return `wrote ${shown} (verifies pushed commits; skip once with git push --no-verify)`;
210
210
  }
211
+ /** The DiffCI command a managed hook was written for, read from its in-place verify line (every version has it). */
212
+ export function hookCommandOf(hook) {
213
+ const match = /^[ \t]*(\S.*?) verify --base "\$base" --head "\$local_sha" <\/dev\/null[ \t]*$/m.exec(hook.replace(/\r\n/g, "\n"));
214
+ return match?.[1];
215
+ }
216
+ /**
217
+ * Keeps an installed DiffCI pre-push hook current (2026-11-17).
218
+ *
219
+ * WHY. Repositories keep the hook `diffci init` wrote first, so hook fixes never reached them. DentalPresence's
220
+ * hook of 8 Nov predated the not-installed fix: pushing from a worktree without node_modules, npx printed a
221
+ * 404, the old hook read it as failing tests and blocked a correct push. The current hook says it could not
222
+ * verify and lets the push through.
223
+ *
224
+ * WHAT. When it differs from the hook this version writes for the same command, a hook with DiffCI's marker is
225
+ * replaced; any other hook is never touched. The new file is written beside it and renamed over it, so a
226
+ * hook another push is running keeps reading the old file. Callers run it only outside the hook's own
227
+ * commands (verify of the working tree, the index or paths, never `verify --base/--head`) and ignore any
228
+ * error. `DIFFCI_HOOK_REFRESH=0` turns it off.
229
+ */
230
+ export function refreshPrePushHook(repoPath) {
231
+ const hooksDir = execFileSync("git", ["rev-parse", "--git-path", "hooks"], { cwd: repoPath, encoding: "utf8", windowsHide: true, stdio: ["ignore", "pipe", "ignore"] }).trim();
232
+ const hookPath = join(isAbsolute(hooksDir) ? hooksDir : join(repoPath, hooksDir), "pre-push");
233
+ if (!existsSync(hookPath))
234
+ return undefined;
235
+ const existing = readFileSync(hookPath, "utf8");
236
+ if (!existing.includes(HOOK_MARKER))
237
+ return undefined;
238
+ const command = hookCommandOf(existing);
239
+ if (!command)
240
+ return undefined;
241
+ const content = prePushHook(command);
242
+ if (existing.replace(/\r\n/g, "\n") === content)
243
+ return undefined;
244
+ const temporary = `${hookPath}.diffci-${process.pid}`;
245
+ writeFileSync(temporary, content, "utf8");
246
+ try {
247
+ chmodSync(temporary, 0o755);
248
+ }
249
+ catch { /* Git for Windows runs hooks through sh regardless of mode. */ }
250
+ try {
251
+ renameSync(temporary, hookPath);
252
+ }
253
+ catch (error) {
254
+ try {
255
+ unlinkSync(temporary);
256
+ }
257
+ catch { /* nothing left to clean */ }
258
+ throw error;
259
+ }
260
+ const shown = relative(repoPath, hookPath).replace(/\\/g, "/") || hookPath;
261
+ return `diffci: updated the DiffCI pre-push hook ${shown} to this version's (same command: ${command}); DIFFCI_HOOK_REFRESH=0 turns this off`;
262
+ }
@@ -11,6 +11,12 @@ export interface PackageScriptResult {
11
11
  kept: string[];
12
12
  }
13
13
  export declare function detectPackageManager(repoPath: string): SupportedPackageManager;
14
+ /**
15
+ * Whether the repository uses Yarn 2 or later (Berry). Berry's `yarn add` rejects `--ignore-scripts`
16
+ * ("Unsupported option name") and skips build scripts with `--mode=skip-build` instead. The declared
17
+ * packageManager version decides; without one, a .yarnrc.yml or a Berry lockfile (`__metadata:`) does.
18
+ */
19
+ export declare function usesYarnBerry(repoPath: string): boolean;
14
20
  export declare function installPlan(repoPath: string, version: string, platform?: NodeJS.Platform): InstallPlan;
15
21
  export declare function installDiffci(repoPath: string, version: string, run?: typeof spawnSync, packageSpecOverride?: string): {
16
22
  plan: InstallPlan;
@@ -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
  };
@@ -40,6 +41,32 @@ export function detectPackageManager(repoPath) {
40
41
  }
41
42
  return detected.values().next().value ?? "npm";
42
43
  }
44
+ /**
45
+ * Whether the repository uses Yarn 2 or later (Berry). Berry's `yarn add` rejects `--ignore-scripts`
46
+ * ("Unsupported option name") and skips build scripts with `--mode=skip-build` instead. The declared
47
+ * packageManager version decides; without one, a .yarnrc.yml or a Berry lockfile (`__metadata:`) does.
48
+ */
49
+ export function usesYarnBerry(repoPath) {
50
+ const packagePath = join(repoPath, "package.json");
51
+ let declared;
52
+ try {
53
+ declared = JSON.parse(readFileSync(packagePath, "utf8")).packageManager;
54
+ }
55
+ catch {
56
+ declared = undefined;
57
+ }
58
+ const version = typeof declared === "string" ? /^yarn@(\d+)/.exec(declared.trim()) : null;
59
+ if (version)
60
+ return Number(version[1]) >= 2;
61
+ if (existsSync(join(repoPath, ".yarnrc.yml")))
62
+ return true;
63
+ try {
64
+ return /^__metadata:/m.test(readFileSync(join(repoPath, "yarn.lock"), "utf8"));
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ }
43
70
  export function installPlan(repoPath, version, platform = process.platform) {
44
71
  const manager = detectPackageManager(repoPath);
45
72
  const packageSpec = `@diffci.com/diffci@${version}`;
@@ -47,7 +74,9 @@ export function installPlan(repoPath, version, platform = process.platform) {
47
74
  const argsByManager = {
48
75
  npm: ["install", "--save-dev", "--save-exact", "--ignore-scripts", packageSpec],
49
76
  pnpm: ["add", "--save-dev", "--save-exact", "--ignore-scripts", packageSpec],
50
- yarn: ["add", "--dev", "--exact", "--ignore-scripts", packageSpec],
77
+ yarn: manager === "yarn" && usesYarnBerry(repoPath)
78
+ ? ["add", "--dev", "--exact", "--mode=skip-build", packageSpec]
79
+ : ["add", "--dev", "--exact", "--ignore-scripts", packageSpec],
51
80
  bun: ["add", "--dev", "--exact", "--ignore-scripts", packageSpec],
52
81
  };
53
82
  const managerArgs = argsByManager[manager];
@@ -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
  },
@@ -223,6 +227,10 @@ async function handle(request) {
223
227
  return;
224
228
  case "notifications/initialized":
225
229
  return;
230
+ // Either side may ping at any time, before or after initialization; the answer is an empty result.
231
+ case "ping":
232
+ success(id, {});
233
+ return;
226
234
  case "tools/list":
227
235
  success(id, { tools });
228
236
  return;
@@ -241,7 +249,10 @@ async function handle(request) {
241
249
  const properties = tool.inputSchema.properties;
242
250
  for (const [key, value] of Object.entries(args)) {
243
251
  const property = properties[key];
244
- if (!property || typeof value !== property.type || (key === "timeoutMs" && (!Number.isFinite(value) || value < 0))) {
252
+ const typed = property?.type === "array"
253
+ ? Array.isArray(value) && value.every((item) => typeof item === "string" && item.trim() !== "")
254
+ : property !== undefined && typeof value === property.type && (!property.enum || property.enum.includes(value));
255
+ if (!typed || (key === "timeoutMs" && (!Number.isFinite(value) || value < 0))) {
245
256
  failure(id, -32602, `invalid argument: ${key}`);
246
257
  return;
247
258
  }
@@ -253,7 +264,15 @@ async function handle(request) {
253
264
  success(id, { content: [{ type: "text", text: JSON.stringify(changes) }], structuredContent: changes, isError: changes.status === "blocked" });
254
265
  return;
255
266
  }
256
- const plan = await agentSelection(repo);
267
+ const scope = stringArg(args, "scope") ?? "working-tree";
268
+ const paths = Array.isArray(args.paths) ? args.paths : undefined;
269
+ if ((scope === "paths") !== (paths !== undefined && paths.length > 0)) {
270
+ failure(id, -32602, scope === "paths" ? "scope \"paths\" needs a non-empty paths array" : "paths applies only to scope \"paths\"");
271
+ return;
272
+ }
273
+ const plan = scope === "staged" ? await agentScopedSelection(repo, { kind: "staged" })
274
+ : scope === "paths" ? await agentScopedSelection(repo, { kind: "paths", paths: paths.map((path) => path.replace(/\\/g, "/")) })
275
+ : await agentSelection(repo);
257
276
  success(id, { content: [{ type: "text", text: `${selectionInstruction(plan)}\n\n${JSON.stringify(plan)}` }], structuredContent: plan, isError: plan.status === "blocked" });
258
277
  return;
259
278
  }
@@ -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
  /**
@@ -91,7 +91,8 @@ export async function observe(options) {
91
91
  const repoPath = resolve(options.repoPath);
92
92
  const git = options.git ?? makeGitRunner(repoPath);
93
93
  const ci = readCiEnvironment(options.env);
94
- const [owner, name] = (ci.ownerName ?? "").split("/");
94
+ // GitLab's CI_PROJECT_PATH may name subgroups (group/sub/project): keep every segment, not the first two.
95
+ const ownerName = ci.ownerName && /^[^/]+(?:\/[^/]+)+$/.test(ci.ownerName) ? ci.ownerName : undefined;
95
96
  const before = { head: headSha(git), worktree: worktreeDigest(git) };
96
97
  const hashPath = (path) => (options.redactPaths ? redactPath(path, sha256) : path);
97
98
  // Declared before `finish` closes over it: the range is part of every report, including the reports
@@ -124,7 +125,7 @@ export async function observe(options) {
124
125
  },
125
126
  repository: {
126
127
  provider: ci.provider === "github-actions" ? "github" : ci.provider === "gitlab-ci" ? "gitlab" : "unknown",
127
- ownerName: owner && name ? `${owner}/${name}` : undefined,
128
+ ownerName,
128
129
  defaultBranch: ci.defaultBranch,
129
130
  providerRepositoryId: ci.providerRepositoryId,
130
131
  },
@@ -224,6 +225,10 @@ export async function observe(options) {
224
225
  catch { /* caching never fails an observation */ }
225
226
  }
226
227
  markPhase(cachedGraph ? "graphCached" : "graph");
228
+ try {
229
+ options.onGraph?.(graphResult);
230
+ }
231
+ catch { /* a reader of the graph never fails an observation */ }
227
232
  if (graphResult.graph.nodes.length === 0) {
228
233
  return finish("REFUSED", "graph", {
229
234
  reason: "the dependency graph came back empty - DiffCI will not propose a selection from a graph that sees none of this repository" +
@@ -37,7 +37,7 @@ export interface ObservationCommitRange {
37
37
  }
38
38
  export interface ObservationRepository {
39
39
  provider: "github" | "gitlab" | "unknown";
40
- /** "owner/name". The only repository identifier sent; never a URL carrying a token. */
40
+ /** "owner/name", or GitLab's full "group/subgroup/name" path. The only repository identifier sent; never a URL carrying a token. */
41
41
  ownerName?: string;
42
42
  defaultBranch?: string;
43
43
  /** GitHub's numeric repository id when the environment supplies it - survives a rename. */
@@ -327,14 +327,16 @@ export function configureGraphCache(input) {
327
327
  if (input.shared) {
328
328
  const baseUrl = resolveSharedGraphCacheBaseUrl({ cacheUrl: input.cacheUrl, apiUrl: input.apiUrl });
329
329
  const secret = input.secret && input.secret.length >= 16 ? input.secret : undefined;
330
- if (input.secret && !secret)
331
- notes.push("DIFFCI_GRAPH_CACHE_SECRET ignored: it must be at least 16 characters");
332
330
  if (input.noSend)
333
331
  notes.push("shared graph cache off: --no-send");
334
332
  else if (!baseUrl)
335
333
  notes.push("shared graph cache off: no https api-url or graph-cache-url");
336
334
  else if (!input.token)
337
335
  notes.push("shared graph cache off: no api-token");
336
+ // A secret that is set asks for encryption: one too short to use must not fall back to plaintext uploads.
337
+ // An empty value counts as set: `DIFFCI_GRAPH_CACHE_SECRET: ${{ secrets.X }}` is empty when X is missing.
338
+ else if (input.secret !== undefined && !secret)
339
+ notes.push("shared graph cache off: DIFFCI_GRAPH_CACHE_SECRET must be at least 16 characters");
338
340
  else if (input.redactPaths && !secret)
339
341
  notes.push("shared graph cache off: --redact-paths needs DIFFCI_GRAPH_CACHE_SECRET, because the graph carries file paths");
340
342
  else
@@ -96,7 +96,8 @@ export function repositoryName(repoPath, env) {
96
96
  function surfaceOf(env) {
97
97
  if (env.DIFFCI_MCP === "1")
98
98
  return "local-mcp";
99
- if (env.DIFFCI_SURFACE === "github-action" || env.DIFFCI_SURFACE === "gitlab-component")
99
+ // Each CI wrapper sets its own value: action/, integrations/gitlab and integrations/azure-devops (#303).
100
+ if (env.DIFFCI_SURFACE === "github-action" || env.DIFFCI_SURFACE === "gitlab-component" || env.DIFFCI_SURFACE === "azure-devops-task")
100
101
  return env.DIFFCI_SURFACE;
101
102
  return "cli";
102
103
  }
@@ -1,7 +1,7 @@
1
1
  /** Best-effort usage signal. Carries a repository name only when given one; never content, paths or machine details. */
2
2
  export type UsageCommand = "check" | "observe" | "verify" | "plan";
3
3
  export type UsageOutcome = "observed" | "refused" | "error" | "passed" | "failed" | "blocked" | "selective" | "full";
4
- export type UsageSurface = "cli" | "local-mcp" | "github-action" | "gitlab-component";
4
+ export type UsageSurface = "cli" | "local-mcp" | "github-action" | "gitlab-component" | "azure-devops-task";
5
5
  export interface UsageSignal {
6
6
  command: UsageCommand;
7
7
  outcome: UsageOutcome;
@@ -165,6 +165,12 @@ interface ResolvedSelection {
165
165
  observationSha256?: string;
166
166
  observerVersion?: string;
167
167
  }
168
+ /**
169
+ * At most the last `bytes` bytes of `value`, cut at a character boundary. `bytes` 0 keeps nothing:
170
+ * `value.slice(-0)` is the whole string, so `--tail-bytes 0` used to keep the entire output, and a
171
+ * multi-byte tail was cut by characters, not bytes.
172
+ */
173
+ export declare function tail(value: string, bytes: number): string;
168
174
  export declare function measureCommand(command: string, options: Pick<VerifySavingsOptions, "cwd" | "timeoutMs" | "tailBytes"> & {
169
175
  env?: Record<string, string>;
170
176
  }): CommandMeasurement;
@@ -8,10 +8,22 @@ import { windowsLaunch, withPathEntry } from "./node-bin-launch.js";
8
8
  import { runnerTestCount } from "./selected-coverage.js";
9
9
  import { parseTestFileResults } from "./test-results.js";
10
10
  import { classifyFailureFromEvidence, computeFailureFingerprint } from "../preflight/fingerprint.js";
11
- function tail(value, bytes) {
12
- if (Buffer.byteLength(value, "utf8") <= bytes)
11
+ /**
12
+ * At most the last `bytes` bytes of `value`, cut at a character boundary. `bytes` 0 keeps nothing:
13
+ * `value.slice(-0)` is the whole string, so `--tail-bytes 0` used to keep the entire output, and a
14
+ * multi-byte tail was cut by characters, not bytes.
15
+ */
16
+ export function tail(value, bytes) {
17
+ if (!(bytes > 0))
18
+ return "";
19
+ const buffer = Buffer.from(value, "utf8");
20
+ if (buffer.length <= bytes)
13
21
  return value;
14
- return value.slice(-bytes);
22
+ let start = buffer.length - Math.floor(bytes);
23
+ // Skip UTF-8 continuation bytes so the tail never starts inside a character.
24
+ while (start < buffer.length && (buffer[start] & 0xc0) === 0x80)
25
+ start++;
26
+ return buffer.subarray(start).toString("utf8");
15
27
  }
16
28
  function readSelectionFromObservation(path, override) {
17
29
  const absolutePath = resolve(path);
@@ -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;