@myrialabs/clopen 0.4.35 → 0.4.37

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 (91) hide show
  1. package/backend/artifacts/sync.test.ts +63 -0
  2. package/backend/artifacts/sync.ts +56 -3
  3. package/backend/database/migrations/070_create_worktrees_table.ts +67 -0
  4. package/backend/database/migrations/index.ts +7 -0
  5. package/backend/database/queries/index.ts +1 -0
  6. package/backend/database/queries/session-queries.ts +50 -11
  7. package/backend/database/queries/worktree-queries.ts +148 -0
  8. package/backend/engine/adapters/opencode/server.ts +389 -83
  9. package/backend/engine/adapters/opencode/stream.ts +14 -14
  10. package/backend/engine/hot-reload.ts +25 -10
  11. package/backend/files/file-watcher.ts +35 -9
  12. package/backend/git/conflict-state.test.ts +396 -0
  13. package/backend/git/git-executor.ts +6 -0
  14. package/backend/git/git-parser.ts +144 -48
  15. package/backend/git/git-service.ts +727 -57
  16. package/backend/git/push-target.test.ts +264 -0
  17. package/backend/host/metrics.test.ts +110 -0
  18. package/backend/host/metrics.ts +235 -0
  19. package/backend/index.ts +5 -2
  20. package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
  21. package/backend/ports/attribute.test.ts +3 -2
  22. package/backend/ports/attribute.ts +5 -44
  23. package/backend/preview/browser/browser-pool.ts +81 -0
  24. package/backend/preview/browser/browser-preview-service.ts +142 -32
  25. package/backend/preview/browser/browser-tab-manager.ts +350 -113
  26. package/backend/preview/browser/types.ts +9 -0
  27. package/backend/project/status-manager.ts +20 -0
  28. package/backend/projects/project-cleanup.integration.test.ts +1 -1
  29. package/backend/projects/project-cleanup.ts +7 -1
  30. package/backend/projects/shell-ownership.ts +65 -0
  31. package/backend/snapshot/snapshot-service.ts +6 -2
  32. package/backend/terminal/ptykit.ts +35 -6
  33. package/backend/utils/ws.ts +21 -1
  34. package/backend/worktrees/clone.ts +222 -0
  35. package/backend/worktrees/index.ts +29 -0
  36. package/backend/worktrees/merge.test.ts +93 -0
  37. package/backend/worktrees/merge.ts +232 -0
  38. package/backend/worktrees/paths.test.ts +60 -0
  39. package/backend/worktrees/paths.ts +60 -0
  40. package/backend/worktrees/resolve.ts +67 -0
  41. package/backend/worktrees/service.ts +315 -0
  42. package/backend/worktrees/tree.ts +59 -0
  43. package/backend/ws/access.ts +18 -0
  44. package/backend/ws/artifacts/generate.ts +2 -2
  45. package/backend/ws/chat/stream.ts +9 -2
  46. package/backend/ws/files/panel-state-scope.test.ts +102 -0
  47. package/backend/ws/files/path-access.test.ts +93 -1
  48. package/backend/ws/files/path-access.ts +54 -5
  49. package/backend/ws/files/read.ts +15 -10
  50. package/backend/ws/files/search.ts +7 -7
  51. package/backend/ws/files/state.ts +70 -8
  52. package/backend/ws/files/watch.ts +16 -14
  53. package/backend/ws/git/branch-name.ts +9 -8
  54. package/backend/ws/git/branch.ts +58 -16
  55. package/backend/ws/git/commit-message.ts +16 -13
  56. package/backend/ws/git/commit.ts +17 -17
  57. package/backend/ws/git/conflict.ts +116 -13
  58. package/backend/ws/git/diff-budget.test.ts +125 -0
  59. package/backend/ws/git/diff-budget.ts +220 -0
  60. package/backend/ws/git/diff.ts +9 -9
  61. package/backend/ws/git/ignored.ts +9 -9
  62. package/backend/ws/git/log.ts +28 -3
  63. package/backend/ws/git/remote.ts +118 -44
  64. package/backend/ws/git/staging.ts +16 -16
  65. package/backend/ws/git/status.ts +13 -13
  66. package/backend/ws/index.ts +4 -0
  67. package/backend/ws/preview/access.ts +11 -3
  68. package/backend/ws/projects/index.ts +5 -1
  69. package/backend/ws/projects/info.test.ts +54 -0
  70. package/backend/ws/projects/info.ts +398 -0
  71. package/backend/ws/sessions/crud.ts +21 -6
  72. package/backend/ws/snapshot/restore.ts +11 -14
  73. package/backend/ws/system/device-info.ts +62 -144
  74. package/backend/ws/worktrees/crud.ts +187 -0
  75. package/backend/ws/worktrees/index.ts +33 -0
  76. package/backend/ws/worktrees/transfer.ts +88 -0
  77. package/dist/assets/{index-BRJqss6F.js → index-Bik9TCBi.js} +1 -1
  78. package/dist/assets/{index-B0iIhSO9.js → index-sJmS_CCm.js} +1 -1
  79. package/dist/assets/main-DLqolBI2.css +1 -0
  80. package/dist/assets/main-Df1I3hnw.js +1096 -0
  81. package/dist/index.html +2 -2
  82. package/package.json +1 -1
  83. package/shared/types/database/schema.ts +26 -0
  84. package/shared/types/git.ts +123 -0
  85. package/shared/utils/logger.ts +1 -0
  86. package/shared/utils/workspace-scope.test.ts +80 -0
  87. package/shared/utils/workspace-scope.ts +57 -0
  88. package/shared/utils/ws-client.ts +25 -5
  89. package/shared/utils/ws-server.ts +19 -3
  90. package/dist/assets/main-Buko4D0t.css +0 -1
  91. package/dist/assets/main-C_iGUZyL.js +0 -1078
