@diffci.com/diffci 0.3.31 → 0.3.33

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 (70) hide show
  1. package/README.md +23 -0
  2. package/dist-client/src/client/agent-setup.d.ts +18 -0
  3. package/dist-client/src/client/agent-setup.js +77 -0
  4. package/dist-client/src/client/agent-stop.d.ts +52 -0
  5. package/dist-client/src/client/agent-stop.js +101 -0
  6. package/dist-client/src/client/check-plan-junit.d.ts +25 -0
  7. package/dist-client/src/client/check-plan-junit.js +215 -0
  8. package/dist-client/src/client/check-plan.d.ts +42 -0
  9. package/dist-client/src/client/check-plan.js +143 -0
  10. package/dist-client/src/client/cli.js +288 -13
  11. package/dist-client/src/client/command-batches.d.ts +1 -0
  12. package/dist-client/src/client/command-batches.js +3 -1
  13. package/dist-client/src/client/enforce-misses-collect.js +6 -1
  14. package/dist-client/src/client/enforce-misses.d.ts +3 -2
  15. package/dist-client/src/client/enforce-misses.js +19 -59
  16. package/dist-client/src/client/failure-baseline.js +0 -0
  17. package/dist-client/src/client/full-command.d.ts +8 -0
  18. package/dist-client/src/client/full-command.js +31 -0
  19. package/dist-client/src/client/hook.d.ts +1 -1
  20. package/dist-client/src/client/hook.js +1 -1
  21. package/dist-client/src/client/job-summary.d.ts +7 -0
  22. package/dist-client/src/client/job-summary.js +78 -0
  23. package/dist-client/src/client/observe.d.ts +4 -0
  24. package/dist-client/src/client/observe.js +31 -2
  25. package/dist-client/src/client/report.d.ts +4 -0
  26. package/dist-client/src/client/test-results.js +7 -0
  27. package/dist-client/src/client/verify.d.ts +20 -0
  28. package/dist-client/src/client/verify.js +50 -12
  29. package/dist-client/src/client/watch.d.ts +36 -0
  30. package/dist-client/src/client/watch.js +76 -0
  31. package/dist-client/src/client/working-tree.d.ts +13 -0
  32. package/dist-client/src/client/working-tree.js +40 -1
  33. package/node_modules/@diffci.com/core/README.md +36 -5
  34. package/node_modules/@diffci.com/core/dist/cache/graph-cache.d.ts +1 -1
  35. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +3 -1
  36. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js.map +1 -1
  37. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +12 -0
  38. package/node_modules/@diffci.com/core/dist/git/git-diff.js +86 -0
  39. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  40. package/node_modules/@diffci.com/core/dist/git/types.d.ts +8 -0
  41. package/node_modules/@diffci.com/core/dist/planner/test-command.js +16 -0
  42. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  43. package/node_modules/@diffci.com/core/dist/repo/adapters/index.js +2 -1
  44. package/node_modules/@diffci.com/core/dist/repo/adapters/index.js.map +1 -1
  45. package/node_modules/@diffci.com/core/dist/repo/adapters/python.d.ts +32 -0
  46. package/node_modules/@diffci.com/core/dist/repo/adapters/python.js +273 -0
  47. package/node_modules/@diffci.com/core/dist/repo/adapters/python.js.map +1 -0
  48. package/node_modules/@diffci.com/core/dist/repo/adapters/types.d.ts +2 -0
  49. package/node_modules/@diffci.com/core/dist/repo/adapters/types.js.map +1 -1
  50. package/node_modules/@diffci.com/core/dist/repo/file-references.js +21 -0
  51. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  52. package/node_modules/@diffci.com/core/dist/repo/graph.d.ts +4 -0
  53. package/node_modules/@diffci.com/core/dist/repo/graph.js +182 -21
  54. package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
  55. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +1 -0
  56. package/node_modules/@diffci.com/core/dist/repo/impact.js +29 -4
  57. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  58. package/node_modules/@diffci.com/core/dist/repo/types.d.ts +5 -0
  59. package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +3 -1
  60. package/node_modules/@diffci.com/core/src/git/git-diff.ts +72 -0
  61. package/node_modules/@diffci.com/core/src/git/types.ts +5 -0
  62. package/node_modules/@diffci.com/core/src/planner/test-command.ts +14 -0
  63. package/node_modules/@diffci.com/core/src/repo/adapters/index.ts +2 -1
  64. package/node_modules/@diffci.com/core/src/repo/adapters/python.ts +252 -0
  65. package/node_modules/@diffci.com/core/src/repo/adapters/types.ts +2 -0
  66. package/node_modules/@diffci.com/core/src/repo/file-references.ts +19 -0
  67. package/node_modules/@diffci.com/core/src/repo/graph.ts +154 -20
  68. package/node_modules/@diffci.com/core/src/repo/impact.ts +27 -4
  69. package/node_modules/@diffci.com/core/src/repo/types.ts +5 -0
  70. package/package.json +3 -2
