@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
package/README.md CHANGED
@@ -17,6 +17,29 @@ The `diffci-mcp` binary exposes the same local analysis through MCP. Install
17
17
  the public Codex, Claude Code, Cursor, Grok, or Meta Muse Code integration from
18
18
  the [cross-agent installation guide](https://github.com/DiffCI/core/blob/main/docs/agent-installation.md).
19
19
 
20
+ ## Compare a selection with full-suite results
21
+
22
+ ```sh
23
+ diffci plan --base "$BASE" --head "$HEAD" > plan.json
24
+ # run the full suite with a JUnit reporter
25
+ diffci check-plan --plan plan.json --results junit.xml
26
+ ```
27
+
28
+ `diffci plan` saves Core's advisory plan for a clean checkout at `--head`.
29
+ `check-plan` compares a saved Core execution plan with a full-suite JUnit
30
+ report from the same revision. Without `--base-results base.xml`, skipped failures
31
+ are `possibleMisses`. With a base report, unique matching failures are
32
+ `preExisting`; a skipped failure is `missed` only if its matching base testcase
33
+ passed. Absent, skipped or ambiguous base identities remain `possibleMisses`. Selected and unattributed failures are also reported. Missed, possible
34
+ misses or unattributed failures exit 1; invalid inputs exit 2. Use `--root packages/web`
35
+ for a nested reporter root and `--repo /checkout` for absolute paths. Use
36
+ `--base-repo /base/checkout` if the base report came from another checkout. Exit 0
37
+ describes the comparison, not whether the full suite passed. The command
38
+ runs no tests, writes no files and sends nothing.
39
+
40
+ See the [reporter configuration and scheduled-job example](https://github.com/DiffCI/core/blob/main/docs/using-diffci.md#compare-a-plan-with-a-full-suite-junit-report)
41
+ for Vitest and Jest. Use a CLI build containing this command.
42
+
20
43
  ## Source and license
21
44
 
22
45
  This package is MIT-licensed. Its current source lives in
@@ -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
+ }
@@ -0,0 +1,25 @@
1
+ export interface JunitFailure {
2
+ name: string;
3
+ classname?: string;
4
+ suite?: string;
5
+ file?: string;
6
+ suiteFiles: readonly string[];
7
+ suiteNames: readonly string[];
8
+ suiteLevel?: boolean;
9
+ }
10
+ export interface JunitFailures {
11
+ testCases: number;
12
+ failures: JunitFailure[];
13
+ }
14
+ /** Read only structural failure evidence; logs, comments and CDATA are never tags. */
15
+ export declare function readJunit(xml: string, onCase?: (test: JunitFailure, failed: boolean, skipped: boolean) => void): JunitFailures;
16
+ /** Lexical mapping only: never guess the checkout root from a suffix or access the filesystem. */
17
+ export declare function normalizeTestPath(value: string, repoRoot: string, root?: string): string;
18
+ export type JunitAttribution = {
19
+ file: string;
20
+ } | {
21
+ reason: string;
22
+ candidates?: string[];
23
+ };
24
+ export declare function attributeJunitFile(test: JunitFailure, repoRoot: string, root?: string): JunitAttribution;
25
+ export declare function junitFile(test: JunitFailure, repoRoot: string, root?: string): string;
@@ -0,0 +1,215 @@
1
+ // SPDX-License-Identifier: MIT
2
+ import { posix, win32 } from "node:path";
3
+ import { SaxesParser } from "saxes";
4
+ const MAX_BYTES = 16 * 1024 * 1024;
5
+ const MAX_DEPTH = 128;
6
+ const MAX_TAGS = 100_000;
7
+ const IGNORED_ATTRIBUTE_URIS = new Set([
8
+ "http://www.w3.org/2000/xmlns/",
9
+ "http://www.w3.org/2001/XMLSchema-instance",
10
+ "http://www.w3.org/XML/1998/namespace",
11
+ ]);
12
+ function invalid(message) {
13
+ throw new Error(`Invalid JUnit report: ${message}`);
14
+ }
15
+ function declaredCount(value, name) {
16
+ if (value === undefined)
17
+ return undefined;
18
+ const count = Number(value);
19
+ if (!/^\d+$/.test(value.trim()) || !Number.isSafeInteger(count)) {
20
+ invalid(`${name} must be a nonnegative integer.`);
21
+ }
22
+ return count;
23
+ }
24
+ /** Read only structural failure evidence; logs, comments and CDATA are never tags. */
25
+ export function readJunit(xml, onCase) {
26
+ if (Buffer.byteLength(xml, "utf8") > MAX_BYTES) {
27
+ invalid("XML exceeds the 16 MiB limit.");
28
+ }
29
+ const result = { testCases: 0, failures: [] };
30
+ const frames = [];
31
+ const suites = [];
32
+ let tags = 0;
33
+ let metadataBytes = 0;
34
+ const parser = new SaxesParser({ xmlns: true });
35
+ function emit(failure, failed, skipped) {
36
+ // Passing cases are transient callback data, not retained failure output.
37
+ if (failed) {
38
+ for (const value of [failure.name, failure.classname, failure.file, failure.suite,
39
+ ...failure.suiteFiles, ...failure.suiteNames]) {
40
+ metadataBytes += value === undefined ? 0 : Buffer.byteLength(value, "utf8");
41
+ if (metadataBytes > MAX_BYTES)
42
+ invalid("Failure metadata exceeds the 16 MiB limit.");
43
+ }
44
+ result.failures.push(failure);
45
+ }
46
+ onCase?.(failure, failed, skipped);
47
+ }
48
+ function inherited() {
49
+ return suites[suites.length - 1]?.metadata ?? { suiteFiles: [], suiteNames: [] };
50
+ }
51
+ // Keep the parser's default throwing error handler: partial XML is not evidence.
52
+ parser.on("doctype", () => invalid("DOCTYPE declarations are not supported."));
53
+ parser.on("xmldecl", (declaration) => {
54
+ if (declaration.version !== "1.0")
55
+ invalid("Only XML 1.0 is supported.");
56
+ if (declaration.encoding && declaration.encoding.toUpperCase() !== "UTF-8") {
57
+ invalid("Only UTF-8 XML is supported.");
58
+ }
59
+ });
60
+ parser.on("opentagstart", () => {
61
+ if (++tags > MAX_TAGS)
62
+ invalid("XML exceeds the 100000 tag limit.");
63
+ if (frames.length >= MAX_DEPTH)
64
+ invalid("XML exceeds the 128 level depth limit.");
65
+ });
66
+ parser.on("opentag", (tag) => {
67
+ const name = tag.name;
68
+ const parent = frames[frames.length - 1];
69
+ if (tag.uri !== "")
70
+ invalid("Namespaced JUnit elements are not supported.");
71
+ // Namespace declarations and schema hints carry no testcase identity. Unknown qualified
72
+ // metadata is still refused so x:file/x:failures cannot silently disappear.
73
+ if (Object.values(tag.attributes).some((attribute) => attribute.uri !== "" && !IGNORED_ATTRIBUTE_URIS.has(attribute.uri))) {
74
+ invalid("Unsupported namespaced JUnit attribute.");
75
+ }
76
+ const attributes = Object.fromEntries(Object.entries(tag.attributes).filter(([, attribute]) => attribute.uri === "").map(([key, attribute]) => [key, attribute.value]));
77
+ const frame = { name };
78
+ if (!parent && name !== "testsuite" && name !== "testsuites") {
79
+ invalid("The root must be testsuite or testsuites.");
80
+ }
81
+ if (name === "testsuite" || name === "testsuites") {
82
+ if (parent && parent.name !== "testsuite" && parent.name !== "testsuites") {
83
+ invalid("A test suite must be inside a suite container.");
84
+ }
85
+ const outer = inherited();
86
+ const suite = {
87
+ metadata: {
88
+ suite: name === "testsuite" ? attributes.name : outer.suite,
89
+ suiteFiles: attributes.file === undefined ? outer.suiteFiles : [...outer.suiteFiles, attributes.file],
90
+ suiteNames: name !== "testsuite" || attributes.name === undefined ? outer.suiteNames : [...outer.suiteNames, attributes.name],
91
+ },
92
+ element: name,
93
+ name: attributes.name,
94
+ file: attributes.file,
95
+ declaredTests: declaredCount(attributes.tests, "tests"),
96
+ declaredFailures: declaredCount(attributes.failures, "failures"),
97
+ declaredErrors: declaredCount(attributes.errors, "errors"),
98
+ testCases: 0,
99
+ failures: 0,
100
+ errors: 0,
101
+ };
102
+ frame.suite = suite;
103
+ suites.push(suite);
104
+ }
105
+ else if (name === "testcase") {
106
+ if (parent?.name !== "testsuite" && parent?.name !== "testsuites")
107
+ invalid("A testcase must be inside a testsuite.");
108
+ frame.testCase = {
109
+ skipped: false,
110
+ failed: attributes.failure !== undefined,
111
+ errored: false,
112
+ failure: {
113
+ name: attributes.name ?? "",
114
+ classname: attributes.classname,
115
+ file: attributes.file,
116
+ },
117
+ };
118
+ result.testCases += 1;
119
+ }
120
+ else if (name === "failure" || name === "error") {
121
+ if (parent?.testCase) {
122
+ if (name === "failure")
123
+ parent.testCase.failed = true;
124
+ else
125
+ parent.testCase.errored = true;
126
+ }
127
+ else if (parent?.suite) {
128
+ emit({ name: attributes.message ?? `(suite ${name})`, suiteLevel: true, ...inherited() }, true, false);
129
+ for (const suite of suites) {
130
+ if (name === "failure")
131
+ suite.failures += 1;
132
+ else
133
+ suite.errors += 1;
134
+ }
135
+ }
136
+ else
137
+ invalid("Failure evidence must be a direct testcase or suite child.");
138
+ }
139
+ else if (name === "skipped" && parent?.testCase) {
140
+ parent.testCase.skipped = true;
141
+ }
142
+ frames.push(frame);
143
+ });
144
+ parser.on("closetag", () => {
145
+ const frame = frames.pop();
146
+ if (frame.testCase) {
147
+ const testCase = frame.testCase;
148
+ if (testCase.failed || testCase.errored || onCase) {
149
+ emit({ ...testCase.failure, ...inherited() }, testCase.failed || testCase.errored, testCase.skipped);
150
+ }
151
+ for (const suite of suites) {
152
+ suite.testCases += 1;
153
+ if (testCase.failed)
154
+ suite.failures += 1;
155
+ if (testCase.errored)
156
+ suite.errors += 1;
157
+ }
158
+ }
159
+ if (frame.suite) {
160
+ const suite = frame.suite;
161
+ // jest-junit can emit extra load-error cases without increasing its headers.
162
+ // A higher header, however, means testcase evidence is missing from the report.
163
+ if ((suite.declaredTests ?? 0) > suite.testCases ||
164
+ (suite.declaredFailures ?? 0) > suite.failures ||
165
+ (suite.declaredErrors ?? 0) > suite.errors) {
166
+ invalid("Declared tests, failures or errors exceed the observed testcase evidence.");
167
+ }
168
+ suites.pop();
169
+ }
170
+ });
171
+ parser.write(xml).close();
172
+ if (result.testCases === 0 && result.failures.length === 0)
173
+ invalid("The report contains no testcases.");
174
+ return result;
175
+ }
176
+ /** Lexical mapping only: never guess the checkout root from a suffix or access the filesystem. */
177
+ export function normalizeTestPath(value, repoRoot, root = ".") {
178
+ const slashed = value.replace(/\\/g, "/");
179
+ if (!slashed || /[\x00-\x1f\x7f]/.test(slashed) || slashed.endsWith("/") || slashed.endsWith("/.")
180
+ || slashed.split("/").includes(".."))
181
+ return "";
182
+ const windows = /^[a-z]:\//i.test(slashed) || slashed.startsWith("//");
183
+ const path = windows ? win32 : posix;
184
+ if (path.isAbsolute(slashed)) {
185
+ const checkout = repoRoot.replace(/\\/g, "/");
186
+ if (!path.isAbsolute(checkout) || (windows && !win32.isAbsolute(repoRoot)))
187
+ return slashed;
188
+ const inside = path.relative(checkout, slashed).replace(/\\/g, "/");
189
+ return inside && inside !== ".." && !inside.startsWith("../") && !path.isAbsolute(inside) ? inside : slashed;
190
+ }
191
+ if (/^[a-z][a-z\d+.-]*:/i.test(slashed))
192
+ return "";
193
+ return posix.normalize(posix.join(root, slashed));
194
+ }
195
+ export function attributeJunitFile(test, repoRoot, root = ".") {
196
+ if (test.suiteLevel)
197
+ return { reason: "Suite-level failure has no testcase file identity" };
198
+ const explicit = test.file !== undefined ? [test.file] : test.suiteFiles;
199
+ const values = explicit.length ? explicit : [test.classname, ...test.suiteNames]
200
+ .filter((value) => value !== undefined && /\.[cm]?[jt]sx?$/.test(value));
201
+ if (!values.length)
202
+ return { reason: "No file attribute or recognizable JavaScript file metadata" };
203
+ const paths = values.map(value => normalizeTestPath(value, repoRoot, root));
204
+ const candidates = [...new Set(paths.filter(Boolean))].sort();
205
+ if (paths.some(path => !path || posix.isAbsolute(path) || win32.isAbsolute(path))) {
206
+ return { reason: "File path is invalid or outside the checkout; check --repo/--base-repo", candidates };
207
+ }
208
+ if (candidates.length !== 1)
209
+ return { reason: "File metadata identifies multiple files", candidates };
210
+ return { file: candidates[0] };
211
+ }
212
+ export function junitFile(test, repoRoot, root = ".") {
213
+ const attribution = attributeJunitFile(test, repoRoot, root);
214
+ return "file" in attribution ? attribution.file : "";
215
+ }
@@ -0,0 +1,42 @@
1
+ export interface PlanCheckFailure {
2
+ name: string;
3
+ classname?: string;
4
+ suite?: string;
5
+ reportedFile?: string;
6
+ file?: string;
7
+ }
8
+ export interface UnattributedPlanFailure extends PlanCheckFailure {
9
+ reason: string;
10
+ candidates?: string[];
11
+ }
12
+ export interface PlanCheckReport {
13
+ schemaVersion: 1;
14
+ mode: "SELECTIVE" | "FULL";
15
+ fullFallback: boolean;
16
+ baselineProvided: boolean;
17
+ summary: {
18
+ failedTests: number;
19
+ missed: number;
20
+ possibleMisses: number;
21
+ preExisting: number;
22
+ selected: number;
23
+ unattributed: number;
24
+ };
25
+ possibleMisses: PlanCheckFailure[];
26
+ preExisting: PlanCheckFailure[];
27
+ missed: PlanCheckFailure[];
28
+ selected: PlanCheckFailure[];
29
+ unattributed: UnattributedPlanFailure[];
30
+ }
31
+ export interface PlanCheckOptions {
32
+ /** JUnit results from the plan's base revision, produced with the same reporter configuration. */
33
+ baseResults?: string;
34
+ /** Absolute checkout root that produced the base report. Defaults to repoRoot. */
35
+ baseRepoRoot?: string;
36
+ /** Absolute checkout root for absolute reporter paths. Defaults to the current directory. */
37
+ repoRoot?: string;
38
+ /** Reporter root, relative to the repository root. */
39
+ root?: string;
40
+ }
41
+ /** This checks selection against supplied results, not suite success or report/revision provenance. */
42
+ export declare function checkPlan(planInput: unknown, junitXml: string, options?: PlanCheckOptions): PlanCheckReport;