@diffci.com/diffci 0.3.21 → 0.3.23

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 (67) hide show
  1. package/dist-client/src/client/agent-identity.d.ts +26 -0
  2. package/dist-client/src/client/agent-identity.js +62 -0
  3. package/dist-client/src/client/agent-selection.d.ts +55 -0
  4. package/dist-client/src/client/cli.d.ts +2 -0
  5. package/dist-client/src/client/cli.js +75 -4
  6. package/dist-client/src/client/command-batches.d.ts +27 -0
  7. package/dist-client/src/client/command-batches.js +8 -1
  8. package/dist-client/src/client/context.d.ts +47 -0
  9. package/dist-client/src/client/delivery-warning.d.ts +1 -0
  10. package/dist-client/src/client/economics.d.ts +17 -0
  11. package/dist-client/src/client/enforce-misses-collect.d.ts +49 -0
  12. package/dist-client/src/client/enforce-misses.d.ts +124 -0
  13. package/dist-client/src/client/enforce-policy.d.ts +33 -0
  14. package/dist-client/src/client/failure-baseline.d.ts +67 -0
  15. package/dist-client/src/client/failure-baseline.js +43 -19
  16. package/dist-client/src/client/feedback-prompt.d.ts +6 -0
  17. package/dist-client/src/client/full-command.d.ts +16 -0
  18. package/dist-client/src/client/gate-checks.d.ts +54 -0
  19. package/dist-client/src/client/gate-checks.js +16 -4
  20. package/dist-client/src/client/gate.d.ts +154 -0
  21. package/dist-client/src/client/hook.d.ts +27 -0
  22. package/dist-client/src/client/install.d.ts +19 -0
  23. package/dist-client/src/client/mcp.d.ts +2 -0
  24. package/dist-client/src/client/observe.d.ts +52 -0
  25. package/dist-client/src/client/observe.js +25 -3
  26. package/dist-client/src/client/package-identity.d.ts +14 -0
  27. package/dist-client/src/client/pilot-packet.d.ts +6 -0
  28. package/dist-client/src/client/report.d.ts +265 -0
  29. package/dist-client/src/client/selected-coverage.d.ts +39 -0
  30. package/dist-client/src/client/selected-coverage.js +159 -0
  31. package/dist-client/src/client/shared-graph-cache.d.ts +113 -0
  32. package/dist-client/src/client/shared-graph-cache.js +347 -0
  33. package/dist-client/src/client/spec-conflicts.d.ts +19 -0
  34. package/dist-client/src/client/submit.d.ts +61 -0
  35. package/dist-client/src/client/telemetry.d.ts +13 -0
  36. package/dist-client/src/client/usage-signal.d.ts +19 -0
  37. package/dist-client/src/client/verify-savings.d.ts +188 -0
  38. package/dist-client/src/client/verify-savings.js +4 -0
  39. package/dist-client/src/client/verify.d.ts +113 -0
  40. package/dist-client/src/client/verify.js +56 -16
  41. package/dist-client/src/client/workflow-guard.d.ts +59 -0
  42. package/dist-client/src/client/workflow-guard.js +267 -0
  43. package/dist-client/src/client/workflow-templates.d.ts +8 -0
  44. package/dist-client/src/client/working-tree.d.ts +26 -0
  45. package/dist-client/src/preflight/fingerprint.d.ts +29 -0
  46. package/dist-client/src/preflight/taxonomy.d.ts +10 -0
  47. package/node_modules/@diffci.com/core/README.md +4 -0
  48. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +3 -0
  49. package/node_modules/@diffci.com/core/dist/git/git-diff.js +110 -10
  50. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  51. package/node_modules/@diffci.com/core/dist/git/types.d.ts +6 -2
  52. package/node_modules/@diffci.com/core/dist/planner/test-command.d.ts +2 -0
  53. package/node_modules/@diffci.com/core/dist/planner/test-command.js +53 -1
  54. package/node_modules/@diffci.com/core/dist/planner/test-command.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 +17 -1
  57. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  58. package/node_modules/@diffci.com/core/dist/repo/pnpm-lockfile.d.ts +6 -0
  59. package/node_modules/@diffci.com/core/dist/repo/pnpm-lockfile.js +161 -0
  60. package/node_modules/@diffci.com/core/dist/repo/pnpm-lockfile.js.map +1 -0
  61. package/node_modules/@diffci.com/core/package.json +1 -1
  62. package/node_modules/@diffci.com/core/src/git/git-diff.ts +95 -9
  63. package/node_modules/@diffci.com/core/src/git/types.ts +6 -2
  64. package/node_modules/@diffci.com/core/src/planner/test-command.ts +52 -1
  65. package/node_modules/@diffci.com/core/src/repo/impact.ts +16 -1
  66. package/node_modules/@diffci.com/core/src/repo/pnpm-lockfile.ts +147 -0
  67. package/package.json +9 -2
