crossexamdev 0.3.0 → 0.4.0

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.
package/src/upload.js ADDED
@@ -0,0 +1,212 @@
1
+ // crossexam.upload/v1: what a run would send to crossexam cloud.
2
+ //
3
+ // This module only builds and checks the payload. It never opens a network
4
+ // connection: sending arrives with crossexam cloud, and `crossexam upload
5
+ // --dry-run` shows exactly what would leave, so nothing is a surprise later.
6
+ import fs from 'node:fs';
7
+ import { agentOf } from './github.js';
8
+ import { CATEGORY, mutantFingerprint } from './mutate.js';
9
+ import { scrubText } from './redact.js';
10
+
11
+ export const UPLOAD_KIND = 'crossexam.upload/v1';
12
+ export const LIMITS = { excerpt: 2048, text: 600, code: 400, claims: 100, mutants: 500, files: 300, payloadBytes: 2 * 1024 * 1024 };
13
+ const VERDICTS = ['verified', 'contradicted', 'stale', 'unbacked', 'review'];
14
+ const STATUSES = ['MUTATION_KILLED', 'MUTATION_SURVIVED', 'MUTATION_INVALID', 'MUTATION_UNRESOLVED'];
15
+ const RATINGS = ['strong', 'moderate', 'weak', 'inconclusive'];
16
+ export const SOURCE_POLICIES = ['changed-lines', 'none'];
17
+
18
+ const cap = (s, n) => (typeof s === 'string' && s.length > n ? s.slice(0, n) + '…' : s);
19
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
20
+
21
+ export { mutantFingerprint };
22
+
23
+ /** The GitHub Actions run this is part of, from the runner's environment. Null outside Actions. */
24
+ export function githubContext(env = process.env) {
25
+ if (env.GITHUB_ACTIONS !== 'true' || !env.GITHUB_REPOSITORY) return null;
26
+ let pr = null;
27
+ try {
28
+ const ev = env.GITHUB_EVENT_PATH && fs.existsSync(env.GITHUB_EVENT_PATH) ? JSON.parse(fs.readFileSync(env.GITHUB_EVENT_PATH, 'utf8')) : null;
29
+ const p = ev?.pull_request;
30
+ if (p) {
31
+ pr = {
32
+ number: p.number,
33
+ title: p.title || '',
34
+ author: p.user?.login || '',
35
+ headSha: p.head?.sha || null,
36
+ headRef: p.head?.ref || null,
37
+ baseRef: p.base?.ref || null,
38
+ fork: !!(p.head?.repo && p.base?.repo && p.head.repo.full_name !== p.base.repo.full_name),
39
+ agent: agentOf(p.user?.login || '', p.body || ''),
40
+ };
41
+ }
42
+ } catch {
43
+ /* an unreadable event file leaves pr empty, it doesn't stop the run */
44
+ }
45
+ const int = (v) => (v && /^\d+$/.test(v) ? Number(v) : null);
46
+ return {
47
+ repositoryId: int(env.GITHUB_REPOSITORY_ID),
48
+ repositoryOwnerId: int(env.GITHUB_REPOSITORY_OWNER_ID),
49
+ repository: env.GITHUB_REPOSITORY,
50
+ runId: int(env.GITHUB_RUN_ID),
51
+ runAttempt: int(env.GITHUB_RUN_ATTEMPT) ?? 1,
52
+ event: env.GITHUB_EVENT_NAME || null,
53
+ sha: env.GITHUB_SHA || null,
54
+ ref: env.GITHUB_REF || null,
55
+ pr,
56
+ };
57
+ }
58
+
59
+ /** Tell the two kinds of saved report apart. */
60
+ export function classifyReport(j) {
61
+ if (j && j.kind === 'crossexam.mutation/v1') return { verify: null, mutation: j };
62
+ if (j && Array.isArray(j.results)) return { verify: j, mutation: j.strength ?? null };
63
+ throw new Error('not a crossexam report: expected `crossexam verify --json` or `crossexam mutate --json` output');
64
+ }
65
+
66
+ /**
67
+ * Build the payload from a verify result and/or a mutation report.
68
+ * Every string is scrubbed (paths made relative to `root`, home folder to ~,
69
+ * other absolute paths dropped, secrets redacted) and capped.
70
+ */
71
+ export function buildPayload({ verify = null, mutation = null, github = null, agent, cliVersion, root, sourcePolicy = 'changed-lines', now = new Date() } = {}) {
72
+ if (!verify && !mutation) throw new Error('nothing to upload: pass a verify result or a mutation report');
73
+ if (!SOURCE_POLICIES.includes(sourcePolicy)) throw new Error(`source policy must be one of ${SOURCE_POLICIES.join(', ')}`);
74
+ const t = (s, n = LIMITS.text) => cap(scrubText(s, root), n);
75
+ const code = sourcePolicy !== 'none';
76
+
77
+ const claims = (verify?.results ?? []).slice(0, LIMITS.claims).map((r) => ({
78
+ kind: String(r.kind),
79
+ claim: t(r.claim),
80
+ verdict: VERDICTS.includes(r.verdict) ? r.verdict : 'review',
81
+ reason: t(r.reason),
82
+ command: r.evidence?.command ? t(r.evidence.command, 300) : null,
83
+ exitCode: num(r.evidence?.exitCode),
84
+ excerpt: r.evidence?.excerpt ? t(r.evidence.excerpt, LIMITS.excerpt) : null,
85
+ }));
86
+
87
+ let mut = null;
88
+ if (mutation) {
89
+ const s = mutation.summary ?? {};
90
+ mut = {
91
+ scope: t(mutation.scope, 200),
92
+ base: t(mutation.base, 80),
93
+ testCommand: t(mutation.testCommand, 300),
94
+ isolation: { method: mutation.isolation?.method ?? null, sandboxed: !!mutation.isolation?.sandboxed },
95
+ rating: RATINGS.includes(mutation.rating) ? mutation.rating : 'inconclusive',
96
+ blocker: mutation.blocker ? t(mutation.blocker) : null,
97
+ summary: {
98
+ attempted: num(s.attempted) ?? 0,
99
+ killed: num(s.killed) ?? 0,
100
+ survived: num(s.survived) ?? 0,
101
+ invalid: num(s.invalid) ?? 0,
102
+ unresolved: num(s.unresolved) ?? 0,
103
+ remaining: num(s.remaining) ?? 0,
104
+ score: num(s.score),
105
+ ms: num(s.ms),
106
+ },
107
+ files: (mutation.files ?? []).slice(0, LIMITS.files).map((f) => ({
108
+ file: t(f.file, 300),
109
+ language: f.language ?? null,
110
+ changedLines: Array.isArray(f.changedLines) ? f.changedLines.length : num(f.changedLines) ?? 0,
111
+ mutants: num(f.mutants) ?? 0,
112
+ sha256: typeof f.sha256 === 'string' ? f.sha256 : null,
113
+ })),
114
+ mutants: (mutation.mutants ?? []).slice(0, LIMITS.mutants).map((m) => ({
115
+ fingerprint: typeof m.fingerprint === "string" && /^[0-9a-f]{32}$/.test(m.fingerprint) ? m.fingerprint : mutantFingerprint(m),
116
+ file: t(m.file, 300),
117
+ line: num(m.line),
118
+ col: num(m.col),
119
+ function: m.function ? t(m.function, 120) : null,
120
+ operator: String(m.operator),
121
+ category: m.category ?? CATEGORY[m.operator] ?? null,
122
+ status: STATUSES.includes(m.status) ? m.status : 'MUTATION_UNRESOLVED',
123
+ why: m.why ? t(m.why) : null,
124
+ ms: num(m.ms),
125
+ // the changed code itself only travels when the project allows it
126
+ original: code ? t(m.original, LIMITS.code) : null,
127
+ replacement: code ? t(m.replacement, LIMITS.code) : null,
128
+ before: code && m.before ? t(m.before, LIMITS.code) : null,
129
+ after: code && m.after ? t(m.after, LIMITS.code) : null,
130
+ })),
131
+ execution: mutation.execution
132
+ ? { mutantsGenerated: num(mutation.execution.mutantsGenerated), mutantsPlanned: num(mutation.execution.mutantsPlanned), testRuns: num(mutation.execution.testRuns), durationMs: num(mutation.execution.durationMs), gitUnchanged: mutation.execution.gitUnchanged ?? null }
133
+ : null,
134
+ };
135
+ }
136
+
137
+ const payload = {
138
+ kind: UPLOAD_KIND,
139
+ cli: String(cliVersion),
140
+ createdAt: now.toISOString(),
141
+ sourcePolicy,
142
+ repository: github?.repository ?? (mutation?.repo ? t(mutation.repo, 200) : null),
143
+ github: github
144
+ ? {
145
+ repositoryId: github.repositoryId,
146
+ repositoryOwnerId: github.repositoryOwnerId,
147
+ repository: github.repository,
148
+ runId: github.runId,
149
+ runAttempt: github.runAttempt,
150
+ event: github.event,
151
+ sha: github.sha,
152
+ ref: github.ref,
153
+ pr: github.pr ? { number: github.pr.number, title: t(github.pr.title, 300), author: github.pr.author, headSha: github.pr.headSha, headRef: github.pr.headRef, baseRef: github.pr.baseRef, fork: github.pr.fork } : null,
154
+ }
155
+ : null,
156
+ agent: agent || github?.pr?.agent || 'unknown',
157
+ claims,
158
+ mutation: mut,
159
+ };
160
+ const size = Buffer.byteLength(JSON.stringify(payload));
161
+ if (size > LIMITS.payloadBytes) throw new Error(`payload is ${size} bytes, over the ${LIMITS.payloadBytes}-byte limit; run fewer mutants (--max) or use --source none`);
162
+ return payload;
163
+ }
164
+
165
+ /**
166
+ * Check a payload against crossexam.upload/v1 (docs/upload.schema.json).
167
+ * Returns a list of problems; empty means valid. Cloud runs the same checks.
168
+ */
169
+ export function validatePayload(p) {
170
+ const errs = [];
171
+ const need = (cond, msg) => cond || errs.push(msg);
172
+ const str = (v) => typeof v === 'string';
173
+ const optStr = (v) => v === null || v === undefined || typeof v === 'string';
174
+ const optNum = (v) => v === null || v === undefined || (typeof v === 'number' && Number.isFinite(v));
175
+ need(p && typeof p === 'object', 'payload must be an object');
176
+ if (errs.length) return errs;
177
+ need(p.kind === UPLOAD_KIND, `kind must be ${UPLOAD_KIND}`);
178
+ need(str(p.cli), 'cli must be a string');
179
+ need(str(p.createdAt) && !Number.isNaN(Date.parse(p.createdAt)), 'createdAt must be an ISO date');
180
+ need(SOURCE_POLICIES.includes(p.sourcePolicy), 'sourcePolicy is not recognised');
181
+ need(optStr(p.repository), 'repository must be a string or null');
182
+ need(str(p.agent), 'agent must be a string');
183
+ need(Array.isArray(p.claims) && p.claims.length <= LIMITS.claims, `claims must be an array of at most ${LIMITS.claims}`);
184
+ for (const [i, c] of (p.claims ?? []).entries()) {
185
+ need(str(c.kind) && str(c.claim), `claims[${i}] needs kind and claim`);
186
+ need(VERDICTS.includes(c.verdict), `claims[${i}].verdict is not recognised`);
187
+ need(optNum(c.exitCode), `claims[${i}].exitCode must be a number or null`);
188
+ need(!c.excerpt || c.excerpt.length <= LIMITS.excerpt + 1, `claims[${i}].excerpt is too long`);
189
+ }
190
+ if (p.github !== null && p.github !== undefined) {
191
+ need(str(p.github.repository), 'github.repository is required');
192
+ need(optNum(p.github.repositoryId) && optNum(p.github.runId), 'github ids must be numbers');
193
+ }
194
+ if (p.mutation !== null && p.mutation !== undefined) {
195
+ const m = p.mutation;
196
+ need(RATINGS.includes(m.rating), 'mutation.rating is not recognised');
197
+ need(m.summary && ['attempted', 'killed', 'survived', 'invalid', 'unresolved'].every((k) => typeof m.summary[k] === 'number'), 'mutation.summary needs the counts');
198
+ need(m.summary?.score === null || (typeof m.summary?.score === 'number' && m.summary.score >= 0 && m.summary.score <= 1), 'mutation.summary.score must be 0..1 or null');
199
+ need(Array.isArray(m.mutants) && m.mutants.length <= LIMITS.mutants, `mutation.mutants must be an array of at most ${LIMITS.mutants}`);
200
+ for (const [i, x] of (m.mutants ?? []).entries()) {
201
+ need(/^[0-9a-f]{32}$/.test(x.fingerprint ?? ''), `mutants[${i}].fingerprint is malformed`);
202
+ need(str(x.file) && str(x.operator), `mutants[${i}] needs file and operator`);
203
+ need(STATUSES.includes(x.status), `mutants[${i}].status is not recognised`);
204
+ if (p.sourcePolicy === 'none') need(x.before == null && x.after == null && x.original == null && x.replacement == null, `mutants[${i}] carries code under source policy none`);
205
+ }
206
+ }
207
+ need(p.claims?.length || p.mutation, 'payload has neither claims nor a mutation report');
208
+ // nothing that looks like a local absolute path may travel
209
+ const leak = JSON.stringify(p).match(/(?:[A-Za-z]:\\\\|\/(?:home|Users|root)\/[^"\s/]+)/);
210
+ need(!leak, `payload contains a local path (${leak?.[0]})`);
211
+ return errs;
212
+ }