@diffci.com/diffci 0.3.30 → 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.
Files changed (44) hide show
  1. package/dist-client/src/client/agent-setup.d.ts +18 -0
  2. package/dist-client/src/client/agent-setup.js +77 -0
  3. package/dist-client/src/client/agent-stop.d.ts +52 -0
  4. package/dist-client/src/client/agent-stop.js +101 -0
  5. package/dist-client/src/client/cli.js +102 -7
  6. package/dist-client/src/client/command-batches.d.ts +5 -0
  7. package/dist-client/src/client/command-batches.js +9 -0
  8. package/dist-client/src/client/coverage-map.d.ts +46 -0
  9. package/dist-client/src/client/coverage-map.js +213 -0
  10. package/dist-client/src/client/failure-baseline.js +0 -0
  11. package/dist-client/src/client/hook.d.ts +1 -1
  12. package/dist-client/src/client/hook.js +1 -1
  13. package/dist-client/src/client/job-summary.d.ts +7 -0
  14. package/dist-client/src/client/job-summary.js +78 -0
  15. package/dist-client/src/client/observe.js +3 -0
  16. package/dist-client/src/client/report.d.ts +3 -0
  17. package/dist-client/src/client/verify.d.ts +6 -0
  18. package/dist-client/src/client/verify.js +43 -4
  19. package/dist-client/src/client/working-tree.d.ts +13 -0
  20. package/dist-client/src/client/working-tree.js +40 -1
  21. package/node_modules/@diffci.com/core/dist/git/git-diff.js +59 -0
  22. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  23. package/node_modules/@diffci.com/core/dist/git/types.d.ts +4 -0
  24. package/node_modules/@diffci.com/core/dist/planner/test-command.d.ts +11 -0
  25. package/node_modules/@diffci.com/core/dist/planner/test-command.js +65 -9
  26. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  27. package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +10 -1
  28. package/node_modules/@diffci.com/core/dist/repo/file-references.js +57 -16
  29. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  30. package/node_modules/@diffci.com/core/dist/repo/impact-types.d.ts +3 -0
  31. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +7 -0
  32. package/node_modules/@diffci.com/core/dist/repo/impact.js +43 -16
  33. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  34. package/node_modules/@diffci.com/core/dist/repo/test-fixture-ownership.d.ts +1 -1
  35. package/node_modules/@diffci.com/core/dist/repo/test-fixture-ownership.js +48 -5
  36. package/node_modules/@diffci.com/core/dist/repo/test-fixture-ownership.js.map +1 -1
  37. package/node_modules/@diffci.com/core/src/git/git-diff.ts +48 -0
  38. package/node_modules/@diffci.com/core/src/git/types.ts +4 -0
  39. package/node_modules/@diffci.com/core/src/planner/test-command.ts +54 -9
  40. package/node_modules/@diffci.com/core/src/repo/file-references.ts +60 -18
  41. package/node_modules/@diffci.com/core/src/repo/impact-types.ts +3 -0
  42. package/node_modules/@diffci.com/core/src/repo/impact.ts +39 -16
  43. package/node_modules/@diffci.com/core/src/repo/test-fixture-ownership.ts +39 -5
  44. package/package.json +2 -2
@@ -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";
@@ -54,6 +56,7 @@ import { observerIdentity } from "./package-identity.js";
54
56
  import { buildPilotWorkflow, diffciVerificationWorkflow, diffciWorkflow } from "./workflow-templates.js";
55
57
  import { buildMissReport, formatMissReportMarkdown, parseJunit } from "./enforce-misses.js";
56
58
  import { appendOutcome, formatOutcomeSummary, outcomeLogPath, readOutcomes, summarizeOutcomes } from "./outcome-log.js";
59
+ import { buildCoverageMap, formatCoverageRun } from "./coverage-map.js";
57
60
  import { confidenceCurve, formatConfidenceCurve } from "./test-ranking.js";
58
61
  import { parseShard, readTimings, timingsFromOutcomes } from "./test-shards.js";
59
62
  import { findReceipt, findWindowStart, inferRerunArgs, mergedPullRequests, MISS_REPORT_FILE, rerunFailingFiles, spawnRunner, } from "./enforce-misses-collect.js";
@@ -116,7 +119,7 @@ What this does:
116
119
  New files the run writes are listed in the receipt (snapshot.written_during_verification) and do not block it;
117
120
  consider adding them to .gitignore. If verification changes existing files, review those changes and rerun DiffCI
118
121
  so the new snapshot is verified.