@@ -0,0 +1,143 @@
1
+ // SPDX-License-Identifier: MIT
2
+ /** Compare one advisory selection with failures in the supplied full-suite JUnit report. */
3
+ import { createHash } from "node:crypto";
4
+ import { posix } from "node:path";
5
+ import { readJunit, junitFile, attributeJunitFile, normalizeTestPath } from "./check-plan-junit.js";
6
+ function record(value) {
7
+ return value !== null && typeof value === "object" && !Array.isArray(value);
8
+ }
9
+ function planPaths(value, field) {
10
+ if (!Array.isArray(value))
11
+ throw new Error(`Plan ${field} must be an array of repository-relative file paths`);
12
+ const paths = new Set();
13
+ for (const path of value) {
14
+ if (typeof path !== "string" || path.length === 0 || /[\\\x00-\x1f\x7f]/.test(path)
15
+ || path.startsWith("/") || /^[a-z][a-z\d+.-]*:/i.test(path)
16
+ || path.split("/").some((part) => part === "" || part === "." || part === "..")) {
17
+ throw new Error(`Plan ${field} contains a noncanonical repository-relative path`);
18
+ }
19
+ if (paths.has(path))
20
+ throw new Error(`Plan ${field} contains the duplicate path ${JSON.stringify(path)}`);
21
+ paths.add(path);
22
+ }
23
+ return paths;
24
+ }
25
+ function readSelection(input) {
26
+ if (!record(input))
27
+ throw new Error("Expected an ExecutionPlan or the JSON output of Core's plan command");
28
+ let plan = input;
29
+ if (Object.hasOwn(input, "plan")) {
30
+ if (input.advisoryOnly !== true || typeof input.base !== "string" || !input.base
31
+ || typeof input.head !== "string" || !input.head || !record(input.plan)
32
+ || ["mode", "selectedTests", "skippedTests"].some((key) => Object.hasOwn(input, key))) {
33
+ throw new Error("Expected an unambiguous Core plan output with advisoryOnly, base, head and plan");
34
+ }
35
+ plan = input.plan;
36
+ }
37
+ if (plan.version !== "5.0.0")
38
+ throw new Error("Unsupported plan version; expected ExecutionPlan version 5.0.0");
39
+ if (plan.mode !== "SELECTIVE" && plan.mode !== "FULL")
40
+ throw new Error("Plan mode must be SELECTIVE or FULL");
41
+ if (!record(plan.safety) || typeof plan.safety.fallbackRequired !== "boolean"
42
+ || plan.safety.fallbackRequired !== (plan.mode === "FULL")) {
43
+ throw new Error("Plan safety.fallbackRequired must agree with its mode");
44
+ }
45
+ const selected = planPaths(plan.selectedTests, "selectedTests");
46
+ const skipped = planPaths(plan.skippedTests, "skippedTests");
47
+ for (const path of selected) {
48
+ if (skipped.has(path))
49
+ throw new Error(`Plan selects and skips the same file: ${JSON.stringify(path)}`);
50
+ }
51
+ if (plan.mode === "FULL" && skipped.size > 0)
52
+ throw new Error("A FULL plan cannot contain skipped tests");
53
+ return { mode: plan.mode, selected, skipped };
54
+ }
55
+ function identity(test, file, repoRoot, root) {
56
+ const label = (value) => /\.[cm]?[jt]sx?$/.test(value) ? normalizeTestPath(value, repoRoot, root) || value : value;
57
+ // Keep stored keys bounded even when many passing cases inherit long describe names.
58
+ return createHash("sha256").update(JSON.stringify([file, test.suiteNames.map(label), label(test.classname ?? ""), test.name])).digest("hex");
59
+ }
60
+ function reporterRoot(value = ".") {
61
+ const path = value.replace(/\\/g, "/");
62
+ if (!path || /[\x00-\x1f\x7f]/.test(path) || path.startsWith("/")
63
+ || /^[a-z][a-z\d+.-]*:/i.test(path) || path.split("/").includes("..")) {
64
+ throw new Error("Invalid --root: expected a directory inside the repository, without parent traversal");
65
+ }
66
+ return posix.normalize(path).replace(/\/$/, "") || ".";
67
+ }
68
+ /** This checks selection against supplied results, not suite success or report/revision provenance. */
69
+ export function checkPlan(planInput, junitXml, options = {}) {
70
+ const root = reporterRoot(options.root);
71
+ const repoRoot = options.repoRoot ?? process.cwd();
72
+ const baseRepoRoot = options.baseRepoRoot ?? repoRoot;
73
+ const plan = readSelection(planInput);
74
+ const known = new Set([...plan.selected, ...plan.skipped]);
75
+ const headCounts = new Map();
76
+ const baseCounts = new Map();
77
+ const baseline = new Set();
78
+ const basePassed = new Set();
79
+ function count(test, counts, checkout) {
80
+ const file = junitFile(test, checkout, root);
81
+ // Missing names and ambiguous file identities cannot establish an old failure.
82
+ if (!known.has(file) || !test.name)
83
+ return undefined;
84
+ const key = identity(test, file, checkout, root);
85
+ counts.set(key, (counts.get(key) ?? 0) + 1);
86
+ return key;
87
+ }
88
+ const results = readJunit(junitXml, options.baseResults === undefined ? undefined
89
+ : (test) => { count(test, headCounts, repoRoot); });
90
+ if (options.baseResults !== undefined) {
91
+ readJunit(options.baseResults, (test, failed, skipped) => {
92
+ const key = count(test, baseCounts, baseRepoRoot);
93
+ if (key !== undefined && failed)
94
+ baseline.add(key);
95
+ if (key !== undefined && !failed && !skipped)
96
+ basePassed.add(key);
97
+ });
98
+ }
99
+ const missed = [];
100
+ const possibleMisses = [];
101
+ const preExisting = [];
102
+ const selected = [];
103
+ const unattributed = [];
104
+ for (const failure of results.failures) {
105
+ const details = {
106
+ name: failure.name,
107
+ ...(failure.classname === undefined ? {} : { classname: failure.classname }),
108
+ ...(failure.suite === undefined ? {} : { suite: failure.suite }),
109
+ ...(failure.file === undefined ? {} : { reportedFile: failure.file }),
110
+ };
111
+ const attribution = attributeJunitFile(failure, repoRoot, root);
112
+ if (!("file" in attribution)) {
113
+ unattributed.push({ ...details, ...attribution });
114
+ continue;
115
+ }
116
+ const file = attribution.file;
117
+ if (!known.has(file)) {
118
+ unattributed.push({ ...details, reason: "File is absent from the supplied plan; check --root and report scope", candidates: [file] });
119
+ continue;
120
+ }
121
+ const key = identity(failure, file, repoRoot, root);
122
+ if (baseline.has(key) && baseCounts.get(key) === 1 && headCounts.get(key) === 1) {
123
+ preExisting.push({ ...details, file });
124
+ }
125
+ else if (plan.mode === "SELECTIVE" && plan.skipped.has(file)) {
126
+ // Repeated or unnamed identities cannot tell whether the failing occurrence changed.
127
+ const uncertain = !basePassed.has(key) || (headCounts.get(key) ?? 0) > 1
128
+ || (baseCounts.get(key) ?? 0) > 1
129
+ || !failure.name;
130
+ (uncertain ? possibleMisses : missed).push({ ...details, file });
131
+ }
132
+ else
133
+ selected.push({ ...details, file });
134
+ }
135
+ return {
136
+ schemaVersion: 1,
137
+ mode: plan.mode,
138
+ fullFallback: plan.mode === "FULL",
139
+ baselineProvided: options.baseResults !== undefined,
140
+ summary: { failedTests: results.failures.length, missed: missed.length, possibleMisses: possibleMisses.length, preExisting: preExisting.length, selected: selected.length, unattributed: unattributed.length },
141
+ missed, possibleMisses, preExisting, selected, unattributed,
142
+ };
143
+ }
@@ -14,6 +14,8 @@
14
14
  * verify fail-closed verification of a working-tree snapshot or commit range
