@diffci.com/diffci 0.3.54 → 0.3.56

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 (144) hide show
  1. package/dist-client/src/client/agent-selection.d.ts +9 -2
  2. package/dist-client/src/client/agent-selection.js +20 -8
  3. package/dist-client/src/client/agent-setup.js +1 -1
  4. package/dist-client/src/client/cli.js +19 -7
  5. package/dist-client/src/client/command-batches.js +3 -2
  6. package/dist-client/src/client/context.d.ts +2 -0
  7. package/dist-client/src/client/context.js +51 -2
  8. package/dist-client/src/client/coverage-map.js +6 -1
  9. package/dist-client/src/client/full-command.js +22 -14
  10. package/dist-client/src/client/gate.js +24 -10
  11. package/dist-client/src/client/hook.d.ts +17 -0
  12. package/dist-client/src/client/hook.js +53 -1
  13. package/dist-client/src/client/install.d.ts +6 -0
  14. package/dist-client/src/client/install.js +29 -1
  15. package/dist-client/src/client/job-summary.d.ts +1 -1
  16. package/dist-client/src/client/job-summary.js +2 -1
  17. package/dist-client/src/client/mcp.js +4 -0
  18. package/dist-client/src/client/observe.js +4 -3
  19. package/dist-client/src/client/report.d.ts +8 -1
  20. package/dist-client/src/client/report.js +11 -0
  21. package/dist-client/src/client/shared-graph-cache.js +4 -2
  22. package/dist-client/src/client/telemetry.js +2 -1
  23. package/dist-client/src/client/usage-signal.d.ts +1 -1
  24. package/dist-client/src/client/verify-savings.d.ts +6 -0
  25. package/dist-client/src/client/verify-savings.js +15 -3
  26. package/dist-client/src/client/verify.js +124 -22
  27. package/dist-client/src/client/workflow-guard.js +27 -6
  28. package/dist-client/src/client/workflow-templates.d.ts +11 -1
  29. package/dist-client/src/client/workflow-templates.js +43 -2
  30. package/node_modules/@diffci.com/core/README.md +17 -10
  31. package/node_modules/@diffci.com/core/dist/ci-inference/expression.d.ts +5 -0
  32. package/node_modules/@diffci.com/core/dist/ci-inference/expression.js +38 -5
  33. package/node_modules/@diffci.com/core/dist/ci-inference/expression.js.map +1 -1
  34. package/node_modules/@diffci.com/core/dist/ci-inference/infer.js +26 -6
  35. package/node_modules/@diffci.com/core/dist/ci-inference/infer.js.map +1 -1
  36. package/node_modules/@diffci.com/core/dist/ci-inference/jobs.d.ts +2 -1
  37. package/node_modules/@diffci.com/core/dist/ci-inference/jobs.js +7 -2
  38. package/node_modules/@diffci.com/core/dist/ci-inference/jobs.js.map +1 -1
  39. package/node_modules/@diffci.com/core/dist/ci-inference/matrix.js +15 -8
  40. package/node_modules/@diffci.com/core/dist/ci-inference/matrix.js.map +1 -1
  41. package/node_modules/@diffci.com/core/dist/ci-inference/purpose.js +6 -2
  42. package/node_modules/@diffci.com/core/dist/ci-inference/purpose.js.map +1 -1
  43. package/node_modules/@diffci.com/core/dist/ci-inference/resolve.js +38 -5
  44. package/node_modules/@diffci.com/core/dist/ci-inference/resolve.js.map +1 -1
  45. package/node_modules/@diffci.com/core/dist/git/ci-config-paths.js +13 -1
  46. package/node_modules/@diffci.com/core/dist/git/ci-config-paths.js.map +1 -1
  47. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +5 -0
  48. package/node_modules/@diffci.com/core/dist/git/git-diff.js +64 -31
  49. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  50. package/node_modules/@diffci.com/core/dist/planner/check-narrowing.js +22 -1
  51. package/node_modules/@diffci.com/core/dist/planner/check-narrowing.js.map +1 -1
  52. package/node_modules/@diffci.com/core/dist/planner/pipeline-steps.d.ts +6 -0
  53. package/node_modules/@diffci.com/core/dist/planner/pipeline-steps.js +14 -2
  54. package/node_modules/@diffci.com/core/dist/planner/pipeline-steps.js.map +1 -1
  55. package/node_modules/@diffci.com/core/dist/planner/planner.js +65 -14
  56. package/node_modules/@diffci.com/core/dist/planner/planner.js.map +1 -1
  57. package/node_modules/@diffci.com/core/dist/planner/rust-command.js +43 -1
  58. package/node_modules/@diffci.com/core/dist/planner/rust-command.js.map +1 -1
  59. package/node_modules/@diffci.com/core/dist/planner/script-reads.js +5 -2
  60. package/node_modules/@diffci.com/core/dist/planner/script-reads.js.map +1 -1
  61. package/node_modules/@diffci.com/core/dist/planner/test-command.js +17 -2
  62. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  63. package/node_modules/@diffci.com/core/dist/planner/type-program.js +27 -1
  64. package/node_modules/@diffci.com/core/dist/planner/type-program.js.map +1 -1
  65. package/node_modules/@diffci.com/core/dist/repo/adapters/go.js +5 -1
  66. package/node_modules/@diffci.com/core/dist/repo/adapters/go.js.map +1 -1
  67. package/node_modules/@diffci.com/core/dist/repo/adapters/maven.js +71 -9
  68. package/node_modules/@diffci.com/core/dist/repo/adapters/maven.js.map +1 -1
  69. package/node_modules/@diffci.com/core/dist/repo/adapters/python.d.ts +9 -1
  70. package/node_modules/@diffci.com/core/dist/repo/adapters/python.js +259 -18
  71. package/node_modules/@diffci.com/core/dist/repo/adapters/python.js.map +1 -1
  72. package/node_modules/@diffci.com/core/dist/repo/adapters/rust-invocation.d.ts +3 -1
  73. package/node_modules/@diffci.com/core/dist/repo/adapters/rust-invocation.js +44 -6
  74. package/node_modules/@diffci.com/core/dist/repo/adapters/rust-invocation.js.map +1 -1
  75. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.d.ts +1 -0
  76. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.js +338 -24
  77. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.js.map +1 -1
  78. package/node_modules/@diffci.com/core/dist/repo/adapters/types.d.ts +10 -0
  79. package/node_modules/@diffci.com/core/dist/repo/adapters/types.js.map +1 -1
  80. package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +16 -0
  81. package/node_modules/@diffci.com/core/dist/repo/file-references.js +76 -5
  82. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  83. package/node_modules/@diffci.com/core/dist/repo/graph.js +101 -30
  84. package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
  85. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +7 -0
  86. package/node_modules/@diffci.com/core/dist/repo/impact.js +56 -9
  87. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  88. package/node_modules/@diffci.com/core/dist/repo/layout.js +4 -1
  89. package/node_modules/@diffci.com/core/dist/repo/layout.js.map +1 -1
  90. package/node_modules/@diffci.com/core/dist/repo/runner-universe.js +10 -1
  91. package/node_modules/@diffci.com/core/dist/repo/runner-universe.js.map +1 -1
  92. package/node_modules/@diffci.com/core/dist/repo/script-universe.js +1 -1
  93. package/node_modules/@diffci.com/core/dist/repo/script-universe.js.map +1 -1
  94. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js +5 -1
  95. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js.map +1 -1
  96. package/node_modules/@diffci.com/core/dist/repo/types.d.ts +3 -0
  97. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js +3 -3
  98. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js.map +1 -1
  99. package/node_modules/@diffci.com/core/dist/repo/yarn-berry-lockfile.d.ts +11 -0
  100. package/node_modules/@diffci.com/core/dist/repo/yarn-berry-lockfile.js +208 -0
  101. package/node_modules/@diffci.com/core/dist/repo/yarn-berry-lockfile.js.map +1 -0
  102. package/node_modules/@diffci.com/core/dist/repo/yarn-lockfile.d.ts +3 -0
  103. package/node_modules/@diffci.com/core/dist/repo/yarn-lockfile.js +2 -2
  104. package/node_modules/@diffci.com/core/dist/repo/yarn-lockfile.js.map +1 -1
  105. package/node_modules/@diffci.com/core/dist/research/baseline/matcher.js +65 -13
  106. package/node_modules/@diffci.com/core/dist/research/baseline/matcher.js.map +1 -1
  107. package/node_modules/@diffci.com/core/dist/research/baseline/workflow-parser.js +47 -2
  108. package/node_modules/@diffci.com/core/dist/research/baseline/workflow-parser.js.map +1 -1
  109. package/node_modules/@diffci.com/core/package.json +1 -0
  110. package/node_modules/@diffci.com/core/src/ci-inference/expression.ts +38 -5
  111. package/node_modules/@diffci.com/core/src/ci-inference/infer.ts +21 -6
  112. package/node_modules/@diffci.com/core/src/ci-inference/jobs.ts +7 -2
  113. package/node_modules/@diffci.com/core/src/ci-inference/matrix.ts +15 -8
  114. package/node_modules/@diffci.com/core/src/ci-inference/purpose.ts +6 -2
  115. package/node_modules/@diffci.com/core/src/ci-inference/resolve.ts +37 -5
  116. package/node_modules/@diffci.com/core/src/git/ci-config-paths.ts +8 -1
  117. package/node_modules/@diffci.com/core/src/git/git-diff.ts +57 -32
  118. package/node_modules/@diffci.com/core/src/planner/check-narrowing.ts +22 -1
  119. package/node_modules/@diffci.com/core/src/planner/pipeline-steps.ts +13 -2
  120. package/node_modules/@diffci.com/core/src/planner/planner.ts +42 -14
  121. package/node_modules/@diffci.com/core/src/planner/rust-command.ts +37 -1
  122. package/node_modules/@diffci.com/core/src/planner/script-reads.ts +5 -1
  123. package/node_modules/@diffci.com/core/src/planner/test-command.ts +17 -2
  124. package/node_modules/@diffci.com/core/src/planner/type-program.ts +25 -1
  125. package/node_modules/@diffci.com/core/src/repo/adapters/go.ts +5 -1
  126. package/node_modules/@diffci.com/core/src/repo/adapters/maven.ts +74 -9
  127. package/node_modules/@diffci.com/core/src/repo/adapters/python.ts +209 -18
  128. package/node_modules/@diffci.com/core/src/repo/adapters/rust-invocation.ts +44 -6
  129. package/node_modules/@diffci.com/core/src/repo/adapters/rust.ts +264 -24
  130. package/node_modules/@diffci.com/core/src/repo/adapters/types.ts +10 -1
  131. package/node_modules/@diffci.com/core/src/repo/file-references.ts +70 -5
  132. package/node_modules/@diffci.com/core/src/repo/graph.ts +82 -21
  133. package/node_modules/@diffci.com/core/src/repo/impact.ts +57 -8
  134. package/node_modules/@diffci.com/core/src/repo/layout.ts +5 -1
  135. package/node_modules/@diffci.com/core/src/repo/runner-universe.ts +11 -1
  136. package/node_modules/@diffci.com/core/src/repo/script-universe.ts +1 -1
  137. package/node_modules/@diffci.com/core/src/repo/test-discovery.ts +4 -1
  138. package/node_modules/@diffci.com/core/src/repo/types.ts +3 -1
  139. package/node_modules/@diffci.com/core/src/repo/workflow-test-steps.ts +3 -3
  140. package/node_modules/@diffci.com/core/src/repo/yarn-berry-lockfile.ts +178 -0
  141. package/node_modules/@diffci.com/core/src/repo/yarn-lockfile.ts +2 -2
  142. package/node_modules/@diffci.com/core/src/research/baseline/matcher.ts +43 -13
  143. package/node_modules/@diffci.com/core/src/research/baseline/workflow-parser.ts +44 -2
  144. package/package.json +2 -2
