diffpact 0.0.0-stage → 0.4.2

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/dist/report.js ADDED
@@ -0,0 +1,220 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { canonicalJson, canonicalSha256 } from './canonical-json.js';
4
+ import { validateContract, validateReceiptBasic, validateReviewBasic } from './schema.js';
5
+ import { EXIT_INCOMPLETE } from './types.js';
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+ function pactDirectory(contractPath , cwd = process.cwd()) {
26
+ return path.dirname(path.resolve(cwd, contractPath));
27
+ }
28
+
29
+ function readJson(file ) {
30
+ try {
31
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
32
+ } catch (err) {
33
+ throw new Error(`${file}: ${(err ).message}`);
34
+ }
35
+ }
36
+
37
+ function readJsonLines(file ) {
38
+ if (!fs.existsSync(file)) return [];
39
+ return fs.readFileSync(file, 'utf8').split(/\r?\n/).flatMap((line, index) => {
40
+ if (!line.trim()) return [];
41
+ try {
42
+ return [JSON.parse(line) ];
43
+ } catch {
44
+ throw new Error(`${file}:${index + 1}: invalid JSON`);
45
+ }
46
+ });
47
+ }
48
+
49
+ function validateLedgerEvent(raw ) {
50
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
51
+ throw new Error('Invalid ledger event');
52
+ }
53
+ const event = raw ;
54
+ if (
55
+ typeof event.timestamp !== 'string' || !Number.isFinite(Date.parse(event.timestamp)) ||
56
+ !['verify', 'review', 'amend', 'delegate', 'status'].includes(String(event.kind)) ||
57
+ typeof event.task_id !== 'string' || !event.task_id.trim() ||
58
+ ![0, 1, 2, 3].includes(event.exit_code ) ||
59
+ typeof event.summary !== 'string' ||
60
+ (event.artifact_sha256 !== undefined &&
61
+ (typeof event.artifact_sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(event.artifact_sha256)))
62
+ ) {
63
+ throw new Error('Invalid ledger event fields');
64
+ }
65
+ return raw ;
66
+ }
67
+
68
+ export function appendLedgerEvent(
69
+ contractPath ,
70
+ event ,
71
+ cwd
72
+ ) {
73
+ const record = validateLedgerEvent({ ...event, timestamp: event.timestamp ?? new Date().toISOString() });
74
+ const pactDir = pactDirectory(contractPath, cwd);
75
+ fs.mkdirSync(pactDir, { recursive: true });
76
+ const file = path.join(pactDir, 'ledger.jsonl');
77
+ // Preserve a valid final record even when an external writer omitted its newline.
78
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
79
+ const separator = existing.length > 0 && !existing.endsWith('\n') ? '\n' : '';
80
+ fs.appendFileSync(file, separator + canonicalJson(record) + '\n');
81
+ return record;
82
+ }
83
+
84
+ export function readLedgerEvents(contractPath , cwd ) {
85
+ return readJsonLines(path.join(pactDirectory(contractPath, cwd), 'ledger.jsonl')).map(validateLedgerEvent);
86
+ }
87
+
88
+ function markdown(value ) {
89
+ return String(value)
90
+ .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
91
+ .replace(/\\/g, '&#92;').replace(/\|/g, '&#124;').replace(/`/g, '&#96;')
92
+ .replace(/\*/g, '&#42;').replace(/_/g, '&#95;').replace(/\[/g, '&#91;').replace(/\]/g, '&#93;')
93
+ .replace(/[\r\n]+/g, ' ');
94
+ }
95
+
96
+ /** Summarize persisted evidence; this does not rerun verification or the live Git status gate. */
97
+ export function generateTaskReport(options ) {
98
+ try {
99
+ const contractAbs = path.resolve(options.cwd ?? process.cwd(), options.contractPath);
100
+ const pactDir = path.dirname(contractAbs);
101
+ const contract = validateContract(readJson(contractAbs));
102
+ const contractSha256 = canonicalSha256('diffpact/contract/v0.1', contract);
103
+ const receiptPath = path.join(pactDir, 'receipt.json');
104
+ const receipt = fs.existsSync(receiptPath) ? validateReceiptBasic(readJson(receiptPath)) : null;
105
+ const statuses = ['pass', 'violation', 'incomplete', 'stale'] ;
106
+ if (receipt && (!statuses.includes(receipt.status) || statuses[receipt.exit_code] !== receipt.status)) {
107
+ throw new Error('Invalid receipt status or exit_code');
108
+ }
109
+ const exitCode = receipt?.exit_code ?? EXIT_INCOMPLETE;
110
+ const status = receipt?.status ?? 'incomplete';
111
+ const reviewsDir = path.join(pactDir, 'reviews');
112
+ const reviewPaths = fs.existsSync(reviewsDir)
113
+ ? fs.readdirSync(reviewsDir).filter((file) => file.endsWith('.json')).sort().map((file) => path.join(reviewsDir, file))
114
+ : [];
115
+ const legacyReview = path.join(pactDir, 'review.json');
116
+ if (reviewPaths.length === 0 && fs.existsSync(legacyReview)) reviewPaths.push(legacyReview);
117
+ const reviews = [];
118
+ const seen = new Set ();
119
+ for (const file of reviewPaths) {
120
+ const review = validateReviewBasic(readJson(file));
121
+ if (!seen.has(review.review_sha256)) reviews.push(review);
122
+ seen.add(review.review_sha256);
123
+ }
124
+ const amendmentsPath = path.join(pactDir, 'amendments.jsonl');
125
+ const amendmentCount = fs.existsSync(amendmentsPath) ? readJsonLines(amendmentsPath).length : null;
126
+ const ledgerCount = readLedgerEvents(options.contractPath, options.cwd).length;
127
+ const violations = receipt?.violations ?? [];
128
+ const summary = {
129
+ task_id: contract.task_id,
130
+ starting_sha: contract.starting_sha,
131
+ candidate_sha: receipt?.candidate_sha ?? contract.candidate_sha ?? null,
132
+ contract_sha256: contractSha256,
133
+ status,
134
+ exit_code: exitCode,
135
+ receipt,
136
+ reviews,
137
+ amendment_count: amendmentCount,
138
+ ledger_event_count: ledgerCount
139
+ };
140
+
141
+ if (options.format === 'json') {
142
+ return { exitCode, output: canonicalJson(summary) + '\n' };
143
+ }
144
+ if (options.format === 'sarif') {
145
+ const ruleIds = [...new Set(violations.map((v) => v.code))].sort();
146
+ return {
147
+ exitCode,
148
+ output: canonicalJson({
149
+ $schema: 'https://json.schemastore.org/sarif-2.1.0.json',
150
+ version: '2.1.0',
151
+ runs: [{
152
+ tool: { driver: { name: 'diffpact', version: '0.4.2', rules: ruleIds.map((id) => ({ id })) } },
153
+ results: violations.map((v) => ({
154
+ ruleId: v.code,
155
+ level: exitCode === 1 ? 'error' : 'warning',
156
+ message: { text: v.message },
157
+ ...(v.path ? { locations: [{ physicalLocation: { artifactLocation: {
158
+ uri: v.path.replace(/\\/g, '/').split('/').map(encodeURIComponent).join('/')
159
+ } } }] } : {})
160
+ }))
161
+ }]
162
+ }) + '\n'
163
+ };
164
+ }
165
+ const colors = { pass: 'brightgreen', violation: 'red', incomplete: 'yellow', stale: 'orange' };
166
+ const lines = [
167
+ `## diffpact ![${status.toUpperCase()}](https://img.shields.io/badge/diffpact-${status.toUpperCase()}-${colors[status]}) — ${markdown(contract.task_id)}`,
168
+ '',
169
+ `**starting_sha → candidate_sha:** ${markdown(contract.starting_sha)} → ${markdown(summary.candidate_sha ?? 'pending')}`,
170
+ '',
171
+ `**contract_sha256:** ${contractSha256}`,
172
+ '',
173
+ '### Touched files',
174
+ '',
175
+ `**changed_files:** ${receipt?.diff_summary.changed_files.length ?? 0}`,
176
+ ...(receipt?.diff_summary.changed_files.map((file) => `- ${markdown(file.status)}: ${markdown(file.path)}${file.old_path ? ` (from ${markdown(file.old_path)})` : ''}`) ?? []),
177
+ '',
178
+ `**out_of_bounds_files:** ${receipt?.diff_summary.out_of_bounds_files.length ?? 0}`,
179
+ ...(receipt?.diff_summary.out_of_bounds_files.map((file) => `- ${markdown(file)}`) ?? []),
180
+ '',
181
+ '### Required checks',
182
+ '',
183
+ '| id | exit_code | skipped_count | duration_ms |',
184
+ '| --- | --- | --- | --- |'
185
+ ];
186
+ for (const required of contract.required_checks) {
187
+ const check = receipt?.checks.find((item) => item.id === required.id);
188
+ lines.push(`| ${markdown(required.id)} | ${check?.exit_code ?? 'pending'} | ${check?.skipped_count ?? '—'} | ${check?.duration_ms ?? '—'} |`);
189
+ }
190
+ if ((contract.advisory_checks?.length ?? 0) > 0 || (receipt?.advisory_checks?.length ?? 0) > 0) {
191
+ lines.push('', '### Advisory checks (non-blocking)', '', '| id | exit_code | skipped_count | duration_ms | note |', '| --- | --- | --- | --- | --- |');
192
+ const advisoryDefs = contract.advisory_checks ?? [];
193
+ for (const adv of advisoryDefs) {
194
+ const res = receipt?.advisory_checks?.find((item) => item.id === adv.id);
195
+ const note = res?.spawn_error_code
196
+ ? `spawn error (${res.spawn_error_code})`
197
+ : res?.timed_out
198
+ ? 'timed out'
199
+ : res
200
+ ? res.exit_code === 0
201
+ ? 'ok'
202
+ : 'failed (non-blocking)'
203
+ : 'pending';
204
+ lines.push(`| ${markdown(adv.id)} | ${res?.exit_code ?? 'pending'} | ${res?.skipped_count ?? '—'} | ${res?.duration_ms ?? '—'} | ${markdown(note)} |`);
205
+ }
206
+ }
207
+ lines.push('', '### Independent reviews', '', '| agent_id | harness | verdict | review_sha256 |', '| --- | --- | --- | --- |');
208
+ for (const review of reviews) {
209
+ lines.push(`| ${markdown(review.reviewer_session.agent_id)} | ${markdown(review.reviewer_session.harness)} | ${markdown(review.verdict)} | ${markdown(review.review_sha256)} |`);
210
+ }
211
+ if (reviews.length === 0) lines.push('', 'No reviews recorded.');
212
+ if (amendmentCount !== null) lines.push('', `**Amendments:** ${amendmentCount}`);
213
+ lines.push('', `**Ledger events:** ${ledgerCount}`, '', '### Violations', '');
214
+ lines.push(...(violations.length ? violations.map((v) => `- **${markdown(v.code)}**: ${markdown(v.message)}${v.path ? ` (${markdown(v.path)})` : ''}`) : ['None recorded.']));
215
+ if (!receipt) lines.push('', 'Missing verification receipt.json.');
216
+ return { exitCode, output: lines.join('\n') + '\n' };
217
+ } catch (err) {
218
+ return { exitCode: EXIT_INCOMPLETE, output: '', error: (err ).message };
219
+ }
220
+ }