15
15
  * gate run a build's whole gate and record what DiffCI would have skipped (observe)
16
16
  * check analysis plus automatic paired runtime measurement
17
+ * plan print Core's advisory JSON plan for a commit range (the input check-plan reads)
18
+ * check-plan compare a saved test selection with one full-suite JUnit result
17
19
  * observe analyse the checkout and write an observation report
18
20
  * verify-savings run a paired full-versus-selected timing check
19
21
  * validate-specs block conflicting same-turn change specifications
@@ -29,7 +31,7 @@
29
31
  * exits 1 on a BLOCKING finding - it is a pre-install check run by a human, not a step inside a build.
30
32
  */
31
33
  import { execFileSync, spawnSync } from "node:child_process";
32
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
34
+ import { closeSync, constants, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, writeFileSync } from "node:fs";
33
35
  import { tmpdir } from "node:os";
34
36
  import { basename, dirname, join, resolve } from "node:path";
35
37
  import { observe, isInsideRepository } from "./observe.js";
@@ -37,15 +39,19 @@ import { resolveObservationAgent } from "./agent-identity.js";
37
39
  import { inferFullCommand, inferComparableSelectedCommand, inferWorkspaceComparison } from "./full-command.js";
38
40
  import { addDiffciPackageScripts, detectPackageManager, installDiffci } from "./install.js";
39
41
  import { hookCommand, installPrePushHook, isGitRepository } from "./hook.js";
40
- import { MCP_CONFIG_PATHS, SKILL_PATH, writeMcpConfig, writeSkill } from "./agent-setup.js";
42
+ import { AGENT_HOOK_TIMEOUT_SECONDS, ignoredWrites, MCP_CONFIG_PATHS, SKILL_PATH, writeAgentStopHook, writeMcpConfig, writeSkill } from "./agent-setup.js";
41
43
  import { submitObservation } from "./submit.js";
42
44
  import { configureGraphCache } from "./shared-graph-cache.js";
43
45
  import { GraphCache } from "@diffci.com/core/cache/graph-cache";
44
46
  import { githubDeliveryWarning } from "./delivery-warning.js";
47
+ import { formatJobSummary } from "./job-summary.js";
45
48
  import { configureTelemetry, readTelemetryPreference, recordUsage } from "./telemetry.js";
46
49
  import { formatFeedbackPrompt, markFeedbackPromptShown, shouldShowFeedbackPrompt } from "./feedback-prompt.js";
47
50
  import { detectSpecificationConflicts, readSpecificationFile } from "./spec-conflicts.js";
48
51
  import { formatVerificationSummary, verificationExitCode, verifyChanged, verifyRange } from "./verify.js";
52
+ import { startWatch } from "./watch.js";
53
+ import { captureWorkingTreeSnapshot } from "./working-tree.js";
54
+ import { decideStop, HOOK_AGENTS, maxAttempts, parseStopPayload, sessionAttempts, stopRepoPath } from "./agent-stop.js";
49
55
  import { formatGateSummary, gateExitCode, planGate, runGate } from "./gate.js";
50
56
  import { formatGrowthPrompt, formatVerifySavingsSummary, measureCommand, runVerifySavings, writeVerifySavingsReport } from "./verify-savings.js";
51
57
  import { auditEnforceWorkflows, auditWorkflows, isNonInterfering } from "./workflow-guard.js";
@@ -54,6 +60,7 @@ import { observerIdentity } from "./package-identity.js";
54
60
  import { buildPilotWorkflow, diffciVerificationWorkflow, diffciWorkflow } from "./workflow-templates.js";
55
61
  import { buildMissReport, formatMissReportMarkdown, parseJunit } from "./enforce-misses.js";
56
62
  import { appendOutcome, formatOutcomeSummary, outcomeLogPath, readOutcomes, summarizeOutcomes } from "./outcome-log.js";
63
+ import { checkPlan } from "./check-plan.js";
57
64
  import { buildCoverageMap, formatCoverageRun } from "./coverage-map.js";
58
65
  import { confidenceCurve, formatConfidenceCurve } from "./test-ranking.js";
59
66
  import { parseShard, readTimings, timingsFromOutcomes } from "./test-shards.js";
@@ -80,6 +87,111 @@ function parseArgs(argv) {
80
87
  }
81
88
  return { command, flags };
82
89
  }
