runwork 0.2.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/auth/login-flow.d.ts +10 -0
  2. package/dist/auth/login-flow.js +37 -0
  3. package/dist/commands/clone.d.ts +3 -0
  4. package/dist/commands/clone.js +32 -24
  5. package/dist/commands/dev.d.ts +4 -0
  6. package/dist/commands/dev.js +103 -85
  7. package/dist/commands/init.d.ts +3 -0
  8. package/dist/commands/init.js +29 -21
  9. package/dist/commands/login.js +10 -25
  10. package/dist/commands/open.d.ts +2 -0
  11. package/dist/commands/open.js +43 -0
  12. package/dist/commands/welcome.d.ts +1 -0
  13. package/dist/commands/welcome.js +83 -0
  14. package/dist/generated/version.d.ts +1 -1
  15. package/dist/generated/version.js +1 -1
  16. package/dist/git/__tests__/auto-commit.test.d.ts +1 -0
  17. package/dist/git/__tests__/auto-commit.test.js +373 -0
  18. package/dist/git/__tests__/manifest.test.d.ts +1 -0
  19. package/dist/git/__tests__/manifest.test.js +377 -0
  20. package/dist/git/__tests__/sync.test.d.ts +1 -0
  21. package/dist/git/__tests__/sync.test.js +405 -0
  22. package/dist/git/auto-commit.d.ts +6 -1
  23. package/dist/git/auto-commit.js +29 -13
  24. package/dist/git/sync.d.ts +15 -0
  25. package/dist/git/sync.js +157 -0
  26. package/dist/index.js +16 -0
  27. package/dist/logs/__tests__/tailer-format.test.d.ts +1 -0
  28. package/dist/logs/__tests__/tailer-format.test.js +43 -0
  29. package/dist/logs/tailer.d.ts +3 -0
  30. package/dist/logs/tailer.js +47 -10
  31. package/dist/template/manifest.js +24 -4
  32. package/dist/types.d.ts +1 -0
  33. package/dist/ui/__tests__/banner.test.d.ts +1 -0
  34. package/dist/ui/__tests__/banner.test.js +82 -0
  35. package/dist/ui/__tests__/colors.test.d.ts +1 -0
  36. package/dist/ui/__tests__/colors.test.js +22 -0
  37. package/dist/ui/__tests__/keyboard.test.d.ts +1 -0
  38. package/dist/ui/__tests__/keyboard.test.js +30 -0
  39. package/dist/ui/__tests__/status-line.test.d.ts +1 -0
  40. package/dist/ui/__tests__/status-line.test.js +54 -0
  41. package/dist/ui/banner.d.ts +29 -0
  42. package/dist/ui/banner.js +118 -0
  43. package/dist/ui/colors.d.ts +4 -0
  44. package/dist/ui/colors.js +7 -0
  45. package/dist/ui/keyboard.d.ts +12 -0
  46. package/dist/ui/keyboard.js +57 -0
  47. package/dist/ui/status-line.d.ts +6 -0
  48. package/dist/ui/status-line.js +53 -0
  49. package/dist/utils/__tests__/prompt.test.js +23 -99
  50. package/dist/utils/prompt.d.ts +1 -0
  51. package/dist/utils/prompt.js +29 -21
  52. package/package.json +4 -2
