@diffci.com/diffci 0.3.31 → 0.3.32

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.
@@ -1,3 +1,11 @@
1
+ /**
2
+ * Which of the files init wrote or updated Git would leave out of a commit, from init's own result lines
3
+ * ("wrote <path> ...", "updated <path> ..."). Paths under .git (the pre-push hook) are never versioned.
4
+ *
5
+ * WHY (2026-11-06). DentalPresence ignored all of `/.claude/`, so init reported "wrote
6
+ * .claude/skills/diffci-verify/SKILL.md" for a skill no other checkout or agent session would ever get.
7
+ */
8
+ export declare function ignoredWrites(repoPath: string, results: readonly string[]): string[];
1
9
  /**
2
10
  * Agent integrations `diffci init` sets up by default (2026-11-04): the MCP server in the project
3
11
  * configs Claude Code (`.mcp.json`) and Cursor (`.cursor/mcp.json`) read, and the diffci-verify skill
@@ -19,5 +27,15 @@ export declare function mcpServerEntry(version: string): {
19
27
  export declare function writeMcpConfig(repoPath: string, relativePath: string, version: string, force: boolean): string;
20
28
  /** Kept identical to integrations/agent-plugin/skills/diffci-verify/SKILL.md (tested). */
21
29
  export declare const DIFFCI_VERIFY_SKILL = "---\nname: diffci-verify\ndescription: Select and verify affected tests after editing code in a local Git repository, using DiffCI MCP tools or the DiffCI CLI before reporting the change ready.\n---\n\nPass the absolute path of the edited repository as `repo` on every tool call.\n\nUse `diffci_changed_files` to inspect staged, unstaged, and non-ignored untracked\nchanges. Use `diffci_select_tests` or `diffci_explain_selection` when you need the\naffected-test plan, command, or reasons for full fallback. These tools run no tests;\ntheir counts describe test files, not passing test cases. A plan is not verification.\n\nBefore reporting an edited change ready, call `diffci_run_affected_tests`. It\nrecomputes the selection and verifies the current snapshot. Accept a passing result\nonly when `safe_to_continue` is true and `snapshot.unchanged` is true. After further\nedits, rerun verification. For a clean committed change, use `diffci_verify` with the\nintended base/head range instead; no uncommitted changes does not mean the commit\nhas been tested.\n\nIf MCP is unavailable, use the installed CLI:\n\n```bash\ndiffci verify --changed --repo /absolute/path/to/repository --json\n```\n\nIf DiffCI is not installed, use `npx \"@diffci.com/diffci@latest\" verify --changed`\nwith the same repo and JSON flags. On blocked analysis or installation failure,\nrun the repository's normal verification and report the limitation. On a test\nfailure, fix the cause and rerun. On snapshot changes from generated files, inspect\nthe files and rerun for that snapshot.\n\nReport executed command, selection scope (affected or full fallback), test-file\ncounts, outcome, and any outstanding required checks. Never infer passed suites,\ntest cases, skipped CI jobs, or measured savings from selection counts. Required\nproject CI stays authoritative.\n";
30
+ /**
31
+ * Stop hooks that run `diffci agent-stop` when the agent ends a turn (agent-stop.ts, 2026-11-06), in each
32
+ * agent's project hook file. Claude Code and Codex share one shape (`Stop` > group > handlers); Cursor has
33
+ * its own (`version: 1`, `stop` > handlers). A hook is DiffCI's when its command runs `agent-stop` from
34
+ * the DiffCI package; those are replaced, every other hook is kept.
35
+ */
36
+ export declare const AGENT_HOOK_PATHS: Record<"claude" | "codex" | "cursor", string>;
37
+ /** Seconds the agent waits for the hook; verify's own timeout stays below it (cli.ts, agent-stop). */
38
+ export declare const AGENT_HOOK_TIMEOUT_SECONDS = 1200;
39
+ export declare function writeAgentStopHook(repoPath: string, agent: "claude" | "codex" | "cursor", launcher: string): string;
22
40
  /** A skill file DiffCI wrote is recognised by its frontmatter name and updated; any other file is kept. */
23
41
  export declare function writeSkill(repoPath: string, force: boolean): string;
@@ -1,5 +1,28 @@
1
+ import { spawnSync } from "node:child_process";
1
2
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
3
  import { dirname, join } from "node:path";