90
+ const CHECK_PLAN_MAX_INPUT_BYTES = 16 * 1024 * 1024;
91
+ function readCheckPlanInput(path) {
92
+ // Nonblocking open prevents a named pipe from hanging before the regular-file check. The capped
93
+ // read also preserves the limit if a regular file grows after fstat.
94
+ const descriptor = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
95
+ try {
96
+ const info = fstatSync(descriptor);
97
+ if (!info.isFile())
98
+ throw new Error(`Input must be a regular file: ${path}`);
99
+ if (info.size > CHECK_PLAN_MAX_INPUT_BYTES)
100
+ throw new Error(`Input exceeds the 16 MiB limit: ${path}`);
101
+ const bytes = Buffer.allocUnsafe(Math.min(info.size, CHECK_PLAN_MAX_INPUT_BYTES) + 1);
102
+ let length = 0;
103
+ while (length < bytes.length) {
104
+ const read = readSync(descriptor, bytes, length, bytes.length - length, null);
105
+ if (read === 0)
106
+ break;
107
+ length += read;
108
+ }
109
+ if (length > CHECK_PLAN_MAX_INPUT_BYTES)
110
+ throw new Error(`Input exceeds the 16 MiB limit: ${path}`);
111
+ if (length > info.size)
112
+ throw new Error(`Input grew while being read: ${path}`);
113
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, length));
114
+ }
115
+ finally {
116
+ closeSync(descriptor);
117
+ }
118
+ }
119
+ const PLAN_USAGE = "Usage: diffci plan --base <commit> [--head HEAD] [--repo <clean-checkout>]\nPrints Core's advisory JSON plan, the input check-plan reads. Accepts --flag=value. Does not run, skip or cancel tests.";
120
+ /** Same output and exit codes as Core's own `plan` command, so saved plans stay interchangeable. */
121
+ async function runPlanCommand(args) {
122
+ try {
123
+ if (args.length === 1 && (args[0] === "--help" || args[0] === "-h")) {
124
+ console.log(PLAN_USAGE);
125
+ return 0;
126
+ }
127
+ const values = new Map();
128
+ for (let index = 0; index < args.length; index += 1) {
129
+ const token = args[index];
130
+ const equals = token.indexOf("=");
131
+ const flag = equals < 0 ? token : token.slice(0, equals);
132
+ if (!["--repo", "--base", "--head"].includes(flag))
133
+ throw new Error(`Unsupported plan argument: ${flag}`);
134
+ if (values.has(flag))
135
+ throw new Error(`Repeated plan argument: ${flag}`);
136
+ const value = equals < 0 ? args[++index] : token.slice(equals + 1);
137
+ if (!value || value.startsWith("--"))
138
+ throw new Error(`Missing value for ${flag}`);
139
+ values.set(flag, value);
140
+ }
141
+ const base = values.get("--base");
142
+ if (!base)
143
+ throw new Error("Expected: diffci plan --base <commit> [--head HEAD] [--repo <path>]");
144
+ const { analyzeCheckout } = await import("@diffci.com/core/analyze");
145
+ const plan = await analyzeCheckout({ repoPath: values.get("--repo") ?? process.cwd(), base, head: values.get("--head") ?? "HEAD" });
146
+ console.log(JSON.stringify(plan, null, 2));
147
+ return 0;
148
+ }
149
+ catch (error) {
150
+ console.error(JSON.stringify({ error: error instanceof Error ? error.message : String(error), recommendation: "RUN_FULL_CI" }));
151
+ return 1;
152
+ }
153
+ }
154
+ function runCheckPlanCommand(args) {
155
+ try {
156
+ const files = new Map();
157
+ if (args.length === 1 && args[0] === "--help") {
158
+ console.log("Usage: diffci check-plan --plan <file> --results <file> [--base-results <file>] [--root <reporter-root>] [--repo <checkout-root>] [--base-repo <base-checkout-root>]\nAccepts --flag=value. Without base results, skipped failures are possibleMisses. Exit 1: missed, possibleMisses or unattributed; exit 2: invalid input.");
159
+ return 0;
160
+ }
161
+ for (let index = 0; index < args.length; index += 1) {
162
+ const token = args[index];
163
+ const equals = token.indexOf("=");
164
+ const flag = equals < 0 ? token : token.slice(0, equals);
165
+ if (!["--plan", "--results", "--base-results", "--root", "--repo", "--base-repo"].includes(flag))
166
+ throw new Error(`Unsupported check-plan argument: ${flag}`);
167
+ if (files.has(flag))
168
+ throw new Error(`Repeated check-plan argument: ${flag}`);
169
+ const value = equals < 0 ? args[++index] : token.slice(equals + 1);
170
+ if (!value || value.startsWith("--"))
171
+ throw new Error(`Missing file path for ${flag}`);
172
+ files.set(flag, value);
173
+ }
174
+ const planPath = files.get("--plan");
175
+ const resultsPath = files.get("--results");
176
+ if (!planPath || !resultsPath)
177
+ throw new Error("check-plan requires --plan <file> and --results <file>");
178
+ if (files.has("--base-repo") && !files.has("--base-results"))
179
+ throw new Error("--base-repo requires --base-results");
180
+ const plan = JSON.parse(readCheckPlanInput(planPath));
181
+ const basePath = files.get("--base-results");
182
+ const report = checkPlan(plan, readCheckPlanInput(resultsPath), {
183
+ root: files.get("--root"), repoRoot: resolve(files.get("--repo") ?? process.cwd()),
184
+ baseRepoRoot: files.has("--base-repo") ? resolve(files.get("--base-repo")) : undefined,
185
+ baseResults: basePath === undefined ? undefined : readCheckPlanInput(basePath),
186
+ });
187
+ console.log(JSON.stringify(report));
188
+ return report.summary.missed > 0 || report.summary.possibleMisses > 0 || report.summary.unattributed > 0 ? 1 : 0;
189
+ }
190
+ catch (error) {
191
+ console.error(JSON.stringify({ schemaVersion: 1, error: error instanceof Error ? error.message : "Invalid check-plan input" }));
192
+ return 2;
193
+ }
194
+ }
83
195
  function defaultReportPath(env) {
84
196
  // RUNNER_TEMP is outside GITHUB_WORKSPACE on every GitHub-hosted runner, which is the property that
85
197
  // matters: the report cannot become an untracked file in the repository being observed.
@@ -117,7 +229,7 @@ What this does:
117
229
  New files the run writes are listed in the receipt (snapshot.written_during_verification) and do not block it;
118
230
  consider adding them to .gitignore. If verification changes existing files, review those changes and rerun DiffCI
119
231
  so the new snapshot is verified.
120
- If the repository has the DiffCI pre-push hook (\`diffci init --hook\`), a push verifies the pushed commits again; do not bypass it with \`--no-verify\` unless the user asks.
232
+ If the repository has the DiffCI pre-push hook (\`diffci init\` installs it), a push verifies the pushed commits again; do not bypass it with \`--no-verify\` unless the user asks.
121
233
  Use \`observe --no-send\` when analysis without test execution is needed.
122
234
 
123
235
  Do not propose, commit, push, or deploy when \`safe_to_continue\` is false. If DiffCI is blocked, run the repository's normal required verification and report the blocker; required project CI remains authoritative.
@@ -299,6 +411,11 @@ function runInit(flags, env) {
299
411
  skipped.push(`skipped ${SKILL_PATH} (--no-skill)`);
300
412
  else
301
413
  writes.push(writeSkill(repoPath, force));
414
+ if (flags["no-agent-hooks"] === true)
415
+ skipped.push("skipped the agent stop hooks (--no-agent-hooks)");
416
+ else
417
+ for (const agent of HOOK_AGENTS)
418
+ writes.push(writeAgentStopHook(repoPath, agent, hookCommand(manager, identity.version)));
302
419
  if (flags["no-hook"] === true)
303
420
  skipped.push("skipped the pre-push hook (--no-hook)");
304
421
  else if (!isGitRepository(repoPath))
@@ -314,6 +431,13 @@ function runInit(flags, env) {
314
431
  console.log(" skipped package installation (pass --install to add an exact dev dependency)");
315
432
  for (const line of skipped)
316
433
  console.log(` ${line}`);
434
+ const ignored = ignoredWrites(repoPath, writes);
435
+ if (ignored.length > 0) {
436
+ console.log(`\nWarning: .gitignore keeps ${ignored.length === 1 ? "this file" : "these files"} out of commits, so other checkouts and agent sessions will not get ${ignored.length === 1 ? "it" : "them"}:`);
437
+ for (const path of ignored)
438
+ console.log(` ${path}`);
439
+ console.log("Add an exception (for example !/.claude/skills/ after /.claude/*) or commit with git add -f.");
440
+ }
317
441
  if (!includeWorkflow)
318
442
  console.log(" skipped .github/workflows/diffci.yml (pass --workflow to add it)");
319
443
  if (!includeVerificationWorkflow)
@@ -335,6 +459,100 @@ function runMcp() {
335
459
  throw result.error;
336
460
  return 0;
337
461
  }
462
+ async function runAgentStopCommand(flags, env) {
463
+ const agent = stringFlag(flags, "agent");
464
+ if (!agent || !HOOK_AGENTS.includes(agent)) {
465
+ console.error(`diffci agent-stop needs --agent ${HOOK_AGENTS.join("|")}`);
466
+ return 2;
467
+ }
468
+ // Every exit is 0 with JSON on stdout: a hook that fails would neither stop the agent nor tell it why.
469
+ if (env.DIFFCI_AGENT_HOOK === "0") {
470
+ console.log("{}");
471
+ return 0;
472
+ }
473
+ const payload = parseStopPayload(await readStdin());
474
+ const repoPath = resolve(stopRepoPath(payload, env, process.cwd()));
475
+ const attempts = sessionAttempts(repoPath, payload);
476
+ let report;
477
+ try {
478
+ const identity = observerIdentity();
479
+ report = await verifyChanged({
480
+ repoPath,
481
+ env: env,
482
+ version: identity.version,
483
+ engineSha: identity.sha,
484
+ // Below the hook's own timeout (agent-setup.ts), so the hook always answers.
485
+ timeoutMs: (AGENT_HOOK_TIMEOUT_SECONDS - 120) * 1000,
486
+ tailBytes: 12_000,
487
+ skipChecks: env.DIFFCI_CHECKS === "0",
488
+ });
489
+ appendOutcome(repoPath, report, env);
490
+ }
491
+ catch {
492
+ report = undefined;
493
+ }
494
+ const decision = decideStop(agent, report, attempts.failures, maxAttempts(env));
495
+ attempts.record(decision.failures);
496
+ console.log(decision.stdout);
497
+ return 0;
498
+ }
499
+ function readStdin() {
500
+ if (process.stdin.isTTY)
501
+ return Promise.resolve("");
502
+ return new Promise((resolveText) => {
503
+ let text = "";
504
+ process.stdin.setEncoding("utf8");
505
+ process.stdin.on("data", (chunk) => { text += chunk; });
506
+ process.stdin.on("end", () => resolveText(text));
507
+ process.stdin.on("error", () => resolveText(text));
508
+ });
509
+ }
510
+ async function runWatchCommand(flags, env) {
511
+ const repoPath = resolve(stringFlag(flags, "repo") ?? process.cwd());
512
+ const identity = observerIdentity();
513
+ const checks = flags.checks === true;
514
+ console.log(`DiffCI watching ${repoPath}: verifies the uncommitted changes after each save${checks ? "" : " (tests only; --checks adds lint, typecheck and other checks)"}. Ctrl+C stops.`);
515
+ const session = startWatch({
516
+ repoPath,
517
+ debounceMs: numberFlag(flags, "debounce-ms") ?? 300,
518
+ currentTree: () => { try {
519
+ return captureWorkingTreeSnapshot(repoPath).treeSha;
520
+ }
521
+ catch {
522
+ return undefined;
523
+ } },
524
+ run: async () => {
525
+ const started = Date.now();
526
+ const report = await verifyChanged({
527
+ repoPath,
528
+ env: env,
529
+ version: identity.version,
530
+ engineSha: identity.sha,
531
+ timeoutMs: numberFlag(flags, "timeout-ms") ?? 30 * 60 * 1000,
532
+ tailBytes: 12_000,
533
+ skipChecks: !checks,
534
+ });
535
+ if (flags["no-log"] !== true)
536
+ appendOutcome(repoPath, report, env);
537
+ console.log(formatWatchRun(report, Date.now() - started));
538
+ return { treeSha: report.snapshot.after_tree_sha ?? report.snapshot.before_tree_sha };
539
+ },
540
+ });
541
+ await new Promise((resolveStop) => process.once("SIGINT", () => { session.stop(); resolveStop(); }));
542
+ return 0;
543
+ }
544
+ /** One line for a pass, the full summary for anything else, so a failure shows what broke. */
545
+ function formatWatchRun(report, wallMs) {
546
+ const time = new Date().toTimeString().slice(0, 8);
547
+ if (report.selection === "none" && report.verification === "passed")
548
+ return `${time} no uncommitted changes`;
549
+ if (report.verification === "passed") {
550
+ const how = report.reused_from ? "reused an earlier pass of this tree" : `${report.selection} ${report.tests_selected} of ${report.tests_available} test files`;
551
+ return `${time} passed ${how} (${(wallMs / 1000).toFixed(1)}s)`;
552
+ }
553
+ return `${time} ${report.verification.toUpperCase()}
554
+ ${formatVerificationSummary(report)}`;
555
+ }
338
556
  async function runVerifyCommand(flags, env) {
339
557
  const changed = flags.changed === true;
340
558
  if (changed && (flags.base !== undefined || flags.head !== undefined)) {
@@ -569,7 +787,11 @@ function summarise(report, executionFollows = false) {
569
787
  else {
570
788
  lines.push(" planned reduction: unavailable (no discovered tests); runtime savings unmeasured");
571
789
  }
572
- lines.push(` graph: ${result.graph.nodes} nodes, confidence ${result.graph.effectiveConfidence ?? result.graph.confidence}`);
790
+ const changeConfidence = result.graph.effectiveConfidence ?? result.graph.confidence;
791
+ lines.push(` graph: ${result.graph.nodes} nodes, confidence ${changeConfidence} for this change`);
792
+ if (result.graph.confidence !== changeConfidence || (result.graph.confidenceReasons?.length && changeConfidence !== "COMPLETE")) {
793
+ lines.push(` repository graph: ${result.graph.confidence}${result.graph.confidenceReasons?.length ? ` (${result.graph.confidenceReasons.join("; ")})` : ""}`);
794
+ }
573
795
  if (result.fallbackReasons.length > 0) {
574
796
  lines.push(` fallback: ${result.fallbackReasons.join("; ")}`);
575
797
  for (const [path, blockers] of Object.entries(result.fallbackDetails ?? {})) {
@@ -801,12 +1023,23 @@ async function runObserve(flags, env) {
801
1023
  // says the same thing the report says, including when the answer is "refused" or "not sent".
802
1024
  if (env.GITHUB_STEP_SUMMARY) {
803
1025
  try {
804
- writeFileSync(env.GITHUB_STEP_SUMMARY, `### DiffCI (observation only)\n\n\`\`\`\n${summary}${delivery ? `\n delivery: ${delivery}` : ""}\n\`\`\`\n\n[Open-source engine: DiffCI/core](https://github.com/DiffCI/core)\n`, { flag: "a" });
1026
+ writeFileSync(env.GITHUB_STEP_SUMMARY, formatJobSummary(report, summary, delivery), { flag: "a" });
805
1027
  }
806
1028
  catch {
807
1029
  // Losing the summary is cosmetic; the report on disk is the record.
808
1030
  }
809
1031
  }
