diffpact 0.0.0-stage → 0.4.3

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 (51) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/LICENSE +21 -0
  3. package/README.md +223 -2
  4. package/bin/diffpact.mjs +15 -0
  5. package/dist/adapters/claude-code.d.ts +21 -0
  6. package/dist/adapters/claude-code.js +191 -0
  7. package/dist/adapters/codex.d.ts +31 -0
  8. package/dist/adapters/codex.js +348 -0
  9. package/dist/adapters/gemini-agy.d.ts +26 -0
  10. package/dist/adapters/gemini-agy.js +429 -0
  11. package/dist/adapters/vercel-board.d.ts +30 -0
  12. package/dist/adapters/vercel-board.js +138 -0
  13. package/dist/amend.d.ts +46 -0
  14. package/dist/amend.js +476 -0
  15. package/dist/boundaries.d.ts +43 -0
  16. package/dist/boundaries.js +309 -0
  17. package/dist/canonical-json.d.ts +6 -0
  18. package/dist/canonical-json.js +63 -0
  19. package/dist/cli.d.ts +1 -0
  20. package/dist/cli.js +1704 -0
  21. package/dist/delegate.d.ts +22 -0
  22. package/dist/delegate.js +140 -0
  23. package/dist/doctor.d.ts +36 -0
  24. package/dist/doctor.js +293 -0
  25. package/dist/git.d.ts +27 -0
  26. package/dist/git.js +234 -0
  27. package/dist/index.d.ts +19 -0
  28. package/dist/index.js +19 -0
  29. package/dist/merge-verify.d.ts +31 -0
  30. package/dist/merge-verify.js +721 -0
  31. package/dist/report.d.ts +25 -0
  32. package/dist/report.js +220 -0
  33. package/dist/review.d.ts +46 -0
  34. package/dist/review.js +527 -0
  35. package/dist/runner.d.ts +45 -0
  36. package/dist/runner.js +213 -0
  37. package/dist/schema.d.ts +6 -0
  38. package/dist/schema.js +424 -0
  39. package/dist/types.d.ts +190 -0
  40. package/dist/types.js +220 -0
  41. package/dist/verify.d.ts +45 -0
  42. package/dist/verify.js +952 -0
  43. package/dist/worktree.d.ts +82 -0
  44. package/dist/worktree.js +717 -0
  45. package/examples/harnesses/README.md +63 -0
  46. package/examples/quickstart/README.md +17 -0
  47. package/examples/quickstart/run.mjs +247 -0
  48. package/package.json +62 -4
  49. package/schemas/contract.schema.json +148 -0
  50. package/schemas/receipt.schema.json +49 -0
  51. package/schemas/review.schema.json +48 -0
@@ -0,0 +1,25 @@
1
+ import type { ExitCode } from './types.ts';
2
+ export type LedgerEventKind = 'verify' | 'review' | 'amend' | 'delegate' | 'status';
3
+ export interface LedgerEventRecord {
4
+ timestamp: string;
5
+ kind: LedgerEventKind;
6
+ task_id: string;
7
+ exit_code: ExitCode;
8
+ summary: string;
9
+ artifact_sha256?: string;
10
+ }
11
+ export interface ReportOptions {
12
+ contractPath: string;
13
+ cwd?: string;
14
+ format: 'markdown' | 'json' | 'sarif';
15
+ }
16
+ export declare function appendLedgerEvent(contractPath: string, event: Omit<LedgerEventRecord, 'timestamp'> & {
17
+ timestamp?: string;
18
+ }, cwd?: string): LedgerEventRecord;
19
+ export declare function readLedgerEvents(contractPath: string, cwd?: string): LedgerEventRecord[];
20
+ /** Summarize persisted evidence; this does not rerun verification or the live Git status gate. */
21
+ export declare function generateTaskReport(options: ReportOptions): {
22
+ exitCode: ExitCode;
23
+ output: string;
24
+ error?: string;
25
+ };
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.3', 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
+ }
@@ -0,0 +1,46 @@
1
+ import { type ExitCode, type ReviewAttestationMode, type ReviewAttestationV01, type SessionIdentity } from './types.ts';
2
+ export declare function computeReviewHmac(reviewSha256: string, secret: string): string;
3
+ export interface ReviewOptions {
4
+ contractPath: string;
5
+ cwd?: string;
6
+ reviewer: SessionIdentity;
7
+ verdict: 'approve' | 'reject';
8
+ summary: string;
9
+ findings?: string[];
10
+ inspectedRawDiff?: boolean;
11
+ expectedRawDiffSha256?: string;
12
+ attestationMode?: ReviewAttestationMode;
13
+ reviewerSecret?: string;
14
+ evidenceLineageId?: string;
15
+ }
16
+ export declare function runReview(options: ReviewOptions): {
17
+ exitCode: ExitCode;
18
+ review?: ReviewAttestationV01;
19
+ error?: string;
20
+ };
21
+ export interface StatusCheckOptions {
22
+ contractPath: string;
23
+ cwd?: string;
24
+ requireReview?: boolean;
25
+ integratorAgentId?: string;
26
+ reviewerSecret?: string;
27
+ }
28
+ export type ReviewStatusKind = 'approved' | 'missing' | 'stale' | 'rejected' | 'incomplete' | 'invalid';
29
+ export interface StatusReport {
30
+ exit_code: ExitCode;
31
+ status: 'pass' | 'violation' | 'incomplete' | 'stale';
32
+ reason: string;
33
+ task_id?: string;
34
+ candidate_sha?: string;
35
+ contract_sha256?: string;
36
+ receipt_sha256?: string;
37
+ review_sha256?: string;
38
+ review_status?: ReviewStatusKind;
39
+ required_reviews?: number;
40
+ valid_reviews_count?: number;
41
+ }
42
+ /**
43
+ * Fast, stateless read-only gate check against live Git HEAD, receipt, reviews,
44
+ * and optional canonical integrator / role_substitution policy.
45
+ */
46
+ export declare function checkStatus(options: StatusCheckOptions): StatusReport;