Skip to content

fix(worktrees): stop separator-variant worktree ids purging live checkouts - #15616

Open
yzxcj797 wants to merge 1 commit into
stablyai:mainfrom
yzxcj797:fix/worktree-id-separator-purge-15598
Open

yzxcj797 wants to merge 1 commit into
stablyai:mainfrom
yzxcj797:fix/worktree-id-separator-purge-15598

Conversation

@yzxcj797

Copy link
Copy Markdown
Contributor

Summary

What

Two exact-string worktree-id membership checks now compare through a new shared worktreeIdComparisonKey (src/shared/worktree/id.ts), which folds separator and drive-letter spelling via the existing normalizeRuntimePathForComparison:

  • getRemovedWorktreeIdsAfterAuthoritativeScan (renderer) — a known id survives an authoritative scan when either its exact id or its normalized key is still detected.
  • pruneLineageForMissingRepoWorktrees (main) — a lineage child/parent is "live" when either spelling appears in the git worktree list.

Why

#15598 — on Windows the same checkout ends up in worktreeMeta under two spellings (repo::D:\Agentic\game2 from an app-written registration, repo::D:/Agentic/game2 from git). The reporter's forensics show the exact failure: a Claude Code coordinator survived a restart attached to the backslash entry; when its fleet created a child worktree, the fresh authoritative scan listed only the forward-slash id, getRemovedWorktreeIdsAfterAuthoritativeScan declared the backslash id removed, and the renderer purge force-killed the live pane (session-killed ... immediate:true) 543 ms later. The same exact-match shape in the lineage pruner would delete the lineage and rotate the parent's instanceId for a checkout that never went anywhere.

