@link-assistant/hive-mind 1.76.0 → 1.76.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,51 @@
1
1
  # @link-assistant/hive-mind
2
2
 
3
+ ## 1.76.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 13e7e6a: Docker isolation: reuse the host image instead of re-downloading a copy inside the (nested) Docker daemon (#1879).
8
+ - src/isolation-runner.lib.mjs: add `HIVE_MIND_DOCKER_ISOLATION_IMAGE_TAG` to pin the
9
+ isolation image tag, and `HIVE_MIND_DOCKER_ISOLATION_PULL` (always|missing|never) to emit a
10
+ `docker run --pull` policy. Verbose mode now logs the resolved image and pull policy.
11
+ - scripts/preload-dind-isolation-image.mjs: seed a DinD container's nested daemon from the
12
+ host (`docker save | docker exec -i … docker load`) so isolated tasks reuse the host image.
13
+ - .env.example: document the Docker isolation image/pull controls.
14
+ - Dockerfile / Dockerfile.dind / coolify/Dockerfile: bump the box base images to
15
+ `konard/box:2.2.0` / `konard/box-dind:2.2.0` (and the `docs/UBUNTU-SERVER*.md` examples).
16
+ v2.2.0 ships box's native host-image passthrough (box#94/#95), so the DinD deployment can seed
17
+ the nested daemon from the host automatically with
18
+ `-v /var/run/docker.sock:/var/run/host-docker.sock:ro -e DIND_HOST_PASSTHROUGH=public`.
19
+ - tests/test-issue-1879-docker-image-reuse.mjs: regression coverage.
20
+ - docs/case-studies/issue-1879: deep case study with logs, timeline, root causes, and runbook;
21
+ records that box#94 shipped in v2.2.0 and reports two upstream follow-ups — box#96
22
+ (public-mode passthrough test false positive) and box#97 (per-repository passthrough allowlist).
23
+
24
+ - 7335a73: Continue fork PRs with "Allow edits by maintainers" instead of halting on a misclassified fork divergence (#1893).
25
+
26
+ When the solver continues a cross-repository PR opened from another contributor's fork, it
27
+ synced the upstream default branch and then tried to push it back to `origin` — the
28
+ contributor's fork, which the operating maintainer does not own. GitHub rejected the push
29
+ with `! [remote rejected] main -> main (permission denied)`, and the solver misclassified
30
+ that permission error as a fork divergence (the heuristic matched the substring `rejected`),
31
+ halting with `Repository setup halted - fork divergence requires user decision` and advising
32
+ `--allow-fork-divergence-resolution-using-force-push-with-lease` — a flag that cannot help,
33
+ since force-push also requires fork write access.
34
+ - src/solve.branch-divergence.lib.mjs: add two pure helpers —
35
+ `shouldPushDefaultBranchToFork({currentUser, forkedRepo})` (skip the push when the user does
36
+ not own the fork; fail-open when owner/user is unknown) and `isPermissionDeniedPushError()`
37
+ (recognize a permission-denied rejection so it is never treated as divergence).
38
+ - src/solve.fork-sync.lib.mjs: new module holding `setupUpstreamAndSync` (extracted from
39
+ solve.repository.lib.mjs to stay under the 1500-line limit, re-exported unchanged). It now
40
+ resolves the current user, skips the fork's default-branch push when the user is not the fork
41
+ owner, and on a permission-denied push warns and continues on the PR branch instead of
42
+ halting. Genuine non-fast-forward divergence still triggers the original guidance. Adds
43
+ verbose diagnostics explaining each skip/continue decision.
44
+ - tests/test-issue-1893-fork-pr-permission-denied.mjs: regression coverage (9 cases) using the
45
+ exact failure output from the run log.
46
+ - docs/case-studies/issue-1893: deep case study with downloaded logs/data, timeline, root
47
+ causes, fix, codebase-wide audit, and existing-components review.
48
+
3
49
  ## 1.76.0
4
50
 
5
51
  ### Minor Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@link-assistant/hive-mind",
3
- "version": "1.76.0",
3
+ "version": "1.76.1",
4
4
  "description": "AI-powered issue solver and hive mind for collaborative problem solving",
5
5
  "main": "src/hive.mjs",
6
6
  "type": "module",
@@ -28,8 +28,13 @@ const { $ } = await use('command-stream');
28
28
  const VALID_ISOLATION_BACKENDS = ['screen', 'tmux', 'docker'];
29
29
  const RUNNING_SESSION_STATUSES = new Set(['executing', 'running']);
30
30
  const TERMINAL_SESSION_STATUSES = new Set(['executed', 'completed', 'failed', 'cancelled', 'canceled', 'error']);
31
- const DEFAULT_HIVE_MIND_IMAGE = 'konard/hive-mind:latest';
32
- const DEFAULT_HIVE_MIND_DIND_IMAGE = 'konard/hive-mind-dind:latest';
31
+ const HIVE_MIND_IMAGE_REPO = 'konard/hive-mind';
32
+ const HIVE_MIND_DIND_IMAGE_REPO = 'konard/hive-mind-dind';
33
+ const DEFAULT_HIVE_MIND_IMAGE_TAG = 'latest';
34
+ // Docker's `--pull` accepts these policies. We only emit the flag when an
35
+ // operator explicitly opts in; otherwise Docker's own default ("missing")
36
+ // applies and `docker run` reuses any locally present image. See issue #1879.
37
+ const VALID_DOCKER_PULL_POLICIES = new Set(['always', 'missing', 'never']);
33
38
  const DOCKER_ISOLATION_TRACKING_BACKEND = 'screen';
34
39
  const DOCKER_CONTAINER_HOME = '/home/box';
35
40
  const DOCKER_CONTAINER_PREFIX = 'hive-mind-isolation';
@@ -79,15 +84,52 @@ function maybeAddMount(mounts, source, target, existsSync) {
79
84
  mounts.push({ source, target });
80
85
  }
81
86
 
87
+ /**
88
+ * Resolve the tag used for the Docker isolation image.
89
+ *
90
+ * Defaults to `latest`, but operators can pin it (e.g. to the exact version
91
+ * already present on the host) via `HIVE_MIND_DOCKER_ISOLATION_IMAGE_TAG`.
92
+ * Pinning matters for Docker-in-Docker deployments: the nested daemon starts
93
+ * with an empty image store, so an unpinned `:latest` whose registry digest has
94
+ * drifted from the host copy forces a fresh multi-gigabyte pull on every task.
95
+ * A pinned tag lets a pre-seeded image be reused instead. See issue #1879.
96
+ */
97
+ export function resolveDockerIsolationImageTag({ env = process.env } = {}) {
98
+ const explicit = String(env.HIVE_MIND_DOCKER_ISOLATION_IMAGE_TAG || '').trim();
99
+ return explicit || DEFAULT_HIVE_MIND_IMAGE_TAG;
100
+ }
101
+
82
102
  /**
83
103
  * Pick the Docker image used for `--isolation docker`.
84
104
  *
85
105
  * start-command defaults its Docker backend to a base OS image. Hive Mind needs
86
106
  * an image with the same CLI/tooling baseline as the parent process instead.
107
+ *
108
+ * `HIVE_MIND_DOCKER_ISOLATION_IMAGE` is a full override (repo:tag). Otherwise
109
+ * the repo is chosen by image variant and the tag by
110
+ * `resolveDockerIsolationImageTag()`.
87
111
  */
88
112
  export function getDockerIsolationImage({ env = process.env } = {}) {
89
113
  if (env.HIVE_MIND_DOCKER_ISOLATION_IMAGE) return env.HIVE_MIND_DOCKER_ISOLATION_IMAGE;
90
- return String(env.HIVE_MIND_IMAGE_VARIANT || '').toLowerCase() === 'dind' ? DEFAULT_HIVE_MIND_DIND_IMAGE : DEFAULT_HIVE_MIND_IMAGE;
114
+ const repo = String(env.HIVE_MIND_IMAGE_VARIANT || '').toLowerCase() === 'dind' ? HIVE_MIND_DIND_IMAGE_REPO : HIVE_MIND_IMAGE_REPO;
115
+ return `${repo}:${resolveDockerIsolationImageTag({ env })}`;
116
+ }
117
+
118
+ /**
119
+ * Resolve the Docker `--pull` policy for isolated tasks.
120
+ *
121
+ * Returns one of `always` | `missing` | `never`, or `null` when unset (in which
122
+ * case the `--pull` flag is omitted and Docker's default applies). Operators set
123
+ * `HIVE_MIND_DOCKER_ISOLATION_PULL=never` to force reuse of an image already
124
+ * present in the (possibly nested) daemon and fail fast instead of silently
125
+ * re-downloading it. Invalid values are ignored. See issue #1879.
126
+ */
127
+ export function getDockerIsolationPullPolicy({ env = process.env } = {}) {
128
+ const raw = String(env.HIVE_MIND_DOCKER_ISOLATION_PULL || '')
129
+ .trim()
130
+ .toLowerCase();
131
+ if (!raw) return null;
132
+ return VALID_DOCKER_PULL_POLICIES.has(raw) ? raw : null;
91
133
  }
92
134
 
93
135
  /**
@@ -123,7 +165,16 @@ export function buildDockerIsolationCommand(command, args = [], options = {}) {
123
165
  const { sessionId, tool = 'claude', env = process.env, homeDir = os.homedir(), existsSync = fs.existsSync } = options;
124
166
  const image = getDockerIsolationImage({ env });
125
167
  const innerCommand = buildShellCommand(command, args);
126
- const dockerArgs = ['docker', 'run', '--rm', '--name', makeDockerContainerName(sessionId), '--workdir', DOCKER_CONTAINER_HOME, '-e', `HOME=${DOCKER_CONTAINER_HOME}`, '-e', `HIVE_MIND_PARENT_SESSION_ID=${sessionId || ''}`];
168
+ const dockerArgs = ['docker', 'run', '--rm'];
169
+
170
+ // Reuse a locally present image instead of re-downloading it when the
171
+ // operator opts in. Omitted by default so Docker's "missing" policy applies.
172
+ const pullPolicy = getDockerIsolationPullPolicy({ env });
173
+ if (pullPolicy) {
174
+ dockerArgs.push('--pull', pullPolicy);
175
+ }
176
+
177
+ dockerArgs.push('--name', makeDockerContainerName(sessionId), '--workdir', DOCKER_CONTAINER_HOME, '-e', `HOME=${DOCKER_CONTAINER_HOME}`, '-e', `HIVE_MIND_PARENT_SESSION_ID=${sessionId || ''}`);
127
178
 
128
179
  if (shouldRunPrivilegedDockerIsolation(image, env)) {
129
180
  dockerArgs.push('--privileged');
@@ -359,9 +410,12 @@ export async function executeWithIsolation(command, args, options = {}) {
359
410
  if (verbose) {
360
411
  console.log(`[VERBOSE] isolation-runner: ${[binPath, ...startCommandArgs].map(shellQuote).join(' ')}`);
361
412
  if (backend === 'docker') {
362
- const image = getDockerIsolationImage({ env: options.env || process.env });
363
- const mounts = getDockerIsolationAuthMounts({ tool: options.tool, env: options.env || process.env, homeDir: options.homeDir || os.homedir(), existsSync: options.existsSync || fs.existsSync });
413
+ const env = options.env || process.env;
414
+ const image = getDockerIsolationImage({ env });
415
+ const pullPolicy = getDockerIsolationPullPolicy({ env });
416
+ const mounts = getDockerIsolationAuthMounts({ tool: options.tool, env, homeDir: options.homeDir || os.homedir(), existsSync: options.existsSync || fs.existsSync });
364
417
  console.log(`[VERBOSE] isolation-runner: Docker isolation image: ${image}`);
418
+ console.log(`[VERBOSE] isolation-runner: Docker isolation pull policy: ${pullPolicy || '(docker default: missing — reuse local image if present)'}`);
365
419
  console.log(`[VERBOSE] isolation-runner: Docker isolation mounts: ${mounts.map(m => m.target).join(', ') || '(none)'}`);
366
420
  }
367
421
  }
@@ -38,6 +38,61 @@ export function classifyPushRejection(errorOutput = '') {
38
38
  return 'unknown';
39
39
  }
40
40
 
41
+ /**
42
+ * Detect whether a push failure was caused by missing permissions rather than
43
+ * by branch divergence. Git surfaces this as `! [remote rejected] ...
44
+ * (permission denied)` (HTTP 403). This is fundamentally different from a
45
+ * non-fast-forward / divergence rejection: force-pushing or force-with-lease
46
+ * will NOT help because the user simply cannot write to the remote.
47
+ *
48
+ * Issue #1893: when continuing another contributor's fork PR, the maintainer
49
+ * does not own the fork, so pushing the fork's default branch is rejected with
50
+ * "permission denied". The old heuristic matched the substring "rejected" and
51
+ * misclassified this as fork divergence, halting the run and recommending a
52
+ * useless `--allow-fork-divergence-resolution-using-force-push-with-lease`.
53
+ */
54
+ export function isPermissionDeniedPushError(errorOutput = '') {
55
+ const normalized = String(errorOutput || '').toLowerCase();
56
+ return normalized.includes('permission denied') || normalized.includes('permission to') || normalized.includes('error: 403') || normalized.includes('the requested url returned error: 403') || (normalized.includes('denied') && normalized.includes('to https://'));
57
+ }
58
+
59
+ /**
60
+ * Decide whether the solver should push the freshly-synced default branch to
61
+ * the fork's `origin` remote.
62
+ *
63
+ * We only push the default branch to keep a fork we OWN in sync with upstream.
64
+ * When continuing someone else's fork PR (the fork belongs to the contributor,
65
+ * not the current user), the maintainer has push rights only to the PR branch
66
+ * (via "Allow edits by maintainers"), never to the fork's default branch.
67
+ * Attempting the push is both impossible (permission denied) and unnecessary,
68
+ * so we skip it. Issue #1893.
69
+ *
70
+ * @param {object} params
71
+ * @param {string|null} params.currentUser - authenticated GitHub login
72
+ * @param {string|null} params.forkedRepo - "owner/name" of the fork (origin)
73
+ * @returns {{ shouldPush: boolean, reason: string, forkOwner: string|null }}
74
+ */
75
+ export function shouldPushDefaultBranchToFork({ currentUser, forkedRepo } = {}) {
76
+ const forkOwner = forkedRepo && forkedRepo.includes('/') ? forkedRepo.split('/')[0] : null;
77
+
78
+ if (!forkOwner) {
79
+ // Without a parseable fork owner we cannot prove ownership; fall back to the
80
+ // historical behaviour of attempting the push so nothing regresses.
81
+ return { shouldPush: true, reason: 'fork-owner-unknown', forkOwner: null };
82
+ }
83
+
84
+ if (!currentUser) {
85
+ // Could not resolve the current user; attempt the push and let git report.
86
+ return { shouldPush: true, reason: 'current-user-unknown', forkOwner };
87
+ }
88
+
89
+ if (currentUser.toLowerCase() === forkOwner.toLowerCase()) {
90
+ return { shouldPush: true, reason: 'owns-fork', forkOwner };
91
+ }
92
+
93
+ return { shouldPush: false, reason: 'not-fork-owner', forkOwner };
94
+ }
95
+
41
96
  export function shouldTreatPushRejectionAsRemoteSynchronized(divergence = null) {
42
97
  if (!divergence?.remoteExists || divergence.ahead !== 0 || divergence.behind !== 0) {
43
98
  return false;
@@ -0,0 +1,302 @@
1
+ #!/usr/bin/env node
2
+
3
+ // Fork upstream-sync module for the solve command.
4
+ // Extracted from solve.repository.lib.mjs to keep files under 1500 lines (#1893).
5
+
6
+ // Use use-m to dynamically import modules for cross-runtime compatibility
7
+ // Check if use is already defined globally (when imported from solve.mjs)
8
+ // If not, fetch it (when running standalone)
9
+ if (typeof globalThis.use === 'undefined') {
10
+ globalThis.use = (await eval(await (await fetch('https://unpkg.com/use-m/use.js')).text())).use;
11
+ }
12
+ const use = globalThis.use;
13
+
14
+ // Use command-stream for consistent $ behavior; wrap with rate-limit retry (#1726)
15
+ const { wrapDollarWithGhRetry } = await import('./github-rate-limit.lib.mjs');
16
+ const $ = wrapDollarWithGhRetry((await use('command-stream')).$);
17
+
18
+ // Import shared library functions
19
+ const lib = await import('./lib.mjs');
20
+ const { log, formatAligned } = lib;
21
+
22
+ // Import exit handler
23
+ import { safeExit } from './exit-handler.lib.mjs';
24
+
25
+ // Issue #1893: helpers that decide whether the fork's default branch may be
26
+ // pushed and that distinguish a permission-denied rejection from a genuine
27
+ // fork divergence.
28
+ const { isPermissionDeniedPushError, shouldPushDefaultBranchToFork } = await import('./solve.branch-divergence.lib.mjs');
29
+
30
+ // Set up upstream remote and sync fork
31
+ export const setupUpstreamAndSync = async (tempDir, forkedRepo, upstreamRemote, owner, repo, argv) => {
32
+ if (!forkedRepo || !upstreamRemote) return;
33
+
34
+ await log(`${formatAligned('🔗', 'Setting upstream:', upstreamRemote)}`);
35
+
36
+ // Check if upstream remote already exists
37
+ const checkUpstreamResult = await $({ cwd: tempDir })`git remote get-url upstream 2>/dev/null`;
38
+ let upstreamExists = checkUpstreamResult.code === 0;
39
+
40
+ if (upstreamExists) {
41
+ await log(`${formatAligned('ℹ️', 'Upstream exists:', 'Using existing upstream remote')}`);
42
+ } else {
43
+ // Add upstream remote since it doesn't exist
44
+ const upstreamResult = await $({ cwd: tempDir })`git remote add upstream https://github.com/${upstreamRemote}.git`;
45
+
46
+ if (upstreamResult.code === 0) {
47
+ await log(`${formatAligned('✅', 'Upstream set:', upstreamRemote)}`);
48
+ upstreamExists = true;
49
+ } else {
50
+ await log(`${formatAligned('⚠️', 'Warning:', 'Failed to add upstream remote')}`);
51
+ if (upstreamResult.stderr) {
52
+ await log(`${formatAligned('', 'Error details:', upstreamResult.stderr.toString().trim())}`);
53
+ }
54
+ }
55
+ }
56
+
57
+ // Proceed with fork sync if upstream remote is available
58
+ if (upstreamExists) {
59
+ // Fetch upstream
60
+ await log(`${formatAligned('🔄', 'Fetching upstream...', '')}`);
61
+ const fetchResult = await $({ cwd: tempDir })`git fetch upstream`;
62
+ if (fetchResult.code === 0) {
63
+ await log(`${formatAligned('✅', 'Upstream fetched:', 'Successfully')}`);
64
+
65
+ // Sync the default branch with upstream to avoid merge conflicts
66
+ await log(`${formatAligned('🔄', 'Syncing default branch...', '')}`);
67
+
68
+ // Get current branch so we can return to it after sync
69
+ const currentBranchResult = await $({ cwd: tempDir })`git branch --show-current`;
70
+ if (currentBranchResult.code === 0) {
71
+ const currentBranch = currentBranchResult.stdout.toString().trim();
72
+
73
+ // Get the default branch name from the original repository using GitHub API
74
+ const repoInfoResult = await $`gh api repos/${owner}/${repo} --jq .default_branch`;
75
+ if (repoInfoResult.code === 0) {
76
+ const upstreamDefaultBranch = repoInfoResult.stdout.toString().trim();
77
+ await log(`${formatAligned('ℹ️', 'Default branch:', upstreamDefaultBranch)}`);
78
+
79
+ // Always sync the default branch, regardless of current branch
80
+ // This ensures fork is up-to-date even if we're working on a different branch
81
+
82
+ // Step 1: Switch to default branch if not already on it
83
+ let syncSuccessful = true;
84
+ if (currentBranch !== upstreamDefaultBranch) {
85
+ await log(`${formatAligned('🔄', 'Switching to:', `${upstreamDefaultBranch} branch`)}`);
86
+ const checkoutResult = await $({ cwd: tempDir })`git checkout ${upstreamDefaultBranch}`;
87
+ if (checkoutResult.code !== 0) {
88
+ await log(`${formatAligned('⚠️', 'Warning:', `Failed to checkout ${upstreamDefaultBranch}`)}`);
89
+ syncSuccessful = false; // Cannot proceed with sync
90
+ }
91
+ }
92
+
93
+ // Step 2: Sync default branch with upstream (only if checkout was successful)
94
+ if (syncSuccessful) {
95
+ const syncResult = await $({ cwd: tempDir })`git reset --hard upstream/${upstreamDefaultBranch}`;
96
+ if (syncResult.code === 0) {
97
+ await log(`${formatAligned('✅', 'Default branch synced:', `with upstream/${upstreamDefaultBranch}`)}`);
98
+
99
+ // Step 3: Push the updated default branch to fork to keep it in sync.
100
+ //
101
+ // Issue #1893: only push the default branch when the current user
102
+ // OWNS the fork. When continuing another contributor's fork PR the
103
+ // fork belongs to them, and "Allow edits by maintainers" grants
104
+ // push access only to the PR branch — never to the fork's default
105
+ // branch. Attempting the push there is guaranteed to be rejected
106
+ // with "permission denied" and is unnecessary, so we skip it and
107
+ // keep working on the PR branch.
108
+ const currentUserResult = await $`gh api user --jq .login`;
109
+ const currentUser = currentUserResult.code === 0 ? currentUserResult.stdout.toString().trim() : null;
110
+ const pushDecision = shouldPushDefaultBranchToFork({ currentUser, forkedRepo });
111
+
112
+ if (!pushDecision.shouldPush) {
113
+ await log(`${formatAligned('ℹ️', 'Skipping fork push:', `${upstreamDefaultBranch} synced locally only`)}`);
114
+ await log(`${formatAligned('', 'Reason:', `Fork ${forkedRepo} is owned by ${pushDecision.forkOwner}, not ${currentUser || 'the current user'}`)}`, {
115
+ verbose: true,
116
+ });
117
+ await log(`${formatAligned('', 'Next:', 'Continuing on the PR branch (maintainer edits allowed on the PR head only)')}`, {
118
+ verbose: true,
119
+ });
120
+ // Fall through to Step 4 (return to original branch) without pushing.
121
+ if (currentBranch !== upstreamDefaultBranch) {
122
+ await log(`${formatAligned('🔄', 'Returning to:', `${currentBranch} branch`)}`);
123
+ const returnResult = await $({ cwd: tempDir })`git checkout ${currentBranch}`;
124
+ if (returnResult.code === 0) {
125
+ await log(`${formatAligned('✅', 'Branch restored:', `Back on ${currentBranch}`)}`);
126
+ } else {
127
+ await log(`${formatAligned('⚠️', 'Warning:', `Failed to return to ${currentBranch}`)}`);
128
+ }
129
+ }
130
+ return;
131
+ }
132
+
133
+ await log(`${formatAligned('🔄', 'Pushing to fork:', `${upstreamDefaultBranch} branch`)}`);
134
+ const pushResult = await $({ cwd: tempDir })`git push origin ${upstreamDefaultBranch} 2>&1`;
135
+ if (pushResult.code === 0) {
136
+ await log(`${formatAligned('✅', 'Fork updated:', 'Default branch pushed to fork')}`);
137
+ } else {
138
+ // Check if it's a non-fast-forward error (fork has diverged from upstream)
139
+ const errorMsg = (pushResult.stderr ? pushResult.stderr.toString().trim() : '') || (pushResult.stdout ? pushResult.stdout.toString().trim() : '');
140
+
141
+ // Issue #1893: a "permission denied" rejection is NOT a divergence.
142
+ // It means the current user cannot write to this fork (e.g. it
143
+ // belongs to another contributor). Force-push / force-with-lease
144
+ // cannot fix that, so never recommend the divergence flag here.
145
+ // Syncing the default branch is best-effort, so we warn and
146
+ // continue working on the PR branch instead of halting.
147
+ if (isPermissionDeniedPushError(errorMsg)) {
148
+ await log('');
149
+ await log(`${formatAligned('ℹ️', 'Skipping fork sync:', `No push access to ${forkedRepo}`)}`);
150
+ await log(`${formatAligned('', 'Reason:', "Fork's default branch is owned by another user; this is expected when")}`, { verbose: true });
151
+ await log(`${formatAligned('', '', "continuing a contributor's fork PR (maintainer edits cover the PR branch only)")}`, { verbose: true });
152
+ await log(`${formatAligned('', 'Push output:', errorMsg.split('\n')[0] || errorMsg)}`, { verbose: true });
153
+ // Return to the original branch and continue without halting.
154
+ if (currentBranch !== upstreamDefaultBranch) {
155
+ await log(`${formatAligned('🔄', 'Returning to:', `${currentBranch} branch`)}`);
156
+ const returnResult = await $({ cwd: tempDir })`git checkout ${currentBranch}`;
157
+ if (returnResult.code === 0) {
158
+ await log(`${formatAligned('✅', 'Branch restored:', `Back on ${currentBranch}`)}`);
159
+ } else {
160
+ await log(`${formatAligned('⚠️', 'Warning:', `Failed to return to ${currentBranch}`)}`);
161
+ }
162
+ }
163
+ return;
164
+ }
165
+
166
+ const isNonFastForward = errorMsg.includes('non-fast-forward') || errorMsg.includes('rejected') || errorMsg.includes('tip of your current branch is behind');
167
+
168
+ if (isNonFastForward) {
169
+ // Fork has diverged from upstream
170
+ await log('');
171
+ await log(`${formatAligned('⚠️', 'FORK DIVERGENCE DETECTED', '')}`, { level: 'warn' });
172
+ await log('');
173
+ await log(' 🔍 What happened:');
174
+ await log(` Your fork's ${upstreamDefaultBranch} branch has different commits than upstream`);
175
+ await log(' This typically occurs when upstream had a force push (e.g., git reset --hard)');
176
+ await log('');
177
+ await log(' 📦 Current state:');
178
+ await log(` • Fork: ${forkedRepo}`);
179
+ await log(` • Upstream: ${owner}/${repo}`);
180
+ await log(` • Branch: ${upstreamDefaultBranch}`);
181
+ await log('');
182
+
183
+ // Check if user has enabled automatic force push
184
+ if (argv.allowForkDivergenceResolutionUsingForcePushWithLease) {
185
+ await log(' 🔄 Auto-resolution ENABLED (--allow-fork-divergence-resolution-using-force-push-with-lease):');
186
+ await log(' Attempting to force-push with --force-with-lease...');
187
+ await log('');
188
+
189
+ // Use --force-with-lease for safer force push
190
+ // This will only force push if the remote hasn't changed since our last fetch
191
+ await log(`${formatAligned('🔄', 'Force pushing:', 'Syncing fork with upstream (--force-with-lease)')}`);
192
+ const forcePushResult = await $({
193
+ cwd: tempDir,
194
+ })`git push --force-with-lease origin ${upstreamDefaultBranch} 2>&1`;
195
+
196
+ if (forcePushResult.code === 0) {
197
+ await log(`${formatAligned('✅', 'Fork synced:', 'Successfully force-pushed to align with upstream')}`);
198
+ await log('');
199
+ } else {
200
+ // Force push also failed - this is a more serious issue
201
+ await log('');
202
+ await log(`${formatAligned('❌', 'FATAL ERROR:', 'Failed to sync fork with upstream')}`, {
203
+ level: 'error',
204
+ });
205
+ await log('');
206
+ await log(' 🔍 What happened:');
207
+ await log(` Fork branch ${upstreamDefaultBranch} has diverged from upstream`);
208
+ await log(' Both normal push and force-with-lease push failed');
209
+ await log('');
210
+ await log(' 📦 Error details:');
211
+ const forceErrorMsg = forcePushResult.stderr ? forcePushResult.stderr.toString().trim() : '';
212
+ for (const line of forceErrorMsg.split('\n')) {
213
+ if (line.trim()) await log(` ${line}`);
214
+ }
215
+ await log('');
216
+ await log(' 💡 Possible causes:');
217
+ await log(' • Fork branch is protected (branch protection rules prevent force push)');
218
+ await log(' • Someone else pushed to fork after our fetch');
219
+ await log(' • Insufficient permissions to force push');
220
+ await log('');
221
+ await log(' 🔧 Manual resolution:');
222
+ await log(` 1. Visit your fork: https://github.com/${forkedRepo}`);
223
+ await log(' 2. Check branch protection settings');
224
+ await log(' 3. Manually sync fork with upstream:');
225
+ await log(' git fetch upstream');
226
+ await log(` git reset --hard upstream/${upstreamDefaultBranch}`);
227
+ await log(` git push --force origin ${upstreamDefaultBranch}`);
228
+ await log('');
229
+ await safeExit(1, 'Repository setup failed - fork sync failed');
230
+ }
231
+ } else {
232
+ // Flag is not enabled - provide guidance
233
+ await log(' 💡 Your options:');
234
+ await log('');
235
+ await log(' Option 1: Delete your fork and recreate it (SIMPLEST)');
236
+ await log(` gh repo delete ${forkedRepo}`);
237
+ await log(' Then run the solve command again - the fork will be recreated automatically');
238
+ await log(' ⚠️ Only use this if your fork has no unique commits you need to preserve');
239
+ await log('');
240
+ await log(' Option 2: Enable automatic force-push (DANGEROUS)');
241
+ await log(' Add --allow-fork-divergence-resolution-using-force-push-with-lease flag to your command');
242
+ await log(' This will automatically sync your fork with upstream using force-with-lease');
243
+ await log(' ⚠️ Overwrites fork history - any unique commits will be LOST');
244
+ await log('');
245
+ await log(' Option 3: Manually resolve the divergence');
246
+ await log(' 1. Decide if you need any commits unique to your fork');
247
+ await log(' 2. If yes, cherry-pick them after syncing');
248
+ await log(' 3. If no, manually force-push:');
249
+ await log(' git fetch upstream');
250
+ await log(` git reset --hard upstream/${upstreamDefaultBranch}`);
251
+ await log(` git push --force origin ${upstreamDefaultBranch}`);
252
+ await log('');
253
+ await log(' 🔧 To proceed with auto-resolution, restart with:');
254
+ await log(` solve ${argv.url || argv['issue-url'] || argv._[0] || '<issue-url>'} --allow-fork-divergence-resolution-using-force-push-with-lease`);
255
+ await log('');
256
+ await safeExit(1, 'Repository setup halted - fork divergence requires user decision');
257
+ }
258
+ } else {
259
+ // Some other push error (not divergence-related)
260
+ await log(`${formatAligned('❌', 'FATAL ERROR:', 'Failed to push updated default branch to fork')}`);
261
+ await log(`${formatAligned('', 'Push error:', errorMsg)}`);
262
+ await log(`${formatAligned('', 'Reason:', 'Fork must be updated or process must stop')}`);
263
+ await log(`${formatAligned('', 'Solution draft:', 'Fork sync is required for proper workflow')}`);
264
+ await log(`${formatAligned('', 'Next steps:', '1. Check GitHub permissions for the fork')}`);
265
+ await log(`${formatAligned('', '', '2. Ensure fork is not protected')}`);
266
+ await log(`${formatAligned('', '', '3. Try again after resolving fork issues')}`);
267
+ await safeExit(1, 'Repository setup failed');
268
+ }
269
+ }
270
+
271
+ // Step 4: Return to the original branch if it was different
272
+ if (currentBranch !== upstreamDefaultBranch) {
273
+ await log(`${formatAligned('🔄', 'Returning to:', `${currentBranch} branch`)}`);
274
+ const returnResult = await $({ cwd: tempDir })`git checkout ${currentBranch}`;
275
+ if (returnResult.code === 0) {
276
+ await log(`${formatAligned('✅', 'Branch restored:', `Back on ${currentBranch}`)}`);
277
+ } else {
278
+ await log(`${formatAligned('⚠️', 'Warning:', `Failed to return to ${currentBranch}`)}`);
279
+ // This is not fatal, continue with sync on default branch
280
+ }
281
+ }
282
+ } else {
283
+ await log(`${formatAligned('⚠️', 'Warning:', `Failed to sync ${upstreamDefaultBranch} with upstream`)}`);
284
+ if (syncResult.stderr) {
285
+ await log(`${formatAligned('', 'Sync error:', syncResult.stderr.toString().trim())}`);
286
+ }
287
+ }
288
+ }
289
+ } else {
290
+ await log(`${formatAligned('⚠️', 'Warning:', 'Failed to get default branch name')}`);
291
+ }
292
+ } else {
293
+ await log(`${formatAligned('⚠️', 'Warning:', 'Failed to get current branch')}`);
294
+ }
295
+ } else {
296
+ await log(`${formatAligned('⚠️', 'Warning:', 'Failed to fetch upstream')}`);
297
+ if (fetchResult.stderr) {
298
+ await log(`${formatAligned('', 'Fetch error:', fetchResult.stderr.toString().trim())}`);
299
+ }
300
+ }
301
+ }
302
+ };
@@ -1045,220 +1045,10 @@ export const cloneRepository = async (repoToClone, tempDir, argv, owner, repo) =
1045
1045
  await safeExit(1, 'Repository setup failed');
1046
1046
  };
1047
1047
 
1048
- // Set up upstream remote and sync fork
1049
- export const setupUpstreamAndSync = async (tempDir, forkedRepo, upstreamRemote, owner, repo, argv) => {
1050
- if (!forkedRepo || !upstreamRemote) return;
1051
-
1052
- await log(`${formatAligned('🔗', 'Setting upstream:', upstreamRemote)}`);
1053
-
1054
- // Check if upstream remote already exists
1055
- const checkUpstreamResult = await $({ cwd: tempDir })`git remote get-url upstream 2>/dev/null`;
1056
- let upstreamExists = checkUpstreamResult.code === 0;
1057
-
1058
- if (upstreamExists) {
1059
- await log(`${formatAligned('ℹ️', 'Upstream exists:', 'Using existing upstream remote')}`);
1060
- } else {
1061
- // Add upstream remote since it doesn't exist
1062
- const upstreamResult = await $({ cwd: tempDir })`git remote add upstream https://github.com/${upstreamRemote}.git`;
1063
-
1064
- if (upstreamResult.code === 0) {
1065
- await log(`${formatAligned('✅', 'Upstream set:', upstreamRemote)}`);
1066
- upstreamExists = true;
1067
- } else {
1068
- await log(`${formatAligned('⚠️', 'Warning:', 'Failed to add upstream remote')}`);
1069
- if (upstreamResult.stderr) {
1070
- await log(`${formatAligned('', 'Error details:', upstreamResult.stderr.toString().trim())}`);
1071
- }
1072
- }
1073
- }
1074
-
1075
- // Proceed with fork sync if upstream remote is available
1076
- if (upstreamExists) {
1077
- // Fetch upstream
1078
- await log(`${formatAligned('🔄', 'Fetching upstream...', '')}`);
1079
- const fetchResult = await $({ cwd: tempDir })`git fetch upstream`;
1080
- if (fetchResult.code === 0) {
1081
- await log(`${formatAligned('✅', 'Upstream fetched:', 'Successfully')}`);
1082
-
1083
- // Sync the default branch with upstream to avoid merge conflicts
1084
- await log(`${formatAligned('🔄', 'Syncing default branch...', '')}`);
1085
-
1086
- // Get current branch so we can return to it after sync
1087
- const currentBranchResult = await $({ cwd: tempDir })`git branch --show-current`;
1088
- if (currentBranchResult.code === 0) {
1089
- const currentBranch = currentBranchResult.stdout.toString().trim();
1090
-
1091
- // Get the default branch name from the original repository using GitHub API
1092
- const repoInfoResult = await $`gh api repos/${owner}/${repo} --jq .default_branch`;
1093
- if (repoInfoResult.code === 0) {
1094
- const upstreamDefaultBranch = repoInfoResult.stdout.toString().trim();
1095
- await log(`${formatAligned('ℹ️', 'Default branch:', upstreamDefaultBranch)}`);
1096
-
1097
- // Always sync the default branch, regardless of current branch
1098
- // This ensures fork is up-to-date even if we're working on a different branch
1099
-
1100
- // Step 1: Switch to default branch if not already on it
1101
- let syncSuccessful = true;
1102
- if (currentBranch !== upstreamDefaultBranch) {
1103
- await log(`${formatAligned('🔄', 'Switching to:', `${upstreamDefaultBranch} branch`)}`);
1104
- const checkoutResult = await $({ cwd: tempDir })`git checkout ${upstreamDefaultBranch}`;
1105
- if (checkoutResult.code !== 0) {
1106
- await log(`${formatAligned('⚠️', 'Warning:', `Failed to checkout ${upstreamDefaultBranch}`)}`);
1107
- syncSuccessful = false; // Cannot proceed with sync
1108
- }
1109
- }
1110
-
1111
- // Step 2: Sync default branch with upstream (only if checkout was successful)
1112
- if (syncSuccessful) {
1113
- const syncResult = await $({ cwd: tempDir })`git reset --hard upstream/${upstreamDefaultBranch}`;
1114
- if (syncResult.code === 0) {
1115
- await log(`${formatAligned('✅', 'Default branch synced:', `with upstream/${upstreamDefaultBranch}`)}`);
1116
-
1117
- // Step 3: Push the updated default branch to fork to keep it in sync
1118
- await log(`${formatAligned('🔄', 'Pushing to fork:', `${upstreamDefaultBranch} branch`)}`);
1119
- const pushResult = await $({ cwd: tempDir })`git push origin ${upstreamDefaultBranch} 2>&1`;
1120
- if (pushResult.code === 0) {
1121
- await log(`${formatAligned('✅', 'Fork updated:', 'Default branch pushed to fork')}`);
1122
- } else {
1123
- // Check if it's a non-fast-forward error (fork has diverged from upstream)
1124
- const errorMsg = (pushResult.stderr ? pushResult.stderr.toString().trim() : '') || (pushResult.stdout ? pushResult.stdout.toString().trim() : '');
1125
- const isNonFastForward = errorMsg.includes('non-fast-forward') || errorMsg.includes('rejected') || errorMsg.includes('tip of your current branch is behind');
1126
-
1127
- if (isNonFastForward) {
1128
- // Fork has diverged from upstream
1129
- await log('');
1130
- await log(`${formatAligned('⚠️', 'FORK DIVERGENCE DETECTED', '')}`, { level: 'warn' });
1131
- await log('');
1132
- await log(' 🔍 What happened:');
1133
- await log(` Your fork's ${upstreamDefaultBranch} branch has different commits than upstream`);
1134
- await log(' This typically occurs when upstream had a force push (e.g., git reset --hard)');
1135
- await log('');
1136
- await log(' 📦 Current state:');
1137
- await log(` • Fork: ${forkedRepo}`);
1138
- await log(` • Upstream: ${owner}/${repo}`);
1139
- await log(` • Branch: ${upstreamDefaultBranch}`);
1140
- await log('');
1141
-
1142
- // Check if user has enabled automatic force push
1143
- if (argv.allowForkDivergenceResolutionUsingForcePushWithLease) {
1144
- await log(' 🔄 Auto-resolution ENABLED (--allow-fork-divergence-resolution-using-force-push-with-lease):');
1145
- await log(' Attempting to force-push with --force-with-lease...');
1146
- await log('');
1147
-
1148
- // Use --force-with-lease for safer force push
1149
- // This will only force push if the remote hasn't changed since our last fetch
1150
- await log(`${formatAligned('🔄', 'Force pushing:', 'Syncing fork with upstream (--force-with-lease)')}`);
1151
- const forcePushResult = await $({
1152
- cwd: tempDir,
1153
- })`git push --force-with-lease origin ${upstreamDefaultBranch} 2>&1`;
1154
-
1155
- if (forcePushResult.code === 0) {
1156
- await log(`${formatAligned('✅', 'Fork synced:', 'Successfully force-pushed to align with upstream')}`);
1157
- await log('');
1158
- } else {
1159
- // Force push also failed - this is a more serious issue
1160
- await log('');
1161
- await log(`${formatAligned('❌', 'FATAL ERROR:', 'Failed to sync fork with upstream')}`, {
1162
- level: 'error',
1163
- });
1164
- await log('');
1165
- await log(' 🔍 What happened:');
1166
- await log(` Fork branch ${upstreamDefaultBranch} has diverged from upstream`);
1167
- await log(' Both normal push and force-with-lease push failed');
1168
- await log('');
1169
- await log(' 📦 Error details:');
1170
- const forceErrorMsg = forcePushResult.stderr ? forcePushResult.stderr.toString().trim() : '';
1171
- for (const line of forceErrorMsg.split('\n')) {
1172
- if (line.trim()) await log(` ${line}`);
1173
- }
1174
- await log('');
1175
- await log(' 💡 Possible causes:');
1176
- await log(' • Fork branch is protected (branch protection rules prevent force push)');
1177
- await log(' • Someone else pushed to fork after our fetch');
1178
- await log(' • Insufficient permissions to force push');
1179
- await log('');
1180
- await log(' 🔧 Manual resolution:');
1181
- await log(` 1. Visit your fork: https://github.com/${forkedRepo}`);
1182
- await log(' 2. Check branch protection settings');
1183
- await log(' 3. Manually sync fork with upstream:');
1184
- await log(' git fetch upstream');
1185
- await log(` git reset --hard upstream/${upstreamDefaultBranch}`);
1186
- await log(` git push --force origin ${upstreamDefaultBranch}`);
1187
- await log('');
1188
- await safeExit(1, 'Repository setup failed - fork sync failed');
1189
- }
1190
- } else {
1191
- // Flag is not enabled - provide guidance
1192
- await log(' 💡 Your options:');
1193
- await log('');
1194
- await log(' Option 1: Delete your fork and recreate it (SIMPLEST)');
1195
- await log(` gh repo delete ${forkedRepo}`);
1196
- await log(' Then run the solve command again - the fork will be recreated automatically');
1197
- await log(' ⚠️ Only use this if your fork has no unique commits you need to preserve');
1198
- await log('');
1199
- await log(' Option 2: Enable automatic force-push (DANGEROUS)');
1200
- await log(' Add --allow-fork-divergence-resolution-using-force-push-with-lease flag to your command');
1201
- await log(' This will automatically sync your fork with upstream using force-with-lease');
1202
- await log(' ⚠️ Overwrites fork history - any unique commits will be LOST');
1203
- await log('');
1204
- await log(' Option 3: Manually resolve the divergence');
1205
- await log(' 1. Decide if you need any commits unique to your fork');
1206
- await log(' 2. If yes, cherry-pick them after syncing');
1207
- await log(' 3. If no, manually force-push:');
1208
- await log(' git fetch upstream');
1209
- await log(` git reset --hard upstream/${upstreamDefaultBranch}`);
1210
- await log(` git push --force origin ${upstreamDefaultBranch}`);
1211
- await log('');
1212
- await log(' 🔧 To proceed with auto-resolution, restart with:');
1213
- await log(` solve ${argv.url || argv['issue-url'] || argv._[0] || '<issue-url>'} --allow-fork-divergence-resolution-using-force-push-with-lease`);
1214
- await log('');
1215
- await safeExit(1, 'Repository setup halted - fork divergence requires user decision');
1216
- }
1217
- } else {
1218
- // Some other push error (not divergence-related)
1219
- await log(`${formatAligned('❌', 'FATAL ERROR:', 'Failed to push updated default branch to fork')}`);
1220
- await log(`${formatAligned('', 'Push error:', errorMsg)}`);
1221
- await log(`${formatAligned('', 'Reason:', 'Fork must be updated or process must stop')}`);
1222
- await log(`${formatAligned('', 'Solution draft:', 'Fork sync is required for proper workflow')}`);
1223
- await log(`${formatAligned('', 'Next steps:', '1. Check GitHub permissions for the fork')}`);
1224
- await log(`${formatAligned('', '', '2. Ensure fork is not protected')}`);
1225
- await log(`${formatAligned('', '', '3. Try again after resolving fork issues')}`);
1226
- await safeExit(1, 'Repository setup failed');
1227
- }
1228
- }
1229
-
1230
- // Step 4: Return to the original branch if it was different
1231
- if (currentBranch !== upstreamDefaultBranch) {
1232
- await log(`${formatAligned('🔄', 'Returning to:', `${currentBranch} branch`)}`);
1233
- const returnResult = await $({ cwd: tempDir })`git checkout ${currentBranch}`;
1234
- if (returnResult.code === 0) {
1235
- await log(`${formatAligned('✅', 'Branch restored:', `Back on ${currentBranch}`)}`);
1236
- } else {
1237
- await log(`${formatAligned('⚠️', 'Warning:', `Failed to return to ${currentBranch}`)}`);
1238
- // This is not fatal, continue with sync on default branch
1239
- }
1240
- }
1241
- } else {
1242
- await log(`${formatAligned('⚠️', 'Warning:', `Failed to sync ${upstreamDefaultBranch} with upstream`)}`);
1243
- if (syncResult.stderr) {
1244
- await log(`${formatAligned('', 'Sync error:', syncResult.stderr.toString().trim())}`);
1245
- }
1246
- }
1247
- }
1248
- } else {
1249
- await log(`${formatAligned('⚠️', 'Warning:', 'Failed to get default branch name')}`);
1250
- }
1251
- } else {
1252
- await log(`${formatAligned('⚠️', 'Warning:', 'Failed to get current branch')}`);
1253
- }
1254
- } else {
1255
- await log(`${formatAligned('⚠️', 'Warning:', 'Failed to fetch upstream')}`);
1256
- if (fetchResult.stderr) {
1257
- await log(`${formatAligned('', 'Fetch error:', fetchResult.stderr.toString().trim())}`);
1258
- }
1259
- }
1260
- }
1261
- };
1048
+ // Set up upstream remote and sync fork.
1049
+ // Extracted into solve.fork-sync.lib.mjs (#1893) to keep this file under the
1050
+ // 1500-line limit; re-exported here so existing importers keep working.
1051
+ export { setupUpstreamAndSync } from './solve.fork-sync.lib.mjs';
1262
1052
 
1263
1053
  // Set up pr-fork remote for continuing someone else's fork PR with --fork flag
1264
1054
  export const setupPrForkRemote = async (tempDir, argv, prForkOwner, repo, isContinueMode, owner = null) => {