@diffci.com/diffci 0.3.20 → 0.3.22

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 (56) hide show
  1. package/dist-client/src/client/agent-identity.d.ts +26 -0
  2. package/dist-client/src/client/agent-identity.js +62 -0
  3. package/dist-client/src/client/agent-selection.d.ts +55 -0
  4. package/dist-client/src/client/cli.d.ts +2 -0
  5. package/dist-client/src/client/cli.js +164 -3
  6. package/dist-client/src/client/command-batches.d.ts +26 -0
  7. package/dist-client/src/client/command-batches.js +7 -1
  8. package/dist-client/src/client/context.d.ts +47 -0
  9. package/dist-client/src/client/delivery-warning.d.ts +1 -0
  10. package/dist-client/src/client/economics.d.ts +17 -0
  11. package/dist-client/src/client/enforce-misses-collect.d.ts +49 -0
  12. package/dist-client/src/client/enforce-misses.d.ts +124 -0
  13. package/dist-client/src/client/enforce-policy.d.ts +33 -0
  14. package/dist-client/src/client/failure-baseline.d.ts +67 -0
  15. package/dist-client/src/client/failure-baseline.js +43 -19
  16. package/dist-client/src/client/feedback-prompt.d.ts +6 -0
  17. package/dist-client/src/client/full-command.d.ts +16 -0
  18. package/dist-client/src/client/gate-checks.d.ts +54 -0
  19. package/dist-client/src/client/gate-checks.js +21 -7
  20. package/dist-client/src/client/gate.d.ts +154 -0
  21. package/dist-client/src/client/gate.js +221 -0
  22. package/dist-client/src/client/hook.d.ts +27 -0
  23. package/dist-client/src/client/install.d.ts +19 -0
  24. package/dist-client/src/client/mcp.d.ts +2 -0
  25. package/dist-client/src/client/observe.d.ts +52 -0
  26. package/dist-client/src/client/observe.js +25 -3
  27. package/dist-client/src/client/package-identity.d.ts +14 -0
  28. package/dist-client/src/client/pilot-packet.d.ts +6 -0
  29. package/dist-client/src/client/report.d.ts +265 -0
  30. package/dist-client/src/client/selected-coverage.d.ts +19 -0
  31. package/dist-client/src/client/selected-coverage.js +86 -0
  32. package/dist-client/src/client/shared-graph-cache.d.ts +113 -0
  33. package/dist-client/src/client/shared-graph-cache.js +347 -0
  34. package/dist-client/src/client/spec-conflicts.d.ts +19 -0
  35. package/dist-client/src/client/submit.d.ts +61 -0
  36. package/dist-client/src/client/telemetry.d.ts +13 -0
  37. package/dist-client/src/client/usage-signal.d.ts +19 -0
  38. package/dist-client/src/client/verify-savings.d.ts +186 -0
  39. package/dist-client/src/client/verify-savings.js +3 -0
  40. package/dist-client/src/client/verify.d.ts +113 -0
  41. package/dist-client/src/client/verify.js +37 -13
  42. package/dist-client/src/client/workflow-guard.d.ts +59 -0
  43. package/dist-client/src/client/workflow-guard.js +253 -0
  44. package/dist-client/src/client/workflow-templates.d.ts +8 -0
  45. package/dist-client/src/client/working-tree.d.ts +26 -0
  46. package/dist-client/src/preflight/fingerprint.d.ts +29 -0
  47. package/dist-client/src/preflight/taxonomy.d.ts +10 -0
  48. package/node_modules/@diffci.com/core/README.md +4 -0
  49. package/node_modules/@diffci.com/core/dist/git/git-diff.js +17 -2
  50. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  51. package/node_modules/@diffci.com/core/dist/planner/test-command.d.ts +2 -0
  52. package/node_modules/@diffci.com/core/dist/planner/test-command.js +46 -1
  53. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  54. package/node_modules/@diffci.com/core/src/git/git-diff.ts +17 -2
  55. package/node_modules/@diffci.com/core/src/planner/test-command.ts +45 -1
  56. package/package.json +9 -2