@@ -0,0 +1,405 @@
1
+ import { describe, it, expect, afterEach } from 'vitest';
2
+ import { execFileSync } from 'child_process';
3
+ import { mkdtempSync, writeFileSync, readFileSync, rmSync, existsSync } from 'fs';
4
+ import { join } from 'path';
5
+ import { tmpdir } from 'os';
6
+ import { syncWithRemote, hasCommits, hasTrackedChanges } from '../sync.js';
7
+ const tempDirs = [];
8
+ function makeTempDir(prefix) {
9
+ const dir = mkdtempSync(join(tmpdir(), `runwork-sync-test-${prefix}-`));
10
+ tempDirs.push(dir);
11
+ return dir;
12
+ }
13
+ function createTestRepo() {
14
+ const remote = makeTempDir('remote');
15
+ execFileSync('git', ['init', '--bare', remote]);
16
+ const local = makeTempDir('local');
17
+ execFileSync('git', ['init', local]);
18
+ execFileSync('git', ['remote', 'add', 'runwork', remote], { cwd: local });
19
+ execFileSync('git', ['config', 'user.email', 'test@test.com'], { cwd: local });
20
+ execFileSync('git', ['config', 'user.name', 'Test'], { cwd: local });
21
+ return { local, remote };
22
+ }
23
+ /** Create a second clone of the same bare remote (for simulating remote-side commits). */
24
+ function cloneAsSecondary(remote) {
25
+ const secondary = makeTempDir('secondary');
26
+ execFileSync('git', ['clone', remote, secondary]);
27
+ execFileSync('git', ['config', 'user.email', 'other@test.com'], { cwd: secondary });
28
+ execFileSync('git', ['config', 'user.name', 'Other'], { cwd: secondary });
29
+ return secondary;
30
+ }
31
+ function commitFile(repoDir, filename, content, message) {
32
+ writeFileSync(join(repoDir, filename), content);
33
+ execFileSync('git', ['add', filename], { cwd: repoDir });
34
+ execFileSync('git', ['commit', '-m', message], { cwd: repoDir });
35
+ return execFileSync('git', ['rev-parse', 'HEAD'], { cwd: repoDir, encoding: 'utf-8' }).trim();
36
+ }
37
+ function getLog(repoDir) {
38
+ return execFileSync('git', ['log', '--oneline', '--all'], { cwd: repoDir, encoding: 'utf-8' })
39
+ .trim()
40
+ .split('\n')
41
+ .filter(Boolean);
42
+ }
43
+ function getHeadHash(repoDir) {
44
+ return execFileSync('git', ['rev-parse', 'HEAD'], { cwd: repoDir, encoding: 'utf-8' }).trim();
45
+ }
46
+ afterEach(() => {
47
+ for (const dir of tempDirs) {
48
+ try {
49
+ rmSync(dir, { recursive: true, force: true });
50
+ }
51
+ catch { /* best effort */ }
52
+ }
53
+ tempDirs.length = 0;
54
+ });
55
+ describe('hasCommits()', () => {
56
+ it('returns false for repo with no commits', () => {
57
+ const dir = makeTempDir('empty');
58
+ execFileSync('git', ['init', dir]);
59
+ expect(hasCommits(dir)).toBe(false);
60
+ });
61
+ it('returns true for repo with commits', () => {
62
+ const { local } = createTestRepo();
63
+ commitFile(local, 'a.txt', 'hello', 'init');
64
+ expect(hasCommits(local)).toBe(true);
65
+ });
66
+ });
67
+ describe('hasTrackedChanges()', () => {
68
+ it('returns false for clean working tree', () => {
69
+ const { local } = createTestRepo();
70
+ commitFile(local, 'a.txt', 'hello', 'init');
71
+ expect(hasTrackedChanges(local)).toBe(false);
72
+ });
73
+ it('returns true for modified tracked file', () => {
74
+ const { local } = createTestRepo();
75
+ commitFile(local, 'a.txt', 'hello', 'init');
76
+ writeFileSync(join(local, 'a.txt'), 'changed');
77
+ expect(hasTrackedChanges(local)).toBe(true);
78
+ });
79
+ it('returns false when only untracked files exist', () => {
80
+ const { local } = createTestRepo();
81
+ commitFile(local, 'a.txt', 'hello', 'init');
82
+ writeFileSync(join(local, 'untracked.txt'), 'new');
83
+ expect(hasTrackedChanges(local)).toBe(false);
84
+ });
85
+ });
86
+ describe('syncWithRemote()', () => {
87
+ it('returns skipped when there are no local commits', () => {
88
+ const { local } = createTestRepo();
89
+ const result = syncWithRemote(local);
90
+ expect(result).toEqual({ status: 'skipped', pushed: false });
91
+ });
92
+ it('syncs when local and remote are already in sync', () => {
93
+ const { local, remote } = createTestRepo();
94
+ commitFile(local, 'a.txt', 'hello', 'init');
95
+ execFileSync('git', ['push', 'runwork', 'main'], { cwd: local, stdio: 'pipe' });
96
+ const result = syncWithRemote(local);
97
+ expect(result.status).toBe('synced');
98
+ expect(result.pushed).toBe(true);
99
+ });
100
+ it('pushes local commits when remote has no new changes', () => {
101
+ const { local, remote } = createTestRepo();
102
+ commitFile(local, 'a.txt', 'hello', 'init');
103
+ execFileSync('git', ['push', 'runwork', 'main'], { cwd: local, stdio: 'pipe' });
104
+ // Add a new local commit
105
+ commitFile(local, 'b.txt', 'world', 'second');
106
+ const localHead = getHeadHash(local);
107
+ const result = syncWithRemote(local);
108
+ expect(result.status).toBe('synced');
109
+ expect(result.pushed).toBe(true);
110
+ // Verify remote has the new commit
111
+ const remoteHead = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: remote, encoding: 'utf-8' }).trim();
112
+ expect(remoteHead).toBe(localHead);
113
+ });
114
+ it('rebases local on remote when remote has new commits', () => {
115
+ const { local, remote } = createTestRepo();
116
+ commitFile(local, 'a.txt', 'hello', 'init');
117
+ execFileSync('git', ['push', 'runwork', 'main'], { cwd: local, stdio: 'pipe' });
118
+ // Push a commit from another clone to simulate remote changes
119
+ const secondary = cloneAsSecondary(remote);
120
+ commitFile(secondary, 'remote-file.txt', 'from-remote', 'remote commit');
121
+ execFileSync('git', ['push', 'origin', 'main'], { cwd: secondary, stdio: 'pipe' });
122
+ const result = syncWithRemote(local);
123
+ expect(result.status).toBe('synced');
124
+ // Local should now have the remote file
125
+ expect(existsSync(join(local, 'remote-file.txt'))).toBe(true);
126
+ expect(readFileSync(join(local, 'remote-file.txt'), 'utf-8')).toBe('from-remote');
127
+ });
128
+ it('rebases when both sides have non-conflicting commits', () => {
129
+ const { local, remote } = createTestRepo();
130
+ commitFile(local, 'a.txt', 'hello', 'init');
131
+ execFileSync('git', ['push', 'runwork', 'main'], { cwd: local, stdio: 'pipe' });
132
+ // Remote adds a file
133
+ const secondary = cloneAsSecondary(remote);
134
+ commitFile(secondary, 'remote-file.txt', 'remote-content', 'remote commit');
135
+ execFileSync('git', ['push', 'origin', 'main'], { cwd: secondary, stdio: 'pipe' });
136
+ // Local adds a different file
137
+ commitFile(local, 'local-file.txt', 'local-content', 'local commit');
138
+ const result = syncWithRemote(local);
139
+ expect(result.status).toBe('synced');
140
+ expect(result.pushed).toBe(true);
141
+ // Both files should be present
142
+ expect(readFileSync(join(local, 'remote-file.txt'), 'utf-8')).toBe('remote-content');
143
+ expect(readFileSync(join(local, 'local-file.txt'), 'utf-8')).toBe('local-content');
144
+ // Verify remote also has both
145
+ const secondaryCheck = cloneAsSecondary(remote);
146
+ expect(existsSync(join(secondaryCheck, 'remote-file.txt'))).toBe(true);
147
+ expect(existsSync(join(secondaryCheck, 'local-file.txt'))).toBe(true);
148
+ });
149
+ it('handles unrelated histories with non-overlapping files via rebase', () => {
150
+ const { local, remote } = createTestRepo();
151
+ // Local has its own history
152
+ commitFile(local, 'local-file.txt', 'local', 'local init');
153
+ // Create a completely separate history and force-push it to remote
154
+ const other = makeTempDir('other');
155
+ execFileSync('git', ['init', other]);
156
+ execFileSync('git', ['config', 'user.email', 'other@test.com'], { cwd: other });
157
+ execFileSync('git', ['config', 'user.name', 'Other'], { cwd: other });
158
+ commitFile(other, 'remote-only.txt', 'remote', 'remote init');
159
+ execFileSync('git', ['remote', 'add', 'origin', remote], { cwd: other });
160
+ execFileSync('git', ['push', 'origin', 'main'], { cwd: other, stdio: 'pipe' });
161
+ const result = syncWithRemote(local);
162
+ // Modern git can rebase non-conflicting unrelated histories
163
+ expect(['synced', 'merged']).toContain(result.status);
164
+ // Both files should be present regardless of strategy used
165
+ expect(existsSync(join(local, 'local-file.txt'))).toBe(true);
166
+ expect(existsSync(join(local, 'remote-only.txt'))).toBe(true);
167
+ });
168
+ it('auto-resolves conflicting unrelated histories by accepting remote', () => {
169
+ const { local, remote } = createTestRepo();
170
+ // Local modifies a file
171
+ commitFile(local, 'shared.txt', 'local-line-1\nlocal-line-2\n', 'local init');
172
+ // Remote has completely different history touching the same file
173
+ const other = makeTempDir('other');
174
+ execFileSync('git', ['init', other]);
175
+ execFileSync('git', ['config', 'user.email', 'other@test.com'], { cwd: other });
176
+ execFileSync('git', ['config', 'user.name', 'Other'], { cwd: other });
177
+ commitFile(other, 'shared.txt', 'remote-line-1\nremote-line-2\n', 'remote init');
178
+ execFileSync('git', ['remote', 'add', 'origin', remote], { cwd: other });
179
+ execFileSync('git', ['push', 'origin', 'main'], { cwd: other, stdio: 'pipe' });
180
+ const result = syncWithRemote(local);
181
+ // Conflicts auto-resolved with -X theirs (remote wins for first sync)
182
+ expect(result.status).toBe('merged');
183
+ // Remote version should win
184
+ expect(readFileSync(join(local, 'shared.txt'), 'utf-8')).toBe('remote-line-1\nremote-line-2\n');
185
+ });
186
+ it('stashes and restores dirty working tree during sync', () => {
187
+ const { local, remote } = createTestRepo();
188
+ commitFile(local, 'a.txt', 'hello', 'init');
189
+ execFileSync('git', ['push', 'runwork', 'main'], { cwd: local, stdio: 'pipe' });
190
+ // Remote adds a commit
191
+ const secondary = cloneAsSecondary(remote);
192
+ commitFile(secondary, 'remote-file.txt', 'remote', 'remote commit');
193
+ execFileSync('git', ['push', 'origin', 'main'], { cwd: secondary, stdio: 'pipe' });
194
+ // Make local dirty (modify a tracked file without committing)
195
+ writeFileSync(join(local, 'a.txt'), 'dirty-change');
196
+ const result = syncWithRemote(local);
197
+ expect(result.status).toBe('synced');
198
+ // Dirty change should be preserved
199
+ expect(readFileSync(join(local, 'a.txt'), 'utf-8')).toBe('dirty-change');
200
+ // Remote file should also be present
201
+ expect(existsSync(join(local, 'remote-file.txt'))).toBe(true);
202
+ });
203
+ it('reports stash conflict when stash pop fails', () => {
204
+ const { local, remote } = createTestRepo();
205
+ commitFile(local, 'shared.txt', 'original', 'init');
206
+ execFileSync('git', ['push', 'runwork', 'main'], { cwd: local, stdio: 'pipe' });
207
+ // Remote modifies the same file
208
+ const secondary = cloneAsSecondary(remote);
209
+ writeFileSync(join(secondary, 'shared.txt'), 'remote-version');
210
+ execFileSync('git', ['add', 'shared.txt'], { cwd: secondary });
211
+ execFileSync('git', ['commit', '-m', 'remote change to shared'], { cwd: secondary });
212
+ execFileSync('git', ['push', 'origin', 'main'], { cwd: secondary, stdio: 'pipe' });
213
+ // Local has uncommitted changes to the same file
214
+ writeFileSync(join(local, 'shared.txt'), 'local-dirty-version');
215
+ const result = syncWithRemote(local);
216
+ expect(result.error).toBe('stash-conflict');
217
+ expect(result.pushed).toBe(false);
218
+ });
219
+ it('handles fetch failure gracefully (unreachable remote)', () => {
220
+ const { local } = createTestRepo();
221
+ commitFile(local, 'a.txt', 'hello', 'init');
222
+ // Point remote to a non-existent path
223
+ const badPath = join(tmpdir(), 'nonexistent-repo-' + Date.now());
224
+ execFileSync('git', ['remote', 'set-url', 'runwork', badPath], { cwd: local });
225
+ const result = syncWithRemote(local);
226
+ expect(result.status).toBe('sync-failed');
227
+ expect(result.pushed).toBe(false);
228
+ // Local repo should be untouched
229
+ expect(readFileSync(join(local, 'a.txt'), 'utf-8')).toBe('hello');
230
+ });
231
+ it('removes conflicting untracked files before rebase', () => {
232
+ const { local, remote } = createTestRepo();
233
+ commitFile(local, 'a.txt', 'hello', 'init');
234
+ execFileSync('git', ['push', 'runwork', 'main'], { cwd: local, stdio: 'pipe' });
235
+ // Remote adds a new file via secondary clone
236
+ const secondary = cloneAsSecondary(remote);
237
+ commitFile(secondary, 'skeleton.txt', 'from-remote', 'add skeleton');
238
+ execFileSync('git', ['push', 'origin', 'main'], { cwd: secondary, stdio: 'pipe' });
239
+ // Local has the same file as untracked (simulating template download)
240
+ writeFileSync(join(local, 'skeleton.txt'), 'local-untracked-version');
241
+ const result = syncWithRemote(local);
242
+ expect(result.status).toBe('synced');
243
+ // The file should now contain the remote version (committed)
244
+ expect(readFileSync(join(local, 'skeleton.txt'), 'utf-8')).toBe('from-remote');
245
+ });
246
+ it('preserves local state when fetch fails with dirty tree', () => {
247
+ const { local } = createTestRepo();
248
+ commitFile(local, 'a.txt', 'hello', 'init');
249
+ // Make working tree dirty
250
+ writeFileSync(join(local, 'a.txt'), 'dirty');
251
+ // Point remote to bad path
252
+ const badPath = join(tmpdir(), 'nonexistent-repo-' + Date.now());
253
+ execFileSync('git', ['remote', 'set-url', 'runwork', badPath], { cwd: local });
254
+ const result = syncWithRemote(local);
255
+ expect(result.status).toBe('sync-failed');
256
+ // Dirty changes should be restored from stash
257
+ expect(readFileSync(join(local, 'a.txt'), 'utf-8')).toBe('dirty');
258
+ });
259
+ });
260
+ // ============================================================
261
+ // EDGE CASE TESTS - probing for real bugs
262
+ // ============================================================
263
+ describe('hasTrackedChanges() edge cases', () => {
264
+ it('returns true for staged deletions (git rm)', () => {
265
+ const { local } = createTestRepo();
266
+ commitFile(local, 'a.txt', 'hello', 'init');
267
+ // Stage a deletion
268
+ execFileSync('git', ['rm', 'a.txt'], { cwd: local, stdio: 'pipe' });
269
+ // git status --porcelain shows "D a.txt" which does not start with "??"
270
+ expect(hasTrackedChanges(local)).toBe(true);
271
+ });
272
+ it('returns true for staged new file (git add of new file)', () => {
273
+ const { local } = createTestRepo();
274
+ commitFile(local, 'a.txt', 'hello', 'init');
275
+ // Create and stage a new file (status: "A new.txt")
276
+ writeFileSync(join(local, 'new.txt'), 'new content');
277
+ execFileSync('git', ['add', 'new.txt'], { cwd: local, stdio: 'pipe' });
278
+ expect(hasTrackedChanges(local)).toBe(true);
279
+ });
280
+ });
281
+ describe('syncWithRemote() edge cases', () => {
282
+ it('stash/pop works correctly when only staged deletions exist', () => {
283
+ // Edge case: hasTrackedChanges returns true for staged deletions,
284
+ // but does git stash push actually stash a staged deletion?
285
+ // If stash doesn't capture it, stash pop could fail or restore wrong state.
286
+ const { local, remote } = createTestRepo();
287
+ commitFile(local, 'a.txt', 'hello', 'init');
288
+ commitFile(local, 'b.txt', 'world', 'second');
289
+ execFileSync('git', ['push', 'runwork', 'main'], { cwd: local, stdio: 'pipe' });
290
+ // Remote adds a new file
291
+ const secondary = cloneAsSecondary(remote);
292
+ commitFile(secondary, 'remote-file.txt', 'remote', 'remote commit');
293
+ execFileSync('git', ['push', 'origin', 'main'], { cwd: secondary, stdio: 'pipe' });
294
+ // Stage a deletion locally (without committing)
295
+ execFileSync('git', ['rm', 'b.txt'], { cwd: local, stdio: 'pipe' });
296
+ expect(hasTrackedChanges(local)).toBe(true);
297
+ expect(existsSync(join(local, 'b.txt'))).toBe(false);
298
+ const result = syncWithRemote(local);
299
+ expect(result.status).toBe('synced');
300
+ // After sync, the staged deletion should be restored
301
+ // (stash pop should bring back the staged rm state)
302
+ expect(existsSync(join(local, 'b.txt'))).toBe(false);
303
+ // Verify the deletion is still staged
304
+ const status = execFileSync('git', ['status', '--porcelain'], {
305
+ cwd: local, encoding: 'utf-8',
306
+ }).trim();
307
+ expect(status).toContain('b.txt');
308
+ });
309
+ it('handles sync when remote branch main does not exist yet (empty bare repo)', () => {
310
+ // User creates local repo and commits, but never pushed to remote.
311
+ // Remote is empty. fetch runwork main should fail.
312
+ const { local, remote } = createTestRepo();
313
+ commitFile(local, 'a.txt', 'hello', 'init');
314
+ // Do NOT push -- remote has no 'main' branch
315
+ const result = syncWithRemote(local);
316
+ // fetch should fail because remote has no main branch
317
+ expect(result.status).toBe('sync-failed');
318
+ // But local repo should be intact
319
+ expect(readFileSync(join(local, 'a.txt'), 'utf-8')).toBe('hello');
320
+ });
321
+ it('leaves repo clean after auto-resolving conflicting unrelated histories', () => {
322
+ const { local, remote } = createTestRepo();
323
+ commitFile(local, 'shared.txt', 'local version\n', 'local init');
324
+ // Create conflicting remote history
325
+ const other = makeTempDir('other');
326
+ execFileSync('git', ['init', other]);
327
+ execFileSync('git', ['config', 'user.email', 'other@test.com'], { cwd: other });
328
+ execFileSync('git', ['config', 'user.name', 'Other'], { cwd: other });
329
+ commitFile(other, 'shared.txt', 'remote version\n', 'remote init');
330
+ execFileSync('git', ['remote', 'add', 'origin', remote], { cwd: other });
331
+ execFileSync('git', ['push', 'origin', 'main'], { cwd: other, stdio: 'pipe' });
332
+ const result = syncWithRemote(local);
333
+ // Auto-resolved with -X theirs
334
+ expect(result.status).toBe('merged');
335
+ // Repo should NOT be in a rebase or merge state
336
+ expect(existsSync(join(local, '.git', 'MERGE_HEAD'))).toBe(false);
337
+ expect(existsSync(join(local, '.git', 'rebase-merge'))).toBe(false);
338
+ expect(existsSync(join(local, '.git', 'rebase-apply'))).toBe(false);
339
+ // Remote version wins
340
+ expect(readFileSync(join(local, 'shared.txt'), 'utf-8')).toBe('remote version\n');
341
+ });
342
+ it('handles merge conflict during rebase on related histories (same file edited both sides)', () => {
343
+ const { local, remote } = createTestRepo();
344
+ commitFile(local, 'shared.txt', 'original content\n', 'init');
345
+ execFileSync('git', ['push', 'runwork', 'main'], { cwd: local, stdio: 'pipe' });
346
+ // Remote modifies shared.txt
347
+ const secondary = cloneAsSecondary(remote);
348
+ writeFileSync(join(secondary, 'shared.txt'), 'remote edit line 1\nremote edit line 2\n');
349
+ execFileSync('git', ['add', 'shared.txt'], { cwd: secondary });
350
+ execFileSync('git', ['commit', '-m', 'remote edit'], { cwd: secondary });
351
+ execFileSync('git', ['push', 'origin', 'main'], { cwd: secondary, stdio: 'pipe' });
352
+ // Local also modifies shared.txt (same area -> conflict)
353
+ writeFileSync(join(local, 'shared.txt'), 'local edit line 1\nlocal edit line 2\n');
354
+ execFileSync('git', ['add', 'shared.txt'], { cwd: local });
355
+ execFileSync('git', ['commit', '-m', 'local edit'], { cwd: local });
356
+ const result = syncWithRemote(local);
357
+ // Rebase should fail due to conflict, merge fallback should also have conflicts
358
+ // OR merge with --allow-unrelated-histories might succeed (unlikely for related histories)
359
+ // The key assertion: repo must NOT be left in broken state
360
+ expect(existsSync(join(local, '.git', 'MERGE_HEAD'))).toBe(false);
361
+ expect(existsSync(join(local, '.git', 'rebase-merge'))).toBe(false);
362
+ // Either merged or sync-failed, but never left in limbo
363
+ expect(['synced', 'merged', 'sync-failed']).toContain(result.status);
364
+ });
365
+ it('stash pop after sync-failed still restores dirty state', () => {
366
+ // If sync fails (fetch fails), dirty state should still be restored.
367
+ // But what if the stash was created and then the repo state changed
368
+ // (e.g., aborted rebase left things in weird state)?
369
+ const { local } = createTestRepo();
370
+ commitFile(local, 'a.txt', 'committed', 'init');
371
+ // Make dirty
372
+ writeFileSync(join(local, 'a.txt'), 'uncommitted change');
373
+ // Point to bad remote
374
+ const badPath = join(tmpdir(), 'nonexistent-' + Date.now());
375
+ execFileSync('git', ['remote', 'set-url', 'runwork', badPath], { cwd: local });
376
+ const result = syncWithRemote(local);
377
+ expect(result.status).toBe('sync-failed');
378
+ // The stash should have been popped successfully
379
+ expect(result.error).not.toBe('stash-conflict');
380
+ expect(readFileSync(join(local, 'a.txt'), 'utf-8')).toBe('uncommitted change');
381
+ // Stash list should be empty (stash was popped)
382
+ const stashList = execFileSync('git', ['stash', 'list'], {
383
+ cwd: local, encoding: 'utf-8',
384
+ }).trim();
385
+ expect(stashList).toBe('');
386
+ });
387
+ it('does not leave orphan stash entries on successful sync', () => {
388
+ const { local, remote } = createTestRepo();
389
+ commitFile(local, 'a.txt', 'hello', 'init');
390
+ execFileSync('git', ['push', 'runwork', 'main'], { cwd: local, stdio: 'pipe' });
391
+ // Remote adds a file
392
+ const secondary = cloneAsSecondary(remote);
393
+ commitFile(secondary, 'remote.txt', 'remote', 'remote commit');
394
+ execFileSync('git', ['push', 'origin', 'main'], { cwd: secondary, stdio: 'pipe' });
395
+ // Make local dirty
396
+ writeFileSync(join(local, 'a.txt'), 'dirty');
397
+ const result = syncWithRemote(local);
398
+ expect(result.status).toBe('synced');
399
+ // Stash should be empty - no orphan stash entries
400
+ const stashList = execFileSync('git', ['stash', 'list'], {
401
+ cwd: local, encoding: 'utf-8',
402
+ }).trim();
403
+ expect(stashList).toBe('');
404
+ });
405
+ });
@@ -1,3 +1,8 @@
1
1
  import type { ApiClient } from '../api/client.js';