4
+ /**
5
+ * Which of the files init wrote or updated Git would leave out of a commit, from init's own result lines
6
+ * ("wrote <path> ...", "updated <path> ..."). Paths under .git (the pre-push hook) are never versioned.
7
+ *
8
+ * WHY (2026-11-06). DentalPresence ignored all of `/.claude/`, so init reported "wrote
9
+ * .claude/skills/diffci-verify/SKILL.md" for a skill no other checkout or agent session would ever get.
10
+ */
11
+ export function ignoredWrites(repoPath, results) {
12
+ const paths = results
13
+ .map((result) => /^(?:wrote|updated) (\S+)/.exec(result)?.[1])
14
+ .filter((path) => path !== undefined && !path.startsWith(".git/"));
15
+ if (paths.length === 0)
16
+ return [];
17
+ const result = spawnSync("git", ["check-ignore", "--stdin", "-z"], {
18
+ cwd: repoPath,
19
+ input: `${paths.join("\0")}\0`,
20
+ encoding: "utf8",
21
+ windowsHide: true,
22
+ });
23
+ // Exit 1 means nothing is ignored; anything else (not a repository) leaves nothing to warn about.
24
+ return result.status === 0 ? result.stdout.split("\0").filter(Boolean) : [];
25
+ }
3
26
  /**
4
27
  * Agent integrations `diffci init` sets up by default (2026-11-04): the MCP server in the project
5
28
  * configs Claude Code (`.mcp.json`) and Cursor (`.cursor/mcp.json`) read, and the diffci-verify skill
@@ -92,6 +115,60 @@ counts, outcome, and any outstanding required checks. Never infer passed suites,
92
115
  test cases, skipped CI jobs, or measured savings from selection counts. Required
93
116
  project CI stays authoritative.
94
117
  `;
118
+ /**
119
+ * Stop hooks that run `diffci agent-stop` when the agent ends a turn (agent-stop.ts, 2026-11-06), in each
120
+ * agent's project hook file. Claude Code and Codex share one shape (`Stop` > group > handlers); Cursor has
121
+ * its own (`version: 1`, `stop` > handlers). A hook is DiffCI's when its command runs `agent-stop` from
122
+ * the DiffCI package; those are replaced, every other hook is kept.
123
+ */
124
+ export const AGENT_HOOK_PATHS = {
125
+ claude: ".claude/settings.json",
126
+ codex: ".codex/hooks.json",
127
+ cursor: ".cursor/hooks.json",
128
+ };
129
+ /** Seconds the agent waits for the hook; verify's own timeout stays below it (cli.ts, agent-stop). */
130
+ export const AGENT_HOOK_TIMEOUT_SECONDS = 1200;
131
+ function isDiffciHook(command) {
132
+ return typeof command === "string" && /\bagent-stop\b/.test(command) && /diffci/.test(command);
133
+ }
134
+ export function writeAgentStopHook(repoPath, agent, launcher) {
135
+ const relativePath = AGENT_HOOK_PATHS[agent];
136
+ const absolutePath = join(repoPath, relativePath);
137
+ const command = `${launcher} agent-stop --agent ${agent}`;
138
+ let config = {};
139
+ let existing;
140
+ if (existsSync(absolutePath)) {
141
+ existing = readFileSync(absolutePath, "utf8");
142
+ try {
143
+ const parsed = JSON.parse(existing);
144
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
145
+ throw new Error("not an object");
146
+ config = parsed;
147
+ }
148
+ catch {
149
+ return `kept ${relativePath} (not a JSON object; add the DiffCI stop hook by hand)`;
150
+ }
151
+ }
152
+ const hooks = config.hooks && typeof config.hooks === "object" && !Array.isArray(config.hooks) ? config.hooks : {};
153
+ if (agent === "cursor") {
154
+ const stop = Array.isArray(hooks.stop) ? hooks.stop.filter((entry) => !isDiffciHook(entry?.command)) : [];
155
+ config = { ...config, version: typeof config.version === "number" ? config.version : 1, hooks: { ...hooks, stop: [...stop, { command, loop_limit: 3 }] } };
156
+ }
157
+ else {
158
+ const groups = (Array.isArray(hooks.Stop) ? hooks.Stop : []).flatMap((group) => {
159
+ const handlers = Array.isArray(group?.hooks) ? group.hooks : [];
160
+ const kept = handlers.filter((handler) => !isDiffciHook(handler?.command));
161
+ return kept.length === 0 && handlers.length > 0 ? [] : [kept.length === handlers.length ? group : { ...group, hooks: kept }];
162
+ });
163
+ config = { ...config, hooks: { ...hooks, Stop: [...groups, { hooks: [{ type: "command", command, timeout: AGENT_HOOK_TIMEOUT_SECONDS }] }] } };
164
+ }
165
+ const next = `${JSON.stringify(config, null, 2)}\n`;
166
+ if (next === existing)
167
+ return `kept ${relativePath} (DiffCI stop hook current)`;
168
+ mkdirSync(dirname(absolutePath), { recursive: true });
169
+ writeFileSync(absolutePath, next, "utf8");
170
+ return `${existing === undefined ? "wrote" : "updated"} ${relativePath} (DiffCI stop hook)`;
171
+ }
95
172
  /** A skill file DiffCI wrote is recognised by its frontmatter name and updated; any other file is kept. */
