Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: attach agent worktrees to fork PR head branches so external contributions are workable
Adam Eivy33decb71d7f0
diff --git a/server/lib/README.md b/server/lib/README.mdindex 4067bf89e8..c6137819d4 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -287,6 +287,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. || `execGit.js` | `execGit(args, cwd, options)` utility imported by `git.js` + worktree manager. `cwd` is REQUIRED — it rejects on a missing/blank one rather than letting `spawn` fall back to `process.cwd()` and run git against PortOS's own checkout (#4554). || `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. |+| `forkHead.js` | `normalizeForkHead(value)` / `forkRemoteName(ownerLogin)` / `resolveTaskForkHead(metadata)` — the validated `{remoteUrl, ownerLogin}` address of a cross-repository PR's head branch, which has no `origin/<branch>` to attach to. Fail-closed: anything that isn't a usable pair (or that starts with `-`, which git would read as an option) is `null`, so every caller falls back to origin-only behavior instead of guessing. `forkRemoteName` is the deterministic `fork-<owner>` remote name that makes a re-attach reuse the remote it already added. Shared by `appPullRequests.js` (produces), `agentWorktreeCleanup.js`/`prRemediationFollowUp.js` (persist in task metadata), `agentWorkspacePrep.js` (threads), and `worktreeManager.js` (consumes — it has no forge client of its own). `resolveTaskForkHead` is the single reader of the generic `forkHead` task-metadata key, the fork-side counterpart to `taskTargetBranch.js`. || `frameQuality.js` | Scores decoded video frames so a chained render can CHOOSE its continuation anchor instead of taking whatever an end-seek lands on. `scoreFrame({width,height,data},{recency})` combines three terms over a raw single-channel buffer: log-compressed `gradientVariance` (focus), distance of `meanLuma` from mid-grey (exposure penalty, which rejects a fade-to-black or a blown highlight), and a small linear recency bonus that keeps the anchor near the cut when candidates are comparably clean. Usability and ranking are deliberately separate: `usable` gates on raw gradient variance against `MIN_SIGNAL_VARIANCE` alone, so only a mathematically degenerate frame is rejected and a legitimately dark low-key tail still qualifies — the same contract `imageFrameStats.js` keeps. Gating on the composite score instead would reject every night scene on the exposure term. `TAIL_WINDOW_SECONDS` is capped at the reach of the single `-sseof -1.0` seek this replaces: focus is systematically highest at the OLDEST candidate, so a wider window would widen the backward jump at each chain seam rather than tightening it. `pickBestFrame(paths)` decodes each candidate through `sharp` and returns the winner (or `null` when nothing decodes or every candidate is degenerate, so the caller degrades rather than failing a render); its `index` is the position in the array AS PASSED, because the caller turns that into the anchor's time offset. `MAX_CANDIDATES` is derived from the window, never set independently — the ffmpeg-side `-frames:v` cap truncates from the NEWEST end, exactly the frames recency prefers. `TAIL_WINDOW_SECONDS` / `CANDIDATE_FPS` / `MAX_CANDIDATES` define the window the caller decodes from. Consumer: `services/videoGen/local.js#extractLastFrame`. || `ffmpegRenderGuard.js` | `attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose})` — shared spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior. || `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)`, `isGitStageableFilePath(file)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). `isGitStageableFilePath` is `validateFilePaths`' non-throwing twin, for callers that must refuse an unstageable path BEFORE writing the file rather than 500 on the commit. |diff --git a/server/lib/branchUpstreamGuard.test.js b/server/lib/branchUpstreamGuard.test.jsindex 3d53c0592c..02703f11b4 100644--- a/server/lib/branchUpstreamGuard.test.js+++ b/server/lib/branchUpstreamGuard.test.js@@ -74,6 +74,14 @@ describe('isSafeBranchUpstream', () => {expect(isSafeBranchUpstream('feature/x', 'feature/x')).toBe(true);});+ it('accepts a branch tracking a FORK remote, because the invariant is on the REF (#6064)', () => {+ // A fork PR's head is attached from `fork-<owner>/<branch>`, so its upstream+ // is `remote=fork-contributor, merge=refs/heads/<branch>`. Judging the+ // REMOTE instead of the ref would have this guard "repair" that away — and a+ // config-derived push would then land the contributor's commits on origin.+ expect(isSafeBranchUpstream('contributor/fix-thing', 'refs/heads/contributor/fix-thing')).toBe(true);+ });+it('rejects the default branch — the ref a config-derived push must never resolve to', () => {expect(isSafeBranchUpstream('cos/task/agent', 'refs/heads/main')).toBe(false);});diff --git a/server/lib/forkHead.js b/server/lib/forkHead.jsnew file mode 100644index 0000000000..ca00ce9de0--- /dev/null+++ b/server/lib/forkHead.js@@ -0,0 +1,112 @@+/**+ * Fork-head coordinates — where a cross-repository pull request's branch lives.+ *+ * A PR opened from a fork has no `origin/<headRefName>`: the branch is in the+ * contributor's repository, and the forge only exposes its tip on origin as the+ * read-only `refs/pull/<n>/head`, which nothing can push back to. Every PortOS+ * path that means "work on this PR's branch" therefore needs a second address+ * for it — the fork's clone URL plus the owner whose login names the remote.+ *+ * This module is that address, as a validated value object, so the four places+ * that touch it agree on one shape: the forge read that produces it+ * (`appPullRequests.js`), the task metadata that persists it+ * (`agentWorktreeCleanup.js`, `prRemediationFollowUp.js`), the spawn path that+ * threads it (`agentWorkspacePrep.js`), and the git layer that consumes it+ * (`worktreeManager.js`, which deliberately has no forge client of its own).+ *+ * Pure and fail-closed: anything that isn't a usable pair returns `null`, which+ * every caller reads as "no fork coordinates" and falls back to its existing+ * origin-only behavior rather than guessing.+ */++/**+ * Coerce forge-supplied (or metadata-round-tripped) fork coordinates into the+ * canonical `{ remoteUrl, ownerLogin }` pair, or `null` when they are unusable.+ *+ * The leading-`-` rejection is not cosmetic: both values reach a `git` argv, and+ * a value starting with `-` would be parsed as an option rather than as a URL or+ * a name.+ *+ * @param {unknown} value - candidate coordinates+ * @returns {{remoteUrl: string, ownerLogin: string}|null}+ */+export function normalizeForkHead(value) {+ if (!value || typeof value !== 'object') return null;+ const remoteUrl = typeof value.remoteUrl === 'string' ? value.remoteUrl.trim() : '';+ const ownerLogin = typeof value.ownerLogin === 'string' ? value.ownerLogin.trim() : '';+ if (!remoteUrl || !ownerLogin) return null;+ if (remoteUrl.startsWith('-') || ownerLogin.startsWith('-')) return null;+ return { remoteUrl, ownerLogin };+}++/**+ * The deterministic git remote name for a fork's owner.+ *+ * Deterministic so a re-run (a second review round, a retried remediation)+ * reuses the remote it already added instead of accumulating one per attach —+ * and so teardown can leave it in place, which is what makes the reuse free.+ *+ * Forge logins are conventionally `[A-Za-z0-9-]`, but the value arrives from a+ * forge read, so anything outside git's safe remote-name set is folded to `-`.+ *+ * @param {unknown} ownerLogin+ * @returns {string|null} e.g. `fork-contributor`, or null when nothing survives+ */+export function forkRemoteName(ownerLogin) {+ const slug = (typeof ownerLogin === 'string' ? ownerLogin : '')+ .trim()+ .replace(/[^A-Za-z0-9._-]/g, '-')+ .replace(/^[-.]+/, '');+ return slug ? `fork-${slug}` : null;+}++/**+ * Read a task's fork coordinates out of its metadata.+ *+ * The key is deliberately generic (`forkHead`, not a review-loop-specific+ * name): both producers of a task pointed at a pre-existing PR branch — the+ * review-loop follow-up and the public-PR remediation agent — write it, and+ * `agentWorkspacePrep` is the single reader that threads it into+ * `createWorktree`. Naming it in one place is what keeps them from drifting,+ * the same job `resolveTaskTargetBranch` does for the branch name itself.+ *+ * Re-validates on read because task metadata round-trips through the tasks+ * markdown file, which a human may edit.+ *+ * @param {object} metadata - task metadata+ * @returns {{remoteUrl: string, ownerLogin: string}|null}+ */+export function resolveTaskForkHead(metadata) {+ return normalizeForkHead(metadata?.forkHead);+}++/**+ * Read fork coordinates off a `gh pr view`/`gh pr list --json` row.+ *+ * `gh pr view --json headRepository` answers `{id, name, nameWithOwner}` — it+ * carries no clone URL — so the remote URL is composed from the PR's OWN origin+ * plus `nameWithOwner`. That also keeps GitHub Enterprise correct: the fork is+ * on the same host as the PR, never hardcoded to github.com.+ *+ * A same-repo head returns null: `origin/<branch>` already resolves it, and+ * adding a fork remote for it would be wrong.+ *+ * Requires `isCrossRepository`, `headRepository`, `headRepositoryOwner`, and+ * `url` in the caller's `--json` field list.+ *+ * @param {object} pr - a gh PR row+ * @returns {{remoteUrl: string, ownerLogin: string}|null}+ */+export function forkHeadFromGithubPr(pr) {+ if (pr?.isCrossRepository !== true) return null;+ const ownerLogin = typeof pr?.headRepositoryOwner?.login === 'string' ? pr.headRepositoryOwner.login.trim() : '';+ const repoName = typeof pr?.headRepository?.name === 'string' ? pr.headRepository.name.trim() : '';+ const nameWithOwner = typeof pr?.headRepository?.nameWithOwner === 'string' && pr.headRepository.nameWithOwner.trim()+ ? pr.headRepository.nameWithOwner.trim()+ : (ownerLogin && repoName ? `${ownerLogin}/${repoName}` : '');+ // The PR URL's scheme+host, without constructing a URL object for a value the+ // forge may have omitted entirely.+ const [, origin] = /^(https?:\/\/[^/]+)\//.exec(typeof pr?.url === 'string' ? pr.url : '') || [];+ if (!ownerLogin || !nameWithOwner || !origin) return null;+ return normalizeForkHead({ remoteUrl: `${origin}/${nameWithOwner}.git`, ownerLogin });+}diff --git a/server/lib/index.js b/server/lib/index.jsindex 6a9abe89bb..927740707a 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -271,6 +271,7 @@ export * from './setupScriptRunner.js';export * from './hostShutdown.js';export * from './execGit.js';export * from './ffmpeg.js';+export * from './forkHead.js';export * from './ffmpegRenderGuard.js';export * from './frameQuality.js';export * from './gitArgs.js';diff --git a/server/routes/apps/pullRequests.js b/server/routes/apps/pullRequests.jsindex 1564a1ab8d..e908561483 100644--- a/server/routes/apps/pullRequests.js+++ b/server/routes/apps/pullRequests.js@@ -255,6 +255,10 @@ router.post('/:id/pull-requests/:number/resolve', loadApp, asyncHandler(async (roriginalTask,prUrl: pullRequest.url,prBranch: pullRequest.headBranch,+ // Null for a same-repo head. A FORK PR's head branch has no+ // `origin/<branch>`, so without this the follow-up is queued and then+ // blocked at workspace prep — which is every external contribution (#6064).+ forkHead: pullRequest.forkHead,sourceWorkspace: app.repoPath,prCompletion: PR_COMPLETIONS.REVIEW_THEN_MERGE,...reviewOptions,diff --git a/server/routes/apps/pullRequests.test.js b/server/routes/apps/pullRequests.test.jsindex 098a8388bb..b09e17cd6f 100644--- a/server/routes/apps/pullRequests.test.js+++ b/server/routes/apps/pullRequests.test.js@@ -154,6 +154,25 @@ describe('app pull-request routes', () => {});});+ it('threads a fork PR\'s head coordinates through to the follow-up (#6064)', async () => {+ // Resolve is offered on ANY open PR, and a fork head has no+ // `origin/<branch>`: without these the agent is queued and then blocked at+ // workspace prep for exactly the PRs external contributors open.+ const forkHead = { remoteUrl: 'https://github.com/contributor/widget.git', ownerLogin: 'contributor' };+ listAppPullRequests.mockResolvedValue({+ ...listResult(),+ pullRequests: [{ ...PULL_REQUEST, headBranch: 'contributor/fix-thing', isCrossRepository: true, forkHead }],+ });++ const response = await request(app).post('/api/apps/app-001/pull-requests/17/resolve');++ expect(response.status).toBe(202);+ expect(spawnReviewLoopFollowUp).toHaveBeenCalledWith(expect.objectContaining({+ prBranch: 'contributor/fix-thing',+ forkHead,+ }));+ });+// Pressing the button IS the approval. Without an immediate dispatch the// follow-up is an auto-approved SYSTEM task, which the dequeue only spawns while// CoS auto-run is in `execute` and under budget — so it sat pending until thediff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.jsindex 31f7c0346d..2be4ec94a0 100644--- a/server/services/agentWorkspacePrep.js+++ b/server/services/agentWorkspacePrep.js@@ -38,6 +38,7 @@ import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, isBranchimport { resolveSpawnCwd, usesCreativeDirectorScratchCwd, creativeDirectorScratchCwd } from '../lib/spawnCwd.js';import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';+import { resolveTaskForkHead } from '../lib/forkHead.js';import { getAppWorkspace, getAppDataForTask, createJiraTicketForTask } from './agentPromptBuilder.js';import { INVESTIGATION_TASK_DELIVERY, isInvestigationTask } from '../lib/investigationTasks.js';@@ -135,6 +136,7 @@ async function prepareRequestedWorktree({workspacePath,task,existingBranch,+ forkHead,allowSharedWorkspaceFallback,}) {// Detecting the base branch and resolving the branch holder are independent@@ -181,6 +183,10 @@ async function prepareRequestedWorktree({const worktreeInfo = takeover?.worktreeInfo || await createWorktree(agentId, workspacePath, task.id, {baseBranch: detectedBase || undefined,existingBranch: existingBranch || undefined,+ // Only consulted when `existingBranch` names a FORK PR's head, which has no+ // `origin/<branch>` to attach to (#6064). Null for every other task, which+ // is the behavior that predates it.+ forkHead: forkHead || undefined,planId: task.metadata?.planId || undefined}).catch(err => {worktreeError = err;@@ -340,6 +346,9 @@ export async function prepareAgentWorkspace({ agentId, task }) {// detection returns `proceed` once the dead agent is gone) and silently// abandons the work the pointer was recorded to save.const existingBranch = resolveTaskTargetBranch(task.metadata);+ // Where that branch lives when the task points at a fork PR's head — read+ // here rather than inside the worktree layer, which has no forge client.+ const forkHead = resolveTaskForkHead(task.metadata);const wantsWorktree = explicitWorktree || !!existingBranch;if (!isReadOnly) {@@ -476,6 +485,7 @@ export async function prepareAgentWorkspace({ agentId, task }) {workspacePath,task,existingBranch,+ forkHead,allowSharedWorkspaceFallback: !isReadOnly && !explicitWorktree,});if (worktreeOutcome.outcome !== 'ready') return worktreeOutcome;diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex da4245b41d..3e0da3bdae 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -26,6 +26,7 @@ import { isRetryHoldOwner, clearedRetryHoldMetadata } from '../lib/taskRetryHoldimport { resolveTaskTargetBranch, shouldStripTaskTargetBranch } from '../lib/taskTargetBranch.js';import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';import { detectForgeCli } from '../lib/gitForge.js';+import { normalizeForkHead } from '../lib/forkHead.js';import { PR_COMPLETIONS, PR_COMPLETION_VALUES, PR_CREATION, leavesPrForHuman, prClaimWasVerified } from '../lib/prDisposition.js';import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, MODEL_SELECTABLE_REVIEWERS, EFFORT_SELECTABLE_REVIEWERS, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, prioritizeToolFreeReviewers } from '../lib/reviewerConfig.js';@@ -811,7 +812,12 @@ export async function releaseRetryHold({ agentId, task, success, agentMetadata }** The follow-up task uses an isolated worktree attached to the existing PR branch* through its canonical `reviewLoopPRBranch`, so it can fix-and-push without- * trampling concurrent agents.+ * trampling concurrent agents. `forkHead` is where that branch lives when the PR+ * came from a FORK — such a head has no `origin/<branch>` for the attach to+ * resolve, so without it the follow-up is queued and then blocked at workspace+ * prep for exactly the PRs external contributors open (#6064). Persisted beside+ * the branch name and threaded back out by `agentWorkspacePrep`; a same-repo PR+ * passes null and nothing changes.** `dispatch` decides WHO starts the task:* `'queue'` (default) — the autonomous lane. The task is persisted and the@@ -834,7 +840,7 @@ export async function releaseRetryHold({ agentId, task, success, agentMetadata }* whether an agent actually started or the task is still waiting (no slots,* daemon stopped, …) rather than guessing.*/-export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, sourceWorkspace, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null, reviewerEfforts = null, leaveOpen = false, dispatch = 'queue' }) {+export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, forkHead = null, sourceWorkspace, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null, reviewerEfforts = null, leaveOpen = false, dispatch = 'queue' }) {if (!prUrl || !prBranch) return null;if (prCompletion === PR_COMPLETIONS.LEAVE_OPEN) return null;@@ -959,6 +965,10 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, previewLoopLeaveOpen: leaveOpen,reviewLoopPRUrl: prUrl,reviewLoopPRBranch: prBranch,+ // Fork coordinates for that branch, or null for a same-repo head. The+ // shared reader is `resolveTaskForkHead`, so this key is the generic+ // `forkHead` rather than a review-loop-specific one.+ forkHead: normalizeForkHead(forkHead),reviewLoopPRNumber: parsedPr?.number ?? null,reviewLoopPRHost: parsedPr?.host ?? null,reviewLoopPROwner: parsedPr?.owner ?? null,diff --git a/server/services/appPullRequests.js b/server/services/appPullRequests.jsindex fa627adde4..79731d2b84 100644--- a/server/services/appPullRequests.js+++ b/server/services/appPullRequests.js@@ -14,14 +14,20 @@ import { execGh, ensureForgeReachable } from './github.js';import { execGlabJson } from './gitlab.js';import { resolveAppForgeTarget } from '../lib/workTracker.js';import { safeJSONParse } from '../lib/fileUtils.js';+import { forkHeadFromGithubPr } from '../lib/forkHead.js';const GH_LIST_LIMIT = 200;const GL_PER_PAGE = 100;+// `isCrossRepository`/`maintainerCanModify`/`headRepository*` are what make an+// EXTERNAL contribution actionable: a fork PR's head branch has no+// `origin/<headRefName>`, so anything that attaches a worktree to it needs the+// fork's own address (#6064). They are free on this same call.const GH_PR_FIELDS = ['number', 'title', 'author', 'url', 'createdAt', 'updatedAt', 'isDraft','headRefName', 'baseRefName', 'reviewDecision', 'mergeStateStatus',- 'mergeable', 'statusCheckRollup', 'labels'+ 'mergeable', 'statusCheckRollup', 'labels',+ 'isCrossRepository', 'maintainerCanModify', 'headRepository', 'headRepositoryOwner'].join(',');const baseResult = {@@ -70,6 +76,12 @@ function normalizeGithubPullRequest(pr) {checks: Array.isArray(pr?.statusCheckRollup)? pr.statusCheckRollup.filter(Boolean).map(check => normalizeCheck(check)): [],+ // Strict booleans, or null when the forge didn't answer — the same+ // fail-closed reading `resolvePullRequestWriteAccess` expects, so this row+ // can be handed to it without inventing a write-access answer.+ isCrossRepository: typeof pr?.isCrossRepository === 'boolean' ? pr.isCrossRepository : null,+ maintainerCanModify: typeof pr?.maintainerCanModify === 'boolean' ? pr.maintainerCanModify : null,+ forkHead: forkHeadFromGithubPr(pr),};}@@ -111,6 +123,13 @@ function normalizeGitlabPullRequest(mr) {.filter(label => typeof label === 'string' && label): [],checks: normalizeGitlabPipeline(mr),+ // Shape parity with the GitHub row, deliberately unanswered: `glab` reports+ // a fork MR through project ids, not a clone URL, so there is no fork+ // address to hand a worktree. Null (not false) so nothing reads an+ // unimplemented lookup as "this head is ours to push to".+ isCrossRepository: null,+ maintainerCanModify: null,+ forkHead: null,};}diff --git a/server/services/appPullRequests.test.js b/server/services/appPullRequests.test.jsindex 052247dfb8..757a8481aa 100644--- a/server/services/appPullRequests.test.js+++ b/server/services/appPullRequests.test.js@@ -79,6 +79,66 @@ describe('listAppPullRequests', () => {});});+ it('surfaces where a fork PR\'s head branch lives, so a worktree can attach to it (#6064)', async () => {+ // A cross-repository head has no `origin/<headRefName>`; without these+ // coordinates every "work on this PR's branch" action fails at workspace+ // prep, which is every external contribution.+ execGh.mockResolvedValue(JSON.stringify([{+ number: 21,+ title: 'Contributed fix',+ url: 'https://github.com/acme/widget/pull/21',+ author: { login: 'contributor' },+ headRefName: 'contributor/fix-thing',+ baseRefName: 'main',+ isCrossRepository: true,+ maintainerCanModify: true,+ headRepository: { name: 'widget', nameWithOwner: 'contributor/widget' },+ headRepositoryOwner: { login: 'contributor' },+ }]));++ const result = await listAppPullRequests(APP);++ expect(execGh.mock.calls[0][0].join(' ')).toContain('isCrossRepository');+ expect(result.pullRequests[0]).toMatchObject({+ isCrossRepository: true,+ maintainerCanModify: true,+ // Composed from the PR's OWN origin, so a GitHub Enterprise fork resolves+ // to that host rather than github.com.+ forkHead: { remoteUrl: 'https://github.com/contributor/widget.git', ownerLogin: 'contributor' },+ });+ });++ it('leaves fork coordinates null for a same-repo head, which origin already resolves', async () => {+ execGh.mockResolvedValue(JSON.stringify([{+ number: 22,+ title: 'In-repo fix',+ url: 'https://github.com/acme/widget/pull/22',+ headRefName: 'fix/in-repo',+ isCrossRepository: false,+ maintainerCanModify: false,+ headRepository: { name: 'widget', nameWithOwner: 'acme/widget' },+ headRepositoryOwner: { login: 'acme' },+ }]));++ const result = await listAppPullRequests(APP);++ expect(result.pullRequests[0]).toMatchObject({ isCrossRepository: false, forkHead: null });+ });++ it('reports an unanswered head relationship as null, never as false', async () => {+ // An older `gh`, or a partial read: `resolvePullRequestWriteAccess` reads+ // this row and must land on UNKNOWN rather than on "this head is ours".+ execGh.mockResolvedValue(JSON.stringify([{+ number: 23, title: 'Old gh', url: 'https://github.com/acme/widget/pull/23', headRefName: 'x',+ }]));++ const result = await listAppPullRequests(APP);++ expect(result.pullRequests[0]).toMatchObject({+ isCrossRepository: null, maintainerCanModify: null, forkHead: null,+ });+ });+it('keeps an answered empty GitHub list distinct from a failed read', async () => {execGh.mockResolvedValue('[]');diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex bfc13eba73..fd18b9b10a 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -1707,6 +1707,33 @@ describe('spawnReviewLoopFollowUp', () => {expect(addTask.mock.calls[0][0].metadata.app).toBe('example-app');});+ it('persists fork coordinates so the follow-up can attach a worktree to a fork PR head (#6064)', async () => {+ // A fork head has no `origin/<branch>`, so without these the follow-up is+ // queued and then blocked at workspace prep. The key is the generic+ // `forkHead` that `resolveTaskForkHead` reads for every producer.+ await spawnReviewLoopFollowUp({+ originalAgentId: 'agent-1',+ originalTask: { id: 'task-1', metadata: {}, description: 'X' },+ prUrl: 'https://github.com/o/r/pull/9',+ prBranch: 'contributor/fix-thing',+ forkHead: { remoteUrl: 'https://github.com/contributor/r.git', ownerLogin: 'contributor' },+ sourceWorkspace: '/ws',+ });+ expect(addTask.mock.calls[0][0].metadata).toMatchObject({+ reviewLoopPRBranch: 'contributor/fix-thing',+ forkHead: { remoteUrl: 'https://github.com/contributor/r.git', ownerLogin: 'contributor' },+ });+ });++ it('stores null fork coordinates for a same-repo PR branch', async () => {+ await spawnReviewLoopFollowUp({+ originalAgentId: 'agent-1',+ originalTask: { id: 'task-1', metadata: {}, description: 'X' },+ prUrl: 'https://github.com/o/r/pull/9', prBranch: 'cos/task-1/agent-1', sourceWorkspace: '/ws',+ });+ expect(addTask.mock.calls[0][0].metadata.forkHead).toBeNull();+ });+// Dispatch ownership: an autonomous follow-up belongs to the auto-run-gated// dequeue, while an explicitly requested one must not wait for it.it('leaves the spawn to the dequeue by default', async () => {diff --git a/server/services/issueWatcher.js b/server/services/issueWatcher.jsindex 3f50b91bda..ef5001ab34 100644--- a/server/services/issueWatcher.js+++ b/server/services/issueWatcher.js@@ -29,6 +29,7 @@ import {} from '../lib/prReviewReport.js';import { githubApiHost, githubRepoSpec } from '../lib/workTracker.js';import { MAX_PR_REMEDIATION_ATTEMPTS, PR_HANDBACK, PR_REVIEW_OUTCOME, resolveHandbackDisposition, resolvePullRequestWriteAccess } from '../lib/prHandbackPolicy.js';+import { forkHeadFromGithubPr } from '../lib/forkHead.js';import { getAppById, updateApp } from './apps.js';import { execGh, ensureForgeReachable } from './github.js';import { mergePR, resolveForgeForRepo } from './git.js';@@ -412,6 +413,9 @@ async function applyPullRequestHandback({headSha,headRefName: pr.headRefName,authorLogin: login,+ // Where that head branch lives when the PR came from a fork — the+ // remediation worktree has no `origin/<branch>` to attach to otherwise.+ forkHead: forkHeadFromGithubPr(pr),},writeAccess,reason,@@ -494,9 +498,11 @@ async function readPullRequest(ctx, number) {// `isCrossRepository`/`maintainerCanModify` decide who owns a PR the// coordinator did not merge: with write access on the head branch PortOS// lands it itself, without it the PR goes to the opener's queue- // (`prHandbackPolicy.js`). `assignees` keeps that assignment idempotent- // across scheduled sweeps.- '--json', 'number,title,body,url,state,isDraft,author,assignees,labels,files,additions,deletions,baseRefName,baseRefOid,headRefName,headRefOid,isCrossRepository,maintainerCanModify,mergeable,mergeStateStatus,statusCheckRollup',+ // (`prHandbackPolicy.js`). `headRepository`/`headRepositoryOwner` are where+ // a fork's head branch actually lives, which is what lets the remediation+ // agent's worktree attach to it at all (#6064). `assignees` keeps that+ // assignment idempotent across scheduled sweeps.+ '--json', 'number,title,body,url,state,isDraft,author,assignees,labels,files,additions,deletions,baseRefName,baseRefOid,headRefName,headRefOid,isCrossRepository,maintainerCanModify,headRepository,headRepositoryOwner,mergeable,mergeStateStatus,statusCheckRollup',], ctx);}diff --git a/server/services/prRemediationFollowUp.js b/server/services/prRemediationFollowUp.jsindex 7ad89daef5..25e76d8ba0 100644--- a/server/services/prRemediationFollowUp.js+++ b/server/services/prRemediationFollowUp.js@@ -15,15 +15,14 @@* tells the agent to read the review off GitHub. Titles, descriptions, and* diffs stay where the Stage 1 model-abuse boundary screened them; nothing* re-enters an agent prompt through this side door.- * - **The work happens in a throwaway worktree.** The task runs in the app's- * live checkout (`useWorktree: false`) because a fork branch has no- * `origin/<branch>` for PortOS's own worktree attach to resolve — so the- * agent must create its own with `gh pr checkout`. A bare `gh pr checkout`- * in the live checkout would hijack whatever the user has open, which is why- * the procedure below spells out the worktree. Issue #6064 fixes that gap in- * `worktreeManager.createWorktree` for every caller; once it lands, this- * task becomes `useWorktree: true` with the fork coordinates and step 2 of- * the procedure goes away.+ * - **The work happens in a throwaway worktree PortOS provisions.** The task+ * ships `useWorktree: true` plus the PR's head branch and — for a fork PR —+ * its `forkHead` coordinates, so the shared attach in+ * `worktreeManager.createWorktree` checks the branch out on a fork remote and+ * leaves `git push` aimed at the CONTRIBUTOR's fork (#6064). This used to be+ * prose telling the agent to run `git worktree add` + `gh pr checkout`+ * itself, in the app's live checkout: unenforced, and one forgotten step away+ * from hijacking whatever branch the user had open.* - **No provider pin is inherited.** Stage 3's provider is pinned to a* sandboxed, network-denied review recipe. This task is the opposite job — a* coding harness with forge credentials — so it resolves through the normal@@ -41,31 +40,26 @@* failed to land the PR.*/-import { join } from 'path';import { emitLog } from './cosEvents.js';import { addTask } from './cos.js';import { buildCiMergeGateSteps } from './promptSections/reviewLifecycle.js';-import { PATHS } from '../lib/fileUtils.js';+import { normalizeForkHead } from '../lib/forkHead.js';import { PR_WRITE_ACCESS } from '../lib/prHandbackPolicy.js';-import { kebabCase } from '../lib/textUtils.js';/*** The remediation procedure. `reason` names why the PR did not land, so the* agent starts from the right end of the problem instead of re-deriving it.*/-function renderContext({ app, repoFullName, number, url, headRefName, authorLogin, reason, writeAccess }) {- // `PATHS.worktrees` is shared by every app this install manages, so the app- // name has to be in the path or two apps' PR #7 collide.- const worktreePath = join(PATHS.worktrees, `pr-fix-${kebabCase(app.name) || 'app'}-${number}`);+function renderContext({ repoFullName, number, url, headRefName, authorLogin, reason, writeAccess }) {// Both halves stay conditional: a same-repo head has no contributor who "left// the branch writable", and saying otherwise puts a false claim about a real// person into an operator-facing instruction.const accessNote = writeAccess === PR_WRITE_ACCESS.OWN_REPO? `The head branch \`${headRefName}\` lives in ${repoFullName} itself, so it is yours to push to and \`git push\` goes to origin.`- : `@${authorLogin} left the head branch writable by maintainers ("Allow edits by maintainers"), and \`${headRefName}\` lives in their FORK. \`gh pr checkout\` sets its push remote for you — push to that, never to origin, and never open a second PR.`;+ : `@${authorLogin} left the head branch writable by maintainers ("Allow edits by maintainers"), and \`${headRefName}\` lives in their FORK. Your worktree's branch already tracks that fork, so a plain \`git push\` goes there — never re-point it at origin, and never open a second PR.`;// The shared gate owns everything from "wait for CI" through "confirm MERGED",// including clearing conflicts, so step 3 stays scoped to the review itself.- const { lines: mergeGate } = buildCiMergeGateSteps(5, {+ const { lines: mergeGate } = buildCiMergeGateSteps(4, {prRef: `${number} --repo ${repoFullName}`,forge: 'github',alreadyMergedHint: '',@@ -81,14 +75,9 @@ function renderContext({ app, repoFullName, number, url, headRefName, authorLogi'## Procedure','',`1. Read the review PortOS already posted: \`gh pr view ${number} --repo ${repoFullName} --comments\` and \`gh api repos/${repoFullName}/pulls/${number}/comments\`. The blocking inline comments are the work order; non-blocking ones are follow-up notes, not this task's scope.`,- `2. Work in a THROWAWAY WORKTREE, never in ${app.repoPath} directly — this task runs in the app's live checkout and a bare \`gh pr checkout\` there hijacks whatever branch the user has open:`,- ' ```bash',- ` git -C ${app.repoPath} worktree add --detach ${worktreePath}`,- ` cd ${worktreePath} && gh pr checkout ${number} --repo ${repoFullName}`,- ' ```',- ` ${accessNote}`,+ `2. You are ALREADY in an isolated worktree with \`${headRefName}\` checked out — PortOS attached it for you. Do not check the PR out again, do not create another worktree, and do not switch branches. ${accessNote}`,'3. Fix ONLY what the review asked for. Do not bundle refactors, unrelated cleanups, or your own review opinions onto a contributor\'s branch.',- '4. Run the repo\'s own tests for the code you touched and confirm they pass, then commit with a message that says what you fixed and that it answers the review, and push to the PR\'s own branch. Never force-push over the contributor\'s commits unless a rebase you performed requires it, and never open a new PR.',+ `4. Run the repo's own tests for the code you touched and confirm they pass, then commit with a message that says what you fixed and that it answers the review, and push to the PR's own branch (\`git push\` — its upstream is already the right remote). Never force-push over the contributor's commits unless a rebase you performed requires it, and never open a new PR.`,...mergeGate,'','## Stop instead of merging if',@@ -97,8 +86,6 @@ function renderContext({ app, repoFullName, number, url, headRefName, authorLogi'- The branch stops being writable, or the contributor pushes while you are working.','',`In either case — and in the leave-it-open cases the merge steps above already name — post one comment on the PR explaining exactly what is blocking, assign it back with \`gh pr edit ${number} --repo ${repoFullName} --add-assignee ${authorLogin}\`, and finish. A clear hand-back is a successful outcome for this task; a half-fixed branch is not.`,- '',- `Clean up the worktree when you are done: \`git -C ${app.repoPath} worktree remove --force ${worktreePath}\`.`,].join('\n');}@@ -123,8 +110,12 @@ export const PR_REMEDIATION_SPAWN = Object.freeze({*/export async function spawnPrRemediationFollowUp({ app, repoFullName, pullRequest, writeAccess, reason } = {}) {const number = pullRequest?.number;+ const headRefName = typeof pullRequest?.headRefName === 'string' ? pullRequest.headRefName.trim() : '';const authorLogin = typeof pullRequest?.authorLogin === 'string' ? pullRequest.authorLogin.trim() : '';- if (!app?.id || !app?.repoPath || !repoFullName || !Number.isInteger(number) || !authorLogin) {+ // `headRefName` joins the required set now that PortOS attaches the worktree+ // itself: without the branch name there is nothing to check out, and cutting a+ // fresh branch would put the fixes somewhere the PR never sees.+ if (!app?.id || !app?.repoPath || !repoFullName || !Number.isInteger(number) || !authorLogin || !headRefName) {return { status: PR_REMEDIATION_SPAWN.FAILED, task: null };}@@ -146,20 +137,25 @@ export async function spawnPrRemediationFollowUp({ app, repoFullName, pullRequesprRemediationHeadSha: pullRequest.headSha || null,prRemediationAuthorLogin: authorLogin,prRemediationWriteAccess: writeAccess || null,+ // Attach the worktree to the PR's own head branch rather than cutting a+ // fresh one — the deliverable is commits ON that branch. `forkHead` is how+ // the attach reaches a branch that lives in a fork and therefore has no+ // `origin/<branch>`; null for a same-repo head, where origin resolves it.+ existingBranch: headRefName,+ forkHead: normalizeForkHead(pullRequest?.forkHead),},context: renderContext({- app,repoFullName,number,url: pullRequest.url || `https://github.com/${repoFullName}/pull/${number}`,- headRefName: pullRequest.headRefName || '',+ headRefName,authorLogin,reason: reason || 'the review did not clear it for an automatic merge',writeAccess,}),- // The agent owns its own throwaway worktree (see the module header): PortOS- // cannot attach one to a fork branch, which has no origin/<branch> ref.- useWorktree: false,+ // PortOS provisions the worktree and checks out the PR's head branch, fork+ // or not (see the module header).+ useWorktree: true,// The PR already exists. Cleanup must not open a second one.openPR: false,};diff --git a/server/services/prRemediationFollowUp.test.js b/server/services/prRemediationFollowUp.test.jsindex 5c79573c99..baaff751ab 100644--- a/server/services/prRemediationFollowUp.test.js+++ b/server/services/prRemediationFollowUp.test.js@@ -14,6 +14,7 @@ const PULL_REQUEST = {headRefName: 'contributor/update',baseRefName: 'main',authorLogin: 'contributor',+ forkHead: { remoteUrl: 'https://github.com/contributor/r.git', ownerLogin: 'contributor' },};const spawn = (overrides = {}) => spawnPrRemediationFollowUp({@@ -40,9 +41,10 @@ describe('spawnPrRemediationFollowUp', () => {expect(task).toMatchObject({app: APP.id,priority: 'HIGH',- // PortOS cannot attach a worktree to a fork branch, so the agent makes its- // own; the PR already exists, so cleanup must not open a second one.- useWorktree: false,+ // PortOS provisions the worktree and attaches it to the PR's own head+ // branch — including a fork head, via `forkHead` (#6064). The PR already+ // exists, so cleanup must not open a second one.+ useWorktree: true,openPR: false,metadata: {prRemediationFollowUp: true,@@ -50,6 +52,8 @@ describe('spawnPrRemediationFollowUp', () => {prRemediationRepoFullName: 'o/r',prRemediationAuthorLogin: 'contributor',prRemediationWriteAccess: 'fork-maintainer-modifiable',+ existingBranch: 'contributor/update',+ forkHead: { remoteUrl: 'https://github.com/contributor/r.git', ownerLogin: 'contributor' },},});// The first line carries the PR number so addTask's per-app dedup keeps a@@ -57,12 +61,17 @@ describe('spawnPrRemediationFollowUp', () => {expect(task.description).toContain('#7');});- it('tells the agent to check the PR out in a throwaway worktree and merge it', async () => {+ it('tells the agent the branch is already checked out rather than to fetch it itself', async () => {+ // The prose worktree procedure was the workaround for a worktree layer that+ // could not attach to a fork head. Now that it can (#6064), leaving the+ // instructions in place would have the agent build a SECOND worktree.await spawn();const { context } = addTaskMock.mock.calls[0][0];- expect(context).toContain('gh pr checkout 7 --repo o/r');- expect(context).toContain('worktree add --detach');+ expect(context).toContain('ALREADY in an isolated worktree');+ expect(context).not.toContain('gh pr checkout');+ expect(context).not.toContain('worktree add');+ expect(context).not.toContain('worktree remove');expect(context).toContain('gh pr merge 7 --repo o/r --merge');// Push rights on a fork are not permission to delete the contributor's// branch — the shared merge gate must be asked for `deleteBranch: false`.@@ -85,6 +94,16 @@ describe('spawnPrRemediationFollowUp', () => {const fork = addTaskMock.mock.calls[0][0].context;expect(fork).toContain('@contributor left the head branch writable by maintainers');expect(fork).toContain('lives in their FORK');+ expect(fork).toContain('already tracks that fork');+ });++ it('carries no fork remote for a same-repo head, which origin already resolves', async () => {+ await spawn({ pullRequest: { ...PULL_REQUEST, forkHead: null }, writeAccess: 'own-repo' });++ expect(addTaskMock.mock.calls[0][0].metadata).toMatchObject({+ existingBranch: 'contributor/update',+ forkHead: null,+ });});// The screened title/body/diff stay on the far side of the Stage 1 boundary:@@ -121,6 +140,9 @@ describe('spawnPrRemediationFollowUp', () => {['no repository', { repoFullName: '' }],['no PR number', { pullRequest: { ...PULL_REQUEST, number: null } }],['no author to hand back to', { pullRequest: { ...PULL_REQUEST, authorLogin: ' ' } }],+ // Without the branch name there is nothing for the worktree to check out,+ // and cutting a fresh branch would put the fixes where the PR never sees them.+ ['no head branch to attach a worktree to', { pullRequest: { ...PULL_REQUEST, headRefName: '' } }],])('refuses to queue with %s', async (_label, overrides) => {expect(await spawn(overrides)).toEqual({ status: PR_REMEDIATION_SPAWN.FAILED, task: null });expect(addTaskMock).not.toHaveBeenCalled();diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex 60c06dba6e..958d8bbdd8 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -17,6 +17,7 @@ import { DONE_SENTINEL_NAME, doneSentinelName } from '../lib/agentSentinel.js';import { execGit } from '../lib/execGit.js';import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';+import { forkRemoteName, normalizeForkHead } from '../lib/forkHead.js';import { isHumanClaimWorktree, worktreeAgentId, worktreeOwnershipReason } from '../lib/worktreeOwnership.js';import { ensureInstanceId } from './instances.js';@@ -342,6 +343,67 @@ export function shouldRefuseDefaultBranchMerge(currentBranch, defaultBranch) {return currentBranch !== defaultBranch;}+/**+ * Point a deterministic remote at the fork that holds a cross-repository PR's+ * head branch, fetch that branch, and hand back the remote's name.+ *+ * A fork PR's branch has no `origin/<branch>` — the forge exposes its tip only+ * as the read-only `refs/pull/<n>/head`, which cannot be pushed back to — so a+ * worktree attach needs a second address for it. The coordinates arrive from a+ * caller that already read the PR (`normalizeForkHead`); this layer never calls+ * a forge, which is why it takes a URL rather than a PR number.+ *+ * The remote is named from the OWNER, not from the run, so a second review+ * round or a retried remediation reuses it instead of accumulating one remote+ * per attach — and so teardown can leave it alone, which is what makes that+ * reuse free. An existing remote pointing somewhere else is re-pointed rather+ * than treated as a conflict.+ *+ * Returns `null` for every unusable outcome (no coordinates, remote wouldn't+ * take, fetch failed, ref still missing afterwards) so the caller falls through+ * to its existing origin-only error instead of attaching to a ref it cannot+ * verify.+ *+ * @param {string} sourceWorkspace - the parent git repository+ * @param {unknown} forkHead - `{ remoteUrl, ownerLogin }` from the PR read+ * @param {string} branchName - the PR's head branch, as named in the fork+ * @returns {Promise<string|null>} the fork remote's name, or null+ */+async function ensureForkRemote(sourceWorkspace, forkHead, branchName) {+ const coordinates = normalizeForkHead(forkHead);+ if (!coordinates) return null;+ const remoteName = forkRemoteName(coordinates.ownerLogin);+ if (!remoteName) return null;++ // Three outcomes, not two: `null` is "no such remote" (add it), an equal URL+ // is "already correct" (touch nothing), and a different URL is a stale remote+ // from a contributor who renamed or moved their fork (re-point it).+ const existingUrl = await execGit(['remote', 'get-url', remoteName], sourceWorkspace, { ignoreExitCode: true })+ .then(r => (r.exitCode === 0 ? (r.stdout || '').trim() : null))+ .catch(() => null);+ const remoteOp = existingUrl === null+ ? ['remote', 'add', remoteName, coordinates.remoteUrl]+ : (existingUrl === coordinates.remoteUrl ? null : ['remote', 'set-url', remoteName, coordinates.remoteUrl]);+ if (remoteOp) {+ const pointed = await execGit(remoteOp, sourceWorkspace).then(() => true).catch(err => {+ console.log(`⚠️ Could not point ${remoteName} at the fork holding ${branchName}: ${err.message}`);+ return false;+ });+ if (!pointed) return null;+ }++ await execGit(['fetch', remoteName, branchName], sourceWorkspace).catch(err => {+ console.log(`⚠️ Fork fetch of ${remoteName}/${branchName} failed: ${err.message}`);+ });+ // Verify rather than trust the fetch's exit code: a fetch that reported+ // success but left no remote-tracking ref would otherwise send `worktree add`+ // at a start point git resolves somewhere else entirely.+ const refExists = await execGit(['rev-parse', '--verify', `${remoteName}/${branchName}`], sourceWorkspace, { ignoreExitCode: true })+ .then(r => r.exitCode === 0)+ .catch(() => false);+ return refExists ? remoteName : null;+}+/*** Create a git worktree for an agent.*@@ -355,12 +417,18 @@ export function shouldRefuseDefaultBranchMerge(currentBranch, defaultBranch) {* branch instead of creating a new one — used for the Copilot review-loop follow-up* agent that needs to address comments on a PR branch the previous agent just pushed.*+ * That branch is resolved local → `origin/<branch>` → `options.forkHead`. The third+ * step is what makes an EXTERNAL contribution reachable: a fork PR's head has no+ * `origin/<branch>` at all, so without it every "work on this PR's branch" path+ * failed at workspace prep for exactly the PRs external contributors open (#6064).+ ** @param {string} agentId - The agent identifier (used for branch/directory naming)* @param {string} sourceWorkspace - The original git repository path* @param {string} taskId - Task identifier (included in branch name for traceability)* @param {object} options - Optional configuration* @param {string} options.baseBranch - Branch to base the worktree on (auto-detected if omitted)* @param {string} options.existingBranch - Pre-existing branch to attach (creates from origin/<branch> if no local copy)+ * @param {{remoteUrl: string, ownerLogin: string}} options.forkHead - Where `existingBranch` lives when it is a FORK PR's head, which has no `origin/<branch>`. Consulted only after the local and origin lookups both miss; omitting it preserves today's exact behavior, error message included.* @param {string} options.planId - PLAN.md item slug ID — when provided, spliced into the branch name as `cos/<taskId>/<planId>/<agentId>` so other agents can detect this item is in flight by scanning branches/PRs* @returns {{ worktreePath: string, branchName: string, baseBranch: string|null, existingBranch?: boolean }} paths for the new worktree*/@@ -412,17 +480,32 @@ async function createWorktreeUnlocked(agentId, sourceWorkspace, taskId, optionsconst remoteExists = await execGit(['rev-parse', '--verify', `origin/${branchName}`], sourceWorkspace, { ignoreExitCode: true }).then((r) => r.exitCode === 0).catch(() => false);- if (!remoteExists) {+ // Third and last resolve step: a FORK PR's head lives in the contributor's+ // repository, so `origin/<branch>` legitimately does not exist. Reached+ // only when the caller supplied coordinates AND the two lookups above+ // missed, so a caller that passes no `forkHead` still gets the exact+ // error below rather than a new code path (#6064).+ const forkRemote = remoteExists ? null : await ensureForkRemote(sourceWorkspace, options.forkHead, branchName);+ if (!remoteExists && !forkRemote) {throw new Error(`Cannot attach worktree to ${branchName}: branch missing locally and origin/${branchName} unavailable${fetchSucceeded ? '' : ' (fetch failed)'}`);}- // Use -B (force-create) so we don't fail if a stale local ref exists; track origin.+ // The start point decides the branch's upstream, and on the fork path that+ // is the whole point: tracking `<fork-remote>/<branch>` is what sends a+ // later `git push` to the CONTRIBUTOR's fork. Tracking origin here would+ // push their commits into the upstream repository instead — the #4172+ // failure mode, one remote over.+ const startPoint = forkRemote ? `${forkRemote}/${branchName}` : `origin/${branchName}`;+ // Use -B (force-create) so we don't fail if a stale local ref exists.// Attach path re-uses an existing branch, so no orphan-branch cleanup on failure.- await addWorktreeWithRetry(['worktree', 'add', '-B', branchName, worktreePath, `origin/${branchName}`], sourceWorkspace);+ await addWorktreeWithRetry(['worktree', 'add', '-B', branchName, worktreePath, startPoint], sourceWorkspace);+ if (forkRemote) console.log(`🍴 Attached ${branchName} from fork remote ${forkRemote} (no origin/${branchName})`);}// Re-attaching a branch a PREVIOUS run created — which, before #4172, may// have been left tracking `refs/heads/main`. Repair it before the agent (and- // its `/do:pr`) touches it. Tracking `origin/<branchName>` is the healthy- // shape here and passes untouched.+ // its `/do:pr`) touches it. The guard's invariant is on the `merge` REF, not+ // on the remote, so `origin/<branchName>` and `<fork-remote>/<branchName>`+ // both pass untouched — which is required: dropping the fork upstream would+ // aim a config-derived push back at origin.await enforceUpstreamOrUndoAdd(sourceWorkspace, branchName, worktreePath, { deleteBranch: false });console.log(`🌳 Created worktree for ${agentId} at ${worktreePath} on existing branch ${branchName}`);return { worktreePath, branchName, baseBranch: null, existingBranch: true, instanceId };diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex b170c8068c..2dd02a9444 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -1078,7 +1078,10 @@ describe('createWorktree upstream safety (#4172)', () => {// git is proved in lib/branchUpstreamGuard.test.js (real repos, real config).// What can only be checked here is that createWorktree actually reaches for// it — the flag on the add, and the guard on the result.- function scriptGit({ mergeReadings = [] } = {}) {+ // `originHasBranch` / `forkRemoteUrl` / `forkRefResolves` script the three+ // lookups the existingBranch resolve order makes, so a test can put the tree+ // in the fork-PR state: no local branch, no origin ref, a fork that answers.+ function scriptGit({ mergeReadings = [], originHasBranch = true, forkRemoteUrl = null, forkRefResolves = true } = {}) {const readings = [...mergeReadings];execGitMock.mockReset();execGitMock.mockImplementation((args) => {@@ -1088,6 +1091,16 @@ describe('createWorktree upstream safety (#4172)', () => {// must read as "no upstream" rather than as an error.return Promise.resolve({ stdout: answer, stderr: '', exitCode: answer ? 0 : 1 });}+ if (args[0] === 'rev-parse' && args[1] === '--verify') {+ const ref = args[2] || '';+ const resolves = ref.startsWith('origin/') ? originHasBranch : forkRefResolves;+ return Promise.resolve({ stdout: resolves ? 'deadbeef' : '', stderr: '', exitCode: resolves ? 0 : 1 });+ }+ if (args[0] === 'remote' && args[1] === 'get-url') {+ return forkRemoteUrl+ ? Promise.resolve({ stdout: `${forkRemoteUrl}\n`, stderr: '', exitCode: 0 })+ : Promise.resolve({ stdout: '', stderr: 'No such remote', exitCode: 2 });+ }return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });});}@@ -1148,6 +1161,96 @@ describe('createWorktree upstream safety (#4172)', () => {expect(argsFor(a => a[0] === 'branch' && a[1] === '-D')).toHaveLength(0);});+ it('attaches a FORK PR head from a fork remote and leaves its upstream on the fork (#6064)', async () => {+ // The regression: a fork PR's head has no `origin/<branch>` at all, so+ // before this every "work on this PR's branch" path threw at workspace prep+ // for exactly the PRs external contributors open.+ scriptGit({ originHasBranch: false });++ await createWorktree('agent-fork', '/repo', 'task-fork', {+ existingBranch: 'contributor/fix-thing',+ forkHead: { remoteUrl: 'https://github.com/contributor/widget.git', ownerLogin: 'contributor' },+ });++ expect(argsFor(a => a[0] === 'remote' && a[1] === 'add'))+ .toEqual([['remote', 'add', 'fork-contributor', 'https://github.com/contributor/widget.git']]);+ expect(argsFor(a => a[0] === 'fetch' && a[1] === 'fork-contributor'))+ .toEqual([['fetch', 'fork-contributor', 'contributor/fix-thing']]);+ // The start point is the whole point: it is what makes the branch track the+ // CONTRIBUTOR's fork, so a later `git push` lands there and not on upstream.+ const [add] = argsFor(a => a[0] === 'worktree' && a[1] === 'add');+ expect(add).toEqual([+ 'worktree', 'add', '-B', 'contributor/fix-thing',+ join(PATHS.worktrees, 'agent-fork'), 'fork-contributor/contributor/fix-thing',+ ]);+ // ...and the #4172 guard must not "repair" that fork upstream away.+ expect(argsFor(a => a[0] === 'branch' && a[1] === '--unset-upstream')).toHaveLength(0);+ });++ it('re-points a stale fork remote instead of duplicating it or failing', async () => {+ // The remote is named from the OWNER so re-runs reuse it; a contributor who+ // renamed or moved their fork leaves the recorded URL stale.+ scriptGit({ originHasBranch: false, forkRemoteUrl: 'https://github.com/contributor/old-name.git' });++ await createWorktree('agent-fork2', '/repo', 'task-fork2', {+ existingBranch: 'contributor/fix-thing',+ forkHead: { remoteUrl: 'https://github.com/contributor/widget.git', ownerLogin: 'contributor' },+ });++ expect(argsFor(a => a[0] === 'remote' && a[1] === 'add')).toHaveLength(0);+ expect(argsFor(a => a[0] === 'remote' && a[1] === 'set-url'))+ .toEqual([['remote', 'set-url', 'fork-contributor', 'https://github.com/contributor/widget.git']]);+ });++ it('leaves a fork remote alone when it already points at the right URL', async () => {+ scriptGit({ originHasBranch: false, forkRemoteUrl: 'https://github.com/contributor/widget.git' });++ await createWorktree('agent-fork3', '/repo', 'task-fork3', {+ existingBranch: 'contributor/fix-thing',+ forkHead: { remoteUrl: 'https://github.com/contributor/widget.git', ownerLogin: 'contributor' },+ });++ expect(argsFor(a => a[0] === 'remote' && (a[1] === 'add' || a[1] === 'set-url'))).toHaveLength(0);+ const [add] = argsFor(a => a[0] === 'worktree' && a[1] === 'add');+ expect(add).toContain('fork-contributor/contributor/fix-thing');+ });++ it('still throws today\'s exact error when no forkHead is supplied', async () => {+ // The fork path is a third FALLBACK: a caller that passes no coordinates+ // must get the pre-#6064 behavior, message included.+ scriptGit({ originHasBranch: false });++ await expect(createWorktree('agent-fork4', '/repo', 'task-fork4', { existingBranch: 'contributor/fix-thing' }))+ .rejects.toThrow('Cannot attach worktree to contributor/fix-thing: branch missing locally and origin/contributor/fix-thing unavailable');++ expect(argsFor(a => a[0] === 'remote')).toHaveLength(0);+ expect(argsFor(a => a[0] === 'worktree' && a[1] === 'add')).toHaveLength(0);+ });++ it('falls back to the origin-only error when the fork fetch leaves no ref', async () => {+ // A fetch that "succeeded" but produced no remote-tracking ref must not send+ // `worktree add` at a start point git would resolve somewhere else.+ scriptGit({ originHasBranch: false, forkRefResolves: false });++ await expect(createWorktree('agent-fork5', '/repo', 'task-fork5', {+ existingBranch: 'contributor/fix-thing',+ forkHead: { remoteUrl: 'https://github.com/contributor/widget.git', ownerLogin: 'contributor' },+ })).rejects.toThrow(/branch missing locally and origin\/contributor\/fix-thing unavailable/);++ expect(argsFor(a => a[0] === 'worktree' && a[1] === 'add')).toHaveLength(0);+ });++ it('never consults the fork when origin already has the branch', async () => {+ await createWorktree('agent-fork6', '/repo', 'task-fork6', {+ existingBranch: 'shared/branch',+ forkHead: { remoteUrl: 'https://github.com/contributor/widget.git', ownerLogin: 'contributor' },+ });++ expect(argsFor(a => a[0] === 'remote')).toHaveLength(0);+ const [add] = argsFor(a => a[0] === 'worktree' && a[1] === 'add');+ expect(add).toContain('origin/shared/branch');+ });+it('checks the re-attached branch of an existingBranch worktree too', async () => {// Branches created before this fix keep their bad upstream; a review-loop// agent re-attaching to one must not inherit a push aimed at main.