@diffci.com/diffci 0.3.25 → 0.3.28

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 (31) hide show
  1. package/dist-client/src/client/cli.js +23 -1
  2. package/dist-client/src/client/context.d.ts +1 -1
  3. package/dist-client/src/client/context.js +93 -3
  4. package/dist-client/src/client/enforce-policy.js +4 -0
  5. package/dist-client/src/client/gate.d.ts +3 -1
  6. package/dist-client/src/client/gate.js +1 -0
  7. package/dist-client/src/client/observe.js +15 -1
  8. package/dist-client/src/client/outcome-log.d.ts +80 -0
  9. package/dist-client/src/client/outcome-log.js +145 -0
  10. package/dist-client/src/client/report.d.ts +10 -2
  11. package/dist-client/src/client/verify.d.ts +3 -1
  12. package/dist-client/src/client/verify.js +1 -0
  13. package/node_modules/@diffci.com/core/README.md +2 -0
  14. package/node_modules/@diffci.com/core/dist/git/ci-config-paths.d.ts +18 -0
  15. package/node_modules/@diffci.com/core/dist/git/ci-config-paths.js +136 -0
  16. package/node_modules/@diffci.com/core/dist/git/ci-config-paths.js.map +1 -0
  17. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +2 -1
  18. package/node_modules/@diffci.com/core/dist/git/git-diff.js +17 -4
  19. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  20. package/node_modules/@diffci.com/core/dist/planner/path-baseline.js +2 -1
  21. package/node_modules/@diffci.com/core/dist/planner/path-baseline.js.map +1 -1
  22. package/node_modules/@diffci.com/core/dist/repo/file-references.js +6 -3
  23. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  24. package/node_modules/@diffci.com/core/dist/repo/impact.js +1 -1
  25. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  26. package/node_modules/@diffci.com/core/src/git/ci-config-paths.ts +131 -0
  27. package/node_modules/@diffci.com/core/src/git/git-diff.ts +18 -4
  28. package/node_modules/@diffci.com/core/src/planner/path-baseline.ts +2 -1
  29. package/node_modules/@diffci.com/core/src/repo/file-references.ts +6 -3
  30. package/node_modules/@diffci.com/core/src/repo/impact.ts +1 -1
  31. package/package.json +12 -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;
@@ -10,7 +10,7 @@ export interface ObservationEnvironment {
10
10
  [key: string]: string | undefined;
11
11
  }
