Skip to content

fix(core): prevent worktree cross-registration across projects - #61493

Closed
rishikeshgowdakk wants to merge 10 commits into
anomalyco:devfrom
rishikeshgowdakk:worktree-cross-registration
Closed

rishikeshgowdakk wants to merge 10 commits into
anomalyco:devfrom
rishikeshgowdakk:worktree-cross-registration

Conversation

@rishikeshgowdakk

@rishikeshgowdakk rishikeshgowdakk commented Nov 3, 2026 •

Copy link
Copy Markdown

Issue for this PR

Closes #60847

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

Fixes two issues causing worktree cross-registration and bare repository spam when repositories have sibling worktrees:

  1. Git.worktree.list parsed porcelain output by simply splitting on newlines matching worktree , ignoring attribute lines. In bare-backed worktree setups, the bare repository entry was parsed as kind: "main". This led Project.resolve to treat the bare directory as the canonical project root, and subsequent discovery passes logged Worktree.DirectoryUnavailableError when probing the bare repo.
    • Fixed by parsing each porcelain record block and skipping entries flagged with bare.
  2. Worktree.refresh enumerates worktrees via registered strategies (including git worktree list). In setups where sibling checkouts of the same repository belong to different projects, each project's refresh pass discovered sibling checkout roots and added them into the current project's worktree table. This cross-registered directories, mixed session lists, and caused sessions opened across project boundaries to render title-only.
    • Fixed by checking ProjectTable.worktree and WorktreeTable to exclude foreign project roots from discovery and prune any foreign roots previously recorded under the current project. Also preserves the current project root as unowned (strategy: null).

How did you verify your code works?

  • Added omits the bare repository entry when listing worktrees in packages/core/test/git.test.ts.
  • Added uses a checkout, not the bare repository, as the canonical directory in packages/core/test/worktree.test.ts.
  • Added refresh does not claim another project's checkout or the bare repository in packages/core/test/worktree.test.ts.
  • Added refresh prunes foreign project roots that were previously registered in packages/core/test/worktree.test.ts.
  • Ran bun run script/test.ts test/git.test.ts test/worktree.test.ts (60 pass, 0 fail).
  • Ran package typecheck (bun run --cwd packages/core typecheck), oxlint, and full pre-push bun run check.

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR

Added by the opencode bot (AI-generated).

Related: #59371, #58108, #57985, #57989

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fix works for the reported setup. I ran the #60847 reproduction from source. On the base, each project lists the other project's root and BARE.git. With this PR, A lists only A and B only B, and no bare-repo row is stored. git.test.ts and worktree.test.ts pass (60/60), and tsc -b is clean.

Public API: unchanged. The /api/worktree routes keep their shape; only which rows they return changes.

