@diffci.com/diffci 0.3.21 → 0.3.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist-client/src/client/agent-identity.d.ts +26 -0
  2. package/dist-client/src/client/agent-identity.js +62 -0
  3. package/dist-client/src/client/agent-selection.d.ts +55 -0
  4. package/dist-client/src/client/cli.d.ts +2 -0
  5. package/dist-client/src/client/cli.js +68 -3
  6. package/dist-client/src/client/command-batches.d.ts +26 -0
  7. package/dist-client/src/client/command-batches.js +7 -1
  8. package/dist-client/src/client/context.d.ts +47 -0
  9. package/dist-client/src/client/delivery-warning.d.ts +1 -0
  10. package/dist-client/src/client/economics.d.ts +17 -0
  11. package/dist-client/src/client/enforce-misses-collect.d.ts +49 -0
  12. package/dist-client/src/client/enforce-misses.d.ts +124 -0
  13. package/dist-client/src/client/enforce-policy.d.ts +33 -0
  14. package/dist-client/src/client/failure-baseline.d.ts +67 -0
  15. package/dist-client/src/client/failure-baseline.js +43 -19
  16. package/dist-client/src/client/feedback-prompt.d.ts +6 -0
  17. package/dist-client/src/client/full-command.d.ts +16 -0
  18. package/dist-client/src/client/gate-checks.d.ts +54 -0
  19. package/dist-client/src/client/gate-checks.js +16 -4
  20. package/dist-client/src/client/gate.d.ts +154 -0
  21. package/dist-client/src/client/hook.d.ts +27 -0
  22. package/dist-client/src/client/install.d.ts +19 -0
  23. package/dist-client/src/client/mcp.d.ts +2 -0
  24. package/dist-client/src/client/observe.d.ts +52 -0
  25. package/dist-client/src/client/observe.js +25 -3
  26. package/dist-client/src/client/package-identity.d.ts +14 -0
  27. package/dist-client/src/client/pilot-packet.d.ts +6 -0
  28. package/dist-client/src/client/report.d.ts +265 -0
  29. package/dist-client/src/client/selected-coverage.d.ts +19 -0
  30. package/dist-client/src/client/selected-coverage.js +86 -0
  31. package/dist-client/src/client/shared-graph-cache.d.ts +113 -0
  32. package/dist-client/src/client/shared-graph-cache.js +347 -0
  33. package/dist-client/src/client/spec-conflicts.d.ts +19 -0
  34. package/dist-client/src/client/submit.d.ts +61 -0
  35. package/dist-client/src/client/telemetry.d.ts +13 -0
  36. package/dist-client/src/client/usage-signal.d.ts +19 -0
  37. package/dist-client/src/client/verify-savings.d.ts +186 -0
  38. package/dist-client/src/client/verify-savings.js +3 -0
  39. package/dist-client/src/client/verify.d.ts +113 -0
  40. package/dist-client/src/client/verify.js +37 -13
  41. package/dist-client/src/client/workflow-guard.d.ts +59 -0
  42. package/dist-client/src/client/workflow-guard.js +253 -0
  43. package/dist-client/src/client/workflow-templates.d.ts +8 -0
  44. package/dist-client/src/client/working-tree.d.ts +26 -0
  45. package/dist-client/src/preflight/fingerprint.d.ts +29 -0
  46. package/dist-client/src/preflight/taxonomy.d.ts +10 -0
  47. package/node_modules/@diffci.com/core/README.md +4 -0
  48. package/node_modules/@diffci.com/core/dist/git/git-diff.js +17 -2
  49. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  50. package/node_modules/@diffci.com/core/dist/planner/test-command.d.ts +2 -0
  51. package/node_modules/@diffci.com/core/dist/planner/test-command.js +46 -1
  52. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  53. package/node_modules/@diffci.com/core/src/git/git-diff.ts +17 -2
  54. package/node_modules/@diffci.com/core/src/planner/test-command.ts +45 -1
  55. package/package.json +9 -2
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Which AI coding agent produced a change, when the person running DiffCI chooses to say so.
3
+ *
4
+ * Opt-in only. Nothing here runs unless `--agent <name>` / `DIFFCI_AGENT` is given; `--agent auto`
5
+ * additionally checks a short list of marker variables the agents themselves set. Only the resulting
6
+ * label is recorded - never a variable's value, never any other environment, never source.
7
+ */
8
+ /** Agent identities DiffCI recognises. Anything else declared explicitly is "other". */
9
+ export declare const KNOWN_AGENTS: readonly ["claude", "codex", "cursor", "copilot", "devin", "gemini", "aider", "jules", "openhands"];
10
+ export type KnownAgent = (typeof KNOWN_AGENTS)[number];
11
+ export type AgentId = KnownAgent | "other";
12
+ export interface ObservationAgent {
13
+ name: AgentId;
14
+ /** `flag`: the caller named the agent. `environment`: `--agent auto` found exactly one marker. */
15
+ source: "flag" | "environment";
16
+ }
17
+ /**
18
+ * Normalises a declared agent name. `null` means "declared: no agent"; `undefined` means the value is
19
+ * unusable and must be ignored. Unrecognised but well-formed names become "other" rather than being
20
+ * stored verbatim, so a free-text field cannot grow the set of reported identities.
21
+ */
22
+ export declare function normalizeDeclaredAgent(value: unknown): AgentId | null | undefined;
23
+ /** Exactly one agent's marker present, or nothing: two markers is ambiguity, never a guess. */
24
+ export declare function detectAgentFromEnvironment(env: Record<string, string | undefined>): KnownAgent | undefined;
25
+ /** Resolves `--agent` / `DIFFCI_AGENT`. Absent means the report carries no agent field at all. */
26
+ export declare function resolveObservationAgent(flag: string | boolean | undefined, env: Record<string, string | undefined>): ObservationAgent | undefined;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Which AI coding agent produced a change, when the person running DiffCI chooses to say so.
3
+ *
4
+ * Opt-in only. Nothing here runs unless `--agent <name>` / `DIFFCI_AGENT` is given; `--agent auto`
5
+ * additionally checks a short list of marker variables the agents themselves set. Only the resulting
6
+ * label is recorded - never a variable's value, never any other environment, never source.
7
+ */
8
+ /** Agent identities DiffCI recognises. Anything else declared explicitly is "other". */
9
+ export const KNOWN_AGENTS = ["claude", "codex", "cursor", "copilot", "devin", "gemini", "aider", "jules", "openhands"];
10
+ const ALIASES = {
11
+ claude: "claude", "claude-code": "claude", claudecode: "claude", anthropic: "claude",
12
+ codex: "codex", "codex-cli": "codex", "openai-codex": "codex", "chatgpt-codex": "codex",
13
+ cursor: "cursor", "cursor-agent": "cursor", cursoragent: "cursor",
14
+ copilot: "copilot", "github-copilot": "copilot", "copilot-swe-agent": "copilot",
15
+ devin: "devin", "devin-ai": "devin",
16
+ gemini: "gemini", "gemini-cli": "gemini", "gemini-code-assist": "gemini",
17
+ aider: "aider", jules: "jules", "google-jules": "jules", openhands: "openhands", "all-hands": "openhands",
18
+ };
19
+ const NOT_AN_AGENT = new Set(["human", "none", "no", "false", "0"]);
20
+ /**
21
+ * Normalises a declared agent name. `null` means "declared: no agent"; `undefined` means the value is
22
+ * unusable and must be ignored. Unrecognised but well-formed names become "other" rather than being
23
+ * stored verbatim, so a free-text field cannot grow the set of reported identities.
24
+ */
25
+ export function normalizeDeclaredAgent(value) {
26
+ const raw = typeof value === "string" ? value
27
+ : value && typeof value === "object" && typeof value.name === "string" ? value.name
28
+ : undefined;
29
+ if (raw === undefined)
30
+ return undefined;
31
+ const name = raw.trim().toLowerCase().replace(/[\s_]+/g, "-");
32
+ if (!/^[a-z0-9][a-z0-9.-]{0,39}$/.test(name))
33
+ return undefined;
34
+ if (NOT_AN_AGENT.has(name))
35
+ return null;
36
+ return Object.hasOwn(ALIASES, name) ? ALIASES[name] : "other";
37
+ }
38
+ /** Marker variables set by the agents' own shells. Presence is all that is read. */
39
+ const ENVIRONMENT_MARKERS = [
40
+ ["CLAUDECODE", "claude"],
41
+ ["CURSOR_AGENT", "cursor"],
42
+ ["CODEX_SANDBOX", "codex"],
43
+ ["CODEX_SANDBOX_NETWORK_DISABLED", "codex"],
44
+ ["GEMINI_CLI", "gemini"],
45
+ ];
46
+ /** Exactly one agent's marker present, or nothing: two markers is ambiguity, never a guess. */
47
+ export function detectAgentFromEnvironment(env) {
48
+ const found = new Set(ENVIRONMENT_MARKERS.filter(([key]) => (env[key] ?? "") !== "" && env[key] !== "0").map(([, agent]) => agent));
49
+ return found.size === 1 ? [...found][0] : undefined;
50
+ }
51
+ /** Resolves `--agent` / `DIFFCI_AGENT`. Absent means the report carries no agent field at all. */
52
+ export function resolveObservationAgent(flag, env) {
53
+ const requested = typeof flag === "string" ? flag : env.DIFFCI_AGENT;
54
+ if (!requested)
55
+ return undefined;
56
+ if (requested.trim().toLowerCase() === "auto") {
57
+ const detected = detectAgentFromEnvironment(env);
58
+ return detected ? { name: detected, source: "environment" } : undefined;
59
+ }
60
+ const name = normalizeDeclaredAgent(requested);
61
+ return name ? { name, source: "flag" } : undefined;
62
+ }
@@ -0,0 +1,55 @@
1
+ /** Cheap change discovery, without building the dependency graph. */
2
+ export declare function agentChangedFiles(repoInput: string): {
3
+ schema: string;
4
+ scope: string;
5
+ status: string;
6
+ tests_executed: boolean;
7
+ snapshot: {
8
+ base_sha: string;
9
+ tree_sha: string;
10
+ unchanged: boolean;
11
+ };
12
+ changed_files: string[];
13
+ reason: string;
14
+ };
15
+ export type AgentSelectionPlan = Awaited<ReturnType<typeof agentSelection>>;
16
+ /** Analyze the live snapshot using the same engine as verification. Never executes tests. */
17
+ export declare function agentSelection(repoInput: string): Promise<{
18
+ checks: import("./gate-checks.js").PlannedCheck[];
19
+ skipped_checks: {
20
+ id: string;
21
+ reason: string;
22
+ }[];
23
+ reason: string;
24
+ fallback_reasons: string[];
25
+ analysis_status: string;
26
+ analysis_mode: "SELECTIVE" | "FULL" | undefined;
27
+ graph_confidence: string | undefined;
28
+ risk_signals: {
29
+ level: string;
30
+ reason: string;
31
+ }[];
32
+ required_ci_authoritative: boolean;
33
+ commands?: string[] | undefined;
34
+ schema: string;
35
+ scope: string;
36
+ status: string;
37
+ tests_executed: boolean;
38
+ snapshot: {
39
+ base_sha: string;
40
+ tree_sha: string;
41
+ unchanged: boolean;
42
+ };
43
+ changed_files: string[];
44
+ selection: "none" | "full" | "selected";
45
+ selected_tests: string[];
46
+ tests_available: number;
47
+ tests_selected: number;
48
+ command: string | undefined;
49
+ }>;
50
+ /**
51
+ * One plain sentence ahead of the JSON, naming the exact command to run (2026-10-28). Agents given only
52
+ * the JSON plan mostly went on to pick their own test files or run the whole suite; the first line is
53
+ * what they act on, so it says what to run and nothing else.
54
+ */
55
+ export declare function selectionInstruction(plan: AgentSelectionPlan): string;
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -33,10 +33,13 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
33
33
  import { tmpdir } from "node:os";