96
173
  export function writeSkill(repoPath, force) {
97
174
  const absolutePath = join(repoPath, SKILL_PATH);
@@ -0,0 +1,52 @@
1
+ import type { VerificationReport } from "./verify.js";
2
+ /**
3
+ * Verify when an agent finishes a turn (2026-11-06).
4
+ *
5
+ * WHY. Agents called DiffCI in 24 of over 1,500 test commands on DentalPresence. An instruction to run
6
+ * verify is advice an agent can skip; a hook on the end of its turn is not. The agent finds out what its
7
+ * change broke before it tells anyone the work is done.
8
+ *
9
+ * WHAT. `diffci agent-stop --agent claude|codex|cursor` is the command the agent's stop hook runs
10
+ * (Claude Code `Stop` in .claude/settings.json, Codex `Stop` in .codex/hooks.json, Cursor `stop` in
11
+ * .cursor/hooks.json; `diffci init` installs them). It reads the hook's JSON from stdin, verifies the
12
+ * uncommitted changes, and:
13
+ * - passes quietly when nothing changed or verification passed;
14
+ * - when tests or checks fail, asks the agent to continue with the failures as the reason (Claude Code
15
+ * and Codex: `{"decision": "block", "reason"}`; Cursor: `{"followup_message"}`);
16
+ * - never holds the agent when verification could not run (blocked analysis, no command): that is
17
+ * reported to the person, not turned into work for the agent;
18
+ * - hands back to the person after DIFFCI_AGENT_HOOK_MAX failed attempts in one session (default 3),
19
+ * counted in .git/diffci/agent-hook.json and reset by a pass, on top of the agents' own loop limits.
20
+ * DIFFCI_AGENT_HOOK=0 turns it off. Repeats on an unchanged tree are instant through result reuse.
21
+ */
22
+ export type HookAgent = "claude" | "codex" | "cursor";
23
+ export declare const HOOK_AGENTS: readonly HookAgent[];
24
+ export declare const DEFAULT_MAX_ATTEMPTS = 3;
25
+ export interface StopPayload {
26
+ session_id?: string;
27
+ conversation_id?: string;
28
+ cwd?: string;
29
+ workspace_roots?: string[];
30
+ stop_hook_active?: boolean;
31
+ loop_count?: number;
32
+ status?: string;
33
+ }
34
+ export declare function parseStopPayload(text: string): StopPayload;
35
+ /** The repository the agent worked in: the top level of the hook's cwd, the agent's project directory, or ours. */
36
+ export declare function stopRepoPath(payload: StopPayload, env: Record<string, string | undefined>, fallback: string): string;
37
+ /** Failed attempts so far in this session, and a writer for the new count (sessions older than a day are dropped). */
38
+ export declare function sessionAttempts(repoPath: string, payload: StopPayload): {
39
+ failures: number;
40
+ record(failures: number): void;
41
+ };
42
+ export interface StopDecision {
43
+ /** What the hook prints on stdout (always JSON: Codex rejects plain text on exit 0). */
44
+ stdout: string;
45
+ /** Failed attempts to record for the session after this decision. */
46
+ failures: number;
47
+ }
48
+ /**
49
+ * The hook's answer for one verification. `report` is undefined when nothing could be verified at all.
50
+ */
51
+ export declare function decideStop(agent: HookAgent, report: VerificationReport | undefined, failuresSoFar: number, max: number): StopDecision;
52
+ export declare function maxAttempts(env: Record<string, string | undefined>): number;
@@ -0,0 +1,101 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { outcomeLogPath } from "./outcome-log.js";
5
+ export const HOOK_AGENTS = ["claude", "codex", "cursor"];
6
+ export const DEFAULT_MAX_ATTEMPTS = 3;
7
+ export function parseStopPayload(text) {
8
+ try {
9
+ const parsed = JSON.parse(text);
10
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
11
+ }
12
+ catch {
13
+ return {};
14
+ }
15
+ }
16
+ /** The repository the agent worked in: the top level of the hook's cwd, the agent's project directory, or ours. */
17
+ export function stopRepoPath(payload, env, fallback) {
18
+ const start = payload.cwd ?? payload.workspace_roots?.[0] ?? env.CLAUDE_PROJECT_DIR ?? env.CURSOR_PROJECT_DIR ?? fallback;
19
+ try {
20
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd: start, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true }).trim() || start;
21
+ }
22
+ catch {
23
+ return start;
24
+ }
25
+ }
26
+ function sessionKey(payload) {
27
+ return payload.session_id ?? payload.conversation_id ?? "unknown";
28
+ }
29
+ function attemptsPath(repoPath) {
30
+ const log = outcomeLogPath(repoPath);
31
+ return log ? join(dirname(log), "agent-hook.json") : undefined;
32
+ }
33
+ function readAttempts(path) {
34
+ if (!path || !existsSync(path))
35
+ return {};
36
+ try {
37
+ return JSON.parse(readFileSync(path, "utf8"));
38
+ }
39
+ catch {
40
+ return {};
41
+ }
42
+ }
43
+ /** Failed attempts so far in this session, and a writer for the new count (sessions older than a day are dropped). */
44
+ export function sessionAttempts(repoPath, payload) {
45
+ const path = attemptsPath(repoPath);
46
+ const key = sessionKey(payload);
47
+ const log = readAttempts(path);
48
+ return {
49
+ failures: log[key]?.failures ?? 0,
50
+ record(failures) {
51
+ if (!path)
52
+ return;
53
+ const now = Date.now();
54
+ const kept = Object.fromEntries(Object.entries(log).filter(([id, entry]) => id !== key && now - Date.parse(entry.at) < 24 * 60 * 60 * 1000));
55
+ const next = failures > 0 ? { ...kept, [key]: { failures, at: new Date(now).toISOString() } } : kept;
56
+ try {
57
+ mkdirSync(dirname(path), { recursive: true });
58
+ writeFileSync(path, `${JSON.stringify(next)}\n`, "utf8");
59
+ }
60
+ catch { }
61
+ },
62
+ };
63
+ }
64
+ function failureReason(report, attempt, max) {
65
+ const failing = report.execution?.failingTests ?? [];
66
+ const lines = [
67
+ `DiffCI verified your uncommitted changes and they fail (attempt ${attempt} of ${max} this session): ${report.reason}.`,
68
+ ...(failing.length ? [`Failing tests: ${failing.slice(0, 10).join("; ")}${failing.length > 10 ? `; and ${failing.length - 10} more` : ""}.`] : []),
69
+ ...(report.command ? [`DiffCI ran: ${report.command}`] : []),
70
+ "Fix what broke, then finish. DiffCI verifies again when you stop; `diffci verify --changed` reproduces this run.",
71
+ ];
72
+ return lines.join("\n");
73
+ }
74
+ /**
75
+ * The hook's answer for one verification. `report` is undefined when nothing could be verified at all.
76
+ */
77
+ export function decideStop(agent, report, failuresSoFar, max) {
78
+ const allow = (message) => ({
79
+ stdout: JSON.stringify(message && agent !== "cursor" ? { systemMessage: message } : {}),
80
+ failures: 0,
81
+ });
82
+ if (!report)
83
+ return allow("DiffCI could not verify this turn's changes.");
84
+ if (report.verification === "passed")
85
+ return { ...allow(), failures: 0 };
86
+ if (report.verification === "blocked") {
87
+ return { ...allow(`DiffCI could not verify this turn's changes: ${report.reason}`), failures: failuresSoFar };
88
+ }
89
+ if (failuresSoFar >= max) {
90
+ return { ...allow(`DiffCI verification still fails after ${max} attempt(s) this session; over to you: ${report.reason}`), failures: failuresSoFar };
91
+ }
92
+ const reason = failureReason(report, failuresSoFar + 1, max);
93
+ return {
94
+ stdout: JSON.stringify(agent === "cursor" ? { followup_message: reason } : { decision: "block", reason }),
95
+ failures: failuresSoFar + 1,
96
+ };
97
+ }
98
+ export function maxAttempts(env) {
99
+ const value = Number(env.DIFFCI_AGENT_HOOK_MAX);
100
+ return Number.isInteger(value) && value >= 0 ? value : DEFAULT_MAX_ATTEMPTS;
101
+ }
@@ -37,15 +37,17 @@ import { resolveObservationAgent } from "./agent-identity.js";
37
37
  import { inferFullCommand, inferComparableSelectedCommand, inferWorkspaceComparison } from "./full-command.js";