@@ -48,8 +48,15 @@ export declare function agentSelection(repoInput: string): Promise<{
48
48
  tests_selected: number;
49
49
  command: string | undefined;
50
50
  }>;
51
- /** The one command that verifies `scope` in isolation, as `diffci_select_tests` returns it. */
52
- export declare function scopedVerifyCommand(repoPath: string, scope: VerificationTreeScope, version?: string): string;
51
+ /**
52
+ * A path as one shell word in POSIX shells, cmd.exe and PowerShell, or undefined when no quoting is
53
+ * literal in all three. Inside double quotes `$` and backticks still expand (POSIX, PowerShell), `%` and
54
+ * `!` expand in cmd.exe, and `\` and `"` cannot be escaped the same way in each. The agent runs this
55
+ * command as written, so a repository file named `$(…).ts` must never reach it (CodeQL alert 36).
56
+ */
57
+ export declare function shellPath(path: string): string | undefined;
58
+ /** The one command that verifies `scope` in isolation, as `diffci_select_tests` returns it, or undefined when a path cannot be quoted safely. */
59
+ export declare function scopedVerifyCommand(repoPath: string, scope: VerificationTreeScope, version?: string): string | undefined;
53
60
  /**
54
61
  * The plan for HEAD plus only the staged files, or only the named files (2026-11-17), made in the same
55
62
  * temporary worktree `verify --staged` / `--paths` verifies in. Its `command` is that one verify
@@ -9,8 +9,9 @@ import { createIsolatedWorktree } from "./isolated-worktree.js";
9
9
  import { requireDiffciPackageIdentity } from "./package-identity.js";
10
10
  import { executableSelection, scopedChanges } from "./verify.js";
11
11
  import { captureScopedTree, captureWorkingTreeSnapshot } from "./working-tree.js";
12
+ /** A rename is its old path and its new one: whatever imported the old path is affected too. */
12
13
  function changedPaths(repoPath, snapshot) {
13
- return execFileSync("git", ["diff", "--name-only", "-z", snapshot.baseSha, snapshot.commitSha], {
14
+ return execFileSync("git", ["diff", "--name-only", "--no-renames", "-z", snapshot.baseSha, snapshot.commitSha], {
14
15
  cwd: repoPath, encoding: "utf8", windowsHide: true,
15
16
  }).split("\0").filter(Boolean);
16
17
  }
@@ -98,17 +99,26 @@ function diffciInvocation(repoPath, version) {
98
99
  return hookCommand("npm", version);
99
100
  }
100
101
  }
101
- /** A path as one shell word in POSIX shells, cmd.exe and PowerShell. */
102
- function shellPath(path) {
103
- return /^[A-Za-z0-9_./@+-]+$/.test(path) ? path : `"${path.replace(/"/g, '\\"')}"`;
102
+ /**
103
+ * A path as one shell word in POSIX shells, cmd.exe and PowerShell, or undefined when no quoting is
104
+ * literal in all three. Inside double quotes `$` and backticks still expand (POSIX, PowerShell), `%` and
105
+ * `!` expand in cmd.exe, and `\` and `"` cannot be escaped the same way in each. The agent runs this
106
+ * command as written, so a repository file named `$(…).ts` must never reach it (CodeQL alert 36).
107
+ */
108
+ export function shellPath(path) {
109
+ if (/^[A-Za-z0-9_./@+-]+$/.test(path))
110
+ return path;
111
+ return /[$`"\\%!\0-\x1f\x7f]/.test(path) ? undefined : `"${path}"`;
104
112
  }
105
- /** The one command that verifies `scope` in isolation, as `diffci_select_tests` returns it. */
113
+ /** The one command that verifies `scope` in isolation, as `diffci_select_tests` returns it, or undefined when a path cannot be quoted safely. */
106
114
  export function scopedVerifyCommand(repoPath, scope, version = requireDiffciPackageIdentity().version) {
107
115
  const run = diffciInvocation(repoPath, version);
108
- return scope.kind === "staged"
109
- ? `${run} verify --staged --json`
110
- : `${run} verify --json --paths ${scope.paths.map(shellPath).join(" ")}`;
116
+ if (scope.kind === "staged")
117
+ return `${run} verify --staged --json`;
118
+ const words = scope.paths.map(shellPath);
119
+ return words.every((word) => word !== undefined) ? `${run} verify --json --paths ${words.join(" ")}` : undefined;
111
120
  }
121
+ const UNQUOTABLE_PATH = "a path contains a character no shell quoting keeps literal ($ ` \" \\ % ! or a control character), so DiffCI returns no command to paste; stage the files and use scope \"staged\", or run `diffci verify --paths` with the path quoted for your shell";
112
122
  /**
113
123
  * The plan for HEAD plus only the staged files, or only the named files (2026-11-17), made in the same
114
124
  * temporary worktree `verify --staged` / `--paths` verifies in. Its `command` is that one verify
@@ -134,6 +144,8 @@ export async function agentScopedSelection(repoInput, scope) {
134
144
  });
135
145
  if (!scoped.changed)
136
146
  return unplanned("planned", scope.kind === "staged" ? "nothing is staged: the index matches HEAD" : "the given paths do not differ from HEAD");
147
+ if (command === undefined)
148
+ return unplanned("blocked", UNQUOTABLE_PATH);
137
149
  const worktree = createIsolatedWorktree(repoPath, scoped.baseSha, scoped.treeSha);
138
150
  if ("error" in worktree)
139
151
  return unplanned("blocked", worktree.error);
@@ -54,7 +54,7 @@ export function mcpServerEntry(version) {
54
54
  command: "node",
55
55
  args: [
56
56
  "-e",
57
- `const { spawn } = require('node:child_process'); const npxArgs = ['--yes', '--package', '@diffci.com/diffci@${version}', 'diffci-mcp']; const child = process.platform === 'win32' ? spawn(process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', 'npx', ...npxArgs], { stdio: 'inherit' }); child.once('error', (error) => { console.error('Failed to launch DiffCI MCP:', error.message); process.exit(1); }); child.once('exit', (code, signal) => process.exit(code ?? (signal ? 1 : 0)));`,
57
+ `const { spawn } = require('node:child_process'); const npxArgs = ['--yes', '--package', '@diffci.com/diffci@${version}', 'diffci-mcp']; const child = process.platform === 'win32' ? spawn(process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', 'npx', ...npxArgs], { stdio: 'inherit' }) : spawn('npx', npxArgs, { stdio: 'inherit' }); child.once('error', (error) => { console.error('Failed to launch DiffCI MCP:', error.message); process.exit(1); }); child.once('exit', (code, signal) => process.exit(code ?? (signal ? 1 : 0)));`,
58
58
  ],
59
59
  };
60
60
  }
@@ -46,8 +46,9 @@ import { observe, isInsideRepository } from "./observe.js";
46
46
  import { resolveObservationAgent } from "./agent-identity.js";
47
47
  import { inferFullCommand, inferComparableSelectedCommand, inferWorkspaceComparison } from "./full-command.js";
48
48
  import { addDiffciPackageScripts, detectPackageManager, installDiffci } from "./install.js";
49
- import { hookCommand, installPrePushHook, isGitRepository } from "./hook.js";
49
+ import { hookCommand, installPrePushHook, isGitRepository, refreshPrePushHook } from "./hook.js";
50
50
  import { AGENT_HOOK_TIMEOUT_SECONDS, ignoredWrites, MCP_CONFIG_PATHS, SKILL_PATHS, writeAgentStopHook, writeMcpConfig, writeSkill } from "./agent-setup.js";
51
+ import { worktreeChangeSuspected } from "./report.js";
51
52
  import { submitObservation } from "./submit.js";
52
53
  import { configureGraphCache } from "./shared-graph-cache.js";
53
54
  import { GraphCache } from "@diffci.com/core/cache/graph-cache";
@@ -65,7 +66,7 @@ import { formatGrowthPrompt, formatVerifySavingsSummary, measureCommand, runVeri
65
66
  import { auditEnforceWorkflows, auditWorkflows, isNonInterfering } from "./workflow-guard.js";
66
67
  import { renderPilotPacket } from "./pilot-packet.js";
67
68
  import { observerIdentity } from "./package-identity.js";
68
- import { buildPilotWorkflow, diffciVerificationWorkflow, diffciWorkflow } from "./workflow-templates.js";
69
+ import { buildPilotWorkflow, diffciVerificationWorkflow, diffciWorkflow, verificationInstallCommands } from "./workflow-templates.js";
69
70
  import { buildMissReport, formatMissReportMarkdown, parseJunit } from "./enforce-misses.js";
70
71
  import { appendOutcome, formatOutcomeSummary, outcomeLogPath, readOutcomes, summarizeOutcomes } from "./outcome-log.js";
71
72
  import { checkPlan } from "./check-plan.js";
@@ -435,7 +436,7 @@ function runInit(flags, env) {
435
436
  if (includeWorkflow)
436
437
  writes.push(writeInitFile(repoPath, ".github/workflows/diffci.yml", diffciWorkflow(identity.version), force));
437
438
  if (includeVerificationWorkflow) {
438
- writes.push(writeInitFile(repoPath, ".github/workflows/diffci-verify.yml", diffciVerificationWorkflow(identity.version), force));
439
+ writes.push(writeInitFile(repoPath, ".github/workflows/diffci-verify.yml", diffciVerificationWorkflow(identity.version, verificationInstallCommands(repoPath)), force));
439
440
  }
440
441
  // The hook, MCP server and skill are on by default so an agent meets DiffCI without being told to.
441
442
  const skipped = [];
@@ -684,6 +685,15 @@ async function runVerifyCommand(flags, env) {
684
685
  console.error(`diffci: ${outside} changed file(s) here are not staged and were verified too. If other sessions share this checkout, stage your own files and run \`diffci verify --staged\` (or \`diffci verify --paths <file...>\`) to verify HEAD plus only those, in a temporary worktree.`);
685
686
  }
686
687
  }
688
+ // Never from the hook's own `verify --base/--head`, and never in CI, where no hook is installed.
689
+ if ((changed || staged || paths) && env.DIFFCI_HOOK_REFRESH !== "0" && !(Boolean(env.CI) && env.CI !== "false")) {
690
+ try {
691
+ const refreshed = refreshPrePushHook(repoPath);
692
+ if (refreshed)
693
+ console.error(refreshed);
694
+ }
695
+ catch { /* keeping an old hook never fails verification */ }
696
+ }
687
697
  await recordUsage("verify", report.verification, identity.version, flags, env, repoPath);
688
698
  if (flags["no-log"] !== true)
689
699
  appendOutcome(repoPath, report, env);
@@ -929,7 +939,7 @@ function summarise(report, executionFollows = false) {
929
939
  lines.push(" blind spot: this repository declares a test framework and DiffCI discovered none of its tests");
930
940
  }
931
941
  }
932
- lines.push(` non-interference${executionFollows ? " (analysis phase)" : ""}: worktree ${report.nonInterference.worktreeUnchanged ? "unchanged" : "CHANGED - report this"}, report written ${report.nonInterference.reportWrittenOutsideRepository ? "outside" : "INSIDE"} the checkout`);
942
+ lines.push(` non-interference${executionFollows ? " (analysis phase)" : ""}: worktree ${report.nonInterference.worktreeUnchanged ? "unchanged" : worktreeChangeSuspected(report.nonInterference) ? "CHANGED - report this" : "not a git checkout, nothing to compare"}, report written ${report.nonInterference.reportWrittenOutsideRepository ? "outside" : "INSIDE"} the checkout`);
933
943
  const blocking = report.nonInterference.workflowFindings.filter((f) => f.severity === "BLOCKING");
934
944
  // `check` is a local trial, not an installation, so it names the count and where to look; `observe`
935
945
  // runs inside the installation being judged and keeps every finding in its log.
@@ -1533,11 +1543,11 @@ Usage:
1533
1543
  diffci verify [--changed | --staged | --paths <file...> | --paths-from <file|-> | --base <sha> --head <sha>]
1534
1544
  [--policy enforce] [--repo <path>] [--out <file>] [--json]
1535
1545
  [--redact-paths] [--timeout-ms <ms>] [--baseline-on-failure] [--no-checks | --checks]
1536
- [--share-usage] [--no-send] [--no-log] [--no-reuse] [--no-rank] [--fail-fast]
1546
+ [--no-send] [--no-log] [--no-reuse] [--no-rank] [--fail-fast]
1537
1547
  [--shard <i/N> [--timings <file>]] [--no-coverage]
1538
1548
  diffci telemetry [--mode repo|count-only] [--internal-usage]
1539
1549
  diffci check [--repo <path>] [--out <file>] [--base <sha> --head <sha>]
1540
- [--redact-paths] [--json] [--quiet] [--fail-on-error] [--timeout-ms <ms>] [--share-usage]
1550
+ [--redact-paths] [--json] [--quiet] [--fail-on-error] [--timeout-ms <ms>]
1541
1551
  diffci plan --base <sha> [--head <sha>] [--repo <path>]
1542
1552
  diffci check-plan --plan <plan.json> --results <junit.xml>
1543
1553
  diffci red-builds <owner/repo> [--runs <n>] [--workflow <id|file>] [--json <file>] [--check-jobs <regex>] [--ci-only-jobs <regex>]
@@ -1546,7 +1556,7 @@ Usage:
1546
1556
  [--label <name>] [--repository-url <https-url>] [--redact-paths]
1547
1557
  diffci observe [--repo <path>] [--out <file>] [--base <sha> --head <sha>]
1548
1558
  [--redact-paths] [--json] [--quiet] [--fail-on-error] [--summary-out <file.md>]
1549
- [--api-url <url> --api-token <token>] [--no-send] [--share-usage] [--agent <name|auto>]
1559
+ [--api-url <url> --api-token <token>] [--no-send] [--agent <name|auto>]
1550
1560
  [--graph-cache-dir <dir>] [--shared-graph-cache [--graph-cache-url <url>]]
1551
1561
  diffci verify-savings --repo <path> --full <command>
1552
1562
  (--selected <command> | --selected-from-report <file>)
@@ -1580,6 +1590,8 @@ and adds diffci:verify, diffci:check, and diffci:observe package scripts without
1580
1590
  --verification-workflow adds a blocking GitHub check that uploads a commit-bound verification receipt.
1581
1591
  The pre-push hook runs diffci verify on the commits being pushed and blocks the push
1582
1592
  when verification fails (git push --no-verify skips it; DIFFCI_HOOK_STRICT=1 also blocks when it cannot verify).
1593
+ verify --changed, --staged and --paths replace an outdated DiffCI-written hook with this version's, same
1594
+ command (DIFFCI_HOOK_REFRESH=0 turns it off; a hook DiffCI did not write is never touched).
1583
1595
  mcp runs the stdio MCP server for native agent integrations.
1584
1596
  verify --changed snapshots staged, unstaged, and non-ignored untracked changes, runs the minimum
1585
1597
  executable verification (or full fallback), and exits zero only when that exact snapshot passes.
@@ -1,6 +1,6 @@
1
1
  import { commandArguments } from "./selected-coverage.js";
2
2
  import { mergeTestFileResults } from "./test-results.js";
3
- import { measureCommand } from "./verify-savings.js";
3
+ import { measureCommand, tail as tailBytes } from "./verify-savings.js";
4
4
  /**
5
5
  * Selected-test commands too long for the shell (2026-10-21).
6
6
  *
@@ -149,7 +149,8 @@ export function measureCommands(commands, options) {
149
149
  const failingTests = [...new Set(parts.flatMap((part) => part.failingTests ?? []))].sort();
150
150
  const counted = ranAll && parts.every((part) => part.runnerTestCount !== undefined);
151
151
  const testResults = mergeTestFileResults(...parts.map((part) => part.testResults));
152
- const tail = (key) => parts.map((part) => part[key]).join("").slice(-Math.max(options.tailBytes, 0) || undefined);
152
+ // The same byte-bounded cut as a single command's tail: by UTF-8 bytes, at a character boundary.
153
+ const tail = (key) => tailBytes(parts.map((part) => part[key]).join(""), options.tailBytes);
153
154
  return {
154
155
  command: commands.join(" && "),
155
156
  exitCode: failed ? failed.exitCode : ranAll ? 0 : null,
@@ -1,10 +1,12 @@
1
1
  /** Injected so tests can drive this without a real repository. Returns stdout, or a failure. */
2
+ /** `stderr` is only inspected, never reported: a failed fetch can print a remote URL with credentials. */
2
3
  export type GitRunner = (args: string[]) => {
3
4
  ok: true;
4
5
  stdout: string;
5
6
  } | {
6
7
  ok: false;
7
8
  error: string;
9
+ stderr?: string;
8
10
  };
9
11
  export interface ObservationEnvironment {
10
12
  [key: string]: string | undefined;
@@ -129,12 +129,41 @@ function mergeBase(git, a, b) {
129
129
  const result = git(["merge-base", a, b]);
130
130
  return result.ok ? result.stdout.trim() || undefined : undefined;
131
131
  }
132
+ /**
133
+ * The base for a push that created its branch (2026-11-18). There is no `before`, and the head's parent
134
+ * covers only the last of the commits the push brought, so a change made earlier in the same push was
135
+ * never analysed. The commits the new branch adds are the ones not on the default branch, so the merge
136
+ * base with the default branch's remote-tracking ref is the base - the same range a pull request from the
137
+ * branch would get. Undefined when that ref is not in this checkout, or the head is already on it (nothing
138
+ * new to compare), and the caller then falls back to the labelled `head-parent` range.
139
+ */
140
+ function branchCreationBase(git, headSha, defaultBranch) {
141
+ if (!defaultBranch || !/^[A-Za-z0-9._/-]+$/.test(defaultBranch) || defaultBranch.startsWith("-") || defaultBranch.includes("..")) {
142
+ return undefined;
143
+ }
144
+ const tip = resolveSha(git, `refs/remotes/origin/${defaultBranch}`);
145
+ if (!tip)
146
+ return undefined;
147
+ const common = mergeBase(git, tip, headSha);
148
+ return common && common !== headSha && commitExists(git, common) ? common : undefined;
149
+ }
132
150
  /** The one sentence every "commit missing locally" refusal ends with, so the fix is never a guess. */
133
151
  const DEEPEN_HINT = "the commit is not in this checkout - add `fetch-depth: 0` to the actions/checkout step in the job that runs DiffCI (this does not affect any other job)";
134
152
  /** GitLab clones 20 commits deep by default, so a long merge request loses its base (2026-11-05). */
135
153
  const GITLAB_DEEPEN_HINT = "the commit is not in this checkout - set `GIT_DEPTH: \"0\"` in the variables of the job that runs DiffCI (this does not affect any other job)";
136
154
  /** Azure Pipelines checks out shallow (`fetchDepth: 1`) by default in pipelines created since 2022. */
137
155
  const AZURE_DEEPEN_HINT = "the commit is not in this checkout - set `fetchDepth: 0` on the `checkout` step of the job that runs DiffCI (this does not affect any other job)";
156
+ /** For a path that is not a git checkout: where the checkout is, not how deep it is (#278). */
157
+ function notACheckoutHint(env) {
158
+ if (env.GITHUB_ACTIONS === "true") {
159
+ return "set the DiffCI Action's `repository-path` (or `--repo`) to the directory actions/checkout cloned into - its `path:` when the checkout step sets one";
160
+ }
161
+ if (env.GITLAB_CI === "true")
162
+ return "run DiffCI in the cloned project directory, or pass `--repo` with that directory";
163
+ if (isAzurePipelines(env))
164
+ return "set the DiffCIObserve task's `repositoryPath` (or `--repo`) to the directory the `checkout` step cloned into - its `path:` when it sets one";
165
+ return "pass `--repo` with the directory of a git checkout";
166
+ }
138
167
  function deepenHint(env) {
139
168
  if (env.GITLAB_CI === "true")
140
169
  return GITLAB_DEEPEN_HINT;
@@ -237,6 +266,11 @@ function resolveGitlabRange(env, git) {
237
266
  if (before && before !== ZERO_SHA && commitExists(git, before)) {
238
267
  return { ok: true, range: { baseSha: before, headSha, source: "push-event" } };
239
268
  }
269
+ if (before === ZERO_SHA || before === undefined) {
270
+ const common = branchCreationBase(git, headSha, asString(env.CI_DEFAULT_BRANCH));
271
+ if (common)
272
+ return { ok: true, range: { baseSha: common, headSha, source: "push-event", mergeBaseSha: common } };
273
+ }
240
274
  const parent = resolveSha(git, `${headSha}^`);
241
275
  if (!parent) {
242
276
  return {
@@ -267,6 +301,14 @@ export function resolveCommitRangeFetchingHistory(options) {
267
301
  if (first.ok)
268
302
  return first;
269
303
  const { env, git } = options;
304
+ // A path that is not a git checkout at all (#278): no history depth fixes that, so the deepen hint
305
+ // would send the user the wrong way. Name the setting that points DiffCI at the checkout instead.
306
+ const inside = git(["rev-parse", "--is-inside-work-tree"]);
307
+ // Only git saying so means "not a checkout": dubious ownership or a missing git binary fail differently.
308
+ if (!inside.ok && !/not a git repository/i.test(inside.stderr ?? ""))
309
+ return first;
310
+ if (!inside.ok || inside.stdout.trim() !== "true")
311
+ return { ok: false, reason: `this path is not a git checkout: ${notACheckoutHint(env)}` };
270
312
  if (env.GITHUB_ACTIONS !== "true" && env.GITLAB_CI !== "true" && !isAzurePipelines(env))
271
313
  return first;
272
314
  const shallow = git(["rev-parse", "--is-shallow-repository"]);
@@ -344,8 +386,15 @@ export function resolveCommitRange(options) {
344
386
  if (before && before !== ZERO_SHA && commitExists(git, before)) {
345
387
  return { ok: true, range: { baseSha: before, headSha, source: "push-event" } };
346
388
  }
347
- // A branch's first push has no `before`. The head's own parent is the honest substitute and is
348
- // labelled as such - it answers "what did this commit change", not "what did this push change".
389
+ // A branch's first push has no `before`. Its merge base with the default branch covers every commit
390
+ // the push brought; only when that cannot be computed is the head's own parent used, labelled as
391
+ // such - it answers "what did this commit change", not "what did this push change".
392
+ if (before === ZERO_SHA) {
393
+ const defaultBranch = asString(nested(payload, "repository", "default_branch")) ?? asString(env.GITHUB_DEFAULT_BRANCH);
394
+ const common = branchCreationBase(git, headSha, defaultBranch);
395
+ if (common)
396
+ return { ok: true, range: { baseSha: common, headSha, source: "push-event", mergeBaseSha: common } };
397
+ }
349
398
  const parent = resolveSha(git, `${headSha}^`);
350
399
  if (!parent) {
351
400
  return {
@@ -25,12 +25,17 @@ export const COVERAGE_MAP_SCHEMA = "diffci.coverage-map.v1";
25
25
  const PROBE = `"use strict";
26
26
  if (process.env.NODE_TEST_CONTEXT && process.argv[1] && process.env.DIFFCI_COVERAGE_LOG) {
27
27
  const fs = require("node:fs");
28
+ const { resolve } = require("node:path");
28
29
  const { fileURLToPath } = require("node:url");
29
30
  const file = process.argv[1];
30
31
  const reads = new Set();
31
32
  const listed = new Set();
33
+ // A relative path is resolved against the test process's working directory when it is read, as fs does.
32
34
  const note = (set, target) => {
33
- try { set.add(typeof target === "string" ? target : target instanceof URL ? fileURLToPath(target) : Buffer.isBuffer(target) ? target.toString() : ""); } catch {}
35
+ try {
36
+ const name = typeof target === "string" ? target : target instanceof URL ? fileURLToPath(target) : Buffer.isBuffer(target) ? target.toString() : "";
37
+ if (name) set.add(resolve(name));
38
+ } catch {}
34
39
  };
35
40
  const wrap = (owner, name, set) => {
36
41
  const original = owner[name];
@@ -144,6 +144,9 @@ export function inferFullCommand(repoPath) {
144
144
  };
145
145
  }
146
146
  const packagePath = join(repoPath, "package.json");
147
+ // A package.json without a test script is often tooling only (prettier, husky, commitlint) beside a
148
+ // Go or Python project, whose own runner is then the full command, as it is for the selection.
149
+ let noTestScript;
147
150
  if (existsSync(packagePath)) {
148
151
  let pkg;
149
152
  try {
@@ -153,21 +156,26 @@ export function inferFullCommand(repoPath) {
153
156
  return { reason: "package.json could not be read" };
154
157
  }
155
158
  if (typeof pkg.scripts?.test !== "string" || !pkg.scripts.test.trim()) {
156
- return { reason: "package.json has no test script" };
159
+ noTestScript = { reason: "package.json has no test script" };
157
160
  }
158
- const manager = typeof pkg.packageManager === "string" ? pkg.packageManager.split("@")[0] : undefined;
159
- if (manager === "pnpm" || manager === "yarn" || manager === "bun") {
160
- return { command: `${manager} test`, reason: `package.json test script via ${manager}` };
161
+ else {
162
+ const manager = typeof pkg.packageManager === "string" ? pkg.packageManager.split("@")[0] : undefined;
163
+ // `bun test` is Bun's own test runner and ignores scripts.test; `bun run test` runs the script.
164
+ if (manager === "bun")
165
+ return { command: "bun run test", reason: "package.json test script via bun" };
166
+ if (manager === "pnpm" || manager === "yarn") {
167
+ return { command: `${manager} test`, reason: `package.json test script via ${manager}` };
168
+ }
169
+ if (manager && manager !== "npm")
170
+ return { reason: `unsupported package manager: ${manager}` };
171
+ if (existsSync(join(repoPath, "pnpm-lock.yaml")))
172
+ return { command: "pnpm test", reason: "package.json test script with pnpm lockfile" };
173
+ if (existsSync(join(repoPath, "yarn.lock")))
174
+ return { command: "yarn test", reason: "package.json test script with Yarn lockfile" };
175
+ if (existsSync(join(repoPath, "bun.lock")) || existsSync(join(repoPath, "bun.lockb")))
176
+ return { command: "bun run test", reason: "package.json test script with Bun lockfile" };
177
+ return { command: "npm test", reason: "package.json test script" };
161
178
  }
162
- if (manager && manager !== "npm")
163
- return { reason: `unsupported package manager: ${manager}` };
164
- if (existsSync(join(repoPath, "pnpm-lock.yaml")))
165
- return { command: "pnpm test", reason: "package.json test script with pnpm lockfile" };
166
- if (existsSync(join(repoPath, "yarn.lock")))
167
- return { command: "yarn test", reason: "package.json test script with Yarn lockfile" };
168
- if (existsSync(join(repoPath, "bun.lock")) || existsSync(join(repoPath, "bun.lockb")))
169
- return { command: "bun test", reason: "package.json test script with Bun lockfile" };
170
- return { command: "npm test", reason: "package.json test script" };
171
179
  }
172
180
  if (existsSync(join(repoPath, "go.mod")))
173
181
  return { command: "go test ./...", reason: "root Go module" };
@@ -178,7 +186,7 @@ export function inferFullCommand(repoPath) {
178
186
  ? { command: `${interpreter} -m pytest`, reason: "Python project tested with pytest" }
179
187
  : { reason: "Python project, but no Python 3 interpreter (python3, python or py -3) is on PATH" };
180
188
  }
181
- return { reason: "no supported full test command could be inferred" };
189
+ return noTestScript ?? { reason: "no supported full test command could be inferred" };
182
190
  }
183
191
  function pythonInterpreter(cwd) {
184
192
  for (const candidate of [["python3"], ["python"], ["py", "-3"]]) {
@@ -90,12 +90,19 @@ export async function runGate(options) {
90
90
  const repoPath = resolve(options.repoPath);
91
91
  const run = options.run ?? measureCommand;
92
92
  const started = Date.now();
93
- const remaining = () => Math.max(options.timeoutMs - (Date.now() - started), 0);
94
- const execute = (command) => run(command, { cwd: repoPath, timeoutMs: remaining(), tailBytes: options.tailBytes });
93
+ // The step budget starts after the analysis: a slow analysis must not leave the full gate unrun.
94
+ let stepsStarted = started;
95
+ // A step that would start with no time left is not run: a 0ms timeout would mean no limit at all.
96
+ const execute = (command) => {
97
+ const remaining = options.timeoutMs - (Date.now() - stepsStarted);
98
+ return remaining > 0 ? run(command, { cwd: repoPath, timeoutMs: remaining, tailBytes: options.tailBytes }) : undefined;
99
+ };
100
+ const step = (measurement) => measurement ? stepRun(measurement) : { status: "not_run" };
95
101
  // 1. What DiffCI would do: a plan made elsewhere, or an analysis here. Never fatal: the full gate runs
96
102
  // whatever happens here.
97
103
  const supplied = options.plan !== undefined ? usablePlan(options.plan, options.expectHead) : undefined;
98
104
  const plan = supplied ? supplied.plan : await planGate(options);
105
+ stepsStarted = Date.now();
99
106
  const analysis = plan?.analysis ?? { status: "PLAN_UNUSABLE", reason: supplied?.reason, fallback_reasons: [] };
100
107
  const unplanned = analysis.reason ?? "the change could not be analysed";
101
108
  const analysisMs = supplied?.plan ? 0 : plan?.analysis.duration_ms ?? 0;
@@ -105,7 +112,7 @@ export async function runGate(options) {
105
112
  // 2. The full gate, every leaf, continuing past failures so each one is attributed.
106
113
  const checks = full.map((check) => {
107
114
  const decided = decisionOf.get(check.id);
108
- const measured = stepRun(execute(check.command));
115
+ const measured = step(execute(check.command));
109
116
  return {
110
117
  id: check.id, kind: check.kind,
111
118
  decision: decided?.decision ?? "UNPLANNED",
@@ -119,7 +126,7 @@ export async function runGate(options) {
119
126
  let tests;
120
127
  if (testCommand) {
121
128
  const measurement = execute(testCommand);
122
- const fullRun = { ...stepRun(measurement), ...(measurement.failingTests?.length ? { failing_tests: measurement.failingTests } : {}) };
129
+ const fullRun = { ...step(measurement), ...(measurement?.failingTests?.length ? { failing_tests: measurement.failingTests } : {}) };
123
130
  tests = {
124
131
  command: testCommand, full: fullRun,
125
132
  selection: plan?.tests.selection ?? "unavailable",
@@ -134,27 +141,31 @@ export async function runGate(options) {
134
141
  for (const check of checks) {
135
142
  if (check.full.status === "passed" && !options.measureSelected)
136
143
  continue;
144
+ // A step the time limit left unrun has no result, so it cannot be a miss.
145
+ if (check.full.status === "not_run")
146
+ continue;
137
147
  if (check.decision === "SKIP") {
138
148
  check.missed = check.full.status !== "passed";
139
149
  continue;
140
150
  }
141
151
  if (check.decision !== "NARROWED" || !check.narrowed_command)
142
152
  continue;
143
- check.narrowed = stepRun(execute(check.narrowed_command));
153
+ check.narrowed = step(execute(check.narrowed_command));
144
154
  if (check.full.status !== "passed")
145
155
  check.missed = check.narrowed.status === "passed";
146
156
  }
147
157
  if (tests?.selected_commands && (tests.full.status !== "passed" || options.measureSelected)) {
148
158
  const runs = tests.selected_commands.map((command) => execute(command));
149
- const failed = runs.find((measurement) => stepRun(measurement).status !== "passed");
150
- tests.selected = { ...stepRun(failed ?? runs[runs.length - 1]), wall_ms: runs.reduce((sum, measurement) => sum + measurement.wallMs, 0) };
159
+ const failed = runs.findIndex((measurement) => step(measurement).status !== "passed");
160
+ tests.selected = { ...step(runs[failed >= 0 ? failed : runs.length - 1]), wall_ms: runs.reduce((sum, measurement) => sum + (measurement?.wallMs ?? 0), 0) };
151
161
  if (tests.full.status !== "passed")
152
162
  tests.missed = tests.selected.status === "passed";
153
163
  }
154
164
  // 4. Summary. The build's result is the full gate's, never DiffCI's.
155
165
  const failedSteps = [...checks.filter((check) => check.full.status !== "passed").map((check) => check.id), ...(tests && tests.full.status !== "passed" ? ["tests"] : [])];
156
166
  const fullMs = checks.reduce((sum, check) => sum + (check.full.wall_ms ?? 0), 0) + (tests?.full.wall_ms ?? 0);
157
- let estimated = false;
167
+ // A step the time limit left unrun has no time in either total, so the comparison is not fully measured.
168
+ let estimated = checks.some((check) => check.full.status === "not_run") || tests?.full.status === "not_run";
158
169
  let diffciMs = analysisMs;
159
170
  for (const check of checks) {
160
171
  if (check.decision === "SKIP")
@@ -201,6 +212,9 @@ export function gateExitCode(report) {
201
212
  return report.gate.status === "passed" ? 0 : 1;
202
213
  }
203
214
  const seconds = (ms) => `${(ms / 1000).toFixed(1)}s`;
215
+ /** A step the time limit left unrun did not fail; it reads as not run, and the gate's reason says it failed. */
216
+ const stepLabel = (status) => status === "passed" ? "ok " : status === "not_run" ? "-- " : "FAIL";
217
+ const notRun = (status) => status === "not_run" ? " (not run)" : "";
204
218
  export function formatGateSummary(report) {
205
219
  const lines = [
206
220
  `DiffCI gate (observe): ${report.gate.status.toUpperCase()} - ${report.gate.reason}`,
@@ -208,12 +222,12 @@ export function formatGateSummary(report) {
208
222
  ` analysis: ${report.analysis.status}${report.analysis.mode ? ` (${report.analysis.mode})` : ""}${report.analysis.reason ? ` - ${report.analysis.reason}` : ""}`,
209
223
  ];
210
224
  for (const check of report.checks) {
211
- lines.push(` ${check.full.status === "passed" ? "ok " : "FAIL"} ${check.id} ${seconds(check.full.wall_ms ?? 0)} - DiffCI: ${check.decision}${check.missed ? " (MISSED)" : ""}`);
225
+ lines.push(` ${stepLabel(check.full.status)} ${check.id} ${seconds(check.full.wall_ms ?? 0)}${notRun(check.full.status)} - DiffCI: ${check.decision}${check.missed ? " (MISSED)" : ""}`);
212
226
  }
213
227
  if (report.tests) {
214
228
  const t = report.tests;
215
229
  const scope = t.selection === "selected" ? `${t.tests_selected}/${t.tests_available} test files` : t.selection;
216
- lines.push(` ${t.full.status === "passed" ? "ok " : "FAIL"} tests ${seconds(t.full.wall_ms ?? 0)} - DiffCI: ${scope}${t.missed ? " (MISSED)" : ""}`);
230
+ lines.push(` ${stepLabel(t.full.status)} tests ${seconds(t.full.wall_ms ?? 0)}${notRun(t.full.status)} - DiffCI: ${scope}${t.missed ? " (MISSED)" : ""}`);
217
231
  }
218
232
  const s = report.summary;
219
233
  lines.push(` full gate ${seconds(s.full_ms)}, DiffCI ${seconds(s.diffci_ms)} (${s.basis}), would save ${seconds(s.saved_ms)}`);
@@ -39,3 +39,20 @@ export declare function isGitRepository(repoPath: string): boolean;
39
39
  /** Writes the hook into the directory Git actually runs hooks from (`core.hooksPath` included, such as
40
40
  * `.husky`). An existing hook DiffCI did not write is kept unless `force` is set. */
41
41
  export declare function installPrePushHook(repoPath: string, command: string, force: boolean): string;
42
+ /** The DiffCI command a managed hook was written for, read from its in-place verify line (every version has it). */
43
+ export declare function hookCommandOf(hook: string): string | undefined;
44
+ /**
45
+ * Keeps an installed DiffCI pre-push hook current (2026-11-17).
46
+ *
47
+ * WHY. Repositories keep the hook `diffci init` wrote first, so hook fixes never reached them. DentalPresence's
48
+ * hook of 8 Nov predated the not-installed fix: pushing from a worktree without node_modules, npx printed a
49
+ * 404, the old hook read it as failing tests and blocked a correct push. The current hook says it could not
50
+ * verify and lets the push through.
51
+ *
52
+ * WHAT. When it differs from the hook this version writes for the same command, a hook with DiffCI's marker is
53
+ * replaced; any other hook is never touched. The new file is written beside it and renamed over it, so a
54
+ * hook another push is running keeps reading the old file. Callers run it only outside the hook's own
55
+ * commands (verify of the working tree, the index or paths, never `verify --base/--head`) and ignore any
56
+ * error. `DIFFCI_HOOK_REFRESH=0` turns it off.
57
+ */
58
+ export declare function refreshPrePushHook(repoPath: string): string | undefined;
@@ -1,5 +1,5 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { dirname, isAbsolute, join, relative } from "node:path";
4
4
  /**
5
5
  * The pre-push hook `diffci init` installs (2026-10-28; on by default since 0.3.24).
@@ -208,3 +208,55 @@ export function installPrePushHook(repoPath, command, force) {
208
208
  catch { /* Git for Windows runs hooks through sh regardless of mode. */ }
209
209
  return `wrote ${shown} (verifies pushed commits; skip once with git push --no-verify)`;
210
210
  }
211
+ /** The DiffCI command a managed hook was written for, read from its in-place verify line (every version has it). */
212
+ export function hookCommandOf(hook) {
213
+ const match = /^[ \t]*(\S.*?) verify --base "\$base" --head "\$local_sha" <\/dev\/null[ \t]*$/m.exec(hook.replace(/\r\n/g, "\n"));
214
+ return match?.[1];
215
+ }
216
+ /**
217
+ * Keeps an installed DiffCI pre-push hook current (2026-11-17).
218
+ *
219
+ * WHY. Repositories keep the hook `diffci init` wrote first, so hook fixes never reached them. DentalPresence's
220
+ * hook of 8 Nov predated the not-installed fix: pushing from a worktree without node_modules, npx printed a
221
+ * 404, the old hook read it as failing tests and blocked a correct push. The current hook says it could not
222
+ * verify and lets the push through.
223
+ *
224
+ * WHAT. When it differs from the hook this version writes for the same command, a hook with DiffCI's marker is
225
+ * replaced; any other hook is never touched. The new file is written beside it and renamed over it, so a
226
+ * hook another push is running keeps reading the old file. Callers run it only outside the hook's own
227
+ * commands (verify of the working tree, the index or paths, never `verify --base/--head`) and ignore any
228
+ * error. `DIFFCI_HOOK_REFRESH=0` turns it off.
229
+ */
230
+ export function refreshPrePushHook(repoPath) {
231
+ const hooksDir = execFileSync("git", ["rev-parse", "--git-path", "hooks"], { cwd: repoPath, encoding: "utf8", windowsHide: true, stdio: ["ignore", "pipe", "ignore"] }).trim();
232
+ const hookPath = join(isAbsolute(hooksDir) ? hooksDir : join(repoPath, hooksDir), "pre-push");
233
+ if (!existsSync(hookPath))
234
+ return undefined;
235
+ const existing = readFileSync(hookPath, "utf8");
236
+ if (!existing.includes(HOOK_MARKER))
237
+ return undefined;
238
+ const command = hookCommandOf(existing);
239
+ if (!command)
240
+ return undefined;
241
+ const content = prePushHook(command);
242
+ if (existing.replace(/\r\n/g, "\n") === content)
243
+ return undefined;
244
+ const temporary = `${hookPath}.diffci-${process.pid}`;
245
+ writeFileSync(temporary, content, "utf8");
246
+ try {
247
+ chmodSync(temporary, 0o755);
248
+ }
249
+ catch { /* Git for Windows runs hooks through sh regardless of mode. */ }
250
+ try {
251
+ renameSync(temporary, hookPath);
252
+ }
253
+ catch (error) {
254
+ try {
255
+ unlinkSync(temporary);
256
+ }
257
+ catch { /* nothing left to clean */ }
258
+ throw error;
259
+ }
260
+ const shown = relative(repoPath, hookPath).replace(/\\/g, "/") || hookPath;
261
+ return `diffci: updated the DiffCI pre-push hook ${shown} to this version's (same command: ${command}); DIFFCI_HOOK_REFRESH=0 turns this off`;
262
+ }
@@ -11,6 +11,12 @@ export interface PackageScriptResult {
11
11
  kept: string[];
12
12
  }
13
13
  export declare function detectPackageManager(repoPath: string): SupportedPackageManager;
14
+ /**
15
+ * Whether the repository uses Yarn 2 or later (Berry). Berry's `yarn add` rejects `--ignore-scripts`
16
+ * ("Unsupported option name") and skips build scripts with `--mode=skip-build` instead. The declared
17
+ * packageManager version decides; without one, a .yarnrc.yml or a Berry lockfile (`__metadata:`) does.
18
+ */
19
+ export declare function usesYarnBerry(repoPath: string): boolean;
14
20
  export declare function installPlan(repoPath: string, version: string, platform?: NodeJS.Platform): InstallPlan;
15
21
  export declare function installDiffci(repoPath: string, version: string, run?: typeof spawnSync, packageSpecOverride?: string): {
16
22
  plan: InstallPlan;
@@ -41,6 +41,32 @@ export function detectPackageManager(repoPath) {
41
41
  }
42
42
  return detected.values().next().value ?? "npm";
43
43
  }
44
+ /**
45
+ * Whether the repository uses Yarn 2 or later (Berry). Berry's `yarn add` rejects `--ignore-scripts`
46
+ * ("Unsupported option name") and skips build scripts with `--mode=skip-build` instead. The declared
47
+ * packageManager version decides; without one, a .yarnrc.yml or a Berry lockfile (`__metadata:`) does.
48
+ */
49
+ export function usesYarnBerry(repoPath) {
50
+ const packagePath = join(repoPath, "package.json");
51
+ let declared;
52
+ try {
53
+ declared = JSON.parse(readFileSync(packagePath, "utf8")).packageManager;
54
+ }
55
+ catch {
56
+ declared = undefined;
57
+ }
58
+ const version = typeof declared === "string" ? /^yarn@(\d+)/.exec(declared.trim()) : null;
59
+ if (version)
60
+ return Number(version[1]) >= 2;
61
+ if (existsSync(join(repoPath, ".yarnrc.yml")))
62
+ return true;
63
+ try {
64
+ return /^__metadata:/m.test(readFileSync(join(repoPath, "yarn.lock"), "utf8"));
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ }
44
70
  export function installPlan(repoPath, version, platform = process.platform) {
45
71
  const manager = detectPackageManager(repoPath);
46
72
  const packageSpec = `@diffci.com/diffci@${version}`;
@@ -48,7 +74,9 @@ export function installPlan(repoPath, version, platform = process.platform) {
48
74
  const argsByManager = {
49
75
  npm: ["install", "--save-dev", "--save-exact", "--ignore-scripts", packageSpec],
50
76
  pnpm: ["add", "--save-dev", "--save-exact", "--ignore-scripts", packageSpec],
51
- yarn: ["add", "--dev", "--exact", "--ignore-scripts", packageSpec],
77
+ yarn: manager === "yarn" && usesYarnBerry(repoPath)
78
+ ? ["add", "--dev", "--exact", "--mode=skip-build", packageSpec]
79
+ : ["add", "--dev", "--exact", "--ignore-scripts", packageSpec],
52
80
  bun: ["add", "--dev", "--exact", "--ignore-scripts", packageSpec],
53
81
  };
54
82
  const managerArgs = argsByManager[manager];
@@ -1,4 +1,4 @@
1
- import type { ObservationReport } from "./report.js";
1
+ import { type ObservationReport } from "./report.js";
2
2
  /**
3
3
  * The GitHub job summary for `diffci observe`: the place most people will ever read a report, so it
4
4
  * leads with the answer (what this change affects) and keeps the full text summary one click away.