119
- 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.
120
123
  Use \`observe --no-send\` when analysis without test execution is needed.
121
124
 
122
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.
@@ -298,6 +301,11 @@ function runInit(flags, env) {
298
301
  skipped.push(`skipped ${SKILL_PATH} (--no-skill)`);
299
302
  else
300
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)));
301
309
  if (flags["no-hook"] === true)
302
310
  skipped.push("skipped the pre-push hook (--no-hook)");
303
311
  else if (!isGitRepository(repoPath))
@@ -313,6 +321,13 @@ function runInit(flags, env) {
313
321
  console.log(" skipped package installation (pass --install to add an exact dev dependency)");
314
322
  for (const line of skipped)
315
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
+ }
316
331
  if (!includeWorkflow)
317
332
  console.log(" skipped .github/workflows/diffci.yml (pass --workflow to add it)");
318
333
  if (!includeVerificationWorkflow)
@@ -334,6 +349,54 @@ function runMcp() {
334
349
  throw result.error;
335
350
  return 0;
336
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
+ }
337
400
  async function runVerifyCommand(flags, env) {
338
401
  const changed = flags.changed === true;
339
402
  if (changed && (flags.base !== undefined || flags.head !== undefined)) {
@@ -392,6 +455,7 @@ async function runVerifyCommand(flags, env) {
392
455
  reuse: flags["no-reuse"] !== true && env.DIFFCI_REUSE !== "0",
393
456
  rank: flags["no-rank"] !== true && env.DIFFCI_RANK !== "0",
394
457
  failFast: flags["fail-fast"] === true,
458
+ coverage: flags["no-coverage"] !== true && env.DIFFCI_COVERAGE !== "0",
395
459
  ...(shard ? { shard } : {}),
396
460
  ...(timings ? { timings } : {}),
397
461
  };
@@ -419,6 +483,17 @@ async function runVerifyCommand(flags, env) {
419
483
  }
420
484
  return verificationExitCode(report);
421
485
  }
486
+ function runCoverageCommand(flags, env) {
487
+ const repoPath = resolve(stringFlag(flags, "repo") ?? env.GITHUB_WORKSPACE ?? process.cwd());
488
+ const command = stringFlag(flags, "command") ?? inferFullCommand(repoPath).command;
489
+ if (!command) {
490
+ console.error(`diffci coverage: no full test command could be inferred for ${repoPath}; pass --command`);
491
+ return 2;
492
+ }
493
+ const run = buildCoverageMap(repoPath, command, { timeoutMs: numberFlag(flags, "timeout-ms") ?? 60 * 60 * 1000 });
494
+ console.log(flags.json === true ? JSON.stringify({ ...(run.path ? { path: run.path } : {}), ...(run.error ? { error: run.error } : {}), exit_code: run.execution.exitCode, ...(run.map ? { tests: Object.keys(run.map.tests).length } : {}) }, null, 2) : formatCoverageRun(run));
495
+ return run.map ? 0 : 1;
496
+ }
422
497
  function runOutcomesCommand(flags, env) {
423
498
  const repoPath = resolve(stringFlag(flags, "repo") ?? env.GITHUB_WORKSPACE ?? process.cwd());
424
499
  const path = outcomeLogPath(repoPath);
@@ -559,6 +634,11 @@ function summarise(report, executionFollows = false) {
559
634
  lines.push(` graph: ${result.graph.nodes} nodes, confidence ${result.graph.effectiveConfidence ?? result.graph.confidence}`);
560
635
  if (result.fallbackReasons.length > 0) {
561
636
  lines.push(` fallback: ${result.fallbackReasons.join("; ")}`);
637
+ for (const [path, blockers] of Object.entries(result.fallbackDetails ?? {})) {
638
+ lines.push(` why ${path} is unknown:`);
639
+ for (const blocker of blockers)
640
+ lines.push(` - ${blocker}`);
641
+ }
562
642
  }
563
643
  for (const command of result.proposedCommands)
564
644
  lines.push(` would have run: ${command}`);
@@ -783,7 +863,7 @@ async function runObserve(flags, env) {
783
863
  // says the same thing the report says, including when the answer is "refused" or "not sent".
784
864
  if (env.GITHUB_STEP_SUMMARY) {
785
865
  try {
786
- 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" });
787
867
  }
788
868
  catch {
789
869
  // Losing the summary is cosmetic; the report on disk is the record.
@@ -1135,12 +1215,14 @@ Open-source engine: https://github.com/DiffCI/core
1135
1215
  Pilot a repository: https://diffci.com/#pilot
1136
1216
 
1137
1217
  Usage:
1138
- 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)
1139
1221
  diffci mcp
1140
1222
  diffci verify [--changed | --base <sha> --head <sha>] [--policy enforce] [--repo <path>] [--out <file>] [--json]
1141
1223
  [--redact-paths] [--timeout-ms <ms>] [--baseline-on-failure] [--no-checks | --checks]
1142
1224
  [--share-usage] [--no-send] [--no-log] [--no-reuse] [--no-rank] [--fail-fast]
1143
- [--shard <i/N> [--timings <file>]]
1225
+ [--shard <i/N> [--timings <file>]] [--no-coverage]
1144
1226
  diffci telemetry [--mode off|anonymous|installations] [--internal-usage]
1145
1227
  diffci check [--repo <path>] [--out <file>] [--base <sha> --head <sha>]
1146
1228
  [--redact-paths] [--json] [--quiet] [--fail-on-error] [--timeout-ms <ms>] [--share-usage]
@@ -1166,12 +1248,16 @@ Usage:
1166
1248
  diffci enforce-misses --junit <file> --out-dir <dir> [--repository <owner/name>] [--repo <path>]
1167
1249
  [--head <sha>] [--rerun-junit <file>] [--open-issue]
1168
1250
  diffci outcomes [--repo <path>] [--curve | --timings] [--json]
1251
+ diffci coverage [--repo <path>] [--command <cmd>] [--timeout-ms <ms>] [--json]
1169
1252
  diffci version
1170
1253
 
1171
1254
  init writes AGENTS.md, CLAUDE.md, Cursor rules, Copilot instructions, and diffci.config.json. It also
1172
1255
  registers the DiffCI MCP server in .mcp.json (Claude Code) and .cursor/mcp.json (Cursor), keeping other
1173
- servers, adds the diffci-verify skill to .claude/skills, and installs the pre-push hook; --no-mcp,
1174
- --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,
1175
1261
  or Bun, installs this DiffCI version as an exact dev dependency, updates the manager's lockfile,
1176
1262
  and adds diffci:verify, diffci:check, and diffci:observe package scripts without replacing existing scripts.
1177
1263
  --verification-workflow adds a blocking GitHub check that uploads a commit-bound verification receipt.
@@ -1214,6 +1300,9 @@ failed before in that log, or that the change edited, run first (--no-rank keeps
1214
1300
  selection in an N-job CI matrix; every job splits it the same way, balanced by --timings (a file from
1215
1301
  diffci outcomes --timings that every job reads) or else by file count. The full suite, test-script phases
1216
1302
  and a selection that cannot be split run in shard 1.
1303
+ coverage runs the full node:test suite once under a probe and V8 coverage and keeps, per test file, the files
1304
+ it loaded, read or listed in .git/diffci/coverage-map.json. verify then also runs tests that map connects to a
1305
+ changed file when the dependency graph did not select them; it only ever adds tests (--no-coverage ignores it).
1217
1306
  outcomes summarises that log: results, selected and full runs, top full-run reasons, agents, and possible
1218
1307
  misses (a selected run that passed and a later full run of the same tree that failed). --curve replays the
1219
1308
  failing runs to show how soon the first failure is seen, ranked by history against path order. --timings
@@ -1267,6 +1356,9 @@ async function main() {
1267
1356
  case "verify":
1268
1357
  process.exitCode = await runVerifyCommand(flags, env);
1269
1358
  return;
1359
+ case "agent-stop":
1360
+ process.exitCode = await runAgentStopCommand(flags, env);
1361
+ return;
1270
1362
  case "check":
1271
1363
  process.exitCode = await runCheck(flags, env);
1272
1364
  maybeShowFeedbackPrompt(flags, env);
@@ -1296,6 +1388,9 @@ async function main() {
1296
1388
  case "enforce-misses":
1297
1389
  process.exitCode = runEnforceMisses(flags, env);
1298
1390
  return;
1391
+ case "coverage":
1392
+ process.exitCode = runCoverageCommand(flags, env);
1393
+ return;
1299
1394
  case "outcomes":
1300
1395
  process.exitCode = runOutcomesCommand(flags, env);
1301
1396
  return;
@@ -28,6 +28,11 @@ export declare function splitCommand(command: string, paths: readonly string[],
28
28
  * or undefined when `command` does not end in exactly selected paths and so cannot be cut safely.
29
29
  */
30
30
  export declare function subsetCommand(command: string, paths: readonly string[], keep: ReadonlySet<string>): string | null | undefined;
31
+ /**
32
+ * `command` with `extra` test files appended (coverage-map.ts), or undefined when `command` does not end in
33
+ * exactly the selected paths or an extra path would need quoting, so it cannot be extended safely.
34
+ */
35
+ export declare function appendToCommand(command: string, paths: readonly string[], extra: readonly string[]): string | undefined;
31
36
  /** `command` split so each part fits `limit`, or `[command]` when it fits or cannot be split safely. */
32
37
  export declare function batchCommand(command: string, paths: readonly string[], limit?: number): string[];
33
38
  /**
@@ -77,6 +77,15 @@ export function subsetCommand(command, paths, keep) {
77
77
  const kept = tail.tokens.filter((entry) => keep.has(entry.path));
78
78
  return kept.length ? `${tail.prefix} ${kept.map((entry) => entry.token).join(" ")}` : null;
79
79
  }
80
+ /**
81
+ * `command` with `extra` test files appended (coverage-map.ts), or undefined when `command` does not end in
82
+ * exactly the selected paths or an extra path would need quoting, so it cannot be extended safely.
83
+ */
84
+ export function appendToCommand(command, paths, extra) {
85
+ if (!selectedTail(command, paths) || !extra.every((path) => /^[\w./@+-]+$/.test(path)))
86
+ return undefined;
87
+ return `${command} ${extra.join(" ")}`;
88
+ }
80
89
  /** `command` split so each part fits `limit`, or `[command]` when it fits or cannot be split safely. */
81
90
  export function batchCommand(command, paths, limit = COMMAND_LINE_LIMIT) {
82
91
  if (command.length <= limit || paths.length === 0)
@@ -0,0 +1,46 @@
1
+ import { type CommandMeasurement } from "./verify-savings.js";
2
+ /**
3
+ * The coverage map (2026-11-06), the idea of Datadog Test Impact Analysis and pytest-testmon.
4
+ *
5
+ * WHY. The dependency graph sees imports. A test also reaches files it never imports: a fixture it reads
6
+ * by name, a directory it lists, a module loaded through a computed specifier or a framework. Those edges
7
+ * are the commonest reason a change runs the full suite, and the ones static analysis cannot find.
8
+ *
9
+ * WHAT. `diffci coverage` runs the full test command once with every `node --test` process (one per test
10
+ * file) under a probe and V8 coverage. The probe records the files the test reads and the directories it
11
+ * lists; V8 coverage records every module it loads, ESM included. The result, per test file, is kept in
12
+ * `<git common dir>/diffci/coverage-map.json` beside the outcome log, never committed and never sent.
13
+ *
14
+ * Phase A, the only use so far: a verify run adds the tests whose map entry names a changed file and the
15
+ * graph did not select. Adding a test is always safe, so a stale map costs time, never a miss. Replacing
16
+ * a full-suite fallback with what the map says (phase B) waits until a replay shows it loses no catches.
17
+ * Only node:test is supported: Vitest and Jest run many files in one worker, so reads cannot be told apart.
18
+ */
19
+ export declare const COVERAGE_MAP_SCHEMA: "diffci.coverage-map.v1";
20
+ export interface CoverageMap {
21
+ schema: typeof COVERAGE_MAP_SCHEMA;
22
+ produced_at: string;
23
+ command: string;
24
+ /** Repository-relative files each test file loaded or read, and directories (ending in `/`) it listed. */
25
+ tests: Record<string, string[]>;
26
+ }
27
+ export declare function coverageMapPath(repoPath: string): string | undefined;
28
+ export declare function readCoverageMap(repoPath: string): CoverageMap | undefined;
29
+ export interface CoverageRun {
30
+ map?: CoverageMap;
31
+ path?: string;
32
+ execution: CommandMeasurement;
33
+ error?: string;
34
+ }
35
+ /** Runs `command` under the probe and V8 coverage, and writes the map. */
36
+ export declare function buildCoverageMap(repoPath: string, command: string, options: {
37
+ timeoutMs: number;
38
+ tailBytes?: number;
39
+ nodeOptions?: string;
40
+ }): CoverageRun;
41
+ /** Tests whose map entry names one of `changed` (or lists a directory holding one), that `selected` lacks. */
42
+ export declare function coverageAdditions(map: CoverageMap, changed: readonly string[], selected: readonly string[]): Array<{
43
+ test: string;
44
+ changed_file: string;
45
+ }>;
46
+ export declare function formatCoverageRun(run: CoverageRun): string;