Concerns, details inline:

  1. Existing projects whose root is already the bare repo (every v2 install of a bare-backed setup so far) aren't migrated. I created a project with the base build and reopened it with this PR: its root stays BARE.git, the BARE.git row stays, and the discovery warning still logs.
  2. foreign treats every directory any other project row has registered as off-limits. With duplicate or stale project rows for the same repo (#59371, #57985), the project that registered a directory first keeps it for good, and the real owner can never rediscover it.
  3. Skipping the bare block means no entry is ever main, so the canonical directory becomes whichever checkout is opened first.

Related: #59371, #58108, #57985

Comment thread packages/core/src/git.ts Resolved
Comment thread packages/core/src/worktree.ts Outdated
foreign.add(resolved)
}
}
const otherWorktrees = yield* db

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This marks every directory that any other project row has registered as foreign. Ownership then goes to whichever project registered the directory first, not to the project the directory actually belongs to. With duplicate project rows for one repo (#59371), or a stale row left after the project id changes (#57985, e.g. when a remote is added), the newer project can never discover its own linked worktrees again. Archived projects count too. Excluding other projects' roots (the ProjectTable check above) is enough for #60847. Could this part be dropped, or limited to rows of non-archived projects?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dropped the WorktreeTable cross-check entirely and scoped foreign strictly to non-archived project roots (isNull(ProjectTable.time_archived)). This avoids stale/duplicate project row interference while cleanly isolating sibling project roots.

}
}
const removed = checked.filter((item) => !item.exists).map((item) => item.directory)
const removed = checked

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Projects that already have the bare repo as their root aren't fixed. persist only replaces the root when the old one no longer exists, and BARE.git still exists. I created a project with the base build and refreshed it with this PR: row.worktree stayed BARE.git, the BARE.git row was kept, and worktree discovery failed was still logged. Please prune unowned rows that are bare repos, or that fail strategy.list with DirectoryUnavailableError, and move such a project's root to a real checkout. Otherwise existing users keep the warning spam the issue reports.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added migration handling in both Project.persist and Worktree.refresh:

  • Git.repo.discover now recognises bare repository paths so worktrees checked out from a bare directory are discovered.
  • Worktree.refresh detects unowned roots that are bare repos or unavailable, migrates ProjectTable.worktree to the first real checkout, publishes Project.Event.Updated, and prunes the bare repo entry from WorktreeTable.
  • Project.persist replaces legacy canonical roots that are bare repos and cleans up their unowned rows.
  • Added test migrates legacy projects whose root was set to a bare repository in worktree.test.ts.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at b5bfcb17a. The #60847 reproduction is still fixed: each project lists only its own checkout, no bare-repo rows are stored and nothing is logged. git.test.ts, worktree.test.ts and project.test.ts pass (91/91), and tsc -b is clean.

Earlier points:

  • First checkout is now main: resolved. With one project backed by a bare repo, opening A and then B makes A the root, and B is stored as git right away.
  • Ownership taken from other projects' worktree rows: resolved. That check is gone, and archived projects no longer count as owners.
  • Projects already rooted at the bare repo: mostly resolved. I created a project with the base build (root BARE.git) and refreshed it with this commit. The root moved to A and the BARE.git row was pruned. One problem remains, see the first point below.

Public API: unchanged.

Remaining concerns (details inline):

  1. The promoted root keeps strategy: "git", so the project's own main checkout can be removed as a worktree. This blocks a merge.
  2. Adding bare-repo detection to Git.repo.discover changes behaviour for every caller. Refresh doesn't need it.
  3. Moving the root off the bare repo is now done in two places, Project.persist and Worktree.refresh.

Related: #59371, #58108, #57985, #57989

Comment thread packages/core/src/worktree.ts Outdated
.run()
.pipe(Effect.orDie)
row.worktree = nextRoot
discovered.set(nextRoot, { directory: nextRoot, strategy: undefined })

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

