From ebb6452fd5d811f99bbe13d5aa817f2a1a1a50dd Mon Sep 17 00:00:00 2001 From: adityankale190895 Date: Sun, 25 Oct 2026 21:22:12 +0530 Subject: [PATCH] feat(cli): port enforce policy, enforce-misses and telemetry consent from DiffCI.com Development of these features continued in DiffCI.com's private src/client after the CLI moved to Core on 2026-10-18, so the published CLI lacked them. Three-way merged from the common base (DiffCI.com b35f55c, the archived 0.3.10 source) onto Core's CLI: - add enforce-policy, enforce-misses, enforce-misses-collect and telemetry - verify: run --policy enforce on top of batched selection; fullSelection now returns the same shape as executableSelection - cli: keep --baseline-on-failure alongside --policy enforce, --share-usage, --no-send, and the telemetry and enforce-misses commands - give the CLI package its own tsx test runner and port the matching tests - list the new files in the reviewed release boundary Co-Authored-By: Claude Opus 5.5 --- packages/diffci-cli/package-lock.json | 521 +++++++++++++++++- packages/diffci-cli/package.json | 4 +- packages/diffci-cli/scripts/run-tests.mjs | 18 + packages/diffci-cli/src/client/cli.ts | 147 ++++- packages/diffci-cli/src/client/context.ts | 2 +- .../src/client/enforce-misses-collect.ts | 204 +++++++ .../diffci-cli/src/client/enforce-misses.ts | 347 ++++++++++++ .../diffci-cli/src/client/enforce-policy.ts | 199 +++++++ packages/diffci-cli/src/client/mcp.ts | 2 +- packages/diffci-cli/src/client/observe.ts | 2 +- packages/diffci-cli/src/client/telemetry.ts | 46 ++ .../diffci-cli/src/client/usage-signal.ts | 40 +- packages/diffci-cli/src/client/verify.ts | 47 +- .../tests/client/enforce-misses.test.ts | 288 ++++++++++ .../tests/client/enforce-policy.test.ts | 305 ++++++++++ .../diffci-cli/tests/client/telemetry.test.ts | 47 ++ release-files.json | 10 +- 17 files changed, 2195 insertions(+), 34 deletions(-) create mode 100644 packages/diffci-cli/scripts/run-tests.mjs create mode 100644 packages/diffci-cli/src/client/enforce-misses-collect.ts create mode 100644 packages/diffci-cli/src/client/enforce-misses.ts create mode 100644 packages/diffci-cli/src/client/enforce-policy.ts create mode 100644 packages/diffci-cli/src/client/telemetry.ts create mode 100644 packages/diffci-cli/tests/client/enforce-misses.test.ts create mode 100644 packages/diffci-cli/tests/client/enforce-policy.test.ts create mode 100644 packages/diffci-cli/tests/client/telemetry.test.ts diff --git a/packages/diffci-cli/package-lock.json b/packages/diffci-cli/package-lock.json index 8dc1165c..84db6a6d 100644 --- a/packages/diffci-cli/package-lock.json +++ b/packages/diffci-cli/package-lock.json @@ -21,6 +21,7 @@ }, "devDependencies": { "@types/node": "^22.15.12", + "tsx": "^4.23.15", "typescript": "^5.8.3" }, "engines": { @@ -79,7 +80,7 @@ }, "node_modules/@diffci.com/core": { "version": "0.1.1", - "resolved": "git+https://github.com/DiffCI/core.git#e7ffdaf103800e71d74375afe4bc82604953bf19", + "resolved": "git+ssh://git@github.com/DiffCI/core.git#e7ffdaf103800e71d74375afe4bc82604953bf19", "integrity": "sha512-wgUCMms/PPFe/K+heFzBbX/CQU7lQRe/0OKbpVrDfQlV/EpsFyEQ0LbbSoOB1+U0ut0Wu1lLXWVYnSY9B4qCAQ==", "inBundle": true, "license": "AGPL-3.0-only", @@ -92,6 +93,448 @@ "node": ">=22.5.0" } }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, "node_modules/@jridgewell/sourcemap-codec": { "version": "1.5.5", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", @@ -183,6 +626,48 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, "node_modules/estree-walker": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", @@ -190,6 +675,21 @@ "inBundle": true, "license": "MIT" }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -265,6 +765,25 @@ "node": ">=0.10.0" } }, + "node_modules/tsx": { + "version": "4.23.15", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz", + "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.28.0" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", diff --git a/packages/diffci-cli/package.json b/packages/diffci-cli/package.json index 39d52ea5..ee237f43 100644 --- a/packages/diffci-cli/package.json +++ b/packages/diffci-cli/package.json @@ -55,7 +55,8 @@ "build:client": "tsc -p tsconfig.client.json && node scripts/ensure-client-executables.mjs", "prepack": "npm run build:client", "package:check": "node scripts/check-package-boundary.mjs", - "package:smoke": "node scripts/package-smoke.mjs" + "package:smoke": "node scripts/package-smoke.mjs", + "test": "node scripts/run-tests.mjs" }, "dependencies": { "@diffci.com/core": "git+https://github.com/DiffCI/core.git#e7ffdaf103800e71d74375afe4bc82604953bf19", @@ -63,6 +64,7 @@ }, "devDependencies": { "@types/node": "^22.15.12", + "tsx": "^4.23.15", "typescript": "^5.8.3" }, "bundleDependencies": [ diff --git a/packages/diffci-cli/scripts/run-tests.mjs b/packages/diffci-cli/scripts/run-tests.mjs new file mode 100644 index 00000000..9251c9f1 --- /dev/null +++ b/packages/diffci-cli/scripts/run-tests.mjs @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: AGPL-3.0-only +import { readdirSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { spawnSync } from 'node:child_process'; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +function collect(dir) { + return readdirSync(dir, { withFileTypes: true }).flatMap(entry => { + const full = join(dir, entry.name); + return entry.isDirectory() ? collect(full) : entry.name.endsWith('.test.ts') ? [full] : []; + }); +} +const tests = collect(join(root, 'tests')).sort(); +if (tests.length === 0) throw new Error('No tests found'); +const result = spawnSync(process.execPath, ['--import', 'tsx', '--test', ...tests], { cwd: root, stdio: 'inherit' }); +if (result.error) throw result.error; +process.exitCode = result.status ?? 1; diff --git a/packages/diffci-cli/src/client/cli.ts b/packages/diffci-cli/src/client/cli.ts index ac745f58..068921c0 100644 --- a/packages/diffci-cli/src/client/cli.ts +++ b/packages/diffci-cli/src/client/cli.ts @@ -17,6 +17,7 @@ * verify-savings run a paired full-versus-selected timing check * validate-specs block conflicting same-turn change specifications * verify-workflow check that a DiffCI job in this repository's workflows cannot affect other jobs + * enforce-misses after a full run on main, find failures enforce mode would have skipped * version print the observer version * * Exit codes: `observe` exits 0 even when it refuses or errors, because a broken observer must not @@ -37,7 +38,7 @@ import { addDiffciPackageScripts, detectPackageManager, installDiffci, type Supp import type { ObservationReport, WorkflowFinding } from "./report.js"; import { submitObservation } from "./submit.js"; import { githubDeliveryWarning } from "./delivery-warning.js"; -import { sendUsageSignal } from "./usage-signal.js"; +import { configureTelemetry, readTelemetryPreference, recordUsage } from "./telemetry.js"; import { detectSpecificationConflicts, readSpecificationFile } from "./spec-conflicts.js"; import { formatVerificationSummary, verificationExitCode, verifyChanged, verifyRange } from "./verify.js"; import { formatGrowthPrompt, formatVerifySavingsSummary, measureCommand, runVerifySavings, writeVerifySavingsReport, type VerifySavingsOptions } from "./verify-savings.js"; @@ -45,6 +46,17 @@ import { auditWorkflows, isNonInterfering } from "./workflow-guard.js"; import { renderPilotPacket } from "./pilot-packet.js"; import { observerIdentity } from "./package-identity.js"; import { buildPilotWorkflow, diffciVerificationWorkflow, diffciWorkflow } from "./workflow-templates.js"; +import { buildMissReport, formatMissReportMarkdown, parseJunit, type MissReport } from "./enforce-misses.js"; +import { + findReceipt, + findWindowStart, + inferRerunArgs, + mergedPullRequests, + MISS_REPORT_FILE, + rerunFailingFiles, + spawnRunner, + type CollectOptions, +} from "./enforce-misses-collect.js"; interface ParsedArgs { command?: string; @@ -280,6 +292,7 @@ function runInit(flags: Record, env: NodeJS.ProcessEnv if (!includeWorkflow) console.log(" skipped .github/workflows/diffci.yml (pass --workflow to add it)"); if (!includeVerificationWorkflow) console.log(" skipped .github/workflows/diffci-verify.yml (pass --verification-workflow to add it)"); console.log(`\nDefault agent command: ${agentCommand}`); + console.log("\nOptional telemetry is off unless you have opted in. Use diffci telemetry --mode anonymous for execution counts, or --mode installations to also share a random installation ID. No repository content is sent. Use --mode off to disable; --no-send always overrides consent."); return 0; } @@ -301,6 +314,15 @@ async function runVerifyCommand(flags: Record, env: No console.error("diffci verify accepts either --changed or --base/--head, not both"); return 2; } + const policy = flags.policy === true ? "" : stringFlag(flags, "policy"); + if (policy !== undefined && policy !== "enforce") { + console.error(`diffci verify --policy accepts only "enforce", got ${JSON.stringify(policy)}`); + return 2; + } + if (policy !== undefined && changed) { + console.error("diffci verify --policy enforce applies to a commit range, not --changed"); + return 2; + } const repoPath = resolve(stringFlag(flags, "repo") ?? env.GITHUB_WORKSPACE ?? process.cwd()); const out = stringFlag(flags, "out"); const reportPath = out ? resolve(out) : undefined; @@ -325,7 +347,9 @@ async function runVerifyCommand(flags: Record, env: No ...common, baseOverride: stringFlag(flags, "base"), headOverride: stringFlag(flags, "head"), + policy, }); + await recordUsage("verify", report.verification, identity.version, flags, env); if (reportPath) { mkdirSync(dirname(reportPath), { recursive: true }); writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, "utf8"); @@ -406,9 +430,7 @@ async function runCheck(flags: Record, env: NodeJS.Pro const observationCode = await runObserve({ ...flags, out: reportPath, quiet: true, "no-send": true }, env); if (observationCode !== 0) return observationCode; const observation = JSON.parse(readFileSync(reportPath, "utf8")) as ObservationReport; - if ((flags["share-usage"] === true || env.DIFFCI_SHARE_USAGE === "1") && flags["no-send"] !== true) { - await sendUsageSignal({ command: "check", outcome: observation.status === "OBSERVED" ? "observed" : observation.status === "REFUSED" ? "refused" : "error", version: observerIdentity().version }); - } + await recordUsage("check", observation.status === "OBSERVED" ? "observed" : observation.status === "REFUSED" ? "refused" : "error", observerIdentity().version, flags, env); const print = (message: string): void => { if (flags.quiet !== true && flags.json !== true) console.log(message); }; print(summarise(observation, true)); print(` observation report: ${reportPath}`); @@ -530,9 +552,7 @@ async function runObserve(flags: Record, env: NodeJS.P mkdirSync(dirname(reportPath), { recursive: true }); writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, "utf8"); - if ((flags["share-usage"] === true || env.DIFFCI_SHARE_USAGE === "1") && flags["no-send"] !== true) { - await sendUsageSignal({ command: "observe", outcome: report.status === "OBSERVED" ? "observed" : report.status === "REFUSED" ? "refused" : "error", version: identity.version }); - } + await recordUsage("observe", report.status === "OBSERVED" ? "observed" : report.status === "REFUSED" ? "refused" : "error", identity.version, flags, env); const summary = summarise(report); if (flags.json === true) { @@ -619,6 +639,92 @@ function runVerifyWorkflow(flags: Record, env: NodeJS. return 1; } +/** + * Miss detection (docs/enforce-mode-01-plan.md, step 5). Exit 0: no miss. Exit 1: at least one miss. + * Exit 2: the full run left no results to classify, or the invocation is wrong. It never edits + * diffci.config.json or repository variables; it prints the entries for a human to add. + */ +function runEnforceMisses(flags: Record, env: NodeJS.ProcessEnv): number { + const repoPath = resolve(stringFlag(flags, "repo") ?? env.GITHUB_WORKSPACE ?? process.cwd()); + const junitPath = stringFlag(flags, "junit"); + const outFlag = stringFlag(flags, "out-dir"); + const repository = stringFlag(flags, "repository") ?? env.GITHUB_REPOSITORY; + if (!junitPath || !outFlag || !repository) { + console.error("diffci enforce-misses needs --junit , --out-dir and --repository (or GITHUB_REPOSITORY)"); + return 2; + } + const outDir = resolve(outFlag); + if (outDir === repoPath || isInsideRepository(repoPath, outDir)) { + console.error(`Refusing to write the miss report inside the repository: ${outDir}. Use --out-dir outside the checkout.`); + return 2; + } + if (!existsSync(junitPath)) { + console.error(`No full-suite results at ${junitPath}: nothing can be classified, so no miss can be ruled out.`); + return 2; + } + const headSha = stringFlag(flags, "head") ?? execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoPath, encoding: "utf8" }).trim(); + const fullRun = parseJunit(readFileSync(junitPath, "utf8"), repoPath); + const failing = fullRun.filter((outcome) => outcome.failed); + const runUrl = env.GITHUB_RUN_ID ? `${env.GITHUB_SERVER_URL ?? "https://github.com"}/${repository}/actions/runs/${env.GITHUB_RUN_ID}` : undefined; + const notes: string[] = []; + + let report: MissReport; + if (failing.length === 0) { + // A green run is the cheapest case and the most common one: no GitHub calls, and its record + // (no failures) becomes the next run's window start. + report = buildMissReport({ fullRun, rerun: undefined, baseline: [], pullRequests: [], headSha, producedAt: new Date().toISOString(), runUrl, window: { from_sha: null, source: "none" } }); + } else { + const rerunJunit = stringFlag(flags, "rerun-junit"); + const rerunArgs = inferRerunArgs(repoPath); + const files = [...new Set(failing.map((outcome) => outcome.file).filter(Boolean))]; + const rerun = rerunJunit + ? parseJunit(readFileSync(rerunJunit, "utf8"), repoPath) + : rerunArgs && files.length > 0 ? rerunFailingFiles(repoPath, rerunArgs, files) : undefined; + if (!rerun) notes.push("failures were not re-run, so none could be ruled flaky; every failure was treated as deterministic"); + + const collect: CollectOptions = { + repoPath, + repository, + headSha, + runId: env.GITHUB_RUN_ID, + workDir: join(outDir, "downloads"), + run: spawnRunner, + }; + const window = findWindowStart(collect); + if (!window.fromSha) notes.push("no earlier detector record or green full run was found, so no pull request could be held against these failures"); + const pullRequests = mergedPullRequests(collect, window.fromSha).map((pr) => ({ ...pr, receipt: findReceipt(collect, pr) })); + report = buildMissReport({ + fullRun, + rerun, + baseline: window.baseline, + pullRequests, + headSha, + producedAt: new Date().toISOString(), + runUrl, + window: { from_sha: window.fromSha, source: window.source }, + notes, + }); + } + + mkdirSync(outDir, { recursive: true }); + const markdown = formatMissReportMarkdown(report); + writeFileSync(join(outDir, MISS_REPORT_FILE), `${JSON.stringify(report, null, 2)} +`, "utf8"); + writeFileSync(join(outDir, "enforce-misses.md"), markdown, "utf8"); + console.log(markdown); + if (report.misses === 0) return 0; + + console.log("Add to enforce.openUnsafeMisses in diffci.config.json (not done automatically):"); + console.log(JSON.stringify(report.open_unsafe_misses, null, 2)); + if (flags["open-issue"] === true) { + const title = `DiffCI enforce: unsafe miss on main at ${headSha.slice(0, 12)}`; + const created = spawnRunner("gh", ["issue", "create", "--repo", repository, "--title", title, "--body-file", join(outDir, "enforce-misses.md")]); + if (created.ok) console.log(`Opened ${created.stdout.trim()}`); + else console.error(`Could not open an issue (${created.stderr.trim()}); the report is in ${outDir}.`); + } + return 1; +} + function stringFlag(flags: Record, name: string): string | undefined { const value = flags[name]; return typeof value === "string" ? value : undefined; @@ -819,8 +925,9 @@ Pilot a repository: https://diffci.com/#pilot Usage: diffci init [--repo ] [--workflow] [--verification-workflow] [--install] [--force] diffci mcp - diffci verify [--changed | --base --head ] [--repo ] [--out ] [--json] - [--redact-paths] [--timeout-ms ] [--baseline-on-failure] + diffci verify [--changed | --base --head ] [--policy enforce] [--repo ] [--out ] [--json] + [--redact-paths] [--timeout-ms ] [--baseline-on-failure] [--share-usage] [--no-send] + diffci telemetry [--mode off|anonymous|installations] [--internal-usage] diffci check [--repo ] [--out ] [--base --head ] [--redact-paths] [--json] [--quiet] [--fail-on-error] [--timeout-ms ] [--share-usage] diffci pilot --full [--selected ] [--repo ] [--out-dir ] [--label ] @@ -836,6 +943,8 @@ Usage: [--cache-prepare ] [--fixed-order] diffci validate-specs --file [--json] diffci verify-workflow [--repo ] + diffci enforce-misses --junit --out-dir [--repository ] [--repo ] + [--head ] [--rerun-junit ] [--open-issue] diffci version init writes AGENTS.md, CLAUDE.md, Cursor rules, Copilot instructions, and diffci.config.json. @@ -856,12 +965,17 @@ observe analyses the checkout and writes one JSON report. It runs nothing and ch verify-savings runs both commands and reports measured paired runtime; it is an opt-in pilot command. validate-specs checks an explicit list of specification IDs and logical targets and blocks duplicates. verify-workflow checks that the job running DiffCI cannot affect any other job, and exits 1 if it can. +enforce-misses classifies a full run's failures on main against the enforce dry-run receipts of the pull +requests merged since the last recorded run, and exits 1 on a miss. It never edits configuration. +Failures are re-run with the package.json tsx --test runner, or read from --rerun-junit for other runners. The report is sent only when both --api-url and --api-token are given (or DIFFCI_API_URL and DIFFCI_TOKEN are set). A failed send is reported and never fails the step - the report is on disk either way. Plain http is refused; the token is never printed. ---share-usage (or DIFFCI_SHARE_USAGE=1) sends only command, outcome, and version to DiffCI. -No repository, commit, test, report, or persistent identifier is sent. --no-send disables it. +--share-usage (or DIFFCI_SHARE_USAGE=1) opts in to command, outcome, version, surface and activity reporting. +diffci telemetry --mode anonymous saves consent; --mode installations also shares a random local installation ID. +--mode off disables saved consent and deletes the ID. --internal-usage labels tests/internal activity. +No repository, commit, test, report, paths, or machine details are sent. --no-send or DIFFCI_NO_SEND=1 disables it. `; async function main(): Promise { @@ -875,6 +989,14 @@ async function main(): Promise { } switch (command) { + case "telemetry": { + const mode = stringFlag(flags, "mode"); + const preference = mode ? configureTelemetry(mode, flags["internal-usage"] === true, env) : readTelemetryPreference(env); + console.log(`DiffCI telemetry: ${preference.mode}; activity: ${preference.internal ? "internal" : "external"}.`); + console.log("Reporting includes command, outcome, version, surface and activity. Installation mode adds a random local ID; installations are not people. No repository content or machine details are sent. --no-send always overrides consent."); + process.exitCode = 0; + return; + } case "init": process.exitCode = runInit(flags, env); return; @@ -905,6 +1027,9 @@ async function main(): Promise { case "verify-workflow": process.exitCode = runVerifyWorkflow(flags, env); return; + case "enforce-misses": + process.exitCode = runEnforceMisses(flags, env); + return; case "version": console.log(observerIdentity().version); return; diff --git a/packages/diffci-cli/src/client/context.ts b/packages/diffci-cli/src/client/context.ts index 86e0a7ce..a7b8bd43 100644 --- a/packages/diffci-cli/src/client/context.ts +++ b/packages/diffci-cli/src/client/context.ts @@ -46,7 +46,7 @@ const SYNTHETIC_TRIGGERS = new Set(["schedule", "workflow_dispatch", "repository const ZERO_SHA = "0000000000000000000000000000000000000000"; -function readEventPayload(env: ObservationEnvironment): Record | undefined { +export function readEventPayload(env: ObservationEnvironment): Record | undefined { const path = env.GITHUB_EVENT_PATH; if (!path || !existsSync(path)) return undefined; try { diff --git a/packages/diffci-cli/src/client/enforce-misses-collect.ts b/packages/diffci-cli/src/client/enforce-misses-collect.ts new file mode 100644 index 00000000..2e33d2ac --- /dev/null +++ b/packages/diffci-cli/src/client/enforce-misses-collect.ts @@ -0,0 +1,204 @@ +/** + * The side effects of miss detection (docs/enforce-mode-01-plan.md, step 5): finding the window, the + * pull requests merged in it, their dry-run receipts, and re-running the failing test files. GitHub is + * reached only through the `gh` CLI, and every external call goes through an injectable runner. + * + * The window starts at the most recent earlier run of the detector itself (its uploaded report lists + * the failures that were already there), or, before the first such run exists, at the last green + * `ci.yml` push run on `main`. Either commit must be an ancestor of the commit being checked. + */ +import { spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { MISS_REPORT_SCHEMA, parseJunit, type MergedPullRequest, type MissReport, type ReceiptFields, type TestOutcome, type WindowSource } from "./enforce-misses.js"; +import { VERIFICATION_SCHEMA } from "./verify.js"; + +export const DRY_RUN_ARTIFACT_PREFIX = "diffci-enforce-dry-run-"; +export const MISS_RECORD_ARTIFACT_PREFIX = "diffci-enforce-misses-"; +export const MISS_REPORT_FILE = "enforce-misses.json"; +const DRY_RUN_RECEIPT_FILE = "diffci-enforce-dry-run.json"; + +export interface RunResult { + ok: boolean; + stdout: string; + stderr: string; +} + +export type CommandRunner = (executable: string, args: string[], options?: { cwd?: string }) => RunResult; + +export const spawnRunner: CommandRunner = (executable, args, options = {}) => { + const result = spawnSync(executable, args, { cwd: options.cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); + return { ok: result.status === 0, stdout: result.stdout ?? "", stderr: result.stderr ?? result.error?.message ?? "" }; +}; + +export interface CollectOptions { + repoPath: string; + /** owner/name */ + repository: string; + headSha: string; + /** This run's id, skipped when looking for an earlier detector record. */ + runId?: string; + /** Scratch directory for downloaded artifacts; outside the checkout. */ + workDir: string; + run: CommandRunner; + detectorWorkflow?: string; + fullSuiteWorkflow?: string; + dryRunWorkflow?: string; + /** Upper bound on first-parent commits examined, so a long red streak cannot fan out without limit. */ + maxCommits?: number; +} + +interface WorkflowRun { + id: number; + head_sha: string; +} + +interface Artifact { + id: number; + name: string; + expired: boolean; +} + +function ghJson(options: CollectOptions, path: string): T | undefined { + const result = options.run("gh", ["api", path]); + if (!result.ok) return undefined; + try { + return JSON.parse(result.stdout) as T; + } catch { + return undefined; + } +} + +function isAncestor(options: CollectOptions, ancestor: string): boolean { + return options.run("git", ["merge-base", "--is-ancestor", ancestor, options.headSha], { cwd: options.repoPath }).ok; +} + +function workflowRuns(options: CollectOptions, workflow: string, query: string): WorkflowRun[] { + return ghJson<{ workflow_runs?: WorkflowRun[] }>(options, `repos/${options.repository}/actions/workflows/${workflow}/runs?${query}`)?.workflow_runs ?? []; +} + +function runArtifacts(options: CollectOptions, runId: number, prefix: string): Artifact[] { + const artifacts = ghJson<{ artifacts?: Artifact[] }>(options, `repos/${options.repository}/actions/runs/${runId}/artifacts?per_page=100`)?.artifacts ?? []; + return artifacts.filter((artifact) => !artifact.expired && artifact.name.startsWith(prefix)); +} + +/** Download one artifact and parse the named JSON file from it. */ +function downloadJson(options: CollectOptions, runId: number, artifact: string, file: string): unknown { + mkdirSync(options.workDir, { recursive: true }); + const directory = mkdtempSync(join(options.workDir, "artifact-")); + const result = options.run("gh", ["run", "download", String(runId), "--repo", options.repository, "--name", artifact, "--dir", directory]); + if (!result.ok) return undefined; + const path = join(directory, file); + if (!existsSync(path)) return undefined; + try { + return JSON.parse(readFileSync(path, "utf8")); + } catch { + return undefined; + } +} + +export interface WindowStart { + fromSha: string | null; + source: WindowSource; + baseline: string[]; +} + +export function findWindowStart(options: CollectOptions): WindowStart { + const detector = options.detectorWorkflow ?? "diffci-enforce-misses.yml"; + for (const run of workflowRuns(options, detector, "branch=main&status=completed&per_page=30")) { + if (String(run.id) === options.runId || !isAncestor(options, run.head_sha)) continue; + for (const artifact of runArtifacts(options, run.id, MISS_RECORD_ARTIFACT_PREFIX)) { + const record = downloadJson(options, run.id, artifact.name, MISS_REPORT_FILE) as Partial | undefined; + if (record?.schema === MISS_REPORT_SCHEMA && Array.isArray(record.deterministic_failures)) { + return { fromSha: run.head_sha, source: "detector-record", baseline: record.deterministic_failures }; + } + } + } + const fullSuite = options.fullSuiteWorkflow ?? "ci.yml"; + for (const run of workflowRuns(options, fullSuite, "branch=main&event=push&status=success&per_page=30")) { + if (isAncestor(options, run.head_sha)) return { fromSha: run.head_sha, source: "green-full-run", baseline: [] }; + } + return { fromSha: null, source: "none", baseline: [] }; +} + +interface PullSummary { + number: number; + title?: string; + merged_at: string | null; + base?: { ref?: string }; + head?: { sha?: string }; +} + +/** Pull requests merged into `main` by the first-parent commits after `fromSha`, oldest first. */ +export function mergedPullRequests(options: CollectOptions, fromSha: string | null): MergedPullRequest[] { + if (!fromSha) return []; + const listed = options.run("git", ["rev-list", "--first-parent", "--reverse", `${fromSha}..${options.headSha}`], { cwd: options.repoPath }); + if (!listed.ok) return []; + const commits = listed.stdout.split(/\s+/).filter(Boolean).slice(-(options.maxCommits ?? 100)); + const found = new Map(); + for (const sha of commits) { + for (const pull of ghJson(options, `repos/${options.repository}/commits/${sha}/pulls`) ?? []) { + if (!pull.merged_at || pull.base?.ref !== "main" || !pull.head?.sha || found.has(pull.number)) continue; + found.set(pull.number, { number: pull.number, title: pull.title, mergeSha: sha, headSha: pull.head.sha }); + } + } + return [...found.values()]; +} + +/** The newest dry-run receipt recorded for the pull request's final head commit. */ +export function findReceipt(options: CollectOptions, pr: MergedPullRequest): MergedPullRequest["receipt"] { + const workflow = options.dryRunWorkflow ?? "diffci-enforce-dry-run.yml"; + for (const run of workflowRuns(options, workflow, `head_sha=${pr.headSha}&per_page=20`)) { + for (const artifact of runArtifacts(options, run.id, `${DRY_RUN_ARTIFACT_PREFIX}${pr.number}-`)) { + const report = downloadJson(options, run.id, artifact.name, DRY_RUN_RECEIPT_FILE) as ReceiptFields | undefined; + if (report?.schema === VERIFICATION_SCHEMA) return { artifact: artifact.name, report }; + } + } + return undefined; +} + +/** + * Node arguments that re-run test files the way package.json's `tsx --test` script runs them: tsx's own + * CLI under this Node, so no shell and no `.cmd` shim is involved and test paths stay literal argv. + */ +export function inferRerunArgs(repoPath: string): string[] | undefined { + try { + const script: unknown = JSON.parse(readFileSync(join(repoPath, "package.json"), "utf8")).scripts?.test; + if (typeof script !== "string") return undefined; + const runners = [...script.matchAll(/\btsx(?:\s+--conditions\s+([\w,-]+))?\s+--test\b/g)]; + if (runners.length !== 1) return undefined; + const cli = createRequire(join(repoPath, "package.json")).resolve("tsx/cli"); + const conditions = runners[0]![1]; + return [cli, ...(conditions ? ["--conditions", conditions] : []), "--test"]; + } catch { + return undefined; + } +} + +/** + * Re-run only the failing files with node:test's JUnit reporter, set through NODE_OPTIONS so the runner + * arguments stay what package.json declares. Returns undefined when no result file was written. + */ +export function rerunFailingFiles(repoPath: string, runnerArgs: readonly string[], files: readonly string[]): TestOutcome[] | undefined { + const directory = mkdtempSync(join(tmpdir(), "diffci-misses-rerun-")); + const junit = join(directory, "rerun.junit.xml"); + try { + spawnSync(process.execPath, [...runnerArgs, ...files], { + cwd: repoPath, + stdio: "inherit", + env: { + ...process.env, + NODE_OPTIONS: [process.env.NODE_OPTIONS, "--test-reporter=spec", "--test-reporter-destination=stdout", "--test-reporter=junit", `--test-reporter-destination=${junit}`] + .filter(Boolean) + .join(" "), + }, + }); + if (!existsSync(junit)) return undefined; + return parseJunit(readFileSync(junit, "utf8"), repoPath); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} diff --git a/packages/diffci-cli/src/client/enforce-misses.ts b/packages/diffci-cli/src/client/enforce-misses.ts new file mode 100644 index 00000000..14950c6f --- /dev/null +++ b/packages/diffci-cli/src/client/enforce-misses.ts @@ -0,0 +1,347 @@ +/** + * Enforce mode miss detection (docs/enforce-mode-01-plan.md, step 5). + * + * After a full run on `main`, every failing test is held against the enforce receipts of the pull + * requests merged since the last full run that was recorded. A MISS is a test that fails on `main`, + * fails again when re-run, was not failing before those pull requests merged, and was left out by a + * pull request whose receipt says `selection: "selected"`. That is exactly the failure enforce mode + * would have let through. + * + * Everything here is pure: parsing, classification and the report. GitHub, git and the re-run live in + * `enforce-misses-collect.ts`, so each classification can be tested without a repository or a token. + * + * Nothing here changes configuration. A miss produces the exact `enforce.openUnsafeMisses` entry for + * a human to add; re-enabling enforcement is never automatic. + */ +import { isAbsolute, relative, resolve } from "node:path"; + +import type { VerificationReport } from "./verify.js"; + +export const MISS_REPORT_SCHEMA = "diffci.enforce-misses.v1" as const; + +export interface TestOutcome { + /** `file > suite > name`: stable across runs of the same commit, so it can be matched between them. */ + id: string; + /** Repository-relative, forward slashes. Empty when the reporter gave no file. */ + file: string; + name: string; + failed: boolean; + skipped: boolean; +} + +/** The receipt fields the detector reads; older receipts may lack `selected_tests`. */ +export type ReceiptFields = Pick; + +export interface PullRequestReceipt { + artifact: string; + report: ReceiptFields; +} + +export interface MergedPullRequest { + number: number; + title?: string; + mergeSha: string; + headSha: string; + receipt?: PullRequestReceipt; +} + +/** + * What one merged pull request's receipt says about one failing test. + * - `missed`: the receipt selected tests and this test's file was not among them. + * - `selection-unrecorded`: the receipt selected tests but does not say which; counted as a miss, + * because "cannot tell" must not read as "was covered". + * - `selected` / `ran-full`: the pull request ran this test, so it did not skip it. + * - `no-tests-run`: a `none` receipt (blocked analysis). Enforce mode never passes such a run. + * - `no-receipt`: no dry-run artifact was found for the pull request's head. + */ +export type PullRequestVerdict = "missed" | "selection-unrecorded" | "selected" | "ran-full" | "no-tests-run" | "no-receipt"; + +export type FailureClass = + /** Deterministic, new, and skipped by at least one `selected` pull request. Counts. */ + | "miss" + /** Passed when re-run. Logged, never counted. */ + | "flaky" + /** Already failing at the start of the window, so no pull request in it introduced it. */ + | "pre-existing" + /** Every pull request with a receipt ran it (selected it, or ran the full suite). */ + | "covered" + /** No merged pull request with a receipt to hold it against (direct push, drift, environment). */ + | "unattributed"; + +export interface ClassifiedFailure { + id: string; + file: string; + name: string; + classification: FailureClass; + pull_requests: { number: number; verdict: PullRequestVerdict; artifact?: string }[]; + detail: string; +} + +export interface UnsafeMissEntry { + test: string; + pullRequest: number; + receipt: string | null; + mainSha: string; + detectedAt: string; + run?: string; +} + +export type WindowSource = "detector-record" | "green-full-run" | "none"; + +export interface MissReport { + schema: typeof MISS_REPORT_SCHEMA; + produced_at: string; + head_sha: string; + run_url?: string; + full_suite: "passed" | "failed"; + rerun: "done" | "not-run"; + window: { from_sha: string | null; source: WindowSource }; + pull_requests: { number: number; merge_sha: string; head_sha: string; receipt: string | null; selection: ReceiptFields["selection"] | null }[]; + /** Ids of the failures that were not flaky. The next run reads these as its pre-existing set. */ + deterministic_failures: string[]; + failures: ClassifiedFailure[]; + misses: number; + open_unsafe_misses: UnsafeMissEntry[]; + notes: string[]; +} + +// --------------------------------------------------------------------------------------------------- +// JUnit (node:test's `--test-reporter=junit`, which also matches the common Jest/Vitest shape) + +function decodeEntities(text: string): string { + return text.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (_, entity: string) => { + const lower = entity.toLowerCase(); + if (lower.startsWith("#x")) return String.fromCodePoint(Number.parseInt(lower.slice(2), 16)); + if (lower.startsWith("#")) return String.fromCodePoint(Number.parseInt(lower.slice(1), 10)); + return ({ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" } as Record)[lower]!; + }); +} + +function attributes(source: string): Record { + const result: Record = {}; + for (const match of source.matchAll(/([\w:.-]+)\s*=\s*"([^"]*)"/g)) result[match[1]!] = decodeEntities(match[2]!); + return result; +} + +/** Repository-relative with forward slashes; paths outside the repository stay absolute. */ +export function normalizeTestPath(path: string, repoRoot: string): string { + const slashed = path.replace(/\\/g, "/").replace(/^\.\//, ""); + if (!slashed) return ""; + if (!isAbsolute(path)) return slashed; + const inside = relative(resolve(repoRoot), resolve(path)); + return inside && !inside.startsWith("..") && !isAbsolute(inside) ? inside.replace(/\\/g, "/") : slashed; +} + +/** Testcases in document order, named by their enclosing suites. Repeated ids are merged: any failure wins. */ +export function parseJunit(xml: string, repoRoot: string): TestOutcome[] { + const byId = new Map(); + const suites: string[] = []; + let current: TestOutcome | undefined; + const finish = () => { + if (!current) return; + const seen = byId.get(current.id); + if (seen) { + seen.failed ||= current.failed; + seen.skipped &&= current.skipped; + } else byId.set(current.id, current); + current = undefined; + }; + // Attribute values may hold a raw `>` (failure messages), so the tag body skips over quoted strings. + const tags = /<(\/?)(testsuite|testcase|failure|error|skipped)\b((?:[^>"]|"[^"]*")*?)(\/?)>/g; + for (const [, closing, tag, body, selfClosing] of xml.matchAll(tags)) { + if (tag === "testsuite") { + if (closing) suites.pop(); + else if (!selfClosing) suites.push(attributes(body!).name ?? ""); + } else if (tag === "testcase") { + if (closing) { + finish(); + continue; + } + finish(); + const attrs = attributes(body!); + const file = normalizeTestPath(attrs.file ?? "", repoRoot); + const name = [...suites, attrs.name ?? ""].filter(Boolean).join(" > "); + current = { id: `${file} > ${name}`, file, name, failed: attrs.failure !== undefined, skipped: false }; + if (selfClosing) finish(); + } else if (current && !closing) { + if (tag === "skipped") current.skipped = true; + else current.failed = true; + } + } + finish(); + return [...byId.values()]; +} + +// --------------------------------------------------------------------------------------------------- +// Receipts + +const TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/; + +function normalizeSelected(path: string): string { + return path.replace(/\\/g, "/").replace(/^\.\//, ""); +} + +/** + * The test files a `selected` receipt ran. Receipts from before `selected_tests` existed fall back to the + * test-file arguments of the command. `undefined` means the receipt does not say. + */ +export function selectedFiles(report: ReceiptFields): Set | undefined { + if (Array.isArray(report.selected_tests)) return new Set(report.selected_tests.map(normalizeSelected)); + const fromCommand = (report.command ?? "") + .split(/\s+/) + .map((token) => normalizeSelected(token.replace(/^["']|["']$/g, ""))) + .filter((token) => TEST_FILE.test(token)); + return fromCommand.length > 0 ? new Set(fromCommand) : undefined; +} + +function verdict(pr: MergedPullRequest, file: string): PullRequestVerdict { + const report = pr.receipt?.report; + if (!report) return "no-receipt"; + if (report.selection === "full") return "ran-full"; + if (report.selection !== "selected") return "no-tests-run"; + const files = selectedFiles(report); + if (!files) return "selection-unrecorded"; + return files.has(file) ? "selected" : "missed"; +} + +// --------------------------------------------------------------------------------------------------- +// Classification + +export interface ClassifyInput { + /** Every testcase of the full run on `main`; only failures are classified. */ + fullRun: TestOutcome[]; + /** The re-run of the failing files, or undefined when no re-run was possible. */ + rerun: TestOutcome[] | undefined; + /** Ids already failing at the start of the window. */ + baseline: readonly string[]; + pullRequests: MergedPullRequest[]; +} + +export function classifyFailures(input: ClassifyInput): ClassifiedFailure[] { + const rerun = new Map((input.rerun ?? []).map((outcome) => [outcome.id, outcome])); + const baseline = new Set(input.baseline); + return input.fullRun + .filter((outcome) => outcome.failed) + .map((outcome): ClassifiedFailure => { + const base = { id: outcome.id, file: outcome.file, name: outcome.name }; + const again = rerun.get(outcome.id); + if (again && !again.failed && !again.skipped) { + return { ...base, classification: "flaky", pull_requests: [], detail: "passed when re-run" }; + } + // Not found in the re-run (or no re-run at all) is treated as deterministic: "cannot tell" must + // never be what keeps a miss from being counted. + const rerunNote = !input.rerun ? "not re-run" : again ? "failed again when re-run" : "absent from the re-run"; + if (baseline.has(outcome.id)) { + return { ...base, classification: "pre-existing", pull_requests: [], detail: `already failing at the start of the window; ${rerunNote}` }; + } + const pullRequests = input.pullRequests.map((pr) => ({ + number: pr.number, + verdict: verdict(pr, outcome.file), + ...(pr.receipt ? { artifact: pr.receipt.artifact } : {}), + })); + const skippedBy = pullRequests.filter((pr) => pr.verdict === "missed" || pr.verdict === "selection-unrecorded"); + if (skippedBy.length > 0) { + return { + ...base, + classification: "miss", + pull_requests: pullRequests, + detail: `${rerunNote}; not selected by ${skippedBy.map((pr) => `#${pr.number}`).join(", ")}`, + }; + } + if (pullRequests.every((pr) => pr.verdict === "no-receipt" || pr.verdict === "no-tests-run")) { + return { ...base, classification: "unattributed", pull_requests: pullRequests, detail: `${rerunNote}; no merged pull request in the window ran or skipped it` }; + } + return { ...base, classification: "covered", pull_requests: pullRequests, detail: `${rerunNote}; every pull request with a receipt ran it` }; + }); +} + +export function unsafeMissEntries( + failures: readonly ClassifiedFailure[], + context: { headSha: string; detectedAt: string; runUrl?: string }, +): UnsafeMissEntry[] { + return failures + .filter((failure) => failure.classification === "miss") + .flatMap((failure) => failure.pull_requests + .filter((pr) => pr.verdict === "missed" || pr.verdict === "selection-unrecorded") + .map((pr): UnsafeMissEntry => ({ + test: failure.id, + pullRequest: pr.number, + receipt: pr.artifact ?? null, + mainSha: context.headSha, + detectedAt: context.detectedAt, + ...(context.runUrl ? { run: context.runUrl } : {}), + }))); +} + +export interface BuildReportInput extends ClassifyInput { + headSha: string; + producedAt: string; + runUrl?: string; + window: MissReport["window"]; + notes?: string[]; +} + +export function buildMissReport(input: BuildReportInput): MissReport { + const failures = classifyFailures(input); + const open = unsafeMissEntries(failures, { headSha: input.headSha, detectedAt: input.producedAt, runUrl: input.runUrl }); + return { + schema: MISS_REPORT_SCHEMA, + produced_at: input.producedAt, + head_sha: input.headSha, + ...(input.runUrl ? { run_url: input.runUrl } : {}), + full_suite: input.fullRun.some((outcome) => outcome.failed) ? "failed" : "passed", + rerun: input.rerun ? "done" : "not-run", + window: input.window, + pull_requests: input.pullRequests.map((pr) => ({ + number: pr.number, + merge_sha: pr.mergeSha, + head_sha: pr.headSha, + receipt: pr.receipt?.artifact ?? null, + selection: pr.receipt?.report.selection ?? null, + })), + deterministic_failures: failures.filter((failure) => failure.classification !== "flaky").map((failure) => failure.id), + failures, + misses: failures.filter((failure) => failure.classification === "miss").length, + open_unsafe_misses: open, + notes: input.notes ?? [], + }; +} + +const CLASS_ORDER: readonly FailureClass[] = ["miss", "unattributed", "pre-existing", "covered", "flaky"]; + +export function formatMissReportMarkdown(report: MissReport): string { + const lines = [ + report.misses > 0 ? `# DiffCI enforce: ${report.misses} unsafe miss(es) on main` : "# DiffCI enforce: no misses on main", + "", + `- main: \`${report.head_sha}\`${report.run_url ? ` ([run](${report.run_url}))` : ""}`, + `- full suite: ${report.full_suite}; re-run of failures: ${report.rerun}`, + `- window: ${report.window.from_sha ? `\`${report.window.from_sha.slice(0, 12)}..${report.head_sha.slice(0, 12)}\`` : "none found"} (${report.window.source})`, + `- merged pull requests: ${report.pull_requests.length === 0 ? "none" : report.pull_requests.map((pr) => `#${pr.number} (${pr.selection ?? "no receipt"})`).join(", ")}`, + ]; + for (const note of report.notes) lines.push(`- note: ${note}`); + for (const classification of CLASS_ORDER) { + const group = report.failures.filter((failure) => failure.classification === classification); + if (group.length === 0) continue; + lines.push("", `## ${classification} (${group.length})`, ""); + for (const failure of group) { + const prs = failure.pull_requests.map((pr) => `#${pr.number}: ${pr.verdict}`).join(", "); + lines.push(`- \`${failure.id}\` - ${failure.detail}${prs ? ` [${prs}]` : ""}`); + } + } + if (report.open_unsafe_misses.length > 0) { + lines.push( + "", + "## What to do", + "", + "Enforce mode must stop skipping tests until a human has looked at this. Add these entries to", + "`enforce.openUnsafeMisses` in `diffci.config.json` (fallback 4 then forces the full suite), and turn", + "the `DIFFCI_ENFORCE` repository variable off if enforcement is live. Nothing was changed automatically;", + "clearing the entries is the deliberate step that re-enables enforcement.", + "", + "```json", + JSON.stringify(report.open_unsafe_misses, null, 2), + "```", + ); + } + return `${lines.join("\n")}\n`; +} diff --git a/packages/diffci-cli/src/client/enforce-policy.ts b/packages/diffci-cli/src/client/enforce-policy.ts new file mode 100644 index 00000000..9f5a87e5 --- /dev/null +++ b/packages/diffci-cli/src/client/enforce-policy.ts @@ -0,0 +1,199 @@ +/** + * Enforce mode, Level 1 (docs/enforce-mode-01-plan.md, step 1). + * + * Shadow mode only predicts. Enforce mode lets `diffci verify` run the selected tests INSTEAD of the + * full suite - so every way the selection could be wrong has to be answered here with "run FULL", never + * with "run less". The checks are ordered: repository-level conditions first (is enforcement on at all, + * approved, not demoted), then per-run conditions (is this range and this analysis trustworthy). The + * first one that fires is recorded in the receipt; nothing after it is evaluated. + * + * `evaluateEnforcement` is pure. Everything that touches git, the event payload or the environment is + * in `collectEnforcementContext`, so each fallback can be tested without a repository. + */ +import { extname } from "node:path"; + +import { readEventPayload, type GitRunner } from "./context.js"; +import type { ObservationCommitRange, ObservationReport } from "./report.js"; + +/** The only policy shape this CLI understands. A newer or older `enforce` block falls back to FULL. */ +export const ENFORCE_POLICY_VERSION = 1; +export const FORCE_FULL_LABEL = "diffci:force-full"; +export const ENFORCE_VARIABLE = "DIFFCI_ENFORCE"; + +export type EnforcementFallback = + | "kill-switch" + | "per-run-override" + | "policy-not-approved" + | "open-unsafe-miss" + | "untrusted-range" + | "analysis-failure" + | "graph-confidence" + | "global-risk" + | "empty-selection"; + +export interface EnforcementContext { + /** Value of DIFFCI_ENFORCE. Anything but "on" keeps enforcement off. */ + killSwitch: string | undefined; + pullRequestLabels: string[]; + headCommitMessage: string | undefined; + /** The raw `enforce` block of diffci.config.json, read at the range BASE so a change cannot approve itself. */ + policy: unknown; + range: { trusted: true } | { trusted: false; reason: string }; + pathsRedacted: boolean; +} + +export interface EnforcementDecision { + policy: "enforce"; + policy_version: typeof ENFORCE_POLICY_VERSION; + /** null when every check passed and the selected tests may replace the full suite. */ + fired_fallback: EnforcementFallback | null; + detail: string; +} + +/** + * Paths whose change can affect every test without appearing in the import graph. The analyzer already + * falls back for many of these; enforce mode lists them again because here a gap costs a missed failure, + * not a mis-scored prediction. + */ +const GLOBAL_RISK_PATTERNS: readonly RegExp[] = [ + /^\.github\//, + /(?:^|\/)package\.json$/, + /(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|pnpm-workspace\.yaml|yarn\.lock|bun\.lockb?)$/, + /(?:^|\/)\.(?:npmrc|nvmrc|node-version|tool-versions)$/, + /(?:^|\/)tsconfig(?:\.[^/]+)?\.json$/, + /(?:^|\/)(?:jest|vitest|vite|playwright|cypress|mocha|ava|karma|babel)\.config\.[^/]+$/, + /(?:^|\/)\.(?:mocharc|babelrc)(?:\.[^/]+)?$/, + /(?:^|\/)diffci(?:\.config)?\.json$/, +]; + +const DOC_DIRECTORIES: readonly string[] = ["docs", "doc", "documentation"]; + +/** Same rule as RepositoryLayout.isDocumentationPath, without needing a repository profile. */ +function isDocumentationPath(path: string): boolean { + const ext = extname(path).toLowerCase(); + if (ext === ".md" || ext === ".mdx") return true; + const first = path.split("/")[0]; + return first !== undefined && DOC_DIRECTORIES.includes(first.toLowerCase()); +} + +function policyProblem(policy: unknown): string | undefined { + if (policy === undefined) return "diffci.config.json at the range base has no `enforce` block"; + if (policy === null || typeof policy !== "object" || Array.isArray(policy)) return "`enforce` must be an object"; + const block = policy as Record; + if (block.policyVersion !== ENFORCE_POLICY_VERSION) { + return `enforce.policyVersion is ${JSON.stringify(block.policyVersion)}; this DiffCI supports ${ENFORCE_POLICY_VERSION}`; + } + if (block.level !== 1) return `enforce.level is ${JSON.stringify(block.level)}; only level 1 is implemented`; + if (typeof block.approvedBy !== "string" || block.approvedBy.trim() === "") return "enforce.approvedBy is missing"; + if (typeof block.approvedAt !== "string" || Number.isNaN(Date.parse(block.approvedAt))) return "enforce.approvedAt is not a date"; + if (block.openUnsafeMisses !== undefined && !Array.isArray(block.openUnsafeMisses)) return "enforce.openUnsafeMisses must be an array"; + return undefined; +} + +function openMisses(policy: unknown): unknown[] { + const misses = (policy as Record).openUnsafeMisses; + return Array.isArray(misses) ? misses : []; +} + +/** Matches a `DiffCI: full` trailer line anywhere in the head commit message. */ +export function hasForceFullTrailer(message: string | undefined): boolean { + return message !== undefined && /^diffci:\s*full\s*$/im.test(message); +} + +export function evaluateEnforcement(context: EnforcementContext, observation: ObservationReport): EnforcementDecision { + const decide = (fired: EnforcementFallback | null, detail: string): EnforcementDecision => ({ + policy: "enforce", + policy_version: ENFORCE_POLICY_VERSION, + fired_fallback: fired, + detail, + }); + + if (context.killSwitch !== "on") return decide("kill-switch", `${ENFORCE_VARIABLE} is not "on"`); + if (context.pullRequestLabels.includes(FORCE_FULL_LABEL)) return decide("per-run-override", `pull request is labelled ${FORCE_FULL_LABEL}`); + if (hasForceFullTrailer(context.headCommitMessage)) return decide("per-run-override", "head commit carries a `DiffCI: full` trailer"); + const problem = policyProblem(context.policy); + if (problem) return decide("policy-not-approved", problem); + const misses = openMisses(context.policy); + if (misses.length > 0) return decide("open-unsafe-miss", `${misses.length} unsafe miss(es) recorded and not yet cleared`); + if (!context.range.trusted) return decide("untrusted-range", context.range.reason); + + const result = observation.result; + if (observation.status !== "OBSERVED" || !result) { + return decide("analysis-failure", observation.reason ?? `analysis status ${observation.status}`); + } + + const confidence = result.graph.effectiveConfidence ?? result.graph.confidence; + if (confidence !== "COMPLETE") return decide("graph-confidence", `effective graph confidence is ${confidence}, not COMPLETE`); + + if (context.pathsRedacted) return decide("global-risk", "changed paths are redacted, so global-risk paths cannot be checked"); + const critical = result.riskSignals.find((signal) => signal.level === "critical"); + if (critical) return decide("global-risk", `critical risk signal: ${critical.reason}`); + if (result.mode === "FULL") return decide("global-risk", `analyzer required full validation: ${result.fallbackReasons[0] ?? "no reason given"}`); + const risky = result.changedFiles.find((path) => GLOBAL_RISK_PATTERNS.some((pattern) => pattern.test(path))); + if (risky) return decide("global-risk", `global-risk path changed: ${risky}`); + + if (result.selectedTests.length === 0 && result.changedFiles.some((path) => !isDocumentationPath(path))) { + return decide("empty-selection", "source files changed but no tests were selected"); + } + + return decide(null, "every enforce check passed"); +} + +function git(runner: GitRunner, args: string[]): string | undefined { + const result = runner(args); + return result.ok ? result.stdout : undefined; +} + +function rangeTrust(runner: GitRunner, range: ObservationCommitRange | undefined): EnforcementContext["range"] { + if (!range) return { trusted: false, reason: "no commit range was resolved" }; + // A head-parent range covers one commit, not the whole push or branch it stands in for. + if (range.source === "head-parent") return { trusted: false, reason: "range is the head commit's parent, not the full push" }; + if (git(runner, ["rev-parse", "--is-shallow-repository"])?.trim() !== "false") { + return { trusted: false, reason: "checkout is shallow; use fetch-depth: 0" }; + } + // Force-pushes leave `before` off the new history; a diff from it is not "what this push changed". + if (git(runner, ["merge-base", "--is-ancestor", range.baseSha, range.headSha]) === undefined) { + return { trusted: false, reason: `base ${range.baseSha.slice(0, 12)} is not an ancestor of head ${range.headSha.slice(0, 12)}` }; + } + return { trusted: true }; +} + +function policyAtBase(runner: GitRunner, range: ObservationCommitRange | undefined): unknown { + if (!range) return undefined; + const text = git(runner, ["show", `${range.baseSha}:diffci.config.json`]); + if (text === undefined) return undefined; + try { + const parsed: unknown = JSON.parse(text); + return parsed !== null && typeof parsed === "object" ? (parsed as Record).enforce : undefined; + } catch { + return undefined; + } +} + +function pullRequestLabels(env: Record): string[] { + const payload = readEventPayload(env); + const pullRequest = payload?.pull_request; + if (pullRequest === null || typeof pullRequest !== "object") return []; + const labels = (pullRequest as Record).labels; + if (!Array.isArray(labels)) return []; + return labels.flatMap((label) => { + const name = label !== null && typeof label === "object" ? (label as Record).name : undefined; + return typeof name === "string" ? [name] : []; + }); +} + +export function collectEnforcementContext( + runner: GitRunner, + env: Record, + observation: ObservationReport, +): EnforcementContext { + const range = observation.commitRange; + return { + killSwitch: env[ENFORCE_VARIABLE], + pullRequestLabels: pullRequestLabels(env), + headCommitMessage: range ? git(runner, ["log", "-1", "--format=%B", range.headSha]) : undefined, + policy: policyAtBase(runner, range), + range: rangeTrust(runner, range), + pathsRedacted: observation.payload.pathRedaction !== undefined, + }; +} diff --git a/packages/diffci-cli/src/client/mcp.ts b/packages/diffci-cli/src/client/mcp.ts index ac8e196b..13f86916 100644 --- a/packages/diffci-cli/src/client/mcp.ts +++ b/packages/diffci-cli/src/client/mcp.ts @@ -69,7 +69,7 @@ const tools = [ }, { name: "diffci_check", - description: "Analyze the repository, run inferred full and selected test commands when available, and report paired runtime. Sends nothing to DiffCI Cloud.", + description: "Analyze the repository, run inferred full and selected test commands when available, and report paired runtime. No report is uploaded. Optional aggregate telemetry follows the user's saved consent; DIFFCI_NO_SEND=1 overrides it.", inputSchema: { type: "object", properties: { diff --git a/packages/diffci-cli/src/client/observe.ts b/packages/diffci-cli/src/client/observe.ts index 1e177f82..5a3bebd0 100644 --- a/packages/diffci-cli/src/client/observe.ts +++ b/packages/diffci-cli/src/client/observe.ts @@ -69,7 +69,7 @@ export interface ObserveOptions { vueAnalysisCacheDir?: string; } -function makeGitRunner(repoPath: string): GitRunner { +export function makeGitRunner(repoPath: string): GitRunner { return (args) => { try { const stdout = execFileSync("git", args, { diff --git a/packages/diffci-cli/src/client/telemetry.ts b/packages/diffci-cli/src/client/telemetry.ts new file mode 100644 index 00000000..36648974 --- /dev/null +++ b/packages/diffci-cli/src/client/telemetry.ts @@ -0,0 +1,46 @@ +import { randomUUID } from "node:crypto"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { deliverUsageSignal, type UsageCommand, type UsageOutcome } from "./usage-signal.js"; + +export type TelemetryMode = "off" | "anonymous" | "installations"; +interface Preference { mode: TelemetryMode; installationId?: string; internal: boolean } +type Flags = Record; + +export function preferencePath(env: NodeJS.ProcessEnv): string { + return join(env.DIFFCI_TELEMETRY_HOME ?? join(homedir(), ".diffci"), "telemetry.json"); +} + +export function readTelemetryPreference(env: NodeJS.ProcessEnv): Preference { + try { + const value = JSON.parse(readFileSync(preferencePath(env), "utf8")) as Preference; + if (!["off", "anonymous", "installations"].includes(value.mode)) throw new Error("invalid preference"); + if (value.mode === "installations" && !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.installationId ?? "")) throw new Error("invalid identifier"); + return { mode: value.mode, internal: value.internal === true, ...(value.mode === "installations" ? { installationId: value.installationId } : {}) }; + } catch { return { mode: "off", internal: false }; } +} + +export function configureTelemetry(mode: string, internal: boolean, env: NodeJS.ProcessEnv): Preference { + if (!["off", "anonymous", "installations"].includes(mode)) throw new Error("Choose off, anonymous, or installations."); + const previous = readTelemetryPreference(env); + const value: Preference = { mode: mode as TelemetryMode, internal, + ...(mode === "installations" ? { installationId: previous.installationId ?? randomUUID() } : {}) }; + const path = preferencePath(env); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, `${JSON.stringify(value)}\n`, { encoding: "utf8", mode: 0o600 }); + return value; +} + +export async function recordUsage(command: UsageCommand, outcome: UsageOutcome, version: string, flags: Flags, env: NodeJS.ProcessEnv): Promise { + // Explicit denial overrides saved consent and every opt-in route. + if (flags["no-send"] === true || env.DIFFCI_SHARE_USAGE === "0" || env.DIFFCI_NO_SEND === "1") return; + const preference = readTelemetryPreference(env); + if (flags["share-usage"] !== true && env.DIFFCI_SHARE_USAGE !== "1" && preference.mode === "off") return; + const result = await deliverUsageSignal({ command, outcome, version, + surface: env.DIFFCI_MCP === "1" ? "local-mcp" : "cli", + activity: flags["internal-usage"] === true || env.DIFFCI_USAGE_INTERNAL === "1" || preference.internal ? "internal" : "external", + ...(preference.mode === "installations" ? { installationId: preference.installationId } : {}), + }); + console.error(`DiffCI telemetry: ${result.status}${result.httpStatus ? ` (HTTP ${result.httpStatus})` : ""}. No repository content sent.`); +} diff --git a/packages/diffci-cli/src/client/usage-signal.ts b/packages/diffci-cli/src/client/usage-signal.ts index f21870d8..85c29a78 100644 --- a/packages/diffci-cli/src/client/usage-signal.ts +++ b/packages/diffci-cli/src/client/usage-signal.ts @@ -1,22 +1,38 @@ -/** Explicit, best-effort aggregate usage signal. No repository or machine identifier is sent. */ -export async function sendUsageSignal(input: { - command: "check" | "observe"; - outcome: "observed" | "refused" | "error"; +/** Explicit, best-effort usage signal. Never includes repository or machine details. */ +export type UsageCommand = "check" | "observe" | "verify"; +export type UsageOutcome = "observed" | "refused" | "error" | "passed" | "failed" | "blocked"; +export interface UsageSignal { + command: UsageCommand; + outcome: UsageOutcome; version: string; + surface?: "cli" | "local-mcp"; + activity?: "internal" | "external"; + installationId?: string; endpoint?: string; fetchImpl?: typeof fetch; -}): Promise { - const url = new URL(input.endpoint ?? "https://app.diffci.com/v1/usage-events"); - if (url.protocol !== "https:") return false; +} +export interface DeliveryResult { status: "delivered" | "accepted" | "failed" | "timed-out"; httpStatus?: number } +export async function deliverUsageSignal(input: UsageSignal): Promise { try { + const url = new URL(input.endpoint ?? "https://app.diffci.com/v1/usage-events"); + if (url.protocol !== "https:") return { status: "failed" }; const response = await (input.fetchImpl ?? fetch)(url, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ schema: "diffci.usage.v1", command: input.command, outcome: input.outcome, version: input.version }), - signal: AbortSignal.timeout(2500), + body: JSON.stringify({ schema: "diffci.usage.v1", command: input.command, outcome: input.outcome, version: input.version, + ...(input.surface ? { surface: input.surface } : {}), + ...(input.activity ? { activity: input.activity } : {}), + ...(input.installationId ? { installation_id: input.installationId } : {}), + }), + signal: AbortSignal.timeout(5000), }); - return response.ok; - } catch { - return false; + return { status: !response.ok ? "failed" : response.status === 202 ? "accepted" : "delivered", httpStatus: response.status }; + } catch (error) { + return { status: error instanceof Error && error.name === "TimeoutError" ? "timed-out" : "failed" }; } } + +export async function sendUsageSignal(input: UsageSignal): Promise { + const result = await deliverUsageSignal(input); + return result.status === "delivered" || result.status === "accepted"; +} diff --git a/packages/diffci-cli/src/client/verify.ts b/packages/diffci-cli/src/client/verify.ts index 9550a735..711298b0 100644 --- a/packages/diffci-cli/src/client/verify.ts +++ b/packages/diffci-cli/src/client/verify.ts @@ -4,8 +4,9 @@ import { join, resolve } from "node:path"; import { batchCommand, measureCommands } from "./command-batches.js"; import { compareWithBaseline, type FailureBaseline } from "./failure-baseline.js"; +import { collectEnforcementContext, evaluateEnforcement, type EnforcementDecision } from "./enforce-policy.js"; import { inferFullCommand, inferSelectedCommand } from "./full-command.js"; -import { observe } from "./observe.js"; +import { makeGitRunner, observe } from "./observe.js"; import type { ObservationCommitRange, ObservationReport } from "./report.js"; import type { CommandMeasurement } from "./verify-savings.js"; import { captureWorkingTreeSnapshot, type WorkingTreeSnapshot } from "./working-tree.js"; @@ -31,6 +32,8 @@ export interface VerificationReport { /** Affected tests the full test command does not run; executed after the selection (2026-10-21). */ tests_outside_full_suite?: number; selection: "none" | "selected" | "full"; + /** The test files the selected command ran, when `selection` is "selected". The miss detector reads it. */ + selected_tests?: string[]; command?: string; /** The parts `command` was run as, when one invocation would exceed the shell's command-line limit. */ commands?: string[]; @@ -63,6 +66,8 @@ export interface VerificationReport { required_actions: string[]; /** Present when a failed verification was rerun at the base commit (`--baseline-on-failure`). */ failure_baseline?: FailureBaseline; + /** Present only under `--policy enforce`. `applied` is true when the selected tests replaced the full suite. */ + enforcement?: EnforcementDecision & { applied: boolean }; } interface VerifyOptions { @@ -82,6 +87,8 @@ export interface VerifyChangedOptions extends VerifyOptions {} export interface VerifyRangeOptions extends VerifyOptions { baseOverride?: string; headOverride?: string; + /** Opt-in enforce mode (docs/enforce-mode-01-plan.md). Absent means today's behaviour, unchanged. */ + policy?: "enforce"; } function receiptRange(range: ObservationCommitRange | undefined): VerificationReport["commit_range"] { @@ -140,11 +147,29 @@ function unknownSnapshot(): WorkingTreeSnapshot { } async function executeObservation( + options: VerifyOptions & { policy?: "enforce" }, + scope: VerificationScope, + before: WorkingTreeSnapshot, + observation: ObservationReport, +): Promise { + const enforcement = options.policy === "enforce" + ? evaluateEnforcement(collectEnforcementContext(makeGitRunner(options.repoPath), options.env, observation), observation) + : undefined; + const report = await executeWithPolicy(options, scope, before, observation, enforcement); + if (!enforcement) return report; + return { ...report, enforcement: { ...enforcement, applied: enforcement.fired_fallback === null && report.selection === "selected" } }; +} + +async function executeWithPolicy( options: VerifyOptions, scope: VerificationScope, before: WorkingTreeSnapshot, observation: ObservationReport, + enforcement: EnforcementDecision | undefined, ): Promise { + // Under enforce, a fired fallback runs the full suite even where plain verify would block: an + // unusable analysis is a reason to run everything, never a reason to pass with nothing run. + const enforcedFull = enforcement !== undefined && enforcement.fired_fallback !== null; const result = observation.result; const range = observation.commitRange; const boundRange = scope === "commit-range" ? range : undefined; @@ -163,12 +188,12 @@ async function executeObservation( ...(result?.graph ? { graph_confidence: result.graph.confidence, effective_graph_confidence: result.graph.effectiveConfidence } : {}), }; - if (observation.status !== "OBSERVED" || !result) { + if ((observation.status !== "OBSERVED" || !result) && !enforcedFull) { return blocked(before, scope, observation.reason ?? "DiffCI analysis did not produce a verification plan", analysis, counts, boundRange); } if (scope === "commit-range") { - if (!range) return blocked(before, scope, "DiffCI did not resolve a commit range", analysis, counts); - if (range.headSha !== before.baseSha) { + if (!range && !enforcedFull) return blocked(before, scope, "DiffCI did not resolve a commit range", analysis, counts); + if (range && range.headSha !== before.baseSha) { return blocked( before, scope, @@ -194,7 +219,9 @@ async function executeObservation( return report; } - const { selection, command, commands, reason, outsideSuite } = executableSelection(options.repoPath, result); + const { selection, command, commands, reason, outsideSuite } = enforcedFull || !result + ? fullSelection(options.repoPath, `enforce fallback (${enforcement?.fired_fallback}): ${enforcement?.detail}`) + : executableSelection(options.repoPath, result); if (!command) { const inferred = inferFullCommand(options.repoPath); @@ -244,6 +271,7 @@ async function executeObservation( tests_selected: selection === "full" ? counts.testsAvailable : counts.testsSelected, ...(outsideSuite ? { tests_outside_full_suite: outsideSuite } : {}), selection, + ...(selection === "selected" && result ? { selected_tests: result.selectedTests } : {}), command, ...(commands.length > 1 ? { commands } : {}), execution, @@ -376,11 +404,20 @@ export function formatVerificationSummary(report: VerificationReport): string { ]; if (report.commit_range) lines.splice(2, 0, ` range: ${report.commit_range.base_sha.slice(0, 12)}..${report.commit_range.head_sha.slice(0, 12)}`); if (report.command) lines.push(` command: ${report.command}`); + if (report.enforcement) { + const fired = report.enforcement.fired_fallback; + lines.push(` enforce: ${report.enforcement.applied ? "applied" : fired ? `fell back to full (${fired}: ${report.enforcement.detail})` : "not applied"}`); + } return lines.join("\n"); } +function fullSelection(repoPath: string, reason: string) { + const command = inferFullCommand(repoPath).command; + return { selection: "full" as const, command, commands: command ? [command] : [], reason, outsideSuite: 0 }; +} + /** Shared executable plan for read-only agent selection and verification. */ export function executableSelection(repoPath: string, result: NonNullable) { let selection: "selected" | "full"; diff --git a/packages/diffci-cli/tests/client/enforce-misses.test.ts b/packages/diffci-cli/tests/client/enforce-misses.test.ts new file mode 100644 index 00000000..4c1411b3 --- /dev/null +++ b/packages/diffci-cli/tests/client/enforce-misses.test.ts @@ -0,0 +1,288 @@ +/** + * Enforce mode step 5 (docs/enforce-mode-01-plan.md): miss detection. One fixture per classification - + * miss, flaky, pre-existing failure, a pull request that ran the full suite - plus the JUnit parsing, + * the receipt fallbacks and the collector's window and pull-request discovery, with GitHub faked. + */ +import { strict as assert } from "node:assert"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, it } from "node:test"; + +import { + buildMissReport, + classifyFailures, + formatMissReportMarkdown, + parseJunit, + selectedFiles, + type MergedPullRequest, + type ReceiptFields, + type TestOutcome, +} from "../../src/client/enforce-misses.js"; +import { findReceipt, findWindowStart, mergedPullRequests, type CommandRunner } from "../../src/client/enforce-misses-collect.js"; + +const ROOT = "/repo"; + +function outcome(file: string, name: string, failed: boolean): TestOutcome { + return { id: `${file} > ${name}`, file, name, failed, skipped: false }; +} + +function receipt(report: Partial): ReceiptFields { + return { schema: "diffci.verification.v1", selection: "selected", ...report }; +} + +function pr(number: number, report?: Partial): MergedPullRequest { + return { + number, + mergeSha: `merge${number}`, + headSha: `head${number}`, + ...(report ? { receipt: { artifact: `diffci-enforce-dry-run-${number}-1-1`, report: receipt(report) } } : {}), + }; +} + +const FAILING = outcome("tests/a.test.ts", "adds", true); +const PASSING = outcome("tests/b.test.ts", "subtracts", false); + +describe("classifyFailures", () => { + it("miss: deterministic, new, and left out by a selected receipt", () => { + const [failure] = classifyFailures({ + fullRun: [FAILING, PASSING], + rerun: [FAILING], + baseline: [], + pullRequests: [pr(7, { selection: "selected", selected_tests: ["tests/b.test.ts"] })], + }); + assert.equal(failure!.classification, "miss"); + assert.deepEqual(failure!.pull_requests, [{ number: 7, verdict: "missed", artifact: "diffci-enforce-dry-run-7-1-1" }]); + }); + + it("flaky: passes on re-run, logged and never counted, even when a selected receipt skipped it", () => { + const report = buildMissReport({ + fullRun: [FAILING], + rerun: [{ ...FAILING, failed: false }], + baseline: [], + pullRequests: [pr(7, { selection: "selected", selected_tests: [] })], + headSha: "abc", + producedAt: "2026-10-25T00:00:00Z", + window: { from_sha: "base", source: "detector-record" }, + }); + assert.equal(report.failures[0]!.classification, "flaky"); + assert.equal(report.misses, 0); + assert.deepEqual(report.open_unsafe_misses, []); + assert.deepEqual(report.deterministic_failures, []); + assert.match(formatMissReportMarkdown(report), /## flaky \(1\)/); + }); + + it("pre-existing: already failing at the window start, so no pull request in it is blamed", () => { + const [failure] = classifyFailures({ + fullRun: [FAILING], + rerun: [FAILING], + baseline: [FAILING.id], + pullRequests: [pr(7, { selection: "selected", selected_tests: [] })], + }); + assert.equal(failure!.classification, "pre-existing"); + }); + + it("pull request that ran the full suite cannot have skipped the test", () => { + const [failure] = classifyFailures({ + fullRun: [FAILING], + rerun: [FAILING], + baseline: [], + pullRequests: [pr(8, { selection: "full", enforcement: { policy: "enforce", policy_version: 1, fired_fallback: "global-risk", detail: "x", applied: false } })], + }); + assert.equal(failure!.classification, "covered"); + assert.equal(failure!.pull_requests[0]!.verdict, "ran-full"); + }); + + it("a test the selected receipt did run is covered, not a miss", () => { + const [failure] = classifyFailures({ + fullRun: [FAILING], + rerun: [FAILING], + baseline: [], + pullRequests: [pr(9, { selection: "selected", selected_tests: ["./tests/a.test.ts"] })], + }); + assert.equal(failure!.classification, "covered"); + }); + + it("one skipping pull request is enough for a miss, beside others that ran full", () => { + const [failure] = classifyFailures({ + fullRun: [FAILING], + rerun: [FAILING], + baseline: [], + pullRequests: [pr(8, { selection: "full" }), pr(9, { selection: "selected", selected_tests: ["tests/b.test.ts"] })], + }); + assert.equal(failure!.classification, "miss"); + assert.match(failure!.detail, /#9/); + }); + + it("no receipt for any merged pull request is unattributed, not a miss", () => { + const [failure] = classifyFailures({ fullRun: [FAILING], rerun: [FAILING], baseline: [], pullRequests: [pr(10)] }); + assert.equal(failure!.classification, "unattributed"); + assert.equal(failure!.pull_requests[0]!.verdict, "no-receipt"); + }); + + it("without a re-run, nothing is ruled flaky: the failure is treated as deterministic", () => { + const [failure] = classifyFailures({ + fullRun: [FAILING], + rerun: undefined, + baseline: [], + pullRequests: [pr(7, { selection: "selected", selected_tests: [] })], + }); + assert.equal(failure!.classification, "miss"); + assert.match(failure!.detail, /not re-run/); + }); + + it("a selected receipt that does not say what it selected counts as a miss", () => { + const [failure] = classifyFailures({ + fullRun: [FAILING], + rerun: [FAILING], + baseline: [], + pullRequests: [pr(7, { selection: "selected", command: "npm test" })], + }); + assert.equal(failure!.classification, "miss"); + assert.equal(failure!.pull_requests[0]!.verdict, "selection-unrecorded"); + }); +}); + +describe("buildMissReport", () => { + it("prints the exact openUnsafeMisses entry and never claims to have changed anything", () => { + const report = buildMissReport({ + fullRun: [FAILING, PASSING], + rerun: [FAILING], + baseline: [], + pullRequests: [pr(7, { selection: "selected", selected_tests: ["tests/b.test.ts"] })], + headSha: "abc123", + producedAt: "2026-10-25T00:00:00Z", + runUrl: "https://github.com/o/r/actions/runs/1", + window: { from_sha: "base", source: "detector-record" }, + }); + assert.equal(report.misses, 1); + assert.deepEqual(report.open_unsafe_misses, [{ + test: "tests/a.test.ts > adds", + pullRequest: 7, + receipt: "diffci-enforce-dry-run-7-1-1", + mainSha: "abc123", + detectedAt: "2026-10-25T00:00:00Z", + run: "https://github.com/o/r/actions/runs/1", + }]); + assert.deepEqual(report.deterministic_failures, [FAILING.id]); + const markdown = formatMissReportMarkdown(report); + assert.match(markdown, /enforce\.openUnsafeMisses/); + assert.match(markdown, /Nothing was changed automatically/); + }); +}); + +describe("parseJunit", () => { + it("reads node:test's JUnit output: suites, failures, skips, entities and raw > in attributes", () => { + const xml = ` + + + + at <anonymous> + + + + + + +`; + const outcomes = parseJunit(xml, ROOT); + assert.deepEqual(outcomes.map((o) => [o.id, o.failed, o.skipped]), [ + ["tests/a.test.ts > ok", false, false], + ["tests/a.test.ts > bad & worse", true, false], + ["tests/b.test.ts > group > inner", true, false], + ["tests/b.test.ts > group > later", false, true], + ["tests/c.test.ts > outside", false, false], + ]); + }); +}); + +describe("selectedFiles", () => { + it("prefers selected_tests and falls back to the command's test-file arguments", () => { + assert.deepEqual([...selectedFiles(receipt({ selected_tests: ["tests/x.test.ts"] }))!], ["tests/x.test.ts"]); + assert.deepEqual( + [...selectedFiles(receipt({ command: 'npx --no-install tsx --test "tests/a.test.ts" tests/b.spec.ts' }))!], + ["tests/a.test.ts", "tests/b.spec.ts"], + ); + assert.equal(selectedFiles(receipt({ command: "npm test" })), undefined); + }); +}); + +describe("collector", () => { + function fakeRunner(responses: Record, ancestors: string[], files: Record = {}): CommandRunner { + return (executable, args) => { + if (executable === "git" && args[0] === "merge-base") return { ok: ancestors.includes(args[2]!), stdout: "", stderr: "" }; + if (executable === "git" && args[0] === "rev-list") return { ok: true, stdout: "c1\nc2\n", stderr: "" }; + if (executable === "gh" && args[0] === "api") { + const body = responses[args[1]!]; + return body === undefined ? { ok: false, stdout: "", stderr: "404" } : { ok: true, stdout: JSON.stringify(body), stderr: "" }; + } + if (executable === "gh" && args[0] === "run" && args[1] === "download") { + const content = files[args[args.indexOf("--name") + 1]!]; + const dir = args[args.indexOf("--dir") + 1]!; + if (content === undefined) return { ok: false, stdout: "", stderr: "no artifact" }; + for (const [name, value] of Object.entries(content as Record)) writeFileSync(join(dir, name), JSON.stringify(value)); + return { ok: true, stdout: "", stderr: "" }; + } + return { ok: false, stdout: "", stderr: `unexpected ${executable} ${args.join(" ")}` }; + }; + } + + function options(run: CommandRunner, workDir: string) { + return { repoPath: ROOT, repository: "o/r", headSha: "HEAD1", runId: "99", workDir, run }; + } + + it("starts the window at the newest earlier detector record on an ancestor, with its failures as baseline", () => { + const workDir = mkdtempSync(join(tmpdir(), "diffci-misses-test-")); + try { + const run = fakeRunner( + { + "repos/o/r/actions/workflows/diffci-enforce-misses.yml/runs?branch=main&status=completed&per_page=30": { + workflow_runs: [{ id: 99, head_sha: "HEAD1" }, { id: 98, head_sha: "notAncestor" }, { id: 97, head_sha: "older" }], + }, + "repos/o/r/actions/runs/97/artifacts?per_page=100": { artifacts: [{ id: 1, name: "diffci-enforce-misses-97-1", expired: false }] }, + }, + ["HEAD1", "older"], + { "diffci-enforce-misses-97-1": { "enforce-misses.json": { schema: "diffci.enforce-misses.v1", deterministic_failures: ["tests/a.test.ts > adds"] } } }, + ); + assert.deepEqual(findWindowStart(options(run, workDir)), { fromSha: "older", source: "detector-record", baseline: ["tests/a.test.ts > adds"] }); + } finally { + rmSync(workDir, { recursive: true, force: true }); + } + }); + + it("falls back to the last green ci.yml push run, then to no window", () => { + const green = fakeRunner( + { "repos/o/r/actions/workflows/ci.yml/runs?branch=main&event=push&status=success&per_page=30": { workflow_runs: [{ id: 5, head_sha: "green" }] } }, + ["green"], + ); + assert.deepEqual(findWindowStart(options(green, tmpdir())), { fromSha: "green", source: "green-full-run", baseline: [] }); + assert.deepEqual(findWindowStart(options(fakeRunner({}, []), tmpdir())), { fromSha: null, source: "none", baseline: [] }); + }); + + it("finds merged pull requests on main once each, and their receipt at the pull request head", () => { + const workDir = mkdtempSync(join(tmpdir(), "diffci-misses-test-")); + try { + const run = fakeRunner( + { + "repos/o/r/commits/c1/pulls": [{ number: 7, merged_at: "2026-10-24", base: { ref: "main" }, head: { sha: "h7" } }], + "repos/o/r/commits/c2/pulls": [ + { number: 7, merged_at: "2026-10-24", base: { ref: "main" }, head: { sha: "h7" } }, + { number: 8, merged_at: null, base: { ref: "main" }, head: { sha: "h8" } }, + ], + "repos/o/r/actions/workflows/diffci-enforce-dry-run.yml/runs?head_sha=h7&per_page=20": { workflow_runs: [{ id: 50, head_sha: "h7" }] }, + "repos/o/r/actions/runs/50/artifacts?per_page=100": { artifacts: [{ id: 2, name: "diffci-enforce-dry-run-7-50-1", expired: false }] }, + }, + [], + { "diffci-enforce-dry-run-7-50-1": { "diffci-enforce-dry-run.json": { schema: "diffci.verification.v1", selection: "selected", selected_tests: [] } } }, + ); + const pulls = mergedPullRequests(options(run, workDir), "from"); + assert.deepEqual(pulls.map((p) => [p.number, p.mergeSha, p.headSha]), [[7, "c1", "h7"]]); + const found = findReceipt(options(run, workDir), pulls[0]!); + assert.equal(found?.artifact, "diffci-enforce-dry-run-7-50-1"); + assert.equal(found?.report.selection, "selected"); + assert.deepEqual(mergedPullRequests(options(run, workDir), null), []); + } finally { + rmSync(workDir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/diffci-cli/tests/client/enforce-policy.test.ts b/packages/diffci-cli/tests/client/enforce-policy.test.ts new file mode 100644 index 00000000..f95ce686 --- /dev/null +++ b/packages/diffci-cli/tests/client/enforce-policy.test.ts @@ -0,0 +1,305 @@ +/** + * Enforce mode step 1 (docs/enforce-mode-01-plan.md): every fallback that must force FULL, one fixture + * each, plus the ordering between them and the CLI wiring end to end. + */ +import { strict as assert } from "node:assert"; +import { execFileSync, spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { describe, it } from "node:test"; +import { fileURLToPath } from "node:url"; + +import { + collectEnforcementContext, + evaluateEnforcement, + FORCE_FULL_LABEL, + type EnforcementContext, +} from "../../src/client/enforce-policy.js"; +import { makeGitRunner } from "../../src/client/observe.js"; +import type { ObservationReport, ObservationResult } from "../../src/client/report.js"; + +const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../.."); +const CLI = join(ROOT, "src", "client", "cli.ts"); + +const APPROVED = { policyVersion: 1, level: 1, approvedBy: "maintainer", approvedAt: "2026-10-01T00:00:00Z" }; + +function context(overrides: Partial = {}): EnforcementContext { + return { + killSwitch: "on", + pullRequestLabels: [], + headCommitMessage: "change alpha\n", + policy: APPROVED, + range: { trusted: true }, + pathsRedacted: false, + ...overrides, + }; +} + +function observation(result: Partial = {}, report: Partial = {}): ObservationReport { + return { + status: "OBSERVED", + payload: { includesFilePaths: true, includesFileContents: false, includesEnvironment: false, includesCredentials: false }, + result: { + mode: "SELECTIVE", + changedFileCount: 1, + changedFiles: ["src/alpha.js"], + selectedTests: ["test/alpha.test.js"], + totalTestCount: 2, + fallbackReasons: [], + proposedCommands: ["node --test"], + riskSignals: [], + graph: { nodes: 4, edges: 2, confidence: "COMPLETE", effectiveConfidence: "COMPLETE", durationMs: 1 }, + ...result, + }, + ...report, + } as unknown as ObservationReport; +} + +describe("evaluateEnforcement", () => { + it("permits selection when every check passes", () => { + const decision = evaluateEnforcement(context(), observation()); + assert.equal(decision.fired_fallback, null); + }); + + const cases: Array<[string, EnforcementContext, ObservationReport, string]> = [ + ["1 kill switch unset", context({ killSwitch: undefined }), observation(), "kill-switch"], + ["1 kill switch not exactly on", context({ killSwitch: "true" }), observation(), "kill-switch"], + ["2 force-full label", context({ pullRequestLabels: ["bug", FORCE_FULL_LABEL] }), observation(), "per-run-override"], + ["2 commit trailer", context({ headCommitMessage: "fix\n\nDiffCI: full\n" }), observation(), "per-run-override"], + ["3 no enforce block", context({ policy: undefined }), observation(), "policy-not-approved"], + ["3 wrong policy version", context({ policy: { ...APPROVED, policyVersion: 2 } }), observation(), "policy-not-approved"], + ["3 unapproved", context({ policy: { ...APPROVED, approvedBy: "" } }), observation(), "policy-not-approved"], + ["4 open unsafe miss", context({ policy: { ...APPROVED, openUnsafeMisses: [{ test: "x" }] } }), observation(), "open-unsafe-miss"], + ["5 untrusted range", context({ range: { trusted: false, reason: "force-push" } }), observation(), "untrusted-range"], + ["6 analysis refused", context(), observation({}, { status: "REFUSED", reason: "no range", result: undefined }), "analysis-failure"], + ["7 partial graph", context(), observation({ graph: { nodes: 1, edges: 0, confidence: "COMPLETE", effectiveConfidence: "PARTIAL", durationMs: 1 } }), "graph-confidence"], + ["8 redacted paths", context({ pathsRedacted: true }), observation(), "global-risk"], + ["8 critical risk signal", context(), observation({ riskSignals: [{ level: "critical", reason: "GLOBAL_CONFIG" }] }), "global-risk"], + ["8 analyzer fell back", context(), observation({ mode: "FULL", fallbackReasons: ["lockfile changed"] }), "global-risk"], + ["8 workflow file", context(), observation({ changedFiles: [".github/workflows/ci.yml"] }), "global-risk"], + ["8 lockfile", context(), observation({ changedFiles: ["package-lock.json"] }), "global-risk"], + ["8 test runner config", context(), observation({ changedFiles: ["packages/a/vitest.config.ts"] }), "global-risk"], + ["8 diffci config", context(), observation({ changedFiles: ["diffci.config.json"] }), "global-risk"], + ["9 empty selection on source change", context(), observation({ selectedTests: [] }), "empty-selection"], + ]; + for (const [name, ctx, obs, expected] of cases) { + it(`falls back: ${name}`, () => { + assert.equal(evaluateEnforcement(ctx, obs).fired_fallback, expected); + }); + } + + it("allows an empty selection when only documentation changed", () => { + const decision = evaluateEnforcement(context(), observation({ selectedTests: [], changedFiles: ["README.md", "docs/guide.txt"] })); + assert.equal(decision.fired_fallback, null); + }); + + it("reports the first fallback in order, not a later one", () => { + const decision = evaluateEnforcement( + context({ killSwitch: "off", policy: undefined, range: { trusted: false, reason: "x" } }), + observation({ mode: "FULL" }), + ); + assert.equal(decision.fired_fallback, "kill-switch"); + }); +}); + +function git(cwd: string, ...args: string[]): string { + return execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); +} + +function write(root: string, path: string, contents: string): void { + const target = join(root, path); + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(target, contents, "utf8"); +} + +/** `null` writes no diffci.config.json at all. */ +function fixture(enforce: unknown = APPROVED): string { + const dir = mkdtempSync(join(tmpdir(), "diffci-enforce-")); + git(dir, "init", "--quiet"); + git(dir, "config", "user.email", "test@diffci.local"); + git(dir, "config", "user.name", "Test"); + git(dir, "config", "core.autocrlf", "false"); + write(dir, "package.json", JSON.stringify({ name: "fixture", type: "module", scripts: { test: "node --test" } })); + write(dir, "tsconfig.json", JSON.stringify({ compilerOptions: { target: "ES2022", module: "NodeNext", moduleResolution: "NodeNext", allowJs: true }, include: ["src", "test"] })); + if (enforce !== null) write(dir, "diffci.config.json", JSON.stringify({ enforce })); + write(dir, "src/alpha.js", "export const alpha = () => 1;\n"); + write(dir, "src/beta.js", "export const beta = () => 2;\n"); + write(dir, "test/alpha.test.js", "import test from 'node:test'; import assert from 'node:assert/strict'; import {alpha} from '../src/alpha.js'; test('alpha', () => assert.equal(alpha(), 1));\n"); + write(dir, "test/beta.test.js", "import test from 'node:test'; import assert from 'node:assert/strict'; import {beta} from '../src/beta.js'; test('beta', () => assert.equal(beta(), 2));\n"); + git(dir, "add", "-A"); + git(dir, "commit", "--quiet", "-m", "initial"); + return dir; +} + +function commit(dir: string, message: string, files: Record): string { + for (const [path, contents] of Object.entries(files)) write(dir, path, contents); + git(dir, "add", "-A"); + git(dir, "commit", "--quiet", "-m", message); + return git(dir, "rev-parse", "HEAD"); +} + +const ALPHA_CHANGE = { + "src/alpha.js": "export const alpha = () => 3;\n", + "test/alpha.test.js": "import test from 'node:test'; import assert from 'node:assert/strict'; import {alpha} from '../src/alpha.js'; test('alpha', () => assert.equal(alpha(), 3));\n", +}; + +function rangeObservation(baseSha: string, headSha: string, source = "explicit-flags"): ObservationReport { + return observation({}, { commitRange: { baseSha, headSha, source } } as Partial); +} + +describe("collectEnforcementContext", () => { + it("reads the policy at the range base, so a change cannot approve itself", () => { + const dir = fixture(null); + try { + const base = git(dir, "rev-parse", "HEAD"); + const head = commit(dir, "approve myself", { "diffci.config.json": JSON.stringify({ enforce: APPROVED }) }); + const ctx = collectEnforcementContext(makeGitRunner(dir), { DIFFCI_ENFORCE: "on" }, rangeObservation(base, head)); + assert.equal(ctx.policy, undefined); + assert.equal(evaluateEnforcement(ctx, rangeObservation(base, head)).fired_fallback, "policy-not-approved"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("reads the force-full label from the pull request event and the trailer from the head commit", () => { + const dir = fixture(); + try { + const base = git(dir, "rev-parse", "HEAD"); + const head = commit(dir, "change alpha\n\nDiffCI: full", ALPHA_CHANGE); + const eventPath = join(dir, "..", `${dir.split(/[\\/]/).pop()}-event.json`); + writeFileSync(eventPath, JSON.stringify({ pull_request: { labels: [{ name: FORCE_FULL_LABEL }] } })); + try { + const ctx = collectEnforcementContext(makeGitRunner(dir), { GITHUB_EVENT_PATH: eventPath }, rangeObservation(base, head)); + assert.deepEqual(ctx.pullRequestLabels, [FORCE_FULL_LABEL]); + assert.match(ctx.headCommitMessage ?? "", /DiffCI: full/); + } finally { + rmSync(eventPath, { force: true }); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("distrusts a base that is not an ancestor of head (force-push)", () => { + const dir = fixture(); + try { + const root = git(dir, "rev-parse", "HEAD"); + const abandoned = commit(dir, "abandoned", { "src/beta.js": "export const beta = () => 5;\n" }); + git(dir, "reset", "--quiet", "--hard", root); + const head = commit(dir, "rewritten", ALPHA_CHANGE); + const ctx = collectEnforcementContext(makeGitRunner(dir), {}, rangeObservation(abandoned, head, "push-event")); + assert.equal(ctx.range.trusted, false); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("distrusts a head-parent range and trusts an explicit one", () => { + const dir = fixture(); + try { + const base = git(dir, "rev-parse", "HEAD"); + const head = commit(dir, "change alpha", ALPHA_CHANGE); + const runner = makeGitRunner(dir); + assert.equal(collectEnforcementContext(runner, {}, rangeObservation(base, head, "head-parent")).range.trusted, false); + assert.equal(collectEnforcementContext(runner, {}, rangeObservation(base, head)).range.trusted, true); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +function localTestEnv(extra: Record = {}): NodeJS.ProcessEnv { + return { + ...Object.fromEntries( + Object.entries(process.env).filter(([name]) => name !== "NODE_TEST_CONTEXT" && name !== "DIFFCI_ENFORCE" && !name.startsWith("GITHUB_")), + ), + ...extra, + }; +} + +function runVerify(dir: string, args: string[], env: Record = {}) { + return spawnSync( + process.execPath, + ["--import", "tsx", CLI, "verify", "--repo", dir, "--json", ...args], + { cwd: ROOT, encoding: "utf8", timeout: 600_000, env: localTestEnv(env) }, + ); +} + +describe("verify --policy enforce", () => { + it("runs the full suite when the kill switch is off", () => { + const dir = fixture(); + try { + const base = git(dir, "rev-parse", "HEAD"); + const head = commit(dir, "change alpha", ALPHA_CHANGE); + const run = runVerify(dir, ["--base", base, "--head", head, "--policy", "enforce"]); + assert.equal(run.status, 0, run.stdout + run.stderr); + const report = JSON.parse(run.stdout); + assert.equal(report.selection, "full"); + assert.equal(report.enforcement.fired_fallback, "kill-switch"); + assert.equal(report.enforcement.applied, false); + assert.match(report.reason, /enforce fallback \(kill-switch\)/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("runs only the selected tests when every check passes", () => { + const dir = fixture(); + try { + const base = git(dir, "rev-parse", "HEAD"); + const head = commit(dir, "change alpha", ALPHA_CHANGE); + const run = runVerify(dir, ["--base", base, "--head", head, "--policy", "enforce"], { DIFFCI_ENFORCE: "on" }); + assert.equal(run.status, 0, run.stdout + run.stderr); + const report = JSON.parse(run.stdout); + assert.equal(report.enforcement.fired_fallback, null, report.enforcement.detail); + assert.equal(report.selection, "selected"); + assert.equal(report.enforcement.applied, true); + assert.equal(report.tests_selected, 1); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("runs the full suite when package.json changes", () => { + const dir = fixture(); + try { + const base = git(dir, "rev-parse", "HEAD"); + const head = commit(dir, "bump", { + ...ALPHA_CHANGE, + "package.json": JSON.stringify({ name: "fixture", version: "1.0.1", type: "module", scripts: { test: "node --test" } }), + }); + const run = runVerify(dir, ["--base", base, "--head", head, "--policy", "enforce"], { DIFFCI_ENFORCE: "on" }); + assert.equal(run.status, 0, run.stdout + run.stderr); + const report = JSON.parse(run.stdout); + assert.equal(report.selection, "full"); + assert.equal(report.enforcement.fired_fallback, "global-risk"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("leaves plain verify receipts without an enforcement block", () => { + const dir = fixture(); + try { + const base = git(dir, "rev-parse", "HEAD"); + const head = commit(dir, "change alpha", ALPHA_CHANGE); + const run = runVerify(dir, ["--base", base, "--head", head], { DIFFCI_ENFORCE: "on" }); + assert.equal(run.status, 0, run.stdout + run.stderr); + assert.equal(JSON.parse(run.stdout).enforcement, undefined); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("rejects an unknown or missing policy value and --changed with a policy", () => { + const dir = fixture(); + try { + assert.equal(runVerify(dir, ["--policy", "strict"]).status, 2); + assert.equal(runVerify(dir, ["--policy"]).status, 2); + assert.equal(runVerify(dir, ["--changed", "--policy", "enforce"]).status, 2); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/diffci-cli/tests/client/telemetry.test.ts b/packages/diffci-cli/tests/client/telemetry.test.ts new file mode 100644 index 00000000..ce8707ac --- /dev/null +++ b/packages/diffci-cli/tests/client/telemetry.test.ts @@ -0,0 +1,47 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; +import { configureTelemetry, preferencePath, readTelemetryPreference, recordUsage } from "../../src/client/telemetry.js"; +import { deliverUsageSignal } from "../../src/client/usage-signal.js"; + +test("consent is explicit, denial wins, and installation identity exists only in installation mode", async () => { + const home = mkdtempSync(join(tmpdir(), "diffci-telemetry-")); + const env = { DIFFCI_TELEMETRY_HOME: home }; + const originalFetch = globalThis.fetch; + const bodies: any[] = []; + globalThis.fetch = async (_url, init) => { bodies.push(JSON.parse(String(init?.body))); return new Response(null, { status: 200 }); }; + try { + await recordUsage("verify", "passed", "0.3.9", {}, env); + assert.equal(bodies.length, 0); + const first = configureTelemetry("installations", true, env); + assert.equal(configureTelemetry("installations", true, env).installationId, first.installationId); + await recordUsage("verify", "passed", "0.3.9", { "share-usage": true, "no-send": true }, env); + await recordUsage("verify", "passed", "0.3.9", { "share-usage": true }, { ...env, DIFFCI_NO_SEND: "1" }); + assert.equal(bodies.length, 0); + await recordUsage("verify", "passed", "0.3.9", {}, { ...env, DIFFCI_MCP: "1" }); + assert.equal(bodies[0].installation_id, first.installationId); + assert.equal(bodies[0].activity, "internal"); + assert.equal(bodies[0].surface, "local-mcp"); + configureTelemetry("anonymous", false, env); + await recordUsage("observe", "observed", "0.3.9", {}, env); + assert.equal(bodies[1].installation_id, undefined); + assert.equal(readTelemetryPreference(env).installationId, undefined); + configureTelemetry("off", false, env); + await recordUsage("verify", "passed", "0.3.9", {}, env); + assert.equal(bodies.length, 2); + const second = configureTelemetry("installations", false, env); + assert.notEqual(second.installationId, first.installationId); + writeFileSync(preferencePath(env), '{"mode":"installations","installationId":"email@example.com"}'); + assert.equal(readTelemetryPreference(env).mode, "off"); + } finally { globalThis.fetch = originalFetch; rmSync(home, { recursive: true, force: true }); } +}); + +test("delivery distinguishes receipt acceptance, forwarding success, rejection and timeout", async () => { + const signal = { command: "verify" as const, outcome: "passed" as const, version: "0.3.9" }; + for (const [status, expected] of [[200, "delivered"], [202, "accepted"], [502, "failed"]] as const) { + assert.equal((await deliverUsageSignal({ ...signal, fetchImpl: async () => new Response(null, { status }) })).status, expected); + } + assert.equal((await deliverUsageSignal({ ...signal, fetchImpl: async () => { throw new DOMException("timeout", "TimeoutError"); } })).status, "timed-out"); +}); diff --git a/release-files.json b/release-files.json index f1a1006d..f93b2d72 100644 --- a/release-files.json +++ b/release-files.json @@ -192,6 +192,14 @@ "tests/research/baseline/test-activity.test.ts", "tests/research/baseline/workflow-parser.test.ts", "tsconfig.check.json", - "tsconfig.json" + "tsconfig.json", + "packages/diffci-cli/scripts/run-tests.mjs", + "packages/diffci-cli/src/client/enforce-misses-collect.ts", + "packages/diffci-cli/src/client/enforce-misses.ts", + "packages/diffci-cli/src/client/enforce-policy.ts", + "packages/diffci-cli/src/client/telemetry.ts", + "packages/diffci-cli/tests/client/enforce-misses.test.ts", + "packages/diffci-cli/tests/client/enforce-policy.test.ts", + "packages/diffci-cli/tests/client/telemetry.test.ts" ] }