@myrialabs/clopen 0.4.36 → 0.4.38

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 (115) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +14 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/database/crypto/envelope.test.ts +93 -0
  5. package/backend/database/crypto/envelope.ts +127 -0
  6. package/backend/database/crypto/index.ts +22 -0
  7. package/backend/database/crypto/master-key.ts +129 -0
  8. package/backend/database/crypto/secret-columns.ts +147 -0
  9. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  10. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  11. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  12. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  13. package/backend/database/migrations/index.ts +28 -0
  14. package/backend/database/queries/db-client-connection-queries.ts +23 -12
  15. package/backend/database/queries/engine-queries.ts +23 -10
  16. package/backend/database/queries/index.ts +6 -1
  17. package/backend/database/queries/integration-queries.ts +297 -0
  18. package/backend/database/queries/mcp-server-queries.ts +38 -11
  19. package/backend/database/queries/note-queries.test.ts +190 -0
  20. package/backend/database/queries/note-queries.ts +269 -0
  21. package/backend/database/queries/profile-queries.ts +1 -1
  22. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  23. package/backend/database/queries/work-queries.ts +210 -0
  24. package/backend/engine/docs/artifacts.md +22 -9
  25. package/backend/files/os-clipboard.test.ts +209 -0
  26. package/backend/files/os-clipboard.ts +567 -0
  27. package/backend/git/conflict-state.test.ts +396 -0
  28. package/backend/git/git-executor.ts +6 -0
  29. package/backend/git/git-parser.ts +144 -48
  30. package/backend/git/git-service.ts +727 -57
  31. package/backend/git/push-target.test.ts +264 -0
  32. package/backend/http/integration-hooks.ts +42 -0
  33. package/backend/http/notes-images.test.ts +228 -0
  34. package/backend/http/notes-images.ts +196 -0
  35. package/backend/index.ts +9 -0
  36. package/backend/integrations/accounts.ts +229 -0
  37. package/backend/integrations/health.ts +146 -0
  38. package/backend/integrations/index.ts +36 -0
  39. package/backend/integrations/projections/index.ts +120 -0
  40. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  41. package/backend/integrations/projections/mcp-projector.ts +159 -0
  42. package/backend/integrations/projections/types.ts +51 -0
  43. package/backend/integrations/registry/define.ts +38 -0
  44. package/backend/integrations/registry/index.ts +56 -0
  45. package/backend/integrations/registry/providers/context7.ts +44 -0
  46. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  47. package/backend/integrations/registry/providers/github.ts +78 -0
  48. package/backend/integrations/registry/types.ts +96 -0
  49. package/backend/integrations/webhooks/gateway.ts +160 -0
  50. package/backend/integrations/webhooks/verify.ts +65 -0
  51. package/backend/mcp/README.md +25 -3
  52. package/backend/mcp/external/config.ts +35 -1
  53. package/backend/mcp/index.ts +1 -1
  54. package/backend/mcp/internal/config.ts +1 -1
  55. package/backend/notes/access.test.ts +82 -0
  56. package/backend/notes/access.ts +27 -0
  57. package/backend/notes/storage.test.ts +77 -0
  58. package/backend/notes/storage.ts +114 -0
  59. package/backend/permissions/service.ts +2 -2
  60. package/backend/profiles/service.ts +1 -1
  61. package/backend/project/status-manager.ts +20 -0
  62. package/backend/projects/project-cleanup.ts +6 -0
  63. package/backend/work/bindings.ts +124 -0
  64. package/backend/work/index.ts +42 -0
  65. package/backend/work/prompts.ts +150 -0
  66. package/backend/work/providers/github/actions-logs.ts +180 -0
  67. package/backend/work/providers/github/adapter.test.ts +88 -0
  68. package/backend/work/providers/github/adapter.ts +1255 -0
  69. package/backend/work/providers/github/client.ts +280 -0
  70. package/backend/work/providers/github/list-range.test.ts +158 -0
  71. package/backend/work/providers/github/token-kind.test.ts +42 -0
  72. package/backend/work/pull-requests.ts +242 -0
  73. package/backend/work/registry.ts +27 -0
  74. package/backend/work/service.ts +436 -0
  75. package/backend/work/start-work.test.ts +71 -0
  76. package/backend/work/start-work.ts +232 -0
  77. package/backend/work/types.ts +180 -0
  78. package/backend/ws/files/clipboard.ts +78 -0
  79. package/backend/ws/files/index.ts +5 -0
  80. package/backend/ws/git/branch-name.ts +6 -5
  81. package/backend/ws/git/branch.ts +43 -1
  82. package/backend/ws/git/commit-message.ts +13 -10
  83. package/backend/ws/git/conflict.ts +106 -3
  84. package/backend/ws/git/diff-budget.test.ts +125 -0
  85. package/backend/ws/git/diff-budget.ts +279 -0
  86. package/backend/ws/git/log.ts +25 -0
  87. package/backend/ws/git/remote.ts +75 -1
  88. package/backend/ws/index.ts +11 -1
  89. package/backend/ws/integrations/crud.ts +219 -0
  90. package/backend/ws/integrations/index.ts +22 -0
  91. package/backend/ws/mcp/crud.ts +25 -1
  92. package/backend/ws/notes/index.ts +278 -0
  93. package/backend/ws/profiles/crud.ts +1 -1
  94. package/backend/ws/work/actions.ts +206 -0
  95. package/backend/ws/work/context.ts +51 -0
  96. package/backend/ws/work/crud.ts +347 -0
  97. package/backend/ws/work/index.ts +17 -0
  98. package/backend/ws/work/pull-requests.ts +177 -0
  99. package/backend/ws/work/schemas.ts +226 -0
  100. package/dist/assets/{index-Bg-SUCFg.js → index-CyH7fSbR.js} +1 -1
  101. package/dist/assets/{index-Cz4YpHVi.js → index-DSHIANSy.js} +1 -1
  102. package/dist/assets/main-D2IOjftb.css +1 -0
  103. package/dist/assets/main-DM-tHKbW.js +1152 -0
  104. package/dist/index.html +2 -2
  105. package/package.json +1 -1
  106. package/shared/constants/engine-tools.ts +1 -1
  107. package/shared/constants/tool-icons.ts +33 -0
  108. package/shared/types/database/schema.ts +41 -0
  109. package/shared/types/git.ts +123 -0
  110. package/shared/types/integrations.ts +140 -0
  111. package/shared/types/stores/settings.ts +8 -0
  112. package/shared/types/work.ts +426 -0
  113. package/shared/utils/logger.ts +3 -0
  114. package/dist/assets/main-9G7IpQpK.css +0 -1
  115. package/dist/assets/main-BofFsH8E.js +0 -1085
