@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,113 @@
1
+ import { type FailureBaseline } from "./failure-baseline.js";
2
+ import { type EnforcementDecision } from "./enforce-policy.js";
3
+ import { type CheckResult } from "./gate-checks.js";
4
+ import type { ObservationCommitRange, ObservationReport } from "./report.js";
5
+ import type { CommandMeasurement } from "./verify-savings.js";
6
+ import { type SnapshotChange } from "./working-tree.js";
7
+ export declare const VERIFICATION_SCHEMA: "diffci.verification.v1";
8
+ export type VerificationStatus = "passed" | "failed" | "blocked";
9
+ export type VerificationScope = "working-tree" | "commit-range";
10
+ export interface VerificationReport {
11
+ schema: typeof VERIFICATION_SCHEMA;
12
+ schema_version: "1";
13
+ produced_at: string;
14
+ /** The DiffCI package that produced the receipt, so cohorts can be split by selector version. */
15
+ diffci_version?: string;
16
+ scope: VerificationScope;
17
+ verification: VerificationStatus;
18
+ safe_to_continue: boolean;
19
+ reason: string;
20
+ changed_files: number;
21
+ tests_available: number;
22
+ tests_selected: number;
23
+ /** Affected tests the full test command does not run; executed after the selection (2026-10-21). */
24
+ tests_outside_full_suite?: number;
25
+ selection: "none" | "selected" | "full";
26
+ /** The test files the selected command ran, when `selection` is "selected". The miss detector reads it. */
27
+ selected_tests?: string[];
28
+ command?: string;
29
+ /** The parts `command` was run as, when one invocation would exceed the shell's command-line limit. */
30
+ commands?: string[];
31
+ execution?: CommandMeasurement;
32
+ /** The rest of the repository's gate (lint, typecheck, check scripts), run before the tests. When one
33
+ * fails, the tests do not run and `execution` is that check's run (2026-10-29). */
34
+ checks?: CheckResult[];
35
+ commit_range?: {
36
+ base_sha: string;
37
+ head_sha: string;
38
+ source: ObservationCommitRange["source"];
39
+ merge_base_sha?: string;
40
+ };
41
+ snapshot: {
42
+ base_sha: string;
43
+ before_tree_sha: string;
44
+ after_base_sha?: string;
45
+ after_tree_sha?: string;
46
+ /** The verified files were not changed. New files the run wrote (`written_during_verification`) don't count. */
47
+ unchanged: boolean;
48
+ /** New, non-ignored files that appeared during the checks and tests, at most 20. */
49
+ written_during_verification?: string[];
50
+ /** Files that existed before the run and changed during it, at most 20. Their presence blocks the verdict. */
51
+ changed_during_verification?: SnapshotChange[];
52
+ };
53
+ analysis: {
54
+ status: "not_needed" | ObservationReport["status"];
55
+ stage?: ObservationReport["stage"];
56
+ mode?: ObservationReport["result"] extends infer T ? (T extends {
57
+ mode: infer M;
58
+ } ? M : never) : never;
59
+ fallback_reasons: string[];
60
+ error?: string;
61
+ /** Wall time of the analysis that chose the verification command. */
62
+ duration_ms?: number;
63
+ /** The graph's own confidence and the confidence after narrowing to this change. */
64
+ graph_confidence?: string;
65
+ effective_graph_confidence?: string;
66
+ };
67
+ required_actions: string[];
68
+ /** Present when a failed verification was rerun at the base commit (`--baseline-on-failure`). */
69
+ failure_baseline?: FailureBaseline;
70
+ /** Present only under `--policy enforce`. `applied` is true when the selected tests replaced the full suite. */
71
+ enforcement?: EnforcementDecision & {
72
+ applied: boolean;
73
+ };
74
+ }
75
+ interface VerifyOptions {
76
+ repoPath: string;
77
+ env: Record<string, string | undefined>;
78
+ version: string;
79
+ engineSha?: string;
80
+ timeoutMs: number;
81
+ tailBytes: number;
82
+ redactPaths?: boolean;
83
+ /** Rerun a failed verification at the base commit to tell new failures from existing ones. */
84
+ baselineOnFailure?: boolean;
85
+ /** Run only the tests, not the gate's other checks (`--no-checks`). */
86
+ skipChecks?: boolean;
87
+ }
88
+ export interface VerifyChangedOptions extends VerifyOptions {
89
+ }
90
+ export interface VerifyRangeOptions extends VerifyOptions {
91
+ baseOverride?: string;
92
+ headOverride?: string;
93
+ /** Opt-in enforce mode (docs/enforce-mode-01-plan.md). Absent means today's behaviour, unchanged. */
94
+ policy?: "enforce";
95
+ }
96
+ /** Verify exactly the staged, unstaged, and non-ignored untracked content currently on disk. */
97
+ export declare function verifyChanged(options: VerifyChangedOptions): Promise<VerificationReport>;
98
+ /** Verify a real commit range and bind the receipt to the clean commit that was actually executed. */
99
+ export declare function verifyRange(options: VerifyRangeOptions): Promise<VerificationReport>;
100
+ export declare function verificationExitCode(report: VerificationReport): number;
101
+ export declare function formatVerificationSummary(report: VerificationReport): string;
102
+ /** Shared executable plan for read-only agent selection and verification. */
103
+ export declare function executableSelection(repoPath: string, result: NonNullable<ObservationReport["result"]>): {
104
+ selection: "full" | "selected";
105
+ command: string | undefined;
106
+ commands: string[];
107
+ reason: string;
108
+ outsideSuite: number;
109
+ };
110
+ /** A test-script phase as a standalone command. `npm test` puts `node_modules/.bin` on PATH; outside
111
+ * it a repository-local runner such as tsx is reached the way selected TypeScript tests are. */
112
+ export declare function phaseCommand(phase: string): string;
113
+ export {};
@@ -2,11 +2,12 @@ import { mkdtempSync, rmSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join, resolve } from "node:path";
4
4
  import { batchCommand, measureCommands } from "./command-batches.js";