@@ -0,0 +1,265 @@
1
+ /**
2
+ * The observation report - DiffCI's client-side wire format (Phase 02, 2026-08-26).
3
+ *
4
+ * WHY THIS EXISTS. Every earlier pipeline in this repository analysed OTHER people's repositories on
5
+ * DiffCI's own infrastructure: a container cloned the source, built the graph, and kept the evidence.
6
+ * That shape cannot be installed by a stranger - it asks them to hand a private tree to a service they
7
+ * have not evaluated, before they have seen a single number. Phase 02 inverts it. The analysis runs on
8
+ * the repository's own runner, inside its own CI, against a checkout it already has, and the only thing
9
+ * that ever leaves is this document.
10
+ *
11
+ * So this file is the privacy boundary as much as it is a type. Everything DiffCI could learn about a
12
+ * repository it does not host is a field below, and `payload` states in the document itself what the
13
+ * document contains. If a future field would carry file CONTENT, an environment variable, or anything
14
+ * a `git show` would print, it does not belong here - it belongs in a design conversation first.
15
+ *
16
+ * VERSIONING. `schema` is checked by consumers before anything else is read. A change that removes or
17
+ * repurposes a field is a new version, not an edit to this one: reports are produced by a pinned action
18
+ * inside someone else's CI, and old producers keep sending v1 long after the server has moved on.
19
+ */
20
+ /** Wire identifier. Consumers MUST reject a document whose `schema` they do not recognise. */
21
+ export declare const OBSERVATION_SCHEMA: "diffci.observation.v1";
22
+ /** How far the observation got. `REFUSED` is a stated limit, `ERROR` is a defect - never merge them. */
23
+ export type ObservationStatus = "OBSERVED" | "REFUSED" | "ERROR";
24
+ /**
25
+ * The stage a refusal or error came from, in pipeline order. Recorded even on success (`complete`), so
26
+ * a week of reports can be counted by where they stopped without parsing prose.
27
+ */
28
+ export type ObservationStage = "context" | "eligibility" | "delta" | "graph" | "impact" | "command" | "complete";
29
+ /** Which side produced the base/head pair, so a reader can tell a real PR range from a fallback. */
30
+ export type CommitRangeSource = "explicit-flags" | "pull-request-event" | "push-event" | "head-parent";
31
+ export interface ObservationCommitRange {
32
+ baseSha: string;
33
+ headSha: string;
34
+ source: CommitRangeSource;
35
+ /** Set when base and head diverged and the merge base was used as the real base. */
36
+ mergeBaseSha?: string;
37
+ }
38
+ export interface ObservationRepository {
39
+ provider: "github" | "unknown";
40
+ /** "owner/name". The only repository identifier sent; never a URL carrying a token. */
41
+ ownerName?: string;
42
+ defaultBranch?: string;
43
+ /** GitHub's numeric repository id when the environment supplies it - survives a rename. */
44
+ providerRepositoryId?: string;
45
+ }
46
+ export interface ObservationCi {
47
+ provider: "github-actions" | "local" | "unknown";
48
+ runId?: string;
49
+ runAttempt?: string;
50
+ workflow?: string;
51
+ job?: string;
52
+ event?: string;
53
+ ref?: string;
54
+ /**
55
+ * True when the trigger cannot be tied to a specific commit range without guessing (`schedule`,
56
+ * `workflow_dispatch`). Recorded, not corrected.
57
+ */
58
+ syntheticTrigger?: boolean;
59
+ }
60
+ /**
61
+ * What this document contains, stated by the document. A repository can verify the claim by reading the
62
+ * file the action uploads - those are the same bytes that would be sent anywhere.
63
+ */
64
+ export interface ObservationPayloadDescription {
65
+ /** Repo-relative paths of changed and selected files. False when --redact-paths was used. */
66
+ includesFilePaths: boolean;
67
+ /** Always false. No field in this schema carries file content, and none may be added. */
68
+ includesFileContents: false;
69
+ /** Always false. The observer reads no process env beyond the CI variables recorded in `ci` and, only
70
+ * with `--agent auto`, the presence of the agent markers named in agent-identity.ts (label, never value). */
71
+ includesEnvironment: false;
72
+ /** Always false. Nothing here is derived from a credential, and none is ever requested. */
73
+ includesCredentials: false;
74
+ /** Set when paths were replaced by stable digests - see `redactPath` below. */
75
+ pathRedaction?: "sha256-12";
76
+ }
77
+ /**
78
+ * Evidence that observing did not change the thing being observed. This is the Phase 02 exit criterion
79
+ * ("CI byte-identical") reduced to something a machine checks on every single run, rather than an
80
+ * assurance given once at install time.
81
+ */
82
+ export interface NonInterferenceEvidence {
83
+ /** `git rev-parse HEAD` before and after. Unequal means the observer moved HEAD. */
84
+ headShaBefore?: string;
85
+ headShaAfter?: string;
86
+ /** Digests of `git status --porcelain`. Unequal means the observer dirtied the working tree. */
87
+ worktreeDigestBefore?: string;
88
+ worktreeDigestAfter?: string;
89
+ /** True only when both pairs above were captured and both matched. Absent capture is not a pass. */
90
+ worktreeUnchanged: boolean;
91
+ /** The report was written outside the repository working tree, so no later build step can see it. */
92
+ reportWrittenOutsideRepository: boolean;
93
+ /** Findings from the workflow guard (src/client/workflow-guard.ts), embedded on every run. */
94
+ workflowFindings: WorkflowFinding[];
95
+ }
96
+ export type WorkflowFindingSeverity = "BLOCKING" | "WARNING" | "INFO";
97
+ export interface WorkflowFinding {
98
+ severity: WorkflowFindingSeverity;
99
+ /** Stable machine code, e.g. "JOB_IS_A_DEPENDENCY". Message text may be reworded; codes may not. */
100
+ code: string;
101
+ message: string;
102
+ workflow: string;
103
+ job?: string;
104
+ }
105
+ export interface TypeScriptProgramMetrics {
106
+ sourceFileLoads: number;
107
+ sourceFileLoadMs: number;
108
+ failedSourceFileLoads: number;
109
+ bundledLibraryLoads: number;
110
+ bundledLibraryLoadMs: number;
111
+ otherDeclarationLoads: number;
112
+ otherDeclarationLoadMs: number;
113
+ implementationLoads: number;
114
+ implementationLoadMs: number;
115
+ }
116
+ /** Optional, additive metrics; unknown or incomplete core telemetry stays absent. */
117
+ export declare function readTypeScriptProgramMetrics(value: unknown): TypeScriptProgramMetrics | undefined;
118
+ export interface ObservationGraph {
119
+ nodes: number;
120
+ edges: number;
121
+ /** The graph's own confidence, before per-delta narrowing. */
122
+ confidence: string;
123
+ /** Confidence after reachability narrowing for this delta - the value that drove the verdict. */
124
+ effectiveConfidence?: string;
125
+ durationMs: number;
126
+ phasesMs?: Record<string, number>;
127
+ typescriptProgram?: TypeScriptProgramMetrics;
128
+ adapterMetrics?: Record<string, {
129
+ phasesMs: Record<string, number>;
130
+ counts: Record<string, number>;
131
+ }>;
132
+ }
133
+ /**
134
+ * The comparator. DiffCI's savings are only ever a difference against something, and the something is a
135
+ * simple path-rule CI (src/planner/path-baseline.ts) - not "the whole suite". Phase 01 found that
136
+ * comparator had been a strawman; carrying it in every report is what stops a later ledger quietly
137
+ * dropping it.
138
+ */
139
+ export interface ObservationBaseline {
140
+ mode: "SELECTIVE" | "FULL";
141
+ selectedTestCount: number;
142
+ /**
143
+ * The test files the path-rule comparator actually selected (2026-08-29, agent generation B).
144
+ *
145
+ * WHY THE COUNT WAS NOT ENOUGH. The comparator is the cheapest credible alternative to DiffCI, so the
146
+ * question that decides whether DiffCI is worth paying for is not "did it run fewer tests than
147
+ * everything" but "did running its choice, plus the analysis that produced it, cost less than running
148
+ * the comparator's choice". Answering that requires EXECUTING the comparator's selection and measuring
149
+ * it, and a count cannot be executed.
150
+ *
151
+ * These are the identities the comparator itself produced (`runPathBaseline().selectedTests`), carried
152
+ * through unchanged and given exactly the same sorting and redaction as DiffCI's own `selectedTests`.
153
+ * They are deliberately NOT reconstructed from `matchedRules`: reconstruction would insert an
154
+ * interpretation layer between the comparator and the harness measuring it, which is the entire thing
155
+ * this field exists to eliminate.
156
+ *
157
+ * INVARIANT: `selectedTests.length === selectedTestCount`. They are derived from one array at the
158
+ * point of construction, so divergence is structurally impossible rather than merely unlikely - and
159
+ * consumers still check, because a count and a list that disagree would silently mismeasure the
160
+ * comparator arm of every economics experiment.
161
+ */
162
+ selectedTests: string[];
163
+ matchedRules: string[];
164
+ }
165
+ export interface ObservationResult {
166
+ mode: "SELECTIVE" | "FULL";
167
+ changedFileCount: number;
168
+ /** Repo-relative paths, replaced by digests when `payload.pathRedaction` is set. */
169
+ changedFiles: string[];
170
+ affectedSourceFileCount: number;
171
+ selectedTests: string[];
172
+ /** Test files the full test command runs: the denominator for any selection ratio. Every
173
+ * discovered test file when the test script could not be modelled (2026-10-21). */
174
+ totalTestCount: number;
175
+ /** Every test file the engine could see, including those no full-suite phase runs. */
176
+ discoveredTestCount?: number;
177
+ /** Affected tests the full test command does not run. Never part of `selectedTests`, which stays a
178
+ * subset of the full suite; verification runs them with `outsideSuiteCommands`. */
179
+ testsOutsideFullSuite?: string[];
180
+ outsideSuiteCommands?: string[];
181
+ /** Phases of the test script, verbatim (`node scripts/test-security.js`), that a selective run must
182
+ * also execute: the selection covers some changed files only through them. Present only when the
183
+ * observation was asked for them (ObserveOptions.selectTestPhases). Like `proposedCommands`, these
184
+ * are commands and are not redacted. */
185
+ testPhases?: string[];
186
+ fallbackReasons: string[];
187
+ /** The command DiffCI would have run. Present even in observe mode - it is the claim being tested. */
188
+ proposedCommands: string[];
189
+ /** Workspace execution can widen affected files to whole state-sharing suites. */
190
+ workspaceCommands?: boolean;
191
+ /** Explicit Go CI universe, when configured by the repository. */
192
+ goScope?: "root-module";
193
+ vueScope?: {
194
+ packageRoot: string;
195
+ testConfig: string;
196
+ };
197
+ scopedTestFiles?: string[];
198
+ /** Set when a selection was made but no runnable command could be built for it. */
199
+ commandRefusalReason?: string;
200
+ /** Selected paths no runner claimed. Non-empty means the command does not cover the selection. */
201
+ unroutedTestPaths: string[];
202
+ /**
203
+ * True when the repository declares a test framework and the engine discovered no test files at all.
204
+ * A blind spot forces FULL: an empty test universe must never read as "nothing to run" (Phase 01 F1).
205
+ */
206
+ blindSpot: boolean;
207
+ riskSignals: Array<{
208
+ level: string;
209
+ reason: string;
210
+ }>;
211
+ graph: ObservationGraph;
212
+ pathBaseline: ObservationBaseline;
213
+ analysisStatus: string;
214
+ }
215
+ export interface ObservationReport {
216
+ schema: typeof OBSERVATION_SCHEMA;
217
+ producedAt: string;
218
+ observer: {
219
+ /** DiffCI's package version. */
220
+ version: string;
221
+ /** The exact DiffCI commit that produced this, when the observer's own checkout is a git repo. */
222
+ engineSha?: string;
223
+ node: string;
224
+ platform: string;
225
+ };
226
+ repository: ObservationRepository;
227
+ ci: ObservationCi;
228
+ commitRange?: ObservationCommitRange;
229
+ status: ObservationStatus;
230
+ stage: ObservationStage;
231
+ /** Present for REFUSED and ERROR. Written for a reader who has to decide whether to act. */
232
+ reason?: string;
233
+ result?: ObservationResult;
234
+ economics?: import("./economics.js").EconomicsDecision;
235
+ /** Opt-in (`--agent`): which AI coding agent the caller says produced this change. */
236
+ agent?: import("./agent-identity.js").ObservationAgent;
237
+ payload: ObservationPayloadDescription;
238
+ nonInterference: NonInterferenceEvidence;
239
+ timings: {
240
+ totalMs: number;
241
+ preObserveMs?: number;
242
+ phasesMs?: Record<string, number>;
243
+ };
244
+ }
245
+ /**
246
+ * Path redaction for repositories that will observe but will not send paths off their runner.
247
+ *
248
+ * A truncated SHA-256 is stable across runs and across repositories, which is exactly the trade being
249
+ * made: the same file redacts to the same digest every time (so selection ratios and per-file trends
250
+ * still work), and a holder of the digest can confirm a GUESSED path but cannot enumerate paths from
251
+ * the digest alone. It is redaction, not anonymisation, and is described that way.
252
+ */
253
+ export declare function redactPath(path: string, hash: (input: string) => string): string;
254
+ /**
255
+ * Minimal structural validation, shared by the producer's own tests and (from Phase 03) by ingest.
256
+ * Deliberately shallow: it checks that a document is the shape this version promises, not that its
257
+ * numbers are true.
258
+ */
259
+ export declare function validateObservationReport(value: unknown): {
260
+ ok: true;
261
+ report: ObservationReport;
262
+ } | {
263
+ ok: false;
264
+ error: string;
265
+ };
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Selected tests the runner would never execute (2026-11-01).
3
+ *
4
+ * WHY. `node --test` reads every file argument as a glob. A selected `src/app/ingest/[...path]/route.test.ts`
5
+ * passed as written is a character class that matches nothing; the other selected files still ran, so
6
+ * the verification exited 0 and reported passed while the one test that covered the change never ran
7
+ * (DentalPresence ebac4289f73a, CLI 0.3.21). Selection was right; execution silently was not.
8
+ *
9
+ * WHAT. Before running, each selected file is matched against the patterns the command hands
10
+ * `node --test`, the way Node's own glob matches them; a file no pattern claims means the selection is
11
+ * not executable as written. After running, the runner's own count is checked: a summary reporting
12
+ * fewer tests (node:test) or test files (vitest, jest) than files were selected means some never ran.
13
+ *
14
+ * 2026-11-02. Both checks passed under CLI 0.3.22 while the file still never ran on Linux. The command
15
+ * was `npx --no-install tsx --test "...[[]...path[]]..."`, and npx hands its arguments to a second
16
+ * `sh -c`, quoting only those with characters such as `(`, `*` or a space; that shell expanded the
17
+ * unquoted class back to the real `[...path]` directory. The pre-run check now models that second
18
+ * shell. The count check could not see one missing file among 120 tests, so a `node --test` selection
19
+ * also runs with a probe that records the file each test process started for (`traceNodeTestFiles`),
20
+ * and a selected file that never started blocks the verification.
21
+ */
22
+ /** The arguments `sh` (or `cmd.exe` on Windows) would hand the program, for the quoting DiffCI emits. */
23
+ export declare function commandArguments(command: string, windows?: boolean): string[];
24
+ /** Selected files no `node --test` pattern in `command` matches. Empty when `command` runs no `node --test`. */
25
+ export declare function unmatchedNodeTests(command: string, selectedTests: readonly string[], windows?: boolean): string[];
26
+ /** Selected files `command` hands `node --test`, which the trace from `traceNodeTestFiles` must show. */
27
+ export declare function selectedNodeTests(command: string, selectedTests: readonly string[], windows?: boolean): string[];
28
+ export interface NodeTestTrace {
29
+ /** Environment for the command: NODE_OPTIONS extended with the probe. */
30
+ env: Record<string, string>;
31
+ /** Repository-relative paths of the files that started, or undefined when none did. */
32
+ read(): string[] | undefined;
33
+ dispose(): void;
34
+ }
35
+ export declare function traceNodeTestFiles(cwd: string, nodeOptions?: string | undefined): NodeTestTrace;
36
+ /** Selected `node --test` files the trace does not show starting. Empty when the trace proves nothing. */
37
+ export declare function unstartedNodeTests(expected: readonly string[], started: readonly string[] | undefined, windows?: boolean): string[];
38
+ /** The test count node:test's summary reports, or the test-file total vitest or jest reports. */
39
+ export declare function runnerTestCount(output: string): number | undefined;
@@ -0,0 +1,159 @@
1
+ import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join, matchesGlob, relative, sep } from "node:path";
4
+ /**
5
+ * Selected tests the runner would never execute (2026-11-01).
6
+ *
7
+ * WHY. `node --test` reads every file argument as a glob. A selected `src/app/ingest/[...path]/route.test.ts`
8
+ * passed as written is a character class that matches nothing; the other selected files still ran, so
9
+ * the verification exited 0 and reported passed while the one test that covered the change never ran
10
+ * (DentalPresence ebac4289f73a, CLI 0.3.21). Selection was right; execution silently was not.
11
+ *
12
+ * WHAT. Before running, each selected file is matched against the patterns the command hands
13
+ * `node --test`, the way Node's own glob matches them; a file no pattern claims means the selection is
14
+ * not executable as written. After running, the runner's own count is checked: a summary reporting
15
+ * fewer tests (node:test) or test files (vitest, jest) than files were selected means some never ran.
16
+ *
17
+ * 2026-11-02. Both checks passed under CLI 0.3.22 while the file still never ran on Linux. The command
18
+ * was `npx --no-install tsx --test "...[[]...path[]]..."`, and npx hands its arguments to a second
19
+ * `sh -c`, quoting only those with characters such as `(`, `*` or a space; that shell expanded the
20
+ * unquoted class back to the real `[...path]` directory. The pre-run check now models that second
21
+ * shell. The count check could not see one missing file among 120 tests, so a `node --test` selection
22
+ * also runs with a probe that records the file each test process started for (`traceNodeTestFiles`),
23
+ * and a selected file that never started blocks the verification.
24
+ */
25
+ /** The arguments `sh` (or `cmd.exe` on Windows) would hand the program, for the quoting DiffCI emits. */
26
+ export function commandArguments(command, windows = process.platform === "win32") {
27
+ const args = [];
28
+ let current;
29
+ let quote;
30
+ for (let index = 0; index < command.length; index++) {
31
+ const character = command[index];
32
+ if (quote) {
33
+ if (character === quote)
34
+ quote = undefined;
35
+ else if (!windows && quote === "\"" && character === "\\" && /["$`\\]/.test(command[index + 1] ?? ""))
36
+ current += command[++index];
37
+ else
38
+ current += character;
39
+ }
40
+ else if (/\s/.test(character)) {
41
+ if (current !== undefined)
42
+ args.push(current);
43
+ current = undefined;
44
+ }
45
+ else if (character === "\"" || (!windows && character === "'")) {
46
+ quote = character;
47
+ current ??= "";
48
+ }
49
+ else if (!windows && character === "\\" && index + 1 < command.length) {
50
+ current = (current ?? "") + command[++index];
51
+ }
52
+ else {
53
+ current = (current ?? "") + character;
54
+ }
55
+ }
56
+ if (current !== undefined)
57
+ args.push(current);
58
+ return args;
59
+ }
60
+ /** Arguments npm's `sh` escaping leaves unquoted when npx re-runs a bin through `sh -c`
61
+ * (@npmcli/promise-spawn): those without whitespace or any of ``"#$&'()*;<>?\`|~``. */
62
+ const NPM_UNQUOTED = /^[^\s"#$&'()*;<>?\\`|~]+$/;
63
+ /** The file patterns of each `node --test` invocation in `command` (directly, or through tsx). Paths
64
+ * npx passes to a second `sh` unquoted are marked: that shell expands a pattern that matches files. */
65
+ function nodeTestPatterns(command, windows) {
66
+ const patterns = [];
67
+ let segment = [];
68
+ for (const arg of [...commandArguments(command, windows), "&&"]) {
69
+ if (arg !== "&&") {
70
+ segment.push(arg);
71
+ continue;
72
+ }
73
+ const testFlag = segment.indexOf("--test");
74
+ if (testFlag > 0 && (segment[0] === "node" || segment.slice(0, testFlag).includes("tsx"))) {
75
+ const viaNpx = !windows && (segment[0] === "npx" || (segment[0] === "npm" && segment[1] === "exec"));
76
+ for (const pattern of segment.slice(testFlag + 1).filter((value) => !value.startsWith("-"))) {
77
+ patterns.push({ pattern, reglobbed: viaNpx && NPM_UNQUOTED.test(pattern) });
78
+ }
79
+ }
80
+ segment = [];
81
+ }
82
+ return patterns;
83
+ }
84
+ /** Whether node --test, handed `pattern` by `command`, would run `path`. A pattern the second shell
85
+ * expands reaches node as the literal path it matched, which node then reads as a glob again. */
86
+ function claims({ pattern, reglobbed }, path) {
87
+ return matchesGlob(path, pattern) && (!reglobbed || matchesGlob(path, path));
88
+ }
89
+ /** Selected files no `node --test` pattern in `command` matches. Empty when `command` runs no `node --test`. */
90
+ export function unmatchedNodeTests(command, selectedTests, windows = process.platform === "win32") {
91
+ const patterns = nodeTestPatterns(command, windows);
92
+ if (patterns.length === 0)
93
+ return [];
94
+ return selectedTests.filter((path) => !patterns.some((pattern) => claims(pattern, path)));
95
+ }
96
+ /** Selected files `command` hands `node --test`, which the trace from `traceNodeTestFiles` must show. */
97
+ export function selectedNodeTests(command, selectedTests, windows = process.platform === "win32") {
98
+ const patterns = nodeTestPatterns(command, windows);
99
+ return selectedTests.filter((path) => patterns.some(({ pattern }) => pattern === path || matchesGlob(path, pattern)));
100
+ }
101
+ /** Records the file each node:test process starts for. node --test runs every file in a child process
102
+ * with NODE_TEST_CONTEXT set and the file as argv[1]; NODE_OPTIONS reaches it through npx and tsx.
103
+ * Under `--test-isolation=none` no child starts and the trace stays empty, which proves nothing. */
104
+ const PROBE = `"use strict";
105
+ if (process.env.NODE_TEST_CONTEXT && process.argv[1] && process.env.DIFFCI_NODE_TEST_TRACE) {
106
+ try { require("node:fs").appendFileSync(process.env.DIFFCI_NODE_TEST_TRACE, process.argv[1] + "\\n"); } catch {}
107
+ }
108
+ `;
109
+ export function traceNodeTestFiles(cwd, nodeOptions = process.env.NODE_OPTIONS) {
110
+ const dir = mkdtempSync(join(tmpdir(), "diffci-node-test-trace-"));
111
+ const probe = join(dir, "probe.cjs");
112
+ const log = join(dir, "started.txt");
113
+ writeFileSync(probe, PROBE);
114
+ // NODE_OPTIONS reads a backslash inside double quotes as an escape; forward slashes work on Windows.
115
+ const required = `--require "${probe.split(sep).join("/")}"`;
116
+ const real = (path) => { try {
117
+ return realpathSync.native(path);
118
+ }
119
+ catch {
120
+ return path;
121
+ } };
122
+ return {
123
+ env: { NODE_OPTIONS: nodeOptions?.trim() ? `${nodeOptions} ${required}` : required, DIFFCI_NODE_TEST_TRACE: log },
124
+ read() {
125
+ let lines;
126
+ try {
127
+ lines = readFileSync(log, "utf8").split("\n").filter(Boolean);
128
+ }
129
+ catch {
130
+ return undefined;
131
+ }
132
+ const root = real(cwd);
133
+ const files = lines.map((file) => relative(root, real(file)).split(sep).join("/"));
134
+ return files.length ? [...new Set(files)].sort() : undefined;
135
+ },
136
+ dispose() { rmSync(dir, { recursive: true, force: true }); },
137
+ };
138
+ }
139
+ /** Selected `node --test` files the trace does not show starting. Empty when the trace proves nothing. */
140
+ export function unstartedNodeTests(expected, started, windows = process.platform === "win32") {
141
+ if (!started?.length)
142
+ return [];
143
+ const key = (path) => windows ? path.toLowerCase() : path;
144
+ const seen = new Set(started.map(key));
145
+ return expected.filter((path) => !seen.has(key(path)));
146
+ }
147
+ /** The test count node:test's summary reports, or the test-file total vitest or jest reports. */
148
+ export function runnerTestCount(output) {
149
+ const node = [...output.matchAll(/^(?:ℹ|#) tests (\d+)\s*$/gm)];
150
+ if (node.length)
151
+ return node.reduce((sum, match) => sum + Number(match[1]), 0);
152
+ const vitest = [...output.matchAll(/^\s*Test Files\s+.*\((\d+)\)\s*$/gm)];
153
+ if (vitest.length)
154
+ return vitest.reduce((sum, match) => sum + Number(match[1]), 0);
155
+ const jest = [...output.matchAll(/^Test Suites:.*?(\d+) total\s*$/gm)];
156
+ if (jest.length)
157
+ return jest.reduce((sum, match) => sum + Number(match[1]), 0);
158
+ return undefined;
159
+ }
@@ -0,0 +1,113 @@
1
+ import type { DependencyGraphResult } from "@diffci.com/core/repo/types";
2
+ import type { GitRunner } from "./context.js";
3
+ export declare const SHARED_GRAPH_CACHE_ENVELOPE_SCHEMA = "diffci.graph-cache.v1";
4
+ export declare const CONTENT_SHA256_HEADER = "x-diffci-content-sha256";
5
+ /** Bumped whenever the portable payload format or the key inputs below change. */
6
+ export declare const SHARED_GRAPH_CACHE_KEY_SCHEMA = "shared-1";
7
+ /**
8
+ * The cache key for the graph of `repoPath` as it is checked out right now, or undefined when no key
9
+ * can honestly describe it. A dirty working tree has no commit that names it, so it is never cached.
10
+ *
11
+ * Inputs: HEAD, the schema of this format, DiffCI's version and engine commit, hashes of the files that
12
+ * steer resolution (tsconfig/package/DiffCI config, lockfiles), whether node_modules is installed, the
13
+ * platform, and the excluded directories. The output is a SHA-256 digest; the commit is not readable from it.
14
+ */
15
+ export declare function deriveSharedGraphCacheKey(input: {
16
+ repoPath: string;
17
+ git: GitRunner;
18
+ version: string;
19
+ engineSha?: string;
20
+ excludeDirs: readonly string[];
21
+ platform?: string;
22
+ }): string | undefined;
23
+ /** Plain, machine-independent JSON: the graph reduced to nodes and edges, the checkout path tokenised. */
24
+ export declare function toPortableGraph(result: DependencyGraphResult, repoPath: string): Record<string, unknown>;
25
+ /** The inverse of toPortableGraph, against this machine's checkout. Undefined for an unrecognised shape. */
26
+ export declare function fromPortableGraph(portable: unknown, repoPath: string): DependencyGraphResult | undefined;
27
+ /** With a team secret, the server sees an HMAC of the key, not the key. Different secrets never collide. */
28
+ export declare function remoteCacheKey(localKey: string, secret?: string): string;
29
+ export declare function encodeEnvelope(remoteKey: string, portable: Record<string, unknown>, options?: {
30
+ secret?: string;
31
+ version?: string;
32
+ }): string;
33
+ /** Undefined for anything that is not exactly an envelope for `remoteKey` that we can read. */
34
+ export declare function decodeEnvelope(remoteKey: string, body: string, secret?: string): unknown;
35
+ /**
36
+ * Where the cache lives, from an explicit URL or the configured ingest URL's origin. Undefined (cache
37
+ * off) for anything unparseable or plaintext to a non-loopback host - a token is never sent over http.
38
+ */
39
+ export declare function resolveSharedGraphCacheBaseUrl(input: {
40
+ cacheUrl?: string;
41
+ apiUrl?: string;
42
+ }): string | undefined;
43
+ export interface RemoteGraphCacheOptions {
44
+ baseUrl: string;
45
+ token: string;
46
+ secret?: string;
47
+ version?: string;
48
+ fetchImpl?: typeof fetch;
49
+ timeoutMs?: number;
50
+ }
51
+ /** The DiffCI Cloud tier. Every method resolves; none throws. */
52
+ export declare class RemoteGraphCache {
53
+ private readonly options;
54
+ constructor(options: RemoteGraphCacheOptions);
55
+ private request;
56
+ /** Portable payload for `localKey`, or undefined on any miss or failure. */
57
+ get(localKey: string): Promise<unknown>;
58
+ put(localKey: string, portable: Record<string, unknown>): Promise<boolean>;
59
+ }
60
+ /** Structural match for GraphCache (src/cache/graph-cache.ts here, or Core's), so either can sit underneath. */
61
+ export interface LocalGraphCacheLike {
62
+ load(key: string): DependencyGraphResult | undefined;
63
+ save(key: string, result: DependencyGraphResult): void;
64
+ }
65
+ export type GraphCacheSource = "local" | "remote";
66
+ export declare class LayeredGraphCache {
67
+ private readonly options;
68
+ private readonly pending;
69
+ /** What the last load did, for a one-line summary. */
70
+ lastOutcome: "local-hit" | "remote-hit" | "miss" | undefined;
71
+ constructor(options: {
72
+ repoPath: string;
73
+ local?: LocalGraphCacheLike;
74
+ remote?: RemoteGraphCache;
75
+ });
76
+ load(key: string): Promise<{
77
+ result: DependencyGraphResult;
78
+ source: GraphCacheSource;
79
+ } | undefined>;
80
+ /** Synchronous to the caller; the remote write runs in the background until flush(). */
81
+ save(key: string, result: DependencyGraphResult): void;
82
+ /** Waits for background uploads, bounded by their own request timeouts. */
83
+ flush(): Promise<void>;
84
+ }
85
+ export interface GraphCacheConfigInput {
86
+ repoPath: string;
87
+ version: string;
88
+ /** --graph-cache-dir / DIFFCI_GRAPH_CACHE_DIR: local tier only, no network. */
89
+ localDir?: string;
90
+ /** --shared-graph-cache / DIFFCI_SHARED_GRAPH_CACHE=1: also use DiffCI Cloud. */
91
+ shared?: boolean;
92
+ /** --graph-cache-url / DIFFCI_GRAPH_CACHE_URL, else derived from the ingest URL's origin. */
93
+ cacheUrl?: string;
94
+ apiUrl?: string;
95
+ token?: string;
96
+ /** DIFFCI_GRAPH_CACHE_SECRET only - never a flag, so it cannot land in shell history or `ps`. */
97
+ secret?: string;
98
+ noSend?: boolean;
99
+ redactPaths?: boolean;
100
+ /** Where a shared cache keeps its local tier when no directory is given. */
101
+ defaultLocalRoot: string;
102
+ local?: (dir: string) => LocalGraphCacheLike;
103
+ fetchImpl?: typeof fetch;
104
+ isInsideRepository: (repoPath: string, candidate: string) => boolean;
105
+ }
106
+ /**
107
+ * The opt-in decision, in one place. No `cache` means no caching at all - the observer's default. Notes say
108
+ * why a requested tier was left off, without ever repeating the token or secret.
109
+ */
110
+ export declare function configureGraphCache(input: GraphCacheConfigInput): {
111
+ cache?: LayeredGraphCache;
112
+ notes: string[];
113
+ };