pushwork 2.0.0-preview → 2.0.0-preview.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.
Files changed (49) hide show
  1. package/dist/branches.d.ts +1 -0
  2. package/dist/branches.d.ts.map +1 -1
  3. package/dist/cli.js +16 -7
  4. package/dist/cli.js.map +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +2 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/pushwork.d.ts +15 -1
  10. package/dist/pushwork.d.ts.map +1 -1
  11. package/dist/pushwork.js +151 -7
  12. package/dist/pushwork.js.map +1 -1
  13. package/dist/shapes/types.d.ts +1 -0
  14. package/dist/shapes/types.d.ts.map +1 -1
  15. package/dist/shapes/types.js.map +1 -1
  16. package/dist/shapes/vfs.d.ts.map +1 -1
  17. package/dist/shapes/vfs.js +6 -2
  18. package/dist/shapes/vfs.js.map +1 -1
  19. package/dist/version.d.ts +11 -0
  20. package/dist/version.d.ts.map +1 -0
  21. package/dist/version.js +93 -0
  22. package/dist/version.js.map +1 -0
  23. package/package.json +5 -1
  24. package/.prettierrc +0 -9
  25. package/flake.lock +0 -128
  26. package/flake.nix +0 -66
  27. package/pnpm-workspace.yaml +0 -5
  28. package/src/branches.ts +0 -93
  29. package/src/cli.ts +0 -292
  30. package/src/config.ts +0 -64
  31. package/src/fs-tree.ts +0 -70
  32. package/src/ignore.ts +0 -33
  33. package/src/index.ts +0 -38
  34. package/src/log.ts +0 -8
  35. package/src/pushwork.ts +0 -1055
  36. package/src/repo.ts +0 -76
  37. package/src/shapes/custom.ts +0 -29
  38. package/src/shapes/file.ts +0 -115
  39. package/src/shapes/index.ts +0 -19
  40. package/src/shapes/patchwork-folder.ts +0 -156
  41. package/src/shapes/types.ts +0 -79
  42. package/src/shapes/vfs.ts +0 -93
  43. package/src/stash.ts +0 -106
  44. package/test/integration/branches.test.ts +0 -389
  45. package/test/integration/pushwork.test.ts +0 -547
  46. package/test/setup.ts +0 -29
  47. package/test/unit/doc-shape.test.ts +0 -612
  48. package/tsconfig.json +0 -22
  49. package/vitest.config.ts +0 -14