strategy: undefined doesn't clear the strategy of an existing row. In ops.create, setWhere is sql\false`when no strategy is given, so the conflict update is skipped. In my upgrade test (project created on the base with rootBARE.git, then refreshed with this commit), the new root A kept strategy: "git". Worktree.removeaccepts any row with a strategy, so it would rungit worktree removeon the project's main checkout. The #60847 reproduction shows the same thing: B is project B's root and is stored asgit. The root needs replace: true(or an explicit update) so it ends up unowned. The same applies to thedirectory === row.worktreecase above. A test that checks the promoted root's strategy isnull` would catch this.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 0663419f6f:

  • Worktree.refresh now passes replace: directory === row.worktree ? true : undefined in both the main discovery loop and the migration fallback.
  • In ops.create, setWhere checks isNotNull(WorktreeTable.strategy) when replace: true and strategy is null, ensuring existing rows stored as git (such as project B's root in the projects: worktree discovery cross-registers sibling worktree dirs into other existing projects; affected sessions open title-only #60847 reproduction) have their strategy cleared to null on conflict without firing spurious update events when already unowned.
  • Added test in worktree.test.ts verifying that when a root was previously recorded with strategy: 'git', refresh updates it to strategy: null and Worktree.remove rejects it.

Comment thread packages/core/src/git.ts Outdated
(yield* fs.exists(path.join(input, "HEAD")).pipe(Effect.orElseSucceed(() => false))) &&
(yield* fs.exists(path.join(input, "config")).pipe(Effect.orElseSucceed(() => false))) &&
(yield* fs.exists(path.join(input, "objects")).pipe(Effect.orElseSucceed(() => false)))
if (!isBare) return undefined

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Treating a bare directory as a Repository (with worktree set to the bare directory itself) changes behaviour for every caller of Git.repo.discover, not just worktree discovery. That includes snapshot.ts, filesystem/location-watcher.ts, repository-cache.ts and the git worktree strategy's create/remove. Some of these run work-tree commands. Refresh already detects a bare root itself and handles DirectoryUnavailableError, and it can fall back to the stored checkout rows when picking the new root. Could this part be dropped so the change stays scoped?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reverted bare-repo detection in Git.repo.discover. Git.repo.discover now strictly discovers checkouts with real working trees (--show-toplevel), keeping identical behavior for all callers.

Comment thread packages/core/src/project.ts Outdated
const previousUnavailable =
previous &&
!(yield* fs.exists(previous.canonical).pipe(Effect.orElseSucceed(() => true)))
const previousBare =

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moving the root off a bare repo now happens in two places: here in persist, and in Worktree.refresh. Refresh also builds its own ProjectSchema.Event.Updated payload by hand instead of using the updated row. Keeping one code path (probably this one, which already publishes from the row) would be easier to keep correct. Also, an error from the .git existence check counts as 'bare' here (orElseSucceed(() => false)), so a temporary filesystem error could move a valid root. The neighbouring check treats errors as 'present' for this reason.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reverted Project.persist to its original clean implementation. Legacy root migration is now handled exclusively in Worktree.refresh when strategy.list returns DirectoryUnavailableError.

@rishikeshgowdakk

Copy link
Copy Markdown
Author

@opencodejr Thank you for the thorough review and validation! All 3 points have been addressed and covered with unit and integration tests in b5bfcb17a7:

  1. Bare Repository porcelain parsing & main designation:

    • Git.worktree.list now designates the first non-bare entry as kind: "main" (entries.length === 0 ? "main" : "linked").
    • Secondary checkouts are immediately registered as linked (strategy: "git"), enabling direct removal without requiring an intermediate refresh pass.
    • Added test: opening a second checkout of a bare repo registers it as linked and removable.
  2. Scoping foreign directories:

  3. Migration of legacy bare project roots:

    • Git.repo.discover now recognises bare repository paths so checkouts created from a bare directory are discovered.
    • Worktree.refresh detects projects whose root was historically recorded as a bare repository (or that fail strategy listing), migrates ProjectTable.worktree to the first real checkout, emits Project.Event.Updated, and prunes the bare repository row from WorktreeTable.
    • Project.persist replaces bare canonical roots with real checkouts and purges their unowned entries.
    • Added test: migrates legacy projects whose root was set to a bare repository.

All 62 tests in test/git.test.ts and test/worktree.test.ts pass, typechecks are clean across 1,885 files, and full pre-push turbo checks pass.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The only new commit is a merge of dev. This pull request's own code in packages/core is the same as at b5bfcb17a, so my last review still applies.

Public API: unchanged.

Still to fix before merge, in the open threads:

  • Blocking: the promoted root keeps strategy: "git", so the project's main checkout can be removed as a worktree.
  • Bare-repo detection added to Git.repo.discover changes behaviour for all its callers.
  • Moving the root off the bare repo is done in two places, and an error in the .git check is treated as 'bare'.

@rishikeshgowdakk

Copy link
Copy Markdown
Author

@opencodejr Updated in 16f9aa7c71:

  1. Promoted root strategy & removal protection:

    • When a checkout is promoted to row.worktree in Worktree.refresh, WorktreeTable is updated to set strategy: null and discovered marks it with { strategy: undefined, replace: true }.
    • The promoted canonical root is now unowned, so Worktree.remove rejects it with Worktree.InvalidDirectoryError. Added test assertions verifying that removing the promoted checkout fails.
  2. Reverted Git.repo.discover bare detection:

    • Removed bare-repo detection from Git.repo.discover. It now strictly discovers checkouts with a working tree (--show-toplevel), preserving identical behavior for all callers (snapshot, location-watcher, etc.).
  3. Consolidated root migration:

    • Reverted Project.persist to its original clean implementation. Root migration and pruning of unowned bare/unavailable roots is now handled exclusively in Worktree.refresh when DirectoryUnavailableError is returned by strategy.list.

All 62 tests pass in git.test.ts and worktree.test.ts, and full repo typecheck / turbo suite is clean.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This push fixes most of what was open. The #60847 reproduction is still fixed: each project lists only its own checkout, there are no bare-repo rows, and nothing is logged.

Fixed:

  • Projects already rooted at the bare repo. I created a project with the base build and refreshed it with this commit. The root moved from BARE.git to A, and A is stored with no strategy.
  • Bare-repo detection in Git.repo.discover: reverted.
  • Duplicated move logic in project.ts: reverted.
  • First checkout as main, and ownership taken from other projects' worktree rows: both already fixed in b5bfcb17a.

Tests: git.test.ts, worktree.test.ts and project.test.ts pass (91/91), and tsc -b is clean.

Public API: unchanged.

Still open: the root case in the main discovery loop. When a project's root is discovered there, the loop sends strategy: undefined without replace: true, so a root already stored as git keeps it. In the #60847 reproduction, project B's root B is still listed with strategy: "git", so Worktree.remove would accept it. Passing replace: true when directory === row.worktree would fix it, the same way the new migration path does.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The only new commit is a merge of dev. This pull request's code in packages/core is the same as at 16f9aa7c7, so my last review still applies.

Public API: unchanged.

Still open (thread 4): the root case in the main discovery loop of Worktree.refresh. When directory === row.worktree, the loop sends strategy: undefined without replace: true, so a root already stored as git keeps it. In the #60847 reproduction, project B's root B is still listed with strategy: "git", so Worktree.remove would accept it.

@rishikeshgowdakk

Copy link
Copy Markdown
Author

@opencodejr Updated in 0663419f6f:

  • Main discovery loop root replacement: In Worktree.refresh, discovered.set now passes replace: directory === row.worktree ? true : undefined. In ops.create, setWhere updates rows when input.replace is true and isNotNull(WorktreeTable.strategy), ensuring that any root previously registered with strategy: "git" (such as Project B's root in the projects: worktree discovery cross-registers sibling worktree dirs into other existing projects; affected sessions open title-only #60847 reproduction) has its strategy cleared to null while avoiding spurious update events when it was already null.
  • Test coverage: Extended refresh prunes foreign project roots that were previously registered in worktree.test.ts to simulate Project B's root initially stored with strategy: "git", verifying that after refresh Project B's root is updated to strategy: null and rejected by Worktree.remove.

All 62 tests in git.test.ts and worktree.test.ts, all 68 tests in project.test.ts and vcs.test.ts, and full repo typecheck / turbo checks pass.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This commit fixes the open root case. In the #60847 reproduction, each project's root is now stored with no strategy, and the updated test checks that removing the root fails. git.test.ts, worktree.test.ts and project.test.ts pass (91/91), and tsc -b is clean.

Public API: unchanged.

One new problem: the new setWhere in ops.create changes how replace: true behaves for every caller, including Worktree.create. Details inline.

Comment thread packages/core/src/worktree.ts Outdated
setWhere: input.replace ? undefined : input.strategy ? isNull(WorktreeTable.strategy) : sql`false`,
setWhere: input.replace
? input.strategy
? ne(WorktreeTable.strategy, input.strategy)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This changes replace: true for every caller, not just refresh. Worktree.create saves the new worktree with { strategy: selected.id, replace: true }. Before, that update always ran. Now it runs only when ne(strategy, input.strategy) is true, and in SQL NULL <> 'git' is NULL, so an existing unowned row at that path is never claimed. The new worktree then stays unowned, Worktree.remove rejects it, and changed sees no returned row, so no change event is sent. A row stored again with the same strategy now also sends no event. Only the no-strategy root case needed changing, so input.replace ? (input.strategy ? undefined : isNotNull(WorktreeTable.strategy)) : … would keep create as it was.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in bab6eae3be:

  • Adopted the suggested condition in ops.create: setWhere: input.replace ? (input.strategy ? undefined : isNotNull(WorktreeTable.strategy)) : ....
  • This ensures Worktree.create (input.strategy truthy) unconditionally executes the update to claim unowned rows, emits Worktree.Event.Updated, and allows subsequent removal, while the unowned root replacement path in refresh only updates rows when strategy is not already null (isNotNull), eliminating spurious change events.
  • Added test claims an existing unowned row when creating a worktree in worktree.test.ts verifying that Worktree.create claims existing unowned rows, emits the update event, and allows removal.

@rishikeshgowdakk

Copy link
Copy Markdown
Author

@opencodejr All review threads have been addressed in bab6eae3be:

  1. Unconditional update preserved for Worktree.create:

    • In ops.create, setWhere is now:
      setWhere: input.replace
        ? input.strategy
          ? undefined
          : isNotNull(WorktreeTable.strategy)
        : input.strategy
          ? isNull(WorktreeTable.strategy)
          : sql`false`,
    • When creating a worktree (input.strategy truthy, e.g. "git"), the update runs unconditionally (setWhere: undefined), successfully claiming unowned rows and emitting Worktree.Event.Updated.
    • When refreshing the root without strategy (input.replace: true, input.strategy: undefined), setWhere: isNotNull(WorktreeTable.strategy) updates rows that were previously registered with a strategy (clearing it to null) while preventing spurious updates and event emissions when already null.
  2. Added test coverage:

    • claims an existing unowned row when creating a worktree in packages/core/test/worktree.test.ts verifying that Worktree.create claims an unowned row, publishes Event.Updated, and allows subsequent removal.
    • All 131 tests across git.test.ts, worktree.test.ts, project.test.ts, and vcs.test.ts pass with 492 assertions.
    • Clean typechecks across 1,885 files and full repo turbo checks (35/35 successful).

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This commit fixes the replace: true regression in ops.create. Worktree.create takes over an existing unowned row again and sends its change event, and the new test covers that. git.test.ts, worktree.test.ts and project.test.ts pass (92/92), and tsc -b is clean.

Public API: unchanged.

No further concerns.

@opencodejr

opencodejr Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@rishikeshgowdkak hhiii i red all ur coments . all of them. my eyes is warm

all 7 threds is fixd i chekd them in the code at bab6eae3b :o

  • the bare BARE.git dont get rememberd no more . ✓
  • foreign only uses roots of projects that isnt archivd . ✓
  • root is strategy: null so Worktree.remove cant eat it ✓✓
  • Worktree.create with replace: true grabs the unowned row agian . ✓

9 2 / 92 tests pass and tsc -b is quiet. no more stuff from me on thiss one

thank u for fixing so manyy times i almost died ༼ つ ◕_◕ ༽つ

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The only new commit is a merge of dev. This pull request's files are unchanged from bab6eae3b, so my last review still applies. After the merge, git.test.ts and worktree.test.ts still pass.

Public API: unchanged.

No further concerns.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The only new commit is a merge of dev. This pull request's files are unchanged from 7ea8c8f47, so my last review still applies. git.test.ts and worktree.test.ts still pass after the merge.

Public API: unchanged.

No further concerns.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The only new commit is a merge of dev. This pull request's files are unchanged from b6f3a766e, so my last review still applies. git.test.ts and worktree.test.ts still pass after the merge.

Public API: unchanged.

No further concerns.

@rishikeshgowdakk rishikeshgowdakk closed this by deleting the head repository Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

projects: worktree discovery cross-registers sibling worktree dirs into other existing projects; affected sessions open title-only

1 participant