@diffci.com/diffci 0.3.14 → 0.3.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +20 -661
- package/README.md +1 -1
- package/dist-client/src/client/cli.js +140 -11
- package/dist-client/src/client/context.js +1 -1
- package/dist-client/src/client/enforce-misses-collect.js +157 -0
- package/dist-client/src/client/enforce-misses.js +229 -0
- package/dist-client/src/client/enforce-policy.js +169 -0
- package/dist-client/src/client/feedback-prompt.js +42 -0
- package/dist-client/src/client/mcp.js +1 -1
- package/dist-client/src/client/observe.js +1 -1
- package/dist-client/src/client/telemetry.js +46 -0
- package/dist-client/src/client/usage-signal.js +17 -10
- package/dist-client/src/client/verify.js +29 -5
- package/package.json +5 -3
package/README.md
CHANGED
|
@@ -19,7 +19,7 @@ the [cross-agent installation guide](https://github.com/DiffCI/core/blob/main/do
|
|
|
19
19
|
|
|
20
20
|
## Source and license
|
|
21
21
|
|
|
22
|
-
This package is
|
|
22
|
+
This package is MIT-licensed. Its current source lives in
|
|
23
23
|
[`DiffCI/core`](https://github.com/DiffCI/core/tree/main/packages/diffci-cli).
|
|
24
24
|
The corresponding source for the previously published `0.3.10` package is
|
|
25
25
|
preserved at [tagged Core commit `4c76be14`](https://github.com/DiffCI/core/tree/4c76be14cec37d94eb7df93922f3c29d202f4e65/packages/diffci-cli)
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
* verify-savings run a paired full-versus-selected timing check
|
|
18
18
|
* validate-specs block conflicting same-turn change specifications
|
|
19
19
|
* verify-workflow check that a DiffCI job in this repository's workflows cannot affect other jobs
|
|
20
|
+
* enforce-misses after a full run on main, find failures enforce mode would have skipped
|
|
20
21
|
* version print the observer version
|
|
21
22
|
*
|
|
22
23
|
* Exit codes: `observe` exits 0 even when it refuses or errors, because a broken observer must not
|
|
@@ -35,7 +36,8 @@ import { inferFullCommand, inferComparableSelectedCommand, inferWorkspaceCompari
|
|
|
35
36
|
import { addDiffciPackageScripts, detectPackageManager, installDiffci } from "./install.js";
|
|
36
37
|
import { submitObservation } from "./submit.js";
|
|
37
38
|
import { githubDeliveryWarning } from "./delivery-warning.js";
|
|
38
|
-
import {
|
|
39
|
+
import { configureTelemetry, readTelemetryPreference, recordUsage } from "./telemetry.js";
|
|
40
|
+
import { formatFeedbackPrompt, markFeedbackPromptShown, shouldShowFeedbackPrompt } from "./feedback-prompt.js";
|
|
39
41
|
import { detectSpecificationConflicts, readSpecificationFile } from "./spec-conflicts.js";
|
|
40
42
|
import { formatVerificationSummary, verificationExitCode, verifyChanged, verifyRange } from "./verify.js";
|
|
41
43
|
import { formatGrowthPrompt, formatVerifySavingsSummary, measureCommand, runVerifySavings, writeVerifySavingsReport } from "./verify-savings.js";
|
|
@@ -43,6 +45,8 @@ import { auditWorkflows, isNonInterfering } from "./workflow-guard.js";
|
|
|
43
45
|
import { renderPilotPacket } from "./pilot-packet.js";
|
|
44
46
|
import { observerIdentity } from "./package-identity.js";
|
|
45
47
|
import { buildPilotWorkflow, diffciVerificationWorkflow, diffciWorkflow } from "./workflow-templates.js";
|
|
48
|
+
import { buildMissReport, formatMissReportMarkdown, parseJunit } from "./enforce-misses.js";
|
|
49
|
+
import { findReceipt, findWindowStart, inferRerunArgs, mergedPullRequests, MISS_REPORT_FILE, rerunFailingFiles, spawnRunner, } from "./enforce-misses-collect.js";
|
|
46
50
|
function parseArgs(argv) {
|
|
47
51
|
const args = argv.slice(2);
|
|
48
52
|
const flags = {};
|
|
@@ -276,6 +280,7 @@ function runInit(flags, env) {
|
|
|
276
280
|
if (!includeVerificationWorkflow)
|
|
277
281
|
console.log(" skipped .github/workflows/diffci-verify.yml (pass --verification-workflow to add it)");
|
|
278
282
|
console.log(`\nDefault agent command: ${agentCommand}`);
|
|
283
|
+
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.");
|
|
279
284
|
return 0;
|
|
280
285
|
}
|
|
281
286
|
function runMcp() {
|
|
@@ -297,6 +302,15 @@ async function runVerifyCommand(flags, env) {
|
|
|
297
302
|
console.error("diffci verify accepts either --changed or --base/--head, not both");
|
|
298
303
|
return 2;
|
|
299
304
|
}
|
|
305
|
+
const policy = flags.policy === true ? "" : stringFlag(flags, "policy");
|
|
306
|
+
if (policy !== undefined && policy !== "enforce") {
|
|
307
|
+
console.error(`diffci verify --policy accepts only "enforce", got ${JSON.stringify(policy)}`);
|
|
308
|
+
return 2;
|
|
309
|
+
}
|
|
310
|
+
if (policy !== undefined && changed) {
|
|
311
|
+
console.error("diffci verify --policy enforce applies to a commit range, not --changed");
|
|
312
|
+
return 2;
|
|
313
|
+
}
|
|
300
314
|
const repoPath = resolve(stringFlag(flags, "repo") ?? env.GITHUB_WORKSPACE ?? process.cwd());
|
|
301
315
|
const out = stringFlag(flags, "out");
|
|
302
316
|
const reportPath = out ? resolve(out) : undefined;
|
|
@@ -321,7 +335,9 @@ async function runVerifyCommand(flags, env) {
|
|
|
321
335
|
...common,
|
|
322
336
|
baseOverride: stringFlag(flags, "base"),
|
|
323
337
|
headOverride: stringFlag(flags, "head"),
|
|
338
|
+
policy,
|
|
324
339
|
});
|
|
340
|
+
await recordUsage("verify", report.verification, identity.version, flags, env);
|
|
325
341
|
if (reportPath) {
|
|
326
342
|
mkdirSync(dirname(reportPath), { recursive: true });
|
|
327
343
|
writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");
|
|
@@ -404,9 +420,7 @@ async function runCheck(flags, env) {
|
|
|
404
420
|
if (observationCode !== 0)
|
|
405
421
|
return observationCode;
|
|
406
422
|
const observation = JSON.parse(readFileSync(reportPath, "utf8"));
|
|
407
|
-
|
|
408
|
-
await sendUsageSignal({ command: "check", outcome: observation.status === "OBSERVED" ? "observed" : observation.status === "REFUSED" ? "refused" : "error", version: observerIdentity().version });
|
|
409
|
-
}
|
|
423
|
+
await recordUsage("check", observation.status === "OBSERVED" ? "observed" : observation.status === "REFUSED" ? "refused" : "error", observerIdentity().version, flags, env);
|
|
410
424
|
const print = (message) => { if (flags.quiet !== true && flags.json !== true)
|
|
411
425
|
console.log(message); };
|
|
412
426
|
print(summarise(observation, true));
|
|
@@ -531,9 +545,7 @@ async function runObserve(flags, env) {
|
|
|
531
545
|
});
|
|
532
546
|
mkdirSync(dirname(reportPath), { recursive: true });
|
|
533
547
|
writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");
|
|
534
|
-
|
|
535
|
-
await sendUsageSignal({ command: "observe", outcome: report.status === "OBSERVED" ? "observed" : report.status === "REFUSED" ? "refused" : "error", version: identity.version });
|
|
536
|
-
}
|
|
548
|
+
await recordUsage("observe", report.status === "OBSERVED" ? "observed" : report.status === "REFUSED" ? "refused" : "error", identity.version, flags, env);
|
|
537
549
|
const summary = summarise(report);
|
|
538
550
|
if (flags.json === true) {
|
|
539
551
|
console.log(JSON.stringify(report, null, 2));
|
|
@@ -615,6 +627,93 @@ function runVerifyWorkflow(flags, env) {
|
|
|
615
627
|
console.log("\nBlocking findings above: as written, this installation CAN change what the rest of CI does.");
|
|
616
628
|
return 1;
|
|
617
629
|
}
|
|
630
|
+
/**
|
|
631
|
+
* Miss detection (docs/enforce-mode-01-plan.md, step 5). Exit 0: no miss. Exit 1: at least one miss.
|
|
632
|
+
* Exit 2: the full run left no results to classify, or the invocation is wrong. It never edits
|
|
633
|
+
* diffci.config.json or repository variables; it prints the entries for a human to add.
|
|
634
|
+
*/
|
|
635
|
+
function runEnforceMisses(flags, env) {
|
|
636
|
+
const repoPath = resolve(stringFlag(flags, "repo") ?? env.GITHUB_WORKSPACE ?? process.cwd());
|
|
637
|
+
const junitPath = stringFlag(flags, "junit");
|
|
638
|
+
const outFlag = stringFlag(flags, "out-dir");
|
|
639
|
+
const repository = stringFlag(flags, "repository") ?? env.GITHUB_REPOSITORY;
|
|
640
|
+
if (!junitPath || !outFlag || !repository) {
|
|
641
|
+
console.error("diffci enforce-misses needs --junit <file>, --out-dir <dir> and --repository <owner/name> (or GITHUB_REPOSITORY)");
|
|
642
|
+
return 2;
|
|
643
|
+
}
|
|
644
|
+
const outDir = resolve(outFlag);
|
|
645
|
+
if (outDir === repoPath || isInsideRepository(repoPath, outDir)) {
|
|
646
|
+
console.error(`Refusing to write the miss report inside the repository: ${outDir}. Use --out-dir outside the checkout.`);
|
|
647
|
+
return 2;
|
|
648
|
+
}
|
|
649
|
+
if (!existsSync(junitPath)) {
|
|
650
|
+
console.error(`No full-suite results at ${junitPath}: nothing can be classified, so no miss can be ruled out.`);
|
|
651
|
+
return 2;
|
|
652
|
+
}
|
|
653
|
+
const headSha = stringFlag(flags, "head") ?? execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoPath, encoding: "utf8" }).trim();
|
|
654
|
+
const fullRun = parseJunit(readFileSync(junitPath, "utf8"), repoPath);
|
|
655
|
+
const failing = fullRun.filter((outcome) => outcome.failed);
|
|
656
|
+
const runUrl = env.GITHUB_RUN_ID ? `${env.GITHUB_SERVER_URL ?? "https://github.com"}/${repository}/actions/runs/${env.GITHUB_RUN_ID}` : undefined;
|
|
657
|
+
const notes = [];
|
|
658
|
+
let report;
|
|
659
|
+
if (failing.length === 0) {
|
|
660
|
+
// A green run is the cheapest case and the most common one: no GitHub calls, and its record
|
|
661
|
+
// (no failures) becomes the next run's window start.
|
|
662
|
+
report = buildMissReport({ fullRun, rerun: undefined, baseline: [], pullRequests: [], headSha, producedAt: new Date().toISOString(), runUrl, window: { from_sha: null, source: "none" } });
|
|
663
|
+
}
|
|
664
|
+
else {
|
|
665
|
+
const rerunJunit = stringFlag(flags, "rerun-junit");
|
|
666
|
+
const rerunArgs = inferRerunArgs(repoPath);
|
|
667
|
+
const files = [...new Set(failing.map((outcome) => outcome.file).filter(Boolean))];
|
|
668
|
+
const rerun = rerunJunit
|
|
669
|
+
? parseJunit(readFileSync(rerunJunit, "utf8"), repoPath)
|
|
670
|
+
: rerunArgs && files.length > 0 ? rerunFailingFiles(repoPath, rerunArgs, files) : undefined;
|
|
671
|
+
if (!rerun)
|
|
672
|
+
notes.push("failures were not re-run, so none could be ruled flaky; every failure was treated as deterministic");
|
|
673
|
+
const collect = {
|
|
674
|
+
repoPath,
|
|
675
|
+
repository,
|
|
676
|
+
headSha,
|
|
677
|
+
runId: env.GITHUB_RUN_ID,
|
|
678
|
+
workDir: join(outDir, "downloads"),
|
|
679
|
+
run: spawnRunner,
|
|
680
|
+
};
|
|
681
|
+
const window = findWindowStart(collect);
|
|
682
|
+
if (!window.fromSha)
|
|
683
|
+
notes.push("no earlier detector record or green full run was found, so no pull request could be held against these failures");
|
|
684
|
+
const pullRequests = mergedPullRequests(collect, window.fromSha).map((pr) => ({ ...pr, receipt: findReceipt(collect, pr) }));
|
|
685
|
+
report = buildMissReport({
|
|
686
|
+
fullRun,
|
|
687
|
+
rerun,
|
|
688
|
+
baseline: window.baseline,
|
|
689
|
+
pullRequests,
|
|
690
|
+
headSha,
|
|
691
|
+
producedAt: new Date().toISOString(),
|
|
692
|
+
runUrl,
|
|
693
|
+
window: { from_sha: window.fromSha, source: window.source },
|
|
694
|
+
notes,
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
mkdirSync(outDir, { recursive: true });
|
|
698
|
+
const markdown = formatMissReportMarkdown(report);
|
|
699
|
+
writeFileSync(join(outDir, MISS_REPORT_FILE), `${JSON.stringify(report, null, 2)}
|
|
700
|
+
`, "utf8");
|
|
701
|
+
writeFileSync(join(outDir, "enforce-misses.md"), markdown, "utf8");
|
|
702
|
+
console.log(markdown);
|
|
703
|
+
if (report.misses === 0)
|
|
704
|
+
return 0;
|
|
705
|
+
console.log("Add to enforce.openUnsafeMisses in diffci.config.json (not done automatically):");
|
|
706
|
+
console.log(JSON.stringify(report.open_unsafe_misses, null, 2));
|
|
707
|
+
if (flags["open-issue"] === true) {
|
|
708
|
+
const title = `DiffCI enforce: unsafe miss on main at ${headSha.slice(0, 12)}`;
|
|
709
|
+
const created = spawnRunner("gh", ["issue", "create", "--repo", repository, "--title", title, "--body-file", join(outDir, "enforce-misses.md")]);
|
|
710
|
+
if (created.ok)
|
|
711
|
+
console.log(`Opened ${created.stdout.trim()}`);
|
|
712
|
+
else
|
|
713
|
+
console.error(`Could not open an issue (${created.stderr.trim()}); the report is in ${outDir}.`);
|
|
714
|
+
}
|
|
715
|
+
return 1;
|
|
716
|
+
}
|
|
618
717
|
function stringFlag(flags, name) {
|
|
619
718
|
const value = flags[name];
|
|
620
719
|
return typeof value === "string" ? value : undefined;
|
|
@@ -811,8 +910,9 @@ Pilot a repository: https://diffci.com/#pilot
|
|
|
811
910
|
Usage:
|
|
812
911
|
diffci init [--repo <path>] [--workflow] [--verification-workflow] [--install] [--force]
|
|
813
912
|
diffci mcp
|
|
814
|
-
diffci verify [--changed | --base <sha> --head <sha>] [--repo <path>] [--out <file>] [--json]
|
|
815
|
-
[--redact-paths] [--timeout-ms <ms>] [--baseline-on-failure]
|
|
913
|
+
diffci verify [--changed | --base <sha> --head <sha>] [--policy enforce] [--repo <path>] [--out <file>] [--json]
|
|
914
|
+
[--redact-paths] [--timeout-ms <ms>] [--baseline-on-failure] [--share-usage] [--no-send]
|
|
915
|
+
diffci telemetry [--mode off|anonymous|installations] [--internal-usage]
|
|
816
916
|
diffci check [--repo <path>] [--out <file>] [--base <sha> --head <sha>]
|
|
817
917
|
[--redact-paths] [--json] [--quiet] [--fail-on-error] [--timeout-ms <ms>] [--share-usage]
|
|
818
918
|
diffci pilot --full <command> [--selected <command>] [--repo <path>] [--out-dir <dir>] [--label <name>]
|
|
@@ -828,6 +928,8 @@ Usage:
|
|
|
828
928
|
[--cache-prepare <command>] [--fixed-order]
|
|
829
929
|
diffci validate-specs --file <json> [--json]
|
|
830
930
|
diffci verify-workflow [--repo <path>]
|
|
931
|
+
diffci enforce-misses --junit <file> --out-dir <dir> [--repository <owner/name>] [--repo <path>]
|
|
932
|
+
[--head <sha>] [--rerun-junit <file>] [--open-issue]
|
|
831
933
|
diffci version
|
|
832
934
|
|
|
833
935
|
init writes AGENTS.md, CLAUDE.md, Cursor rules, Copilot instructions, and diffci.config.json.
|
|
@@ -848,13 +950,27 @@ observe analyses the checkout and writes one JSON report. It runs nothing and ch
|
|
|
848
950
|
verify-savings runs both commands and reports measured paired runtime; it is an opt-in pilot command.
|
|
849
951
|
validate-specs checks an explicit list of specification IDs and logical targets and blocks duplicates.
|
|
850
952
|
verify-workflow checks that the job running DiffCI cannot affect any other job, and exits 1 if it can.
|
|
953
|
+
enforce-misses classifies a full run's failures on main against the enforce dry-run receipts of the pull
|
|
954
|
+
requests merged since the last recorded run, and exits 1 on a miss. It never edits configuration.
|
|
955
|
+
Failures are re-run with the package.json tsx --test runner, or read from --rerun-junit for other runners.
|
|
851
956
|
|
|
852
957
|
The report is sent only when both --api-url and --api-token are given (or DIFFCI_API_URL and
|
|
853
958
|
DIFFCI_TOKEN are set). A failed send is reported and never fails the step - the report is on disk
|
|
854
959
|
either way. Plain http is refused; the token is never printed.
|
|
855
|
-
--share-usage (or DIFFCI_SHARE_USAGE=1)
|
|
856
|
-
|
|
960
|
+
--share-usage (or DIFFCI_SHARE_USAGE=1) opts in to command, outcome, version, surface and activity reporting.
|
|
961
|
+
diffci telemetry --mode anonymous saves consent; --mode installations also shares a random local installation ID.
|
|
962
|
+
--mode off disables saved consent and deletes the ID. --internal-usage labels tests/internal activity.
|
|
963
|
+
No repository, commit, test, report, paths, or machine details are sent. --no-send or DIFFCI_NO_SEND=1 disables it.
|
|
964
|
+
Interactive check and observe runs print feedback links to stderr at most weekly; they send nothing.
|
|
965
|
+
CI, MCP, --json and --quiet never show them; DIFFCI_NO_FEEDBACK_PROMPT=1 hides them.
|
|
857
966
|
`;
|
|
967
|
+
function maybeShowFeedbackPrompt(flags, env) {
|
|
968
|
+
if (!shouldShowFeedbackPrompt(flags, env, process.stderr.isTTY === true))
|
|
969
|
+
return;
|
|
970
|
+
// stderr keeps piped stdout unchanged.
|
|
971
|
+
console.error(formatFeedbackPrompt(readTelemetryPreference(env).mode));
|
|
972
|
+
markFeedbackPromptShown(env);
|
|
973
|
+
}
|
|
858
974
|
async function main() {
|
|
859
975
|
const { command, flags } = parseArgs(process.argv);
|
|
860
976
|
const env = process.env;
|
|
@@ -864,6 +980,14 @@ async function main() {
|
|
|
864
980
|
return;
|
|
865
981
|
}
|
|
866
982
|
switch (command) {
|
|
983
|
+
case "telemetry": {
|
|
984
|
+
const mode = stringFlag(flags, "mode");
|
|
985
|
+
const preference = mode ? configureTelemetry(mode, flags["internal-usage"] === true, env) : readTelemetryPreference(env);
|
|
986
|
+
console.log(`DiffCI telemetry: ${preference.mode}; activity: ${preference.internal ? "internal" : "external"}.`);
|
|
987
|
+
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.");
|
|
988
|
+
process.exitCode = 0;
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
867
991
|
case "init":
|
|
868
992
|
process.exitCode = runInit(flags, env);
|
|
869
993
|
return;
|
|
@@ -875,6 +999,7 @@ async function main() {
|
|
|
875
999
|
return;
|
|
876
1000
|
case "check":
|
|
877
1001
|
process.exitCode = await runCheck(flags, env);
|
|
1002
|
+
maybeShowFeedbackPrompt(flags, env);
|
|
878
1003
|
return;
|
|
879
1004
|
case "pilot":
|
|
880
1005
|
process.exitCode = await runPilot(flags, env);
|
|
@@ -884,6 +1009,7 @@ async function main() {
|
|
|
884
1009
|
return;
|
|
885
1010
|
case "observe":
|
|
886
1011
|
process.exitCode = await runObserve(flags, env);
|
|
1012
|
+
maybeShowFeedbackPrompt(flags, env);
|
|
887
1013
|
return;
|
|
888
1014
|
case "verify-savings":
|
|
889
1015
|
process.exitCode = runVerifySavingsCommand(flags, env);
|
|
@@ -894,6 +1020,9 @@ async function main() {
|
|
|
894
1020
|
case "verify-workflow":
|
|
895
1021
|
process.exitCode = runVerifyWorkflow(flags, env);
|
|
896
1022
|
return;
|
|
1023
|
+
case "enforce-misses":
|
|
1024
|
+
process.exitCode = runEnforceMisses(flags, env);
|
|
1025
|
+
return;
|
|
897
1026
|
case "version":
|
|
898
1027
|
console.log(observerIdentity().version);
|
|
899
1028
|
return;
|
|
@@ -22,7 +22,7 @@ import { existsSync, readFileSync } from "node:fs";
|
|
|
22
22
|
/** Triggers that carry no inherent "what changed" - a range for these would have to be invented. */
|
|
23
23
|
const SYNTHETIC_TRIGGERS = new Set(["schedule", "workflow_dispatch", "repository_dispatch", "release"]);
|
|
24
24
|
const ZERO_SHA = "0000000000000000000000000000000000000000";
|
|
25
|
-
function readEventPayload(env) {
|
|
25
|
+
export function readEventPayload(env) {
|
|
26
26
|
const path = env.GITHUB_EVENT_PATH;
|
|
27
27
|
if (!path || !existsSync(path))
|
|
28
28
|
return undefined;
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The side effects of miss detection (docs/enforce-mode-01-plan.md, step 5): finding the window, the
|
|
3
|
+
* pull requests merged in it, their dry-run receipts, and re-running the failing test files. GitHub is
|
|
4
|
+
* reached only through the `gh` CLI, and every external call goes through an injectable runner.
|
|
5
|
+
*
|
|
6
|
+
* The window starts at the most recent earlier run of the detector itself (its uploaded report lists
|
|
7
|
+
* the failures that were already there), or, before the first such run exists, at the last green
|
|
8
|
+
* `ci.yml` push run on `main`. Either commit must be an ancestor of the commit being checked.
|
|
9
|
+
*/
|
|
10
|
+
import { spawnSync } from "node:child_process";
|
|
11
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
12
|
+
import { createRequire } from "node:module";
|
|
13
|
+
import { tmpdir } from "node:os";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
import { MISS_REPORT_SCHEMA, parseJunit } from "./enforce-misses.js";
|
|
16
|
+
import { VERIFICATION_SCHEMA } from "./verify.js";
|
|
17
|
+
export const DRY_RUN_ARTIFACT_PREFIX = "diffci-enforce-dry-run-";
|
|
18
|
+
export const MISS_RECORD_ARTIFACT_PREFIX = "diffci-enforce-misses-";
|
|
19
|
+
export const MISS_REPORT_FILE = "enforce-misses.json";
|
|
20
|
+
const DRY_RUN_RECEIPT_FILE = "diffci-enforce-dry-run.json";
|
|
21
|
+
export const spawnRunner = (executable, args, options = {}) => {
|
|
22
|
+
const result = spawnSync(executable, args, { cwd: options.cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
|
|
23
|
+
return { ok: result.status === 0, stdout: result.stdout ?? "", stderr: result.stderr ?? result.error?.message ?? "" };
|
|
24
|
+
};
|
|
25
|
+
function ghJson(options, path) {
|
|
26
|
+
const result = options.run("gh", ["api", path]);
|
|
27
|
+
if (!result.ok)
|
|
28
|
+
return undefined;
|
|
29
|
+
try {
|
|
30
|
+
return JSON.parse(result.stdout);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function isAncestor(options, ancestor) {
|
|
37
|
+
return options.run("git", ["merge-base", "--is-ancestor", ancestor, options.headSha], { cwd: options.repoPath }).ok;
|
|
38
|
+
}
|
|
39
|
+
function workflowRuns(options, workflow, query) {
|
|
40
|
+
return ghJson(options, `repos/${options.repository}/actions/workflows/${workflow}/runs?${query}`)?.workflow_runs ?? [];
|
|
41
|
+
}
|
|
42
|
+
function runArtifacts(options, runId, prefix) {
|
|
43
|
+
const artifacts = ghJson(options, `repos/${options.repository}/actions/runs/${runId}/artifacts?per_page=100`)?.artifacts ?? [];
|
|
44
|
+
return artifacts.filter((artifact) => !artifact.expired && artifact.name.startsWith(prefix));
|
|
45
|
+
}
|
|
46
|
+
/** Download one artifact and parse the named JSON file from it. */
|
|
47
|
+
function downloadJson(options, runId, artifact, file) {
|
|
48
|
+
mkdirSync(options.workDir, { recursive: true });
|
|
49
|
+
const directory = mkdtempSync(join(options.workDir, "artifact-"));
|
|
50
|
+
const result = options.run("gh", ["run", "download", String(runId), "--repo", options.repository, "--name", artifact, "--dir", directory]);
|
|
51
|
+
if (!result.ok)
|
|
52
|
+
return undefined;
|
|
53
|
+
const path = join(directory, file);
|
|
54
|
+
if (!existsSync(path))
|
|
55
|
+
return undefined;
|
|
56
|
+
try {
|
|
57
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export function findWindowStart(options) {
|
|
64
|
+
const detector = options.detectorWorkflow ?? "diffci-enforce-misses.yml";
|
|
65
|
+
for (const run of workflowRuns(options, detector, "branch=main&status=completed&per_page=30")) {
|
|
66
|
+
if (String(run.id) === options.runId || !isAncestor(options, run.head_sha))
|
|
67
|
+
continue;
|
|
68
|
+
for (const artifact of runArtifacts(options, run.id, MISS_RECORD_ARTIFACT_PREFIX)) {
|
|
69
|
+
const record = downloadJson(options, run.id, artifact.name, MISS_REPORT_FILE);
|
|
70
|
+
if (record?.schema === MISS_REPORT_SCHEMA && Array.isArray(record.deterministic_failures)) {
|
|
71
|
+
return { fromSha: run.head_sha, source: "detector-record", baseline: record.deterministic_failures };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const fullSuite = options.fullSuiteWorkflow ?? "ci.yml";
|
|
76
|
+
for (const run of workflowRuns(options, fullSuite, "branch=main&event=push&status=success&per_page=30")) {
|
|
77
|
+
if (isAncestor(options, run.head_sha))
|
|
78
|
+
return { fromSha: run.head_sha, source: "green-full-run", baseline: [] };
|
|
79
|
+
}
|
|
80
|
+
return { fromSha: null, source: "none", baseline: [] };
|
|
81
|
+
}
|
|
82
|
+
/** Pull requests merged into `main` by the first-parent commits after `fromSha`, oldest first. */
|
|
83
|
+
export function mergedPullRequests(options, fromSha) {
|
|
84
|
+
if (!fromSha)
|
|
85
|
+
return [];
|
|
86
|
+
const listed = options.run("git", ["rev-list", "--first-parent", "--reverse", `${fromSha}..${options.headSha}`], { cwd: options.repoPath });
|
|
87
|
+
if (!listed.ok)
|
|
88
|
+
return [];
|
|
89
|
+
const commits = listed.stdout.split(/\s+/).filter(Boolean).slice(-(options.maxCommits ?? 100));
|
|
90
|
+
const found = new Map();
|
|
91
|
+
for (const sha of commits) {
|
|
92
|
+
for (const pull of ghJson(options, `repos/${options.repository}/commits/${sha}/pulls`) ?? []) {
|
|
93
|
+
if (!pull.merged_at || pull.base?.ref !== "main" || !pull.head?.sha || found.has(pull.number))
|
|
94
|
+
continue;
|
|
95
|
+
found.set(pull.number, { number: pull.number, title: pull.title, mergeSha: sha, headSha: pull.head.sha });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return [...found.values()];
|
|
99
|
+
}
|
|
100
|
+
/** The newest dry-run receipt recorded for the pull request's final head commit. */
|
|
101
|
+
export function findReceipt(options, pr) {
|
|
102
|
+
const workflow = options.dryRunWorkflow ?? "diffci-enforce-dry-run.yml";
|
|
103
|
+
for (const run of workflowRuns(options, workflow, `head_sha=${pr.headSha}&per_page=20`)) {
|
|
104
|
+
for (const artifact of runArtifacts(options, run.id, `${DRY_RUN_ARTIFACT_PREFIX}${pr.number}-`)) {
|
|
105
|
+
const report = downloadJson(options, run.id, artifact.name, DRY_RUN_RECEIPT_FILE);
|
|
106
|
+
if (report?.schema === VERIFICATION_SCHEMA)
|
|
107
|
+
return { artifact: artifact.name, report };
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Node arguments that re-run test files the way package.json's `tsx --test` script runs them: tsx's own
|
|
114
|
+
* CLI under this Node, so no shell and no `.cmd` shim is involved and test paths stay literal argv.
|
|
115
|
+
*/
|
|
116
|
+
export function inferRerunArgs(repoPath) {
|
|
117
|
+
try {
|
|
118
|
+
const script = JSON.parse(readFileSync(join(repoPath, "package.json"), "utf8")).scripts?.test;
|
|
119
|
+
if (typeof script !== "string")
|
|
120
|
+
return undefined;
|
|
121
|
+
const runners = [...script.matchAll(/\btsx(?:\s+--conditions\s+([\w,-]+))?\s+--test\b/g)];
|
|
122
|
+
if (runners.length !== 1)
|
|
123
|
+
return undefined;
|
|
124
|
+
const cli = createRequire(join(repoPath, "package.json")).resolve("tsx/cli");
|
|
125
|
+
const conditions = runners[0][1];
|
|
126
|
+
return [cli, ...(conditions ? ["--conditions", conditions] : []), "--test"];
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Re-run only the failing files with node:test's JUnit reporter, set through NODE_OPTIONS so the runner
|
|
134
|
+
* arguments stay what package.json declares. Returns undefined when no result file was written.
|
|
135
|
+
*/
|
|
136
|
+
export function rerunFailingFiles(repoPath, runnerArgs, files) {
|
|
137
|
+
const directory = mkdtempSync(join(tmpdir(), "diffci-misses-rerun-"));
|
|
138
|
+
const junit = join(directory, "rerun.junit.xml");
|
|
139
|
+
try {
|
|
140
|
+
spawnSync(process.execPath, [...runnerArgs, ...files], {
|
|
141
|
+
cwd: repoPath,
|
|
142
|
+
stdio: "inherit",
|
|
143
|
+
env: {
|
|
144
|
+
...process.env,
|
|
145
|
+
NODE_OPTIONS: [process.env.NODE_OPTIONS, "--test-reporter=spec", "--test-reporter-destination=stdout", "--test-reporter=junit", `--test-reporter-destination=${junit}`]
|
|
146
|
+
.filter(Boolean)
|
|
147
|
+
.join(" "),
|
|
148
|
+
},
|
|
149
|
+
});
|
|
150
|
+
if (!existsSync(junit))
|
|
151
|
+
return undefined;
|
|
152
|
+
return parseJunit(readFileSync(junit, "utf8"), repoPath);
|
|
153
|
+
}
|
|
154
|
+
finally {
|
|
155
|
+
rmSync(directory, { recursive: true, force: true });
|
|
156
|
+
}
|
|
157
|
+
}
|