normalizeRuntimePathForComparison already exists for exactly this class of mismatch (added for session attribution in #10832: separator folding, Windows case folding, NFC); this PR points the two worktree-id set-membership sites at the same contract through one shared key. Distinct repos, distinct paths, and distinct folder-workspace instances remain distinct; malformed ids keep the exact-match behavior; genuinely-missing checkouts purge exactly as before.

Not in scope (per the issue's expectations, worth their own follow-ups): merging/canonicalizing the duplicate worktreeMeta entries themselves at load, and the broader "reconciliation should never force-kill" question — this PR removes the wrongful purge trigger, not the force-kill mechanism.

Testing

  • src/shared/worktree/id.test.ts — new worktreeIdComparisonKey unit cases: backslash/forward-slash fold, repo/path/instance distinctness, malformed-id nulls. 24/24.
  • src/main/worktree-lineage-pruning.test.ts — new case: git listing with forward-slash paths vs a backslash-keyed lineage keeps the lineage and does not rotate the parent instanceId (verified to fail on the pre-fix code). 3/3.
  • New worktree-host-ownership-purge.test.ts — a backslash-spelled known id is not purged when the scan reports the forward-slash spelling; a genuinely-gone checkout still purges; a separator variant with no surviving scan row still purges (also verified to fail pre-fix). 3/3.
  • Adjacent suites (worktree-removal-maps-leak, bulk-worktree-purge-terminal-maps-leak) 11/11; pnpm run typecheck clean.

Fixes #15598

…kouts

The same Windows checkout can be keyed with backslashes by the app and
forward slashes by git, leaving worktreeMeta holding two spellings of
one directory (stablyai#15598). Two exact-string membership checks then treated
the other spelling as removed on an authoritative scan:

- getRemovedWorktreeIdsAfterAuthoritativeScan declared the backslash id
  removed and the renderer purge force-killed the terminals still bound
  to it — an unattended agent dies mid-task with no error anywhere.
- pruneLineageForMissingRepoWorktrees pruned the lineage and rotated the
  parent's instanceId for a checkout that never went anywhere.

Both now compare through a new shared worktreeIdComparisonKey, which
folds separator/drive-letter spelling (and NFC, via the existing
normalizeRuntimePathForComparison) while keeping distinct repos, paths,
and folder-workspace instances distinct. Malformed ids keep the exact
match behavior. Genuinely-missing checkouts still purge exactly as
before.
@coderabbitai

coderabbitai Bot commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds worktreeIdComparisonKey to normalize valid worktree IDs for comparison. Lineage pruning uses normalized liveness checks for workspace lineage, worktree lineage, and parent identity rotation. Authoritative-scan purge logic also recognizes equivalent path separator forms. Tests cover Windows path separators, drive-letter forms, distinct worktree identities, malformed IDs, lineage preservation, and purge behavior.

Merge Risk: ⚪ Minimal · up to 47744

The PR normalizes worktree-id comparisons to prevent separator-variant live checkouts from being purged. Remaining feedback is limited to an optional edge-case test and comment cleanup, so no actionable merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR fixes the separator-based purge trigger but does not implement the issue's requested storage canonicalization, duplicate migration, or safe live-PTY reconciliation. Implement the remaining issue requirements or split them into explicit follow-up issues and clarify that this PR is a partial fix.
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary fix for live worktrees incorrectly purged due to separator variants.
Description check ✅ Passed The description explains the bug, implementation, rationale, linked issue, scope limits, and test results, but it uses a condensed structure instead of the repository template.
Out of Scope Changes check ✅ Passed The code and tests remain focused on normalized worktree ID comparison, lineage retention, and purge prevention described by the linked issue.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/shared/worktree/id.ts (1)

21-35: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Condense the API comment.

The comment repeats incident history and implementation effects across 15 lines. Keep the API contract and one short rationale here. Put detailed incident history in the linked issue.

As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a83cc17a-99d5-4bdb-a065-e48bd6cfd09c

📥 Commits

Reviewing files that changed from the base of the PR and between 0f26ff4 and 477441f.

📒 Files selected for processing (6)
  • src/main/worktree-lineage-pruning.test.ts
  • src/main/worktree-lineage-pruning.ts
  • src/renderer/src/store/slices/worktrees/listing/worktree-host-ownership-purge.test.ts
  • src/renderer/src/store/slices/worktrees/listing/worktree-host-ownership.ts
  • src/shared/worktree/id.test.ts
  • src/shared/worktree/id.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment on lines +125 to +130
const BACKSLASH = 'repo-1::D:' + String.fromCharCode(92) + 'Agentic' + String.fromCharCode(92) + 'game2'
const FORWARD = 'repo-1::D:/Agentic/game2'

it('folds Windows separator and drive-letter spelling of one checkout (#15598)', () => {
expect(worktreeIdComparisonKey(BACKSLASH)).toBe(worktreeIdComparisonKey(FORWARD))
})

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Test drive-letter case folding.

Both fixtures use D:. This assertion only tests separator folding. Add a d:/Agentic/game2 fixture and compare its key with FORWARD.

Proposed test update
 const FORWARD = 'repo-1::D:/Agentic/game2'
+const LOWERCASE_DRIVE = 'repo-1::d:/Agentic/game2'

 it('folds Windows separator and drive-letter spelling of one checkout (`#15598`)', () => {
   expect(worktreeIdComparisonKey(BACKSLASH)).toBe(worktreeIdComparisonKey(FORWARD))
+  expect(worktreeIdComparisonKey(LOWERCASE_DRIVE)).toBe(worktreeIdComparisonKey(FORWARD))
 })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const BACKSLASH = 'repo-1::D:' + String.fromCharCode(92) + 'Agentic' + String.fromCharCode(92) + 'game2'
const FORWARD = 'repo-1::D:/Agentic/game2'
it('folds Windows separator and drive-letter spelling of one checkout (#15598)', () => {
expect(worktreeIdComparisonKey(BACKSLASH)).toBe(worktreeIdComparisonKey(FORWARD))
})
const BACKSLASH = 'repo-1::D:' + String.fromCharCode(92) + 'Agentic' + String.fromCharCode(92) + 'game2'
const FORWARD = 'repo-1::D:/Agentic/game2'
const LOWERCASE_DRIVE = 'repo-1::d:/Agentic/game2'
it('folds Windows separator and drive-letter spelling of one checkout (#15598)', () => {
expect(worktreeIdComparisonKey(BACKSLASH)).toBe(worktreeIdComparisonKey(FORWARD))
expect(worktreeIdComparisonKey(LOWERCASE_DRIVE)).toBe(worktreeIdComparisonKey(FORWARD))
})

OrcaWin pushed a commit that referenced this pull request Aug 27, 2026
…16243) (#16494)

* test(worktrees): cover id: selector path-spelling parity with path: (#16243)

The renderer can only address a workspace by id (toRuntimeWorktreeSelector always
emits id:<repoId>::<path>), and the runtime matches that id byte for byte while a
path: selector has always compared through normalizeRuntimePathForComparison. A
stored id that spells its path differently from `git worktree list` therefore
resolves for the CLI and answers selector_not_found for the UI, which reads that
as a stale local mirror, calls forgetLocal, reports success, and lets the row
return on the next catalog refresh: a silent delete.

These tests fail on both resolution sites -- the fleet `id:` branch of
resolveWorktreeSelector and the scoped resolveScopedWorktreeIdRow a
host-qualified removal takes -- and pin what must stay closed: an exact repo id
(STA-4343), host qualification, dot segments neither selector canonicalizes, and
a refusal rather than a guess when two rows spell one path.

13 failing, 35 passing.

* fix(worktrees): resolve id: worktree selectors by path equivalence (#16243)

worktreeIdComparisonKey names one repo, one filesystem location, and one
folder-workspace instance, folding exactly the path spellings
normalizeRuntimePathForComparison already folds for a path: selector -- and
nothing more, so dot segments stay unresolved for both shapes. Both id:
resolution sites consult it only after an exact match finds nothing: the fleet
branch of resolveWorktreeSelector and resolveScopedWorktreeIdRow, which a
host-qualified removal takes. runtimeWorktreeIdsEqual now derives from the same
key so the runtime has one normalizer rather than a parallel one.

Not a pure refactor at that last site: runtimeWorktreeIdsEqual used to
normalize-compare ids that parse but carry an empty repoId or an empty path
('::/p', or 'repo::' against 'repo::/'), and worktreeIdComparisonKey returns
null for those, so across its call sites (PTY identity, refresh, mutation
queue) such ids now compare byte-exact instead. That narrows matching rather
than widening it, no real worktree carries such an id, and it is the behavior
#15616 guarantees for malformed ids -- but it is a behavior delta, not just a
tidy-up.

Perf (#14399): the exact match is still tried first and still wins outright, so
a resolvable id costs exactly what it did before. Neither site adds a scan --
the fleet branch re-filters the array it had already listed, the scoped lookup
re-filters the single owning repo's projected rows -- so an explicit id still
never scans every repo.

Fail-closed behavior is unchanged: the repo id compares exactly (STA-4343), host
qualification is untouched, the folder-workspace instance suffix stays part of
the path, and a scoped lookup with two equivalent rows refuses instead of
guessing. The bare unprefixed selector branch keeps byte-exact id matching,
since only the id: shape reaches a renderer caller.

Shares src/shared/worktree/id.ts with the open #15616, which introduces
worktreeIdComparisonKey for the same divergence in lineage pruning and
authoritative-scan purging; this adopts that helper rather than adding a second
one. Complementary to the open #16295, which makes the miss visible; this
removes the miss.

* chore(worktrees): satisfy oxfmt and oxlint on #16243 tests

oxfmt --check flagged both new test files and oxlint's
unicorn/no-useless-fallback-in-spread flagged the store mock; the full
lint and format gates now match the pre-change baseline.

* test(worktrees): pin Windows spellings and malformed-id exactness (#16243)

Review found two axes the first pass left unproven at the two id: resolution
sites. Both are the invariants the open #15616 guarantees for the shared
worktreeIdComparisonKey it introduces for #15598, so violating either here would
break a contract a sibling PR depends on.

Windows: #15598's whole defect is that one checkout is recorded under both
`D:\Agentic\game2` and `D:/Agentic/game2`. The fleet branch, the scoped removal
lookup, and the key itself now each resolve the backslash spelling against the
forward-slash spelling git reports, and fold drive-letter case -- while a
backslash inside a POSIX path stays a filename character and a POSIX root stays
case-sensitive, exactly as normalizeRuntimePathForComparison already decides for
a path: selector.

Malformed ids keep exact matching at both sites: an id with no repo boundary or
an empty path still refuses, and the scoped lookup still refuses it without
scanning.

Four of these fail without the production change (three fleet/removal Windows
cases and the scoped one); the malformed-id and POSIX-backslash cases are
invariant guards that hold either way.

Verified: 58 passed in the three files; 18 fail with the production hunks
reverted; orca-runtime.test.ts and worktree-teardown-unstopped-pty.test.ts green
(1270 passed | 1 skipped); pnpm tc:node clean.

* test(worktrees): pin Windows id: spelling folds and fleet ambiguity refusal (#16243)

The Windows backslash spelling now rides the ID_SPELLINGS rows, so it is driven
through both id: sites -- resolveWorktreeSelector and the scoped removal target --
and compared against what the same workspace's path: selector resolves, rather
than only through worktreeIdComparisonKey. That is the spelling #15598/#15616
found in the wild and the one the owner's Windows client produces.

The fleet path's ambiguity refusal had no test: two same-repo rows spelling one
directory, an id: matching neither exactly, must reject selector_ambiguous. It is
the fail-closed guard on a delete-capable resolver, and the property a later
refactor is most likely to turn into a silent pick.

Also records two limits at the source instead of leaving them to be rediscovered:
a UNC or WSL root never folds into a drive-letter location (while Windows' two
WSL UNC aliases do name one location), and a folder-workspace id keeps a trailing
slash placed before the ::workspace:<uuid> suffix, so that spelling stays
exact-match-only. Neither behavior changes here.

The file docblock overclaimed parity. path: collapses duplicate same-host
registrations to the first row while a folded id: refuses them; the contract this
file pins is path-spelling parity, not dedup parity, and the divergence is
deliberate because this resolver also serves delete.

Non-vacuity, verified by temporarily reverting the production hunks: neutralizing
both id: fallbacks turns 10 of these tests red, including both new Windows rows
and the ambiguity refusal (it degrades to selector_not_found). Making the fleet
fallback pick the first folded match instead of collecting all of them turns the
ambiguity test red on its own. The remaining cases -- malformed ids, dot
segments, the POSIX backslash, the folder-workspace slash -- pass against the
pre-fix code too: they guard against future widening rather than proving this
fix.

Drops the two Windows cases the ID_SPELLINGS row subsumes.

The drive-letter case test asserted only the Windows half its name promised; it
now also pins that a POSIX root does NOT fold case, since an unconditional
lowercase would merge /data/Foo with /data/foo on the platform CI runs on.

Fixture paths use the upstream-attested /srv/projects prefix (and a neutral
plugin-host leaf) instead of a local install root; the spelling variations the
tests exist to pin -- doubled separator, dot segment, trailing slash, uppercase
POSIX, cafe NFC/NFD, and the Windows D: rows -- are unchanged in form.

* docs(worktrees): trim the id: selector test header and document the comparison key (#16243)
@OrcaWin

OrcaWin commented Aug 27, 2026

Copy link
Copy Markdown
Collaborator

Heads-up: #16494 just merged (de6fe8b7ea) for #16243, and it adds a worktreeIdComparisonKey to src/shared/worktree/id.ts that is byte-identical to the one here — same signature, same null-on-malformed contract, same normalizeRuntimePathForComparison fold with the repo-id half kept exact.

So this branch will now conflict in id.ts, but only textually: drop your copy of the helper and keep the two call-site changes (worktree-lineage-pruning.ts and worktree-host-ownership.ts), which #16494 does not touch. The credit for the helper is yours — #16494 cites #15598/#15616 in its tests for the Windows backslash case.

Nothing about the purge behavior this PR fixes is addressed by #16494; it stays worth landing.

paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 30, 2026
…tablyai#16243) (stablyai#16494)

* test(worktrees): cover id: selector path-spelling parity with path: (stablyai#16243)

The renderer can only address a workspace by id (toRuntimeWorktreeSelector always
emits id:<repoId>::<path>), and the runtime matches that id byte for byte while a
path: selector has always compared through normalizeRuntimePathForComparison. A
stored id that spells its path differently from `git worktree list` therefore
resolves for the CLI and answers selector_not_found for the UI, which reads that
as a stale local mirror, calls forgetLocal, reports success, and lets the row
return on the next catalog refresh: a silent delete.

These tests fail on both resolution sites -- the fleet `id:` branch of
resolveWorktreeSelector and the scoped resolveScopedWorktreeIdRow a
host-qualified removal takes -- and pin what must stay closed: an exact repo id
(STA-4343), host qualification, dot segments neither selector canonicalizes, and
a refusal rather than a guess when two rows spell one path.

13 failing, 35 passing.

* fix(worktrees): resolve id: worktree selectors by path equivalence (stablyai#16243)

worktreeIdComparisonKey names one repo, one filesystem location, and one
folder-workspace instance, folding exactly the path spellings
normalizeRuntimePathForComparison already folds for a path: selector -- and
nothing more, so dot segments stay unresolved for both shapes. Both id:
resolution sites consult it only after an exact match finds nothing: the fleet
branch of resolveWorktreeSelector and resolveScopedWorktreeIdRow, which a
host-qualified removal takes. runtimeWorktreeIdsEqual now derives from the same
key so the runtime has one normalizer rather than a parallel one.

Not a pure refactor at that last site: runtimeWorktreeIdsEqual used to
normalize-compare ids that parse but carry an empty repoId or an empty path
('::/p', or 'repo::' against 'repo::/'), and worktreeIdComparisonKey returns
null for those, so across its call sites (PTY identity, refresh, mutation
queue) such ids now compare byte-exact instead. That narrows matching rather
than widening it, no real worktree carries such an id, and it is the behavior
stablyai#15616 guarantees for malformed ids -- but it is a behavior delta, not just a
tidy-up.

Perf (stablyai#14399): the exact match is still tried first and still wins outright, so
a resolvable id costs exactly what it did before. Neither site adds a scan --
the fleet branch re-filters the array it had already listed, the scoped lookup
re-filters the single owning repo's projected rows -- so an explicit id still
never scans every repo.

Fail-closed behavior is unchanged: the repo id compares exactly (STA-4343), host
qualification is untouched, the folder-workspace instance suffix stays part of
the path, and a scoped lookup with two equivalent rows refuses instead of
guessing. The bare unprefixed selector branch keeps byte-exact id matching,
since only the id: shape reaches a renderer caller.

Shares src/shared/worktree/id.ts with the open stablyai#15616, which introduces
worktreeIdComparisonKey for the same divergence in lineage pruning and
authoritative-scan purging; this adopts that helper rather than adding a second
one. Complementary to the open stablyai#16295, which makes the miss visible; this
removes the miss.

* chore(worktrees): satisfy oxfmt and oxlint on stablyai#16243 tests

oxfmt --check flagged both new test files and oxlint's
unicorn/no-useless-fallback-in-spread flagged the store mock; the full
lint and format gates now match the pre-change baseline.

* test(worktrees): pin Windows spellings and malformed-id exactness (stablyai#16243)

Review found two axes the first pass left unproven at the two id: resolution
sites. Both are the invariants the open stablyai#15616 guarantees for the shared
worktreeIdComparisonKey it introduces for stablyai#15598, so violating either here would
break a contract a sibling PR depends on.

Windows: stablyai#15598's whole defect is that one checkout is recorded under both
`D:\Agentic\game2` and `D:/Agentic/game2`. The fleet branch, the scoped removal
lookup, and the key itself now each resolve the backslash spelling against the
forward-slash spelling git reports, and fold drive-letter case -- while a
backslash inside a POSIX path stays a filename character and a POSIX root stays
case-sensitive, exactly as normalizeRuntimePathForComparison already decides for
a path: selector.

Malformed ids keep exact matching at both sites: an id with no repo boundary or
an empty path still refuses, and the scoped lookup still refuses it without
scanning.

Four of these fail without the production change (three fleet/removal Windows
cases and the scoped one); the malformed-id and POSIX-backslash cases are
invariant guards that hold either way.

Verified: 58 passed in the three files; 18 fail with the production hunks
reverted; orca-runtime.test.ts and worktree-teardown-unstopped-pty.test.ts green
(1270 passed | 1 skipped); pnpm tc:node clean.

* test(worktrees): pin Windows id: spelling folds and fleet ambiguity refusal (stablyai#16243)

The Windows backslash spelling now rides the ID_SPELLINGS rows, so it is driven
through both id: sites -- resolveWorktreeSelector and the scoped removal target --
and compared against what the same workspace's path: selector resolves, rather
than only through worktreeIdComparisonKey. That is the spelling stablyai#15598/stablyai#15616
found in the wild and the one the owner's Windows client produces.

The fleet path's ambiguity refusal had no test: two same-repo rows spelling one
directory, an id: matching neither exactly, must reject selector_ambiguous. It is
the fail-closed guard on a delete-capable resolver, and the property a later
refactor is most likely to turn into a silent pick.

Also records two limits at the source instead of leaving them to be rediscovered:
a UNC or WSL root never folds into a drive-letter location (while Windows' two
WSL UNC aliases do name one location), and a folder-workspace id keeps a trailing
slash placed before the ::workspace:<uuid> suffix, so that spelling stays
exact-match-only. Neither behavior changes here.

The file docblock overclaimed parity. path: collapses duplicate same-host
registrations to the first row while a folded id: refuses them; the contract this
file pins is path-spelling parity, not dedup parity, and the divergence is
deliberate because this resolver also serves delete.

Non-vacuity, verified by temporarily reverting the production hunks: neutralizing
both id: fallbacks turns 10 of these tests red, including both new Windows rows
and the ambiguity refusal (it degrades to selector_not_found). Making the fleet
fallback pick the first folded match instead of collecting all of them turns the
ambiguity test red on its own. The remaining cases -- malformed ids, dot
segments, the POSIX backslash, the folder-workspace slash -- pass against the
pre-fix code too: they guard against future widening rather than proving this
fix.

Drops the two Windows cases the ID_SPELLINGS row subsumes.

The drive-letter case test asserted only the Windows half its name promised; it
now also pins that a POSIX root does NOT fold case, since an unconditional
lowercase would merge /data/Foo with /data/foo on the platform CI runs on.

Fixture paths use the upstream-attested /srv/projects prefix (and a neutral
plugin-host leaf) instead of a local install root; the spelling variations the
tests exist to pin -- doubled separator, dot segment, trailing slash, uppercase
POSIX, cafe NFC/NFD, and the Windows D: rows -- are unchanged in form.

* docs(worktrees): trim the id: selector test header and document the comparison key (stablyai#16243)

(cherry picked from commit de6fe8b)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#16243) (stablyai#16494)

* test(worktrees): cover id: selector path-spelling parity with path: (stablyai#16243)

The renderer can only address a workspace by id (toRuntimeWorktreeSelector always
emits id:<repoId>::<path>), and the runtime matches that id byte for byte while a
path: selector has always compared through normalizeRuntimePathForComparison. A
stored id that spells its path differently from `git worktree list` therefore
resolves for the CLI and answers selector_not_found for the UI, which reads that
as a stale local mirror, calls forgetLocal, reports success, and lets the row
return on the next catalog refresh: a silent delete.

These tests fail on both resolution sites -- the fleet `id:` branch of
resolveWorktreeSelector and the scoped resolveScopedWorktreeIdRow a
host-qualified removal takes -- and pin what must stay closed: an exact repo id
(STA-4343), host qualification, dot segments neither selector canonicalizes, and
a refusal rather than a guess when two rows spell one path.

13 failing, 35 passing.

* fix(worktrees): resolve id: worktree selectors by path equivalence (stablyai#16243)

worktreeIdComparisonKey names one repo, one filesystem location, and one
folder-workspace instance, folding exactly the path spellings
normalizeRuntimePathForComparison already folds for a path: selector -- and
nothing more, so dot segments stay unresolved for both shapes. Both id:
resolution sites consult it only after an exact match finds nothing: the fleet
branch of resolveWorktreeSelector and resolveScopedWorktreeIdRow, which a
host-qualified removal takes. runtimeWorktreeIdsEqual now derives from the same
key so the runtime has one normalizer rather than a parallel one.

Not a pure refactor at that last site: runtimeWorktreeIdsEqual used to
normalize-compare ids that parse but carry an empty repoId or an empty path
('::/p', or 'repo::' against 'repo::/'), and worktreeIdComparisonKey returns
null for those, so across its call sites (PTY identity, refresh, mutation
queue) such ids now compare byte-exact instead. That narrows matching rather
than widening it, no real worktree carries such an id, and it is the behavior
stablyai#15616 guarantees for malformed ids -- but it is a behavior delta, not just a
tidy-up.

Perf (stablyai#14399): the exact match is still tried first and still wins outright, so
a resolvable id costs exactly what it did before. Neither site adds a scan --
the fleet branch re-filters the array it had already listed, the scoped lookup
re-filters the single owning repo's projected rows -- so an explicit id still
never scans every repo.

Fail-closed behavior is unchanged: the repo id compares exactly (STA-4343), host
qualification is untouched, the folder-workspace instance suffix stays part of
the path, and a scoped lookup with two equivalent rows refuses instead of
guessing. The bare unprefixed selector branch keeps byte-exact id matching,
since only the id: shape reaches a renderer caller.

Shares src/shared/worktree/id.ts with the open stablyai#15616, which introduces
worktreeIdComparisonKey for the same divergence in lineage pruning and
authoritative-scan purging; this adopts that helper rather than adding a second
one. Complementary to the open stablyai#16295, which makes the miss visible; this
removes the miss.

* chore(worktrees): satisfy oxfmt and oxlint on stablyai#16243 tests

oxfmt --check flagged both new test files and oxlint's
unicorn/no-useless-fallback-in-spread flagged the store mock; the full
lint and format gates now match the pre-change baseline.

* test(worktrees): pin Windows spellings and malformed-id exactness (stablyai#16243)

Review found two axes the first pass left unproven at the two id: resolution
sites. Both are the invariants the open stablyai#15616 guarantees for the shared
worktreeIdComparisonKey it introduces for stablyai#15598, so violating either here would
break a contract a sibling PR depends on.

Windows: stablyai#15598's whole defect is that one checkout is recorded under both
`D:\Agentic\game2` and `D:/Agentic/game2`. The fleet branch, the scoped removal
lookup, and the key itself now each resolve the backslash spelling against the
forward-slash spelling git reports, and fold drive-letter case -- while a
backslash inside a POSIX path stays a filename character and a POSIX root stays
case-sensitive, exactly as normalizeRuntimePathForComparison already decides for
a path: selector.

Malformed ids keep exact matching at both sites: an id with no repo boundary or
an empty path still refuses, and the scoped lookup still refuses it without
scanning.

Four of these fail without the production change (three fleet/removal Windows
cases and the scoped one); the malformed-id and POSIX-backslash cases are
invariant guards that hold either way.

Verified: 58 passed in the three files; 18 fail with the production hunks
reverted; orca-runtime.test.ts and worktree-teardown-unstopped-pty.test.ts green
(1270 passed | 1 skipped); pnpm tc:node clean.

* test(worktrees): pin Windows id: spelling folds and fleet ambiguity refusal (stablyai#16243)

The Windows backslash spelling now rides the ID_SPELLINGS rows, so it is driven
through both id: sites -- resolveWorktreeSelector and the scoped removal target --
and compared against what the same workspace's path: selector resolves, rather
than only through worktreeIdComparisonKey. That is the spelling stablyai#15598/stablyai#15616
found in the wild and the one the owner's Windows client produces.

The fleet path's ambiguity refusal had no test: two same-repo rows spelling one
directory, an id: matching neither exactly, must reject selector_ambiguous. It is
the fail-closed guard on a delete-capable resolver, and the property a later
refactor is most likely to turn into a silent pick.

Also records two limits at the source instead of leaving them to be rediscovered:
a UNC or WSL root never folds into a drive-letter location (while Windows' two
WSL UNC aliases do name one location), and a folder-workspace id keeps a trailing
slash placed before the ::workspace:<uuid> suffix, so that spelling stays
exact-match-only. Neither behavior changes here.

The file docblock overclaimed parity. path: collapses duplicate same-host
registrations to the first row while a folded id: refuses them; the contract this
file pins is path-spelling parity, not dedup parity, and the divergence is
deliberate because this resolver also serves delete.

Non-vacuity, verified by temporarily reverting the production hunks: neutralizing
both id: fallbacks turns 10 of these tests red, including both new Windows rows
and the ambiguity refusal (it degrades to selector_not_found). Making the fleet
fallback pick the first folded match instead of collecting all of them turns the
ambiguity test red on its own. The remaining cases -- malformed ids, dot
segments, the POSIX backslash, the folder-workspace slash -- pass against the
pre-fix code too: they guard against future widening rather than proving this
fix.

Drops the two Windows cases the ID_SPELLINGS row subsumes.

The drive-letter case test asserted only the Windows half its name promised; it
now also pins that a POSIX root does NOT fold case, since an unconditional
lowercase would merge /data/Foo with /data/foo on the platform CI runs on.

Fixture paths use the upstream-attested /srv/projects prefix (and a neutral
plugin-host leaf) instead of a local install root; the spelling variations the
tests exist to pin -- doubled separator, dot segment, trailing slash, uppercase
POSIX, cafe NFC/NFD, and the Windows D: rows -- are unchanged in form.

* docs(worktrees): trim the id: selector test header and document the comparison key (stablyai#16243)

This branch has not been deployed

No deployments
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.

[Bug]: Duplicate worktreeMeta entries differing only by path separator force-kill a live agent pane when a child worktree is created

2 participants