@diffci.com/diffci 0.3.31 → 0.3.33

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 (70) hide show
  1. package/README.md +23 -0
  2. package/dist-client/src/client/agent-setup.d.ts +18 -0
  3. package/dist-client/src/client/agent-setup.js +77 -0
  4. package/dist-client/src/client/agent-stop.d.ts +52 -0
  5. package/dist-client/src/client/agent-stop.js +101 -0
  6. package/dist-client/src/client/check-plan-junit.d.ts +25 -0
  7. package/dist-client/src/client/check-plan-junit.js +215 -0
  8. package/dist-client/src/client/check-plan.d.ts +42 -0
  9. package/dist-client/src/client/check-plan.js +143 -0
  10. package/dist-client/src/client/cli.js +288 -13
  11. package/dist-client/src/client/command-batches.d.ts +1 -0
  12. package/dist-client/src/client/command-batches.js +3 -1
  13. package/dist-client/src/client/enforce-misses-collect.js +6 -1
  14. package/dist-client/src/client/enforce-misses.d.ts +3 -2
  15. package/dist-client/src/client/enforce-misses.js +19 -59
  16. package/dist-client/src/client/failure-baseline.js +0 -0
  17. package/dist-client/src/client/full-command.d.ts +8 -0
  18. package/dist-client/src/client/full-command.js +31 -0
  19. package/dist-client/src/client/hook.d.ts +1 -1
  20. package/dist-client/src/client/hook.js +1 -1
  21. package/dist-client/src/client/job-summary.d.ts +7 -0
  22. package/dist-client/src/client/job-summary.js +78 -0
  23. package/dist-client/src/client/observe.d.ts +4 -0
  24. package/dist-client/src/client/observe.js +31 -2
  25. package/dist-client/src/client/report.d.ts +4 -0
  26. package/dist-client/src/client/test-results.js +7 -0
  27. package/dist-client/src/client/verify.d.ts +20 -0
  28. package/dist-client/src/client/verify.js +50 -12
  29. package/dist-client/src/client/watch.d.ts +36 -0
  30. package/dist-client/src/client/watch.js +76 -0
  31. package/dist-client/src/client/working-tree.d.ts +13 -0
  32. package/dist-client/src/client/working-tree.js +40 -1
  33. package/node_modules/@diffci.com/core/README.md +36 -5
  34. package/node_modules/@diffci.com/core/dist/cache/graph-cache.d.ts +1 -1
  35. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +3 -1
  36. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js.map +1 -1
  37. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +12 -0
  38. package/node_modules/@diffci.com/core/dist/git/git-diff.js +86 -0
  39. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  40. package/node_modules/@diffci.com/core/dist/git/types.d.ts +8 -0
  41. package/node_modules/@diffci.com/core/dist/planner/test-command.js +16 -0
  42. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  43. package/node_modules/@diffci.com/core/dist/repo/adapters/index.js +2 -1
  44. package/node_modules/@diffci.com/core/dist/repo/adapters/index.js.map +1 -1
  45. package/node_modules/@diffci.com/core/dist/repo/adapters/python.d.ts +32 -0
  46. package/node_modules/@diffci.com/core/dist/repo/adapters/python.js +273 -0
  47. package/node_modules/@diffci.com/core/dist/repo/adapters/python.js.map +1 -0
  48. package/node_modules/@diffci.com/core/dist/repo/adapters/types.d.ts +2 -0
  49. package/node_modules/@diffci.com/core/dist/repo/adapters/types.js.map +1 -1
  50. package/node_modules/@diffci.com/core/dist/repo/file-references.js +21 -0
  51. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  52. package/node_modules/@diffci.com/core/dist/repo/graph.d.ts +4 -0
  53. package/node_modules/@diffci.com/core/dist/repo/graph.js +182 -21
  54. package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
  55. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +1 -0
  56. package/node_modules/@diffci.com/core/dist/repo/impact.js +29 -4
  57. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  58. package/node_modules/@diffci.com/core/dist/repo/types.d.ts +5 -0
  59. package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +3 -1
  60. package/node_modules/@diffci.com/core/src/git/git-diff.ts +72 -0
  61. package/node_modules/@diffci.com/core/src/git/types.ts +5 -0
  62. package/node_modules/@diffci.com/core/src/planner/test-command.ts +14 -0
  63. package/node_modules/@diffci.com/core/src/repo/adapters/index.ts +2 -1
  64. package/node_modules/@diffci.com/core/src/repo/adapters/python.ts +252 -0
  65. package/node_modules/@diffci.com/core/src/repo/adapters/types.ts +2 -0
  66. package/node_modules/@diffci.com/core/src/repo/file-references.ts +19 -0
  67. package/node_modules/@diffci.com/core/src/repo/graph.ts +154 -20
  68. package/node_modules/@diffci.com/core/src/repo/impact.ts +27 -4
  69. package/node_modules/@diffci.com/core/src/repo/types.ts +5 -0
  70. package/package.json +3 -2
@@ -13,27 +13,12 @@
13
13
  * Nothing here changes configuration. A miss produces the exact `enforce.openUnsafeMisses` entry for
14
14
  * a human to add; re-enabling enforcement is never automatic.
15
15
  */
16
+ import { readJunit, junitFile } from "./check-plan-junit.js";
16
17
  import { isAbsolute, relative, resolve } from "node:path";
17
18
  export const MISS_REPORT_SCHEMA = "diffci.enforce-misses.v1";
18
19
  // ---------------------------------------------------------------------------------------------------
19
20
  // JUnit (node:test's `--test-reporter=junit`, which also matches the common Jest/Vitest shape)