34
34
  import { basename, dirname, join, resolve } from "node:path";
35
35
  import { observe, isInsideRepository } from "./observe.js";
36
+ import { resolveObservationAgent } from "./agent-identity.js";
36
37
  import { inferFullCommand, inferComparableSelectedCommand, inferWorkspaceComparison } from "./full-command.js";
37
38
  import { addDiffciPackageScripts, detectPackageManager, installDiffci } from "./install.js";
38
39
  import { hookCommand, installPrePushHook } from "./hook.js";
39
40
  import { submitObservation } from "./submit.js";
41
+ import { configureGraphCache } from "./shared-graph-cache.js";
42
+ import { GraphCache } from "@diffci.com/core/cache/graph-cache";
40
43
  import { githubDeliveryWarning } from "./delivery-warning.js";
41
44
  import { configureTelemetry, readTelemetryPreference, recordUsage } from "./telemetry.js";
42
45
  import { formatFeedbackPrompt, markFeedbackPromptShown, shouldShowFeedbackPrompt } from "./feedback-prompt.js";
@@ -44,7 +47,7 @@ import { detectSpecificationConflicts, readSpecificationFile } from "./spec-conf
44
47
  import { formatVerificationSummary, verificationExitCode, verifyChanged, verifyRange } from "./verify.js";