12
12
  export interface CiEnvironmentFacts {
13
- provider: "github-actions" | "local" | "unknown";
13
+ provider: "github-actions" | "gitlab-ci" | "local" | "unknown";
14
14
  ownerName?: string;
15
15
  providerRepositoryId?: string;
16
16
  defaultBranch?: string;
@@ -48,7 +48,26 @@ function nested(record, ...keys) {
48
48
  function asString(value) {
49
49
  return typeof value === "string" && value !== "" ? value : undefined;
50
50
  }
51
+ /** GitLab pipeline sources with no change of their own to analyse (2026-11-05). */
52
+ const GITLAB_SYNTHETIC_SOURCES = new Set(["schedule", "web", "api", "trigger", "pipeline", "parent_pipeline", "chat", "webide"]);
53
+ function readGitlabEnvironment(env) {
54
+ const event = asString(env.CI_PIPELINE_SOURCE);
55
+ return {
56
+ provider: "gitlab-ci",
57
+ ownerName: asString(env.CI_PROJECT_PATH),
58
+ providerRepositoryId: asString(env.CI_PROJECT_ID),
59
+ defaultBranch: asString(env.CI_DEFAULT_BRANCH),
60
+ runId: asString(env.CI_PIPELINE_ID),
61
+ workflow: asString(env.CI_CONFIG_PATH),
62
+ job: asString(env.CI_JOB_NAME),
63
+ event,
64
+ ref: asString(env.CI_COMMIT_REF_NAME),
65
+ syntheticTrigger: event !== undefined && GITLAB_SYNTHETIC_SOURCES.has(event),
66
+ };
67
+ }
51
68
  export function readCiEnvironment(env) {
69
+ if (env.GITLAB_CI === "true")
70
+ return readGitlabEnvironment(env);
52
71
  if (env.GITHUB_ACTIONS !== "true") {
53
72
  return { provider: env.CI === "true" ? "unknown" : "local" };
54
73
  }
@@ -89,6 +108,72 @@ function mergeBase(git, a, b) {
89
108
  }
90
109
  /** The one sentence every "commit missing locally" refusal ends with, so the fix is never a guess. */
91
110
  const DEEPEN_HINT = "the commit is not in this checkout - add `fetch-depth: 0` to the actions/checkout step in the job that runs DiffCI (this does not affect any other job)";
111
+ /** GitLab clones 20 commits deep by default, so a long merge request loses its base (2026-11-05). */
112
+ const GITLAB_DEEPEN_HINT = "the commit is not in this checkout - set `GIT_DEPTH: \"0\"` in the variables of the job that runs DiffCI (this does not affect any other job)";
113
+ function deepenHint(env) {
114
+ return env.GITLAB_CI === "true" ? GITLAB_DEEPEN_HINT : DEEPEN_HINT;
115
+ }
116
+ /**
117
+ * GitLab's version of the GitHub event handling below (2026-11-05). The traps have different names:
118
+ *
119
+ * - In a merged-results pipeline `CI_COMMIT_SHA` is a merge commit GitLab created, like GitHub's
120
+ * merge ref. The source branch head is `CI_MERGE_REQUEST_SOURCE_BRANCH_SHA`, which GitLab sets
121
+ * only in merged-results pipelines; in a plain merge request pipeline `CI_COMMIT_SHA` is the head.
122
+ * - `CI_COMMIT_BEFORE_SHA` is forty zeros in every merge request pipeline and on a branch's first
123
+ * push, so it is read only for pushes and never trusted when zero.
124
+ *
125
+ * Returns undefined for pipeline sources that carry no range (schedule, web, api, ...), which then
126
+ * take the generic HEAD^ path with `syntheticTrigger` recorded, exactly as a GitHub schedule does.
127
+ */
128
+ function resolveGitlabRange(env, git) {
129
+ const hint = GITLAB_DEEPEN_HINT;
130
+ const source = env.CI_PIPELINE_SOURCE;
131
+ if (source === "merge_request_event") {
132
+ const headSha = asString(env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA) ?? asString(env.CI_COMMIT_SHA);
133
+ const baseSha = asString(env.CI_MERGE_REQUEST_DIFF_BASE_SHA);
134
+ if (!headSha || !baseSha) {
135
+ return { ok: false, reason: "merge request pipeline carried no CI_MERGE_REQUEST_DIFF_BASE_SHA or head commit" };
136
+ }
137
+ if (!commitExists(git, headSha)) {
138
+ return { ok: false, reason: `merge request head ${headSha.slice(0, 12)} is not present locally: ${hint}` };
139
+ }
140
+ if (!commitExists(git, baseSha)) {
141
+ return { ok: false, reason: `merge request base ${baseSha.slice(0, 12)} is not present locally: ${hint}` };
142
+ }
143
+ // The diff base is already the merge base when the pipeline was created. Recomputing it guards
144
+ // against a retried job whose source branch was rebased since; a different answer is recorded.
145
+ const common = mergeBase(git, baseSha, headSha);
146
+ return {
147
+ ok: true,
148
+ range: {
149
+ baseSha: common ?? baseSha,
150
+ headSha,
151
+ source: "pull-request-event",
152
+ mergeBaseSha: common && common !== baseSha ? common : undefined,
153
+ },
154
+ };
155
+ }
156
+ if (source === "push") {
157
+ const headSha = asString(env.CI_COMMIT_SHA) ?? resolveSha(git, "HEAD");
158
+ if (!headSha)
159
+ return { ok: false, reason: "could not determine the head commit of this push" };
160
+ const before = asString(env.CI_COMMIT_BEFORE_SHA);
161
+ if (before && before !== ZERO_SHA && commitExists(git, before)) {
162
+ return { ok: true, range: { baseSha: before, headSha, source: "push-event" } };
163
+ }
164
+ const parent = resolveSha(git, `${headSha}^`);
165
+ if (!parent) {
166
+ return {
167
+ ok: false,
168
+ reason: before === ZERO_SHA || before === undefined
169
+ ? `this push created the branch and its head commit has no parent in this checkout: ${hint}`
170
+ : `no usable base commit for this push: ${hint}`,
171
+ };
172
+ }
173
+ return { ok: true, range: { baseSha: parent, headSha, source: "head-parent" } };
174
+ }
175
+ return undefined;
176
+ }
92
177
  export function resolveCommitRange(options) {
93
178
  const { env, git, baseOverride, headOverride } = options;
94
179
  if (baseOverride !== undefined || headOverride !== undefined) {
@@ -98,11 +183,16 @@ export function resolveCommitRange(options) {
98
183
  const base = resolveSha(git, baseOverride);
99
184
  const head = resolveSha(git, headOverride);
100
185
  if (!base)
101
- return { ok: false, reason: `base revision ${baseOverride} could not be resolved: ${DEEPEN_HINT}` };
186
+ return { ok: false, reason: `base revision ${baseOverride} could not be resolved: ${deepenHint(env)}` };
102
187
  if (!head)
103
- return { ok: false, reason: `head revision ${headOverride} could not be resolved: ${DEEPEN_HINT}` };
188
+ return { ok: false, reason: `head revision ${headOverride} could not be resolved: ${deepenHint(env)}` };
104
189
  return { ok: true, range: { baseSha: base, headSha: head, source: "explicit-flags" } };
105
190
  }
191
+ if (env.GITLAB_CI === "true") {
192
+ const gitlab = resolveGitlabRange(env, git);
193
+ if (gitlab)
194
+ return gitlab;
195
+ }
106
196
  const payload = readEventPayload(env);
107
197
  const event = env.GITHUB_EVENT_NAME;
108
198
  if (event === "pull_request" || event === "pull_request_target") {
@@ -166,7 +256,7 @@ export function resolveCommitRange(options) {
166
256
  if (!parent) {
167
257
  return {
168
258
  ok: false,
169
- reason: `HEAD has no parent commit in this checkout, so there is no range to analyse: ${DEEPEN_HINT}`,
259
+ reason: `HEAD has no parent commit in this checkout, so there is no range to analyse: ${deepenHint(env)}`,
170
260
  };
171
261
  }
172
262
  return { ok: true, range: { baseSha: parent, headSha: head, source: "head-parent" } };
@@ -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"]);
@@ -108,7 +121,7 @@ export async function observe(options) {
108
121
  platform: process.platform,
109
122
  },
110
123
  repository: {
111
- provider: ci.provider === "github-actions" ? "github" : "unknown",
124
+ provider: ci.provider === "github-actions" ? "github" : ci.provider === "gitlab-ci" ? "gitlab" : "unknown",
112
125
  ownerName: owner && name ? `${owner}/${name}` : undefined,
113
126
  defaultBranch: ci.defaultBranch,
114
127
  providerRepositoryId: ci.providerRepositoryId,
@@ -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
+ }
@@ -36,7 +36,7 @@ export interface ObservationCommitRange {
36
36
  mergeBaseSha?: string;
37
37
  }
38
38
  export interface ObservationRepository {
39
- provider: "github" | "unknown";
39
+ provider: "github" | "gitlab" | "unknown";
40
40
  /** "owner/name". The only repository identifier sent; never a URL carrying a token. */
41
41
  ownerName?: string;
42
42
  defaultBranch?: string;
@@ -44,7 +44,7 @@ export interface ObservationRepository {
44
44
  providerRepositoryId?: string;
45
45
  }
46
46
  export interface ObservationCi {
47
- provider: "github-actions" | "local" | "unknown";
47
+ provider: "github-actions" | "gitlab-ci" | "local" | "unknown";
48
48
  runId?: string;
49
49
  runAttempt?: string;
50
50
  workflow?: string;
@@ -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,
@@ -171,6 +171,8 @@ Sponsors' bug reports are labelled [`sponsor`](https://github.com/DiffCI/core/la
171
171
 
172
172
  Only the explicitly extracted Core files and standalone tooling are in this repository. There is no private monorepo history, customer data, deployment configuration or Cloud implementation here. Core is usable independently; it is not a promise that the private product has already migrated to consume this package.
173
173
 
174
+ DiffCI Cloud's team features are free for public open-source repositories: an organization whose connected repositories are all public on GitHub gets them at no cost.
175
+
174
176
  What stays in Core, and never moves to Cloud, is set out in [STEWARDSHIP.md](STEWARDSHIP.md). The plan DiffCI writes for each change is an open format other tools can produce or consume: [the change plan](docs/change-plan.md). Report vulnerabilities privately as described in [SECURITY.md](SECURITY.md).
175
177
 
176
178
  ## Contributing
@@ -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;