@diffci.com/diffci 0.3.25 → 0.3.26

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 (25) hide show
  1. package/dist-client/src/client/cli.js +23 -1
  2. package/dist-client/src/client/enforce-policy.js +4 -0
  3. package/dist-client/src/client/gate.d.ts +3 -1
  4. package/dist-client/src/client/gate.js +1 -0
  5. package/dist-client/src/client/observe.js +14 -0
  6. package/dist-client/src/client/outcome-log.d.ts +80 -0
  7. package/dist-client/src/client/outcome-log.js +145 -0
  8. package/dist-client/src/client/report.d.ts +8 -0
  9. package/dist-client/src/client/verify.d.ts +3 -1
  10. package/dist-client/src/client/verify.js +1 -0
  11. package/node_modules/@diffci.com/core/dist/git/ci-config-paths.d.ts +18 -0
  12. package/node_modules/@diffci.com/core/dist/git/ci-config-paths.js +136 -0
  13. package/node_modules/@diffci.com/core/dist/git/ci-config-paths.js.map +1 -0
  14. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +2 -1
  15. package/node_modules/@diffci.com/core/dist/git/git-diff.js +17 -4
  16. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  17. package/node_modules/@diffci.com/core/dist/planner/path-baseline.js +2 -1
  18. package/node_modules/@diffci.com/core/dist/planner/path-baseline.js.map +1 -1
  19. package/node_modules/@diffci.com/core/dist/repo/impact.js +1 -1
  20. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  21. package/node_modules/@diffci.com/core/src/git/ci-config-paths.ts +131 -0
  22. package/node_modules/@diffci.com/core/src/git/git-diff.ts +18 -4
  23. package/node_modules/@diffci.com/core/src/planner/path-baseline.ts +2 -1
  24. package/node_modules/@diffci.com/core/src/repo/impact.ts +1 -1
  25. package/package.json +2 -2
@@ -53,6 +53,7 @@ import { renderPilotPacket } from "./pilot-packet.js";
53
53
  import { observerIdentity } from "./package-identity.js";
54
54
  import { buildPilotWorkflow, diffciVerificationWorkflow, diffciWorkflow } from "./workflow-templates.js";
55
55
  import { buildMissReport, formatMissReportMarkdown, parseJunit } from "./enforce-misses.js";
56
+ import { appendOutcome, formatOutcomeSummary, outcomeLogPath, readOutcomes, summarizeOutcomes } from "./outcome-log.js";
56
57
  import { findReceipt, findWindowStart, inferRerunArgs, mergedPullRequests, MISS_REPORT_FILE, rerunFailingFiles, spawnRunner, } from "./enforce-misses-collect.js";
57
58
  function parseArgs(argv) {
58
59
  const args = argv.slice(2);
@@ -375,6 +376,8 @@ async function runVerifyCommand(flags, env) {
375
376
  policy,
376
377
  });
377
378
  await recordUsage("verify", report.verification, identity.version, flags, env);
379
+ if (flags["no-log"] !== true)
380
+ appendOutcome(repoPath, report, env);
378
381
  if (reportPath) {
379
382
  mkdirSync(dirname(reportPath), { recursive: true });
380
383
  writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");
@@ -388,6 +391,17 @@ async function runVerifyCommand(flags, env) {
388
391
  }
389
392
  return verificationExitCode(report);
390
393
  }
