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/CHANGELOG.md +126 -0
- package/LICENSE +21 -0
- package/README.md +214 -2
- package/bin/diffpact.mjs +10 -0
- package/dist/adapters/claude-code.js +191 -0
- package/dist/adapters/codex.js +348 -0
- package/dist/adapters/gemini-agy.js +429 -0
- package/dist/adapters/vercel-board.js +138 -0
- package/dist/amend.js +470 -0
- package/dist/boundaries.js +309 -0
- package/dist/canonical-json.js +63 -0
- package/dist/cli.js +1433 -0
- package/dist/delegate.js +140 -0
- package/dist/doctor.js +293 -0
- package/dist/git.js +219 -0
- package/dist/index.js +19 -0
- package/dist/merge-verify.js +721 -0
- package/dist/report.js +220 -0
- package/dist/review.js +527 -0
- package/dist/runner.js +213 -0
- package/dist/schema.js +424 -0
- package/dist/types.js +220 -0
- package/dist/verify.js +952 -0
- package/dist/worktree.js +717 -0
- package/examples/harnesses/README.md +63 -0
- package/examples/quickstart/README.md +17 -0
- package/examples/quickstart/run.mjs +247 -0
- package/package.json +62 -4
- package/schemas/contract.schema.json +148 -0
- package/schemas/receipt.schema.json +49 -0
- package/schemas/review.schema.json +48 -0
package/dist/worktree.js
ADDED
|
@@ -0,0 +1,717 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { evaluatePathBoundary } from './boundaries.js';
|
|
4
|
+
import {
|
|
5
|
+
collectRepoChanges,
|
|
6
|
+
ensureGitInfoExclude,
|
|
7
|
+
resolveCurrentBranch,
|
|
8
|
+
resolveHeadSha,
|
|
9
|
+
resolveRepoRoot,
|
|
10
|
+
runGitText
|
|
11
|
+
} from './git.js';
|
|
12
|
+
import { checkStatus } from './review.js';
|
|
13
|
+
import { generateTaskReport } from './report.js';
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
function readTrailingSlashGitignoreEntries(repoRoot ) {
|
|
24
|
+
const entries = new Set ();
|
|
25
|
+
const giPath = path.join(repoRoot, '.gitignore');
|
|
26
|
+
if (!fs.existsSync(giPath)) return entries;
|
|
27
|
+
try {
|
|
28
|
+
const raw = fs.readFileSync(giPath, 'utf8');
|
|
29
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
30
|
+
const trimmed = line.trim();
|
|
31
|
+
if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('!')) continue;
|
|
32
|
+
if (trimmed.endsWith('/')) {
|
|
33
|
+
entries.add(trimmed.replace(/^\/+/, '').replace(/\/+$/, ''));
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
} catch {
|
|
37
|
+
// ignore read errors
|
|
38
|
+
}
|
|
39
|
+
return entries;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Inspects dirty/untracked paths in `repoRoot` against `contract`, producing:
|
|
44
|
+
* - Human-readable dirty file entries (`?? path`, `M path`, etc.)
|
|
45
|
+
* - Out-of-bounds violations for `--resume` pre-flight validation
|
|
46
|
+
* - Actionable hints when an untracked symlink matches a trailing-slash `.gitignore` pattern
|
|
47
|
+
* (e.g. `ln -s .../node_modules node_modules` vs `.gitignore` containing `node_modules/`).
|
|
48
|
+
*/
|
|
49
|
+
export function inspectDirtyTreeDiagnostics(
|
|
50
|
+
repoRoot ,
|
|
51
|
+
contract
|
|
52
|
+
) {
|
|
53
|
+
const head = resolveHeadSha(repoRoot);
|
|
54
|
+
const snap = collectRepoChanges(repoRoot, head, head);
|
|
55
|
+
const dirtyEntries = [];
|
|
56
|
+
const outOfBoundsViolations = [];
|
|
57
|
+
const symlinkGitignoreHints = [];
|
|
58
|
+
|
|
59
|
+
const trailingSlashIgnores = readTrailingSlashGitignoreEntries(repoRoot);
|
|
60
|
+
|
|
61
|
+
for (const ch of snap.changedFiles) {
|
|
62
|
+
const isSym = Boolean(ch.is_symlink);
|
|
63
|
+
dirtyEntries.push({ status: ch.status, path: ch.path, isSymlink: isSym });
|
|
64
|
+
const v = evaluatePathBoundary(ch.path, repoRoot, contract);
|
|
65
|
+
if (v) outOfBoundsViolations.push(v);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
for (const u of snap.untrackedFiles) {
|
|
69
|
+
let isSym = false;
|
|
70
|
+
try {
|
|
71
|
+
isSym = fs.lstatSync(path.join(repoRoot, u)).isSymbolicLink();
|
|
72
|
+
} catch {
|
|
73
|
+
isSym = false;
|
|
74
|
+
}
|
|
75
|
+
dirtyEntries.push({ status: '??', path: u, isSymlink: isSym });
|
|
76
|
+
const v = evaluatePathBoundary(u, repoRoot, contract);
|
|
77
|
+
if (v) outOfBoundsViolations.push(v);
|
|
78
|
+
|
|
79
|
+
if (isSym) {
|
|
80
|
+
const norm = u.replace(/^\/+/, '').replace(/\/+$/, '');
|
|
81
|
+
if (trailingSlashIgnores.has(norm) || trailingSlashIgnores.has(path.basename(norm))) {
|
|
82
|
+
symlinkGitignoreHints.push(
|
|
83
|
+
`Untracked symlink "${u}" matches trailing-slash ".gitignore" entry "${norm}/" (Git only ignores directories for trailing-slash rules). Add "${norm}" (without trailing slash) to ".git/info/exclude" or create worktrees with "diffpact worktree create --share-node-modules".`
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return {
|
|
90
|
+
clean: snap.workingTreeClean,
|
|
91
|
+
dirtyEntries,
|
|
92
|
+
outOfBoundsViolations,
|
|
93
|
+
symlinkGitignoreHints
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
function parsePnpmWorkspacePatterns(yamlText ) {
|
|
118
|
+
const patterns = [];
|
|
119
|
+
let inPackages = false;
|
|
120
|
+
for (const rawLine of yamlText.split(/\r?\n/)) {
|
|
121
|
+
const noComment = rawLine.replace(/#.*$/, '');
|
|
122
|
+
const trimmed = noComment.trim();
|
|
123
|
+
if (!trimmed) continue;
|
|
124
|
+
if (/^packages\s*:/.test(trimmed)) {
|
|
125
|
+
inPackages = true;
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (inPackages) {
|
|
129
|
+
if (!/^\s+/.test(noComment) && !trimmed.startsWith('-')) {
|
|
130
|
+
inPackages = false;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
const itemMatch = trimmed.match(/^-\s+(.+)$/);
|
|
134
|
+
if (itemMatch && itemMatch[1]) {
|
|
135
|
+
const val = itemMatch[1].trim().replace(/^['"]|['"]$/g, '');
|
|
136
|
+
if (val) patterns.push(val);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return patterns;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function readWorkspacePatterns(repoDir ) {
|
|
144
|
+
const patterns = [];
|
|
145
|
+
const pkgPath = path.join(repoDir, 'package.json');
|
|
146
|
+
if (fs.existsSync(pkgPath)) {
|
|
147
|
+
try {
|
|
148
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
|
|
149
|
+
|
|
150
|
+
;
|
|
151
|
+
if (Array.isArray(pkg.workspaces)) {
|
|
152
|
+
for (const item of pkg.workspaces) {
|
|
153
|
+
if (typeof item === 'string' && item.trim()) patterns.push(item.trim());
|
|
154
|
+
}
|
|
155
|
+
} else if (
|
|
156
|
+
pkg.workspaces &&
|
|
157
|
+
typeof pkg.workspaces === 'object' &&
|
|
158
|
+
Array.isArray((pkg.workspaces ).packages)
|
|
159
|
+
) {
|
|
160
|
+
for (const item of (pkg.workspaces ).packages) {
|
|
161
|
+
if (typeof item === 'string' && item.trim()) patterns.push(item.trim());
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
} catch {
|
|
165
|
+
// ignore malformed package.json
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const pnpmPath = path.join(repoDir, 'pnpm-workspace.yaml');
|
|
170
|
+
if (fs.existsSync(pnpmPath)) {
|
|
171
|
+
try {
|
|
172
|
+
patterns.push(...parsePnpmWorkspacePatterns(fs.readFileSync(pnpmPath, 'utf8')));
|
|
173
|
+
} catch {
|
|
174
|
+
// ignore unreadable pnpm-workspace.yaml
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return patterns;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function globSegmentToRegex(segment ) {
|
|
182
|
+
const escaped = segment.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]');
|
|
183
|
+
return new RegExp(`^${escaped}$`);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function listSubdirs(dir ) {
|
|
187
|
+
try {
|
|
188
|
+
return fs
|
|
189
|
+
.readdirSync(dir, { withFileTypes: true })
|
|
190
|
+
.filter((d) => d.isDirectory() && d.name !== 'node_modules' && d.name !== '.git')
|
|
191
|
+
.map((d) => d.name);
|
|
192
|
+
} catch {
|
|
193
|
+
return [];
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function expandWorkspacePattern(rootDir , rawPattern ) {
|
|
198
|
+
const norm = rawPattern.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '');
|
|
199
|
+
if (!norm) return [];
|
|
200
|
+
const segments = norm.split('/').filter(Boolean);
|
|
201
|
+
let currentDirs = [rootDir];
|
|
202
|
+
|
|
203
|
+
for (const seg of segments) {
|
|
204
|
+
const nextDirs = [];
|
|
205
|
+
for (const cur of currentDirs) {
|
|
206
|
+
if (seg === '**') {
|
|
207
|
+
const stack = [cur];
|
|
208
|
+
while (stack.length > 0) {
|
|
209
|
+
const d = stack.pop() ;
|
|
210
|
+
nextDirs.push(d);
|
|
211
|
+
for (const sub of listSubdirs(d)) {
|
|
212
|
+
stack.push(path.join(d, sub));
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
} else if (seg.includes('*') || seg.includes('?')) {
|
|
216
|
+
const rx = globSegmentToRegex(seg);
|
|
217
|
+
for (const sub of listSubdirs(cur)) {
|
|
218
|
+
if (rx.test(sub)) nextDirs.push(path.join(cur, sub));
|
|
219
|
+
}
|
|
220
|
+
} else {
|
|
221
|
+
const candidate = path.join(cur, seg);
|
|
222
|
+
try {
|
|
223
|
+
if (fs.statSync(candidate).isDirectory()) nextDirs.push(candidate);
|
|
224
|
+
} catch {
|
|
225
|
+
// ignore missing path
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
currentDirs = nextDirs;
|
|
230
|
+
if (currentDirs.length === 0) break;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return currentDirs;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Discovers local npm/pnpm workspace packages inside `worktreeRoot`, returning
|
|
238
|
+
* a map of `<package-name>` -> `<absolute path inside worktreeRoot>`.
|
|
239
|
+
*/
|
|
240
|
+
export function discoverLocalWorkspaces(worktreeRoot ) {
|
|
241
|
+
const rawPatterns = readWorkspacePatterns(worktreeRoot);
|
|
242
|
+
const included = new Set ();
|
|
243
|
+
const excluded = new Set ();
|
|
244
|
+
|
|
245
|
+
for (const pat of rawPatterns) {
|
|
246
|
+
if (pat.startsWith('!')) {
|
|
247
|
+
for (const dir of expandWorkspacePattern(worktreeRoot, pat.slice(1))) {
|
|
248
|
+
excluded.add(path.resolve(dir));
|
|
249
|
+
}
|
|
250
|
+
} else {
|
|
251
|
+
for (const dir of expandWorkspacePattern(worktreeRoot, pat)) {
|
|
252
|
+
included.add(path.resolve(dir));
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const packages = new Map ();
|
|
258
|
+
for (const dir of included) {
|
|
259
|
+
if (excluded.has(dir)) continue;
|
|
260
|
+
const pkgJsonPath = path.join(dir, 'package.json');
|
|
261
|
+
if (!fs.existsSync(pkgJsonPath)) continue;
|
|
262
|
+
try {
|
|
263
|
+
const parsed = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8')) ;
|
|
264
|
+
if (typeof parsed.name === 'string' && parsed.name.trim()) {
|
|
265
|
+
packages.set(parsed.name.trim(), dir);
|
|
266
|
+
}
|
|
267
|
+
} catch {
|
|
268
|
+
// ignore invalid workspace package.json
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return packages;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function setupWorkspaceAwareNodeModules(
|
|
275
|
+
mainNodeModules ,
|
|
276
|
+
worktreeRoot ,
|
|
277
|
+
localWorkspaces
|
|
278
|
+
) {
|
|
279
|
+
const wtNodeModules = path.join(worktreeRoot, 'node_modules');
|
|
280
|
+
fs.mkdirSync(wtNodeModules, { recursive: true });
|
|
281
|
+
|
|
282
|
+
const localScopes = new Set ();
|
|
283
|
+
for (const pkgName of localWorkspaces.keys()) {
|
|
284
|
+
if (pkgName.startsWith('@') && pkgName.includes('/')) {
|
|
285
|
+
localScopes.add(pkgName.split('/')[0] );
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
for (const entry of fs.readdirSync(mainNodeModules)) {
|
|
290
|
+
const srcEntry = path.join(mainNodeModules, entry);
|
|
291
|
+
const dstEntry = path.join(wtNodeModules, entry);
|
|
292
|
+
|
|
293
|
+
if (localWorkspaces.has(entry)) {
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (entry.startsWith('@') && localScopes.has(entry)) {
|
|
298
|
+
fs.mkdirSync(dstEntry, { recursive: true });
|
|
299
|
+
try {
|
|
300
|
+
if (fs.statSync(srcEntry).isDirectory()) {
|
|
301
|
+
for (const subEntry of fs.readdirSync(srcEntry)) {
|
|
302
|
+
const fullName = `${entry}/${subEntry}`;
|
|
303
|
+
if (localWorkspaces.has(fullName)) continue;
|
|
304
|
+
const subDst = path.join(dstEntry, subEntry);
|
|
305
|
+
if (!fs.existsSync(subDst)) {
|
|
306
|
+
fs.symlinkSync(path.join(srcEntry, subEntry), subDst);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
} catch {
|
|
311
|
+
// ignore broken scope directory
|
|
312
|
+
}
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
if (!fs.existsSync(dstEntry)) {
|
|
317
|
+
fs.symlinkSync(srcEntry, dstEntry);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const linkedNames = [];
|
|
322
|
+
for (const [pkgName, localDir] of localWorkspaces.entries()) {
|
|
323
|
+
if (pkgName.startsWith('@') && pkgName.includes('/')) {
|
|
324
|
+
const [scope, subName] = pkgName.split('/');
|
|
325
|
+
const scopeDir = path.join(wtNodeModules, scope );
|
|
326
|
+
fs.mkdirSync(scopeDir, { recursive: true });
|
|
327
|
+
const linkDst = path.join(scopeDir, subName );
|
|
328
|
+
if (!fs.existsSync(linkDst)) {
|
|
329
|
+
fs.symlinkSync(localDir, linkDst);
|
|
330
|
+
}
|
|
331
|
+
} else {
|
|
332
|
+
const linkDst = path.join(wtNodeModules, pkgName);
|
|
333
|
+
if (!fs.existsSync(linkDst)) {
|
|
334
|
+
fs.symlinkSync(localDir, linkDst);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
linkedNames.push(pkgName);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
return linkedNames.sort();
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function resolveMainRepoRoot(repoRoot ) {
|
|
344
|
+
try {
|
|
345
|
+
const commonDirRaw = runGitText(repoRoot, ['rev-parse', '--git-common-dir']).trim();
|
|
346
|
+
const commonAbs = path.resolve(repoRoot, commonDirRaw);
|
|
347
|
+
if (path.basename(commonAbs) === '.git') {
|
|
348
|
+
return path.dirname(commonAbs);
|
|
349
|
+
}
|
|
350
|
+
} catch {
|
|
351
|
+
// fallback
|
|
352
|
+
}
|
|
353
|
+
return repoRoot;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const SKIP_NM_SCAN_DIRS = new Set([
|
|
357
|
+
'.git',
|
|
358
|
+
'.diffpact',
|
|
359
|
+
'node_modules',
|
|
360
|
+
'dist',
|
|
361
|
+
'build',
|
|
362
|
+
'coverage',
|
|
363
|
+
'.next',
|
|
364
|
+
'.nuxt',
|
|
365
|
+
'.svelte-kit',
|
|
366
|
+
'.turbo'
|
|
367
|
+
]);
|
|
368
|
+
|
|
369
|
+
function discoverNodeModulesPackageDirs(mainRepoRoot , explicitDirs ) {
|
|
370
|
+
if (explicitDirs && explicitDirs.length > 0) {
|
|
371
|
+
return explicitDirs.map((d) => d.replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+|\/+$/g, ''));
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
if (fs.existsSync(path.join(mainRepoRoot, 'node_modules'))) {
|
|
375
|
+
return [''];
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
const found = [];
|
|
379
|
+
const scan = (relPrefix , depth ) => {
|
|
380
|
+
if (depth > 2) return;
|
|
381
|
+
const absDir = relPrefix ? path.join(mainRepoRoot, relPrefix) : mainRepoRoot;
|
|
382
|
+
let entries ;
|
|
383
|
+
try {
|
|
384
|
+
entries = fs.readdirSync(absDir, { withFileTypes: true });
|
|
385
|
+
} catch {
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
for (const ent of entries) {
|
|
389
|
+
if (!ent.isDirectory() || SKIP_NM_SCAN_DIRS.has(ent.name)) continue;
|
|
390
|
+
const childRel = relPrefix ? `${relPrefix}/${ent.name}` : ent.name;
|
|
391
|
+
const childAbs = path.join(mainRepoRoot, childRel);
|
|
392
|
+
const hasPkg = fs.existsSync(path.join(childAbs, 'package.json'));
|
|
393
|
+
const hasNm = fs.existsSync(path.join(childAbs, 'node_modules'));
|
|
394
|
+
if (hasPkg && hasNm) {
|
|
395
|
+
found.push(childRel);
|
|
396
|
+
} else if (depth < 2) {
|
|
397
|
+
scan(childRel, depth + 1);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
};
|
|
401
|
+
scan('', 1);
|
|
402
|
+
return found.sort();
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function copyDirectoryRecursive(srcDir , dstDir ) {
|
|
406
|
+
fs.mkdirSync(dstDir, { recursive: true });
|
|
407
|
+
for (const ent of fs.readdirSync(srcDir, { withFileTypes: true })) {
|
|
408
|
+
if (ent.name === 'archive') continue;
|
|
409
|
+
const srcPath = path.join(srcDir, ent.name);
|
|
410
|
+
const dstPath = path.join(dstDir, ent.name);
|
|
411
|
+
if (ent.isDirectory()) {
|
|
412
|
+
copyDirectoryRecursive(srcPath, dstPath);
|
|
413
|
+
} else if (ent.isFile()) {
|
|
414
|
+
fs.copyFileSync(srcPath, dstPath);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function archiveWorktreeEvidence(options
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
) {
|
|
426
|
+
const contractAbs = path.resolve(options.worktreeRoot, options.contractPath);
|
|
427
|
+
const pactDir = path.dirname(contractAbs);
|
|
428
|
+
if (!fs.existsSync(pactDir)) return undefined;
|
|
429
|
+
|
|
430
|
+
let taskSlug = options.branch ?? path.basename(options.worktreeRoot);
|
|
431
|
+
let shortSha = 'unknown';
|
|
432
|
+
|
|
433
|
+
try {
|
|
434
|
+
if (fs.existsSync(contractAbs)) {
|
|
435
|
+
const c = JSON.parse(fs.readFileSync(contractAbs, 'utf8')) ;
|
|
436
|
+
if (typeof c.task_id === 'string' && c.task_id.trim()) taskSlug = c.task_id.trim();
|
|
437
|
+
}
|
|
438
|
+
} catch {
|
|
439
|
+
// keep fallback
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
try {
|
|
443
|
+
const receiptPath = path.join(pactDir, 'receipt.json');
|
|
444
|
+
if (fs.existsSync(receiptPath)) {
|
|
445
|
+
const r = JSON.parse(fs.readFileSync(receiptPath, 'utf8')) ;
|
|
446
|
+
if (typeof r.candidate_sha === 'string' && r.candidate_sha.length >= 7) {
|
|
447
|
+
shortSha = r.candidate_sha.slice(0, 8);
|
|
448
|
+
}
|
|
449
|
+
} else {
|
|
450
|
+
shortSha = resolveHeadSha(options.worktreeRoot).slice(0, 8);
|
|
451
|
+
}
|
|
452
|
+
} catch {
|
|
453
|
+
// keep fallback
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
const safeSlug = taskSlug.replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') || 'task';
|
|
457
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
458
|
+
const destDir = options.archiveDirOverride
|
|
459
|
+
? path.resolve(options.mainRepoRoot, options.archiveDirOverride)
|
|
460
|
+
: path.join(options.mainRepoRoot, '.diffpact', 'archive', `${stamp}-${safeSlug}-${shortSha}`);
|
|
461
|
+
|
|
462
|
+
copyDirectoryRecursive(pactDir, destDir);
|
|
463
|
+
|
|
464
|
+
// Also export durable Markdown + JSON reports alongside raw contract/receipt/reviews
|
|
465
|
+
if (fs.existsSync(contractAbs)) {
|
|
466
|
+
const md = generateTaskReport({ contractPath: options.contractPath, cwd: options.worktreeRoot, format: 'markdown' });
|
|
467
|
+
if (md.output) fs.writeFileSync(path.join(destDir, 'report.md'), md.output, 'utf8');
|
|
468
|
+
const js = generateTaskReport({ contractPath: options.contractPath, cwd: options.worktreeRoot, format: 'json' });
|
|
469
|
+
if (js.output) fs.writeFileSync(path.join(destDir, 'report.json'), js.output, 'utf8');
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// Ensure main repo ignores .diffpact/ so durable archives never dirty git status
|
|
473
|
+
try {
|
|
474
|
+
ensureGitInfoExclude(options.mainRepoRoot, '.diffpact/');
|
|
475
|
+
} catch {
|
|
476
|
+
// ignore if non-git
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
return destDir;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* Creates a linked Git worktree with `.diffpact/` pre-excluded and optional clean
|
|
484
|
+
* `node_modules` sharing:
|
|
485
|
+
* - For standard repos: symlinks `<main>/node_modules` and excludes `node_modules` in `.git/info/exclude`.
|
|
486
|
+
* - For npm/pnpm workspace monorepos: creates a real `<worktree>/node_modules` directory that
|
|
487
|
+
* symlinks third-party dependencies from `<main>/node_modules` while pointing every local
|
|
488
|
+
* workspace package (`@scope/pkg` or unscoped) to the worktree's own directory.
|
|
489
|
+
* - For subdirectory apps (e.g. `site/package.json` + `site/node_modules`): auto-discovers
|
|
490
|
+
* depth 1-2 package subdirectories or honors explicit `nodeModulesDirs` (`--node-modules-dir`).
|
|
491
|
+
*/
|
|
492
|
+
export function createManagedWorktree(options ) {
|
|
493
|
+
const cwd = options.cwd ?? process.cwd();
|
|
494
|
+
const repoRoot = resolveRepoRoot(cwd);
|
|
495
|
+
const targetAbs = path.resolve(cwd, options.dir);
|
|
496
|
+
|
|
497
|
+
const addArgs = ['worktree', 'add', '-b', options.branch, targetAbs];
|
|
498
|
+
if (options.fromRef) addArgs.push(options.fromRef);
|
|
499
|
+
runGitText(repoRoot, addArgs);
|
|
500
|
+
|
|
501
|
+
const resolvedWt = fs.realpathSync(targetAbs);
|
|
502
|
+
ensureGitInfoExclude(resolvedWt, '.diffpact/');
|
|
503
|
+
|
|
504
|
+
let sharedNodeModules = false;
|
|
505
|
+
let nodeModulesTarget ;
|
|
506
|
+
const sharedNodeModulesPaths = [];
|
|
507
|
+
let workspaceMode ;
|
|
508
|
+
let workspacePackagesLinked ;
|
|
509
|
+
let nodeModulesNote ;
|
|
510
|
+
|
|
511
|
+
if (options.shareNodeModules || (options.nodeModulesDirs && options.nodeModulesDirs.length > 0)) {
|
|
512
|
+
const mainRepoRoot = resolveMainRepoRoot(repoRoot);
|
|
513
|
+
const pkgDirs = discoverNodeModulesPackageDirs(mainRepoRoot, options.nodeModulesDirs);
|
|
514
|
+
|
|
515
|
+
for (const relPkgDir of pkgDirs) {
|
|
516
|
+
const mainPkgRoot = relPkgDir ? path.join(mainRepoRoot, relPkgDir) : mainRepoRoot;
|
|
517
|
+
const wtPkgRoot = relPkgDir ? path.join(resolvedWt, relPkgDir) : resolvedWt;
|
|
518
|
+
const candidateNm = path.join(mainPkgRoot, 'node_modules');
|
|
519
|
+
const linkPath = path.join(wtPkgRoot, 'node_modules');
|
|
520
|
+
const relNmPath = relPkgDir ? `${relPkgDir}/node_modules` : 'node_modules';
|
|
521
|
+
|
|
522
|
+
if (!fs.existsSync(candidateNm)) {
|
|
523
|
+
if (options.nodeModulesDirs && options.nodeModulesDirs.length > 0) {
|
|
524
|
+
nodeModulesNote = `Requested node_modules directory "${relNmPath}" does not exist in main checkout "${mainRepoRoot}".`;
|
|
525
|
+
}
|
|
526
|
+
continue;
|
|
527
|
+
}
|
|
528
|
+
if (!fs.existsSync(wtPkgRoot) || fs.existsSync(linkPath)) {
|
|
529
|
+
continue;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
const localWorkspaces = discoverLocalWorkspaces(wtPkgRoot);
|
|
533
|
+
if (localWorkspaces.size > 0) {
|
|
534
|
+
const linked = setupWorkspaceAwareNodeModules(candidateNm, wtPkgRoot, localWorkspaces);
|
|
535
|
+
workspacePackagesLinked = [...(workspacePackagesLinked ?? []), ...linked].sort();
|
|
536
|
+
ensureGitInfoExclude(resolvedWt, `${relNmPath}/`);
|
|
537
|
+
ensureGitInfoExclude(resolvedWt, relNmPath);
|
|
538
|
+
workspaceMode = 'workspace-overlay';
|
|
539
|
+
} else {
|
|
540
|
+
fs.symlinkSync(candidateNm, linkPath);
|
|
541
|
+
ensureGitInfoExclude(resolvedWt, relNmPath);
|
|
542
|
+
if (!workspaceMode) workspaceMode = 'symlink';
|
|
543
|
+
}
|
|
544
|
+
sharedNodeModules = true;
|
|
545
|
+
if (!nodeModulesTarget) nodeModulesTarget = candidateNm;
|
|
546
|
+
sharedNodeModulesPaths.push(relNmPath);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
if (!sharedNodeModules && !nodeModulesNote) {
|
|
550
|
+
nodeModulesNote =
|
|
551
|
+
'No node_modules directory found at repo root or depth 1-2 package subdirectories (run `npm install` in main checkout or pass `--node-modules-dir <subdir>`).';
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
return {
|
|
556
|
+
worktreePath: resolvedWt,
|
|
557
|
+
branch: options.branch,
|
|
558
|
+
sharedNodeModules,
|
|
559
|
+
...(nodeModulesTarget ? { nodeModulesTarget } : {}),
|
|
560
|
+
...(sharedNodeModulesPaths.length > 0 ? { sharedNodeModulesPaths } : {}),
|
|
561
|
+
...(workspaceMode ? { workspaceMode } : {}),
|
|
562
|
+
...(workspacePackagesLinked ? { workspacePackagesLinked } : {}),
|
|
563
|
+
...(nodeModulesNote ? { nodeModulesNote } : {})
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* Removes a linked Git worktree cleanly (companion to `createManagedWorktree`),
|
|
592
|
+
* archiving `.diffpact/` evidence (contract, receipt, reviews, amendments, ledger, and reports)
|
|
593
|
+
* into `<main>/.diffpact/archive/` by default before removal, optionally verifying
|
|
594
|
+
* `diffpact status --require-review` passes first and deleting the worktree's feature branch
|
|
595
|
+
* (never deleting `main` or `master`).
|
|
596
|
+
*/
|
|
597
|
+
export function removeManagedWorktree(options ) {
|
|
598
|
+
const cwd = options.cwd ?? process.cwd();
|
|
599
|
+
const repoRoot = resolveRepoRoot(cwd);
|
|
600
|
+
const mainRepoRoot = resolveMainRepoRoot(repoRoot);
|
|
601
|
+
const targetAbs = fs.existsSync(path.resolve(cwd, options.dir))
|
|
602
|
+
? fs.realpathSync(path.resolve(cwd, options.dir))
|
|
603
|
+
: path.resolve(cwd, options.dir);
|
|
604
|
+
|
|
605
|
+
if (targetAbs === repoRoot || targetAbs === mainRepoRoot) {
|
|
606
|
+
return {
|
|
607
|
+
ok: false,
|
|
608
|
+
exitCode: 1,
|
|
609
|
+
worktreePath: targetAbs,
|
|
610
|
+
branchDeleted: false,
|
|
611
|
+
error: 'Refusing to remove the primary repository root as a linked worktree'
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
const contractPath = options.contractPath ?? '.diffpact/contract.json';
|
|
616
|
+
|
|
617
|
+
if (options.requireVerified && !options.force) {
|
|
618
|
+
const st = checkStatus({
|
|
619
|
+
contractPath,
|
|
620
|
+
cwd: targetAbs,
|
|
621
|
+
requireReview: true
|
|
622
|
+
});
|
|
623
|
+
if (st.exit_code !== 0) {
|
|
624
|
+
return {
|
|
625
|
+
ok: false,
|
|
626
|
+
exitCode: st.exit_code,
|
|
627
|
+
worktreePath: targetAbs,
|
|
628
|
+
branchDeleted: false,
|
|
629
|
+
error: `Worktree has not passed diffpact status --require-review (exit ${st.exit_code}: ${st.reason}). Pass --force to remove anyway.`
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
let branch ;
|
|
635
|
+
try {
|
|
636
|
+
const b = resolveCurrentBranch(targetAbs);
|
|
637
|
+
if (b && b !== 'HEAD') branch = b;
|
|
638
|
+
} catch {
|
|
639
|
+
branch = undefined;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
// Durably archive .diffpact/ evidence before deleting the worktree (unless --no-archive)
|
|
643
|
+
let archivedTo ;
|
|
644
|
+
if (!options.noArchive) {
|
|
645
|
+
try {
|
|
646
|
+
archivedTo = archiveWorktreeEvidence({
|
|
647
|
+
mainRepoRoot,
|
|
648
|
+
worktreeRoot: targetAbs,
|
|
649
|
+
contractPath,
|
|
650
|
+
branch,
|
|
651
|
+
archiveDirOverride: options.archiveDir
|
|
652
|
+
});
|
|
653
|
+
} catch (err) {
|
|
654
|
+
return {
|
|
655
|
+
ok: false,
|
|
656
|
+
exitCode: 1,
|
|
657
|
+
worktreePath: targetAbs,
|
|
658
|
+
...(branch ? { branch } : {}),
|
|
659
|
+
branchDeleted: false,
|
|
660
|
+
error: `Failed to archive .diffpact evidence before worktree removal: ${(err ).message}`
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
const removeArgs = ['worktree', 'remove'];
|
|
666
|
+
if (options.force) removeArgs.push('--force');
|
|
667
|
+
removeArgs.push(targetAbs);
|
|
668
|
+
|
|
669
|
+
try {
|
|
670
|
+
runGitText(repoRoot, removeArgs);
|
|
671
|
+
runGitText(repoRoot, ['worktree', 'prune']);
|
|
672
|
+
} catch (err) {
|
|
673
|
+
return {
|
|
674
|
+
ok: false,
|
|
675
|
+
exitCode: 1,
|
|
676
|
+
worktreePath: targetAbs,
|
|
677
|
+
...(branch ? { branch } : {}),
|
|
678
|
+
...(archivedTo ? { archivedTo } : {}),
|
|
679
|
+
branchDeleted: false,
|
|
680
|
+
error: (err ).message
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
let branchDeleted = false;
|
|
685
|
+
let branchDeleteMode ;
|
|
686
|
+
const shouldDeleteBranch = Boolean(options.deleteBranch || options.forceDeleteBranch);
|
|
687
|
+
if (shouldDeleteBranch && branch && branch !== 'main' && branch !== 'master') {
|
|
688
|
+
const deleteFlag =
|
|
689
|
+
options.force || options.forceDeleteBranch || options.requireVerified ? '-D' : '-d';
|
|
690
|
+
try {
|
|
691
|
+
runGitText(repoRoot, ['branch', deleteFlag, branch]);
|
|
692
|
+
branchDeleted = true;
|
|
693
|
+
branchDeleteMode = deleteFlag;
|
|
694
|
+
} catch (err) {
|
|
695
|
+
return {
|
|
696
|
+
ok: false,
|
|
697
|
+
exitCode: 1,
|
|
698
|
+
worktreePath: targetAbs,
|
|
699
|
+
branch,
|
|
700
|
+
...(archivedTo ? { archivedTo } : {}),
|
|
701
|
+
branchDeleted: false,
|
|
702
|
+
error: `Worktree removed, but deleting branch "${branch}" failed: ${(err ).message}`
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
return {
|
|
708
|
+
ok: true,
|
|
709
|
+
exitCode: 0,
|
|
710
|
+
worktreePath: targetAbs,
|
|
711
|
+
...(branch ? { branch } : {}),
|
|
712
|
+
branchDeleted,
|
|
713
|
+
...(branchDeleteMode ? { branchDeleteMode } : {}),
|
|
714
|
+
...(archivedTo ? { archivedTo } : {})
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
|