@@ -0,0 +1,124 @@
1
+ import type { VerificationReport } from "./verify.js";
2
+ export declare const MISS_REPORT_SCHEMA: "diffci.enforce-misses.v1";
3
+ export interface TestOutcome {
4
+ /** `file > suite > name`: stable across runs of the same commit, so it can be matched between them. */
5
+ id: string;
6
+ /** Repository-relative, forward slashes. Empty when the reporter gave no file. */
7
+ file: string;
8
+ name: string;
9
+ failed: boolean;
10
+ skipped: boolean;
11
+ }
12
+ /** The receipt fields the detector reads; older receipts may lack `selected_tests`. */
13
+ export type ReceiptFields = Pick<VerificationReport, "schema" | "selection" | "selected_tests" | "command" | "enforcement" | "commit_range">;
14
+ export interface PullRequestReceipt {
15
+ artifact: string;
16
+ report: ReceiptFields;
17
+ }
18
+ export interface MergedPullRequest {
19
+ number: number;
20
+ title?: string;
21
+ mergeSha: string;
22
+ headSha: string;
23
+ receipt?: PullRequestReceipt;
24
+ }
25
+ /**
26
+ * What one merged pull request's receipt says about one failing test.
27
+ * - `missed`: the receipt selected tests and this test's file was not among them.
28
+ * - `selection-unrecorded`: the receipt selected tests but does not say which; counted as a miss,
29
+ * because "cannot tell" must not read as "was covered".
30
+ * - `selected` / `ran-full`: the pull request ran this test, so it did not skip it.
31
+ * - `no-tests-run`: a `none` receipt (blocked analysis). Enforce mode never passes such a run.
32
+ * - `no-receipt`: no dry-run artifact was found for the pull request's head.
33
+ */
34
+ export type PullRequestVerdict = "missed" | "selection-unrecorded" | "selected" | "ran-full" | "no-tests-run" | "no-receipt";
35
+ export type FailureClass =
36
+ /** Deterministic, new, and skipped by at least one `selected` pull request. Counts. */
37
+ "miss"
38
+ /** Passed when re-run. Logged, never counted. */
39
+ | "flaky"
40
+ /** Already failing at the start of the window, so no pull request in it introduced it. */
41
+ | "pre-existing"
42
+ /** Every pull request with a receipt ran it (selected it, or ran the full suite). */
43
+ | "covered"
44
+ /** No merged pull request with a receipt to hold it against (direct push, drift, environment). */
45
+ | "unattributed";
46
+ export interface ClassifiedFailure {
47
+ id: string;
48
+ file: string;
49
+ name: string;
50
+ classification: FailureClass;
51
+ pull_requests: {
52
+ number: number;
53
+ verdict: PullRequestVerdict;
54
+ artifact?: string;
55
+ }[];
56
+ detail: string;
57
+ }
58
+ export interface UnsafeMissEntry {
59
+ test: string;
60
+ pullRequest: number;
61
+ receipt: string | null;
62
+ mainSha: string;
63
+ detectedAt: string;
64
+ run?: string;
65
+ }
66
+ export type WindowSource = "detector-record" | "green-full-run" | "none";
67
+ export interface MissReport {
68
+ schema: typeof MISS_REPORT_SCHEMA;
69
+ produced_at: string;
70
+ head_sha: string;
71
+ run_url?: string;
72
+ full_suite: "passed" | "failed";
73
+ rerun: "done" | "not-run";
74
+ window: {
75
+ from_sha: string | null;
76
+ source: WindowSource;
77
+ };
78
+ pull_requests: {
79
+ number: number;
80
+ merge_sha: string;
81
+ head_sha: string;
82
+ receipt: string | null;
83
+ selection: ReceiptFields["selection"] | null;
84
+ }[];
85
+ /** Ids of the failures that were not flaky. The next run reads these as its pre-existing set. */
86
+ deterministic_failures: string[];
87
+ failures: ClassifiedFailure[];
88
+ misses: number;
89
+ open_unsafe_misses: UnsafeMissEntry[];
90
+ notes: string[];
91
+ }
92
+ /** Repository-relative with forward slashes; paths outside the repository stay absolute. */
93
+ export declare function normalizeTestPath(path: string, repoRoot: string): string;
94
+ /** Testcases in document order, named by their enclosing suites. Repeated ids are merged: any failure wins. */
95
+ export declare function parseJunit(xml: string, repoRoot: string): TestOutcome[];
96
+ /**
97
+ * The test files a `selected` receipt ran. Receipts from before `selected_tests` existed fall back to the
98
+ * test-file arguments of the command. `undefined` means the receipt does not say.
99
+ */
100
+ export declare function selectedFiles(report: ReceiptFields): Set<string> | undefined;
101
+ export interface ClassifyInput {
102
+ /** Every testcase of the full run on `main`; only failures are classified. */
103
+ fullRun: TestOutcome[];
104
+ /** The re-run of the failing files, or undefined when no re-run was possible. */
105
+ rerun: TestOutcome[] | undefined;
106
+ /** Ids already failing at the start of the window. */
107
+ baseline: readonly string[];
108
+ pullRequests: MergedPullRequest[];
109
+ }
110
+ export declare function classifyFailures(input: ClassifyInput): ClassifiedFailure[];
111
+ export declare function unsafeMissEntries(failures: readonly ClassifiedFailure[], context: {
112
+ headSha: string;
113
+ detectedAt: string;
114
+ runUrl?: string;
115
+ }): UnsafeMissEntry[];
116
+ export interface BuildReportInput extends ClassifyInput {
117
+ headSha: string;
118
+ producedAt: string;
119
+ runUrl?: string;
120
+ window: MissReport["window"];
121
+ notes?: string[];
122
+ }
123
+ export declare function buildMissReport(input: BuildReportInput): MissReport;
124
+ export declare function formatMissReportMarkdown(report: MissReport): string;
@@ -0,0 +1,33 @@
1
+ import { type GitRunner } from "./context.js";
2
+ import type { ObservationReport } from "./report.js";
3
+ /** The only policy shape this CLI understands. A newer or older `enforce` block falls back to FULL. */
4
+ export declare const ENFORCE_POLICY_VERSION = 1;
5
+ export declare const FORCE_FULL_LABEL = "diffci:force-full";
6
+ export declare const ENFORCE_VARIABLE = "DIFFCI_ENFORCE";
7
+ export type EnforcementFallback = "kill-switch" | "per-run-override" | "policy-not-approved" | "open-unsafe-miss" | "untrusted-range" | "analysis-failure" | "graph-confidence" | "global-risk" | "empty-selection";
8
+ export interface EnforcementContext {
9
+ /** Value of DIFFCI_ENFORCE. Anything but "on" keeps enforcement off. */
10
+ killSwitch: string | undefined;
11
+ pullRequestLabels: string[];
12
+ headCommitMessage: string | undefined;
13
+ /** The raw `enforce` block of diffci.config.json, read at the range BASE so a change cannot approve itself. */
14
+ policy: unknown;
15
+ range: {
16
+ trusted: true;
17
+ } | {
18
+ trusted: false;
19
+ reason: string;
20
+ };
21
+ pathsRedacted: boolean;
22
+ }
23
+ export interface EnforcementDecision {
24
+ policy: "enforce";
25
+ policy_version: typeof ENFORCE_POLICY_VERSION;
26
+ /** null when every check passed and the selected tests may replace the full suite. */
27
+ fired_fallback: EnforcementFallback | null;
28
+ detail: string;
29
+ }
30
+ /** Matches a `DiffCI: full` trailer line anywhere in the head commit message. */
31
+ export declare function hasForceFullTrailer(message: string | undefined): boolean;
32
+ export declare function evaluateEnforcement(context: EnforcementContext, observation: ObservationReport): EnforcementDecision;
33
+ export declare function collectEnforcementContext(runner: GitRunner, env: Record<string, string | undefined>, observation: ObservationReport): EnforcementContext;
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Did this change introduce the failures, or were they already there? (2026-10-21.)
3
+ *
4
+ * WHY. 44 of DentalPresence's 124 verification receipts failed, and about 31 of those were one
5
+ * route-list assertion failing on commit after commit. Each receipt told the agent "verification
6
+ * failed" with nothing to separate a regression it caused from a suite that was already red.
7
+ *
8
+ * WHAT. On request, the failing command is rerun against the base commit, exported with `git archive`
9
+ * into a temporary directory (the repository, its index and its .git are never written), and the
10
+ * failing test names on both sides are compared. The verdict never changes: a red suite stays
11
+ * `failed` and `safe_to_continue` stays false, because required CI fails either way. Only the
12
+ * explanation changes.
13
+ *
14
+ * WHEN IT DECLINES. No identifiable failing test names, a dependency manifest or lockfile that differs
15
+ * between base and head (the base would run against the wrong installed dependencies), no installed
16
+ * node_modules to share, or an export or run that fails to start: the status is `unknown`, with why.
17
+ */
18
+ export interface FailureBaseline {
19
+ status: "preexisting" | "introduced" | "mixed" | "unknown";
20
+ base_sha: string;
21
+ reason: string;
22
+ failing_at_head: number;
23
+ failing_at_base?: number;
24
+ /** Failing test names found on both sides, at most 20. */
25
+ preexisting: string[];
26
+ /** Failing test names found only at head, at most 20. */
27
+ introduced: string[];
28
+ base_execution?: {
29
+ exit_code: number | null;
30
+ wall_ms: number;
31
+ timed_out: boolean;
32
+ };
33
+ }
34
+ /** Test names a runner reported as failing: node:test spec and TAP, Vitest and Jest. */
35
+ export declare function failingTestNames(output: string): string[];
36
+ export declare function compareWithBaseline(input: {
37
+ repoPath: string;
38
+ baseSha: string;
39
+ /** The commit (or snapshot commit) that was verified. */
40
+ headSha: string;
41
+ commands: readonly string[];
42
+ headFailures: readonly string[];
43
+ timeoutMs: number;
44
+ }): FailureBaseline;
45
+ /**
46
+ * A gate check that failed at head, rerun at the base (2026-10-31). The CI replay found 5 introduced
47
+ * breakages hidden behind a check that was already red at the base (DentalPresence `validate:aws`):
48
+ * verify stopped at that check and never reached the change's own failure. A check is all or nothing,
49
+ * so the comparison is its exit status, not test names.
50
+ */
51
+ export interface CheckBaseline {
52
+ status: "preexisting" | "introduced" | "unknown";
53
+ base_sha: string;
54
+ reason: string;
55
+ base_execution?: {
56
+ exit_code: number | null;
57
+ wall_ms: number;
58
+ timed_out: boolean;
59
+ };
60
+ }
61
+ export declare function checkAtBaseline(input: {
62
+ repoPath: string;
63
+ baseSha: string;
64
+ headSha: string;
65
+ command: string;
66
+ timeoutMs: number;
67
+ }): CheckBaseline;
@@ -37,24 +37,7 @@ export function compareWithBaseline(input) {
37
37
  });