1032
+ // The same Markdown for CI systems without a step summary (the GitLab component exposes it as an artifact).
1033
+ const summaryOut = stringFlag(flags, "summary-out");
1034
+ if (summaryOut) {
1035
+ try {
1036
+ mkdirSync(dirname(resolve(summaryOut)), { recursive: true });
1037
+ writeFileSync(resolve(summaryOut), formatJobSummary(report, summary, delivery), "utf8");
1038
+ }
1039
+ catch {
1040
+ // Cosmetic, as above.
1041
+ }
1042
+ }
810
1043
  if (env.GITHUB_OUTPUT) {
811
1044
  try {
812
1045
  writeFileSync(env.GITHUB_OUTPUT, `report-path=${reportPath}\nstatus=${report.status}\n`, { flag: "a" });
@@ -895,8 +1128,15 @@ function runEnforceMisses(flags, env) {
895
1128
  console.error(`No full-suite results at ${junitPath}: nothing can be classified, so no miss can be ruled out.`);
896
1129
  return 2;
897
1130
  }
1131
+ let fullRun;
1132
+ try {
1133
+ fullRun = parseJunit(readCheckPlanInput(junitPath), repoPath);
1134
+ }
1135
+ catch (error) {
1136
+ console.error(`Cannot read full-suite JUnit: ${error instanceof Error ? error.message : String(error)}`);
1137
+ return 2;
1138
+ }
898
1139
  const headSha = stringFlag(flags, "head") ?? execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoPath, encoding: "utf8" }).trim();