@@ -14,7 +14,10 @@ import {
14
14
  parseLog,
15
15
  parseRemotes,
16
16
  parseStashList,
17
- parseConflictMarkers
17
+ parseConflictMarkers,
18
+ parseReflog,
19
+ parseUnmergedStages,
20
+ hasConflictMarkers
18
21
  } from './git-parser';
19
22
  import type {
20
23
  GitStatus,
@@ -25,7 +28,12 @@ import type {
25
28
  GitLogResult,
26
29
  GitRemote,
27
30
  GitStashEntry,
28
- GitConflictFile
31
+ GitPushTarget,
32
+ GitConflictFile,
33
+ GitConflictKind,
34
+ GitConflictResolution,
35
+ GitOperationState,
36
+ GitReflogEntry
29
37
  } from '$shared/types/git';
30
38
  import { debug } from '$shared/utils/logger';
31
39
  import {
@@ -119,13 +127,48 @@ export class GitService {
119
127
  }
120
128
  }
121
129
 
130
+ /**
131
+ * Stage everything. Git will happily record a conflicted file that still has
132
+ * `<<<<<<<` in it as resolved, so we check first and refuse — committing the
133
+ * markers is far more expensive to undo than this error is to read.
134
+ */
122
135
  async stageAll(cwd: string): Promise<void> {
136
+ const unresolved = await this.findFilesWithLeftoverMarkers(cwd);
137
+ if (unresolved.length > 0) {
138
+ const shown = unresolved.slice(0, 5).join(', ');
139
+ const rest = unresolved.length > 5 ? ` and ${unresolved.length - 5} more` : '';
140
+ throw new Error(
141
+ `Cannot stage everything: ${shown}${rest} still contain conflict markers. Resolve them first.`
142
+ );
143
+ }
123
144
  const result = await execGit(['add', '-A'], cwd);
124
145
  if (result.exitCode !== 0) {
125
146
  throw new Error(`git add -A failed: ${result.stderr}`);
126
147
  }
127
148
  }
128
149
 
150
+ /** Unmerged paths whose working-tree text still has conflict markers in it. */
151
+ private async findFilesWithLeftoverMarkers(cwd: string): Promise<string[]> {
152
+ const unmerged = await this.getUnmergedPaths(cwd);
153
+ if (unmerged.length === 0) return [];
154
+
155
+ const { readFile } = await import('node:fs/promises');
156
+ const { join } = await import('node:path');
157
+ const offenders: string[] = [];
158
+
159
+ for (const filePath of unmerged) {
160
+ try {
161
+ const buffer = await readFile(join(cwd, filePath));
162
+ if (buffer.subarray(0, 8000).includes(0)) continue;
163
+ if (hasConflictMarkers(buffer.toString('utf-8'))) offenders.push(filePath);
164
+ } catch {
165
+ // Missing file (both-deleted) has no markers to leave behind.
166
+ }
167
+ }
168
+
169
+ return offenders;
170
+ }
171
+
129
172
  async unstageFile(cwd: string, filePath: string): Promise<void> {
130
173
  assertSafeGitPathOperand(filePath, 'unstage path');
131
174
  // Try normal reset first, fall back to rm --cached for initial commit
@@ -169,9 +212,27 @@ export class GitService {
169
212
  }
170
213
  }
171
214
 
215
+ /**
216
+ * Discard every working-tree change.
217
+ *
218
+ * Refused during a conflict: `git checkout -- .` cannot restore an unmerged
219
+ * path, so it would half-succeed — wiping the unrelated edits while leaving
220
+ * the conflict in place — and the old code ignored both exit codes, so that
221
+ * partial result was invisible. Unwinding a merge is `abortOperation`'s job.
222
+ */
172
223
  async discardAll(cwd: string): Promise<void> {
224
+ const unmerged = await this.getUnmergedPaths(cwd);
225
+ if (unmerged.length > 0) {
226
+ throw new Error(
227
+ 'Cannot discard everything while a merge is unresolved. Abort the operation instead, or resolve the conflicts first.'
228
+ );
229
+ }
230
+
173
231
  // Restore tracked files
174
- await execGit(['checkout', '--', '.'], cwd);
232
+ const restore = await execGit(['checkout', '--', '.'], cwd);
233
+ if (restore.exitCode !== 0 && restore.stderr.trim()) {
234
+ throw new Error(`git checkout failed: ${restore.stderr.trim()}`);
235
+ }
175
236
  // Remove untracked files
176
237
  await execGit(['clean', '-fd'], cwd);
177
238
  }
@@ -297,7 +358,10 @@ export class GitService {
297
358
  // where `HEAD` is `*` for the current branch and ` ` for others.
298
359
  // `iso-date` is strict ISO 8601 so it can't collide with the `|`
299
360
  // separators — the parser uses `lastIndexOf('|')` to extract it.
300
- const localFmt = '%(HEAD)|%(refname:short)|%(objectname:short)|%(subject)|%(committerdate:iso8601)';
361
+ // `%1f` emits a literal 0x1F, which separates the upstream from the legacy
362
+ // pipe-delimited fields without colliding with a `|` inside a subject.
363
+ const localFmt =
364
+ '%(HEAD)|%(refname:short)|%(objectname:short)|%(subject)|%(committerdate:iso8601)%1f%(upstream:short)';
301
365
  const remoteFmt = '%(refname:short)|%(objectname:short)|%(subject)|%(committerdate:iso8601)';
302
366
  const [localResult, remoteResult, headRef] = await Promise.all([
303
367
  execGit(['for-each-ref', `--format=${localFmt}`, 'refs/heads/'], cwd),
@@ -334,10 +398,35 @@ export class GitService {
334
398
  branchInfo.current = headName;
335
399
  for (const b of branchInfo.local) b.isCurrent = b.name === headName;
336
400
 
337
- // Get ahead/behind for current branch relative to the SELECTED remote
338
- if (branchInfo.current && selectedRemote) {
401
+ // Fill in upstreams that git cannot name. `gh pr checkout` on a fork PR
402
+ // writes the fork's URL into `branch.<name>.remote`, and a URL has no
403
+ // remote-tracking ref, so `%(upstream:short)` comes back empty even though
404
+ // the branch is very much tracking something.
405
+ for (const localBranch of branchInfo.local) {
406
+ if (localBranch.upstream) continue;
407
+ const configured = await this.readBranchTracking(cwd, localBranch.name);
408
+ if (configured) localBranch.upstream = `${configured.remote}/${configured.remoteBranch}`;
409
+ }
410
+
411
+ // Ahead/behind belongs against the branch's REAL upstream. Measuring it
412
+ // against `<selectedRemote>/<same name>` reported 0/0 whenever the branch
413
+ // tracked a differently-named branch or a different remote — which is
414
+ // exactly the fork-PR case.
415
+ const currentUpstream = branchInfo.local.find(b => b.isCurrent)?.upstream;
416
+ const trackingRef = currentUpstream
417
+ ? // Tracks something. Use it when it resolves locally; when it does not —
418
+ // a URL upstream has no local ref — report nothing rather than compare
419
+ // against an unrelated same-named branch on the selected remote.
420
+ (await this.hasRef(cwd, currentUpstream))
421
+ ? currentUpstream
422
+ : null
423
+ : selectedRemote
424
+ ? `${selectedRemote}/${branchInfo.current}`
425
+ : null;
426
+
427
+ if (branchInfo.current && trackingRef) {
339
428
  try {
340
- const remoteRef = `${selectedRemote}/${branchInfo.current}`;
429
+ const remoteRef = trackingRef;
341
430
  const abResult = await execGit(
342
431
  ['rev-list', '--left-right', '--count', `${branchInfo.current}...${remoteRef}`],
343
432
  cwd
@@ -455,12 +544,27 @@ export class GitService {
455
544
  }
456
545
  }
457
546
 
458
- async mergeBranch(cwd: string, branchName: string, noFastForward = false): Promise<{ success: boolean; message: string }> {
547
+ /**
548
+ * Merge `branchName` into the current branch.
549
+ *
550
+ * The three mode flags are mutually exclusive in git, so the caller picks one:
551
+ * `--no-ff` always records a merge commit, `--squash` collapses the branch into
552
+ * staged changes without committing, `--ff-only` refuses anything that is not a
553
+ * fast-forward.
554
+ */
555
+ async mergeBranch(
556
+ cwd: string,
557
+ branchName: string,
558
+ options: { noFastForward?: boolean; squash?: boolean; ffOnly?: boolean } | boolean = false
559
+ ): Promise<{ success: boolean; message: string }> {
459
560
  assertSafeGitRevish(branchName, 'merge branch');
561
+ const opts = typeof options === 'boolean' ? { noFastForward: options } : options;
460
562
  const args = ['merge'];
461
- if (noFastForward) args.push('--no-ff');
563
+ if (opts.squash) args.push('--squash');
564
+ else if (opts.ffOnly) args.push('--ff-only');
565
+ else if (opts.noFastForward) args.push('--no-ff');
462
566
  args.push(branchName);
463
- const result = await execGit(args, cwd);
567
+ const result = await execGit(args, cwd, 120000);
464
568
  return {
465
569
  success: result.exitCode === 0,
466
570
  message: result.exitCode === 0 ? result.stdout : result.stderr
@@ -533,15 +637,28 @@ export class GitService {
533
637
  return result.stderr || result.stdout; // git fetch outputs to stderr
534
638
  }
535
639
 
640
+ /**
641
+ * Pull the current branch.
642
+ *
643
+ * Mirrors `push`: naming `<selectedRemote> <localName>` explicitly pulled from
644
+ * the wrong place whenever the branch tracked a different remote or a
645
+ * differently-named branch, which is the normal state of a fork PR under
646
+ * review. A tracked branch pulls from its own upstream.
647
+ */
536
648
  async pull(cwd: string, remote = 'origin', branch?: string, rebase = false): Promise<{ success: boolean; message: string }> {
537
- assertSafeGitRemoteName(remote);
538
649
  const args = ['pull'];
539
650
  if (rebase) args.push('--rebase');
540
- args.push(remote);
541
- if (branch) {
542
- assertSafeGitRevish(branch, 'pull branch');
543
- args.push(branch);
651
+
652
+ const target = await this.getPushTarget(cwd, branch);
653
+ if (!target.hasUpstream) {
654
+ assertSafeGitRemoteName(remote);
655
+ args.push(remote);
656
+ if (branch) {
657
+ assertSafeGitRevish(branch, 'pull branch');
658
+ args.push(branch);
659
+ }
544
660
  }
661
+
545
662
  const result = await execGit(args, cwd, 60000);
546
663
  return {
547
664
  success: result.exitCode === 0,
@@ -564,10 +681,130 @@ export class GitService {
564
681
  if (!(await this.hasCommits(cwd))) {
565
682
  return { success: false, message: 'This branch has no commits yet, so there is nothing to push.' };
566
683
  }
684
+ // `--force-with-lease` compares against the remote-tracking ref. A branch
685
+ // that tracks a bare URL — a fork PR checked out for review — has no such
686
+ // ref, so git refuses with a bare "stale info" that explains nothing.
687
+ if (/stale info/i.test(result.stderr)) {
688
+ return {
689
+ success: false,
690
+ message:
691
+ 'Force push with lease needs a remote-tracking ref to compare against, and this branch does not have one (it tracks a URL rather than a named remote). Fetch the branch first, or use a plain force push.'
692
+ };
693
+ }
567
694
  return { success: false, message: result.stderr };
568
695
  }
569
696
 
570
- async push(cwd: string, remote = 'origin', branch?: string, force = false): Promise<{ success: boolean; message: string }> {
697
+ /** Read a single git config value, or null when it is unset. */
698
+ private async readConfig(cwd: string, key: string): Promise<string | null> {
699
+ const result = await execGit(['config', '--get', key], cwd, { okExitCodes: [1] });
700
+ const value = result.stdout.trim();
701
+ return result.exitCode === 0 && value ? value : null;
702
+ }
703
+
704
+ /** True when `ref` resolves in this repo. */
705
+ private async hasRef(cwd: string, ref: string): Promise<boolean> {
706
+ if (!/^[^\0\n\r]+$/.test(ref) || ref.startsWith('-')) return false;
707
+ const result = await execGit(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], cwd, {
708
+ okExitCodes: [1]
709
+ });
710
+ return result.exitCode === 0;
711
+ }
712
+
713
+ /**
714
+ * The tracking configuration recorded for a branch, straight from git config.
715
+ *
716
+ * Read from config rather than from `@{upstream}` on purpose: when
717
+ * `branch.<name>.remote` holds a URL instead of a remote name — which is what
718
+ * `gh pr checkout` writes for a fork PR — every ref-based lookup fails with
719
+ * "not stored as a remote-tracking branch", even though the branch does track
720
+ * something and a plain `git push` sends it to exactly the right place.
721
+ */
722
+ private async readBranchTracking(
723
+ cwd: string,
724
+ branch: string
725
+ ): Promise<{ remote: string; remoteBranch: string } | null> {
726
+ assertSafeGitRevish(branch, 'branch name');
727
+ const remote = await this.readConfig(cwd, `branch.${branch}.remote`);
728
+ const merge = await this.readConfig(cwd, `branch.${branch}.merge`);
729
+ if (!remote || !merge) return null;
730
+ return { remote, remoteBranch: merge.replace(/^refs\/heads\//, '') };
731
+ }
732
+
733
+ /** A remote name is a configured remote; anything else we treat as a URL. */
734
+ private async isConfiguredRemote(cwd: string, name: string): Promise<boolean> {
735
+ const result = await execGit(['remote'], cwd);
736
+ return result.stdout.split('\n').map(r => r.trim()).includes(name);
737
+ }
738
+
739
+ /**
740
+ * Resolve where a push would actually land, following git's own precedence:
741
+ * `branch.<name>.pushRemote` > `remote.pushDefault` > `branch.<name>.remote`.
742
+ *
743
+ * Used for display and to decide whether a push needs `-u`; the push itself
744
+ * still delegates to git so nothing here can drift from what git does.
745
+ */
746
+ async getPushTarget(cwd: string, branch?: string): Promise<GitPushTarget> {
747
+ const current = branch ?? (await execGit(['branch', '--show-current'], cwd)).stdout.trim();
748
+ const fallback: GitPushTarget = {
749
+ remote: 'origin',
750
+ remoteBranch: current,
751
+ hasUpstream: false,
752
+ isUrl: false,
753
+ branch: current
754
+ };
755
+ if (!current) return fallback;
756
+
757
+ const tracking = await this.readBranchTracking(cwd, current);
758
+ const pushRemote =
759
+ (await this.readConfig(cwd, `branch.${current}.pushRemote`)) ??
760
+ (await this.readConfig(cwd, 'remote.pushDefault')) ??
761
+ tracking?.remote ??
762
+ null;
763
+
764
+ if (!pushRemote) return fallback;
765
+
766
+ return {
767
+ remote: pushRemote,
768
+ // When pushing to a different remote than the branch fetches from, git's
769
+ // default `push.default=simple` uses the local name; otherwise it uses
770
+ // the configured merge ref.
771
+ remoteBranch:
772
+ tracking && pushRemote === tracking.remote ? tracking.remoteBranch : current,
773
+ hasUpstream: Boolean(tracking),
774
+ isUrl: !(await this.isConfiguredRemote(cwd, pushRemote)),
775
+ branch: current
776
+ };
777
+ }
778
+
779
+ /**
780
+ * Push the current branch.
781
+ *
782
+ * When the branch already tracks something we run a bare `git push` and let
783
+ * git resolve the destination. Naming a remote and a branch explicitly — which
784
+ * this used to do unconditionally, with `-u` — sent a fork PR's review commits
785
+ * into the main repository as a brand-new branch, and the `-u` then rewrote
786
+ * the branch's remote so every subsequent push went there too.
787
+ *
788
+ * `remote`/`branch` are only used for the genuinely untracked case (the first
789
+ * push of a new local branch), where a destination has to be chosen and `-u`
790
+ * is what the user wants.
791
+ */
792
+ async push(
793
+ cwd: string,
794
+ remote = 'origin',
795
+ branch?: string,
796
+ force = false,
797
+ options: { useUpstream?: boolean } = {}
798
+ ): Promise<{ success: boolean; message: string }> {
799
+ const { useUpstream = true } = options;
800
+ const target = await this.getPushTarget(cwd, branch);
801
+
802
+ if (useUpstream && target.hasUpstream) {
803
+ const args = ['push'];
804
+ if (force) args.push('--force-with-lease');
805
+ return this.describePushResult(cwd, await execGit(args, cwd, 60000));
806
+ }
807
+
571
808
  assertSafeGitRemoteName(remote);
572
809
  const args = ['push', remote];
573
810
  if (branch) {
@@ -575,11 +812,40 @@ export class GitService {
575
812
  args.push(branch);
576
813
  }
577
814
  if (force) args.push('--force-with-lease');
578
- // Set upstream if needed
815
+ // Only safe here: the branch tracks nothing, so there is no upstream to
816
+ // overwrite and recording one is the point of a first push.
579
817
  args.push('-u');
580
818
  return this.describePushResult(cwd, await execGit(args, cwd, 60000));
581
819
  }
582
820
 
821
+ /** Point a branch at a different upstream — the way back from a wrong push. */
822
+ async setUpstream(
823
+ cwd: string,
824
+ branch: string,
825
+ remote: string,
826
+ remoteBranch?: string
827
+ ): Promise<void> {
828
+ assertSafeGitRevish(branch, 'branch name');
829
+ assertSafeGitRemoteName(remote);
830
+ const target = remoteBranch ?? branch;
831
+ assertSafeGitRevish(target, 'upstream branch');
832
+ const result = await execGit(
833
+ ['branch', `--set-upstream-to=${remote}/${target}`, branch],
834
+ cwd
835
+ );
836
+ if (result.exitCode !== 0) {
837
+ throw new Error(`Could not set upstream: ${result.stderr.trim() || 'unknown error'}`);
838
+ }
839
+ }
840
+
841
+ async unsetUpstream(cwd: string, branch: string): Promise<void> {
842
+ assertSafeGitRevish(branch, 'branch name');
843
+ const result = await execGit(['branch', '--unset-upstream', branch], cwd);
844
+ if (result.exitCode !== 0) {
845
+ throw new Error(`Could not clear upstream: ${result.stderr.trim() || 'unknown error'}`);
846
+ }
847
+ }
848
+
583
849
  /**
584
850
  * Advanced push variants surfaced in the "More" menu:
585
851
  * - `with-tags` → push branch + reachable annotated tags (--follow-tags)
@@ -593,20 +859,36 @@ export class GitService {
593
859
  remote = 'origin',
594
860
  branch?: string
595
861
  ): Promise<{ success: boolean; message: string }> {
862
+ // `--tags` is about the tag namespace, not this branch, so it always needs
863
+ // an explicit remote.
864
+ if (mode === 'all-tags') {
865
+ assertSafeGitRemoteName(remote);
866
+ return this.describePushResult(
867
+ cwd,
868
+ await execGit(['push', remote, '--tags'], cwd, 60000)
869
+ );
870
+ }
871
+
872
+ const flag =
873
+ mode === 'with-tags'
874
+ ? '--follow-tags'
875
+ : mode === 'force-lease'
876
+ ? '--force-with-lease'
877
+ : '--force';
878
+
879
+ // Same rule as `push`: a tracked branch goes where git says it goes.
880
+ const target = await this.getPushTarget(cwd, branch);
881
+ if (target.hasUpstream) {
882
+ return this.describePushResult(cwd, await execGit(['push', flag], cwd, 60000));
883
+ }
884
+
596
885
  assertSafeGitRemoteName(remote);
597
886
  const args = ['push', remote];
598
- if (mode === 'all-tags') {
599
- args.push('--tags');
600
- } else {
601
- if (branch) {
602
- assertSafeGitRevish(branch, 'push branch');
603
- args.push(branch);
604
- }
605
- if (mode === 'with-tags') args.push('--follow-tags');
606
- else if (mode === 'force-lease') args.push('--force-with-lease');
607
- else if (mode === 'force') args.push('--force');
608
- args.push('-u');
887
+ if (branch) {
888
+ assertSafeGitRevish(branch, 'push branch');
889
+ args.push(branch);
609
890
  }
891
+ args.push(flag, '-u');
610
892
  return this.describePushResult(cwd, await execGit(args, cwd, 60000));
611
893
  }
612
894
 
@@ -716,6 +998,30 @@ export class GitService {
716
998
  return { success: true, hasConflicts: false, message: result.stdout };
717
999
  }
718
1000
 
1001
+ /**
1002
+ * Like `stashPop`, but leaves the entry in the stash list. Preferred when the
1003
+ * changes might not apply cleanly: a conflicted `pop` is easy to abort into a
1004
+ * state where the work looks lost, whereas `apply` always keeps a copy.
1005
+ */
1006
+ async stashApply(
1007
+ cwd: string,
1008
+ index = 0
1009
+ ): Promise<{ success: boolean; hasConflicts: boolean; message: string }> {
1010
+ if (!Number.isInteger(index) || index < 0) {
1011
+ throw new Error('Invalid stash index');
1012
+ }
1013
+ const result = await execGit(['stash', 'apply', `stash@{${index}}`], cwd);
1014
+ const combined = `${result.stdout}\n${result.stderr}`;
1015
+ const hasConflicts = /CONFLICT \(/.test(combined) || /needs merge/.test(combined);
1016
+ if (result.exitCode !== 0) {
1017
+ if (hasConflicts) {
1018
+ return { success: false, hasConflicts: true, message: result.stderr || result.stdout };
1019
+ }
1020
+ throw new Error(`git stash apply failed: ${result.stderr}`);
1021
+ }
1022
+ return { success: true, hasConflicts: false, message: result.stdout };
1023
+ }
1024
+
719
1025
  async stashDrop(cwd: string, index = 0): Promise<void> {
720
1026
  if (!Number.isInteger(index) || index < 0) {
721
1027
  throw new Error('Invalid stash index');
@@ -808,54 +1114,184 @@ export class GitService {
808
1114
  // Conflict Resolution
809
1115
  // ============================================
810
1116
 
1117
+ /**
1118
+ * Working-tree text above this size is not shipped to the client. A conflicted
1119
+ * minified bundle can be tens of megabytes; reading it, holding it as a JS
1120
+ * string and pushing it down the WebSocket stalls the panel for no benefit,
1121
+ * since nobody resolves a 20 MB file marker-by-marker anyway.
1122
+ */
1123
+ private static readonly MAX_CONFLICT_CONTENT_BYTES = 2 * 1024 * 1024;
1124
+
1125
+ /**
1126
+ * Classify a conflict from the stages present in the index. Git records up to
1127
+ * three: 1 = merge base, 2 = ours, 3 = theirs. A missing stage means that side
1128
+ * deleted (or never had) the path.
1129
+ */
1130
+ private conflictKindFromStages(stages: Set<number>): GitConflictKind {
1131
+ const base = stages.has(1);
1132
+ const ours = stages.has(2);
1133
+ const theirs = stages.has(3);
1134
+
1135
+ if (ours && theirs) return base ? 'both-modified' : 'both-added';
1136
+ if (ours && !theirs) return base ? 'deleted-by-them' : 'added-by-us';
1137
+ if (!ours && theirs) return base ? 'deleted-by-us' : 'added-by-them';
1138
+ return 'both-deleted';
1139
+ }
1140
+
1141
+ /**
1142
+ * List every unmerged path with enough context for the resolver to render it.
1143
+ *
1144
+ * The source of truth is `git ls-files -u`, not the working tree. Reading files
1145
+ * first (and dropping the ones that throw) silently hid whole classes of
1146
+ * conflict: both-deleted has no file on disk at all, so those paths vanished
1147
+ * from the UI while git still refused to continue.
1148
+ */
811
1149
  async getConflictFiles(cwd: string): Promise<GitConflictFile[]> {
812
- const status = await this.getStatus(cwd);
1150
+ const result = await execGit(['ls-files', '-u', '-z'], cwd);
1151
+ if (result.exitCode !== 0) {
1152
+ throw new Error(`git ls-files -u failed: ${result.stderr}`);
1153
+ }
1154
+
1155
+ const stages = parseUnmergedStages(result.stdout);
1156
+ const { readFile, stat } = await import('node:fs/promises');
1157
+ const { join } = await import('node:path');
813
1158
  const conflicts: GitConflictFile[] = [];
814
1159
 
815
- for (const file of status.conflicted) {
1160
+ for (const [filePath, fileStages] of stages) {
1161
+ const kind = this.conflictKindFromStages(fileStages);
1162
+ const entry: GitConflictFile = {
1163
+ path: filePath,
1164
+ content: '',
1165
+ markers: [],
1166
+ kind,
1167
+ contentOmitted: true
1168
+ };
1169
+
816
1170
  try {
817
- const { readFile } = await import('node:fs/promises');
818
- const { join } = await import('node:path');
819
- const content = await readFile(join(cwd, file.path), 'utf-8');
820
- const markers = parseConflictMarkers(content);
821
- conflicts.push({ path: file.path, content, markers });
822
- } catch (err) {
823
- debug.error('git', `Failed to read conflict file: ${file.path}`, err);
1171
+ const info = await stat(join(cwd, filePath));
1172
+ entry.size = info.size;
1173
+ if (info.size > GitService.MAX_CONFLICT_CONTENT_BYTES) {
1174
+ entry.omitReason = 'too-large';
1175
+ } else {
1176
+ const buffer = await readFile(join(cwd, filePath));
1177
+ // A NUL in the head is git's own binary heuristic. Decoding such a
1178
+ // file as UTF-8 produces replacement characters, and writing that
1179
+ // back as a "resolution" would corrupt it.
1180
+ if (buffer.subarray(0, 8000).includes(0)) {
1181
+ entry.omitReason = 'binary';
1182
+ } else {
1183
+ entry.content = buffer.toString('utf-8');
1184
+ entry.markers = parseConflictMarkers(entry.content);
1185
+ entry.contentOmitted = false;
1186
+ }
1187
+ }
1188
+ } catch {
1189
+ // No working-tree file: both-deleted, or deleted-by-us before the user
1190
+ // restored it. Still a conflict git needs an answer for.
1191
+ entry.omitReason = 'missing';
824
1192
  }
1193
+
1194
+ conflicts.push(entry);
825
1195
  }
826
1196
 
827
1197
  return conflicts;
828
1198
  }
829
1199
 
1200
+ /**
1201
+ * Apply one resolution to one conflicted path and stage the result.
1202
+ *
1203
+ * `ours`/`theirs` need the file to have that stage — `git checkout --ours` on a
1204
+ * path the other side deleted fails with an opaque "does not have our version",
1205
+ * so we translate those into the keep/delete answer git actually wants.
1206
+ */
830
1207
  async resolveConflict(
831
1208
  cwd: string,
832
1209
  filePath: string,
833
- resolution: 'ours' | 'theirs' | 'custom',
1210
+ resolution: GitConflictResolution,
834
1211
  customContent?: string
835
1212
  ): Promise<void> {
836
1213
  assertSafeGitPathOperand(filePath, 'conflict path');
837
- if (resolution === 'custom' && customContent !== undefined) {
838
- // Write custom content
839
- const { writeFile } = await import('node:fs/promises');
840
- const { join } = await import('node:path');
841
- await writeFile(join(cwd, filePath), customContent, 'utf-8');
842
- } else if (resolution === 'ours') {
843
- await execGit(['checkout', '--ours', '--', filePath], cwd);
844
- } else if (resolution === 'theirs') {
845
- await execGit(['checkout', '--theirs', '--', filePath], cwd);
1214
+ const { writeFile, readFile } = await import('node:fs/promises');
1215
+ const { join } = await import('node:path');
1216
+ const absolute = join(cwd, filePath);
1217
+
1218
+ if (resolution === 'reset') {
1219
+ // Re-materialize the conflict so the user can start over.
1220
+ const reset = await execGit(['checkout', '--merge', '--', filePath], cwd);
1221
+ if (reset.exitCode !== 0) {
1222
+ throw new Error(`git checkout --merge failed: ${reset.stderr}`);
1223
+ }
1224
+ return;
1225
+ }
1226
+
1227
+ if (resolution === 'delete') {
1228
+ const removed = await execGit(['rm', '-f', '--', filePath], cwd);
1229
+ if (removed.exitCode !== 0) {
1230
+ throw new Error(`git rm failed: ${removed.stderr}`);
1231
+ }
1232
+ return;
1233
+ }
1234
+
1235
+ if (resolution === 'custom') {
1236
+ if (customContent === undefined) {
1237
+ throw new Error('A custom resolution needs the resolved file content');
1238
+ }
1239
+ this.assertNoLeftoverMarkers(customContent, filePath);
1240
+ await writeFile(absolute, customContent, 'utf-8');
1241
+ } else if (resolution === 'ours' || resolution === 'theirs') {
1242
+ const stages = parseUnmergedStages(
1243
+ (await execGit(['ls-files', '-u', '-z', '--', filePath], cwd)).stdout
1244
+ );
1245
+ const present = stages.get(filePath) ?? new Set<number>();
1246
+ const wanted = resolution === 'ours' ? 2 : 3;
1247
+ if (!present.has(wanted)) {
1248
+ // That side deleted the path — "take ours" means "stay deleted".
1249
+ const removed = await execGit(['rm', '-f', '--', filePath], cwd);
1250
+ if (removed.exitCode !== 0) {
1251
+ throw new Error(`git rm failed: ${removed.stderr}`);
1252
+ }
1253
+ return;
1254
+ }
1255
+ const flag = resolution === 'ours' ? '--ours' : '--theirs';
1256
+ const checkout = await execGit(['checkout', flag, '--', filePath], cwd);
1257
+ if (checkout.exitCode !== 0) {
1258
+ throw new Error(`git checkout ${flag} failed: ${checkout.stderr}`);
1259
+ }
1260
+ } else if (resolution === 'keep') {
1261
+ // Keep whatever is on disk — but not if it still has markers in it.
1262
+ try {
1263
+ const buffer = await readFile(absolute);
1264
+ if (!buffer.subarray(0, 8000).includes(0)) {
1265
+ this.assertNoLeftoverMarkers(buffer.toString('utf-8'), filePath);
1266
+ }
1267
+ } catch (err) {
1268
+ if (err instanceof Error && err.message.includes('conflict marker')) throw err;
1269
+ throw new Error(`Cannot keep "${filePath}": the file is not in the working tree`);
1270
+ }
846
1271
  }
847
1272
 
848
- // Stage the resolved file
849
1273
  await this.stageFile(cwd, filePath);
850
1274
  }
851
1275
 
852
1276
  /**
853
- * Aborts the in-progress conflict-producing operation: merge, cherry-pick,
854
- * revert, rebase, or a stash pop that left unmerged paths. We detect the
855
- * type via `.git/*_HEAD` sentinel files and pick the matching abort command.
856
- * For stash conflicts (no sentinel) we fall back to `git reset --merge`,
857
- * which unwinds the unmerged paths while keeping unrelated local edits.
1277
+ * Refuse to stage text that still contains `<<<<<<<`. Git does not check this,
1278
+ * so without the guard a half-finished resolution commits the markers.
858
1279
  */
1280
+ private assertNoLeftoverMarkers(content: string, filePath: string): void {
1281
+ if (hasConflictMarkers(content)) {
1282
+ throw new Error(
1283
+ `"${filePath}" still contains conflict markers. Remove every <<<<<<< / ======= / >>>>>>> block before staging it.`
1284
+ );
1285
+ }
1286
+ }
1287
+
1288
+ /** Paths git still considers unmerged. */
1289
+ async getUnmergedPaths(cwd: string): Promise<string[]> {
1290
+ const result = await execGit(['diff', '--name-only', '--diff-filter=U', '-z'], cwd);
1291
+ if (result.exitCode !== 0) return [];
1292
+ return result.stdout.split('\0').filter(Boolean);
1293
+ }
1294
+
859
1295
  /** Resolve the absolute git dir for a working tree (handles worktrees/.git files). */
860
1296
  private async resolveGitDir(cwd: string): Promise<string> {
861
1297
  const { join } = await import('node:path');
@@ -883,7 +1319,177 @@ export class GitService {
883
1319
  return null;
884
1320
  }
885
1321
 
886
- async abortMerge(cwd: string): Promise<void> {
1322
+ /** Short subject of a revision, or an empty string when it cannot be read. */
1323
+ private async subjectOf(cwd: string, rev: string): Promise<string> {
1324
+ const result = await execGit(['log', '-1', '--format=%s', rev], cwd);
1325
+ return result.exitCode === 0 ? result.stdout.trim() : '';
1326
+ }
1327
+
1328
+ /** Best human name for a commit-ish: a branch name if one points at it, else a short hash. */
1329
+ private async describeRef(cwd: string, rev: string): Promise<string> {
1330
+ const named = await execGit(
1331
+ ['name-rev', '--name-only', '--refs=refs/heads/*', '--refs=refs/remotes/*', rev],
1332
+ cwd
1333
+ );
1334
+ const name = named.stdout.trim();
1335
+ if (named.exitCode === 0 && name && name !== 'undefined') {
1336
+ return name.replace(/^remotes\//, '');
1337
+ }
1338
+ const short = await execGit(['rev-parse', '--short', rev], cwd);
1339
+ return short.exitCode === 0 ? short.stdout.trim() : rev;
1340
+ }
1341
+
1342
+ /**
1343
+ * Everything the UI needs to describe and finish an in-progress operation.
1344
+ *
1345
+ * The `ours`/`theirs` labels matter more than they look: during a rebase git
1346
+ * replays your commit on top of the upstream, so `--ours` is the upstream and
1347
+ * `--theirs` is your own work — inverted relative to a merge. Surfacing the
1348
+ * raw words without the branch names is what makes people pick the wrong side.
1349
+ */
1350
+ async getOperationState(cwd: string): Promise<GitOperationState> {
1351
+ const { existsSync, readFileSync } = await import('node:fs');
1352
+ const { join } = await import('node:path');
1353
+ const gitDir = await this.resolveGitDir(cwd);
1354
+ const readTrimmed = (...parts: string[]): string => {
1355
+ const target = join(gitDir, ...parts);
1356
+ try {
1357
+ return existsSync(target) ? readFileSync(target, 'utf-8').trim() : '';
1358
+ } catch {
1359
+ return '';
1360
+ }
1361
+ };
1362
+
1363
+ const operation = await this.detectGitOperation(cwd);
1364
+ const unmerged = await this.getUnmergedPaths(cwd);
1365
+ const state: GitOperationState = {
1366
+ operation,
1367
+ oursLabel: 'ours',
1368
+ theirsLabel: 'theirs',
1369
+ unmergedCount: unmerged.length,
1370
+ canContinue: false,
1371
+ canSkip: false,
1372
+ stashConflict: false
1373
+ };
1374
+
1375
+ const currentBranch = (await execGit(['branch', '--show-current'], cwd)).stdout.trim();
1376
+
1377
+ if (operation === 'rebase') {
1378
+ // Interactive/merge-backend rebases use rebase-merge; `git am`-style ones
1379
+ // use rebase-apply. They spell the same counters differently.
1380
+ const isMerge = existsSync(join(gitDir, 'rebase-merge'));
1381
+ const dir = isMerge ? 'rebase-merge' : 'rebase-apply';
1382
+ const step = Number(readTrimmed(dir, isMerge ? 'msgnum' : 'next'));
1383
+ const total = Number(readTrimmed(dir, isMerge ? 'end' : 'last'));
1384
+ if (Number.isInteger(step) && step > 0) state.step = step;
1385
+ if (Number.isInteger(total) && total > 0) state.total = total;
1386
+
1387
+ const headName = readTrimmed(dir, 'head-name').replace(/^refs\/heads\//, '');
1388
+ const onto = readTrimmed(dir, 'onto');
1389
+ state.oursLabel = onto ? await this.describeRef(cwd, onto) : 'upstream';
1390
+ state.theirsLabel = headName ? `your commit (${headName})` : 'your commit';
1391
+
1392
+ const stopped = readTrimmed(dir, 'stopped-sha') || readTrimmed(dir, 'original-commit');
1393
+ if (stopped) state.currentCommit = await this.subjectOf(cwd, stopped);
1394
+ state.canSkip = true;
1395
+ } else if (operation === 'merge') {
1396
+ state.oursLabel = currentBranch || 'current branch';
1397
+ state.theirsLabel = await this.describeRef(cwd, 'MERGE_HEAD');
1398
+ state.currentCommit = await this.subjectOf(cwd, 'MERGE_HEAD');
1399
+ } else if (operation === 'cherry-pick' || operation === 'revert') {
1400
+ const head = operation === 'cherry-pick' ? 'CHERRY_PICK_HEAD' : 'REVERT_HEAD';
1401
+ state.oursLabel = currentBranch || 'current branch';
1402
+ state.theirsLabel = await this.describeRef(cwd, head);
1403
+ state.currentCommit = await this.subjectOf(cwd, head);
1404
+ state.canSkip = true;
1405
+ } else if (operation === null && unmerged.length > 0) {
1406
+ // Unmerged paths with no sentinel: a stash pop/apply that conflicted.
1407
+ state.stashConflict = true;
1408
+ state.oursLabel = currentBranch || 'working tree';
1409
+ state.theirsLabel = 'stashed changes';
1410
+ }
1411
+
1412
+ // Bisect never has a "continue"; everything else is finishable once the
1413
+ // index is clean.
1414
+ state.canContinue =
1415
+ operation !== null && operation !== 'bisect' && unmerged.length === 0;
1416
+
1417
+ return state;
1418
+ }
1419
+
1420
+ /**
1421
+ * Finish the in-progress operation. Returns the git output instead of throwing
1422
+ * on failure, because the common failures here are instructions rather than
1423
+ * errors — "nothing to commit, use --skip" is something the user must read.
1424
+ */
1425
+ async continueOperation(cwd: string): Promise<{ success: boolean; message: string }> {
1426
+ const operation = await this.detectGitOperation(cwd);
1427
+ const unmerged = await this.getUnmergedPaths(cwd);
1428
+ if (unmerged.length > 0) {
1429
+ throw new Error(
1430
+ `${unmerged.length} file${unmerged.length === 1 ? ' is' : 's are'} still unmerged. Resolve and stage them first.`
1431
+ );
1432
+ }
1433
+
1434
+ let args: string[];
1435
+ switch (operation) {
1436
+ case 'rebase':
1437
+ args = ['rebase', '--continue'];
1438
+ break;
1439
+ case 'merge':
1440
+ args = ['merge', '--continue'];
1441
+ break;
1442
+ case 'cherry-pick':
1443
+ args = ['cherry-pick', '--continue'];
1444
+ break;
1445
+ case 'revert':
1446
+ args = ['revert', '--continue'];
1447
+ break;
1448
+ default:
1449
+ throw new Error('There is no operation to continue.');
1450
+ }
1451
+
1452
+ const result = await execGit(args, cwd, 120000);
1453
+ return {
1454
+ success: result.exitCode === 0,
1455
+ message: (result.exitCode === 0 ? result.stdout : result.stderr).trim()
1456
+ };
1457
+ }
1458
+
1459
+ /** Drop the commit git is currently stuck on and move to the next one. */
1460
+ async skipOperation(cwd: string): Promise<{ success: boolean; message: string }> {
1461
+ const operation = await this.detectGitOperation(cwd);
1462
+ let args: string[];
1463
+ switch (operation) {
1464
+ case 'rebase':
1465
+ args = ['rebase', '--skip'];
1466
+ break;
1467
+ case 'cherry-pick':
1468
+ args = ['cherry-pick', '--skip'];
1469
+ break;
1470
+ case 'revert':
1471
+ args = ['revert', '--skip'];
1472
+ break;
1473
+ default:
1474
+ throw new Error('This operation cannot be skipped.');
1475
+ }
1476
+
1477
+ const result = await execGit(args, cwd, 120000);
1478
+ return {
1479
+ success: result.exitCode === 0,
1480
+ message: (result.exitCode === 0 ? result.stdout : result.stderr).trim()
1481
+ };
1482
+ }
1483
+
1484
+ /**
1485
+ * Aborts the in-progress conflict-producing operation: merge, cherry-pick,
1486
+ * revert, rebase, or a stash pop that left unmerged paths. We detect the
1487
+ * type via `.git/*_HEAD` sentinel files and pick the matching abort command.
1488
+ * For stash conflicts (no sentinel) we fall back to `git reset --merge`,
1489
+ * which unwinds the unmerged paths while keeping unrelated local edits — the
1490
+ * stash entry itself survives a failed pop, so nothing is actually lost.
1491
+ */
1492
+ async abortOperation(cwd: string): Promise<void> {
887
1493
  const { existsSync } = await import('node:fs');
888
1494
  const { join } = await import('node:path');
889
1495
 
@@ -897,21 +1503,85 @@ export class GitService {
897
1503
  else if (has('rebase-merge') || has('rebase-apply')) args = ['rebase', '--abort'];
898
1504
 
899
1505
  if (args) {
900
- const result = await execGit(args, cwd);
1506
+ const result = await execGit(args, cwd, 120000);
901
1507
  if (result.exitCode !== 0) {
902
1508
  throw new Error(`git ${args.join(' ')} failed: ${result.stderr}`);
903
1509
  }
904
1510
  return;
905
1511
  }
906
1512
 
907
- // No standard in-progress operation — likely a stash pop conflict. Use
908
- // `git reset --merge` to unwind unmerged paths safely.
909
1513
  const reset = await execGit(['reset', '--merge'], cwd);
910
1514
  if (reset.exitCode !== 0) {
911
1515
  throw new Error(`git reset --merge failed: ${reset.stderr}`);
912
1516
  }
913
1517
  }
914
1518
 
1519
+ /** Back-compat alias — the panel called this before rebase/cherry-pick were handled. */
1520
+ async abortMerge(cwd: string): Promise<void> {
1521
+ return this.abortOperation(cwd);
1522
+ }
1523
+
1524
+ /**
1525
+ * Rebase the current branch onto `upstream`.
1526
+ *
1527
+ * `--autostash` is on by default: without it git refuses to start whenever the
1528
+ * working tree is dirty, which from the panel just looks like the button not
1529
+ * working.
1530
+ */
1531
+ async rebaseOnto(
1532
+ cwd: string,
1533
+ upstream: string,
1534
+ autostash = true
1535
+ ): Promise<{ success: boolean; hasConflicts: boolean; message: string }> {
1536
+ assertSafeGitRevish(upstream, 'rebase upstream');
1537
+ const args = ['rebase'];
1538
+ if (autostash) args.push('--autostash');
1539
+ args.push(upstream);
1540
+
1541
+ const result = await execGit(args, cwd, 120000);
1542
+ const combined = `${result.stdout}\n${result.stderr}`;
1543
+ const hasConflicts = /CONFLICT \(/.test(combined) || /could not apply/i.test(combined);
1544
+ if (result.exitCode !== 0 && !hasConflicts) {
1545
+ throw new Error(`git rebase failed: ${result.stderr || result.stdout}`);
1546
+ }
1547
+ return {
1548
+ success: result.exitCode === 0,
1549
+ hasConflicts,
1550
+ message: (result.exitCode === 0 ? result.stdout : result.stderr || result.stdout).trim()
1551
+ };
1552
+ }
1553
+
1554
+ /** Restore the HEAD position recorded before the last checkout. */
1555
+ async returnToBranch(cwd: string, branch?: string): Promise<void> {
1556
+ if (branch) {
1557
+ await this.switchBranch(cwd, branch);
1558
+ return;
1559
+ }
1560
+ // `-` is git's own "previous checkout" shorthand, which is exactly what the
1561
+ // user wants after inspecting a commit from the history view.
1562
+ const result = await execGit(['checkout', '-'], cwd);
1563
+ if (result.exitCode !== 0) {
1564
+ throw new Error(
1565
+ `Could not return to the previous branch: ${result.stderr.trim() || 'no previous checkout recorded'}`
1566
+ );
1567
+ }
1568
+ }
1569
+
1570
+ /** Read the repo's undo journal — the only way back from a bad reset or rebase. */
1571
+ async getReflog(cwd: string, limit = 100): Promise<GitReflogEntry[]> {
1572
+ const SEPARATOR = '|||';
1573
+ const format = `%H${SEPARATOR}%h${SEPARATOR}%gd${SEPARATOR}%gs${SEPARATOR}%cI`;
1574
+ const result = await execGit(
1575
+ ['reflog', `--format=${format}`, `--max-count=${Math.max(1, Math.min(limit, 500))}`],
1576
+ cwd
1577
+ );
1578
+ if (result.exitCode !== 0) {
1579
+ if (!(await this.hasCommits(cwd))) return [];
1580
+ throw new Error(`git reflog failed: ${result.stderr}`);
1581
+ }
1582
+ return parseReflog(result.stdout);
1583
+ }
1584
+
915
1585
  // ============================================
916
1586
  // History rewrite / undo
917
1587
  // ============================================