fix(worktrees): keep strict true-empty listing behind the mockable lister

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Brennan Benson
2026-11-12 06:03:40 -08:00
co-authored by Claude Opus 5.5
parent d1f0913c32
commit 6573ce6161
13 changed files with 52 additions and 43 deletions
@@ -0,0 +1,18 @@
import type { GitWorktreeInfo } from '../../../../shared/worktree/types'
import type { GitWorktreeExecOptions } from '../worktree-operation-options'
import { isTrueEmptyWorktreeListing, listWorktreesStrict } from './worktree-listing'
/** Reject scan failures to prevent pruning valid worktrees and tabs; confirmed missing/non-repos return []. */
export async function listWorktreesStrictAllowingTrueEmpty(
repoPath: string,
options: GitWorktreeExecOptions = {}
): Promise<GitWorktreeInfo[]> {
try {
return await listWorktreesStrict(repoPath, options)
} catch (err) {
if (await isTrueEmptyWorktreeListing(repoPath, err)) {
return []
}
throw err
}
}
@@ -68,7 +68,7 @@ export async function listWorktreesUnshared(
}
/** Only a missing path or confirmed non-repo permits an authoritative empty listing. */
async function isTrueEmptyWorktreeListing(repoPath: string, err: unknown): Promise<boolean> {
export async function isTrueEmptyWorktreeListing(repoPath: string, err: unknown): Promise<boolean> {
if (getErrorCode(err) === 'ENOENT') {
try {
await stat(repoPath)
@@ -96,21 +96,6 @@ export async function listWorktreesStrict(
return annotateSparseCheckoutStatus(repoPath, visibleWorktrees, options)
}
/** Reject scan failures to prevent pruning valid worktrees and tabs; confirmed missing/non-repos return []. */
export async function listWorktreesStrictAllowingTrueEmpty(
repoPath: string,
options: GitWorktreeExecOptions = {}
): Promise<GitWorktreeInfo[]> {
try {
return await listWorktreesStrict(repoPath, options)
} catch (err) {
if (await isTrueEmptyWorktreeListing(repoPath, err)) {
return []
}
throw err
}
}
export async function annotateSparseCheckoutStatus(
repoPath: string,
worktrees: GitWorktreeInfo[],
@@ -2,9 +2,9 @@ import type { GitWorktreeInfo } from '../../../../shared/worktree/types'
import {
annotateSparseCheckoutStatus,
listWorktreeGraph as listWorktreeGraphUnshared,
listWorktreesStrict as listWorktreesStrictUnshared,
listWorktreesStrictAllowingTrueEmpty as listWorktreesStrictAllowingTrueEmptyUnshared
listWorktreesStrict as listWorktreesStrictUnshared
} from './worktree-listing'
import { listWorktreesStrictAllowingTrueEmpty as listWorktreesStrictAllowingTrueEmptyUnshared } from './strict-true-empty-worktree-listing'
import type { GitWorktreeExecOptions } from '../worktree-operation-options'
import { WORKTREE_LIST_TIMEOUT_MS } from '../worktree-operation-options'
import { resolveGitAdmissionTier } from '../../command-runner/admission/git-operation-executor'
@@ -15,9 +15,11 @@ vi.mock('../removal/registered-worktree-roots-cache', () => ({
registerWorktreeRootsForRepo: vi.fn()
}))
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the owner and hygiene plan read only these repo fields.
const repo = { id: 'repo-1', path: '/repos/app', kind: 'git' } as Repo
async function readFailing(times: number, claimsHygiene: boolean) {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the expectation is only carried, never read, when every scan fails.
const capture = vi.fn(() => ({}) as never)
const store = { captureNativeLocalWorktreeMetadataScanExpectation: capture }
for (let read = 0; read < times; read += 1) {
@@ -18,14 +18,6 @@ import {
registerWorktreeRootsForRepo
} from '../removal/registered-worktree-roots-cache'
type HygieneStore = Pick<Store, 'captureNativeLocalWorktreeMetadataScanExpectation'>
export type WorktreeCatalogHygieneWitness = WorktreeCatalogWitness & {
readonly expectation?: NativeLocalWorktreeMetadataScanExpectation
/** Roots revision after this observation registered its roots; later side effects fence on it. */
rootsRevision: number
}
export type WorktreeCatalogHygieneClaim = Readonly<{
generation: number
authorizedRootsRevision: number
@@ -35,7 +27,7 @@ export type WorktreeCatalogHygieneClaim = Readonly<{
/** Pre-scan facts for every flight; only readers that prune claim the evidence gate (#17775). */
export function worktreeCatalogHygienePlan(
store: Store | HygieneStore,
store: Store,
repo: Repo,
gitOptions: { wslDistro?: string },
claimsHygiene: boolean
@@ -54,7 +46,7 @@ export function worktreeCatalogHygienePlan(
hygieneDue && !gitOptions.wslDistro
? store.captureNativeLocalWorktreeMetadataScanExpectation?.(repo)
: undefined
const witness: WorktreeCatalogHygieneWitness = {
const witness: WorktreeCatalogWitness = {
authorizedRootsRevision,
hygieneDue,
...(expectation ? { expectation } : {}),
@@ -74,7 +66,7 @@ export function worktreeCatalogHygienePlan(
repo.id,
worktrees.map((worktree) => worktree.path)
)
const witness = observation.witness as WorktreeCatalogHygieneWitness | undefined
const witness = observation.witness
if (
!witness ||
getRepoExecutionHostId(repo) !== LOCAL_EXECUTION_HOST_ID ||
@@ -84,7 +76,7 @@ export function worktreeCatalogHygienePlan(
}
// Reuse listing roots for authorization to avoid another Git scan and macOS folder-permission prompts.
registerWorktreeRootsForRepo(
store as Store,
store,
repo,
[repo.path, ...worktrees.map((worktree) => worktree.path)],
gitOptions
@@ -98,7 +90,7 @@ export function worktreeCatalogHygienePlan(
export function claimWorktreeCatalogHygiene(
observation: WorktreeCatalogObservation
): WorktreeCatalogHygieneClaim | null {
const witness = observation.witness as WorktreeCatalogHygieneWitness | undefined
const witness = observation.witness
if (!witness) {
return null
}
@@ -8,6 +8,7 @@ import {
import { setWorktreeCatalogRouteResolver } from '../../../workspaces/catalog/repo-worktree-catalog-route'
import { pruneMetadataMissingFromAuthoritativeLocalScan } from './authoritative-local-worktree-metadata-pruning'
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the owner and pruning read only these repo fields.
const repo = { id: 'repo-1', path: '/repos/app', kind: 'git' } as Repo
const goneWorktreeId = 'repo-1::/repos/app-gone'
@@ -38,6 +39,7 @@ describe('metadata pruning under catalog owner authority', () => {
let releaseProbe: (() => void) | undefined
const pruneMissing = vi.fn(() => [goneWorktreeId])
const pruning = pruneMetadataMissingFromAuthoritativeLocalScan({
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the helper reads only these store members.
store: {
getRepos: () => [repo],
pruneSessionlessMissingLocalWorktreeMetadataForRepo: pruneMissing,
@@ -47,6 +49,7 @@ describe('metadata pruning under catalog owner authority', () => {
gitWorktrees: [
{ path: repo.path, head: 'abc', branch: 'main', isBare: false, isMainWorktree: true }
],
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: pruning compares only the repo identity and metadata ids.
scan: {
repo: { id: repo.id, path: repo.path },
metadata: [{ worktreeId: goneWorktreeId }]
@@ -35,9 +35,7 @@ vi.mock('../../../git/worktrees/catalog/worktree-listing', async (importOriginal
const facade = getWorktreeListingMocks()
return {
...(await importOriginal<typeof WorktreeListingModule>()),
listWorktreesStrict: facade.listWorktreesStrict,
// Runtime scans share the strict, true-empty-aware reader with desktop scans.
listWorktreesStrictAllowingTrueEmpty: facade.listWorktreesStrict
listWorktreesStrict: facade.listWorktreesStrict
}
})
@@ -345,6 +345,7 @@ describe('RuntimeManagedWorktreeQueries.listDetected overtaken scan', () => {
scan: async () => ({ kind: 'rows', worktrees: rows([repo.path]) }),
// The observation carries the pre-scan hygiene claim a pruning listing consumes.
captureWitness: () =>
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the mocked prune reads only the expectation's presence.
({
authorizedRootsRevision: 0,
rootsRevision: 0,
@@ -71,9 +71,7 @@ async function scanRuntimeWorktreesWithMutationWitness(
isLocalWorktreeScanGenerationCurrent(repo.id, scanGeneration) && authorityCurrent()
? claimWorktreeCatalogHygiene(observation)
: null
metadataPruneExpectation = claim?.expectation as
| NativeLocalWorktreeMetadataScanExpectation
| undefined
metadataPruneExpectation = claim?.expectation
lineagePrune = claimRuntimeLineagePrune(scan)
} else {
metadataPruneExpectation = captureLocalMetadataPruneExpectation(store, repo)
@@ -17,9 +17,7 @@ const electronMocks = vi.hoisted(() => {
vi.mock('../../../git/worktrees/catalog/worktree-listing', async (importOriginal) => {
return {
...(await importOriginal<typeof WorktreeListingModule>()),
listWorktreesStrict: listWorktreesStrictMock,
// Runtime scans share the strict, true-empty-aware reader with desktop scans.
listWorktreesStrictAllowingTrueEmpty: listWorktreesStrictMock
listWorktreesStrict: listWorktreesStrictMock
}
})
@@ -1,4 +1,5 @@
import type { GitWorktreeInfo } from '../../../shared/worktree/types'
import type { NativeLocalWorktreeMetadataScanExpectation } from '../../persistence/tracking-repos/missing-local-worktree-metadata-pruning'
/** One `git worktree list`; a confirmed missing/non-repo stays distinct from a failed run. */
export type WorktreeCatalogOutcome =
@@ -9,8 +10,10 @@ export type WorktreeCatalogOutcome =
/** Captured before Git runs; destructive consumers claim it at most once. */
export type WorktreeCatalogWitness = {
readonly authorizedRootsRevision: number
/** Roots revision after this observation registered its roots; later side effects fence on it. */
rootsRevision: number
readonly hygieneDue: boolean
readonly expectation?: unknown
readonly expectation?: NativeLocalWorktreeMetadataScanExpectation
/** Returns an unconsumed claim so the evidence gate can re-arm. */
readonly release: () => void
}
@@ -17,6 +17,7 @@ import type {
WorktreeCatalogOutcome
} from './repo-worktree-catalog-observation'
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the owner reads only these repo fields.
const repo = { id: 'repo-1', path: '/repos/app', kind: 'git' } as Repo
const row = (path: string): GitWorktreeInfo => ({
path,
@@ -238,7 +239,12 @@ describe('repo worktree catalog owner', () => {
const release = vi.fn()
const plan = {
...scanner([rows('/repos/app')]),
captureWitness: () => ({ authorizedRootsRevision: 1, hygieneDue: true, release })
captureWitness: () => ({
authorizedRootsRevision: 1,
rootsRevision: 1,
hygieneDue: true,
release
})
}
await readWorktreeCatalog(repo, 'local:default', desktop, plan)
invalidateWorktreeCatalogForRepo(repo.id)
@@ -15,7 +15,10 @@ import {
isLocalWorktreeScanGenerationCurrent,
onWorktreeRouteInputsChanged
} from './local-worktree-scan-generation'
import { isLiveWorktreeCatalogRoute } from './repo-worktree-catalog-route'
import {
isLiveWorktreeCatalogRoute,
setWorktreeCatalogRouteResolver
} from './repo-worktree-catalog-route'
import { verify } from './repo-worktree-catalog-verification'
import { onWslDiscoveryChanged } from '../../wsl/discovery/wsl-discovery-change'
@@ -309,6 +312,8 @@ export function retireObsoleteWorktreeCatalogs(): void {
}
export function _resetWorktreeCatalogOwnerForTests(): void {
// Shared test workers outlive the runtime whose store registered the resolver.
setWorktreeCatalogRouteResolver(null)
for (const [key, entry] of entries) {
retireEntry(key, entry)
}