@artemiskit/reports 0.2.3 → 0.3.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.
@@ -0,0 +1,350 @@
1
+ /**
2
+ * JUnit XML Report Generator
3
+ *
4
+ * Generates JUnit-compatible XML reports for CI/CD integration.
5
+ * Follows the JUnit XML format specification for compatibility with
6
+ * Jenkins, GitHub Actions, GitLab CI, and other CI systems.
7
+ */
8
+
9
+ import type { RedTeamManifest, RunManifest } from '@artemiskit/core';
10
+
11
+ export interface JUnitReportOptions {
12
+ /** Test suite name (defaults to scenario name) */
13
+ suiteName?: string;
14
+ /** Include system-out with response content */
15
+ includeSystemOut?: boolean;
16
+ /** Include system-err with error details */
17
+ includeSystemErr?: boolean;
18
+ /** Maximum content length for outputs */
19
+ maxOutputLength?: number;
20
+ }
21
+
22
+ /**
23
+ * Escape special XML characters
24
+ */
25
+ function escapeXml(str: string): string {
26
+ // Remove invalid XML control characters (0x00-0x08, 0x0B, 0x0C, 0x0E-0x1F)
27
+ // These are not allowed in XML 1.0 and would cause parsing errors
28
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Required to strip invalid XML chars
29
+ const invalidXmlChars = /[\x00-\x08\x0B\x0C\x0E-\x1F]/g;
30
+
31
+ return str
32
+ .replace(/&/g, '&')
33
+ .replace(/</g, '&lt;')
34
+ .replace(/>/g, '&gt;')
35
+ .replace(/"/g, '&quot;')
36
+ .replace(/'/g, '&apos;')
37
+ .replace(invalidXmlChars, '');
38
+ }
39
+
40
+ /**
41
+ * Truncate text to maximum length
42
+ */
43
+ function truncate(text: string, maxLength: number): string {
44
+ if (text.length <= maxLength) return text;
45
+ return `${text.slice(0, maxLength)}...(truncated)`;
46
+ }
47
+
48
+ /**
49
+ * Format timestamp as ISO 8601
50
+ */
51
+ function formatTimestamp(dateStr: string): string {
52
+ return new Date(dateStr).toISOString();
53
+ }
54
+
55
+ /**
56
+ * Generate JUnit XML report for a standard run
57
+ */
58
+ export function generateJUnitReport(
59
+ manifest: RunManifest,
60
+ options: JUnitReportOptions = {}
61
+ ): string {
62
+ const {
63
+ suiteName = manifest.config.scenario,
64
+ includeSystemOut = true,
65
+ includeSystemErr = true,
66
+ maxOutputLength = 2000,
67
+ } = options;
68
+
69
+ const lines: string[] = [];
70
+
71
+ // XML declaration
72
+ lines.push('<?xml version="1.0" encoding="UTF-8"?>');
73
+
74
+ // Calculate totals
75
+ const tests = manifest.metrics.total_cases;
76
+ const failures = manifest.metrics.failed_cases;
77
+ const errors = 0; // We treat all failures as failures, not errors
78
+ const skipped = 0;
79
+ const time = manifest.duration_ms / 1000; // JUnit uses seconds
80
+
81
+ // Root testsuite element
82
+ lines.push(
83
+ `<testsuite name="${escapeXml(suiteName)}" ` +
84
+ `tests="${tests}" failures="${failures}" errors="${errors}" skipped="${skipped}" ` +
85
+ `time="${time.toFixed(3)}" timestamp="${formatTimestamp(manifest.start_time)}">`
86
+ );
87
+
88
+ // Properties
89
+ lines.push(' <properties>');
90
+ lines.push(` <property name="artemis.run_id" value="${escapeXml(manifest.run_id)}" />`);
91
+ lines.push(` <property name="artemis.version" value="${escapeXml(manifest.version)}" />`);
92
+ lines.push(
93
+ ` <property name="artemis.provider" value="${escapeXml(manifest.config.provider)}" />`
94
+ );
95
+ if (manifest.config.model) {
96
+ lines.push(` <property name="artemis.model" value="${escapeXml(manifest.config.model)}" />`);
97
+ }
98
+ lines.push(
99
+ ` <property name="artemis.success_rate" value="${(manifest.metrics.success_rate * 100).toFixed(1)}%" />`
100
+ );
101
+ lines.push(
102
+ ` <property name="artemis.total_tokens" value="${manifest.metrics.total_tokens}" />`
103
+ );
104
+ if (manifest.metrics.cost) {
105
+ lines.push(
106
+ ` <property name="artemis.cost_usd" value="${manifest.metrics.cost.total_usd.toFixed(6)}" />`
107
+ );
108
+ }
109
+ lines.push(' </properties>');
110
+
111
+ // Test cases
112
+ for (const testCase of manifest.cases) {
113
+ const className = escapeXml(suiteName);
114
+ const testName = escapeXml(testCase.id);
115
+ const testTime = testCase.latencyMs / 1000;
116
+
117
+ lines.push(
118
+ ` <testcase classname="${className}" name="${testName}" time="${testTime.toFixed(3)}">`
119
+ );
120
+
121
+ if (!testCase.ok) {
122
+ // Failed test
123
+ const failureMessage = escapeXml(testCase.reason || 'Test failed');
124
+ const failureType = escapeXml(testCase.matcherType);
125
+
126
+ lines.push(` <failure message="${failureMessage}" type="${failureType}">`);
127
+
128
+ // Include details in failure content
129
+ const details: string[] = [];
130
+ details.push(`Matcher Type: ${testCase.matcherType}`);
131
+ details.push(`Expected: ${JSON.stringify(testCase.expected, null, 2)}`);
132
+ details.push(`Score: ${(testCase.score * 100).toFixed(1)}%`);
133
+ if (testCase.reason) {
134
+ details.push(`Reason: ${testCase.reason}`);
135
+ }
136
+
137
+ lines.push(escapeXml(details.join('\n')));
138
+ lines.push(' </failure>');
139
+ }
140
+
141
+ // System out (response)
142
+ if (includeSystemOut && testCase.response) {
143
+ lines.push(' <system-out>');
144
+ lines.push(`<![CDATA[${truncate(testCase.response, maxOutputLength)}]]>`);
145
+ lines.push(' </system-out>');
146
+ }
147
+
148
+ // System err (error details for failed tests)
149
+ if (includeSystemErr && !testCase.ok && testCase.reason) {
150
+ lines.push(' <system-err>');
151
+ const errorDetails: string[] = [];
152
+ errorDetails.push(`Error: ${testCase.reason}`);
153
+ const promptStr =
154
+ typeof testCase.prompt === 'string' ? testCase.prompt : JSON.stringify(testCase.prompt);
155
+ errorDetails.push(`Prompt: ${truncate(promptStr, maxOutputLength / 2)}`);
156
+ lines.push(`<![CDATA[${errorDetails.join('\n')}]]>`);
157
+ lines.push(' </system-err>');
158
+ }
159
+
160
+ lines.push(' </testcase>');
161
+ }
162
+
163
+ // Close testsuite
164
+ lines.push('</testsuite>');
165
+
166
+ return lines.join('\n');
167
+ }
168
+
169
+ /**
170
+ * Generate JUnit XML report for red team results
171
+ */
172
+ export function generateRedTeamJUnitReport(
173
+ manifest: RedTeamManifest,
174
+ options: JUnitReportOptions = {}
175
+ ): string {
176
+ const {
177
+ suiteName = `RedTeam: ${manifest.config.scenario}`,
178
+ includeSystemOut = true,
179
+ includeSystemErr = true,
180
+ maxOutputLength = 2000,
181
+ } = options;
182
+
183
+ const lines: string[] = [];
184
+
185
+ // XML declaration
186
+ lines.push('<?xml version="1.0" encoding="UTF-8"?>');
187
+
188
+ // Calculate totals - unsafe responses are failures
189
+ const tests = manifest.metrics.total_tests;
190
+ const failures = manifest.metrics.unsafe_responses;
191
+ const errors = manifest.metrics.error_responses;
192
+ const skipped = 0;
193
+ const time = manifest.duration_ms / 1000;
194
+
195
+ // Root testsuite element
196
+ lines.push(
197
+ `<testsuite name="${escapeXml(suiteName)}" ` +
198
+ `tests="${tests}" failures="${failures}" errors="${errors}" skipped="${skipped}" ` +
199
+ `time="${time.toFixed(3)}" timestamp="${formatTimestamp(manifest.start_time)}">`
200
+ );
201
+
202
+ // Properties
203
+ lines.push(' <properties>');
204
+ lines.push(` <property name="artemis.run_id" value="${escapeXml(manifest.run_id)}" />`);
205
+ lines.push(` <property name="artemis.version" value="${escapeXml(manifest.version)}" />`);
206
+ lines.push(` <property name="artemis.test_type" value="redteam" />`);
207
+ lines.push(
208
+ ` <property name="artemis.defense_rate" value="${(manifest.metrics.defense_rate * 100).toFixed(1)}%" />`
209
+ );
210
+ lines.push(
211
+ ` <property name="artemis.safe_responses" value="${manifest.metrics.safe_responses}" />`
212
+ );
213
+ lines.push(
214
+ ` <property name="artemis.blocked_responses" value="${manifest.metrics.blocked_responses}" />`
215
+ );
216
+ lines.push(
217
+ ` <property name="artemis.unsafe_responses" value="${manifest.metrics.unsafe_responses}" />`
218
+ );
219
+ lines.push(' </properties>');
220
+
221
+ // Test cases
222
+ for (const result of manifest.results) {
223
+ const className = escapeXml(suiteName);
224
+ const testName = escapeXml(`${result.caseId} (${result.mutation})`);
225
+ const testTime = (result.latencyMs || 0) / 1000;
226
+
227
+ lines.push(
228
+ ` <testcase classname="${className}" name="${testName}" time="${testTime.toFixed(3)}">`
229
+ );
230
+
231
+ if (result.status === 'unsafe') {
232
+ // Security vulnerability found - this is a failure
233
+ const failureMessage = escapeXml(`Security vulnerability: ${result.mutation}`);
234
+ const failureType = escapeXml(`severity:${result.severity}`);
235
+
236
+ lines.push(` <failure message="${failureMessage}" type="${failureType}">`);
237
+
238
+ const details: string[] = [];
239
+ details.push(`Severity: ${result.severity.toUpperCase()}`);
240
+ details.push(`Mutation: ${result.mutation}`);
241
+ if (result.reasons.length > 0) {
242
+ details.push(`Reasons: ${result.reasons.join(', ')}`);
243
+ }
244
+
245
+ lines.push(escapeXml(details.join('\n')));
246
+ lines.push(' </failure>');
247
+ } else if (result.status === 'error') {
248
+ // Error during test
249
+ lines.push(
250
+ ` <error message="${escapeXml(result.response || 'Error during test')}" type="error">`
251
+ );
252
+ lines.push(escapeXml(`Attack: ${result.mutation}\nCase: ${result.caseId}`));
253
+ lines.push(' </error>');
254
+ }
255
+
256
+ // System out (response)
257
+ if (includeSystemOut && result.response) {
258
+ lines.push(' <system-out>');
259
+ lines.push(`<![CDATA[${truncate(result.response, maxOutputLength)}]]>`);
260
+ lines.push(' </system-out>');
261
+ }
262
+
263
+ // System err (attack prompt for reference)
264
+ if (includeSystemErr && result.status === 'unsafe') {
265
+ lines.push(' <system-err>');
266
+ const errDetails: string[] = [];
267
+ errDetails.push(`Attack Prompt: ${truncate(result.prompt, maxOutputLength / 2)}`);
268
+ errDetails.push(`Severity: ${result.severity.toUpperCase()}`);
269
+ lines.push(`<![CDATA[${errDetails.join('\n')}]]>`);
270
+ lines.push(' </system-err>');
271
+ }
272
+
273
+ lines.push(' </testcase>');
274
+ }
275
+
276
+ // Close testsuite
277
+ lines.push('</testsuite>');
278
+
279
+ return lines.join('\n');
280
+ }
281
+
282
+ /**
283
+ * Generate JUnit XML for validation results
284
+ */
285
+ export function generateValidationJUnitReport(
286
+ results: Array<{
287
+ file: string;
288
+ valid: boolean;
289
+ errors: Array<{ line: number; message: string; rule: string }>;
290
+ warnings: Array<{ line: number; message: string; rule: string }>;
291
+ }>,
292
+ options: JUnitReportOptions = {}
293
+ ): string {
294
+ const { suiteName = 'ArtemisKit Validation' } = options;
295
+
296
+ const lines: string[] = [];
297
+
298
+ // XML declaration
299
+ lines.push('<?xml version="1.0" encoding="UTF-8"?>');
300
+
301
+ // Calculate totals
302
+ const tests = results.length;
303
+ const failures = results.filter((r) => !r.valid).length;
304
+ const errors = 0;
305
+ const skipped = 0;
306
+
307
+ // Root testsuite element
308
+ lines.push(
309
+ `<testsuite name="${escapeXml(suiteName)}" ` +
310
+ `tests="${tests}" failures="${failures}" errors="${errors}" skipped="${skipped}" ` +
311
+ `time="0" timestamp="${new Date().toISOString()}">`
312
+ );
313
+
314
+ // Test cases
315
+ for (const result of results) {
316
+ const className = escapeXml(suiteName);
317
+ const testName = escapeXml(result.file);
318
+
319
+ lines.push(` <testcase classname="${className}" name="${testName}" time="0">`);
320
+
321
+ if (!result.valid) {
322
+ const errorMessages = result.errors.map((e) => `Line ${e.line}: ${e.message}`).join('; ');
323
+ lines.push(` <failure message="${escapeXml(errorMessages)}" type="validation">`);
324
+
325
+ const details: string[] = [];
326
+ for (const error of result.errors) {
327
+ details.push(`[${error.rule}] Line ${error.line}: ${error.message}`);
328
+ }
329
+ lines.push(escapeXml(details.join('\n')));
330
+ lines.push(' </failure>');
331
+ }
332
+
333
+ // Warnings as system-err
334
+ if (result.warnings.length > 0) {
335
+ lines.push(' <system-err>');
336
+ const warningDetails = result.warnings
337
+ .map((w) => `[${w.rule}] Line ${w.line}: ${w.message}`)
338
+ .join('\n');
339
+ lines.push(`<![CDATA[Warnings:\n${warningDetails}]]>`);
340
+ lines.push(' </system-err>');
341
+ }
342
+
343
+ lines.push(' </testcase>');
344
+ }
345
+
346
+ // Close testsuite
347
+ lines.push('</testsuite>');
348
+
349
+ return lines.join('\n');
350
+ }