45
48
  import { formatGateSummary, gateExitCode, planGate, runGate } from "./gate.js";
46
49
  import { formatGrowthPrompt, formatVerifySavingsSummary, measureCommand, runVerifySavings, writeVerifySavingsReport } from "./verify-savings.js";
47
- import { auditWorkflows, isNonInterfering } from "./workflow-guard.js";
50
+ import { auditEnforceWorkflows, auditWorkflows, isNonInterfering } from "./workflow-guard.js";
48
51
  import { renderPilotPacket } from "./pilot-packet.js";
49
52
  import { observerIdentity } from "./package-identity.js";
50
53
  import { buildPilotWorkflow, diffciVerificationWorkflow, diffciWorkflow } from "./workflow-templates.js";
@@ -625,7 +628,24 @@ async function runObserve(flags, env) {
625
628
  console.warn("DiffCI timing history is unreadable; performing normal analysis.");
626
629
  }
627
630
  }
631
+ // Opt-in graph cache: local with --graph-cache-dir, plus DiffCI Cloud with --shared-graph-cache.
632
+ const graphCacheConfig = configureGraphCache({
633
+ repoPath,
634
+ version: identity.version,
635
+ localDir: typeof flags["graph-cache-dir"] === "string" ? resolve(flags["graph-cache-dir"]) : env.DIFFCI_GRAPH_CACHE_DIR ? resolve(env.DIFFCI_GRAPH_CACHE_DIR) : undefined,
636
+ shared: flags["shared-graph-cache"] === true || env.DIFFCI_SHARED_GRAPH_CACHE === "1",
637
+ cacheUrl: typeof flags["graph-cache-url"] === "string" ? flags["graph-cache-url"] : env.DIFFCI_GRAPH_CACHE_URL,
638
+ apiUrl: typeof flags["api-url"] === "string" ? flags["api-url"] : env.DIFFCI_API_URL,
639
+ token: typeof flags["api-token"] === "string" ? flags["api-token"] : env.DIFFCI_TOKEN,
640
+ secret: env.DIFFCI_GRAPH_CACHE_SECRET,
641
+ noSend: flags["no-send"] === true || env.DIFFCI_NO_SEND === "1",
642
+ redactPaths: flags["redact-paths"] === true,
643
+ defaultLocalRoot: env.RUNNER_TEMP ?? tmpdir(),
644
+ local: (dir) => new GraphCache({ cacheDir: dir }),
645
+ isInsideRepository,
646
+ });
628
647
  const report = await observe({
648
+ graphCache: graphCacheConfig.cache,
629
649
  repoPath,
630
650
  env: env,
631
651
  version: identity.version,
@@ -638,6 +658,7 @@ async function runObserve(flags, env) {
638
658
  economicsJobKey: typeof flags["economics-job"] === "string" ? flags["economics-job"] : undefined,
639
659
  forceAnalysis: flags["force-analysis"] === true,
640
660
  vueAnalysisCacheDir: typeof flags["vue-analysis-cache"] === "string" ? flags["vue-analysis-cache"] : undefined,
661
+ agent: resolveObservationAgent(flags.agent, env),
641
662
  });
642
663
  mkdirSync(dirname(reportPath), { recursive: true });
643
664
  writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");
@@ -650,6 +671,15 @@ async function runObserve(flags, env) {
650
671
  console.log(summary);
651
672
  console.log(` report: ${reportPath}`);
652
673
  }
674
+ if (graphCacheConfig.cache || graphCacheConfig.notes.length) {
675
+ await graphCacheConfig.cache?.flush();
676
+ if (flags.quiet !== true && flags.json !== true) {
677
+ for (const note of graphCacheConfig.notes)
678
+ console.log(` graph cache: ${note}`);
679
+ if (graphCacheConfig.cache?.lastOutcome)
680
+ console.log(` graph cache: ${graphCacheConfig.cache.lastOutcome}`);
681
+ }
682
+ }
653
683
  // Sending happens before the job summary is written, so the summary can say whether it worked.
654
684
  // It is allowed to fail: by this point the report is on disk and (in the action) about to become an
655
685
  // artifact, so a delivery problem costs the observation nothing - it is DiffCI's problem to fix, not
@@ -723,6 +753,33 @@ function runVerifyWorkflow(flags, env) {
723
753
  console.log("\nBlocking findings above: as written, this installation CAN change what the rest of CI does.");
724
754
  return 1;
725
755
  }
756
+ /**
757
+ * `verify-workflow --enforce` (docs/enforce-mode-01-plan.md, step 4). The observer audit cannot apply:
758
+ * an enforcing job is meant to change CI. This checks the opposite - that the gate is real, that its
759
+ * kill switch is the repository variable, and that the full suite still runs on every push to main.
760
+ */
761
+ function runVerifyEnforceWorkflow(flags, env) {
762
+ const repoPath = resolve(stringFlag(flags, "repo") ?? env.GITHUB_WORKSPACE ?? process.cwd());
763
+ const result = auditEnforceWorkflows(repoPath, {
764
+ defaultBranch: stringFlag(flags, "default-branch"),
765
+ fullCommand: stringFlag(flags, "full-command"),
766
+ });
767
+ if (result.workflowsScanned.length === 0) {
768
+ console.log(`No workflow files found under ${join(repoPath, ".github", "workflows")}. Nothing was checked.`);
769
+ return 1;
770
+ }
771
+ console.log(`Scanned ${result.workflowsScanned.length} workflow file(s).`);
772
+ console.log(`Enforcing job(s): ${result.enforceJobs.length ? result.enforceJobs.join(", ") : "none"}`);
773
+ console.log(`Full suite (${result.fullCommand ?? "unknown"}) on every push: ${result.fullSuiteJobs.length ? result.fullSuiteJobs.join(", ") : "none"}`);
774
+ for (const finding of result.findings)
775
+ console.log(formatFinding(finding));
776
+ if (isNonInterfering(result)) {
777
+ console.log("\nNo blocking findings. Enforcement is gated by DIFFCI_ENFORCE and the full suite still runs on push.");
778
+ return 0;
779
+ }
780
+ console.log("\nBlocking findings above: as written, enforce mode could skip tests with nothing checking the skips.");
781
+ return 1;
782
+ }
726
783
  /**
727
784
  * Miss detection (docs/enforce-mode-01-plan.md, step 5). Exit 0: no miss. Exit 1: at least one miss.
728
785
  * Exit 2: the full run left no results to classify, or the invocation is wrong. It never edits
@@ -1017,7 +1074,8 @@ Usage:
1017
1074
  [--label <name>] [--repository-url <https-url>] [--redact-paths]
1018
1075
  diffci observe [--repo <path>] [--out <file>] [--base <sha> --head <sha>]
1019
1076
  [--redact-paths] [--json] [--quiet] [--fail-on-error]
1020
- [--api-url <url> --api-token <token>] [--no-send] [--share-usage]
1077
+ [--api-url <url> --api-token <token>] [--no-send] [--share-usage] [--agent <name|auto>]
1078
+ [--graph-cache-dir <dir>] [--shared-graph-cache [--graph-cache-url <url>]]
1021
1079
  diffci verify-savings --repo <path> --full <command>
1022
1080
  (--selected <command> | --selected-from-report <file>)
1023
1081
  --out <file> [--markdown <file>] [--label <name>]
@@ -1025,6 +1083,7 @@ Usage:
1025
1083
  [--cache-prepare <command>] [--fixed-order]
1026
1084
  diffci validate-specs --file <json> [--json]
1027
1085
  diffci verify-workflow [--repo <path>]
1086
+ diffci verify-workflow --enforce [--repo <path>] [--default-branch main] [--full-command "<cmd>"]
1028
1087
  diffci gate [--base <sha> --head <sha>] [--tests <command>] [--script <name,...>] [--measure-selected]
1029
1088
  [--only checks|tests] [--plan <file> [--expect-head <sha>]] [--repo <path>] [--out <file>]
1030
1089
  [--json] [--timeout-ms <ms>]
@@ -1055,6 +1114,8 @@ observe analyses the checkout and writes one JSON report. It runs nothing and ch
1055
1114
  verify-savings runs both commands and reports measured paired runtime; it is an opt-in pilot command.
1056
1115
  validate-specs checks an explicit list of specification IDs and logical targets and blocks duplicates.
1057
1116
  verify-workflow checks that the job running DiffCI cannot affect any other job, and exits 1 if it can.
1117
+ With --enforce it instead checks that an enforcing job exists, is gated by vars.DIFFCI_ENFORCE, and
1118
+ that the full suite still runs on every push to the default branch; it exits 1 if any of that fails.
1058
1119
  gate replaces a build's gate script (for example "npm run check && npm test"). In observe mode, the only
1059
1120
  mode so far, it runs every gate check and the full test command (--tests, default the repository's test
1060
1121
  script) exactly as the build would and exits with their result. It records what DiffCI would have run,
@@ -1071,6 +1132,10 @@ Failures are re-run with the package.json tsx --test runner, or read from --reru
1071
1132
  The report is sent only when both --api-url and --api-token are given (or DIFFCI_API_URL and
1072
1133
  DIFFCI_TOKEN are set). A failed send is reported and never fails the step - the report is on disk
1073
1134
  either way. Plain http is refused; the token is never printed.
1135
+ --graph-cache-dir (or DIFFCI_GRAPH_CACHE_DIR) reuses dependency graphs for clean checkouts from a local
1136
+ directory outside the checkout. --shared-graph-cache (or DIFFCI_SHARED_GRAPH_CACHE=1) also shares them via
1137
+ DiffCI Cloud (Team/Business) using the api-url and api-token; DIFFCI_GRAPH_CACHE_SECRET encrypts them
1138
+ client-side. Graphs hold paths and import edges, never file contents; a cache failure only means a local build.
1074
1139
  --share-usage (or DIFFCI_SHARE_USAGE=1) opts in to command, outcome, version, surface and activity reporting.
1075
1140
  diffci telemetry --mode anonymous saves consent; --mode installations also shares a random local installation ID.
1076
1141
  --mode off disables saved consent and deletes the ID. --internal-usage labels tests/internal activity.
@@ -1132,7 +1197,7 @@ async function main() {
1132
1197
  process.exitCode = runValidateSpecs(flags);
1133
1198
  return;
1134
1199
  case "verify-workflow":
1135
- process.exitCode = runVerifyWorkflow(flags, env);
1200
+ process.exitCode = flags.enforce === true ? runVerifyEnforceWorkflow(flags, env) : runVerifyWorkflow(flags, env);
1136
1201
  return;
1137
1202
  case "gate":
1138
1203
  process.exitCode = await runGateCommand(flags, env);
@@ -0,0 +1,26 @@
1
+ import { type CommandMeasurement } from "./verify-savings.js";
2
+ /**
3
+ * Selected-test commands too long for the shell (2026-10-21).
4
+ *
5
+ * WHY. A selection is one runner invocation listing every selected test file. Windows runs it through
6
+ * cmd.exe, whose command line stops at 8,191 characters: replaying a dogfood repository, every
7
+ * selection of 191 files failed in under a second with exit 255 before any test ran, which a receipt
8
+ * would report as a failed verification. Linux shells allow far more, so CI never saw it.
9
+ *
10
+ * WHAT. A command over the limit is split into several invocations of the same runner prefix, each
11
+ * listing a share of the files, run one after another and reported as one verification. Splitting only
12
+ * happens when the command ends in exactly the selected paths as plain tokens; anything else is left
13
+ * whole, because rewriting a command that is not understood could change what it runs.
14
+ */
15
+ export declare const COMMAND_LINE_LIMIT: number;
16
+ /** `command` split so each part fits `limit`, or `[command]` when it fits or cannot be split safely. */
17
+ export declare function batchCommand(command: string, paths: readonly string[], limit?: number): string[];
18
+ /**
19
+ * Runs `commands` in order as one verification. Every part runs, so one receipt carries every failing
20
+ * test; the first non-zero exit is the result, and the remaining time budget is shared between parts.
21
+ */
22
+ export declare function measureCommands(commands: readonly string[], options: {
23
+ cwd: string;
24
+ timeoutMs: number;
25
+ tailBytes: number;
26
+ }): CommandMeasurement;
@@ -1,3 +1,4 @@
1
+ import { commandArguments } from "./selected-coverage.js";
1
2
  import { measureCommand } from "./verify-savings.js";
2
3
  /**
3
4
  * Selected-test commands too long for the shell (2026-10-21).
@@ -19,8 +20,11 @@ export function batchCommand(command, paths, limit = COMMAND_LINE_LIMIT) {
19
20
  return [command];
20
21
  const tokens = command.split(" ");
21
22
  const selected = new Set(paths);
23
+ // A `node --test` path with brackets arrives quoted and class-escaped: "src/app/[[]id[]]/x.test.ts".
24
+ const isSelected = (token) => selected.has(token)
25
+ || selected.has((commandArguments(token)[0] ?? "").replace(/\[(.)\]/g, "$1"));
22
26
  let start = tokens.length;
23
- while (start > 0 && selected.has(tokens[start - 1]))
27
+ while (start > 0 && isSelected(tokens[start - 1]))
24
28
  start--;
25
29
  const trailing = tokens.slice(start);
26
30
  if (trailing.length === 0 || new Set(trailing).size !== trailing.length)
@@ -64,6 +68,7 @@ export function measureCommands(commands, options) {
64
68
  const failed = parts.find((part) => part.exitCode !== 0 || part.signal !== null || part.timedOut);
65
69
  const ranAll = parts.length === commands.length;
66
70
  const failingTests = [...new Set(parts.flatMap((part) => part.failingTests ?? []))].sort();
71
+ const counted = ranAll && parts.every((part) => part.runnerTestCount !== undefined);
67
72
  const tail = (key) => parts.map((part) => part[key]).join("").slice(-Math.max(options.tailBytes, 0) || undefined);
68
73
  return {
69
74
  command: commands.join(" && "),
@@ -76,5 +81,6 @@ export function measureCommands(commands, options) {
76
81
  stdoutTail: options.tailBytes > 0 ? tail("stdoutTail") : "",
77
82
  stderrTail: options.tailBytes > 0 ? tail("stderrTail") : "",
78
83
  ...(failingTests.length ? { failingTests } : {}),
84
+ ...(counted ? { runnerTestCount: parts.reduce((sum, part) => sum + part.runnerTestCount, 0) } : {}),
79
85
  };
80
86
  }
@@ -0,0 +1,47 @@
1
+ /** Injected so tests can drive this without a real repository. Returns stdout, or a failure. */
2
+ export type GitRunner = (args: string[]) => {
3
+ ok: true;
4
+ stdout: string;
5
+ } | {
6
+ ok: false;
7
+ error: string;
8
+ };
9
+ export interface ObservationEnvironment {
10
+ [key: string]: string | undefined;
11
+ }
12
+ export interface CiEnvironmentFacts {
13
+ provider: "github-actions" | "local" | "unknown";
14
+ ownerName?: string;
15
+ providerRepositoryId?: string;
16
+ defaultBranch?: string;
17
+ runId?: string;
18
+ runAttempt?: string;
19
+ workflow?: string;
20
+ job?: string;
21
+ event?: string;
22
+ ref?: string;
23
+ syntheticTrigger?: boolean;
24
+ }
25
+ export declare function readEventPayload(env: ObservationEnvironment): Record<string, unknown> | undefined;
26
+ export declare function readCiEnvironment(env: ObservationEnvironment): CiEnvironmentFacts;
27
+ export interface ResolvedCommitRange {
28
+ baseSha: string;
29
+ headSha: string;
30
+ source: "explicit-flags" | "pull-request-event" | "push-event" | "head-parent";
31
+ mergeBaseSha?: string;
32
+ }
33
+ export type CommitRangeResolution = {
34
+ ok: true;
35
+ range: ResolvedCommitRange;
36
+ } | {
37
+ ok: false;
38
+ reason: string;
39
+ };
40
+ export interface ResolveCommitRangeOptions {
41
+ env: ObservationEnvironment;
42
+ git: GitRunner;
43
+ /** --base / --head. When either is given, both must be, and neither is second-guessed. */
44
+ baseOverride?: string;
45
+ headOverride?: string;
46
+ }
47
+ export declare function resolveCommitRange(options: ResolveCommitRangeOptions): CommitRangeResolution;
@@ -0,0 +1 @@
1
+ export declare function githubDeliveryWarning(delivery: string, env: NodeJS.ProcessEnv): string | undefined;
@@ -0,0 +1,17 @@
1
+ export { economicsContext } from "@diffci.com/core/cache/economics-context";
2
+ export interface EconomicsDecision {
3
+ decision: "ANALYZE" | "BYPASS_FULL";
4
+ reason: string;
5
+ contextKey: string;
6
+ sampleCount?: number;
7
+ maximumGrossSavedMs?: number;
8
+ minimumObserverMs?: number;
9
+ }
10
+ /** Economics may decline analysis; it never approves a selection or removes tests. */
11
+ export declare function evaluateEconomics(raw: unknown, context: {
12
+ repository?: string;
13
+ jobKey?: string;
14
+ contextKey: string;
15
+ observerVersion: string;
16
+ now?: number;
17
+ }): EconomicsDecision;
@@ -0,0 +1,49 @@
1
+ import { type MergedPullRequest, type TestOutcome, type WindowSource } from "./enforce-misses.js";
2
+ export declare const DRY_RUN_ARTIFACT_PREFIX = "diffci-enforce-dry-run-";
3
+ export declare const MISS_RECORD_ARTIFACT_PREFIX = "diffci-enforce-misses-";
4
+ export declare const MISS_REPORT_FILE = "enforce-misses.json";
5
+ export interface RunResult {
6
+ ok: boolean;
7
+ stdout: string;
8
+ stderr: string;
9
+ }
10
+ export type CommandRunner = (executable: string, args: string[], options?: {
11
+ cwd?: string;
12
+ }) => RunResult;
13
+ export declare const spawnRunner: CommandRunner;
14
+ export interface CollectOptions {
15
+ repoPath: string;
16
+ /** owner/name */
17
+ repository: string;
18
+ headSha: string;
19
+ /** This run's id, skipped when looking for an earlier detector record. */
20
+ runId?: string;
21
+ /** Scratch directory for downloaded artifacts; outside the checkout. */
22
+ workDir: string;
23
+ run: CommandRunner;
24
+ detectorWorkflow?: string;
25
+ fullSuiteWorkflow?: string;
26
+ dryRunWorkflow?: string;
27
+ /** Upper bound on first-parent commits examined, so a long red streak cannot fan out without limit. */
28
+ maxCommits?: number;
29
+ }
30
+ export interface WindowStart {
31
+ fromSha: string | null;
32
+ source: WindowSource;
33
+ baseline: string[];
34
+ }
35
+ export declare function findWindowStart(options: CollectOptions): WindowStart;
36
+ /** Pull requests merged into `main` by the first-parent commits after `fromSha`, oldest first. */
37
+ export declare function mergedPullRequests(options: CollectOptions, fromSha: string | null): MergedPullRequest[];
38
+ /** The newest dry-run receipt recorded for the pull request's final head commit. */
39
+ export declare function findReceipt(options: CollectOptions, pr: MergedPullRequest): MergedPullRequest["receipt"];
40
+ /**
41
+ * Node arguments that re-run test files the way package.json's `tsx --test` script runs them: tsx's own
42
+ * CLI under this Node, so no shell and no `.cmd` shim is involved and test paths stay literal argv.
43
+ */
44
+ export declare function inferRerunArgs(repoPath: string): string[] | undefined;
45
+ /**
46
+ * Re-run only the failing files with node:test's JUnit reporter, set through NODE_OPTIONS so the runner
47
+ * arguments stay what package.json declares. Returns undefined when no result file was written.
48
+ */
49
+ export declare function rerunFailingFiles(repoPath: string, runnerArgs: readonly string[], files: readonly string[]): TestOutcome[] | undefined;
@@ -0,0 +1,124 @@
1
+ import type { VerificationReport } from "./verify.js";
2
+ export declare const MISS_REPORT_SCHEMA: "diffci.enforce-misses.v1";
3
+ export interface TestOutcome {
4
+ /** `file > suite > name`: stable across runs of the same commit, so it can be matched between them. */
5
+ id: string;
6
+ /** Repository-relative, forward slashes. Empty when the reporter gave no file. */
7
+ file: string;
8
+ name: string;
9
+ failed: boolean;
10
+ skipped: boolean;
11
+ }
12
+ /** The receipt fields the detector reads; older receipts may lack `selected_tests`. */
13
+ export type ReceiptFields = Pick<VerificationReport, "schema" | "selection" | "selected_tests" | "command" | "enforcement" | "commit_range">;
14
+ export interface PullRequestReceipt {
15
+ artifact: string;
16
+ report: ReceiptFields;
17
+ }
18
+ export interface MergedPullRequest {
19
+ number: number;
20
+ title?: string;
21
+ mergeSha: string;
22
+ headSha: string;
23
+ receipt?: PullRequestReceipt;
24
+ }
25
+ /**
26
+ * What one merged pull request's receipt says about one failing test.
27
+ * - `missed`: the receipt selected tests and this test's file was not among them.
28
+ * - `selection-unrecorded`: the receipt selected tests but does not say which; counted as a miss,
29
+ * because "cannot tell" must not read as "was covered".
30
+ * - `selected` / `ran-full`: the pull request ran this test, so it did not skip it.
31
+ * - `no-tests-run`: a `none` receipt (blocked analysis). Enforce mode never passes such a run.
32
+ * - `no-receipt`: no dry-run artifact was found for the pull request's head.
33
+ */
34
+ export type PullRequestVerdict = "missed" | "selection-unrecorded" | "selected" | "ran-full" | "no-tests-run" | "no-receipt";
35
+ export type FailureClass =
36
+ /** Deterministic, new, and skipped by at least one `selected` pull request. Counts. */
37
+ "miss"
38
+ /** Passed when re-run. Logged, never counted. */
39
+ | "flaky"
40
+ /** Already failing at the start of the window, so no pull request in it introduced it. */
41
+ | "pre-existing"
42
+ /** Every pull request with a receipt ran it (selected it, or ran the full suite). */
43
+ | "covered"
44
+ /** No merged pull request with a receipt to hold it against (direct push, drift, environment). */
45
+ | "unattributed";
46
+ export interface ClassifiedFailure {
47
+ id: string;
48
+ file: string;
49
+ name: string;
50
+ classification: FailureClass;
51
+ pull_requests: {
52
+ number: number;
53
+ verdict: PullRequestVerdict;
54
+ artifact?: string;
55
+ }[];
56
+ detail: string;
57
+ }
58
+ export interface UnsafeMissEntry {
59
+ test: string;
60
+ pullRequest: number;
61
+ receipt: string | null;
62
+ mainSha: string;
63
+ detectedAt: string;
64
+ run?: string;
65
+ }
66
+ export type WindowSource = "detector-record" | "green-full-run" | "none";
67
+ export interface MissReport {
68
+ schema: typeof MISS_REPORT_SCHEMA;
69
+ produced_at: string;
70
+ head_sha: string;
71
+ run_url?: string;
72
+ full_suite: "passed" | "failed";
73
+ rerun: "done" | "not-run";
74
+ window: {
75
+ from_sha: string | null;
76
+ source: WindowSource;
77
+ };
78
+ pull_requests: {
79
+ number: number;
80
+ merge_sha: string;
81
+ head_sha: string;
82
+ receipt: string | null;
83
+ selection: ReceiptFields["selection"] | null;
84
+ }[];
85
+ /** Ids of the failures that were not flaky. The next run reads these as its pre-existing set. */
86
+ deterministic_failures: string[];
87
+ failures: ClassifiedFailure[];
88
+ misses: number;
89
+ open_unsafe_misses: UnsafeMissEntry[];
90
+ notes: string[];
91
+ }
92
+ /** Repository-relative with forward slashes; paths outside the repository stay absolute. */
93
+ export declare function normalizeTestPath(path: string, repoRoot: string): string;
94
+ /** Testcases in document order, named by their enclosing suites. Repeated ids are merged: any failure wins. */
95
+ export declare function parseJunit(xml: string, repoRoot: string): TestOutcome[];
96
+ /**
97
+ * The test files a `selected` receipt ran. Receipts from before `selected_tests` existed fall back to the
98
+ * test-file arguments of the command. `undefined` means the receipt does not say.
99
+ */
100
+ export declare function selectedFiles(report: ReceiptFields): Set<string> | undefined;
101
+ export interface ClassifyInput {
102
+ /** Every testcase of the full run on `main`; only failures are classified. */
103
+ fullRun: TestOutcome[];
104
+ /** The re-run of the failing files, or undefined when no re-run was possible. */
105
+ rerun: TestOutcome[] | undefined;
106
+ /** Ids already failing at the start of the window. */
107
+ baseline: readonly string[];
108
+ pullRequests: MergedPullRequest[];
109
+ }
110
+ export declare function classifyFailures(input: ClassifyInput): ClassifiedFailure[];
111
+ export declare function unsafeMissEntries(failures: readonly ClassifiedFailure[], context: {
112
+ headSha: string;
113
+ detectedAt: string;
114
+ runUrl?: string;
115
+ }): UnsafeMissEntry[];
116
+ export interface BuildReportInput extends ClassifyInput {
117
+ headSha: string;
118
+ producedAt: string;
119
+ runUrl?: string;
120
+ window: MissReport["window"];
121
+ notes?: string[];
122
+ }
123
+ export declare function buildMissReport(input: BuildReportInput): MissReport;
124
+ export declare function formatMissReportMarkdown(report: MissReport): string;
@@ -0,0 +1,33 @@
1
+ import { type GitRunner } from "./context.js";
2
+ import type { ObservationReport } from "./report.js";
3
+ /** The only policy shape this CLI understands. A newer or older `enforce` block falls back to FULL. */
4
+ export declare const ENFORCE_POLICY_VERSION = 1;
5
+ export declare const FORCE_FULL_LABEL = "diffci:force-full";
6
+ export declare const ENFORCE_VARIABLE = "DIFFCI_ENFORCE";
7
+ export type EnforcementFallback = "kill-switch" | "per-run-override" | "policy-not-approved" | "open-unsafe-miss" | "untrusted-range" | "analysis-failure" | "graph-confidence" | "global-risk" | "empty-selection";
8
+ export interface EnforcementContext {
9
+ /** Value of DIFFCI_ENFORCE. Anything but "on" keeps enforcement off. */
10
+ killSwitch: string | undefined;
11
+ pullRequestLabels: string[];
12
+ headCommitMessage: string | undefined;
13
+ /** The raw `enforce` block of diffci.config.json, read at the range BASE so a change cannot approve itself. */
14
+ policy: unknown;
15
+ range: {
16
+ trusted: true;
17
+ } | {
18
+ trusted: false;
19
+ reason: string;
20
+ };
21
+ pathsRedacted: boolean;
22
+ }
23
+ export interface EnforcementDecision {
24
+ policy: "enforce";
25
+ policy_version: typeof ENFORCE_POLICY_VERSION;
26
+ /** null when every check passed and the selected tests may replace the full suite. */
27
+ fired_fallback: EnforcementFallback | null;
28
+ detail: string;
29
+ }
30
+ /** Matches a `DiffCI: full` trailer line anywhere in the head commit message. */
31
+ export declare function hasForceFullTrailer(message: string | undefined): boolean;
32
+ export declare function evaluateEnforcement(context: EnforcementContext, observation: ObservationReport): EnforcementDecision;
33
+ export declare function collectEnforcementContext(runner: GitRunner, env: Record<string, string | undefined>, observation: ObservationReport): EnforcementContext;