38
38
  if (input.headFailures.length === 0)
39
39
  return report("unknown", "no failing test names could be identified in the verification output");
40
- const changedDependencies = git(input.repoPath, ["diff", "--quiet", input.baseSha, input.headSha, "--", ...DEPENDENCY_FILES]);
41
- if (changedDependencies.status !== 0)
42
- return report("unknown", "dependency manifests or lockfiles differ between base and head");
43
- const modules = join(input.repoPath, "node_modules");
44
- if (declaresDependencies(input.repoPath) && !existsSync(modules)) {
45
- return report("unknown", "no installed node_modules to run the base commit with");
46
- }
47
- const directory = mkdtempSync(join(tmpdir(), "diffci-baseline-"));
48
- const link = join(directory, "node_modules");
49
- try {
50
- const archive = git(input.repoPath, ["archive", "--format=tar", input.baseSha]);
51
- if (archive.status !== 0)
52
- return report("unknown", "the base commit could not be exported");
53
- const extract = spawnSync("tar", ["-x", "-f", "-", "-C", directory], { input: archive.stdout, maxBuffer: 64 * 1024 * 1024 });
54
- if (extract.status !== 0)
55
- return report("unknown", "the base commit could not be extracted");
56
- if (existsSync(modules))
57
- symlinkSync(modules, link, process.platform === "win32" ? "junction" : "dir");
40
+ const run = withBaseTree(input, (directory) => {
58
41
  const execution = measureCommands(input.commands, { cwd: directory, timeoutMs: input.timeoutMs, tailBytes: 0 });
59
42
  const baseExecution = { exit_code: execution.exitCode, wall_ms: execution.wallMs, timed_out: execution.timedOut };
60
43
  if (execution.timedOut)
@@ -72,9 +55,50 @@ export function compareWithBaseline(input) {
72
55
  ? `none of the ${introduced.length} failing test(s) fail at the base commit`
73
56
  : `${introduced.length} failing test(s) are new; ${preexisting.length} also fail at the base commit`;
74
57
  return report(status, reason, { failing_at_base: atBase.size, preexisting: preexisting.slice(0, 20), introduced: introduced.slice(0, 20), base_execution: baseExecution });
58
+ });
59
+ return run.ok ? run.value : report("unknown", run.reason);
60
+ }
61
+ export function checkAtBaseline(input) {
62
+ const report = (status, reason, extra = {}) => ({ status, base_sha: input.baseSha, reason, ...extra });
63
+ const run = withBaseTree(input, (directory) => {
64
+ const execution = measureCommands([input.command], { cwd: directory, timeoutMs: input.timeoutMs, tailBytes: 0 });
65
+ const baseExecution = { exit_code: execution.exitCode, wall_ms: execution.wallMs, timed_out: execution.timedOut };
66
+ if (execution.timedOut)
67
+ return report("unknown", "the base run timed out", { base_execution: baseExecution });
68
+ return execution.exitCode === 0
69
+ ? report("introduced", "the same check passes at the base commit", { base_execution: baseExecution })
70
+ : report("preexisting", "the same check also fails at the base commit", { base_execution: baseExecution });
71
+ });
72
+ return run.ok ? run.value : report("unknown", run.reason);
73
+ }
74
+ /**
75
+ * Runs `use` in the base commit, exported with `git archive` into a temporary directory with the
76
+ * repository's installed node_modules linked in. The same declines apply to tests and checks: the
77
+ * dependency manifests differ, or nothing is installed. The repository itself is never written.
78
+ */
79
+ function withBaseTree(input, use) {
80
+ const changedDependencies = git(input.repoPath, ["diff", "--quiet", input.baseSha, input.headSha, "--", ...DEPENDENCY_FILES]);
81
+ if (changedDependencies.status !== 0)
82
+ return { ok: false, reason: "dependency manifests or lockfiles differ between base and head" };
83
+ const modules = join(input.repoPath, "node_modules");
84
+ if (declaresDependencies(input.repoPath) && !existsSync(modules)) {
85
+ return { ok: false, reason: "no installed node_modules to run the base commit with" };
86
+ }
87
+ const directory = mkdtempSync(join(tmpdir(), "diffci-baseline-"));
88
+ const link = join(directory, "node_modules");
89
+ try {
90
+ const archive = git(input.repoPath, ["archive", "--format=tar", input.baseSha]);
91
+ if (archive.status !== 0)
92
+ return { ok: false, reason: "the base commit could not be exported" };
93
+ const extract = spawnSync("tar", ["-x", "-f", "-", "-C", directory], { input: archive.stdout, maxBuffer: 64 * 1024 * 1024 });
94
+ if (extract.status !== 0)
95
+ return { ok: false, reason: "the base commit could not be extracted" };
96
+ if (existsSync(modules))
97
+ symlinkSync(modules, link, process.platform === "win32" ? "junction" : "dir");
98
+ return { ok: true, value: use(directory) };
75
99
  }
76
100
  catch (error) {
77
- return report("unknown", `the base run could not be prepared: ${error instanceof Error ? error.message : String(error)}`);
101
+ return { ok: false, reason: `the base run could not be prepared: ${error instanceof Error ? error.message : String(error)}` };
78
102
  }
79
103
  finally {
80
104
  // Remove the dependency link itself first, so cleanup can never descend into the real node_modules.
@@ -0,0 +1,6 @@
1
+ import { type TelemetryMode } from "./telemetry.js";
2
+ type Flags = Record<string, string | boolean>;
3
+ export declare function shouldShowFeedbackPrompt(flags: Flags, env: NodeJS.ProcessEnv, interactive: boolean, now?: number): boolean;
4
+ export declare function formatFeedbackPrompt(telemetry: TelemetryMode): string;
5
+ export declare function markFeedbackPromptShown(env: NodeJS.ProcessEnv, now?: number): void;
6
+ export {};
@@ -0,0 +1,16 @@
1
+ /** Rebuild the complete plan locally; never join arbitrary report commands. */
2
+ export declare function inferWorkspaceComparison(repoPath: string, proposed: readonly string[], selectedTests: readonly string[]): {
3
+ full?: string;
4
+ selected?: string;
5
+ reason: string;
6
+ };
7
+ export interface FullCommandDecision {
8
+ command?: string;
9
+ reason: string;
10
+ }
11
+ /** Automatic timing must retain the non-selected phases of the declared test script. */
12
+ export declare function inferComparableSelectedCommand(repoPath: string, proposed: string, selectedTests: readonly string[]): FullCommandDecision;
13
+ /** Preserve the repository's TypeScript test loader for selected node:test files. */
14
+ export declare function inferSelectedCommand(repoPath: string, proposed: string, selectedTests: readonly string[]): FullCommandDecision;
15
+ /** Choose the repository's conventional full test command without executing anything. */
16
+ export declare function inferFullCommand(repoPath: string): FullCommandDecision;
@@ -0,0 +1,54 @@
1
+ import { type GateCheckKind } from "@diffci.com/core/planner/pipeline-steps";
2
+ import type { CheckBaseline } from "./failure-baseline.js";
3
+ import { measureCommand } from "./verify-savings.js";
4
+ /** One leaf of the repository's gate (`npm run check`), as an agent or verify runs it. */
5
+ export interface PlannedCheck {
6
+ id: string;
7
+ kind: GateCheckKind;
8
+ /** RUN as written, NARROWED to the changed files, or SKIP for this change (never run). */
9
+ decision: "RUN" | "NARROWED" | "SKIP";
10
+ command: string;
11
+ reason: string;
12
+ }
13
+ export interface CheckResult extends PlannedCheck {
14
+ status: "passed" | "failed" | "timed_out" | "not_run" | "skipped";
15
+ exit_code?: number | null;
16
+ wall_ms?: number;
17
+ /** Present when a failed check was rerun at the base commit (`--baseline-on-failure`). */
18
+ baseline?: CheckBaseline;
19
+ }
20
+ /** The commits a change runs between; without one every check runs as written. */
21
+ export interface CheckChange {
22
+ baseSha: string;
23
+ headSha: string;
24
+ }
25
+ /**
26
+ * The checks the repository's gate runs besides its tests (2026-10-29, docs/design/pipeline-impact.md).
27
+ * Agents ran the tests DiffCI selected and then failed `npm run check` after push; these are the rest of
28
+ * the gate. With a change, per-file lint and format checks are narrowed to its files or skipped
29
+ * (check-narrowing.ts); if the change cannot be read, every check runs. No package.json, or one that
30
+ * cannot be read, has none. `extraRoots` replaces the scripts CI workflows add to the gate, for a caller
31
+ * that knows exactly which scripts its build runs (`diffci gate --script`).
32
+ */
33
+ export declare function plannedChecks(repoPath: string, change?: CheckChange, options?: {
34
+ extraRoots?: readonly string[];
35
+ }): PlannedCheck[];
36
+ /** Runs checks in order and stops at the first failure, as the gate's `&&` chain would. SKIP checks
37
+ * are recorded as skipped and not run. `baseline` reruns a failed check at the base commit; one that
38
+ * fails there too is recorded in `preexisting` and the run goes on, so a check that was already red
39
+ * cannot hide what the change itself broke. */
40
+ export declare function runChecks(checks: readonly PlannedCheck[], options: {
41
+ cwd: string;
42
+ timeoutMs: number;
43
+ tailBytes: number;
44
+ baseline?: (check: PlannedCheck, remainingMs: number) => CheckBaseline;
45
+ }): {
46
+ results: CheckResult[];
47
+ failure: {
48
+ check: CheckResult;
49
+ measurement: ReturnType<typeof measureCommand>;
50
+ } | undefined;
51
+ preexisting: CheckResult[];
52
+ outOfTime: boolean;
53
+ wallMs: number;
54
+ };
@@ -55,9 +55,10 @@ function readRepositoryFile(repoPath, path) {
55
55
  * Agents ran the tests DiffCI selected and then failed `npm run check` after push; these are the rest of
56
56
  * the gate. With a change, per-file lint and format checks are narrowed to its files or skipped
57
57
  * (check-narrowing.ts); if the change cannot be read, every check runs. No package.json, or one that
58
- * cannot be read, has none.
58
+ * cannot be read, has none. `extraRoots` replaces the scripts CI workflows add to the gate, for a caller
59
+ * that knows exactly which scripts its build runs (`diffci gate --script`).
59
60
  */
60
- export function plannedChecks(repoPath, change) {
61
+ export function plannedChecks(repoPath, change, options = {}) {
61
62
  const path = join(repoPath, "package.json");
62
63
  if (!existsSync(path))
63
64
  return [];
@@ -73,7 +74,8 @@ export function plannedChecks(repoPath, change) {
73
74
  const scripts = Object.fromEntries(Object.entries(pkg.scripts).filter((entry) => typeof entry[1] === "string"));
74
75
  const manager = packageManager(repoPath, pkg.packageManager);
75
76
  const lifecycleHooks = manager !== "pnpm";
76
- let { checks } = discoverGateChecks(scripts, { lifecycleHooks, workflowScripts: workflowGateScripts(workflowTexts(repoPath), scripts) });
77
+ const workflowScripts = options.extraRoots ?? workflowGateScripts(workflowTexts(repoPath), scripts);
78
+ let { checks } = discoverGateChecks(scripts, { lifecycleHooks, workflowScripts });
77
79
  if (change) {
78
80
  try {
79
81
  const changes = changedPaths(repoPath, change);
@@ -93,10 +95,13 @@ export function plannedChecks(repoPath, change) {
93
95
  }));
94
96
  }
95
97
  /** Runs checks in order and stops at the first failure, as the gate's `&&` chain would. SKIP checks
96
- * are recorded as skipped and not run. */
98
+ * are recorded as skipped and not run. `baseline` reruns a failed check at the base commit; one that
99
+ * fails there too is recorded in `preexisting` and the run goes on, so a check that was already red
100
+ * cannot hide what the change itself broke. */
97
101
  export function runChecks(checks, options) {
98
102
  const started = Date.now();
99
103
  const results = [];
104
+ const preexisting = [];
100
105
  let failure;
101
106
  for (const check of checks) {
102
107
  if (check.decision === "SKIP") {
@@ -112,9 +117,18 @@ export function runChecks(checks, options) {
112
117
  const status = measurement.timedOut ? "timed_out" : measurement.exitCode === 0 && measurement.signal === null ? "passed" : "failed";
113
118
  const result = { ...check, status, exit_code: measurement.exitCode, wall_ms: measurement.wallMs };
114
119
  results.push(result);
115
- if (status !== "passed")
116
- failure = { check: result, measurement };
120
+ if (status === "passed")
121
+ continue;
122
+ // Only a check run as written is comparable at the base: a NARROWED one names files the base may not have.
123
+ if (status === "failed" && check.decision === "RUN" && options.baseline) {
124
+ result.baseline = options.baseline(check, options.timeoutMs - (Date.now() - started));
125
+ if (result.baseline.status === "preexisting") {
126
+ preexisting.push(result);
127
+ continue;
128
+ }
129
+ }
130
+ failure = { check: result, measurement };
117
131
  }
118
132
  const outOfTime = !failure && results.some((result) => result.status === "not_run");
119
- return { results, failure, outOfTime, wallMs: Date.now() - started };
133
+ return { results, failure, preexisting, outOfTime, wallMs: Date.now() - started };
120
134
  }
@@ -0,0 +1,154 @@
1
+ import { type PlannedCheck } from "./gate-checks.js";
2
+ import { observe } from "./observe.js";
3
+ import type { ObservationReport } from "./report.js";
4
+ import { type CommandMeasurement } from "./verify-savings.js";
5
+ /**
6
+ * `diffci gate` in observe mode (2026-10-30, docs/design/pipeline-impact.md, phase 2).
7
+ *
8
+ * WHY. Builds that run a script instead of workflow jobs (DentalPresence's Cloudflare Sandbox build runs
9
+ * `npm run check` and its whole test suite on every staging build, about 19 of 44 build-hours) cannot use
10
+ * per-job `if:` conditions. `diffci gate` replaces that script. Before anything is skipped in a build, the
11
+ * miss rate has to be measured on real builds, so this mode changes nothing about what runs.
12
+ *
13
+ * WHAT IT DOES. Runs every leaf of the gate and the full test command, exactly as the build would, and
14
+ * exits with their result. Alongside, it records what DiffCI would have done for the same commit range:
15
+ * each check's RUN/NARROWED/SKIP decision and the test selection. A miss is a step DiffCI would have
16
+ * skipped or narrowed that failed in full while DiffCI's version passed; those are only rerun when the full
17
+ * step failed, so a passing build pays for nothing but the analysis. `--measure-selected` also runs the
18
+ * narrowed checks and selected tests on passing builds, to measure rather than estimate the saving.
19
+ *
20
+ * DiffCI never decides the build's outcome here: an analysis that fails still runs and reports the full gate.
21
+ */
22
+ export declare const GATE_SCHEMA: "diffci.gate.v1";
23
+ export type StepStatus = "passed" | "failed" | "timed_out" | "not_run";
24
+ export interface StepRun {
25
+ status: StepStatus;
26
+ wall_ms?: number;
27
+ exit_code?: number | null;
28
+ }
29
+ export interface GateCheckReport {
30
+ id: string;
31
+ kind: PlannedCheck["kind"];
32
+ /** What DiffCI would have done; UNPLANNED when the change could not be analysed. */
33
+ decision: PlannedCheck["decision"] | "UNPLANNED";
34
+ reason: string;
35
+ command: string;
36
+ narrowed_command?: string;
37
+ full: StepRun;
38
+ narrowed?: StepRun;
39
+ /** The full step failed and DiffCI would have skipped it, or its narrowed run passed. */
40
+ missed?: boolean;
41
+ }
42
+ export interface GateTestReport {
43
+ command: string;
44
+ full: StepRun & {
45
+ failing_tests?: string[];
46
+ };
47
+ selection: "selected" | "full" | "unavailable";
48
+ reason: string;
49
+ tests_selected: number;
50
+ tests_available: number;
51
+ selected_commands?: string[];
52
+ selected?: StepRun;
53
+ missed?: boolean;
54
+ }
55
+ export interface GateReport {
56
+ schema: typeof GATE_SCHEMA;
57
+ schema_version: "1";
58
+ produced_at: string;
59
+ diffci_version: string;
60
+ mode: "observe";
61
+ /** Present when the build runs its checks and tests as separate stages (`--only`). */
62
+ only?: "checks" | "tests";
63
+ /** Present when a plan was supplied (`--plan`): whether it was used. Analysis time then belongs to the
64
+ * planning step, not this report. */
65
+ plan?: "supplied" | "unusable";
66
+ range?: {
67
+ base_sha: string;
68
+ head_sha: string;
69
+ source: string;
70
+ };
71
+ analysis: {
72
+ status: string;
73
+ reason?: string;
74
+ mode?: string;
75
+ fallback_reasons: string[];
76
+ duration_ms?: number;
77
+ };
78
+ gate: {
79
+ status: "passed" | "failed";
80
+ wall_ms: number;
81
+ reason: string;
82
+ };
83
+ checks: GateCheckReport[];
84
+ tests?: GateTestReport;
85
+ summary: {
86
+ /** Every gate step run one after another, as observed. */
87
+ full_ms: number;
88
+ /** Analysis plus the steps DiffCI would have run. */
89
+ diffci_ms: number;
90
+ saved_ms: number;
91
+ /** `measured` when every step DiffCI would have run was timed; `estimated` when narrowed checks count at
92
+ * their full time and selected tests in proportion to the files selected. */
93
+ basis: "measured" | "estimated";
94
+ misses: string[];
95
+ };
96
+ }
97
+ export interface GateOptions {
98
+ repoPath: string;
99
+ env: Record<string, string | undefined>;
100
+ version: string;
101
+ engineSha?: string;
102
+ baseOverride?: string;
103
+ headOverride?: string;
104
+ /** The build's full test command; defaults to the repository's conventional one (`npm test`). */
105
+ tests?: string;
106
+ /** The build's gate scripts beyond `check`; replaces the scripts CI workflows add. */
107
+ scripts?: readonly string[];
108
+ measureSelected?: boolean;
109
+ /** Run one half of the gate, for builds that run checks and tests as separate stages (DentalPresence
110
+ * runs `npm run check` on the host and its tests in a container, because together they exhausted the
111
+ * builder's memory). */
112
+ only?: "checks" | "tests";
113
+ timeoutMs: number;
114
+ tailBytes: number;
115
+ /** A plan from `gate --plan-out`, used instead of analysing here (no git history needed). */
116
+ plan?: unknown;
117
+ /** The commit being gated; a plan for another commit is not used. */
118
+ expectHead?: string;
119
+ /** Injected for tests. */
120
+ run?: (command: string, options: {
121
+ cwd: string;
122
+ timeoutMs: number;
123
+ tailBytes: number;
124
+ }) => CommandMeasurement;
125
+ analyse?: (options: Parameters<typeof observe>[0]) => Promise<ObservationReport>;
126
+ }
127
+ export declare const GATE_PLAN_SCHEMA: "diffci.gate-plan.v1";
128
+ /**
129
+ * DiffCI's decisions for a range, without running anything. A build whose gate runs where there is no git
130
+ * history (DentalPresence's Sandbox receives a `git archive` of one commit) plans where the checkout is
131
+ * (`gate --plan-out`) and ships the plan to the stage that runs the gate (`gate --plan`).
132
+ */
133
+ export interface GatePlan {
134
+ schema: typeof GATE_PLAN_SCHEMA;
135
+ diffci_version: string;
136
+ range?: {
137
+ base_sha: string;
138
+ head_sha: string;
139
+ source: string;
140
+ };
141
+ analysis: GateReport["analysis"];
142
+ checks: PlannedCheck[];
143
+ tests: {
144
+ selection: "selected" | "full" | "unavailable";
145
+ reason: string;
146
+ tests_selected: number;
147
+ tests_available: number;
148
+ selected_commands?: string[];
149
+ };
150
+ }
151
+ export declare function planGate(options: Omit<GateOptions, "plan" | "expectHead" | "run" | "timeoutMs" | "tailBytes" | "measureSelected" | "only" | "tests">): Promise<GatePlan>;
152
+ export declare function runGate(options: GateOptions): Promise<GateReport>;
153
+ export declare function gateExitCode(report: GateReport): number;
154
+ export declare function formatGateSummary(report: GateReport): string;