5
- import { compareWithBaseline } from "./failure-baseline.js";
5
+ import { checkAtBaseline, compareWithBaseline } from "./failure-baseline.js";
6
6
  import { collectEnforcementContext, evaluateEnforcement } from "./enforce-policy.js";
7
7
  import { inferFullCommand, inferSelectedCommand } from "./full-command.js";
8
8
  import { plannedChecks, runChecks } from "./gate-checks.js";
9
9
  import { makeGitRunner, observe } from "./observe.js";
10
+ import { unmatchedNodeTests } from "./selected-coverage.js";
10
11
  import { captureWorkingTreeSnapshot, snapshotChanges } from "./working-tree.js";
11
12
  export const VERIFICATION_SCHEMA = "diffci.verification.v1";
12
13
  function receiptRange(range) {
@@ -116,9 +117,18 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
116
117
  const checkBase = scope === "commit-range" ? range?.baseSha : before.baseSha;
117
118
  const checkHead = scope === "commit-range" ? range?.headSha : before.commitSha;
118
119
  const planned = options.skipChecks ? [] : plannedChecks(options.repoPath, checkBase && checkHead ? { baseSha: checkBase, headSha: checkHead } : undefined);
119
- const checkRun = options.skipChecks ? undefined : runChecks(planned, { cwd: options.repoPath, timeoutMs: options.timeoutMs, tailBytes: options.tailBytes });
120
+ const checkBaseline = options.baselineOnFailure && checkBase && checkHead
121
+ ? (check, remainingMs) => checkAtBaseline({ repoPath: options.repoPath, baseSha: checkBase, headSha: checkHead, command: check.command, timeoutMs: Math.max(remainingMs, 0) })
122
+ : undefined;
123
+ const checkRun = options.skipChecks ? undefined : runChecks(planned, { cwd: options.repoPath, timeoutMs: options.timeoutMs, tailBytes: options.tailBytes, baseline: checkBaseline });
120
124
  const checks = checkRun?.results.length ? checkRun.results : undefined;
121
125
  const failedCheck = checkRun?.failure?.check;
126
+ // Checks that also fail at the base: still a failed verdict (required CI fails either way), but they
127
+ // no longer stop the run before the change's own failures.
128
+ const preexistingChecks = checkRun?.preexisting ?? [];
129
+ const preexistingNote = preexistingChecks.length
130
+ ? `; gate check(s) ${preexistingChecks.map((check) => check.id).join(", ")} also fail at the base commit (already broken before this change)`
131
+ : "";
122
132
  const execution = checkRun?.failure
123
133
  ? checkRun.failure.measurement
124
134
  : measureCommands(commands, { cwd: options.repoPath, timeoutMs: Math.max(options.timeoutMs - (checkRun?.wallMs ?? 0), 0), tailBytes: options.tailBytes });
@@ -152,19 +162,28 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
152
162
  const written = changes.filter((change) => change.status === "added").map((change) => change.path);
153
163
  const altered = changes.filter((change) => change.status !== "added");
154
164
  const unchanged = before.baseSha === after.baseSha && altered.length === 0;
155
- const succeeded = !failedCheck && execution.exitCode === 0 && !execution.timedOut;
156
- const verification = !unchanged ? "blocked" : succeeded ? "passed" : "failed";
165
+ const testsPassed = !failedCheck && execution.exitCode === 0 && !execution.timedOut;
166
+ const succeeded = testsPassed && preexistingChecks.length === 0;
167
+ // Every selected file contributes at least one test (node:test) or test file (vitest, jest) to the
168
+ // runner's summary; a smaller count means some selected tests never ran, which is not a pass.
169
+ const selectedCount = selection === "selected" && result ? result.selectedTests.length : 0;
170
+ const unexecuted = succeeded && execution.runnerTestCount !== undefined && execution.runnerTestCount < selectedCount;
171
+ const verification = !unchanged || unexecuted ? "blocked" : succeeded ? "passed" : "failed";
157
172
  const finalReason = !unchanged
158
173
  ? before.baseSha !== after.baseSha
159
174
  ? "HEAD moved while verification was running; rerun DiffCI for the new snapshot"
160
175
  : `the working tree changed while verification was running (${altered.slice(0, 5).map((change) => `${change.status} ${change.path}`).join(", ")}${altered.length > 5 ? `, ${altered.length - 5} more` : ""}); rerun DiffCI for the new snapshot`
161
- : succeeded
162
- ? checks ? `${reason}; ${checkSummary(checks)}` : reason
163
- : failedCheck
164
- ? `gate check ${failedCheck.id} ${failedCheck.status === "timed_out" ? "timed out" : `failed with exit code ${String(failedCheck.exit_code)}`}; tests were not run (${failedCheck.command})`
165
- : execution.timedOut
166
- ? `verification timed out after ${options.timeoutMs}ms`
167
- : `verification command failed with exit code ${String(execution.exitCode)}`;
176
+ : unexecuted
177
+ ? `the runner reported ${String(execution.runnerTestCount)} test(s) for ${selectedCount} selected test file(s), so some selected tests did not run; run the full test command instead`
178
+ : succeeded
179
+ ? checks ? `${reason}; ${checkSummary(checks)}` : reason
180
+ : failedCheck
181
+ ? `gate check ${failedCheck.id} ${failedCheck.status === "timed_out" ? "timed out" : `failed with exit code ${String(failedCheck.exit_code)}`}; tests were not run (${failedCheck.command})`
182
+ : execution.timedOut
183
+ ? `verification timed out after ${options.timeoutMs}ms${preexistingNote}`
184
+ : testsPassed
185
+ ? `${preexistingChecks.length} gate check(s) failed that also fail at the base commit; nothing this change introduced failed (${preexistingChecks.map((check) => check.id).join(", ")})`
186
+ : `verification command failed with exit code ${String(execution.exitCode)}${preexistingNote}`;
168
187
  const baselineSha = scope === "commit-range" ? range?.baseSha : before.baseSha;
169
188
  const failureBaseline = verification === "failed" && !failedCheck && !execution.timedOut && options.baselineOnFailure && baselineSha
170
189
  ? compareWithBaseline({ repoPath: options.repoPath, baseSha: baselineSha, headSha: scope === "commit-range" ? before.baseSha : before.commitSha, commands, headFailures: execution.failingTests ?? [], timeoutMs: options.timeoutMs })
@@ -321,7 +340,7 @@ export function formatVerificationSummary(report) {
321
340
  if (written?.length)
322
341
  lines.push(` written by the run (not in .gitignore): ${written.slice(0, 5).join(", ")}${written.length > 5 ? ", ..." : ""}`);
323
342
  if (report.checks)
324
- lines.push(` checks: ${report.checks.map((check) => `${check.id} ${check.status}`).join(", ")}`);
343
+ lines.push(` checks: ${report.checks.map((check) => `${check.id} ${check.status}${check.baseline?.status === "preexisting" ? " (also fails at base)" : ""}`).join(", ")}`);
325
344
  if (report.command)
326
345
  lines.push(` command: ${report.command}`);
327
346
  // A blocked push has to say what broke, not only that something did (2026-10-30 demo rehearsal: the
@@ -354,7 +373,12 @@ export function executableSelection(repoPath, result) {
354
373
  let reason;
355
374
  let primaryPhases = [];
356
375
  if (result.mode === "SELECTIVE" && !result.commandRefusalReason && result.proposedCommands.length === 1) {
357
- const selected = inferSelectedCommand(repoPath, result.proposedCommands[0], result.selectedTests);
376
+ const inferred = inferSelectedCommand(repoPath, result.proposedCommands[0], result.selectedTests);
377
+ // A selected file the runner's glob would not match never runs, and the rest still pass (2026-11-01).
378
+ const unmatched = inferred.command ? unmatchedNodeTests(inferred.command, result.selectedTests) : [];
379
+ const selected = unmatched.length
380
+ ? { reason: `node --test would not match ${unmatched.length} selected test file(s), such as ${unmatched[0]}` }
381
+ : inferred;
358
382
  const phases = result.testPhases ?? [];
359
383
  if (selected.command && phases.length) {
360
384
  // The selection covers some changed files only through these test-script phases, so they run
@@ -0,0 +1,59 @@
1
+ import type { WorkflowFinding } from "./report.js";
2
+ export interface WorkflowGuardOptions {
3
+ /**
4
+ * How a step is recognised as the DiffCI action. Defaults to any `uses:` mentioning "diffci",
5
+ * which covers `DiffCI/core@sha`, a local `./.github/actions/diffci`, and a future npm-published
6
+ * action alike.
7
+ */
8
+ actionPattern?: RegExp;
9
+ }
10
+ export interface WorkflowGuardResult {
11
+ /** "<workflow file>#<job id>" for every job that runs the DiffCI action. */
12
+ observerJobs: string[];
13
+ findings: WorkflowFinding[];
14
+ /** Workflow files that were read. Zero means nothing was checked, which is not a pass. */
15
+ workflowsScanned: string[];
16
+ }
17
+ export declare function auditWorkflows(repoPath: string, options?: WorkflowGuardOptions): WorkflowGuardResult;
18
+ /**
19
+ * Enforce mode audit (docs/enforce-mode-01-plan.md, step 4).
20
+ *
21
+ * The non-interference audit above proves an observer cannot change CI. Enforce mode deliberately does
22
+ * change it - pull requests stop running the full suite - so it needs the opposite guarantees:
23
+ *
24
+ * 1. There is an enforcing job, and it is a real gate (not continue-on-error, nothing like the dry run).
25
+ * 2. Its kill switch is wired to the repository variable. A hardcoded "on" would mean flipping the
26
+ * variable no longer stops enforcement, and the plan's main rollback silently stops working.
27
+ * 3. The full suite still runs on every push to main. That run is the safety net and the ground truth
28
+ * the miss detector reads; an installation without it skips tests with nothing checking the skips.
29
+ *
30
+ * "Cannot tell" is a finding, never a pass: an `if:` this module cannot evaluate, or a full command it
31
+ * cannot infer, is BLOCKING, because the whole point of the audit is to prove (3) rather than assume it.
32
+ */
33
+ export interface EnforceAuditOptions {
34
+ /** The branch whose pushes must run the full suite. */
35
+ defaultBranch?: string;
36
+ /** Overrides the full command inferred from the repository (`npm test` and its equivalents). */
37
+ fullCommand?: string;
38
+ }
39
+ export interface EnforceAuditResult {
40
+ /** "<workflow file>#<job id>" for every job that enforces (runs `verify --policy enforce` as a gate). */
41
+ enforceJobs: string[];
42
+ /** "<workflow file>#<job id>" for every job that runs the full suite on push to the default branch. */
43
+ fullSuiteJobs: string[];
44
+ /** The command recognised as the full suite, or undefined when none could be inferred. */
45
+ fullCommand?: string;
46
+ findings: WorkflowFinding[];
47
+ workflowsScanned: string[];
48
+ }
49
+ type Truth = "TRUE" | "FALSE" | "UNKNOWN";
50
+ /**
51
+ * Evaluates an `if:` for a push to `branch` with Kleene logic. `vars.*`, `inputs.*` and anything else
52
+ * not fixed by "this is a push to the default branch" are UNKNOWN, so a condition only counts as TRUE
53
+ * when it holds whatever those are. Unsupported syntax is UNKNOWN as well, never FALSE or TRUE.
54
+ */
55
+ export declare function evaluatePushCondition(expression: string, branch: string): Truth;
56
+ export declare function auditEnforceWorkflows(repoPath: string, options?: EnforceAuditOptions): EnforceAuditResult;
57
+ /** True when nothing found would let the observation change what the rest of CI does. */
58
+ export declare function isNonInterfering(result: Pick<WorkflowGuardResult, "findings">): boolean;
59
+ export {};
@@ -27,6 +27,7 @@
27
27
  import { existsSync, readdirSync, readFileSync } from "node:fs";
28
28
  import { join } from "node:path";
29
29
  import YAML from "yaml";
30
+ import { inferFullCommand } from "./full-command.js";
30
31
  /** Steps a dedicated observation job may legitimately contain besides the DiffCI action itself. */
31
32
  const ALLOWED_STEP_ACTIONS = [
32
33
  "actions/checkout",
@@ -307,6 +308,258 @@ export function auditWorkflows(repoPath, options = {}) {
307
308
  }
308
309
  return { observerJobs, findings, workflowsScanned };
309
310
  }
311
+ /** Where repository-wide findings (no single workflow to blame) point. */
312
+ const WORKFLOWS_DIR = join(".github", "workflows");
313
+ const ENFORCE_VARIABLE_EXPRESSION = /^\$\{\{\s*vars\.DIFFCI_ENFORCE\s*\}\}$/;
314
+ function runInvokesEnforcePolicy(run) {
315
+ return runInvokesDiffCiVerification(run) && /--policy[=\s]+["']?enforce\b/.test(commandText(run));
316
+ }
317
+ /** `npm run test` and `npm test` are the same command; so are the pnpm/yarn/bun pairs. */
318
+ function normalizeTestCommand(command) {
319
+ return command.trim().replace(/\s+/g, " ").replace(/^(npm|pnpm|yarn|bun) run test$/, "$1 test");
320
+ }
321
+ function runInvokesFullCommand(run, fullCommand) {
322
+ const target = normalizeTestCommand(fullCommand);
323
+ return commandText(run).split("\n").some((line) => normalizeTestCommand(line) === target);
324
+ }
325
+ function globToRegExp(glob) {
326
+ const pattern = glob
327
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
328
+ .replace(/\*\*/g, "\u0000")
329
+ .replace(/\*/g, "[^/]*")
330
+ .replace(/\?/g, "[^/]")
331
+ .replace(/\u0000/g, ".*");
332
+ return new RegExp(`^${pattern}$`);
333
+ }
334
+ /**
335
+ * Does this workflow run on every push to `branch`? A `paths` or `paths-ignore` filter means some pushes
336
+ * do not trigger it, and those are exactly the pushes nothing would check, so it does not count.
337
+ */
338
+ function triggersOnEveryPush(on, branch) {
339
+ if (on === "push")
340
+ return { ok: true };
341
+ if (Array.isArray(on))
342
+ return { ok: on.includes("push") };
343
+ if (!isRecord(on) || !("push" in on))
344
+ return { ok: false };
345
+ const push = on.push;
346
+ if (push === null || push === undefined)
347
+ return { ok: true };
348
+ if (!isRecord(push))
349
+ return { ok: false };
350
+ if (push.paths !== undefined || push["paths-ignore"] !== undefined) {
351
+ return { ok: false, reason: "its push trigger has a paths filter, so some pushes do not run it" };
352
+ }
353
+ const branches = asArray(push.branches).filter((value) => typeof value === "string");
354
+ const ignored = asArray(push["branches-ignore"]).filter((value) => typeof value === "string");
355
+ if (ignored.some((glob) => globToRegExp(glob).test(branch)))
356
+ return { ok: false };
357
+ if (push.branches === undefined) {
358
+ // `tags:` alone restricts push to tags; branches are then not covered.
359
+ return { ok: push.tags === undefined && push["tags-ignore"] === undefined };
360
+ }
361
+ let included = false;
362
+ for (const glob of branches) {
363
+ if (glob.startsWith("!")) {
364
+ if (globToRegExp(glob.slice(1)).test(branch))
365
+ included = false;
366
+ }
367
+ else if (globToRegExp(glob).test(branch)) {
368
+ included = true;
369
+ }
370
+ }
371
+ return { ok: included };
372
+ }
373
+ /**
374
+ * Evaluates an `if:` for a push to `branch` with Kleene logic. `vars.*`, `inputs.*` and anything else
375
+ * not fixed by "this is a push to the default branch" are UNKNOWN, so a condition only counts as TRUE
376
+ * when it holds whatever those are. Unsupported syntax is UNKNOWN as well, never FALSE or TRUE.
377
+ */
378
+ export function evaluatePushCondition(expression, branch) {
379
+ const source = expression.trim().replace(/^\$\{\{\s*|\s*\}\}$/g, "").trim();
380
+ const known = {
381
+ "github.event_name": "push",
382
+ "github.ref": `refs/heads/${branch}`,
383
+ "github.ref_name": branch,
384
+ "github.ref_type": "branch",
385
+ };
386
+ const tokens = source.match(/'(?:[^']|'')*'|"[^"]*"|&&|\|\||==|!=|!|\(|\)|[A-Za-z_][\w.-]*\(\)|[A-Za-z_][\w.-]*/g);
387
+ if (!tokens || tokens.join("").replace(/\s/g, "") !== source.replace(/\s/g, ""))
388
+ return "UNKNOWN";
389
+ let index = 0;
390
+ const peek = () => tokens[index];
391
+ const truth = (value) => (!value.known ? "UNKNOWN" : value.value === false || value.value === "" ? "FALSE" : "TRUE");
392
+ const fromTruth = (value) => (value === "UNKNOWN" ? { known: false } : { known: true, value: value === "TRUE" });
393
+ const operand = () => {
394
+ const token = tokens[index++];
395
+ if (token === undefined)
396
+ return { known: false };
397
+ if (token === "(") {
398
+ const inner = or();
399
+ if (tokens[index++] !== ")")
400
+ return { known: false };
401
+ return fromTruth(inner);
402
+ }
403
+ if (token.startsWith("'"))
404
+ return { known: true, value: token.slice(1, -1).replace(/''/g, "'") };
405
+ if (token.startsWith('"'))
406
+ return { known: true, value: token.slice(1, -1) };
407
+ if (token === "true" || token === "false")
408
+ return { known: true, value: token === "true" };
409
+ if (token === "always()" || token === "success()")
410
+ return { known: true, value: true };
411
+ if (token === "failure()" || token === "cancelled()")
412
+ return { known: true, value: false };
413
+ if (token in known)
414
+ return { known: true, value: known[token] };
415
+ return { known: false };
416
+ };
417
+ const comparison = () => {
418
+ if (peek() === "!") {
419
+ index++;
420
+ const inner = comparison();
421
+ return inner === "UNKNOWN" ? "UNKNOWN" : inner === "TRUE" ? "FALSE" : "TRUE";
422
+ }
423
+ const left = operand();
424
+ const operator = peek();
425
+ if (operator !== "==" && operator !== "!=")
426
+ return truth(left);
427
+ index++;
428
+ const right = operand();
429
+ if (!left.known || !right.known)
430
+ return "UNKNOWN";
431
+ // GitHub compares strings case-insensitively.
432
+ const equal = String(left.value).toLowerCase() === String(right.value).toLowerCase();
433
+ return (operator === "==") === equal ? "TRUE" : "FALSE";
434
+ };
435
+ const and = () => {
436
+ let result = comparison();
437
+ while (peek() === "&&") {
438
+ index++;
439
+ const next = comparison();
440
+ result = result === "FALSE" || next === "FALSE" ? "FALSE" : result === "UNKNOWN" || next === "UNKNOWN" ? "UNKNOWN" : "TRUE";
441
+ }
442
+ return result;
443
+ };
444
+ function or() {
445
+ let result = and();
446
+ while (peek() === "||") {
447
+ index++;
448
+ const next = and();
449
+ result = result === "TRUE" || next === "TRUE" ? "TRUE" : result === "UNKNOWN" || next === "UNKNOWN" ? "UNKNOWN" : "FALSE";
450
+ }
451
+ return result;
452
+ }
453
+ const result = or();
454
+ return index === tokens.length ? result : "UNKNOWN";
455
+ }
456
+ function conditionHolds(condition, branch) {
457
+ if (condition === undefined)
458
+ return "TRUE";
459
+ if (typeof condition === "boolean")
460
+ return condition ? "TRUE" : "FALSE";
461
+ if (typeof condition !== "string")
462
+ return "UNKNOWN";
463
+ return evaluatePushCondition(condition, branch);
464
+ }
465
+ export function auditEnforceWorkflows(repoPath, options = {}) {
466
+ const branch = options.defaultBranch ?? "main";
467
+ const findings = [];
468
+ const enforceJobs = [];
469
+ const fullSuiteJobs = [];
470
+ const workflowsScanned = [];
471
+ const unprovable = [];
472
+ const inferred = options.fullCommand ? { command: options.fullCommand, reason: "--full-command" } : inferFullCommand(repoPath);
473
+ const fullCommand = inferred.command;
474
+ if (!fullCommand) {
475
+ findings.push({
476
+ severity: "BLOCKING",
477
+ code: "FULL_COMMAND_UNKNOWN",
478
+ workflow: WORKFLOWS_DIR,
479
+ message: `could not infer the full test command (${inferred.reason}), so it cannot be shown that the full suite still runs on ${branch}. Pass --full-command.`,
480
+ });
481
+ }
482
+ for (const relativePath of listWorkflowFiles(repoPath)) {
483
+ let document;
484
+ try {
485
+ document = YAML.parse(readFileSync(join(repoPath, relativePath), "utf8"));
486
+ }
487
+ catch {
488
+ // The non-interference audit reports unparseable workflows; here they simply prove nothing.
489
+ continue;
490
+ }
491
+ workflowsScanned.push(relativePath);
492
+ if (!isRecord(document))
493
+ continue;
494
+ const jobs = isRecord(document.jobs) ? document.jobs : {};
495
+ const workflowEnv = isRecord(document.env) ? document.env : {};
496
+ const trigger = triggersOnEveryPush(document.on, branch);
497
+ for (const [jobId, rawJob] of Object.entries(jobs)) {
498
+ if (!isRecord(rawJob))
499
+ continue;
500
+ const steps = asArray(rawJob.steps).filter(isRecord);
501
+ const where = `${relativePath}#${jobId}`;
502
+ // 1 + 2. Enforcing jobs. A continue-on-error job is a dry run whatever it calls itself.
503
+ const enforceSteps = steps.filter((step) => typeof step.run === "string" && runInvokesEnforcePolicy(step.run));
504
+ if (enforceSteps.length > 0 && rawJob["continue-on-error"] !== true) {
505
+ enforceJobs.push(where);
506
+ const jobEnv = isRecord(rawJob.env) ? rawJob.env : {};
507
+ for (const step of enforceSteps) {
508
+ const stepEnv = isRecord(step.env) ? step.env : {};
509
+ const value = stepEnv.DIFFCI_ENFORCE ?? jobEnv.DIFFCI_ENFORCE ?? workflowEnv.DIFFCI_ENFORCE;
510
+ if (typeof value !== "string" || !ENFORCE_VARIABLE_EXPRESSION.test(value.trim())) {
511
+ findings.push({
512
+ severity: "BLOCKING",
513
+ code: "ENFORCE_KILL_SWITCH_NOT_WIRED",
514
+ message: `job "${jobId}" runs verify --policy enforce with DIFFCI_ENFORCE ${value === undefined ? "unset" : `set to ${JSON.stringify(value)}`} - set it to \${{ vars.DIFFCI_ENFORCE }} so turning the repository variable off stops enforcement.`,
515
+ workflow: relativePath,
516
+ job: jobId,
517
+ });
518
+ }
519
+ }
520
+ }
521
+ // 3. The full suite on push to the default branch.
522
+ if (!fullCommand || !trigger.ok)
523
+ continue;
524
+ const jobCondition = conditionHolds(rawJob.if, branch);
525
+ if (jobCondition === "FALSE")
526
+ continue;
527
+ for (const step of steps) {
528
+ if (typeof step.run !== "string" || !runInvokesFullCommand(step.run, fullCommand))
529
+ continue;
530
+ if (step["working-directory"] !== undefined && step["working-directory"] !== ".")
531
+ continue;
532
+ const stepCondition = conditionHolds(step.if, branch);
533
+ if (jobCondition === "TRUE" && stepCondition === "TRUE") {
534
+ fullSuiteJobs.push(where);
535
+ break;
536
+ }
537
+ if (stepCondition !== "FALSE")
538
+ unprovable.push(where);
539
+ }
540
+ }
541
+ }
542
+ if (enforceJobs.length === 0) {
543
+ findings.push({
544
+ severity: "BLOCKING",
545
+ code: "ENFORCE_JOB_MISSING",
546
+ workflow: WORKFLOWS_DIR,
547
+ message: "no job runs `diffci verify --policy enforce` as a gate. A continue-on-error job is a dry run and does not count.",
548
+ });
549
+ }
550
+ if (fullCommand && fullSuiteJobs.length === 0) {
551
+ const detail = unprovable.length > 0
552
+ ? ` ${unprovable.join(", ")} might, but its if: could not be shown to hold for every push to ${branch}.`
553
+ : "";
554
+ findings.push({
555
+ severity: "BLOCKING",
556
+ code: "FULL_SUITE_NOT_ON_DEFAULT_BRANCH",
557
+ workflow: WORKFLOWS_DIR,
558
+ message: `no job provably runs "${fullCommand}" on every push to ${branch}.${detail} Enforce mode skips tests on pull requests; without that run nothing checks what was skipped.`,
559
+ });
560
+ }
561
+ return { enforceJobs, fullSuiteJobs, fullCommand, findings, workflowsScanned };
562
+ }
310
563
  /** True when nothing found would let the observation change what the rest of CI does. */
311
564
  export function isNonInterfering(result) {
312
565
  return result.findings.every((finding) => finding.severity !== "BLOCKING");
@@ -0,0 +1,8 @@
1
+ /** GitHub-hosted runner and Node 24 action pins shared by every workflow the CLI generates. */
2
+ export declare const RUNNER = "ubuntu-26.04";
3
+ export declare const CHECKOUT_SHA = "3d3c42e5aac5ba805825da76410c181273ba90b1";
4
+ export declare const SETUP_NODE_SHA = "820762786026740c76f36085b0efc47a31fe5020";
5
+ export declare const UPLOAD_ARTIFACT_SHA = "043fb46d1a93c77aae656e7c1c64a875d1fc6a0a";
6
+ export declare function diffciWorkflow(version: string): string;
7
+ export declare function diffciVerificationWorkflow(version: string): string;
8
+ export declare function buildPilotWorkflow(version: string): string;
@@ -0,0 +1,26 @@
1
+ export interface WorkingTreeSnapshot {
2
+ /** The real checked-out commit this snapshot is relative to. */
3
+ baseSha: string;
4
+ /** Git tree identity covering tracked, staged, unstaged, and non-ignored untracked files. */
5
+ treeSha: string;
6
+ /** Unreachable commit used only so the existing commit-range analyzer can inspect the tree. */
7
+ commitSha: string;
8
+ changed: boolean;
9
+ }
10
+ /** One path that differs between two snapshots. A rename is a deletion plus an addition. */
11
+ export interface SnapshotChange {
12
+ path: string;
13
+ status: "added" | "modified" | "deleted";
14
+ }
15
+ /**
16
+ * Materialize the current worktree as a Git tree without changing the user's index or checkout.
17
+ *
18
+ * A temporary index begins at HEAD and stages the working tree into that isolated index. Git therefore
19
+ * applies the repository's normal ignore rules, executable-bit handling, symlink handling, and clean
20
+ * filters, while the real index and every source file stay untouched. The resulting tree SHA is a
21
+ * content-addressed verification identity. The synthetic commit is intentionally unreachable and is
22
+ * used only by DiffCI's existing commit-to-commit analyzer.
23
+ */
24
+ export declare function captureWorkingTreeSnapshot(repoPathInput: string): WorkingTreeSnapshot;
25
+ /** The paths that differ between two snapshot trees of the same repository. */
26
+ export declare function snapshotChanges(repoPathInput: string, beforeTreeSha: string, afterTreeSha: string): SnapshotChange[];
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Failure classification (from raw evidence) and normalized fingerprinting (Part 1/3). Deliberately does
3
+ * NOT hash raw log text - timestamps, absolute paths, container ids, and incidental byte offsets would
4
+ * make two occurrences of the exact same underlying failure look different. Every normalization step
5
+ * below strips or generalizes exactly one such source of incidental variance; the corpus of patterns is
6
+ * intentionally small and explicit rather than a black-box regex pile, so a wrong classification is easy
7
+ * to find and fix by reading this file.
8
+ */
9
+ import type { FailureClass } from "./taxonomy.js";
10
+ export interface FailureEvidence {
11
+ jobName: string;
12
+ stepName?: string;
13
+ command?: string;
14
+ errorText: string;
15
+ }
16
+ export declare function classifyFailureFromEvidence(evidence: FailureEvidence): FailureClass;
17
+ /**
18
+ * failure_fingerprint (Part 3): failureClass + job/step class + a normalized error signature + (when
19
+ * known) the specific failing test/module identifier - deliberately NOT the raw log. Two occurrences of
20
+ * "the same" failure (identical error class, same test, same normalized message) produce the identical
21
+ * fingerprint even if timestamps/paths/durations differ between the two CI runs.
22
+ */
23
+ export declare function computeFailureFingerprint(input: {
24
+ failureClass: FailureClass;
25
+ jobName: string;
26
+ stepName?: string;
27
+ failingTest?: string;
28
+ errorText: string;
29
+ }): string;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Preflight failure taxonomy (Part 1). Deliberately independent of GitHub-specific job names - a job
3
+ * called "check" must not automatically imply a class (Stage 2C's own measurement-pipeline fix ran into
4
+ * exactly this trap for a different purpose: job names/categories are a weak, sometimes-wrong signal).
5
+ * Classification here is driven by STEP-LEVEL evidence (error text, failing command, exit semantics),
6
+ * never the job's display name alone - see classifyFailureFromEvidence() in fingerprint.ts.
7
+ */
8
+ export type FailureClass = "TYPECHECK" | "LINT" | "BUILD" | "UNIT_TEST" | "INTEGRATION_TEST" | "DEPENDENCY" | "CONFIGURATION" | "GENERATED_ARTIFACT" | "SECURITY_SCAN" | "DEPLOYMENT" | "RUNNER_INFRASTRUCTURE" | "TIMEOUT" | "FLAKY" | "UNKNOWN";
9
+ export declare const FAILURE_CLASSES: readonly FailureClass[];
10
+ export declare function isFailureClass(value: string): value is FailureClass;
@@ -44,6 +44,10 @@ from this repository. Meta Muse Code reads the native root
44
44
  use the local MCP configuration in the agent-plugin package or visit
45
45
  https://diffci.com/mcp-server.
46
46
 
47
+ Installing the plugin does not make an agent use it. Paste the
48
+ [short agent-instructions snippet](docs/agent-installation.md#short-snippet)
49
+ into `CLAUDE.md` or `AGENTS.md` so it runs DiffCI before pushing.
50
+
47
51
  ## GitHub Action
48
52
 
49
53
  The public [`action.yml`](action.yml) is an observation-only GitHub Action