38
38
  import { addDiffciPackageScripts, detectPackageManager, installDiffci } from "./install.js";
39
39
  import { hookCommand, installPrePushHook, isGitRepository } from "./hook.js";
40
- import { MCP_CONFIG_PATHS, SKILL_PATH, writeMcpConfig, writeSkill } from "./agent-setup.js";
40
+ import { AGENT_HOOK_TIMEOUT_SECONDS, ignoredWrites, MCP_CONFIG_PATHS, SKILL_PATH, writeAgentStopHook, writeMcpConfig, writeSkill } from "./agent-setup.js";
41
41
  import { submitObservation } from "./submit.js";
42
42
  import { configureGraphCache } from "./shared-graph-cache.js";
43
43
  import { GraphCache } from "@diffci.com/core/cache/graph-cache";
44
44
  import { githubDeliveryWarning } from "./delivery-warning.js";
45
+ import { formatJobSummary } from "./job-summary.js";
45
46
  import { configureTelemetry, readTelemetryPreference, recordUsage } from "./telemetry.js";
46
47
  import { formatFeedbackPrompt, markFeedbackPromptShown, shouldShowFeedbackPrompt } from "./feedback-prompt.js";
47
48
  import { detectSpecificationConflicts, readSpecificationFile } from "./spec-conflicts.js";
48
49
  import { formatVerificationSummary, verificationExitCode, verifyChanged, verifyRange } from "./verify.js";
50
+ import { decideStop, HOOK_AGENTS, maxAttempts, parseStopPayload, sessionAttempts, stopRepoPath } from "./agent-stop.js";
49
51
  import { formatGateSummary, gateExitCode, planGate, runGate } from "./gate.js";
50
52
  import { formatGrowthPrompt, formatVerifySavingsSummary, measureCommand, runVerifySavings, writeVerifySavingsReport } from "./verify-savings.js";
51
53
  import { auditEnforceWorkflows, auditWorkflows, isNonInterfering } from "./workflow-guard.js";
@@ -117,7 +119,7 @@ What this does:
117
119
  New files the run writes are listed in the receipt (snapshot.written_during_verification) and do not block it;
118
120
  consider adding them to .gitignore. If verification changes existing files, review those changes and rerun DiffCI
119
121
  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.