@@ -42,7 +42,7 @@ import {
42
42
  mapToolName,
43
43
  TOOL_NAME_MAP,
44
44
  } from './message-converter';
45
- import { ensureClient, acquireServer, releaseServer, getClient, getServerUrl, type ServerInstance } from './server';
45
+ import { ensureClient, acquireServer, releaseServer, getDefaultServer, type ServerInstance } from './server';
46
46
  import { syncSkills } from '$backend/skills';
47
47
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
48
48
  import { artifactFilter } from '$backend/profiles';
@@ -887,7 +887,7 @@ export class OpenCodeEngine implements AIEngine {
887
887
  // The pool hold is still held here on purpose — handing the server back
888
888
  // first could let it be reaped out from under this very call.
889
889
  for (const run of targets) {
890
- const client = run.server?.client ?? getClient();
890
+ const client = run.server?.client ?? getDefaultServer()?.client;
891
891
  const { sessionId, projectPath } = run;
892
892
  if (!client || !sessionId) continue;
893
893
  try {
@@ -948,8 +948,8 @@ export class OpenCodeEngine implements AIEngine {
948
948
  * POST /question/{requestID}/reply to send user answers back to the OpenCode server.
949
949
  */
950
950
  private replyToQuestion(run: OpenCodeRun | null, requestId: string, orderedAnswers: string[][]): void {
951
- const serverUrl = run?.server?.url ?? getServerUrl();
952
- if (!serverUrl) {
951
+ const server = run?.server ?? getDefaultServer();
952
+ if (!server) {
953
953
  debug.warn('engine', 'replyToQuestion: Server URL not available');
954
954
  return;
955
955
  }
@@ -959,12 +959,12 @@ export class OpenCodeEngine implements AIEngine {
959
959
  // a shared "current server" would post this reply into the wrong one and
960
960
  // leave the asking session waiting forever.
961
961
  const dirParam = run?.projectPath ? `?directory=${encodeURIComponent(run.projectPath)}` : '';
962
- const url = `${serverUrl}/question/${requestId}/reply${dirParam}`;
962
+ const url = `${server.url}/question/${requestId}/reply${dirParam}`;
963
963
  debug.log('engine', `Replying to question ${requestId}:`, orderedAnswers);
964
964
 
965
965
  fetch(url, {
966
966
  method: 'POST',
967
- headers: { 'Content-Type': 'application/json' },
967
+ headers: { 'Content-Type': 'application/json', ...server.authHeaders },
968
968
  body: JSON.stringify({ answers: orderedAnswers }),
969
969
  }).then(async res => {
970
970
  if (res.ok) {
@@ -986,15 +986,15 @@ export class OpenCodeEngine implements AIEngine {
986
986
  // still-running one when there is exactly one, else the shared client.
987
987
  const running = this.runs.all();
988
988
  const run = running.length === 1 ? running[0] : null;
989
- const serverUrl = run?.server?.url ?? getServerUrl();
990
- if (!serverUrl) {
989
+ const server = run?.server ?? getDefaultServer();
990
+ if (!server) {
991
991
  debug.warn('engine', 'fetchAndReplyToQuestion: Server URL not available');
992
992
  return;
993
993
  }
994
994
 
995
995
  try {
996
996
  const dirParam = run?.projectPath ? `?directory=${encodeURIComponent(run.projectPath)}` : '';
997
- const res = await fetch(`${serverUrl}/question${dirParam}`);
997
+ const res = await fetch(`${server.url}/question${dirParam}`, { headers: server.authHeaders });
998
998
  if (!res.ok) {
999
999
  debug.error('engine', `Failed to list pending questions: ${res.status}`);
1000
1000
  return;
@@ -1029,14 +1029,14 @@ export class OpenCodeEngine implements AIEngine {
1029
1029
  * the v2 permission.reply method.
1030
1030
  */
1031
1031
  private replyPermission(run: OpenCodeRun, permissionId: string, sessionId: string, response: 'once' | 'reject'): void {
1032
- const serverUrl = run.server?.url ?? getServerUrl();
1033
- if (!serverUrl) return;
1032
+ const server = run.server ?? getDefaultServer();
1033
+ if (!server) return;
1034
1034
  const verb = response === 'reject' ? 'rejected' : 'approved';
1035
1035
 
1036
1036
  // Try v2 endpoint first (/permission/{requestID}/reply), fall back to v1
1037
- fetch(`${serverUrl}/permission/${permissionId}/reply`, {
1037
+ fetch(`${server.url}/permission/${permissionId}/reply`, {
1038
1038
  method: 'POST',
1039
- headers: { 'Content-Type': 'application/json' },
1039
+ headers: { 'Content-Type': 'application/json', ...server.authHeaders },
1040
1040
  body: JSON.stringify({ reply: response }),
1041
1041
  }).then(res => {
1042
1042
  if (res.ok) {
@@ -1044,7 +1044,7 @@ export class OpenCodeEngine implements AIEngine {
1044
1044
  return;
1045
1045
  }
1046
1046
  // v2 endpoint not available — try v1
1047
- const client = run.server?.client ?? getClient();
1047
+ const client = run.server?.client ?? getDefaultServer()?.client;
1048
1048
  if (client) {
1049
1049
  client.postSessionIdPermissionsPermissionId({
1050
1050
  path: { id: sessionId, permissionID: permissionId },
@@ -34,6 +34,8 @@ import {
34
34
  acquireServer,
35
35
  pooledScopeKeys,
36
36
  reconcileServerHolders,
37
+ revalidatePool,
38
+ setLiveStreamSource,
37
39
  DEFAULT_SCOPE_KEY,
38
40
  } from './adapters/opencode/server';
39
41
  import { debug } from '$shared/utils/logger';
@@ -51,7 +53,6 @@ let started = false;
51
53
  * talk to a server anyway.
52
54
  */
53
55
  async function warmDefaultScope(): Promise<void> {
54
- if (!pooledScopeKeys().includes(DEFAULT_SCOPE_KEY)) return;
55
56
  try {
56
57
  await acquireServer({});
57
58
  debug.log('engine', 'Open Code default server re-warmed for the new config');
@@ -71,6 +72,10 @@ export function startEngineHotReload(): void {
71
72
  if (started) return;
72
73
  started = true;
73
74
 
75
+ // The pool sweeps itself on a timer; this is where it learns which holds are
76
+ // still backed by a running stream.
77
+ setLiveStreamSource(() => new Set(streamManager.getActiveStreams().map(s => s.streamId)));
78
+
74
79
  onEngineConfigChanged(revision => {
75
80
  // Holder bookkeeping is reconciled against the live stream set first, so
76
81
  // "is anything running" and "is this server still needed" are answered from
@@ -83,16 +88,26 @@ export function startEngineHotReload(): void {
83
88
  // that is mid-answer.
84
89
  retireAllEngines();
85
90
 
86
- if (liveStreams.length > 0) {
87
- debug.log(
88
- 'engine',
89
- `Engine config now at revision ${revision}; ${liveStreams.length} stream(s) in flight — ` +
90
- 'applying it to the next turn and draining the old server behind them'
91
- );
92
- return;
93
- }
91
+ // Read BEFORE revalidating: revalidation is what makes the outgoing default
92
+ // server reapable, so asking afterwards would report the scope as unused
93
+ // and skip the warm-up on exactly the change that needs it.
94
+ const defaultScopeInUse = pooledScopeKeys().includes(DEFAULT_SCOPE_KEY);
94
95
 
95
- void warmDefaultScope();
96
+ // Re-resolve every pooled scope's key, not just the default one. A Profile
97
+ // server is otherwise still its own scope's current key, so it is neither
98
+ // superseded nor idle and goes on serving the config — and the credentials —
99
+ // that were just replaced. Held servers are unaffected: they are pinned.
100
+ void revalidatePool().then(() => {
101
+ if (liveStreams.length > 0) {
102
+ debug.log(
103
+ 'engine',
104
+ `Engine config now at revision ${revision}; ${liveStreams.length} stream(s) in flight — ` +
105
+ 'applying it to the next turn and draining the old server behind them'
106
+ );
107
+ return;
108
+ }
109
+ if (defaultScopeInUse) return warmDefaultScope();
110
+ });
96
111
  });
97
112
 
98
113
  debug.log('engine', 'Engine hot-reload active');
@@ -33,6 +33,7 @@ import { stat, readdir } from 'node:fs/promises';
33
33
  import { join, relative, normalize, sep } from 'node:path';
34
34
  import { ws } from '$backend/utils/ws';
35
35
  import { debug } from '$shared/utils/logger';
36
+ import { isScopeOfProject, scopeProjectId } from '$shared/utils/workspace-scope';
36
37
  import { resolveGitDirs, type GitDirTarget } from '$backend/git/git-dirs';
37
38
  import {
38
39
  beginWatchedDiscovery,
@@ -413,7 +414,7 @@ class FileWatcherManager {
413
414
  'file',
414
415
  `Watch ceiling (${MAX_WATCHED_DIRS} dirs) reached for project ${pw.projectId}; deeper directories will not report changes`
415
416
  );
416
- ws.emit.project(pw.projectId, 'files:watch-error', {
417
+ ws.emit.project(scopeProjectId(pw.projectId), 'files:watch-error', {
417
418
  projectId: pw.projectId,
418
419
  error: `Project is too large to watch entirely (${MAX_WATCHED_DIRS}+ directories). Changes in deeply nested folders may not appear automatically.`
419
420
  });
@@ -484,8 +485,15 @@ class FileWatcherManager {
484
485
  * Recursively attach watchers to every non-ignored directory under `dir`.
485
486
  * Ignored directories (node_modules, .git, build output, …) are never
486
487
  * descended into — that pruning is what keeps the watch count survivable.
488
+ *
489
+ * `announceGitDirs` reports each pruned `.git` to git discovery. Set it when
490
+ * walking a directory that just APPEARED: everything inside it was created
491
+ * before this watcher had a handle on it, so a `git clone` or `git init` into
492
+ * a fresh nested path emits no event we can ever see. Pruning `.git` without
493
+ * announcing it therefore lost the sub-repo for the whole session. The
494
+ * initial walk leaves it off — `syncGitWatchers` already resolves the tree.
487
495
  */
488
- private async watchSubtree(pw: ProjectWatcher, dir: string): Promise<void> {
496
+ private async watchSubtree(pw: ProjectWatcher, dir: string, announceGitDirs = false): Promise<void> {
489
497
  if (pw.closed) return;
490
498
 
491
499
  let entries;
@@ -501,7 +509,12 @@ class FileWatcherManager {
501
509
 
502
510
  const childPath = join(dir, entry.name);
503
511
  const relativePath = relative(pw.projectPath, childPath).replace(/\\/g, '/');
504
- if (this.shouldIgnore(relativePath)) continue;
512
+ if (this.shouldIgnore(relativePath)) {
513
+ if (announceGitDirs && entry.name === '.git') {
514
+ this.routeGitEvent(pw, relativePath, childPath);
515
+ }
516
+ continue;
517
+ }
505
518
 
506
519
  if (!this.watchDir(pw, childPath)) {
507
520
  // Ceiling reached — stop descending entirely rather than watching an
@@ -509,7 +522,7 @@ class FileWatcherManager {
509
522
  if (pw.truncated) return;
510
523
  continue;
511
524
  }
512
- await this.watchSubtree(pw, childPath);
525
+ await this.watchSubtree(pw, childPath, announceGitDirs);
513
526
  }
514
527
  }
515
528
 
@@ -579,6 +592,17 @@ class FileWatcherManager {
579
592
  this.stopWatching(projectId);
580
593
  }
581
594
 
595
+ /**
596
+ * Release every workspace of a project — the main tree and each worktree.
597
+ * Watchers are keyed per workspace, so releasing the project id alone would
598
+ * leave a deleted project's worktree watchers running.
599
+ */
600
+ releaseProjectScopes(projectId: string): void {
601
+ for (const key of [...this.watchers.keys(), ...this.viewers.keys()]) {
602
+ if (isScopeOfProject(key, projectId)) this.releaseProject(key);
603
+ }
604
+ }
605
+
582
606
  /**
583
607
  * Check if a project is being watched
584
608
  */
@@ -653,7 +677,9 @@ class FileWatcherManager {
653
677
  if (!USE_NATIVE_RECURSIVE_WATCH) {
654
678
  if (isDirectory && changeType === 'created') {
655
679
  if (this.watchDir(projectWatcher, fullPath)) {
656
- void this.watchSubtree(projectWatcher, fullPath);
680
+ // Announce pruned git dirs: this subtree existed before we could
681
+ // watch it, so anything already inside it emitted no event.
682
+ void this.watchSubtree(projectWatcher, fullPath, true);
657
683
  }
658
684
  } else if (changeType === 'deleted' && projectWatcher.dirWatchers.has(fullPath)) {
659
685
  this.unwatchDir(projectWatcher, fullPath);
@@ -719,7 +745,7 @@ class FileWatcherManager {
719
745
  projectWatcher.debounceTimer = null;
720
746
 
721
747
  // Emit changes to users currently viewing the project
722
- ws.emit.project(projectId, 'files:changed', {
748
+ ws.emit.project(scopeProjectId(projectId), 'files:changed', {
723
749
  projectId,
724
750
  changes,
725
751
  timestamp: Date.now()
@@ -934,7 +960,7 @@ class FileWatcherManager {
934
960
  projectWatcher.gitDebounceTimer = null;
935
961
  const repoPaths = Array.from(projectWatcher.pendingGitRepos);
936
962
  projectWatcher.pendingGitRepos.clear();
937
- ws.emit.project(projectId, 'git:changed', {
963
+ ws.emit.project(scopeProjectId(projectId), 'git:changed', {
938
964
  projectId,
939
965
  repoPaths,
940
966
  timestamp: Date.now()
@@ -971,7 +997,7 @@ class FileWatcherManager {
971
997
  'file',
972
998
  `Watcher for project ${projectId} faulted ${attempt} times; giving up on automatic restart`
973
999
  );
974
- ws.emit.project(projectId, 'files:watch-error', {
1000
+ ws.emit.project(scopeProjectId(projectId), 'files:watch-error', {
975
1001
  projectId,
976
1002
  error: 'File watching stopped after repeated failures. Refresh to retry.'
977
1003
  });
@@ -1003,7 +1029,7 @@ class FileWatcherManager {
1003
1029
  // reconcile — deliberately NOT via `files:changed`, which means "these
1004
1030
  // specific paths changed" and made consumers tear down and rebuild live
1005
1031
  // views (the open diff editor) on every restart.
1006
- ws.emit.project(projectId, 'files:resync', {
1032
+ ws.emit.project(scopeProjectId(projectId), 'files:resync', {
1007
1033
  projectId,
1008
1034
  timestamp: Date.now()
1009
1035
  });
@@ -0,0 +1,396 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
2
+ import { mkdtemp, rm, writeFile, readFile, unlink } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { execGit } from './git-executor';
6
+ import { gitService } from './git-service';
7
+ import { parseConflictMarkers, parseReflog, parseUnmergedStages } from './git-parser';
8
+
9
+ /**
10
+ * Covers the conflict states the panel used to mishandle: paths with no working
11
+ * -tree file (which were silently dropped), binary conflicts (decoded as UTF-8),
12
+ * and in-progress operations that had no "continue" at all.
13
+ */
14
+
15
+ let repo: string;
16
+
17
+ async function git(...args: string[]) {
18
+ return execGit(args, repo);
19
+ }
20
+
21
+ async function gitOk(...args: string[]) {
22
+ const result = await git(...args);
23
+ if (result.exitCode !== 0) throw new Error(`git ${args.join(' ')}: ${result.stderr}`);
24
+ return result.stdout;
25
+ }
26
+
27
+ async function commitAll(message: string) {
28
+ await gitOk('add', '-A');
29
+ await gitOk('commit', '-m', message);
30
+ }
31
+
32
+ beforeEach(async () => {
33
+ repo = await mkdtemp(path.join(tmpdir(), 'clopen-conflict-'));
34
+ await gitOk('init', '-b', 'main', '.');
35
+ await gitOk('config', 'user.email', 'test@example.com');
36
+ await gitOk('config', 'user.name', 'Test');
37
+ await gitOk('config', 'commit.gpgsign', 'false');
38
+ await writeFile(path.join(repo, 'base.txt'), 'base\n');
39
+ await commitAll('init');
40
+ });
41
+
42
+ afterEach(async () => {
43
+ await rm(repo, { recursive: true, force: true });
44
+ });
45
+
46
+ /** Create a both-modified conflict on `file.txt` by merging `feature` into main. */
47
+ async function makeBothModifiedConflict() {
48
+ await writeFile(path.join(repo, 'file.txt'), 'one\ntwo\nthree\n');
49
+ await commitAll('add file');
50
+
51
+ await gitOk('checkout', '-b', 'feature');
52
+ await writeFile(path.join(repo, 'file.txt'), 'one\nfeature\nthree\n');
53
+ await commitAll('feature edit');
54
+
55
+ await gitOk('checkout', 'main');
56
+ await writeFile(path.join(repo, 'file.txt'), 'one\nmain\nthree\n');
57
+ await commitAll('main edit');
58
+
59
+ // Expected to fail with a conflict.
60
+ await git('merge', 'feature');
61
+ }
62
+
63
+ describe('parseConflictMarkers', () => {
64
+ test('parses a plain conflict', () => {
65
+ const markers = parseConflictMarkers(
66
+ ['a', '<<<<<<< HEAD', 'ours', '=======', 'theirs', '>>>>>>> feature', 'b'].join('\n')
67
+ );
68
+ expect(markers).toHaveLength(1);
69
+ expect(markers[0].ourContent).toBe('ours');
70
+ expect(markers[0].theirContent).toBe('theirs');
71
+ expect(markers[0].ourStart).toBe(1);
72
+ });
73
+
74
+ test('captures the merge base from diff3-style markers', () => {
75
+ const markers = parseConflictMarkers(
76
+ [
77
+ '<<<<<<< HEAD',
78
+ 'ours',
79
+ '||||||| base',
80
+ 'original',
81
+ '=======',
82
+ 'theirs',
83
+ '>>>>>>> feature'
84
+ ].join('\n')
85
+ );
86
+ expect(markers[0].baseContent).toBe('original');
87
+ expect(markers[0].ourContent).toBe('ours');
88
+ });
89
+
90
+ test('ignores dividers that merely start with the same character', () => {
91
+ // Eight arrows is an ASCII divider, not a marker. The old `startsWith`
92
+ // check treated it as one and reported a phantom conflict.
93
+ const markers = parseConflictMarkers(
94
+ ['<<<<<<<<<<<<<<<<', 'text', '================', 'more', '>>>>>>>>>>>>>>>>'].join('\n')
95
+ );
96
+ expect(markers).toHaveLength(0);
97
+ });
98
+
99
+ test('ignores an opener with no separator', () => {
100
+ expect(parseConflictMarkers(['<<<<<<< HEAD', 'orphan', 'text'].join('\n'))).toHaveLength(0);
101
+ });
102
+
103
+ test('recovers when a second opener appears before the first closes', () => {
104
+ const markers = parseConflictMarkers(
105
+ [
106
+ '<<<<<<< stray',
107
+ 'noise',
108
+ '<<<<<<< HEAD',
109
+ 'ours',
110
+ '=======',
111
+ 'theirs',
112
+ '>>>>>>> feature'
113
+ ].join('\n')
114
+ );
115
+ expect(markers).toHaveLength(1);
116
+ expect(markers[0].ourContent).toBe('ours');
117
+ });
118
+ });
119
+
120
+ describe('parseUnmergedStages', () => {
121
+ test('groups stages per path', () => {
122
+ // `\x00`, not `\0`: in a JS string `\0` followed by a digit is a legacy
123
+ // octal escape, so `\0100644` would be one character, not NUL + "100644".
124
+ const output = [
125
+ '100644 aaa 1\tsrc/a.ts',
126
+ '100644 bbb 2\tsrc/a.ts',
127
+ '100644 ccc 3\tsrc/a.ts',
128
+ '100644 ddd 3\tsrc/b.ts',
129
+ ''
130
+ ].join('\x00');
131
+ const stages = parseUnmergedStages(output);
132
+ expect([...(stages.get('src/a.ts') ?? [])].sort()).toEqual([1, 2, 3]);
133
+ expect([...(stages.get('src/b.ts') ?? [])]).toEqual([3]);
134
+ });
135
+ });
136
+
137
+ describe('parseReflog', () => {
138
+ test('splits the action from the subject', () => {
139
+ const entries = parseReflog(
140
+ 'abc123|||abc123|||HEAD@{0}|||rebase (finish): returning to refs/heads/main|||2026-01-01T00:00:00Z'
141
+ );
142
+ expect(entries[0].action).toBe('rebase (finish)');
143
+ expect(entries[0].subject).toBe('returning to refs/heads/main');
144
+ expect(entries[0].selector).toBe('HEAD@{0}');
145
+ });
146
+
147
+ test('tolerates a subject with no action prefix', () => {
148
+ const entries = parseReflog('abc|||abc|||HEAD@{1}|||something|||2026-01-01T00:00:00Z');
149
+ expect(entries[0].action).toBe('something');
150
+ expect(entries[0].subject).toBe('');
151
+ });
152
+ });
153
+
154
+ describe('getConflictFiles', () => {
155
+ test('reports a both-modified conflict with markers', async () => {
156
+ await makeBothModifiedConflict();
157
+
158
+ const conflicts = await gitService.getConflictFiles(repo);
159
+ expect(conflicts).toHaveLength(1);
160
+ expect(conflicts[0].path).toBe('file.txt');
161
+ expect(conflicts[0].kind).toBe('both-modified');
162
+ expect(conflicts[0].contentOmitted).toBe(false);
163
+ expect(conflicts[0].markers).toHaveLength(1);
164
+ });
165
+
166
+ test('keeps a delete/modify conflict instead of dropping it', async () => {
167
+ await writeFile(path.join(repo, 'gone.txt'), 'content\n');
168
+ await commitAll('add gone');
169
+
170
+ await gitOk('checkout', '-b', 'feature');
171
+ await writeFile(path.join(repo, 'gone.txt'), 'changed\n');
172
+ await commitAll('modify');
173
+
174
+ await gitOk('checkout', 'main');
175
+ await unlink(path.join(repo, 'gone.txt'));
176
+ await commitAll('delete');
177
+
178
+ await git('merge', 'feature');
179
+
180
+ const conflicts = await gitService.getConflictFiles(repo);
181
+ expect(conflicts.map(c => c.path)).toContain('gone.txt');
182
+ // Deleted on our side, modified on theirs — no markers to walk.
183
+ expect(conflicts[0].kind).toBe('deleted-by-us');
184
+ expect(conflicts[0].markers).toHaveLength(0);
185
+ });
186
+
187
+ test('flags a binary conflict rather than decoding it as text', async () => {
188
+ const binary = (a: number) => Buffer.from([0x00, 0x01, a, 0xff, 0x00]);
189
+ await writeFile(path.join(repo, 'blob.bin'), binary(0x10));
190
+ await commitAll('add blob');
191
+
192
+ await gitOk('checkout', '-b', 'feature');
193
+ await writeFile(path.join(repo, 'blob.bin'), binary(0x20));
194
+ await commitAll('feature blob');
195
+
196
+ await gitOk('checkout', 'main');
197
+ await writeFile(path.join(repo, 'blob.bin'), binary(0x30));
198
+ await commitAll('main blob');
199
+
200
+ await git('merge', 'feature');
201
+
202
+ const conflicts = await gitService.getConflictFiles(repo);
203
+ const blob = conflicts.find(c => c.path === 'blob.bin');
204
+ expect(blob).toBeDefined();
205
+ expect(blob?.contentOmitted).toBe(true);
206
+ expect(blob?.omitReason).toBe('binary');
207
+ expect(blob?.content).toBe('');
208
+ });
209
+ });
210
+
211
+ describe('resolveConflict', () => {
212
+ test('refuses to stage content that still has markers', async () => {
213
+ await makeBothModifiedConflict();
214
+ const withMarkers = await readFile(path.join(repo, 'file.txt'), 'utf-8');
215
+
216
+ await expect(
217
+ gitService.resolveConflict(repo, 'file.txt', 'custom', withMarkers)
218
+ ).rejects.toThrow(/conflict markers/i);
219
+
220
+ // Still unmerged — the guard must not half-apply.
221
+ expect(await gitService.getUnmergedPaths(repo)).toEqual(['file.txt']);
222
+ });
223
+
224
+ test('"ours" takes our side and stages it', async () => {
225
+ await makeBothModifiedConflict();
226
+ await gitService.resolveConflict(repo, 'file.txt', 'ours');
227
+
228
+ expect(await readFile(path.join(repo, 'file.txt'), 'utf-8')).toBe('one\nmain\nthree\n');
229
+ expect(await gitService.getUnmergedPaths(repo)).toEqual([]);
230
+ });
231
+
232
+ test('"ours" resolves as a deletion when our side deleted the path', async () => {
233
+ await writeFile(path.join(repo, 'gone.txt'), 'content\n');
234
+ await commitAll('add gone');
235
+ await gitOk('checkout', '-b', 'feature');
236
+ await writeFile(path.join(repo, 'gone.txt'), 'changed\n');
237
+ await commitAll('modify');
238
+ await gitOk('checkout', 'main');
239
+ await unlink(path.join(repo, 'gone.txt'));
240
+ await commitAll('delete');
241
+ await git('merge', 'feature');
242
+
243
+ // `git checkout --ours` cannot work here; the answer git wants is `rm`.
244
+ await gitService.resolveConflict(repo, 'gone.txt', 'ours');
245
+ expect(await gitService.getUnmergedPaths(repo)).toEqual([]);
246
+ });
247
+
248
+ test('"reset" puts the markers back', async () => {
249
+ await makeBothModifiedConflict();
250
+ await writeFile(path.join(repo, 'file.txt'), 'one\nresolved\nthree\n');
251
+ await gitService.resolveConflict(repo, 'file.txt', 'reset');
252
+
253
+ const restored = await readFile(path.join(repo, 'file.txt'), 'utf-8');
254
+ expect(restored).toContain('<<<<<<<');
255
+ expect(await gitService.getUnmergedPaths(repo)).toEqual(['file.txt']);
256
+ });
257
+ });
258
+
259
+ describe('stageAll', () => {
260
+ test('refuses while a conflicted file still has markers', async () => {
261
+ await makeBothModifiedConflict();
262
+ await expect(gitService.stageAll(repo)).rejects.toThrow(/conflict markers/i);
263
+ });
264
+
265
+ test('proceeds once the markers are gone', async () => {
266
+ await makeBothModifiedConflict();
267
+ await writeFile(path.join(repo, 'file.txt'), 'one\nresolved\nthree\n');
268
+ await gitService.stageAll(repo);
269
+ expect(await gitService.getUnmergedPaths(repo)).toEqual([]);
270
+ });
271
+ });
272
+
273
+ describe('getOperationState', () => {
274
+ test('is idle in a clean repo', async () => {
275
+ const state = await gitService.getOperationState(repo);
276
+ expect(state.operation).toBeNull();
277
+ expect(state.canContinue).toBe(false);
278
+ expect(state.unmergedCount).toBe(0);
279
+ });
280
+
281
+ test('describes a merge and names both sides', async () => {
282
+ await makeBothModifiedConflict();
283
+
284
+ const state = await gitService.getOperationState(repo);
285
+ expect(state.operation).toBe('merge');
286
+ expect(state.oursLabel).toBe('main');
287
+ expect(state.theirsLabel).toBe('feature');
288
+ expect(state.unmergedCount).toBe(1);
289
+ // Blocked until the conflict is staged.
290
+ expect(state.canContinue).toBe(false);
291
+ });
292
+
293
+ test('allows continue once every path is resolved', async () => {
294
+ await makeBothModifiedConflict();
295
+ await gitService.resolveConflict(repo, 'file.txt', 'ours');
296
+
297
+ const state = await gitService.getOperationState(repo);
298
+ expect(state.canContinue).toBe(true);
299
+ });
300
+
301
+ test('reports rebase progress with the sides inverted', async () => {
302
+ await writeFile(path.join(repo, 'file.txt'), 'one\ntwo\n');
303
+ await commitAll('add file');
304
+
305
+ await gitOk('checkout', '-b', 'feature');
306
+ await writeFile(path.join(repo, 'file.txt'), 'one\nfeature\n');
307
+ await commitAll('feature edit');
308
+
309
+ await gitOk('checkout', 'main');
310
+ await writeFile(path.join(repo, 'file.txt'), 'one\nmain\n');
311
+ await commitAll('main edit');
312
+
313
+ await gitOk('checkout', 'feature');
314
+ await git('rebase', 'main');
315
+
316
+ const state = await gitService.getOperationState(repo);
317
+ expect(state.operation).toBe('rebase');
318
+ // During a rebase "ours" is the branch being rebased ONTO.
319
+ expect(state.oursLabel).toBe('main');
320
+ expect(state.theirsLabel).toContain('feature');
321
+ expect(state.canSkip).toBe(true);
322
+ expect(state.total).toBe(1);
323
+ });
324
+
325
+ test('flags unmerged paths with no sentinel as a stash conflict', async () => {
326
+ await writeFile(path.join(repo, 'file.txt'), 'one\n');
327
+ await commitAll('add file');
328
+
329
+ await writeFile(path.join(repo, 'file.txt'), 'stashed\n');
330
+ await gitOk('stash', 'push', '-m', 'wip');
331
+ await writeFile(path.join(repo, 'file.txt'), 'other\n');
332
+ await commitAll('conflicting edit');
333
+ await git('stash', 'pop');
334
+
335
+ const state = await gitService.getOperationState(repo);
336
+ expect(state.operation).toBeNull();
337
+ expect(state.stashConflict).toBe(true);
338
+ expect(state.unmergedCount).toBeGreaterThan(0);
339
+ });
340
+ });
341
+
342
+ describe('continueOperation', () => {
343
+ test('refuses while paths are still unmerged', async () => {
344
+ await makeBothModifiedConflict();
345
+ await expect(gitService.continueOperation(repo)).rejects.toThrow(/still unmerged/i);
346
+ });
347
+
348
+ test('finishes a merge once the conflict is staged', async () => {
349
+ await makeBothModifiedConflict();
350
+ await gitService.resolveConflict(repo, 'file.txt', 'ours');
351
+
352
+ const result = await gitService.continueOperation(repo);
353
+ expect(result.success).toBe(true);
354
+
355
+ const state = await gitService.getOperationState(repo);
356
+ expect(state.operation).toBeNull();
357
+ });
358
+
359
+ test('finishes a rebase, leaving the branch on top of the upstream', async () => {
360
+ await writeFile(path.join(repo, 'file.txt'), 'one\ntwo\n');
361
+ await commitAll('add file');
362
+ await gitOk('checkout', '-b', 'feature');
363
+ await writeFile(path.join(repo, 'file.txt'), 'one\nfeature\n');
364
+ await commitAll('feature edit');
365
+ await gitOk('checkout', 'main');
366
+ await writeFile(path.join(repo, 'file.txt'), 'one\nmain\n');
367
+ await commitAll('main edit');
368
+ await gitOk('checkout', 'feature');
369
+ await git('rebase', 'main');
370
+
371
+ await gitService.resolveConflict(repo, 'file.txt', 'theirs');
372
+ const result = await gitService.continueOperation(repo);
373
+ expect(result.success).toBe(true);
374
+
375
+ const state = await gitService.getOperationState(repo);
376
+ expect(state.operation).toBeNull();
377
+ const branch = (await gitOk('branch', '--show-current')).trim();
378
+ expect(branch).toBe('feature');
379
+ });
380
+
381
+ test('reports there is nothing to continue', async () => {
382
+ await expect(gitService.continueOperation(repo)).rejects.toThrow(/no operation/i);
383
+ });
384
+ });
385
+
386
+ describe('getReflog', () => {
387
+ test('lists recent HEAD movements', async () => {
388
+ await writeFile(path.join(repo, 'a.txt'), 'a\n');
389
+ await commitAll('second');
390
+
391
+ const entries = await gitService.getReflog(repo, 10);
392
+ expect(entries.length).toBeGreaterThan(0);
393
+ expect(entries[0].selector).toBe('HEAD@{0}');
394
+ expect(entries[0].action).toContain('commit');
395
+ });
396
+ });
@@ -62,6 +62,12 @@ export async function execGit(
62
62
  // actually changing. Commands that genuinely need the index lock (commit,
63
63
  // add, checkout) still take it; only the optional refresh is suppressed.
64
64
  GIT_OPTIONAL_LOCKS: '0',
65
+ // `rebase --continue`, `merge --continue` and friends open $EDITOR for the
66
+ // commit message. With no TTY that call blocks until our timeout kills it,
67
+ // so point both editors at `true`: it exits 0 immediately and git keeps
68
+ // the message git already prepared.
69
+ GIT_EDITOR: 'true',
70
+ GIT_SEQUENCE_EDITOR: 'true',
65
71
  // Use English output for consistent parsing
66
72
  LANG: 'en_US.UTF-8',
67
73
  LC_ALL: 'en_US.UTF-8'