394
+ function runOutcomesCommand(flags, env) {
395
+ const repoPath = resolve(stringFlag(flags, "repo") ?? env.GITHUB_WORKSPACE ?? process.cwd());
396
+ const path = outcomeLogPath(repoPath);
397
+ if (!path) {
398
+ console.error(`Not a Git repository: ${repoPath}`);
399
+ return 2;
400
+ }
401
+ const summary = summarizeOutcomes(readOutcomes(path));
402
+ console.log(flags.json === true ? JSON.stringify({ log: path, ...summary }, null, 2) : formatOutcomeSummary(summary, path));
403
+ return 0;
404
+ }
391
405
  async function runGateCommand(flags, env) {
392
406
  const mode = stringFlag(flags, "mode") ?? "observe";
393
407
  if (mode !== "observe") {
@@ -1087,7 +1101,7 @@ Usage:
1087
1101
  diffci mcp
1088
1102
  diffci verify [--changed | --base <sha> --head <sha>] [--policy enforce] [--repo <path>] [--out <file>] [--json]
1089
1103
  [--redact-paths] [--timeout-ms <ms>] [--baseline-on-failure] [--no-checks | --checks]
1090
- [--share-usage] [--no-send]
1104
+ [--share-usage] [--no-send] [--no-log]
1091
1105
  diffci telemetry [--mode off|anonymous|installations] [--internal-usage]
1092
1106
  diffci check [--repo <path>] [--out <file>] [--base <sha> --head <sha>]
1093
1107
  [--redact-paths] [--json] [--quiet] [--fail-on-error] [--timeout-ms <ms>] [--share-usage]
@@ -1112,6 +1126,7 @@ Usage:
1112
1126
  diffci gate --plan-out <file> [--base <sha> --head <sha>] [--script <name,...>] [--repo <path>]
1113
1127
  diffci enforce-misses --junit <file> --out-dir <dir> [--repository <owner/name>] [--repo <path>]
1114
1128
  [--head <sha>] [--rerun-junit <file>] [--open-issue]
1129
+ diffci outcomes [--repo <path>] [--json]
1115
1130
  diffci version
1116
1131
 
1117
1132
  init writes AGENTS.md, CLAUDE.md, Cursor rules, Copilot instructions, and diffci.config.json. It also
@@ -1151,6 +1166,10 @@ and writes DiffCI's decisions, for a gate that runs without git history; --plan
1151
1166
  analysing, and --expect-head ignores a plan made for another commit. It sends nothing.
1152
1167
  enforce-misses classifies a full run's failures on main against the enforce dry-run receipts of the pull
1153
1168
  requests merged since the last recorded run, and exits 1 on a miss. It never edits configuration.
1169
+ verify appends each run (plan, selection reasons, checks, results, durations, failing tests) to
1170
+ .git/diffci/outcomes.jsonl, which is never committed and never sent; --no-log or DIFFCI_OUTCOME_LOG=0 skips it.
1171
+ outcomes summarises that log: results, selected and full runs, top full-run reasons, agents, and possible
1172
+ misses (a selected run that passed and a later full run of the same tree that failed).
1154
1173
  Failures are re-run with the package.json tsx --test runner, or read from --rerun-junit for other runners.
1155
1174
 
1156
1175
  The report is sent only when both --api-url and --api-token are given (or DIFFCI_API_URL and
@@ -1229,6 +1248,9 @@ async function main() {
1229
1248
  case "enforce-misses":
1230
1249
  process.exitCode = runEnforceMisses(flags, env);
1231
1250
  return;
1251
+ case "outcomes":
1252
+ process.exitCode = runOutcomesCommand(flags, env);
1253
+ return;
1232
1254
  case "version":
1233
1255
  console.log(observerIdentity().version);
1234
1256
  return;
@@ -23,6 +23,10 @@ export const ENFORCE_VARIABLE = "DIFFCI_ENFORCE";
23
23
  */
24
24
  const GLOBAL_RISK_PATTERNS = [
25
25
  /^\.github\//,
26
+ // GitLab pipeline definitions (2026-11-05). Files pulled in by `include: local:` under other names
27
+ // are caught by the analyzer, which follows includes; this is the name-only backstop.
28
+ /(?:^|\/|\.)gitlab-ci\.ya?ml$/i,
29
+ /^\.gitlab\/.*\.ya?ml$/i,
26
30
  /(?:^|\/)package\.json$/,
27
31
  /(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|pnpm-workspace\.yaml|yarn\.lock|bun\.lockb?)$/,
28
32
  /(?:^|\/)\.(?:npmrc|nvmrc|node-version|tool-versions)$/,
@@ -1,6 +1,6 @@
1
1
  import { type PlannedCheck } from "./gate-checks.js";
2
2
  import { observe } from "./observe.js";
3
- import type { ObservationReport } from "./report.js";
3
+ import type { ObservationReport, SelectionReason } from "./report.js";
4
4
  import { type CommandMeasurement } from "./verify-savings.js";
5
5
  /**
6
6
  * `diffci gate` in observe mode (2026-10-30, docs/design/pipeline-impact.md, phase 2).
@@ -146,6 +146,8 @@ export interface GatePlan {
146
146
  tests_selected: number;
147
147
  tests_available: number;
148
148
  selected_commands?: string[];
149
+ /** Why each selected test was selected (ObservationResult.selectionReasons). */
150
+ selection_reasons?: Record<string, SelectionReason>;
149
151
  };
150
152
  }
151
153
  export declare function planGate(options: Omit<GateOptions, "plan" | "expectHead" | "run" | "timeoutMs" | "tailBytes" | "measureSelected" | "only" | "tests">): Promise<GatePlan>;
@@ -71,6 +71,7 @@ export async function planGate(options) {
71
71
  tests_selected: selection === "selected" ? result?.selectedTests.length ?? 0 : result?.totalTestCount ?? 0,
72
72
  tests_available: result?.totalTestCount ?? 0,
73
73
  ...(selection === "selected" ? { selected_commands: selected.commands } : {}),
74
+ ...(selection === "selected" && result?.selectionReasons ? { selection_reasons: result.selectionReasons } : {}),
74
75
  },
75
76
  };
76
77
  }
@@ -48,6 +48,19 @@ export function makeGitRunner(repoPath) {
48
48
  function sha256(input) {
49
49
  return createHash("sha256").update(input).digest("hex");
50
50
  }
51
+ /** The first piece of engine evidence for each selected test: which changed file selected it, and how. */
52
+ function selectionReasons(affected, selected, hashPath) {
53
+ const reasons = {};
54
+ for (const test of affected) {
55
+ if (!selected.has(test.path))
56
+ continue;
57
+ const first = test.evidence[0];
58
+ reasons[hashPath(test.path)] = first
59
+ ? { reason: first.reason, changed_file: hashPath(first.changedFile) }
60
+ : { reason: test.reasons[0] ?? "UNKNOWN", changed_file: "" };
61
+ }
62
+ return reasons;
63
+ }
51
64
  /** A digest rather than the porcelain text itself: the point is only whether it changed. */
52
65
  function worktreeDigest(git) {
53
66
  const result = git(["status", "--porcelain"]);
@@ -244,6 +257,7 @@ export async function observe(options) {
244
257
  changedFiles: delta.files.map((file) => hashPath(file.path)),
245
258
  affectedSourceFileCount: impact.affectedSourceFiles.length,
246
259
  selectedTests: selectedTests.map(hashPath),
260
+ selectionReasons: selectionReasons(impact.affectedTests, new Set(selectedTests), hashPath),
247
261
  totalTestCount: impact.fullSuiteTestCount ?? profile.testFilePaths.length,
248
262
  discoveredTestCount: profile.testFilePaths.length,
249
263
  ...(outsideSuite.length ? {
@@ -0,0 +1,80 @@
1
+ import type { SelectionReason } from "./report.js";
2
+ import type { VerificationReport } from "./verify.js";
3
+ /**
4
+ * The local outcome log (2026-11-05).
5
+ *
6
+ * WHY. Every verify run decides what to run and then learns what happened. Kept, those pairs are the
7
+ * training data for ranking tests and the only way to measure misses over time; they cannot be
8
+ * reconstructed afterwards. Receipts were written only when asked for (`--out`) and dropped otherwise.
9
+ *
10
+ * WHAT. One JSON line per `diffci verify`, appended to `<git common dir>/diffci/outcomes.jsonl`: inside
11
+ * `.git`, so it is never committed, never an untracked file that changes the next snapshot, and shared
12
+ * by every worktree of the repository. It holds the plan (selection, reasons, checks), the result, the
13
+ * durations and the failing tests. Nothing is sent anywhere. `--no-log` or DIFFCI_OUTCOME_LOG=0 skip it.
14
+ */
15
+ export declare const OUTCOME_SCHEMA: "diffci.outcome.v1";
16
+ export interface OutcomeRecord {
17
+ schema: typeof OUTCOME_SCHEMA;
18
+ produced_at: string;
19
+ diffci_version?: string;
20
+ agent?: string;
21
+ scope: VerificationReport["scope"];
22
+ base_sha: string;
23
+ head_sha?: string;
24
+ /** The verified tree; runs on the same tree verified the same content. */
25
+ tree_sha: string;
26
+ verification: VerificationReport["verification"];
27
+ selection: VerificationReport["selection"];
28
+ tests_selected: number;
29
+ tests_available: number;
30
+ selected_tests?: string[];
31
+ selection_reasons?: Record<string, SelectionReason>;
32
+ fallback_reasons: string[];
33
+ analysis_ms?: number;
34
+ tests_ms?: number;
35
+ exit_code?: number | null;
36
+ failing_tests?: string[];
37
+ checks?: Array<{
38
+ id: string;
39
+ decision: string;
40
+ status: string;
41
+ wall_ms?: number;
42
+ }>;
43
+ }
44
+ export declare function outcomeRecord(report: VerificationReport, env?: Record<string, string | undefined>): OutcomeRecord;
45
+ /** `<git common dir>/diffci/outcomes.jsonl`, or undefined outside a Git repository. */
46
+ export declare function outcomeLogPath(repoPath: string): string | undefined;
47
+ /** Appends the run to the log. Best effort: a log that cannot be written never fails verification. */
48
+ export declare function appendOutcome(repoPath: string, report: VerificationReport, env: Record<string, string | undefined>): string | undefined;
49
+ /** Every well-formed record in the log, oldest first; malformed lines are skipped. */
50
+ export declare function readOutcomes(path: string): OutcomeRecord[];
51
+ /**
52
+ * A selected run that passed and a later full run of the same tree that failed: the selection left out
53
+ * something that fails. Possible, not proven - a flaky test fails the same way - so it is reported as
54
+ * a lead. Misses on CI full runs are classified by `diffci enforce-misses`.
55
+ */
56
+ export interface PossibleMiss {
57
+ tree_sha: string;
58
+ selected_at: string;
59
+ full_at: string;
60
+ failing_tests: string[];
61
+ }
62
+ export interface OutcomeSummary {
63
+ runs: number;
64
+ passed: number;
65
+ failed: number;
66
+ blocked: number;
67
+ selected: number;
68
+ full: number;
69
+ /** Median wall time of the test command, by selection. */
70
+ median_selected_ms?: number;
71
+ median_full_ms?: number;
72
+ top_fallback_reasons: Array<{
73
+ reason: string;
74
+ runs: number;
75
+ }>;
76
+ agents: Record<string, number>;
77
+ possible_misses: PossibleMiss[];
78
+ }
79
+ export declare function summarizeOutcomes(records: readonly OutcomeRecord[]): OutcomeSummary;
80
+ export declare function formatOutcomeSummary(summary: OutcomeSummary, path: string): string;
@@ -0,0 +1,145 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import { detectAgentFromEnvironment } from "./agent-identity.js";
5
+ /**
6
+ * The local outcome log (2026-11-05).
7
+ *
8
+ * WHY. Every verify run decides what to run and then learns what happened. Kept, those pairs are the
9
+ * training data for ranking tests and the only way to measure misses over time; they cannot be
10
+ * reconstructed afterwards. Receipts were written only when asked for (`--out`) and dropped otherwise.
11
+ *
12
+ * WHAT. One JSON line per `diffci verify`, appended to `<git common dir>/diffci/outcomes.jsonl`: inside
13
+ * `.git`, so it is never committed, never an untracked file that changes the next snapshot, and shared
14
+ * by every worktree of the repository. It holds the plan (selection, reasons, checks), the result, the
15
+ * durations and the failing tests. Nothing is sent anywhere. `--no-log` or DIFFCI_OUTCOME_LOG=0 skip it.
16
+ */
17
+ export const OUTCOME_SCHEMA = "diffci.outcome.v1";
18
+ export function outcomeRecord(report, env = {}) {
19
+ const agent = detectAgentFromEnvironment(env);
20
+ return {
21
+ schema: OUTCOME_SCHEMA,
22
+ produced_at: report.produced_at,
23
+ ...(report.diffci_version ? { diffci_version: report.diffci_version } : {}),
24
+ ...(agent ? { agent } : {}),
25
+ scope: report.scope,
26
+ base_sha: report.commit_range?.base_sha ?? report.snapshot.base_sha,
27
+ ...(report.commit_range ? { head_sha: report.commit_range.head_sha } : {}),
28
+ tree_sha: report.snapshot.before_tree_sha,
29
+ verification: report.verification,
30
+ selection: report.selection,
31
+ tests_selected: report.tests_selected,
32
+ tests_available: report.tests_available,
33
+ ...(report.selected_tests ? { selected_tests: report.selected_tests } : {}),
34
+ ...(report.selection_reasons ? { selection_reasons: report.selection_reasons } : {}),
35
+ fallback_reasons: report.analysis.fallback_reasons,
36
+ ...(report.analysis.duration_ms !== undefined ? { analysis_ms: report.analysis.duration_ms } : {}),
37
+ ...(report.execution ? { tests_ms: report.execution.wallMs, exit_code: report.execution.exitCode } : {}),
38
+ ...(report.execution?.failingTests?.length ? { failing_tests: report.execution.failingTests } : {}),
39
+ ...(report.checks ? { checks: report.checks.map((check) => ({ id: check.id, decision: check.decision, status: check.status, ...(check.wall_ms !== undefined ? { wall_ms: check.wall_ms } : {}) })) } : {}),
40
+ };
41
+ }
42
+ /** `<git common dir>/diffci/outcomes.jsonl`, or undefined outside a Git repository. */
43
+ export function outcomeLogPath(repoPath) {
44
+ try {
45
+ const common = execFileSync("git", ["rev-parse", "--git-common-dir"], { cwd: repoPath, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
46
+ return join(resolve(repoPath, common), "diffci", "outcomes.jsonl");
47
+ }
48
+ catch {
49
+ return undefined;
50
+ }
51
+ }
52
+ /** Appends the run to the log. Best effort: a log that cannot be written never fails verification. */
53
+ export function appendOutcome(repoPath, report, env) {
54
+ if (env.DIFFCI_OUTCOME_LOG === "0")
55
+ return undefined;
56
+ const path = outcomeLogPath(repoPath);
57
+ if (!path)
58
+ return undefined;
59
+ try {
60
+ mkdirSync(join(path, ".."), { recursive: true });
61
+ appendFileSync(path, `${JSON.stringify(outcomeRecord(report, env))}\n`, "utf8");
62
+ return path;
63
+ }
64
+ catch {
65
+ return undefined;
66
+ }
67
+ }
68
+ /** Every well-formed record in the log, oldest first; malformed lines are skipped. */
69
+ export function readOutcomes(path) {
70
+ if (!existsSync(path))
71
+ return [];
72
+ return readFileSync(path, "utf8").split("\n").flatMap((line) => {
73
+ if (!line.trim())
74
+ return [];
75
+ try {
76
+ const record = JSON.parse(line);
77
+ return record.schema === OUTCOME_SCHEMA ? [record] : [];
78
+ }
79
+ catch {
80
+ return [];
81
+ }
82
+ });
83
+ }
84
+ function median(values) {
85
+ if (values.length === 0)
86
+ return undefined;
87
+ const sorted = [...values].sort((a, b) => a - b);
88
+ const middle = Math.floor(sorted.length / 2);
89
+ return sorted.length % 2 ? sorted[middle] : Math.round((sorted[middle - 1] + sorted[middle]) / 2);
90
+ }
91
+ export function summarizeOutcomes(records) {
92
+ const fallback = new Map();
93
+ for (const record of records) {
94
+ if (record.selection !== "full")
95
+ continue;
96
+ for (const reason of new Set(record.fallback_reasons))
97
+ fallback.set(reason, (fallback.get(reason) ?? 0) + 1);
98
+ }
99
+ const agents = {};
100
+ for (const record of records)
101
+ agents[record.agent ?? "none"] = (agents[record.agent ?? "none"] ?? 0) + 1;
102
+ const possible_misses = [];
103
+ records.forEach((full, index) => {
104
+ if (full.selection !== "full" || full.verification !== "failed")
105
+ return;
106
+ const earlier = records.slice(0, index).reverse().find((run) => run.tree_sha === full.tree_sha && run.selection === "selected" && run.verification === "passed");
107
+ if (earlier)
108
+ possible_misses.push({ tree_sha: full.tree_sha, selected_at: earlier.produced_at, full_at: full.produced_at, failing_tests: full.failing_tests ?? [] });
109
+ });
110
+ const ms = (selection) => records.filter((r) => r.selection === selection && r.tests_ms !== undefined).map((r) => r.tests_ms);
111
+ const medianSelected = median(ms("selected"));
112
+ const medianFull = median(ms("full"));
113
+ return {
114
+ runs: records.length,
115
+ passed: records.filter((r) => r.verification === "passed").length,
116
+ failed: records.filter((r) => r.verification === "failed").length,
117
+ blocked: records.filter((r) => r.verification === "blocked").length,
118
+ selected: records.filter((r) => r.selection === "selected").length,
119
+ full: records.filter((r) => r.selection === "full").length,
120
+ ...(medianSelected !== undefined ? { median_selected_ms: medianSelected } : {}),
121
+ ...(medianFull !== undefined ? { median_full_ms: medianFull } : {}),
122
+ top_fallback_reasons: [...fallback].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 5).map(([reason, runs]) => ({ reason, runs })),
123
+ agents,
124
+ possible_misses,
125
+ };
126
+ }
127
+ export function formatOutcomeSummary(summary, path) {
128
+ const seconds = (value) => value === undefined ? "-" : `${(value / 1000).toFixed(1)}s`;
129
+ const lines = [
130
+ `DiffCI outcomes: ${summary.runs} verify run(s) in ${path}`,
131
+ ` results: ${summary.passed} passed, ${summary.failed} failed, ${summary.blocked} blocked`,
132
+ ` selection: ${summary.selected} selected (median tests ${seconds(summary.median_selected_ms)}), ${summary.full} full (median ${seconds(summary.median_full_ms)})`,
133
+ ` agents: ${Object.entries(summary.agents).map(([agent, runs]) => `${agent} ${runs}`).join(", ") || "-"}`,
134
+ ];
135
+ if (summary.top_fallback_reasons.length) {
136
+ lines.push(" top full-run reasons:");
137
+ for (const { reason, runs } of summary.top_fallback_reasons)
138
+ lines.push(` ${runs}x ${reason}`);
139
+ }
140
+ lines.push(` possible misses: ${summary.possible_misses.length}`);
141
+ for (const miss of summary.possible_misses) {
142
+ lines.push(` tree ${miss.tree_sha.slice(0, 12)}: selected run passed ${miss.selected_at}, full run failed ${miss.full_at}${miss.failing_tests.length ? ` (${miss.failing_tests.slice(0, 3).join(", ")})` : ""}`);
143
+ }
144
+ return lines.join("\n");
145
+ }
@@ -162,6 +162,11 @@ export interface ObservationBaseline {
162
162
  selectedTests: string[];
163
163
  matchedRules: string[];
164
164
  }
165
+ /** The changed file that selected a test and how it reaches it (IMPORT, FILE_REFERENCE, DEPENDENCY, ...). */
166
+ export interface SelectionReason {
167
+ reason: string;
168
+ changed_file: string;
169
+ }
165
170
  export interface ObservationResult {
166
171
  mode: "SELECTIVE" | "FULL";
167
172
  changedFileCount: number;
@@ -169,6 +174,9 @@ export interface ObservationResult {
169
174
  changedFiles: string[];
170
175
  affectedSourceFileCount: number;
171
176
  selectedTests: string[];
177
+ /** Why each selected test was selected: the first piece of engine evidence for it (2026-11-05). Keys
178
+ * and changed files are redacted like `selectedTests`. Absent from engines that predate it. */
179
+ selectionReasons?: Record<string, SelectionReason>;
172
180
  /** Test files the full test command runs: the denominator for any selection ratio. Every
173
181
  * discovered test file when the test script could not be modelled (2026-10-21). */
174
182
  totalTestCount: number;
@@ -1,7 +1,7 @@
1
1
  import { type FailureBaseline } from "./failure-baseline.js";
2
2
  import { type EnforcementDecision } from "./enforce-policy.js";
3
3
  import { type CheckResult } from "./gate-checks.js";
4
- import type { ObservationCommitRange, ObservationReport } from "./report.js";
4
+ import type { ObservationCommitRange, ObservationReport, SelectionReason } from "./report.js";
5
5
  import type { CommandMeasurement } from "./verify-savings.js";
6
6
  import { type SnapshotChange } from "./working-tree.js";
7
7
  export declare const VERIFICATION_SCHEMA: "diffci.verification.v1";
@@ -25,6 +25,8 @@ export interface VerificationReport {
25
25
  selection: "none" | "selected" | "full";
26
26
  /** The test files the selected command ran, when `selection` is "selected". The miss detector reads it. */
27
27
  selected_tests?: string[];
28
+ /** Why each selected test was selected (ObservationResult.selectionReasons), when `selection` is "selected". */
29
+ selection_reasons?: Record<string, SelectionReason>;
28
30
  command?: string;
29
31
  /** The parts `command` was run as, when one invocation would exceed the shell's command-line limit. */
30
32
  commands?: string[];
@@ -218,6 +218,7 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
218
218
  ...(outsideSuite ? { tests_outside_full_suite: outsideSuite } : {}),
219
219
  selection,
220
220
  ...(selection === "selected" && result ? { selected_tests: result.selectedTests } : {}),
221
+ ...(selection === "selected" && result?.selectionReasons ? { selection_reasons: result.selectionReasons } : {}),
221
222
  command,
222
223
  ...(commands.length > 1 ? { commands } : {}),
223
224
  execution,
@@ -0,0 +1,18 @@
1
+ /** Recognised by name alone, with no file content. */
2
+ export declare function isConventionalCiConfigPath(path: string): boolean;
3
+ export interface GitlabIncludes {
4
+ /** Local files reached from the root through `include`, without the leading slash. */
5
+ paths: Set<string>;
6
+ /** Local include patterns with `*`, as regular expressions over repository paths. */
7
+ patterns: RegExp[];
8
+ /** An include could not be followed, so any YAML file may be pipeline config. */
9
+ unresolved: boolean;
10
+ }
11
+ /**
12
+ * Follows `include` from `.gitlab-ci.yml` at one commit. `read` returns a file's content at that
13
+ * commit, or undefined when it does not exist. `files` lists the repository's files at that commit; it
14
+ * is called only for a wildcard include, whose matches may include further files.
15
+ */
16
+ export declare function gitlabLocalIncludes(read: (path: string) => string | undefined, files?: () => readonly string[]): GitlabIncludes;
17
+ /** A predicate over changed paths: conventional names, plus whatever either commit's includes reach. */
18
+ export declare function ciConfigPredicate(includes?: readonly GitlabIncludes[]): (path: string) => boolean;
@@ -0,0 +1,136 @@
1
+ // SPDX-License-Identifier: MIT
2
+ /**
3
+ * Which changed paths are CI pipeline definitions (2026-11-05).
4
+ *
5
+ * WHY. A pipeline definition decides which commands CI runs, so changing one can change a test outcome
6
+ * without touching anything a test imports. Only `.github/workflows/` was recognised. A GitLab
7
+ * pipeline file fell through to the unknown-file path, where reference resolution narrowed it to the
8
+ * files that name it: a test reading `.gitlab-ci.yml` became the only selected test, and a file pulled
9
+ * in by `include: local:` (read only by `.gitlab-ci.yml`) selected no tests at all.
10
+ *
11
+ * GitLab has no fixed directory, so this recognises the conventional names and also follows
12
+ * `include` from the root `.gitlab-ci.yml`. Anything it cannot follow (a variable in the path, an
13
+ * unparsable file) makes every YAML file count as pipeline config.
14
+ */
15
+ import { parse as parseYaml } from "yaml";
16
+ const GITLAB_ROOT = ".gitlab-ci.yml";
17
+ const YAML = /\.ya?ml$/i;
18
+ const MAX_INCLUDE_DEPTH = 10;
19
+ /** Recognised by name alone, with no file content. */
20
+ export function isConventionalCiConfigPath(path) {
21
+ if (path.startsWith(".github/workflows/"))
22
+ return true;
23
+ const base = path.slice(path.lastIndexOf("/") + 1).toLowerCase();
24
+ if (/(?:^|\.)gitlab-ci\.ya?ml$/.test(base))
25
+ return true; // .gitlab-ci.yml, test.gitlab-ci.yml
26
+ return path.startsWith(".gitlab/") && YAML.test(path); // .gitlab/ci/*.yml and similar
27
+ }
28
+ function globToRegExp(glob) {
29
+ let source = "";
30
+ for (let i = 0; i < glob.length; i++) {
31
+ const char = glob[i];
32
+ if (char === "*" && glob[i + 1] === "*") {
33
+ source += ".*";
34
+ i++;
35
+ if (glob[i + 1] === "/")
36
+ i++;
37
+ }
38
+ else if (char === "*")
39
+ source += "[^/]*";
40
+ else
41
+ source += char.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
42
+ }
43
+ return new RegExp(`^${source}$`);
44
+ }
45
+ /** The local include targets one parsed pipeline document names. Remote, project, template and
46
+ * component includes live outside the repository, so a diff of this repository cannot change them. */
47
+ function localIncludeTargets(doc) {
48
+ if (doc === null || typeof doc !== "object" || Array.isArray(doc))
49
+ return { targets: [], unresolved: false };
50
+ const include = doc.include;
51
+ if (include === undefined)
52
+ return { targets: [], unresolved: false };
53
+ const entries = Array.isArray(include) ? include : [include];
54
+ const targets = [];
55
+ let unresolved = false;
56
+ for (const entry of entries) {
57
+ let target;
58
+ if (typeof entry === "string") {
59
+ if (/^https?:\/\//i.test(entry))
60
+ continue; // shorthand for `remote:`
61
+ target = entry;
62
+ }
63
+ else if (entry !== null && typeof entry === "object") {
64
+ const record = entry;
65
+ if (!("local" in record))
66
+ continue;
67
+ target = record.local;
68
+ }
69
+ else {
70
+ unresolved = true;
71
+ continue;
72
+ }
73
+ if (typeof target !== "string" || target === "" || target.includes("$")) {
74
+ unresolved = true;
75
+ continue;
76
+ }
77
+ targets.push(target.replace(/^\/+/, ""));
78
+ }
79
+ return { targets, unresolved };
80
+ }
81
+ /**
82
+ * Follows `include` from `.gitlab-ci.yml` at one commit. `read` returns a file's content at that
83
+ * commit, or undefined when it does not exist. `files` lists the repository's files at that commit; it
84
+ * is called only for a wildcard include, whose matches may include further files.
85
+ */
86
+ export function gitlabLocalIncludes(read, files = () => []) {
87
+ const result = { paths: new Set(), patterns: [], unresolved: false };
88
+ const queue = [{ path: GITLAB_ROOT, depth: 0 }];
89
+ const seen = new Set([GITLAB_ROOT]);
90
+ while (queue.length > 0) {
91
+ const { path, depth } = queue.shift();
92
+ const content = read(path);
93
+ if (content === undefined)
94
+ continue; // a missing include fails the GitLab pipeline itself
95
+ let doc;
96
+ try {
97
+ doc = parseYaml(content);
98
+ }
99
+ catch {
100
+ result.unresolved = true;
101
+ continue;
102
+ }
103
+ const { targets, unresolved } = localIncludeTargets(doc);
104
+ if (unresolved)
105
+ result.unresolved = true;
106
+ for (const target of targets) {
107
+ const matches = target.includes("*")
108
+ ? (() => { const pattern = globToRegExp(target); result.patterns.push(pattern); return files().filter((f) => pattern.test(f)); })()
109
+ : [target];
110
+ for (const match of matches) {
111
+ if (match !== GITLAB_ROOT)
112
+ result.paths.add(match);
113
+ if (seen.has(match))
114
+ continue;
115
+ seen.add(match);
116
+ if (depth + 1 >= MAX_INCLUDE_DEPTH) {
117
+ result.unresolved = true;
118
+ continue;
119
+ }
120
+ queue.push({ path: match, depth: depth + 1 });
121
+ }
122
+ }
123
+ }
124
+ return result;
125
+ }
126
+ /** A predicate over changed paths: conventional names, plus whatever either commit's includes reach. */
127
+ export function ciConfigPredicate(includes = []) {
128
+ const paths = new Set(includes.flatMap((i) => [...i.paths]));
129
+ const patterns = includes.flatMap((i) => i.patterns);
130
+ const anyYaml = includes.some((i) => i.unresolved);
131
+ return (path) => isConventionalCiConfigPath(path)
132
+ || paths.has(path)
133
+ || patterns.some((pattern) => pattern.test(path))
134
+ || (anyYaml && YAML.test(path));
135
+ }
136
+ //# sourceMappingURL=ci-config-paths.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ci-config-paths.js","sourceRoot":"","sources":["../../src/git/ci-config-paths.ts"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,KAAK,IAAI,SAAS,EAAE,MAAM,MAAM,CAAC;AAE1C,MAAM,WAAW,GAAG,gBAAgB,CAAC;AACrC,MAAM,IAAI,GAAG,WAAW,CAAC;AACzB,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAE7B,sDAAsD;AACtD,MAAM,UAAU,0BAA0B,CAAC,IAAY;IACrD,IAAI,IAAI,CAAC,UAAU,CAAC,oBAAoB,CAAC;QAAE,OAAO,IAAI,CAAC;IACv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AC7B,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC;WACf,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;WAC9C,CAAC,OAAO,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AACpC,CAAC"}
@@ -61,7 +61,8 @@ export interface PackageJsonChange {
61
61
  export declare function packageJsonChange(oldContent: string | undefined, newContent: string | undefined): PackageJsonChange;
62
62
  /** packageJsonChange's kind, with a dependency change reported as behavioral. */
63
63
  export declare function packageJsonChangeKind(oldContent: string | undefined, newContent: string | undefined): "metadata" | "data" | "behavioral";
64
- export declare function computeAnalysis(files: ChangedFile[]): GitDeltaAnalysis;
64
+ /** `isCiConfig` defaults to names alone; analyzeGitDelta also passes what GitLab `include` reaches. */
65
+ export declare function computeAnalysis(files: ChangedFile[], isCiConfig?: (path: string) => boolean): GitDeltaAnalysis;
65
66
  export declare function summarize(files: ChangedFile[]): GitDeltaSummary;
66
67
  export declare function resolveCommitParents(sha: string, repoPath: string | undefined): string[];
67
68
  /**