20
- function decodeEntities(text) {
21
- return text.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (_, entity) => {
22
- const lower = entity.toLowerCase();
23
- if (lower.startsWith("#x"))
24
- return String.fromCodePoint(Number.parseInt(lower.slice(2), 16));
25
- if (lower.startsWith("#"))
26
- return String.fromCodePoint(Number.parseInt(lower.slice(1), 10));
27
- return { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" }[lower];
28
- });
29
- }
30
- function attributes(source) {
31
- const result = {};
32
- for (const match of source.matchAll(/([\w:.-]+)\s*=\s*"([^"]*)"/g))
33
- result[match[1]] = decodeEntities(match[2]);
34
- return result;
35
- }
36
- /** Repository-relative with forward slashes; paths outside the repository stay absolute. */
21
+ /** Legacy identity normalization: stored v1 detector baselines depend on these exact rules. */
37
22
  export function normalizeTestPath(path, repoRoot) {
38
23
  const slashed = path.replace(/\\/g, "/").replace(/^\.\//, "");
39
24
  if (!slashed)
@@ -43,53 +28,25 @@ export function normalizeTestPath(path, repoRoot) {
43
28
  const inside = relative(resolve(repoRoot), resolve(path));
44
29
  return inside && !inside.startsWith("..") && !isAbsolute(inside) ? inside.replace(/\\/g, "/") : slashed;
45
30
  }
46
- /** Testcases in document order, named by their enclosing suites. Repeated ids are merged: any failure wins. */
31
+ /** Testcases in document order. Repeated ids are merged: any failure wins. */
47
32
  export function parseJunit(xml, repoRoot) {
48
33
  const byId = new Map();
49
- const suites = [];
50
- let current;
51
- const finish = () => {
52
- if (!current)
53
- return;
54
- const seen = byId.get(current.id);
34
+ readJunit(xml, (test, failed, skipped) => {
35
+ const file = junitFile(test, repoRoot);
36
+ const name = [...test.suiteNames, test.name].filter(Boolean).join(" > ");
37
+ const id = `${normalizeTestPath(test.file ?? "", repoRoot)} > ${name}`;
38
+ const seen = byId.get(id);
55
39
  if (seen) {
56
- seen.failed ||= current.failed;
57
- seen.skipped &&= current.skipped;
40
+ seen.failed ||= failed;
41
+ seen.skipped &&= skipped;
42
+ if (test.suiteLevel)
43
+ seen.suiteLevel = true;
44
+ if (seen.file !== file)
45
+ seen.file = "";
58
46
  }
59
47
  else
60
- byId.set(current.id, current);
61
- current = undefined;
62
- };
63
- // Attribute values may hold a raw `>` (failure messages), so the tag body skips over quoted strings.
64
- const tags = /<(\/?)(testsuite|testcase|failure|error|skipped)\b((?:[^>"]|"[^"]*")*?)(\/?)>/g;
65
- for (const [, closing, tag, body, selfClosing] of xml.matchAll(tags)) {
66
- if (tag === "testsuite") {
67
- if (closing)
68
- suites.pop();
69
- else if (!selfClosing)
70
- suites.push(attributes(body).name ?? "");
71
- }
72
- else if (tag === "testcase") {
73
- if (closing) {
74
- finish();
75
- continue;
76
- }
77
- finish();
78
- const attrs = attributes(body);
79
- const file = normalizeTestPath(attrs.file ?? "", repoRoot);
80
- const name = [...suites, attrs.name ?? ""].filter(Boolean).join(" > ");
81
- current = { id: `${file} > ${name}`, file, name, failed: attrs.failure !== undefined, skipped: false };
82
- if (selfClosing)
83
- finish();
84
- }
85
- else if (current && !closing) {
86
- if (tag === "skipped")
87
- current.skipped = true;
88
- else
89
- current.failed = true;
90
- }
91
- }
92
- finish();
48
+ byId.set(id, { id, file, name, failed, skipped, ...(test.suiteLevel ? { suiteLevel: true } : {}) });
49
+ });
93
50
  return [...byId.values()];
94
51
  }
95
52
  // ---------------------------------------------------------------------------------------------------
@@ -141,6 +98,9 @@ export function classifyFailures(input) {
141
98
  if (baseline.has(outcome.id)) {
142
99
  return { ...base, classification: "pre-existing", pull_requests: [], detail: `already failing at the start of the window; ${rerunNote}` };
143
100
  }
101
+ if (outcome.suiteLevel || !outcome.file) {
102
+ return { ...base, classification: "unattributed", pull_requests: [], detail: `no testcase file identity; cannot attribute this failure to a pull request; ${rerunNote}` };
103
+ }
144
104
  const pullRequests = input.pullRequests.map((pr) => ({
145
105
  number: pr.number,
146
106
  verdict: verdict(pr, outcome.file),
@@ -8,6 +8,14 @@ export declare function inferSelectedCommands(repoPath: string, proposed: readon
8
8
  commands?: string[];
9
9
  reason: string;
10
10
  };
11
+ /** The planner's commands for `tests` on their own, rebuilt from the repository (a FULL observation
12
+ * reports none): several already split to fit the shell, or one whole command for the caller to check
13
+ * and split. Undefined when the planner refuses them. */
14
+ export declare function inferPlannedCommands(repoPath: string, tests: readonly string[]): {
15
+ commands: string[];
16
+ } | {
17
+ single: string;
18
+ } | undefined;
11
19
  /** Rebuild the complete plan locally; never join arbitrary report commands. */
12
20
  export declare function inferWorkspaceComparison(repoPath: string, proposed: readonly string[], selectedTests: readonly string[]): {
13
21
  full?: string;
@@ -1,3 +1,4 @@
1
+ import { spawnSync } from "node:child_process";
1
2
  import { existsSync, readFileSync } from "node:fs";
2
3
  import { join } from "node:path";
3
4
  import { readRepositoryConfig } from "@diffci.com/core/repo/repo-config";
@@ -25,6 +26,21 @@ export function inferSelectedCommands(repoPath, proposed, selectedTests) {
25
26
  });
26
27
  return { commands, reason: `${plan.commands.length} commands from the verified plan` };
27
28
  }
29
+ /** The planner's commands for `tests` on their own, rebuilt from the repository (a FULL observation
30
+ * reports none): several already split to fit the shell, or one whole command for the caller to check
31
+ * and split. Undefined when the planner refuses them. */
32
+ export function inferPlannedCommands(repoPath, tests) {
33
+ const plan = planSelectiveTestCommands(analyzeRepository({ repoPath }), tests);
34
+ if (plan.refusalReason || plan.commands.length === 0)
35
+ return undefined;
36
+ const proposed = plan.commands.map(commandSpecToString);
37
+ if (proposed.length > 1) {
38
+ const commands = inferSelectedCommands(repoPath, proposed, tests).commands;
39
+ return commands ? { commands } : undefined;
40
+ }
41
+ const single = inferSelectedCommand(repoPath, proposed[0], tests).command;
42
+ return single ? { single } : undefined;
43
+ }
28
44
  /** Rebuild the complete plan locally; never join arbitrary report commands. */
29
45
  export function inferWorkspaceComparison(repoPath, proposed, selectedTests) {
30
46
  const profile = analyzeRepository({ repoPath });
@@ -155,5 +171,20 @@ export function inferFullCommand(repoPath) {
155
171
  }
156
172
  if (existsSync(join(repoPath, "go.mod")))
157
173
  return { command: "go test ./...", reason: "root Go module" };
174
+ // Python projects run pytest with the interpreter Core's Python adapter would find (2026-11-06).
175
+ if (["pyproject.toml", "setup.py", "setup.cfg", "pytest.ini", "tox.ini", "conftest.py"].some((file) => existsSync(join(repoPath, file)))) {
176
+ const interpreter = pythonInterpreter(repoPath);
177
+ return interpreter
178
+ ? { command: `${interpreter} -m pytest`, reason: "Python project tested with pytest" }
179
+ : { reason: "Python project, but no Python 3 interpreter (python3, python or py -3) is on PATH" };
180
+ }
158
181
  return { reason: "no supported full test command could be inferred" };
159
182
  }
183
+ function pythonInterpreter(cwd) {
184
+ for (const candidate of [["python3"], ["python"], ["py", "-3"]]) {
185
+ const result = spawnSync(candidate[0], [...candidate.slice(1), "-c", "import sys; print(sys.version_info[0])"], { cwd, encoding: "utf8", timeout: 10_000, windowsHide: true });
186
+ if (result.status === 0 && result.stdout.trim() === "3")
187
+ return candidate.join(" ");
188
+ }
189
+ return undefined;
190
+ }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The pre-push hook `diffci init --hook` installs (2026-10-28).
2
+ * The pre-push hook `diffci init` installs (2026-10-28; on by default since 0.3.24).
3
3
  *
4
4
  * WHY. In 449 agent sessions on DentalPresence, agents ran DiffCI in 24 of over 1,500 test commands:
5
5
  * they picked test files themselves (928) or ran the whole suite (282), and 104 pushes then failed the
@@ -2,7 +2,7 @@ import { execFileSync } from "node:child_process";
2
2
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { dirname, isAbsolute, join, relative } from "node:path";
4
4
  /**
5
- * The pre-push hook `diffci init --hook` installs (2026-10-28).
5
+ * The pre-push hook `diffci init` installs (2026-10-28; on by default since 0.3.24).
6
6
  *
7
7
  * WHY. In 449 agent sessions on DentalPresence, agents ran DiffCI in 24 of over 1,500 test commands:
8
8
  * they picked test files themselves (928) or ran the whole suite (282), and 104 pushes then failed the
@@ -0,0 +1,7 @@
1
+ import type { ObservationReport } from "./report.js";
2
+ /**
3
+ * The GitHub job summary for `diffci observe`: the place most people will ever read a report, so it
4
+ * leads with the answer (what this change affects) and keeps the full text summary one click away.
5
+ * It claims nothing the report doesn't: no savings, and every fallback and refusal says so.
6
+ */
7
+ export declare function formatJobSummary(report: ObservationReport, textSummary: string, delivery?: string): string;
@@ -0,0 +1,78 @@
1
+ /** Selected tests listed by name before the rest collapse into a count. */
2
+ const MAX_LISTED_TESTS = 20;
3
+ /** Inline code that survives any path: no backticks to close it early, no pipes to split a table cell. */
4
+ function code(text) {
5
+ return `\`${text.replace(/`/g, "'").replace(/\|/g, "\\|")}\``;
6
+ }
7
+ function plural(count, one, many = `${one}s`) {
8
+ return `${count} ${count === 1 ? one : many}`;
9
+ }
10
+ /** `DIRECT_IMPORT` reads as "direct import"; prose reasons pass through. */
11
+ function readableReason(reason) {
12
+ return /^[A-Z0-9_]+$/.test(reason) ? reason.toLowerCase().replace(/_/g, " ") : reason;
13
+ }
14
+ /**
15
+ * The GitHub job summary for `diffci observe`: the place most people will ever read a report, so it
16
+ * leads with the answer (what this change affects) and keeps the full text summary one click away.
17
+ * It claims nothing the report doesn't: no savings, and every fallback and refusal says so.
18
+ */
19
+ export function formatJobSummary(report, textSummary, delivery) {
20
+ const lines = ["### DiffCI: what this change affects", ""];
21
+ const result = report.result;
22
+ if (report.status !== "OBSERVED" || !result) {
23
+ lines.push(`**No plan for this change** (${report.status.toLowerCase()} at ${report.stage}).`);
24
+ if (report.reason)
25
+ lines.push("", report.reason);
26
+ }
27
+ else if (result.mode === "FULL") {
28
+ lines.push(`**The full test suite is needed** for ${plural(result.changedFileCount, "changed file")}: DiffCI could not prove which of the ${plural(result.totalTestCount, "test file")} this change leaves untouched, so it would run them all.`);
29
+ if (result.fallbackReasons.length > 0) {
30
+ lines.push("", "Why:");
31
+ for (const reason of result.fallbackReasons)
32
+ lines.push(`- ${reason}`);
33
+ }
34
+ }
35
+ else {
36
+ const selected = result.selectedTests.length;
37
+ lines.push(`**${selected} of ${plural(result.totalTestCount, "test file")}** ${selected === 1 ? "is" : "are"} affected by ${plural(result.changedFileCount, "changed file")}.`);
38
+ const baseline = result.pathBaseline.mode === "FULL"
39
+ ? "everything"
40
+ : plural(result.pathBaseline.selectedTestCount, "test file");
41
+ lines.push(`A simple path-rule CI would have run ${baseline}.`);
42
+ if (selected > 0) {
43
+ const reasons = result.selectionReasons ?? {};
44
+ lines.push("", `<details><summary>Why these ${plural(selected, "test")}</summary>`, "");
45
+ lines.push("| Test | Because |", "| --- | --- |");
46
+ for (const test of result.selectedTests.slice(0, MAX_LISTED_TESTS)) {
47
+ const why = reasons[test];
48
+ const because = why
49
+ ? `${readableReason(why.reason)}${why.changed_file ? ` from ${code(why.changed_file)}` : ""}`
50
+ : "affected by the change";
51
+ lines.push(`| ${code(test)} | ${because} |`);
52
+ }
53
+ if (selected > MAX_LISTED_TESTS)
54
+ lines.push(`| and ${selected - MAX_LISTED_TESTS} more | see the report artifact |`);
55
+ lines.push("", "</details>");
56
+ }
57
+ if (result.proposedCommands.length > 0) {
58
+ lines.push("", "Would run:", "");
59
+ for (const command of result.proposedCommands)
60
+ lines.push("```", command, "```");
61
+ }
62
+ else if (result.commandRefusalReason) {
63
+ lines.push("", `No runnable command: ${result.commandRefusalReason}`);
64
+ }
65
+ }
66
+ // A broken promise of non-interference is the one thing that must never hide in a collapsed block.
67
+ const blocking = report.nonInterference.workflowFindings.filter((finding) => finding.severity === "BLOCKING");
68
+ if (!report.nonInterference.worktreeUnchanged) {
69
+ lines.push("", "> [!WARNING]", "> The working tree changed while DiffCI observed it. Please report this at https://github.com/DiffCI/core/issues.");
70
+ }
71
+ if (blocking.length > 0) {
72
+ lines.push("", "> [!WARNING]", `> ${plural(blocking.length, "blocking workflow finding")}: this installation can affect other jobs. Details are in the full report below.`);
73
+ }
74
+ if (delivery?.startsWith("not sent"))
75
+ lines.push("", `Delivery: ${delivery}`);
76
+ lines.push("", "<details><summary>Full report</summary>", "", "```", `${textSummary}${delivery ? `\n delivery: ${delivery}` : ""}`, "```", "", "</details>", "", "<sub>Observation only: DiffCI ran, skipped and changed nothing in this job. [DiffCI](https://github.com/DiffCI/core) is open source (MIT) and tells AI coding agents what their change breaks.</sub>", "");
77
+ return lines.join("\n");
78
+ }
@@ -50,3 +50,7 @@ export declare function makeGitRunner(repoPath: string): GitRunner;
50
50
  */
51
51
  export declare function isInsideRepository(repoPath: string, candidate: string): boolean;
52
52
  export declare function observe(options: ObserveOptions): Promise<ObservationReport>;
53
+ /** Why tests outside the full suite cannot run from the root, when they sit in a project with its own
54
+ * lockfile: the root install does not install it (2026-11-06: LobeHub's apps/desktop, a separate pnpm
55
+ * project, left 8 affected tests unrun with only "outside the default runner configuration" to say why). */
56
+ export declare function separateProjectReason(repoPath: string, tests: readonly string[], hashPath?: (path: string) => string): string | undefined;
@@ -21,7 +21,8 @@
21
21
  */
22
22
  import { execFileSync } from "node:child_process";
23
23
  import { createHash } from "node:crypto";
24
- import { relative, resolve } from "node:path";
24
+ import { existsSync } from "node:fs";
25
+ import { dirname, join, relative, resolve } from "node:path";
25
26
  import { economicsContext, evaluateEconomics } from "./economics.js";
26
27
  import { readCiEnvironment, resolveCommitRange, } from "./context.js";
27
28
  import { OBSERVATION_SCHEMA, readTypeScriptProgramMetrics, redactPath, } from "./report.js";
@@ -178,9 +179,12 @@ export async function observe(options) {
178
179
  if (economics.decision === "BYPASS_FULL")
179
180
  return finish("REFUSED", "eligibility", { reason: `ECONOMICS_FULL_BYPASS: ${economics.reason}. No selective command is authorized.` });
180
181
  }
181
- const [{ analyzeGitDelta }, { classifyRepositoryProject, buildDependencyGraph, hydrateDependencyGraph }, { ImpactAnalyzer }, { runPathBaseline }, { commandSpecToString, planSelectiveTestCommands }, { repositoryFileReader }] = await Promise.all([
182
+ const [{ analyzeGitDelta }, graphEngine, { ImpactAnalyzer }, { runPathBaseline }, { commandSpecToString, planSelectiveTestCommands }, { repositoryFileReader }] = await Promise.all([
182
183
  import("@diffci.com/core/git/git-diff"), import("@diffci.com/core/repo/graph"), import("@diffci.com/core/repo/impact"), import("@diffci.com/core/planner/path-baseline"), import("@diffci.com/core/planner/test-command"), import("@diffci.com/core/repo/file-references"),
183
184
  ]);
185
+ const { classifyRepositoryProject, buildDependencyGraph, hydrateDependencyGraph } = graphEngine;
186
+ // Engines before 2026-11-06 do not explain their confidence; the report then omits the reasons.
187
+ const explainGraphConfidence = graphEngine.explainGraphConfidence;
184
188
  markPhase("engineLoad");
185
189
  // The eligibility gate is asked of the graph builder itself (classifyRepositoryProject), not of a
186
190
  // separate list of conditions that can drift away from it. Phase 01 F3 is what that drift costs.
@@ -265,6 +269,7 @@ export async function observe(options) {
265
269
  ...(outsideSuite.length ? {
266
270
  testsOutsideFullSuite: outsideSuite.map(hashPath),
267
271
  outsideSuiteCommands: outsidePlan?.refusalReason ? [] : (outsidePlan?.commands ?? []).map(commandSpecToString),
272
+ ...(outsidePlan?.refusalReason ? { outsideSuiteRefusalReason: separateProjectReason(repoPath, outsideSuite, hashPath) ?? outsidePlan.refusalReason } : {}),
268
273
  } : {}),
269
274
  fallbackReasons: impact.fallbackReasons,
270
275
  ...(fallbackDetails ? { fallbackDetails } : {}),
@@ -283,6 +288,7 @@ export async function observe(options) {
283
288
  edges: graphResult.graph.edges.length,
284
289
  confidence: graphResult.confidence,
285
290
  effectiveConfidence: impact.effectiveGraphConfidence,
291
+ ...(graphResult.confidence !== "COMPLETE" && explainGraphConfidence ? { confidenceReasons: explainGraphConfidence(graphResult) } : {}),
286
292
  durationMs: Math.round(graphResult.performance.durationMs),
287
293
  phasesMs: graphResult.performance.phasesMs,
288
294
  typescriptProgram: readTypeScriptProgramMetrics(graphResult.performance.typescriptProgram),
@@ -319,3 +325,26 @@ function safeAuditWorkflows(repoPath) {
319
325
  return [];
320
326
  }
321
327
  }
328
+ const LOCKFILES = ["pnpm-lock.yaml", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "bun.lock", "bun.lockb"];
329
+ /** Why tests outside the full suite cannot run from the root, when they sit in a project with its own
330
+ * lockfile: the root install does not install it (2026-11-06: LobeHub's apps/desktop, a separate pnpm
331
+ * project, left 8 affected tests unrun with only "outside the default runner configuration" to say why). */
332
+ export function separateProjectReason(repoPath, tests, hashPath = (path) => path) {
333
+ const roots = new Set();
334
+ for (const test of tests) {
335
+ let root;
336
+ for (let dir = dirname(test); dir !== "." && dir !== "/" && dir !== ""; dir = dirname(dir)) {
337
+ if (LOCKFILES.some((name) => existsSync(join(repoPath, dir, name)))) {
338
+ root = dir;
339
+ break;
340
+ }
341
+ }
342
+ if (!root)
343
+ return undefined;
344
+ roots.add(root);
345
+ }
346
+ if (roots.size === 0)
347
+ return undefined;
348
+ const names = [...roots].sort().map(hashPath);
349
+ return `${names.join(", ")} ${names.length === 1 ? "is a separate project with its own lockfile" : "are separate projects with their own lockfiles"}, which the root install does not install; run ${tests.length === 1 ? "that test" : `those ${tests.length} tests`} from there after installing it`;
350
+ }
@@ -122,6 +122,8 @@ export interface ObservationGraph {
122
122
  confidence: string;
123
123
  /** Confidence after reachability narrowing for this delta - the value that drove the verdict. */
124
124
  effectiveConfidence?: string;
125
+ /** Why `confidence` is below COMPLETE, in counts only; absent when it is COMPLETE. */
126
+ confidenceReasons?: string[];
125
127
  durationMs: number;
126
128
  phasesMs?: Record<string, number>;
127
129
  typescriptProgram?: TypeScriptProgramMetrics;
@@ -186,6 +188,8 @@ export interface ObservationResult {
186
188
  * subset of the full suite; verification runs them with `outsideSuiteCommands`. */
187
189
  testsOutsideFullSuite?: string[];
188
190
  outsideSuiteCommands?: string[];
191
+ /** Why `outsideSuiteCommands` is empty when the plan for those tests was refused. */
192
+ outsideSuiteRefusalReason?: string;
189
193
  /** Phases of the test script, verbatim (`node scripts/test-security.js`), that a selective run must
190
194
  * also execute: the selection covers some changed files only through them. Present only when the
191
195
  * observation was asked for them (ObserveOptions.selectTestPhases). Like `proposedCommands`, these
@@ -40,6 +40,13 @@ export function parseTestFileResults(output) {
40
40
  if (jest) {
41
41
  const ms = duration(jest[3], "s");
42
42
  results.set(jest[2], { file: jest[2], status: jest[1] === "FAIL" ? "failed" : "passed", ...(ms !== undefined ? { ms } : {}) });
43
+ continue;
44
+ }
45
+ // pytest progress: `tests/test_a.py ..F. [ 50%]`; F or E marks a failure (2026-11-06).
46
+ const pytest = /^(\S+\.py) ([.FEsxXp]+)\s*(?:\[\s*\d+%\])?\s*$/.exec(line);
47
+ if (pytest) {
48
+ const failed = /[FE]/.test(pytest[2]) || results.get(pytest[1])?.status === "failed";
49
+ results.set(pytest[1], { file: pytest[1], status: failed ? "failed" : "passed" });
43
50
  }
44
51
  }
45
52
  return [...results.values()].sort((a, b) => a.file.localeCompare(b.file));
@@ -52,6 +52,8 @@ export interface VerificationReport {
52
52
  written_during_verification?: string[];
53
53
  /** Files that existed before the run and changed during it, at most 20. Their presence blocks the verdict. */
54
54
  changed_during_verification?: SnapshotChange[];
55
+ /** Commit-range only: checked-out files that differ from HEAD only by CRLF line endings, at most 20. */
56
+ line_ending_only_changes?: string[];
55
57
  };
56
58
  analysis: {
57
59
  status: "not_needed" | ObservationReport["status"];
@@ -66,6 +68,8 @@ export interface VerificationReport {
66
68
  /** The graph's own confidence and the confidence after narrowing to this change. */
67
69
  graph_confidence?: string;
68
70
  effective_graph_confidence?: string;
71
+ /** Why graph_confidence is below COMPLETE, in counts only. */
72
+ graph_confidence_reasons?: string[];
69
73
  };
70
74
  required_actions: string[];
71
75
  /** Present when a failed verification was rerun at the base commit (`--baseline-on-failure`). */
@@ -86,6 +90,12 @@ export interface VerificationReport {
86
90
  total: number;
87
91
  timings: "file" | "equal";
88
92
  };
93
+ /** A full run that first ran the tests the dependency graph found affected (firstPassParts). */
94
+ first_pass?: {
95
+ tests: number;
96
+ commands: string[];
97
+ stopped_full_suite: boolean;
98
+ };
89
99
  /** Tests the coverage map added to the selection (coverage-map.ts), when it added any. */
90
100
  coverage_added?: string[];
91
101
  }
@@ -127,6 +137,16 @@ export declare function verifyChanged(options: VerifyChangedOptions): Promise<Ve
127
137
  export declare function verifyRange(options: VerifyRangeOptions): Promise<VerificationReport>;
128
138
  export declare function verificationExitCode(report: VerificationReport): number;
129
139
  export declare function formatVerificationSummary(report: VerificationReport): string;
140
+ /**
141
+ * The commands that run a FULL observation's affected tests on their own, before the full suite: the
142
+ * tests the dependency graph did find, which a fallback elsewhere in the change does not make less
143
+ * likely to fail. Only when they are under half the suite, so the extra pass stays small, and only when
144
+ * the planner can run every one of them (paths are not redacted).
145
+ */
146
+ export declare function firstPassParts(repoPath: string, result: NonNullable<ObservationReport["result"]>): {
147
+ parts: string[];
148
+ tests: number;
149
+ } | undefined;
130
150
  /** The order to run selected tests in, and under --fail-fast the ones to run first (test-ranking.ts). */
131
151
  export interface SelectedOrdering {
132
152
  order: readonly string[];
@@ -5,7 +5,7 @@ import { appendToCommand, batchCommand, measureCommands, orderCommand, splitComm
5
5
  import { coverageAdditions, readCoverageMap } from "./coverage-map.js";
6
6
  import { checkAtBaseline, compareWithBaseline } from "./failure-baseline.js";
7
7
  import { collectEnforcementContext, evaluateEnforcement } from "./enforce-policy.js";
8
- import { inferFullCommand, inferSelectedCommand, inferSelectedCommands } from "./full-command.js";
8
+ import { inferFullCommand, inferPlannedCommands, inferSelectedCommand, inferSelectedCommands } from "./full-command.js";
9
9
  import { plannedChecks, runChecks } from "./gate-checks.js";
10
10
  import { makeGitRunner, observe } from "./observe.js";
11
11
  import { selectedNodeTests, traceNodeTestFiles, unmatchedNodeTests, unstartedNodeTests } from "./selected-coverage.js";
@@ -13,7 +13,7 @@ import { outcomeLogPath, readOutcomes, reusablePass } from "./outcome-log.js";
13
13
  import { likelyFailures, rankTests, testHistory } from "./test-ranking.js";
14
14
  import { assignShards } from "./test-shards.js";
15
15
  import { mergeTestFileResults } from "./test-results.js";
16
- import { captureWorkingTreeSnapshot, snapshotChanges } from "./working-tree.js";
16
+ import { captureWorkingTreeSnapshot, lineEndingOnlyChanges, snapshotChanges } from "./working-tree.js";
17
17
  export const VERIFICATION_SCHEMA = "diffci.verification.v1";
18
18
  function receiptRange(range) {
19
19
  if (!range)
@@ -36,6 +36,7 @@ function baseReport(snapshot, scope, range) {
36
36
  base_sha: snapshot.baseSha,
37
37
  before_tree_sha: snapshot.treeSha,
38
38
  unchanged: false,
39
+ ...(snapshot.lineEndingOnly ? { line_ending_only_changes: snapshot.lineEndingOnly.slice(0, 20) } : {}),
39
40
  },
40
41
  };
41
42
  }
@@ -85,7 +86,7 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
85
86
  fallback_reasons: result?.fallbackReasons ?? [],
86
87
  error: observation.reason,
87
88
  ...(observation.timings?.totalMs !== undefined ? { duration_ms: observation.timings.totalMs } : {}),
88
- ...(result?.graph ? { graph_confidence: result.graph.confidence, effective_graph_confidence: result.graph.effectiveConfidence } : {}),
89
+ ...(result?.graph ? { graph_confidence: result.graph.confidence, effective_graph_confidence: result.graph.effectiveConfidence, ...(result.graph.confidenceReasons?.length ? { graph_confidence_reasons: result.graph.confidenceReasons } : {}) } : {}),
89
90
  };
90
91
  if ((observation.status !== "OBSERVED" || !result) && !enforcedFull) {
91
92
  return blocked(before, scope, observation.reason ?? "DiffCI analysis did not produce a verification plan", analysis, counts, boundRange);
@@ -143,6 +144,10 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
143
144
  ? fullSelection(options.repoPath, `enforce fallback (${enforcement?.fired_fallback}): ${enforcement?.detail}`)
144
145
  : executableSelection(options.repoPath, result, rankedOrdering(options, result), shard && shardTests ? { tests: new Set(shardTests), first: shard.index === 1 } : undefined);
145
146
  const { selection, command, commands, outsideSuite } = executable;
147
+ // A full run first runs the tests the graph did find, and stops if one fails (2026-11-06 LobeHub catch
148
+ // study: both test-only failures were lost when the full suite reached the time limit first).
149
+ const firstPass = selection === "full" && !enforcedFull && !shard && !options.redactPaths && result ? firstPassParts(options.repoPath, result) : undefined;
150
+ const runCommands = firstPass ? [...firstPass.parts, ...commands] : commands;
146
151
  const reason = coverageAdded.length && selection === "selected"
147
152
  ? `${executable.reason}; the coverage map added ${coverageAdded.length} test file(s) the dependency graph did not select (${coverageAdded.slice(0, 3).join(", ")})`
148
153
  : executable.reason;
@@ -236,7 +241,7 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
236
241
  try {
237
242
  execution = checkRun?.failure
238
243
  ? checkRun.failure.measurement
239
- : measureCommands(commands, { cwd: options.repoPath, timeoutMs: Math.max(options.timeoutMs - (checkRun?.wallMs ?? 0), 0), tailBytes: options.tailBytes, env: trace?.env, stopOnFailure: options.failFast });
244
+ : measureCommands(runCommands, { cwd: options.repoPath, timeoutMs: Math.max(options.timeoutMs - (checkRun?.wallMs ?? 0), 0), tailBytes: options.tailBytes, env: trace?.env, stopOnFailure: options.failFast, stopOnFailureWithin: firstPass?.parts.length });
240
245
  startedNodeTests = trace?.read();
241
246
  const nodeResults = trace?.results() ?? [];
242
247
  if (nodeResults.length)
@@ -245,9 +250,12 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
245
250
  finally {
246
251
  trace?.dispose();
247
252
  }
248
- const failFastNote = execution.partsNotRun
249
- ? `; --fail-fast stopped at the first failing part, so ${execution.partsNotRun} later part(s) of the selection did not run`
250
- : "";
253
+ const stoppedInFirstPass = firstPass && execution.partsNotRun !== undefined && runCommands.length - execution.partsNotRun <= firstPass.parts.length;
254
+ const failFastNote = stoppedInFirstPass
255
+ ? `; ${firstPass.tests} test file(s) the dependency graph found affected ran before the full suite and failed, so the full suite was not run`
256
+ : execution.partsNotRun
257
+ ? `; --fail-fast stopped at the first failing part, so ${execution.partsNotRun} later part(s) of the selection did not run`
258
+ : "";
251
259
  const preexistingNote = checksNote + failFastNote;
252
260
  let after;
253
261
  try {
@@ -308,7 +316,8 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
308
316
  : `verification command failed with exit code ${String(execution.exitCode)}${preexistingNote}`;
309
317
  const baselineSha = scope === "commit-range" ? range?.baseSha : before.baseSha;
310
318
  const failureBaseline = verification === "failed" && !failedCheck && !execution.timedOut && options.baselineOnFailure && baselineSha
311
- ? compareWithBaseline({ repoPath: options.repoPath, baseSha: baselineSha, headSha: scope === "commit-range" ? before.baseSha : before.commitSha, commands, headFailures: execution.failingTests ?? [], timeoutMs: options.timeoutMs })
319
+ // The base reruns only the parts that ran here: a first-pass failure is compared without the full suite.
320
+ ? compareWithBaseline({ repoPath: options.repoPath, baseSha: baselineSha, headSha: scope === "commit-range" ? before.baseSha : before.commitSha, commands: stoppedInFirstPass ? firstPass.parts : commands, headFailures: execution.failingTests ?? [], timeoutMs: options.timeoutMs })
312
321
  : undefined;
313
322
  const baselineNote = failureBaseline && failureBaseline.status !== "unknown"
314
323
  ? `; ${failureBaseline.reason} (${failureBaseline.base_sha.slice(0, 12)})`
@@ -325,8 +334,9 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
325
334
  selection,
326
335
  ...(selection === "selected" && result ? { selected_tests: result.selectedTests } : {}),
327
336
  ...(selection === "selected" && result?.selectionReasons ? { selection_reasons: result.selectionReasons } : {}),
328
- command,
329
- ...(commands.length > 1 ? { commands } : {}),
337
+ command: firstPass ? runCommands.join(" && ") : command,
338
+ ...(runCommands.length > 1 ? { commands: runCommands } : {}),
339
+ ...(firstPass ? { first_pass: { tests: firstPass.tests, commands: firstPass.parts, stopped_full_suite: Boolean(stoppedInFirstPass) } } : {}),
330
340
  execution,
331
341
  ...(checks ? { checks } : {}),
332
342
  snapshot: {
@@ -416,7 +426,11 @@ async function verifyCommitRange(options) {
416
426
  return blocked(unknownSnapshot(), "commit-range", message, { status: "ERROR", stage: "context", fallback_reasons: [], error: message });
417
427
  }
418
428
  if (before.changed) {
419
- return blocked(before, "commit-range", "commit-range verification requires a clean checkout; use verify --changed for uncommitted changes", { status: "not_needed", fallback_reasons: [] });
429
+ const lineEndingOnly = lineEndingOnlyChanges(repoPath, before);
430
+ if (!lineEndingOnly) {
431
+ return blocked(before, "commit-range", "commit-range verification requires a clean checkout; use verify --changed for uncommitted changes", { status: "not_needed", fallback_reasons: [] });
432
+ }
433
+ before = { ...before, lineEndingOnly };
420
434
  }
421
435
  const temporaryDirectory = mkdtempSync(join(tmpdir(), "diffci-verify-"));
422
436
  try {
@@ -461,6 +475,10 @@ export function formatVerificationSummary(report) {
461
475
  ];
462
476
  if (report.commit_range)
463
477
  lines.splice(2, 0, ` range: ${report.commit_range.base_sha.slice(0, 12)}..${report.commit_range.head_sha.slice(0, 12)}`);
478
+ const lineEndings = report.snapshot.line_ending_only_changes;
479
+ if (lineEndings?.length) {
480
+ 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`);
481
+ }
464
482
  const written = report.snapshot.written_during_verification;
465
483
  if (written?.length)
466
484
  lines.push(` written by the run (not in .gitignore): ${written.slice(0, 5).join(", ")}${written.length > 5 ? ", ..." : ""}`);
@@ -491,6 +509,26 @@ function fullSelection(repoPath, reason) {
491
509
  const command = inferFullCommand(repoPath).command;
492
510
  return { selection: "full", command, commands: command ? [command] : [], reason, outsideSuite: 0 };
493
511
  }
512
+ /**
513
+ * The commands that run a FULL observation's affected tests on their own, before the full suite: the
514
+ * tests the dependency graph did find, which a fallback elsewhere in the change does not make less
515
+ * likely to fail. Only when they are under half the suite, so the extra pass stays small, and only when
516
+ * the planner can run every one of them (paths are not redacted).
517
+ */
518
+ export function firstPassParts(repoPath, result) {
519
+ const tests = result.selectedTests;
520
+ if (result.mode !== "FULL" || tests.length === 0 || !(tests.length * 2 < result.totalTestCount))
521
+ return undefined;
522
+ const planned = inferPlannedCommands(repoPath, tests);
523
+ if (!planned)
524
+ return undefined;
525
+ if ("commands" in planned)
526
+ return { parts: planned.commands, tests: tests.length };
527
+ // A selected file the runner's glob would not match never runs (as executableSelection checks).
528
+ if (unmatchedNodeTests(planned.single, tests).length)
529
+ return undefined;
530
+ return { parts: batchCommand(planned.single, tests), tests: tests.length };
531
+ }
494
532
  /** Ranks the selected tests by the outcome log's history, or undefined when nothing in it says any is
495
533
  * likelier to fail than another, so a repository without history runs its selection exactly as before. */
496
534
  function rankedOrdering(options, result) {
@@ -593,7 +631,7 @@ export function executableSelection(repoPath, result, ordering, shard) {
593
631
  reason = `${reason}; also ran ${outside.length} affected test file(s) the full test command does not run`;
594
632
  }
595
633
  else {
596
- reason = `${reason}; ${outside.length} affected test file(s) outside the full test command were not run (${auxiliary?.reason ?? "no single command covers them"})`;
634
+ reason = `${reason}; ${outside.length} affected test file(s) outside the full test command were not run (${auxiliary?.reason ?? result.outsideSuiteRefusalReason ?? "no single command covers them"})`;
597
635
  }
598
636
  }
599
637
  // Under --shard each selected command keeps only the shard's files, and the test-script phases and the
@@ -0,0 +1,36 @@
1
+ /**
2
+ * `diffci watch` (2026-11-06), the idea of `jest --watch` with DiffCI's selection.
3
+ *
4
+ * WHY. A person working beside an agent, or in a `node --test` repository whose own watch mode reruns
5
+ * everything, wants the "what did I just break" answer on every save without typing a command. It is also
6
+ * the plainest way to see what DiffCI does: the selection changes as the files do.
7
+ *
8
+ * WHAT. Watches the repository recursively and, after a quiet period (debounce), runs one verification of
9
+ * the uncommitted changes: the same `verify --changed` an agent runs, so the selection, reuse, ranking and
10
+ * coverage map all apply. Changes inside `.git` and `node_modules` are ignored. Saves during a run start
11
+ * one more run after it, never two at once. Events that leave the tree as the last run left it start
12
+ * nothing, so files a test writes during a run do not trigger the next one.
13
+ * Each run is a fresh analysis; re-parsing only the changed files is not done yet.
14
+ */
15
+ export interface WatchRun {
16
+ /** The tree as the run left it (files it wrote included), so its own writes start nothing new. */
17
+ treeSha: string;
18
+ }
19
+ export interface WatchOptions {
20
+ repoPath: string;
21
+ /** Runs one verification and reports it; resolves with the verified tree. */
22
+ run: () => Promise<WatchRun>;
23
+ debounceMs?: number;
24
+ /** Injected in tests; defaults to a recursive fs.watch. Calls `onChange` with a repository-relative path. */
25
+ watch?: (repoPath: string, onChange: (path: string) => void) => {
26
+ close(): void;
27
+ };
28
+ /** The tree as it is now, to tell a save from the run's own writes; undefined means "assume changed". */
29
+ currentTree?: () => string | undefined;
30
+ }
31
+ export declare function ignoredWatchPath(path: string): boolean;
32
+ /** Starts watching and runs once at start. `idle()` resolves when no run is pending or in progress. */
33
+ export declare function startWatch(options: WatchOptions): {
34
+ stop(): void;
35
+ idle(): Promise<void>;
36
+ };