2
- export declare function watchAndAutoCommit(directory: string, client: ApiClient, appId: string): Promise<void>;
2
+ export declare function isIgnored(filePath: string): boolean;
3
+ export declare function watchAndAutoCommit(directory: string, client: ApiClient, appId: string, callbacks?: {
4
+ onFileChange?: (relPath: string, pendingCount: number) => void;
5
+ onFastSync?: (count: number) => void;
6
+ onGitPush?: (count: number) => void;
7
+ }): Promise<void>;
3
8
  export declare function stopAutoCommit(): Promise<void>;
@@ -2,17 +2,19 @@ import { execFileSync } from 'child_process';
2
2
  import { readFileSync } from 'fs';
3
3
  import { watch } from 'chokidar';
4
4
  import { basename, join, relative } from 'path';
5
+ import { dim, cyan, yellow } from '../ui/colors.js';
5
6
  let watcher = null;
6
7
  let fastSyncTimer = null;
7
8
  let gitTimer = null;
8
9
  let gitPushing = false;
9
10
  let gitPendingAfterPush = false;
11
+ let activeCallbacks;
10
12
  // Files awaiting fast sync: path -> 'changed' | 'deleted'
11
13
  const pendingFastSync = new Map();
12
14
  // Track files the user actually touched during this session (for git)