122
+ 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
123
  Use \`observe --no-send\` when analysis without test execution is needed.
122
124
 
123
125
  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 +301,11 @@ function runInit(flags, env) {
299
301
  skipped.push(`skipped ${SKILL_PATH} (--no-skill)`);
300
302
  else
301
303
  writes.push(writeSkill(repoPath, force));
304
+ if (flags["no-agent-hooks"] === true)
305
+ skipped.push("skipped the agent stop hooks (--no-agent-hooks)");
306
+ else
307
+ for (const agent of HOOK_AGENTS)
308
+ writes.push(writeAgentStopHook(repoPath, agent, hookCommand(manager, identity.version)));
302
309
  if (flags["no-hook"] === true)
303
310
  skipped.push("skipped the pre-push hook (--no-hook)");
304
311
  else if (!isGitRepository(repoPath))
@@ -314,6 +321,13 @@ function runInit(flags, env) {
314
321
  console.log(" skipped package installation (pass --install to add an exact dev dependency)");
315
322
  for (const line of skipped)
316
323
  console.log(` ${line}`);
324
+ const ignored = ignoredWrites(repoPath, writes);
325
+ if (ignored.length > 0) {
326
+ 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"}:`);
327
+ for (const path of ignored)
328
+ console.log(` ${path}`);
329
+ console.log("Add an exception (for example !/.claude/skills/ after /.claude/*) or commit with git add -f.");
330
+ }
317
331
  if (!includeWorkflow)
318
332
  console.log(" skipped .github/workflows/diffci.yml (pass --workflow to add it)");
319
333
  if (!includeVerificationWorkflow)
@@ -335,6 +349,54 @@ function runMcp() {
335
349
  throw result.error;
336
350
  return 0;
337
351
  }