package/src/pushwork.ts DELETED
@@ -1,1055 +0,0 @@
1
- import * as fs from "fs/promises";
2
- import * as path from "path";
3
- import * as Automerge from "@automerge/automerge";
4
- import {
5
- isValidAutomergeUrl,
6
- parseAutomergeUrl,
7
- type AutomergeUrl,
8
- type DocHandle,
9
- type Repo,
10
- } from "@automerge/automerge-repo";
11
- import {
12
- CONFIG_VERSION,
13
- configExists,
14
- pushworkDir,
15
- readConfig,
16
- storageDir,
17
- writeConfig,
18
- type Backend,
19
- type PushworkConfig,
20
- } from "./config.js";
21
- import {
22
- DEFAULT_BRANCH,
23
- deleteBranchFile,
24
- detectDocType,
25
- isBranchesDoc,
26
- listBranchNames,
27
- readBranchFile,
28
- resolveEffectiveRoot,
29
- writeBranchFile,
30
- type BranchesDoc,
31
- } from "./branches.js";
32
- import { loadIgnore } from "./ignore.js";
33
- import { byteEq, walkDir, writeFileAtomic } from "./fs-tree.js";
34
- import { log } from "./log.js";
35
- import { openRepo, waitForSync } from "./repo.js";
36
- import {
37
- appendStash,
38
- decodeBytes,
39
- encodeBytes,
40
- listStashes,
41
- takeStash,
42
- type Stash,
43
- type StashEntry,
44
- } from "./stash.js";
45
- import {
46
- contentEquals,
47
- contentToBytes,
48
- flattenLeaves,
49
- isInArtifactDir,
50
- makeFileEntry,
51
- newDir,
52
- normalizeArtifactDir,
53
- pinUrl,
54
- resolveShape,
55
- setFileAt,
56
- stripHeads,
57
- type Shape,
58
- type UnixFileEntry,
59
- type VfsNode,
60
- } from "./shapes/index.js";
61
-
62
- const dlog = log("pushwork");
63
-
64
- const DEFAULT_ARTIFACT_DIRECTORIES = ["dist"];
65
-
66
- export type InitOpts = {
67
- dir: string;
68
- backend: Backend;
69
- shape: string;
70
- artifactDirectories?: readonly string[];
71
- branches?: boolean; // default: true
72
- online?: boolean; // default: true
73
- };
74
-
75
- export type CloneOpts = {
76
- url: string;
77
- dir: string;
78
- backend: Backend;
79
- shape: string;
80
- artifactDirectories?: readonly string[];
81
- branch?: string; // pick a specific branch on a BranchesDoc (default "default")
82
- online?: boolean; // default: true
83
- };
84
-
85
- export type Diff = {
86
- added: string[];
87
- modified: string[];
88
- deleted: string[];
89
- };
90
-
91
- export async function init(opts: InitOpts): Promise<AutomergeUrl> {
92
- const root = path.resolve(opts.dir);
93
- const useBranches = opts.branches ?? true;
94
- const online = opts.online ?? true;
95
- dlog("init root=%s backend=%s shape=%s branches=%s online=%s", root, opts.backend, opts.shape, useBranches, online);
96
- if (await configExists(root)) {
97
- throw new Error(`pushwork already initialized at ${root}`);
98
- }
99
- const artifactDirs = normalizeDirs(
100
- opts.artifactDirectories ?? DEFAULT_ARTIFACT_DIRECTORIES,
101
- );
102
- dlog("init artifactDirs=%o", artifactDirs);
103
- await fs.mkdir(pushworkDir(root), { recursive: true });
104
-
105
- const repo = await openRepo(opts.backend, storageDir(root), { offline: !online });
106
- try {
107
- const shape = await resolveShape(opts.shape);
108
- const ig = await loadIgnore(root);
109
- const fsFiles = await walkDir(root, ig);
110
- dlog("init walked %d files", fsFiles.size);
111
-
112
- const tree = await pushFiles(repo, fsFiles, undefined, artifactDirs);
113
- const folderUrl = await shape.encode({ repo, tree });
114
- dlog("init encoded folder=%s", folderUrl);
115
- const folderHandle = await repo.find<unknown>(folderUrl);
116
-
117
- if (online) {
118
- await waitForSync(folderHandle, { minMs: 3000, idleMs: 1500, maxMs: 15000 });
119
- stampLastSyncAt(folderHandle);
120
- await waitForSync(folderHandle, { idleMs: 1500, maxMs: 10000 });
121
- }
122
-
123
- let rootUrl: AutomergeUrl = folderUrl;
124
- if (useBranches) {
125
- const branchesHandle = repo.create<BranchesDoc>({
126
- "@patchwork": { type: "branches" },
127
- branches: { [DEFAULT_BRANCH]: folderUrl },
128
- });
129
- if (online) {
130
- await waitForSync(branchesHandle, { minMs: 1500, idleMs: 1500, maxMs: 10000 });
131
- }
132
- rootUrl = branchesHandle.url;
133
- dlog("init wrapped in BranchesDoc=%s", rootUrl);
134
- await writeBranchFile(root, DEFAULT_BRANCH);
135
- }
136
-
137
- await writeConfig(root, {
138
- version: CONFIG_VERSION,
139
- rootUrl,
140
- backend: opts.backend,
141
- shape: opts.shape,
142
- artifactDirectories: artifactDirs,
143
- branches: useBranches,
144
- });
145
- dlog("init complete: rootUrl=%s", rootUrl);
146
- return rootUrl;
147
- } finally {
148
- await repo.shutdown();
149
- }
150
- }
151
-
152
- export async function clone(opts: CloneOpts): Promise<void> {
153
- if (!isValidAutomergeUrl(opts.url)) {
154
- throw new Error(`invalid automerge URL: ${opts.url}`);
155
- }
156
- const root = path.resolve(opts.dir);
157
- dlog("clone url=%s root=%s backend=%s shape=%s", opts.url, root, opts.backend, opts.shape);
158
- await fs.mkdir(root, { recursive: true });
159
- if (await configExists(root)) {
160
- throw new Error(`pushwork already initialized at ${root}`);
161
- }
162
- const artifactDirs = normalizeDirs(
163
- opts.artifactDirectories ?? DEFAULT_ARTIFACT_DIRECTORIES,
164
- );
165
- await fs.mkdir(pushworkDir(root), { recursive: true });
166
-
167
- const online = opts.online ?? true;
168
- const repo = await openRepo(opts.backend, storageDir(root), { offline: !online });
169
- try {
170
- const shape = await resolveShape(opts.shape);
171
- const rootHandle = await repo.find<unknown>(opts.url as AutomergeUrl);
172
- if (online) {
173
- await waitForSync(rootHandle, { idleMs: 1500, maxMs: 15000 });
174
- }
175
- const docType = detectDocType(rootHandle.doc());
176
- dlog("clone detected docType=%s", docType);
177
-
178
- let useBranches = false;
179
- let folderHandle: DocHandle<unknown> = rootHandle;
180
- if (docType === "branches") {
181
- useBranches = true;
182
- const branchName = opts.branch ?? DEFAULT_BRANCH;
183
- folderHandle = await resolveEffectiveRoot(repo, rootHandle, branchName);
184
- if (online) {
185
- await waitForSync(folderHandle, { idleMs: 1500, maxMs: 15000 });
186
- }
187
- await writeBranchFile(root, branchName);
188
- dlog("clone branch=%s folder=%s", branchName, folderHandle.url);
189
- } else if (opts.branch) {
190
- throw new Error(
191
- `--branch passed but root doc is not a branches doc (type=${docType})`,
192
- );
193
- }
194
-
195
- const tree = await shape.decode({ repo, root: folderHandle });
196
- await materializeTree(repo, root, tree);
197
-
198
- await writeConfig(root, {
199
- version: CONFIG_VERSION,
200
- rootUrl: opts.url as AutomergeUrl,
201
- backend: opts.backend,
202
- shape: opts.shape,
203
- artifactDirectories: artifactDirs,
204
- branches: useBranches,
205
- });
206
- dlog("clone complete");
207
- } finally {
208
- await repo.shutdown();
209
- }
210
- }
211
-
212
- export async function url(cwd: string): Promise<AutomergeUrl> {
213
- const config = await readConfig(path.resolve(cwd));
214
- return config.rootUrl;
215
- }
216
-
217
- export async function sync(cwd: string): Promise<void> {
218
- await commitWorkdir(cwd, { online: true });
219
- }
220
-
221
- export async function save(cwd: string): Promise<void> {
222
- await commitWorkdir(cwd, { online: false });
223
- }
224
-
225
- async function commitWorkdir(
226
- cwd: string,
227
- { online }: { online: boolean },
228
- ): Promise<void> {
229
- const root = path.resolve(cwd);
230
- const config = await readConfig(root);
231
- const branchName = config.branches ? await readBranchFile(root) : null;
232
- dlog("commit online=%s root=%s branch=%s", online, root, branchName);
233
-
234
- const repo = await openRepo(config.backend, storageDir(root), {
235
- offline: !online,
236
- });
237
- try {
238
- const shape = await resolveShape(config.shape);
239
- const rootHandle = await repo.find<unknown>(config.rootUrl);
240
-
241
- // In branches mode + online, touch every branch's folder doc so the
242
- // network adapter announces them. Without this, a branch created
243
- // offline (`pushwork branch X`) is never pushed to the server, even
244
- // though its entry is in the BranchesDoc.
245
- const otherBranchHandles: DocHandle<unknown>[] = [];
246
- if (online && config.branches && isBranchesDoc(rootHandle.doc())) {
247
- const doc = rootHandle.doc() as BranchesDoc;
248
- for (const [name, url] of Object.entries(doc.branches)) {
249
- if (name === branchName) continue;
250
- otherBranchHandles.push(await repo.find<unknown>(url));
251
- }
252
- }
253
-
254
- const folderHandle = await resolveEffectiveRoot(repo, rootHandle, branchName);
255
-
256
- const previousTree = await shape.decode({ repo, root: folderHandle });
257
- const previousFiles = await readFileBytes(repo, previousTree);
258
-
259
- const ig = await loadIgnore(root);
260
- const fsFiles = await walkDir(root, ig);
261
-
262
- const newTree = await pushFiles(
263
- repo,
264
- fsFiles,
265
- previousFiles,
266
- config.artifactDirectories,
267
- );
268
- const changed = !sameTree(previousTree, newTree);
269
- dlog("commit tree changed: %s", changed);
270
- if (changed) {
271
- await shape.encode({ repo, tree: newTree, previousRoot: folderHandle });
272
- }
273
-
274
- if (online) {
275
- // Always stamp lastSyncAt on a sync, regardless of whether the
276
- // working tree changed — a sync is also a checkpoint that "we
277
- // reconciled with the server at this time."
278
- stampLastSyncAt(folderHandle);
279
-
280
- // Wait for the current branch's folder, the BranchesDoc itself
281
- // (when in branches mode), and any other branch folder docs to
282
- // flush. The maxMs is generous so a brand-new offline-created
283
- // branch reliably propagates.
284
- await waitForSync(folderHandle, {
285
- minMs: 3000,
286
- idleMs: 1500,
287
- maxMs: 15000,
288
- });
289
- if (config.branches) {
290
- await waitForSync(rootHandle, { idleMs: 1500, maxMs: 10000 });
291
- }
292
- for (const h of otherBranchHandles) {
293
- await waitForSync(h, { idleMs: 1500, maxMs: 10000 });
294
- }
295
- }
296
-
297
- const finalTree = await shape.decode({ repo, root: folderHandle });
298
- await materializeTree(repo, root, finalTree);
299
- dlog("commit complete");
300
- } finally {
301
- await repo.shutdown();
302
- }
303
- }
304
-
305
- export async function status(
306
- cwd: string,
307
- ): Promise<{ branch: string | null; diff: Diff }> {
308
- const root = path.resolve(cwd);
309
- const config = await readConfig(root);
310
- const branchName = config.branches ? await readBranchFile(root) : null;
311
-
312
- const repo = await openRepo(config.backend, storageDir(root), { offline: true });
313
- try {
314
- const shape = await resolveShape(config.shape);
315
- const rootHandle = await repo.find<unknown>(config.rootUrl);
316
- const folderHandle = await resolveEffectiveRoot(repo, rootHandle, branchName);
317
- const previousTree = await shape.decode({ repo, root: folderHandle });
318
- const previousFiles = await readFileBytes(repo, previousTree);
319
-
320
- const ig = await loadIgnore(root);
321
- const fsFiles = await walkDir(root, ig);
322
-
323
- const diff = computeDiff(previousFiles, fsFiles);
324
- return { branch: branchName, diff };
325
- } finally {
326
- await repo.shutdown();
327
- }
328
- }
329
-
330
- export async function diff(
331
- cwd: string,
332
- limitToPath?: string,
333
- ): Promise<Array<{ path: string; kind: "added" | "modified" | "deleted"; before?: Uint8Array; after?: Uint8Array }>> {
334
- const root = path.resolve(cwd);
335
- const config = await readConfig(root);
336
- const branchName = config.branches ? await readBranchFile(root) : null;
337
-
338
- const repo = await openRepo(config.backend, storageDir(root), { offline: true });
339
- try {
340
- const shape = await resolveShape(config.shape);
341
- const rootHandle = await repo.find<unknown>(config.rootUrl);
342
- const folderHandle = await resolveEffectiveRoot(repo, rootHandle, branchName);
343
- const previousTree = await shape.decode({ repo, root: folderHandle });
344
- const previousFiles = await readFileBytes(repo, previousTree);
345
-
346
- const ig = await loadIgnore(root);
347
- const fsFiles = await walkDir(root, ig);
348
-
349
- const out: Array<{ path: string; kind: "added" | "modified" | "deleted"; before?: Uint8Array; after?: Uint8Array }> = [];
350
- for (const [p, bytes] of fsFiles) {
351
- if (limitToPath && p !== limitToPath) continue;
352
- const prev = previousFiles.get(p);
353
- if (!prev) {
354
- out.push({ path: p, kind: "added", after: bytes });
355
- } else if (!byteEq(prev.bytes, bytes)) {
356
- out.push({ path: p, kind: "modified", before: prev.bytes, after: bytes });
357
- }
358
- }
359
- for (const [p, prev] of previousFiles) {
360
- if (limitToPath && p !== limitToPath) continue;
361
- if (!fsFiles.has(p)) out.push({ path: p, kind: "deleted", before: prev.bytes });
362
- }
363
- return out;
364
- } finally {
365
- await repo.shutdown();
366
- }
367
- }
368
-
369
- export async function listBranches(cwd: string): Promise<{ current: string | null; names: string[] }> {
370
- const root = path.resolve(cwd);
371
- const config = await readConfig(root);
372
- if (!config.branches) {
373
- throw new Error("pushwork repo has no branches");
374
- }
375
- const current = await readBranchFile(root);
376
-
377
- const repo = await openRepo(config.backend, storageDir(root), { offline: true });
378
- try {
379
- const rootHandle = await repo.find<BranchesDoc>(config.rootUrl);
380
- const doc = rootHandle.doc();
381
- if (!isBranchesDoc(doc)) {
382
- throw new Error(`root doc at ${config.rootUrl} is not a branches doc`);
383
- }
384
- return { current, names: listBranchNames(doc) };
385
- } finally {
386
- await repo.shutdown();
387
- }
388
- }
389
-
390
- export async function currentBranch(cwd: string): Promise<string | null> {
391
- const root = path.resolve(cwd);
392
- const config = await readConfig(root);
393
- if (!config.branches) return null;
394
- return readBranchFile(root);
395
- }
396
-
397
- export async function createBranch(cwd: string, name: string): Promise<AutomergeUrl> {
398
- if (!name) throw new Error("branch name is required");
399
- if (name.includes("/") || name.includes("\\")) {
400
- throw new Error("branch name may not contain slashes");
401
- }
402
- const root = path.resolve(cwd);
403
- const config = await readConfig(root);
404
- if (!config.branches) throw new Error("pushwork repo has no branches");
405
- const currentName = await readBranchFile(root);
406
- if (!currentName) throw new Error("no current branch is set");
407
-
408
- const repo = await openRepo(config.backend, storageDir(root), { offline: true });
409
- try {
410
- const shape = await resolveShape(config.shape);
411
- const rootHandle = await repo.find<BranchesDoc>(config.rootUrl);
412
- const doc = rootHandle.doc();
413
- if (!isBranchesDoc(doc)) {
414
- throw new Error(`root doc at ${config.rootUrl} is not a branches doc`);
415
- }
416
- if (doc.branches[name]) {
417
- throw new Error(`branch "${name}" already exists`);
418
- }
419
- const sourceUrl = doc.branches[currentName];
420
- if (!sourceUrl) {
421
- throw new Error(`current branch "${currentName}" not found in branches doc`);
422
- }
423
- const sourceHandle = await repo.find<unknown>(sourceUrl);
424
-
425
- // Clone the folder doc.
426
- const clonedFolder = repo.clone(sourceHandle);
427
- dlog("createBranch %s cloned folder %s → %s", name, sourceUrl, clonedFolder.url);
428
-
429
- // Deep-clone every file doc the source folder references, then rewrite
430
- // the cloned folder's leaves to point at the new file URLs. Without
431
- // this step both branches would alias the same UnixFileEntry docs and
432
- // editing one branch would silently mutate the other.
433
- const sourceTree = await shape.decode({ repo, root: sourceHandle });
434
- const fileUrlRemap = new Map<AutomergeUrl, AutomergeUrl>();
435
- for (const [, fileUrl] of flattenLeaves(sourceTree)) {
436
- const bare = stripHeads(fileUrl);
437
- if (fileUrlRemap.has(bare)) continue;
438
- const orig = await repo.find<unknown>(bare);
439
- const cloned = repo.clone(orig);
440
- fileUrlRemap.set(bare, cloned.url);
441
- dlog("createBranch cloned file %s → %s", bare, cloned.url);
442
- }
443
- const newTree = newDir();
444
- for (const [posixPath, fileUrl] of flattenLeaves(sourceTree)) {
445
- const bare = stripHeads(fileUrl);
446
- const remappedBare = fileUrlRemap.get(bare);
447
- if (!remappedBare) continue;
448
- const parsed = parseAutomergeUrl(fileUrl);
449
- // Preserve heads-pinning if the source URL was pinned.
450
- let finalUrl: AutomergeUrl = remappedBare;
451
- if (parsed.heads) {
452
- const newHandle = await repo.find<unknown>(remappedBare);
453
- finalUrl = pinUrl(newHandle);
454
- }
455
- const segments = posixPath.split("/").filter(Boolean);
456
- setFileAt(newTree, segments, finalUrl);
457
- }
458
- await shape.encode({ repo, tree: newTree, previousRoot: clonedFolder });
459
-
460
- rootHandle.change((d: BranchesDoc) => {
461
- d.branches[name] = clonedFolder.url;
462
- });
463
- return clonedFolder.url;
464
- } finally {
465
- await repo.shutdown();
466
- }
467
- }
468
-
469
- export type MergeReport = {
470
- source: string;
471
- target: string;
472
- merged: string[]; // paths present in both branches whose file docs were merged
473
- added: string[]; // paths that were only in source, added to target
474
- };
475
-
476
- export type MergePreviewEntry = {
477
- path: string;
478
- kind: "merged" | "added";
479
- before?: Uint8Array;
480
- after: Uint8Array;
481
- };
482
-
483
- export type MergePreview = {
484
- source: string;
485
- target: string;
486
- entries: MergePreviewEntry[];
487
- };
488
-
489
- /**
490
- * Apply changes from `source` branch onto the current branch.
491
- *
492
- * For each path:
493
- * - In both branches: their UnixFileEntry docs share Automerge history (deep
494
- * cloned at branch creation), so we Automerge-merge source's content into
495
- * target's. Concurrent edits are CRDT-merged inside each file doc.
496
- * - Only in source: deep-clone the source's file doc into a new doc and add
497
- * it to target's folder. Editing on either branch afterward stays isolated.
498
- * - Only in target: untouched. We don't propagate deletions from source — the
499
- * user can do that explicitly.
500
- *
501
- * Refuses if the working tree has uncommitted changes against the current
502
- * branch (run `pushwork save` first). Offline only — propagation happens on
503
- * the next `pushwork sync`.
504
- */
505
- /**
506
- * Compute what `merge <source>` would do without mutating any docs or the
507
- * working tree. For paths in both branches we apply the merge to a *clone*
508
- * of the target's file doc to learn the merged bytes; for paths only in
509
- * source we just read source's bytes.
510
- */
511
- export async function previewMerge(
512
- cwd: string,
513
- source: string,
514
- ): Promise<MergePreview> {
515
- if (!source) throw new Error("source branch name is required");
516
- const root = path.resolve(cwd);
517
- const config = await readConfig(root);
518
- if (!config.branches) throw new Error("pushwork repo has no branches");
519
- const targetName = await readBranchFile(root);
520
- if (!targetName) throw new Error("no current branch is set");
521
- if (source === targetName) {
522
- throw new Error(`cannot merge "${source}" into itself`);
523
- }
524
-
525
- const repo = await openRepo(config.backend, storageDir(root), { offline: true });
526
- try {
527
- const shape = await resolveShape(config.shape);
528
- const rootHandle = await repo.find<BranchesDoc>(config.rootUrl);
529
- const branchesDoc = rootHandle.doc();
530
- if (!isBranchesDoc(branchesDoc)) {
531
- throw new Error(`root doc at ${config.rootUrl} is not a branches doc`);
532
- }
533
- if (!branchesDoc.branches[source]) {
534
- throw new Error(`source branch "${source}" does not exist`);
535
- }
536
- const targetFolder = await repo.find<unknown>(branchesDoc.branches[targetName]);
537
- const sourceFolder = await repo.find<unknown>(branchesDoc.branches[source]);
538
-
539
- const tTree = await shape.decode({ repo, root: targetFolder });
540
- const sTree = await shape.decode({ repo, root: sourceFolder });
541
- const tLeaves = flattenLeaves(tTree);
542
- const sLeaves = flattenLeaves(sTree);
543
-
544
- const entries: MergePreviewEntry[] = [];
545
-
546
- for (const [posixPath, sUrl] of sLeaves) {
547
- const tUrl = tLeaves.get(posixPath);
548
- const sBare = stripHeads(sUrl);
549
- const sHandle = await repo.find<UnixFileEntry>(sBare);
550
- if (!tUrl) {
551
- entries.push({
552
- path: posixPath,
553
- kind: "added",
554
- after: contentToBytes(sHandle.doc().content),
555
- });
556
- continue;
557
- }
558
- const tBare = stripHeads(tUrl);
559
- if (tBare === sBare) continue;
560
- const tHandle = await repo.find<UnixFileEntry>(tBare);
561
- const before = contentToBytes(tHandle.doc().content);
562
- // Compute merge result without touching the target doc.
563
- const merged = Automerge.merge(
564
- Automerge.clone(tHandle.doc()),
565
- Automerge.clone(sHandle.doc()),
566
- ) as UnixFileEntry;
567
- const after = contentToBytes(merged.content);
568
- if (byteEq(before, after)) continue;
569
- entries.push({ path: posixPath, kind: "merged", before, after });
570
- }
571
-
572
- entries.sort((a, b) => a.path.localeCompare(b.path));
573
- return { source, target: targetName, entries };
574
- } finally {
575
- await repo.shutdown();
576
- }
577
- }
578
-
579
- export async function mergeBranch(
580
- cwd: string,
581
- source: string,
582
- ): Promise<MergeReport> {
583
- if (!source) throw new Error("source branch name is required");
584
- const root = path.resolve(cwd);
585
- const config = await readConfig(root);
586
- if (!config.branches) throw new Error("pushwork repo has no branches");
587
- const targetName = await readBranchFile(root);
588
- if (!targetName) throw new Error("no current branch is set");
589
- if (source === targetName) {
590
- throw new Error(`cannot merge "${source}" into itself`);
591
- }
592
- dlog("merge source=%s target=%s", source, targetName);
593
-
594
- const repo = await openRepo(config.backend, storageDir(root), { offline: true });
595
- try {
596
- const shape = await resolveShape(config.shape);
597
- const rootHandle = await repo.find<BranchesDoc>(config.rootUrl);
598
- const branchesDoc = rootHandle.doc();
599
- if (!isBranchesDoc(branchesDoc)) {
600
- throw new Error(`root doc at ${config.rootUrl} is not a branches doc`);
601
- }
602
- if (!branchesDoc.branches[source]) {
603
- throw new Error(`source branch "${source}" does not exist`);
604
- }
605
- const targetUrl = branchesDoc.branches[targetName];
606
- const sourceUrl = branchesDoc.branches[source];
607
-
608
- const targetFolder = await repo.find<unknown>(targetUrl);
609
- const sourceFolder = await repo.find<unknown>(sourceUrl);
610
-
611
- // Refuse on dirty working tree (mirror switchBranch policy).
612
- const tFiles = await readFileBytes(
613
- repo,
614
- await shape.decode({ repo, root: targetFolder }),
615
- );
616
- const ig = await loadIgnore(root);
617
- const fsFiles = await walkDir(root, ig);
618
- const dirty = computeDiff(tFiles, fsFiles);
619
- if (dirty.added.length || dirty.modified.length || dirty.deleted.length) {
620
- throw new Error(
621
- `refusing to merge: working tree has uncommitted changes on branch "${targetName}". run \`pushwork save\` first.`,
622
- );
623
- }
624
-
625
- const tTree = await shape.decode({ repo, root: targetFolder });
626
- const sTree = await shape.decode({ repo, root: sourceFolder });
627
- const tLeaves = flattenLeaves(tTree);
628
- const sLeaves = flattenLeaves(sTree);
629
-
630
- const merged: string[] = [];
631
- const added: string[] = [];
632
-
633
- // For paths in both: merge file docs in place.
634
- for (const [posixPath, sUrl] of sLeaves) {
635
- const tUrl = tLeaves.get(posixPath);
636
- if (!tUrl) continue;
637
- const tBare = stripHeads(tUrl);
638
- const sBare = stripHeads(sUrl);
639
- if (tBare === sBare) {
640
- // Same file doc identity (shared) — already in sync, nothing to do.
641
- continue;
642
- }
643
- const tHandle = await repo.find<UnixFileEntry>(tBare);
644
- const sHandle = await repo.find<UnixFileEntry>(sBare);
645
- tHandle.update((d) => Automerge.merge(d, Automerge.clone(sHandle.doc())));
646
- merged.push(posixPath);
647
- dlog("merge merged file at %s (%s ← %s)", posixPath, tBare, sBare);
648
- }
649
-
650
- // For paths only in source: deep-clone source's file doc, add to target's folder.
651
- const newLeaves = new Map<string, AutomergeUrl>();
652
- for (const [posixPath, sUrl] of sLeaves) {
653
- if (tLeaves.has(posixPath)) continue;
654
- const sBare = stripHeads(sUrl);
655
- const sHandle = await repo.find<unknown>(sBare);
656
- const cloned = repo.clone(sHandle);
657
- let finalUrl: AutomergeUrl = cloned.url;
658
- const parsed = parseAutomergeUrl(sUrl);
659
- if (parsed.heads) {
660
- finalUrl = pinUrl(cloned);
661
- }
662
- newLeaves.set(posixPath, finalUrl);
663
- added.push(posixPath);
664
- dlog("merge added %s url=%s", posixPath, finalUrl);
665
- }
666
-
667
- if (newLeaves.size > 0) {
668
- // Build a tree for the encode call: existing target leaves + new ones.
669
- const nextTree = newDir();
670
- for (const [p, url] of tLeaves) {
671
- setFileAt(nextTree, p.split("/").filter(Boolean), url);
672
- }
673
- for (const [p, url] of newLeaves) {
674
- setFileAt(nextTree, p.split("/").filter(Boolean), url);
675
- }
676
- await shape.encode({ repo, tree: nextTree, previousRoot: targetFolder });
677
- }
678
-
679
- // Materialize current branch (target) onto disk to reflect the merge.
680
- const finalTree = await shape.decode({ repo, root: targetFolder });
681
- await materializeTree(repo, root, finalTree);
682
-
683
- merged.sort();
684
- added.sort();
685
- return { source, target: targetName, merged, added };
686
- } finally {
687
- await repo.shutdown();
688
- }
689
- }
690
-
691
- /**
692
- * Capture the working tree's changes against the current branch's saved
693
- * state into a local stash, then reset the working tree to the saved state.
694
- * Stashes live in `.pushwork/stash.json` and are never synced.
695
- */
696
- export async function cutWorkdir(
697
- cwd: string,
698
- opts: { name?: string } = {},
699
- ): Promise<{ id: number; entries: number }> {
700
- const root = path.resolve(cwd);
701
- const config = await readConfig(root);
702
- const branchName = config.branches ? await readBranchFile(root) : null;
703
- dlog("cut root=%s branch=%s name=%s", root, branchName, opts.name ?? "(unnamed)");
704
-
705
- const repo = await openRepo(config.backend, storageDir(root), { offline: true });
706
- try {
707
- const shape = await resolveShape(config.shape);
708
- const rootHandle = await repo.find<unknown>(config.rootUrl);
709
- const folderHandle = await resolveEffectiveRoot(repo, rootHandle, branchName);
710
- const previousTree = await shape.decode({ repo, root: folderHandle });
711
- const previousFiles = await readFileBytes(repo, previousTree);
712
-
713
- const ig = await loadIgnore(root);
714
- const fsFiles = await walkDir(root, ig);
715
-
716
- const entries: StashEntry[] = [];
717
- for (const [p, bytes] of fsFiles) {
718
- const prev = previousFiles.get(p);
719
- if (!prev) {
720
- entries.push({ path: p, kind: "added", contentBase64: encodeBytes(bytes) });
721
- } else if (!byteEq(prev.bytes, bytes)) {
722
- entries.push({
723
- path: p,
724
- kind: "modified",
725
- contentBase64: encodeBytes(bytes),
726
- });
727
- }
728
- }
729
- for (const [p] of previousFiles) {
730
- if (!fsFiles.has(p)) entries.push({ path: p, kind: "deleted" });
731
- }
732
-
733
- if (entries.length === 0) {
734
- throw new Error("nothing to cut: working tree clean");
735
- }
736
- entries.sort((a, b) => a.path.localeCompare(b.path));
737
-
738
- const stash = await appendStash(root, {
739
- name: opts.name,
740
- branch: branchName,
741
- entries,
742
- });
743
-
744
- // Reset working tree to the branch's saved state.
745
- await materializeTree(repo, root, previousTree);
746
- dlog("cut complete id=%d entries=%d", stash.id, entries.length);
747
- return { id: stash.id, entries: entries.length };
748
- } finally {
749
- await repo.shutdown();
750
- }
751
- }
752
-
753
- /**
754
- * Apply a stash on top of the current working tree, then remove the stash
755
- * entry. Refuses if the working tree has uncommitted changes (caller can
756
- * `pushwork save` or `pushwork cut` first).
757
- */
758
- export async function pasteStash(
759
- cwd: string,
760
- selector?: string,
761
- ): Promise<{ id: number; entries: number; name?: string }> {
762
- const root = path.resolve(cwd);
763
- const config = await readConfig(root);
764
- const branchName = config.branches ? await readBranchFile(root) : null;
765
-
766
- // Check the working tree is clean against the current branch state.
767
- const repo = await openRepo(config.backend, storageDir(root), { offline: true });
768
- try {
769
- const shape = await resolveShape(config.shape);
770
- const rootHandle = await repo.find<unknown>(config.rootUrl);
771
- const folderHandle = await resolveEffectiveRoot(repo, rootHandle, branchName);
772
- const previousTree = await shape.decode({ repo, root: folderHandle });
773
- const previousFiles = await readFileBytes(repo, previousTree);
774
- const ig = await loadIgnore(root);
775
- const fsFiles = await walkDir(root, ig);
776
- const dirty = computeDiff(previousFiles, fsFiles);
777
- if (dirty.added.length || dirty.modified.length || dirty.deleted.length) {
778
- throw new Error(
779
- "refusing to paste: working tree has uncommitted changes. run `pushwork save` or `pushwork cut` first.",
780
- );
781
- }
782
- } finally {
783
- await repo.shutdown();
784
- }
785
-
786
- const stash = await takeStash(root, selector);
787
- if (!stash) {
788
- throw new Error(
789
- selector
790
- ? `no stash matches "${selector}"`
791
- : "nothing to paste: no stashes",
792
- );
793
- }
794
-
795
- for (const entry of stash.entries) {
796
- const target = path.join(root, fromPosix(entry.path));
797
- if (entry.kind === "deleted") {
798
- try {
799
- await fs.unlink(target);
800
- } catch {
801
- // already gone
802
- }
803
- await pruneEmptyDirs(root, path.dirname(fromPosix(entry.path)));
804
- } else if (entry.contentBase64 != null) {
805
- const bytes = decodeBytes(entry.contentBase64);
806
- await writeFileAtomic(target, bytes);
807
- }
808
- }
809
-
810
- dlog("paste complete id=%d entries=%d", stash.id, stash.entries.length);
811
- return { id: stash.id, name: stash.name, entries: stash.entries.length };
812
- }
813
-
814
- export async function showStashes(cwd: string): Promise<Stash[]> {
815
- return listStashes(path.resolve(cwd));
816
- }
817
-
818
- export async function switchBranch(cwd: string, name: string): Promise<void> {
819
- if (!name) throw new Error("branch name is required");
820
- const root = path.resolve(cwd);
821
- const config = await readConfig(root);
822
- if (!config.branches) throw new Error("pushwork repo has no branches");
823
- const currentName = await readBranchFile(root);
824
-
825
- const repo = await openRepo(config.backend, storageDir(root), { offline: true });
826
- try {
827
- const shape = await resolveShape(config.shape);
828
- const rootHandle = await repo.find<BranchesDoc>(config.rootUrl);
829
- const doc = rootHandle.doc();
830
- if (!isBranchesDoc(doc)) {
831
- throw new Error(`root doc at ${config.rootUrl} is not a branches doc`);
832
- }
833
- if (!doc.branches[name]) {
834
- throw new Error(`branch "${name}" does not exist`);
835
- }
836
-
837
- // Refuse if the working dir has uncommitted changes against the current branch.
838
- if (currentName) {
839
- const folderHandle = await resolveEffectiveRoot(repo, rootHandle, currentName);
840
- const previousTree = await shape.decode({ repo, root: folderHandle });
841
- const previousFiles = await readFileBytes(repo, previousTree);
842
- const ig = await loadIgnore(root);
843
- const fsFiles = await walkDir(root, ig);
844
- const d = computeDiff(previousFiles, fsFiles);
845
- if (d.added.length || d.modified.length || d.deleted.length) {
846
- throw new Error(
847
- `refusing to switch: working tree has uncommitted changes on branch "${currentName}". run \`pushwork save\` first.`,
848
- );
849
- }
850
- }
851
-
852
- // Materialize from the new branch.
853
- const newFolder = await repo.find<unknown>(doc.branches[name]);
854
- const tree = await shape.decode({ repo, root: newFolder });
855
- await materializeTree(repo, root, tree);
856
- await writeBranchFile(root, name);
857
- dlog("switch → %s", name);
858
- } finally {
859
- await repo.shutdown();
860
- }
861
- }
862
-
863
- type Stamped = { lastSyncAt?: number };
864
-
865
- function stampLastSyncAt(handle: DocHandle<unknown>): void {
866
- (handle as DocHandle<Stamped>).change((d: Stamped) => {
867
- d.lastSyncAt = Date.now();
868
- });
869
- }
870
-
871
- function normalizeDirs(dirs: readonly string[]): string[] {
872
- const seen = new Set<string>();
873
- const out: string[] = [];
874
- for (const d of dirs) {
875
- const norm = normalizeArtifactDir(d);
876
- if (!norm || seen.has(norm)) continue;
877
- seen.add(norm);
878
- out.push(norm);
879
- }
880
- return out;
881
- }
882
-
883
- function computeDiff(
884
- previous: Map<string, { url: AutomergeUrl; bytes: Uint8Array }>,
885
- current: Map<string, Uint8Array>,
886
- ): Diff {
887
- const added: string[] = [];
888
- const modified: string[] = [];
889
- const deleted: string[] = [];
890
- for (const [p, bytes] of current) {
891
- const prev = previous.get(p);
892
- if (!prev) added.push(p);
893
- else if (!byteEq(prev.bytes, bytes)) modified.push(p);
894
- }
895
- for (const p of previous.keys()) {
896
- if (!current.has(p)) deleted.push(p);
897
- }
898
- added.sort();
899
- modified.sort();
900
- deleted.sort();
901
- return { added, modified, deleted };
902
- }
903
-
904
- async function pushFiles(
905
- repo: Repo,
906
- fsFiles: Map<string, Uint8Array>,
907
- previous: Map<string, { url: AutomergeUrl; bytes: Uint8Array }> | undefined,
908
- artifactDirs: readonly string[],
909
- ): Promise<VfsNode> {
910
- const root = newDir();
911
- let created = 0;
912
- let updated = 0;
913
- let unchanged = 0;
914
- for (const [posixPath, bytes] of fsFiles) {
915
- const segments = posixPath.split("/").filter(Boolean);
916
- const isArtifact = isInArtifactDir(posixPath, artifactDirs);
917
- const fresh = makeFileEntry(posixPath, bytes, isArtifact);
918
- const prev = previous?.get(posixPath);
919
-
920
- let baseUrl: AutomergeUrl;
921
- if (prev && byteEq(prev.bytes, bytes)) {
922
- // Unchanged path: keep the existing file-doc URL. For artifacts
923
- // we'll re-pin from the current heads below.
924
- baseUrl = stripHeads(prev.url);
925
- unchanged++;
926
- } else if (prev) {
927
- // Changed path: mutate the existing file doc in place. This keeps
928
- // the file URL stable within a branch and avoids the propagation
929
- // race where a brand-new file doc URL is referenced by the folder
930
- // before its bytes have reached the sync server.
931
- //
932
- // For string content (text files) we use Automerge.updateText so
933
- // concurrent character-level edits merge correctly. Bytes and
934
- // ImmutableString are atomic — last writer wins on the field.
935
- //
936
- // Branch isolation is enforced separately: `createBranch` deep
937
- // clones every file doc the source branch references, so two
938
- // branches never share a UnixFileEntry doc identity.
939
- const refreshUrl = stripHeads(prev.url);
940
- const handle = await repo.find<UnixFileEntry>(refreshUrl);
941
- handle.change((d: UnixFileEntry) => {
942
- if (!contentEquals(d.content, fresh.content)) {
943
- if (
944
- typeof d.content === "string" &&
945
- typeof fresh.content === "string"
946
- ) {
947
- Automerge.updateText(d, ["content"], fresh.content);
948
- } else {
949
- d.content = fresh.content;
950
- }
951
- }
952
- if (d.extension !== fresh.extension) d.extension = fresh.extension;
953
- if (d.mimeType !== fresh.mimeType) d.mimeType = fresh.mimeType;
954
- if (d.name !== fresh.name) d.name = fresh.name;
955
- if (!d["@patchwork"]) d["@patchwork"] = { type: "file" };
956
- });
957
- baseUrl = refreshUrl;
958
- updated++;
959
- dlog("pushFiles updated %s url=%s artifact=%s bytes=%d", posixPath, baseUrl, isArtifact, bytes.length);
960
- } else {
961
- // New path: create a fresh file doc.
962
- const handle = repo.create<UnixFileEntry>(fresh);
963
- baseUrl = handle.url;
964
- created++;
965
- dlog("pushFiles created %s url=%s artifact=%s bytes=%d", posixPath, baseUrl, isArtifact, bytes.length);
966
- }
967
-
968
- const finalUrl = isArtifact
969
- ? pinUrl(await repo.find<UnixFileEntry>(baseUrl))
970
- : baseUrl;
971
- setFileAt(root, segments, finalUrl);
972
- }
973
- dlog("pushFiles done: %d created, %d updated, %d unchanged", created, updated, unchanged);
974
- return root;
975
- }
976
-
977
- async function readFileBytes(
978
- repo: Repo,
979
- tree: VfsNode,
980
- ): Promise<Map<string, { url: AutomergeUrl; bytes: Uint8Array }>> {
981
- const out = new Map<string, { url: AutomergeUrl; bytes: Uint8Array }>();
982
- for (const [posixPath, fileUrl] of flattenLeaves(tree)) {
983
- const handle = await repo.find<UnixFileEntry>(fileUrl);
984
- out.set(posixPath, {
985
- url: fileUrl,
986
- bytes: contentToBytes(handle.doc().content),
987
- });
988
- }
989
- return out;
990
- }
991
-
992
- async function materializeTree(
993
- repo: Repo,
994
- root: string,
995
- tree: VfsNode,
996
- ): Promise<void> {
997
- const desired = new Map<string, Uint8Array>();
998
- for (const [posixPath, fileUrl] of flattenLeaves(tree)) {
999
- const handle = await repo.find<UnixFileEntry>(fileUrl);
1000
- desired.set(posixPath, contentToBytes(handle.doc().content));
1001
- }
1002
- dlog("materialize desired: %d files", desired.size);
1003
-
1004
- const ig = await loadIgnore(root);
1005
- const present = await walkDir(root, ig);
1006
-
1007
- let written = 0;
1008
- let removed = 0;
1009
- for (const [posixPath, bytes] of desired) {
1010
- if (byteEq(present.get(posixPath), bytes)) continue;
1011
- await writeFileAtomic(path.join(root, fromPosix(posixPath)), bytes);
1012
- written++;
1013
- }
1014
- for (const posixPath of present.keys()) {
1015
- if (desired.has(posixPath)) continue;
1016
- try {
1017
- await fs.unlink(path.join(root, fromPosix(posixPath)));
1018
- removed++;
1019
- } catch {
1020
- // already gone
1021
- }
1022
- await pruneEmptyDirs(root, path.dirname(fromPosix(posixPath)));
1023
- }
1024
- dlog("materialize done: %d written, %d removed", written, removed);
1025
- }
1026
-
1027
- const fromPosix = (p: string) => p.split("/").join(path.sep);
1028
-
1029
- async function pruneEmptyDirs(root: string, relDir: string): Promise<void> {
1030
- let dir = relDir;
1031
- while (dir && dir !== "." && dir !== path.sep) {
1032
- const full = path.join(root, dir);
1033
- try {
1034
- const entries = await fs.readdir(full);
1035
- if (entries.length > 0) return;
1036
- await fs.rmdir(full);
1037
- } catch {
1038
- return;
1039
- }
1040
- dir = path.dirname(dir);
1041
- }
1042
- }
1043
-
1044
- function sameTree(a: VfsNode, b: VfsNode): boolean {
1045
- const av = flattenLeaves(a);
1046
- const bv = flattenLeaves(b);
1047
- if (av.size !== bv.size) return false;
1048
- for (const [k, v] of av) {
1049
- if (bv.get(k) !== v) return false;
1050
- }
1051
- return true;
1052
- }
1053
-
1054
- export type { Shape, UnixFileEntry, VfsNode, PushworkConfig };
1055
- export { deleteBranchFile };