13
15
  const changedFiles = new Set();
14
16
  const SKIP_DIRS = new Set(['node_modules', '.git', '.runwork']);
15
- const SKIP_FILES = new Set(['.dev.vars']);
17
+ const SKIP_FILES = new Set(['.dev.vars', '.env']);
16
18
  const SKIP_EXTENSIONS = new Set(['.log']);
17
19
  // Binary extensions to skip in fast sync (git handles them fine)
18
20
  const BINARY_EXTENSIONS = new Set([
@@ -22,7 +24,7 @@ const BINARY_EXTENSIONS = new Set([
22
24
  '.zip', '.tar', '.gz', '.br',
23
25
  '.pdf', '.wasm',
24
26
  ]);
25
- function isIgnored(filePath) {
27
+ export function isIgnored(filePath) {
26
28
  const name = basename(filePath);
27
29
  if (SKIP_DIRS.has(name))
28
30
  return true;
@@ -33,7 +35,8 @@ function isIgnored(filePath) {
33
35
  return true;
34
36
  return false;
35
37
  }
36
- export async function watchAndAutoCommit(directory, client, appId) {
38
+ export async function watchAndAutoCommit(directory, client, appId, callbacks) {
39
+ activeCallbacks = callbacks;
37
40
  watcher = watch(directory, {
38
41
  ignored: isIgnored,
39
42
  persistent: true,
@@ -46,19 +49,20 @@ export async function watchAndAutoCommit(directory, client, appId) {
46
49
  const onFileChange = (filePath) => {
47
50
  const rel = relative(directory, filePath);
48
51
  if (changedFiles.size === 0) {
49
- console.log(`Changed: ${rel}`);
52
+ console.log(` ${dim('Changed:')} ${cyan(rel)}`);
50
53
  }
51
54
  else {
52
- console.log(`Changed: ${rel} (+${changedFiles.size} pending)`);
55
+ console.log(` ${dim('Changed:')} ${cyan(rel)} ${dim(`(+${changedFiles.size} pending)`)}`);
53
56
  }
54
57
  changedFiles.add(rel);
55
58
  pendingFastSync.set(rel, 'changed');
59
+ activeCallbacks?.onFileChange?.(rel, changedFiles.size);
56
60
  scheduleFastSync(directory, client, appId);
57
61
  scheduleGitCommit();
58
62
  };
59
63
  const onFileUnlink = (filePath) => {
60
64
  const rel = relative(directory, filePath);
61
- console.log(`Deleted: ${rel}`);
65
+ console.log(` ${dim('Deleted:')} ${cyan(rel)}`);
62
66
  changedFiles.add(rel);
63
67
  pendingFastSync.set(rel, 'deleted');
64
68
  scheduleFastSync(directory, client, appId);
@@ -109,11 +113,12 @@ async function executeFastSync(directory, client, appId) {
109
113
  const total = files.length + deletedFiles.length;
110
114
  try {
111
115
  await client.syncFiles(appId, files, deletedFiles.length > 0 ? deletedFiles : undefined);
112
- console.log(` Synced ${total} file(s) to preview.`);
116
+ console.log(dim(` Synced ${total} file(s) to preview.`));
117
+ activeCallbacks?.onFastSync?.(total);
113
118
  }
114
119
  catch (error) {
115
120
  const message = error instanceof Error ? error.message : String(error);
116
- console.warn(` Fast sync failed (git will handle it): ${message}`);
121
+ console.warn(yellow(` Fast sync failed (git will handle it): ${message}`));
117
122
  }
118
123
  }
119
124
  // ========================================
@@ -153,7 +158,7 @@ function commitAndPush() {
153
158
  }
154
159
  }
155
160
  // Check if anything was actually staged
156
- const staged = execFileSync('git', ['diff', '--cached', '--name-only'], { encoding: 'utf-8' });
161
+ const staged = execFileSync('git', ['-c', 'core.quotePath=false', 'diff', '--cached', '--name-only'], { encoding: 'utf-8' });
157
162
  if (!staged.trim())
158
163
  return;
159
164
  const stagedFiles = staged.trim().split('\n').filter(Boolean);
@@ -169,8 +174,18 @@ function commitAndPush() {
169
174
  execFileSync('git', ['rebase', '--abort'], { stdio: 'pipe' });
170
175
  }
171
176
  catch { /* no rebase in progress */ }
172
- console.warn('Auto-sync: rebase failed, skipping push. Run `git pull --rebase runwork main` manually.');
173
- return;
177
+ // Rebase fails when histories diverged (e.g. template update). Fall back to merge.
178
+ try {
179
+ execFileSync('git', ['merge', 'runwork/main', '--allow-unrelated-histories', '--no-edit'], { stdio: 'pipe' });
180
+ }
181
+ catch {
182
+ try {
183
+ execFileSync('git', ['merge', '--abort'], { stdio: 'pipe' });
184
+ }
185
+ catch { /* no merge in progress */ }
186
+ console.warn(yellow('Auto-sync: merge failed, skipping push. Run `git pull --rebase runwork main` manually.'));
187
+ return;
188
+ }
174
189
  }
175
190
  try {
176
191
  execFileSync('git', ['rev-parse', '--abbrev-ref', '@{u}'], { stdio: 'pipe' });
@@ -179,11 +194,12 @@ function commitAndPush() {
179
194
  catch {
180
195
  execFileSync('git', ['push', '-u', 'runwork', 'main'], { stdio: 'pipe' });
181
196
  }
182
- console.log(` Pushed ${stagedFiles.length} file(s) to git.`);
197
+ console.log(dim(` Pushed ${stagedFiles.length} file(s) to git.`));
198
+ activeCallbacks?.onGitPush?.(stagedFiles.length);
183
199
  }
184
200
  catch (error) {
185
201
  const message = error instanceof Error ? error.message : String(error);
186
- console.warn(`Auto-sync failed: ${message}`);
202
+ console.warn(yellow(`Auto-sync failed: ${message}`));
187
203
  }
188
204
  finally {
189
205
  gitPushing = false;
@@ -0,0 +1,15 @@
1
+ export interface SyncResult {
2
+ status: 'synced' | 'merged' | 'sync-failed' | 'skipped';
3
+ pushed: boolean;
4
+ error?: string;
5
+ }
6
+ export declare function hasCommits(cwd: string): boolean;
7
+ export declare function hasTrackedChanges(cwd: string): boolean;
8
+ /**
9
+ * Sync local repository with the runwork remote.
10
+ *
11
+ * Strategy: fetch, then attempt rebase. If rebase fails (e.g. diverged
12
+ * histories after a template update), fall back to merge with
13
+ * --allow-unrelated-histories. Stash/pop around dirty working trees.
14
+ */
15
+ export declare function syncWithRemote(cwd: string): SyncResult;