352
+ async function runAgentStopCommand(flags, env) {
353
+ const agent = stringFlag(flags, "agent");
354
+ if (!agent || !HOOK_AGENTS.includes(agent)) {
355
+ console.error(`diffci agent-stop needs --agent ${HOOK_AGENTS.join("|")}`);
356
+ return 2;
357
+ }
358
+ // Every exit is 0 with JSON on stdout: a hook that fails would neither stop the agent nor tell it why.
359
+ if (env.DIFFCI_AGENT_HOOK === "0") {
360
+ console.log("{}");
361
+ return 0;
362
+ }
363
+ const payload = parseStopPayload(await readStdin());
364
+ const repoPath = resolve(stopRepoPath(payload, env, process.cwd()));
365
+ const attempts = sessionAttempts(repoPath, payload);
366
+ let report;
367
+ try {
368
+ const identity = observerIdentity();
369
+ report = await verifyChanged({
370
+ repoPath,
371
+ env: env,
372
+ version: identity.version,
373
+ engineSha: identity.sha,
374
+ // Below the hook's own timeout (agent-setup.ts), so the hook always answers.
375
+ timeoutMs: (AGENT_HOOK_TIMEOUT_SECONDS - 120) * 1000,
376
+ tailBytes: 12_000,
377
+ skipChecks: env.DIFFCI_CHECKS === "0",
378
+ });
379
+ appendOutcome(repoPath, report, env);
380
+ }
381
+ catch {
382
+ report = undefined;
383
+ }
384
+ const decision = decideStop(agent, report, attempts.failures, maxAttempts(env));
385
+ attempts.record(decision.failures);
386
+ console.log(decision.stdout);
387
+ return 0;
388
+ }
389
+ function readStdin() {
390
+ if (process.stdin.isTTY)
391
+ return Promise.resolve("");
392
+ return new Promise((resolveText) => {
393
+ let text = "";
394
+ process.stdin.setEncoding("utf8");
395
+ process.stdin.on("data", (chunk) => { text += chunk; });
396
+ process.stdin.on("end", () => resolveText(text));
397
+ process.stdin.on("error", () => resolveText(text));
398
+ });
399
+ }
338
400
  async function runVerifyCommand(flags, env) {
339
401
  const changed = flags.changed === true;
340
402
  if (changed && (flags.base !== undefined || flags.head !== undefined)) {
@@ -801,7 +863,7 @@ async function runObserve(flags, env) {
801
863
  // says the same thing the report says, including when the answer is "refused" or "not sent".
802
864
  if (env.GITHUB_STEP_SUMMARY) {
803
865
  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" });
866
+ writeFileSync(env.GITHUB_STEP_SUMMARY, formatJobSummary(report, summary, delivery), { flag: "a" });
805
867
  }
806
868
  catch {
807
869
  // Losing the summary is cosmetic; the report on disk is the record.
@@ -1153,7 +1215,9 @@ Open-source engine: https://github.com/DiffCI/core
1153
1215
  Pilot a repository: https://diffci.com/#pilot
1154
1216
 
1155
1217
  Usage:
1156
- diffci init [--repo <path>] [--workflow] [--verification-workflow] [--install] [--no-hook] [--no-mcp] [--no-skill] [--force]
1218
+ diffci init [--repo <path>] [--workflow] [--verification-workflow] [--install] [--no-hook] [--no-mcp] [--no-skill]
1219
+ [--no-agent-hooks] [--force]
1220
+ diffci agent-stop --agent claude|codex|cursor (run by the agent stop hooks init installs; reads the hook JSON on stdin)
1157
1221
  diffci mcp
1158
1222
  diffci verify [--changed | --base <sha> --head <sha>] [--policy enforce] [--repo <path>] [--out <file>] [--json]
1159
1223
  [--redact-paths] [--timeout-ms <ms>] [--baseline-on-failure] [--no-checks | --checks]
@@ -1189,8 +1253,11 @@ Usage:
1189
1253
 
1190
1254
  init writes AGENTS.md, CLAUDE.md, Cursor rules, Copilot instructions, and diffci.config.json. It also
1191
1255
  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,
1256
+ servers, adds the diffci-verify skill to .claude/skills, installs the pre-push hook, and adds stop hooks
1257
+ (.claude/settings.json, .codex/hooks.json, .cursor/hooks.json) that run diffci agent-stop when an agent ends a
1258
+ turn: it verifies the uncommitted changes and, when tests or checks fail, asks the agent to fix them before
1259
+ finishing, at most DIFFCI_AGENT_HOOK_MAX times a session (default 3; DIFFCI_AGENT_HOOK=0 turns it off).
1260
+ --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
1261
  or Bun, installs this DiffCI version as an exact dev dependency, updates the manager's lockfile,
1195
1262
  and adds diffci:verify, diffci:check, and diffci:observe package scripts without replacing existing scripts.
1196
1263
  --verification-workflow adds a blocking GitHub check that uploads a commit-bound verification receipt.
@@ -1289,6 +1356,9 @@ async function main() {
1289
1356
  case "verify":
1290
1357
  process.exitCode = await runVerifyCommand(flags, env);
1291
1358
  return;
1359
+ case "agent-stop":
1360
+ process.exitCode = await runAgentStopCommand(flags, env);
1361
+ return;
1292
1362
  case "check":
1293
1363
  process.exitCode = await runCheck(flags, env);
1294
1364
  maybeShowFeedbackPrompt(flags, env);
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The pre-push hook `diffci init --hook` installs (2026-10-28).
2
+ * The pre-push hook `diffci init` installs (2026-10-28; on by default since 0.3.24).
3
3
  *
4
4
  * WHY. In 449 agent sessions on DentalPresence, agents ran DiffCI in 24 of over 1,500 test commands:
5
5
  * they picked test files themselves (928) or ran the whole suite (282), and 104 pushes then failed the
@@ -2,7 +2,7 @@ import { execFileSync } from "node:child_process";
2
2
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { dirname, isAbsolute, join, relative } from "node:path";
4
4
  /**
5
- * The pre-push hook `diffci init --hook` installs (2026-10-28).
5
+ * The pre-push hook `diffci init` installs (2026-10-28; on by default since 0.3.24).
6
6
  *
7
7
  * WHY. In 449 agent sessions on DentalPresence, agents ran DiffCI in 24 of over 1,500 test commands:
8
8
  * they picked test files themselves (928) or ran the whole suite (282), and 104 pushes then failed the
@@ -0,0 +1,7 @@
1
+ import type { ObservationReport } from "./report.js";
2
+ /**
3
+ * The GitHub job summary for `diffci observe`: the place most people will ever read a report, so it
4
+ * leads with the answer (what this change affects) and keeps the full text summary one click away.
5
+ * It claims nothing the report doesn't: no savings, and every fallback and refusal says so.
6
+ */
7
+ export declare function formatJobSummary(report: ObservationReport, textSummary: string, delivery?: string): string;
@@ -0,0 +1,78 @@
1
+ /** Selected tests listed by name before the rest collapse into a count. */
2
+ const MAX_LISTED_TESTS = 20;
3
+ /** Inline code that survives any path: no backticks to close it early, no pipes to split a table cell. */
4
+ function code(text) {
5
+ return `\`${text.replace(/`/g, "'").replace(/\|/g, "\\|")}\``;
6
+ }
7
+ function plural(count, one, many = `${one}s`) {
8
+ return `${count} ${count === 1 ? one : many}`;
9
+ }
10
+ /** `DIRECT_IMPORT` reads as "direct import"; prose reasons pass through. */
11
+ function readableReason(reason) {
12
+ return /^[A-Z0-9_]+$/.test(reason) ? reason.toLowerCase().replace(/_/g, " ") : reason;
13
+ }
14
+ /**
15
+ * The GitHub job summary for `diffci observe`: the place most people will ever read a report, so it
16
+ * leads with the answer (what this change affects) and keeps the full text summary one click away.
17
+ * It claims nothing the report doesn't: no savings, and every fallback and refusal says so.
18
+ */
19
+ export function formatJobSummary(report, textSummary, delivery) {
20
+ const lines = ["### DiffCI: what this change affects", ""];
21
+ const result = report.result;
22
+ if (report.status !== "OBSERVED" || !result) {
23
+ lines.push(`**No plan for this change** (${report.status.toLowerCase()} at ${report.stage}).`);
24
+ if (report.reason)
25
+ lines.push("", report.reason);
26
+ }
27
+ else if (result.mode === "FULL") {
28
+ lines.push(`**The full test suite is needed** for ${plural(result.changedFileCount, "changed file")}: DiffCI could not prove which of the ${plural(result.totalTestCount, "test file")} this change leaves untouched, so it would run them all.`);
29
+ if (result.fallbackReasons.length > 0) {
30
+ lines.push("", "Why:");
31
+ for (const reason of result.fallbackReasons)
32
+ lines.push(`- ${reason}`);
33
+ }
34
+ }
35
+ else {
36
+ const selected = result.selectedTests.length;
37
+ lines.push(`**${selected} of ${plural(result.totalTestCount, "test file")}** ${selected === 1 ? "is" : "are"} affected by ${plural(result.changedFileCount, "changed file")}.`);
38
+ const baseline = result.pathBaseline.mode === "FULL"
39
+ ? "everything"
40
+ : plural(result.pathBaseline.selectedTestCount, "test file");
41
+ lines.push(`A simple path-rule CI would have run ${baseline}.`);
42
+ if (selected > 0) {
43
+ const reasons = result.selectionReasons ?? {};
44
+ lines.push("", `<details><summary>Why these ${plural(selected, "test")}</summary>`, "");
45
+ lines.push("| Test | Because |", "| --- | --- |");
46
+ for (const test of result.selectedTests.slice(0, MAX_LISTED_TESTS)) {
47
+ const why = reasons[test];
48
+ const because = why
49
+ ? `${readableReason(why.reason)}${why.changed_file ? ` from ${code(why.changed_file)}` : ""}`
50
+ : "affected by the change";
51
+ lines.push(`| ${code(test)} | ${because} |`);
52
+ }
53
+ if (selected > MAX_LISTED_TESTS)
54
+ lines.push(`| and ${selected - MAX_LISTED_TESTS} more | see the report artifact |`);
55
+ lines.push("", "</details>");
56
+ }
57
+ if (result.proposedCommands.length > 0) {
58
+ lines.push("", "Would run:", "");
59
+ for (const command of result.proposedCommands)
60
+ lines.push("```", command, "```");
61
+ }
62
+ else if (result.commandRefusalReason) {
63
+ lines.push("", `No runnable command: ${result.commandRefusalReason}`);
64
+ }
65
+ }
66
+ // A broken promise of non-interference is the one thing that must never hide in a collapsed block.
67
+ const blocking = report.nonInterference.workflowFindings.filter((finding) => finding.severity === "BLOCKING");
68
+ if (!report.nonInterference.worktreeUnchanged) {
69
+ lines.push("", "> [!WARNING]", "> The working tree changed while DiffCI observed it. Please report this at https://github.com/DiffCI/core/issues.");
70
+ }
71
+ if (blocking.length > 0) {
72
+ lines.push("", "> [!WARNING]", `> ${plural(blocking.length, "blocking workflow finding")}: this installation can affect other jobs. Details are in the full report below.`);
73
+ }
74
+ if (delivery?.startsWith("not sent"))
75
+ lines.push("", `Delivery: ${delivery}`);
76
+ lines.push("", "<details><summary>Full report</summary>", "", "```", `${textSummary}${delivery ? `\n delivery: ${delivery}` : ""}`, "```", "", "</details>", "", "<sub>Observation only: DiffCI ran, skipped and changed nothing in this workflow. [DiffCI](https://github.com/DiffCI/core) is open source (MIT) and tells AI coding agents what their change breaks.</sub>", "");
77
+ return lines.join("\n");
78
+ }
@@ -52,6 +52,8 @@ export interface VerificationReport {
52
52
  written_during_verification?: string[];
53
53
  /** Files that existed before the run and changed during it, at most 20. Their presence blocks the verdict. */
54
54
  changed_during_verification?: SnapshotChange[];
55
+ /** Commit-range only: checked-out files that differ from HEAD only by CRLF line endings, at most 20. */
56
+ line_ending_only_changes?: string[];
55
57
  };
56
58
  analysis: {
57
59
  status: "not_needed" | ObservationReport["status"];
@@ -13,7 +13,7 @@ import { outcomeLogPath, readOutcomes, reusablePass } from "./outcome-log.js";
13
13
  import { likelyFailures, rankTests, testHistory } from "./test-ranking.js";
14
14
  import { assignShards } from "./test-shards.js";
15
15
  import { mergeTestFileResults } from "./test-results.js";
16
- import { captureWorkingTreeSnapshot, snapshotChanges } from "./working-tree.js";
16
+ import { captureWorkingTreeSnapshot, lineEndingOnlyChanges, snapshotChanges } from "./working-tree.js";
17
17
  export const VERIFICATION_SCHEMA = "diffci.verification.v1";
18
18
  function receiptRange(range) {
19
19
  if (!range)
@@ -36,6 +36,7 @@ function baseReport(snapshot, scope, range) {
36
36
  base_sha: snapshot.baseSha,
37
37
  before_tree_sha: snapshot.treeSha,
38
38
  unchanged: false,
39
+ ...(snapshot.lineEndingOnly ? { line_ending_only_changes: snapshot.lineEndingOnly.slice(0, 20) } : {}),
39
40
  },
40
41
  };
41
42
  }
@@ -416,7 +417,11 @@ async function verifyCommitRange(options) {
416
417
  return blocked(unknownSnapshot(), "commit-range", message, { status: "ERROR", stage: "context", fallback_reasons: [], error: message });
417
418
  }
418
419
  if (before.changed) {
419
- return blocked(before, "commit-range", "commit-range verification requires a clean checkout; use verify --changed for uncommitted changes", { status: "not_needed", fallback_reasons: [] });
420
+ const lineEndingOnly = lineEndingOnlyChanges(repoPath, before);
421
+ if (!lineEndingOnly) {
422
+ return blocked(before, "commit-range", "commit-range verification requires a clean checkout; use verify --changed for uncommitted changes", { status: "not_needed", fallback_reasons: [] });
423
+ }
424
+ before = { ...before, lineEndingOnly };
420
425
  }
421
426
  const temporaryDirectory = mkdtempSync(join(tmpdir(), "diffci-verify-"));
422
427
  try {
@@ -461,6 +466,10 @@ export function formatVerificationSummary(report) {
461
466
  ];
462
467
  if (report.commit_range)
463
468
  lines.splice(2, 0, ` range: ${report.commit_range.base_sha.slice(0, 12)}..${report.commit_range.head_sha.slice(0, 12)}`);
469
+ const lineEndings = report.snapshot.line_ending_only_changes;
470
+ if (lineEndings?.length) {
471
+ lines.push(` line endings only: ${lineEndings.length}${lineEndings.length === 20 ? "+" : ""} checked-out file(s) differ from HEAD only by CRLF (${lineEndings.slice(0, 3).join(", ")}${lineEndings.length > 3 ? ", ..." : ""}); verified as checked out`);
472
+ }
464
473
  const written = report.snapshot.written_during_verification;
465
474
  if (written?.length)
466
475
  lines.push(` written by the run (not in .gitignore): ${written.slice(0, 5).join(", ")}${written.length > 5 ? ", ..." : ""}`);
@@ -6,7 +6,20 @@ export interface WorkingTreeSnapshot {
6
6
  /** Unreachable commit used only so the existing commit-range analyzer can inspect the tree. */
7
7
  commitSha: string;
8
8
  changed: boolean;
9
+ /** Set when every difference from HEAD is a CRLF checkout of an LF-committed file (see lineEndingOnlyChanges). */
10
+ lineEndingOnly?: string[];
9
11
  }
12
+ /**
13
+ * The paths, when every difference between HEAD and the snapshot is only CRLF line endings on files
14
+ * committed with LF; otherwise undefined.
15
+ *
16
+ * WHY (2026-11-06). On DentalPresence the pre-push hook could not verify any push: 268 files had been
17
+ * checked out with CRLF under Git for Windows' system-wide `core.autocrlf=true` before the repository
18
+ * set it to false. `git status` called the checkout clean because its stat cache still matched, while
19
+ * the snapshot re-reads every file and saw 268 changes. Git's own view decides "clean" for the user, so
20
+ * a CRLF-only checkout is verified rather than blocked, and the receipt names the files.
21
+ */
22
+ export declare function lineEndingOnlyChanges(repoPathInput: string, snapshot: WorkingTreeSnapshot): string[] | undefined;
10
23
  /** One path that differs between two snapshots. A rename is a deletion plus an addition. */
11
24
  export interface SnapshotChange {
12
25
  path: string;
@@ -1,7 +1,46 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { mkdtempSync, rmSync } from "node:fs";
2
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join, resolve } from "node:path";
5
+ /**
6
+ * The paths, when every difference between HEAD and the snapshot is only CRLF line endings on files
7
+ * committed with LF; otherwise undefined.
8
+ *
9
+ * WHY (2026-11-06). On DentalPresence the pre-push hook could not verify any push: 268 files had been
10
+ * checked out with CRLF under Git for Windows' system-wide `core.autocrlf=true` before the repository
11
+ * set it to false. `git status` called the checkout clean because its stat cache still matched, while
12
+ * the snapshot re-reads every file and saw 268 changes. Git's own view decides "clean" for the user, so
13
+ * a CRLF-only checkout is verified rather than blocked, and the receipt names the files.
14
+ */
15
+ export function lineEndingOnlyChanges(repoPathInput, snapshot) {
16
+ const repoPath = resolve(repoPathInput);
17
+ const baseTreeSha = requireGit(repoPath, ["rev-parse", "--verify", `${snapshot.baseSha}^{tree}`], "could not resolve the snapshot base tree");
18
+ const changes = snapshotChanges(repoPath, baseTreeSha, snapshot.treeSha);
19
+ if (changes.length === 0 || changes.some((change) => change.status !== "modified"))
20
+ return undefined;
21
+ for (const change of changes) {
22
+ const committed = spawnSync("git", ["cat-file", "blob", `${baseTreeSha}:${change.path}`], {
23
+ cwd: repoPath,
24
+ maxBuffer: 256 * 1024 * 1024,
25
+ windowsHide: true,
26
+ });
27
+ if (committed.status !== 0 || committed.stdout.includes(13))
28
+ return undefined;
29
+ let checkedOut;
30
+ try {
31
+ checkedOut = readFileSync(join(repoPath, change.path));
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ if (!checkedOut.includes(13))
37
+ return undefined;
38
+ const normalized = Buffer.from(checkedOut.toString("latin1").replace(/\r\n/g, "\n"), "latin1");
39
+ if (!normalized.equals(committed.stdout))
40
+ return undefined;
41
+ }
42
+ return changes.map((change) => change.path);
43
+ }
5
44
  function runGit(repoPath, args, env, input) {
6
45
  const result = spawnSync("git", args, {
7
46
  cwd: repoPath,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diffci.com/diffci",
3
- "version": "0.3.31",
3
+ "version": "0.3.32",
4
4
  "description": "Fail-closed, change-aware verification for AI coding agents with conservative affected-test selection",
5
5
  "keywords": [
6
6
  "ci",