899
- const fullRun = parseJunit(readFileSync(junitPath, "utf8"), repoPath);
900
1140
  const failing = fullRun.filter((outcome) => outcome.failed);
901
1141
  const runUrl = env.GITHUB_RUN_ID ? `${env.GITHUB_SERVER_URL ?? "https://github.com"}/${repository}/actions/runs/${env.GITHUB_RUN_ID}` : undefined;
902
1142
  const notes = [];
@@ -910,9 +1150,14 @@ function runEnforceMisses(flags, env) {
910
1150
  const rerunJunit = stringFlag(flags, "rerun-junit");
911
1151
  const rerunArgs = inferRerunArgs(repoPath);
912
1152
  const files = [...new Set(failing.map((outcome) => outcome.file).filter(Boolean))];
913
- const rerun = rerunJunit
914
- ? parseJunit(readFileSync(rerunJunit, "utf8"), repoPath)
915
- : rerunArgs && files.length > 0 ? rerunFailingFiles(repoPath, rerunArgs, files) : undefined;
1153
+ let rerun;
1154
+ try {
1155
+ rerun = rerunJunit ? parseJunit(readCheckPlanInput(rerunJunit), repoPath)
1156
+ : rerunArgs && files.length > 0 ? rerunFailingFiles(repoPath, rerunArgs, files) : undefined;
1157
+ }
1158
+ catch (error) {
1159
+ notes.push(`rerun results unavailable: ${error instanceof Error ? error.message : String(error)}`);
1160
+ }
916
1161
  if (!rerun)
917
1162
  notes.push("failures were not re-run, so none could be ruled flaky; every failure was treated as deterministic");
918
1163
  const collect = {
@@ -1153,7 +1398,10 @@ Open-source engine: https://github.com/DiffCI/core
1153
1398
  Pilot a repository: https://diffci.com/#pilot
1154
1399
 
1155
1400
  Usage:
1156
- diffci init [--repo <path>] [--workflow] [--verification-workflow] [--install] [--no-hook] [--no-mcp] [--no-skill] [--force]
1401
+ diffci init [--repo <path>] [--workflow] [--verification-workflow] [--install] [--no-hook] [--no-mcp] [--no-skill]
1402
+ [--no-agent-hooks] [--force]
1403
+ diffci watch [--repo <path>] [--checks] [--debounce-ms <ms>] [--no-log]
1404
+ diffci agent-stop --agent claude|codex|cursor (run by the agent stop hooks init installs; reads the hook JSON on stdin)
1157
1405
  diffci mcp
1158
1406
  diffci verify [--changed | --base <sha> --head <sha>] [--policy enforce] [--repo <path>] [--out <file>] [--json]
1159
1407
  [--redact-paths] [--timeout-ms <ms>] [--baseline-on-failure] [--no-checks | --checks]
@@ -1162,11 +1410,13 @@ Usage:
1162
1410
  diffci telemetry [--mode off|anonymous|installations] [--internal-usage]
1163
1411
  diffci check [--repo <path>] [--out <file>] [--base <sha> --head <sha>]
1164
1412
  [--redact-paths] [--json] [--quiet] [--fail-on-error] [--timeout-ms <ms>] [--share-usage]
1413
+ diffci plan --base <sha> [--head <sha>] [--repo <path>]
1414
+ diffci check-plan --plan <plan.json> --results <junit.xml>
1165
1415
  diffci pilot --full <command> [--selected <command>] [--repo <path>] [--out-dir <dir>] [--label <name>]
1166
1416
  diffci pilot-packet [--repo <path>] [--out-dir <dir>] [--base <sha> --head <sha>]
1167
1417
  [--label <name>] [--repository-url <https-url>] [--redact-paths]
1168
1418
  diffci observe [--repo <path>] [--out <file>] [--base <sha> --head <sha>]
1169
- [--redact-paths] [--json] [--quiet] [--fail-on-error]
1419
+ [--redact-paths] [--json] [--quiet] [--fail-on-error] [--summary-out <file.md>]
1170
1420
  [--api-url <url> --api-token <token>] [--no-send] [--share-usage] [--agent <name|auto>]
1171
1421
  [--graph-cache-dir <dir>] [--shared-graph-cache [--graph-cache-url <url>]]
1172
1422
  diffci verify-savings --repo <path> --full <command>
@@ -1189,8 +1439,11 @@ Usage:
1189
1439
 
1190
1440
  init writes AGENTS.md, CLAUDE.md, Cursor rules, Copilot instructions, and diffci.config.json. It also
1191
1441
  registers the DiffCI MCP server in .mcp.json (Claude Code) and .cursor/mcp.json (Cursor), keeping other
1192
- servers, adds the diffci-verify skill to .claude/skills, and installs the pre-push hook; --no-mcp,
1193
- --no-skill and --no-hook leave each out. --workflow adds a separate non-blocking observation workflow. --install detects npm, pnpm, Yarn,
1442
+ servers, adds the diffci-verify skill to .claude/skills, installs the pre-push hook, and adds stop hooks
1443
+ (.claude/settings.json, .codex/hooks.json, .cursor/hooks.json) that run diffci agent-stop when an agent ends a
1444
+ turn: it verifies the uncommitted changes and, when tests or checks fail, asks the agent to fix them before
1445
+ finishing, at most DIFFCI_AGENT_HOOK_MAX times a session (default 3; DIFFCI_AGENT_HOOK=0 turns it off).
1446
+ --no-mcp, --no-skill, --no-hook and --no-agent-hooks leave each out. --workflow adds a separate non-blocking observation workflow. --install detects npm, pnpm, Yarn,
1194
1447
  or Bun, installs this DiffCI version as an exact dev dependency, updates the manager's lockfile,
1195
1448
  and adds diffci:verify, diffci:check, and diffci:observe package scripts without replacing existing scripts.
1196
1449
  --verification-workflow adds a blocking GitHub check that uploads a commit-bound verification receipt.
@@ -1204,6 +1457,11 @@ leaves) and stops at the first failure; --no-checks skips them, and they are ski
1204
1457
  verify without --changed resolves the CI event range (or HEAD^..HEAD locally), requires a clean checkout,
1205
1458
  and exits zero only when the analyzed head is the commit that actually passed verification.
1206
1459
  check analyzes the change, runs inferred full and selected commands, and shows measured savings.
1460
+ plan prints Core's advisory JSON plan for a clean checkout at --head; save it before the full suite runs.
1461
+ It exits 1 with a RUN_FULL_CI error when it cannot plan. It runs no tests and sends nothing.
1462
+ check-plan reads one saved plan and one full-suite JUnit result, and prints a JSON failure comparison.
1463
+ It exits 1 for missed, possible-miss or unattributed failures, 2 for invalid inputs, and 0 otherwise. It runs no tests,
1464
+ reads no Git state, writes no reports, and sends nothing. Each UTF-8 input must be at most 16 MiB.
1207
1465
  pilot runs observe and verify-savings together, writing reports to ../diffci-output by default.
1208
1466
  pilot-packet writes a shareable compatibility summary, raw observation, and non-blocking workflow
1209
1467
  outside the checkout. It runs no tests, modifies no target-repository files, and sends nothing.
@@ -1236,6 +1494,8 @@ and a selection that cannot be split run in shard 1.
1236
1494
  coverage runs the full node:test suite once under a probe and V8 coverage and keeps, per test file, the files
1237
1495
  it loaded, read or listed in .git/diffci/coverage-map.json. verify then also runs tests that map connects to a
1238
1496
  changed file when the dependency graph did not select them; it only ever adds tests (--no-coverage ignores it).
1497
+ watch verifies the uncommitted changes after each save, as verify --changed would, and prints one line per
1498
+ pass and the full summary on a failure; tests only unless --checks.
1239
1499
  outcomes summarises that log: results, selected and full runs, top full-run reasons, agents, and possible
1240
1500
  misses (a selected run that passed and a later full run of the same tree that failed). --curve replays the
1241
1501
  failing runs to show how soon the first failure is seen, ranked by history against path order. --timings
@@ -1264,6 +1524,15 @@ function maybeShowFeedbackPrompt(flags, env) {
1264
1524
  markFeedbackPromptShown(env);
1265
1525
  }
1266
1526
  async function main() {
1527
+ // This stateless command deliberately bypasses shared flag handling, telemetry and feedback.
1528
+ if (process.argv[2] === "check-plan") {
1529
+ process.exitCode = runCheckPlanCommand(process.argv.slice(3));
1530
+ return;
1531
+ }
1532
+ if (process.argv[2] === "plan") {
1533
+ process.exitCode = await runPlanCommand(process.argv.slice(3));
1534
+ return;
1535
+ }
1267
1536
  const { command, flags } = parseArgs(process.argv);
1268
1537
  const env = process.env;
1269
1538
  if (flags.help === true || command === "help" || command === undefined) {
@@ -1289,6 +1558,12 @@ async function main() {
1289
1558
  case "verify":
1290
1559
  process.exitCode = await runVerifyCommand(flags, env);
1291
1560
  return;
1561
+ case "watch":
1562
+ process.exitCode = await runWatchCommand(flags, env);
1563
+ return;
1564
+ case "agent-stop":
1565
+ process.exitCode = await runAgentStopCommand(flags, env);
1566
+ return;
1292
1567
  case "check":
1293
1568
  process.exitCode = await runCheck(flags, env);
1294
1569
  maybeShowFeedbackPrompt(flags, env);
@@ -46,4 +46,5 @@ export declare function measureCommands(commands: readonly string[], options: {
46
46
  tailBytes: number;
47
47
  env?: Record<string, string>;
48
48
  stopOnFailure?: boolean;
49
+ stopOnFailureWithin?: number;
49
50
  }): CommandMeasurement;
@@ -131,7 +131,9 @@ export function measureCommands(commands, options) {
131
131
  parts.push(part);
132
132
  if (part.timedOut)
133
133
  break;
134
- if (options.stopOnFailure && (part.exitCode !== 0 || part.signal !== null) && parts.length < commands.length) {
134
+ // `stopOnFailureWithin`: only a failure among the first n parts stops the run (verify's first pass).
135
+ const stops = options.stopOnFailure || parts.length <= (options.stopOnFailureWithin ?? 0);
136
+ if (stops && (part.exitCode !== 0 || part.signal !== null) && parts.length < commands.length) {
135
137
  stopped = true;
136
138
  break;
137
139
  }
@@ -149,7 +149,12 @@ export function rerunFailingFiles(repoPath, runnerArgs, files) {
149
149
  });
150
150
  if (!existsSync(junit))
151
151
  return undefined;
152
- return parseJunit(readFileSync(junit, "utf8"), repoPath);
152
+ try {
153
+ return parseJunit(readFileSync(junit, "utf8"), repoPath);
154
+ }
155
+ catch {
156
+ return undefined;
157
+ } // A partial rerun cannot prove a full-run failure flaky.
153
158
  }
154
159
  finally {
155
160
  rmSync(directory, { recursive: true, force: true });
@@ -8,6 +8,7 @@ export interface TestOutcome {
8
8
  name: string;
9
9
  failed: boolean;
10
10
  skipped: boolean;
11
+ suiteLevel?: boolean;
11
12
  }
12
13
  /** The receipt fields the detector reads; older receipts may lack `selected_tests`. */
13
14
  export type ReceiptFields = Pick<VerificationReport, "schema" | "selection" | "selected_tests" | "command" | "enforcement" | "commit_range">;
@@ -89,9 +90,9 @@ export interface MissReport {
89
90
  open_unsafe_misses: UnsafeMissEntry[];
90
91
  notes: string[];
91
92
  }
92
- /** Repository-relative with forward slashes; paths outside the repository stay absolute. */
93
+ /** Legacy identity normalization: stored v1 detector baselines depend on these exact rules. */
93
94
  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
+ /** Testcases in document order. Repeated ids are merged: any failure wins. */
95
96
  export declare function parseJunit(xml: string, repoRoot: string): TestOutcome[];
96
97
  /**
97
98
  * The test files a `selected` receipt ran. Receipts from before `selected_tests` existed fall back to the