Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/users/features/code-review.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,8 @@ When reviewing a PR, `/review` creates a temporary git worktree (`.qwen/tmp/revi
- Build and test commands run in isolation without polluting your local build cache
- If anything goes wrong, your environment is unaffected — just delete the worktree
- The worktree is automatically cleaned up after the review completes
- If a review is interrupted (Ctrl+C, crash), the next `/review` of the same PR automatically cleans up the stale worktree before starting fresh
- If a review is interrupted (Ctrl+C, crash), the next `/review` of the same PR automatically cleans up the stale worktree before starting fresh. If the interrupted session still leaves its lease behind — a hard kill that skips this, or a multi-prompt review interrupted during a later prompt — `/review` refuses and names the lease file to delete
- The worktree is leased to its session: a second `/review` of a PR that is already under review refuses to start (naming the holder) rather than tear down the running review's worktree
- Review reports and cache are saved to the main project directory (not the worktree)

## Cross-repo PR Review
Expand Down
66 changes: 66 additions & 0 deletions packages/cli/src/commands/review/cleanup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ const mocks = vi.hoisted(() => ({
writeStdoutLine: vi.fn(),
writeStderrLine: vi.fn(),
clearReviewWorktreeLease: vi.fn(),
readReviewWorktreeLease: vi.fn((): unknown => null),
reviewLeaseHeldByAnotherSession: vi.fn((_lease: unknown): boolean => false),
refExists: vi.fn(() => true),
// The parameter is declared so `mock.calls` is typed `[string][]` rather than
// `[][]` — the paths it was asked to free are the assertion in the sweep test.
Expand Down Expand Up @@ -62,6 +64,10 @@ vi.mock('../../utils/stdioHelpers.js', () => ({

vi.mock('../../services/review-worktree-lease.js', () => ({
clearReviewWorktreeLease: mocks.clearReviewWorktreeLease,
readReviewWorktreeLease: mocks.readReviewWorktreeLease,
reviewLeaseHeldByAnotherSession: mocks.reviewLeaseHeldByAnotherSession,
reviewLeasePath: (repositoryRoot: string, target: string) =>
`${repositoryRoot}/.qwen/tmp/qwen-review-lease-${target}.json`,
}));

vi.mock('./lib/git.js', () => ({
Expand Down Expand Up @@ -136,6 +142,66 @@ describe('runCleanup', () => {
);
});

it('skips the whole target when another session holds the lease (#9205)', () => {
// The incident shape: session B cleans up while session A is mid-review.
// Nothing of A's may be touched — worktree, siblings, branch, side files,
// audit window, or the lease itself.
const lease = {
sessionId: 'session-a',
promptId: 'prompt-a',
target: 'pr-123',
repositoryRoot: '/repo',
worktreePath: '/repo/.qwen/tmp/review-pr-123',
branch: 'qwen-review/pr-123',
};
mocks.readReviewWorktreeLease.mockReturnValueOnce(lease);
mocks.reviewLeaseHeldByAnotherSession.mockImplementationOnce(
(l: unknown) => l === lease,
);

runCleanup('pr-123');

// The skip must key on THIS target's lease: mockReturnValueOnce is
// argument-blind, so an unwired read consults another PR's lease.
expect(mocks.readReviewWorktreeLease).toHaveBeenCalledWith(
process.cwd(),
'pr-123',
);
expect(mocks.releaseWorktree).not.toHaveBeenCalled();
expect(mocks.execFileSync).not.toHaveBeenCalled();
expect(mocks.rmSync).not.toHaveBeenCalled();
expect(mocks.ghApiAll).not.toHaveBeenCalled();
expect(mocks.clearReviewWorktreeLease).not.toHaveBeenCalled();
expect(mocks.writeStdoutLine).toHaveBeenCalledWith(
expect.stringContaining('skipped cleanup for "pr-123"'),
);
expect(mocks.writeStdoutLine).toHaveBeenCalledWith(
expect.stringContaining('session-a'),
);
});

it('proceeds when the lease belongs to this session', () => {
const lease = {
sessionId: 'session-b',
promptId: 'prompt-b',
target: 'pr-123',
repositoryRoot: '/repo',
worktreePath: '/repo/.qwen/tmp/review-pr-123',
branch: 'qwen-review/pr-123',
};
mocks.readReviewWorktreeLease.mockReturnValueOnce(lease);
mocks.reviewLeaseHeldByAnotherSession.mockReturnValueOnce(false);
mocks.execFileSync.mockReturnValue(Buffer.from(''));

runCleanup('pr-123');

expect(mocks.releaseWorktree).toHaveBeenCalledTimes(3);
expect(mocks.clearReviewWorktreeLease).toHaveBeenCalledWith(
process.cwd(),
'pr-123',
);
});

it('releases the review worktree AND both disposable siblings', () => {
// `base-tree` deliberately leaves its tree standing for the whole review
// (a later verifier may need it, and a base that failed to build is kept as
Expand Down
26 changes: 25 additions & 1 deletion packages/cli/src/commands/review/cleanup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@ import { execFileSync } from 'node:child_process';
import { existsSync, readFileSync, readdirSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { writeStdoutLine, writeStderrLine } from '../../utils/stdioHelpers.js';
import { clearReviewWorktreeLease } from '../../services/review-worktree-lease.js';
import {
clearReviewWorktreeLease,
readReviewWorktreeLease,
reviewLeaseHeldByAnotherSession,
reviewLeasePath,
} from '../../services/review-worktree-lease.js';
import { currentUser, getGhHost, ghApiAll, setGhHost } from './lib/gh.js';
import { parseReceiptIds } from './lib/receipt.js';
import { refExists, releaseWorktree } from './lib/git.js';
Expand Down Expand Up @@ -385,6 +390,25 @@ export function runCleanup(target: string): void {
if (prMatch) {
const prNumber = prMatch[1];

// The lease is also a lock (#9205). The worktree path, the side files,
// and the fetch report carrying the audit window are all fixed per PR
// number, so cleaning while ANOTHER session reviews the same PR deletes
// its worktree, diff, and plan mid-run — and audits ITS window against
// receipts it never wrote. Skip the whole target: worktree, siblings,
// branch, side files, audit, and the lease itself all belong to the
// holder until its own cleanup releases them.
const holder = readReviewWorktreeLease(process.cwd(), target);
if (reviewLeaseHeldByAnotherSession(holder)) {
writeStdoutLine(
`note: skipped cleanup for "${target}" — another review session ` +
`(session ${holder.sessionId}) still holds the worktree lease at ` +
`${reviewLeasePath(process.cwd(), target)}. Its own cleanup ` +
`releases the lease when it finishes; if that session is gone, ` +
`delete the lease file and re-run to force cleanup.`,
);
return;
}

// Before the sweep below deletes the fetch report (the audit window's
// carrier), check the PR for writes that bypassed `qwen review submit`.
auditPrWrites(target, prNumber);
Expand Down
134 changes: 131 additions & 3 deletions packages/cli/src/commands/review/fetch-pr.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ import {
isEmptyDiff,
isCollapsedFromUpstream,
} from './fetch-pr.js';
import {
clearReviewWorktreeLease,
createReviewWorktreeLease,
readReviewWorktreeLease,
reviewLeaseHeldByAnotherSession,
} from '../../services/review-worktree-lease.js';
import { classifyHeavy } from './lib/heavy.js';
import { PARSE_ARGS_REPORT } from './lib/paths.js';

Expand Down Expand Up @@ -217,6 +223,8 @@ const producerMocks = vi.hoisted(() => ({
}),
gh: vi.fn(),
git: vi.fn(),
execFileSync: vi.fn(),
releaseWorktree: vi.fn(() => ({ existed: false, freed: true })),
writeStderrLine: vi.fn(),
}));

Expand All @@ -240,8 +248,8 @@ vi.mock('node:child_process', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:child_process')>();
return {
...actual,
default: { ...actual, execFileSync: vi.fn() },
execFileSync: vi.fn(),
default: { ...actual, execFileSync: producerMocks.execFileSync },
execFileSync: producerMocks.execFileSync,
};
});

Expand All @@ -251,7 +259,12 @@ vi.mock('../../utils/stdioHelpers.js', () => ({
}));

vi.mock('../../services/review-worktree-lease.js', () => ({
clearReviewWorktreeLease: vi.fn(),
createReviewWorktreeLease: vi.fn(),
readReviewWorktreeLease: vi.fn((): unknown => null),
reviewLeaseHeldByAnotherSession: vi.fn((): boolean => false),
reviewLeasePath: (repositoryRoot: string, target: string) =>
`${repositoryRoot}/.qwen/tmp/qwen-review-lease-${target}.json`,
}));

vi.mock('./lib/gh.js', () => ({
Expand All @@ -265,7 +278,7 @@ vi.mock('./lib/git.js', () => ({
gitOpt: vi.fn(() => null),
gitRaw: vi.fn(() => Buffer.from('')),
refExists: vi.fn(() => false),
releaseWorktree: vi.fn(() => ({ existed: false, freed: true })),
releaseWorktree: producerMocks.releaseWorktree,
}));

vi.mock('./lib/merge-base.js', () => ({
Expand Down Expand Up @@ -334,6 +347,121 @@ describe('fetch-pr report assembly', () => {
expect(report.host).toBe('ghe.example.com');
});

// The lease is also a lock (#9205): a concurrent same-PR fetch-pr used to
// stale-clean the holder's worktree before failing on, destroying it. The
// refusal must precede every destructive step, including the lease write.
describe('lease lock', () => {
const foreignLease = {
sessionId: 'session-other',
promptId: 'prompt-other',
target: 'pr-42',
repositoryRoot: process.cwd(),
worktreePath: '.qwen/tmp/review-pr-42',
branch: 'qwen-review/pr-42',
};

it('refuses with an actionable error when another session holds the lease', async () => {
vi.mocked(readReviewWorktreeLease).mockReturnValueOnce(foreignLease);
vi.mocked(reviewLeaseHeldByAnotherSession).mockReturnValueOnce(true);
Comment on lines +456 to +458

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Suggestion] Neither lock test verifies which lease target the command reads — mockReturnValueOnce is argument-blind, so the lock's target wiring is untested. The same shape exists in cleanup.test.ts's skip test (readReviewWorktreeLease is never argument-asserted there either). — Failure scenario: probe-verified surviving mutant — readReviewWorktreeLease(process.cwd(), leaseTarget) → readReviewWorktreeLease(process.cwd(), 'pr-999') keeps 38/38 fetch-pr tests and 29/29 cleanup tests green; the 'qwen-review-lease-pr-42.json' assertion only pins the target passed to reviewLeasePath for the error message (a separate call). In production the lock consults an unrelated PR's lease file, the same-PR race goes undetected, and the concurrent same-PR worktree destruction recurs.

Witness:

under the 'pr-999' mutant:   Tests 38 passed (38)   <- survives
with the assertion below:    AssertionError: expected "spy" to be called with arguments ... - "pr-42", + "pr-999"   <- killed

Fix: assert the wiring in both suites:

expect(vi.mocked(readReviewWorktreeLease)).toHaveBeenCalledWith(process.cwd(), 'pr-42');
// and in the cleanup skip test:
expect(vi.mocked(readReviewWorktreeLease)).toHaveBeenCalledWith(process.cwd(), 'pr-123');
中文说明

[建议] 两个锁测试都没有验证命令读取的是哪个租约目标——mockReturnValueOnce 对参数不敏感,因此锁的目标接线未被测试。cleanup.test.ts 的跳过测试存在同样的形态(那里的 readReviewWorktreeLease 同样从未被参数断言)。— 失败场景:经探针验证的存活变异体——readReviewWorktreeLease(process.cwd(), leaseTarget) → readReviewWorktreeLease(process.cwd(), 'pr-999') 仍使 fetch-pr 38/38、cleanup 29/29 测试全绿;'qwen-review-lease-pr-42.json' 断言只钉住了传给 reviewLeasePath 用于报错文案的目标(另一次调用)。在生产中锁会去查一个无关 PR 的租约文件,同 PR 竞态无法被检测到,并发同 PR 审查互相删除 worktree 的问题会复现。

证据:'pr-999' 变异体下 Tests 38 passed (38)(存活);加上下方断言后 AssertionError: expected "spy" to be called with arguments ... - "pr-42", + "pr-999"(被杀)。

修复:在两个测试套件中断言接线(fetch-pr 用 'pr-42',cleanup 用 'pr-123')。

— qwen3.8-max via Qwen Code /review (v0.21.11)


await expect(reportFor({})).rejects.toThrow(
'PR #42 is already being reviewed by another session ' +
'(session session-other)',
);
// The lock must consult THIS PR's lease: mockReturnValueOnce is
// argument-blind, so an unwired target leaves the race undetected.
expect(vi.mocked(readReviewWorktreeLease)).toHaveBeenCalledWith(
process.cwd(),
'pr-42',
);
// Nothing was touched on the way out.
expect(vi.mocked(createReviewWorktreeLease)).not.toHaveBeenCalled();
expect(producerMocks.git).not.toHaveBeenCalled();
expect(producerMocks.gh).not.toHaveBeenCalled();
expect(producerMocks.releaseWorktree).not.toHaveBeenCalled();
expect(producerMocks.execFileSync).not.toHaveBeenCalled();
expect(producerMocks.writeFileSync).not.toHaveBeenCalled();
Comment on lines +477 to +483

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Suggestion] The refusal test's comment promises "the refusal must precede every destructive step", but its negative-space assertions omit cleanStale's releaseWorktree/execFileSync — the most destructive steps in the function. — Failure scenario: probe-verified surviving mutant — moving cleanStale(prNumber) above the lock check keeps the lease-lock tests green (2/2): releaseWorktree is an anonymous no-op vi.fn in the ./lib/git.js mock factory (not in producerMocks) and refExists is mocked false so the branch delete is skipped, so cleanStale leaves no trace in any asserted mock. In production that mutant removes the holder's worktree before refusing — the exact #9205 destruction this PR exists to prevent.

Witness:

MUTANT-B (cleanStale moved above the lock) vs original tests:
  Tests 2 passed | 36 skipped (38)   <- survives
MUTANT-B + the fix below:
  AssertionError: expected "spy" to not be called at all, but actually been called 1 times   <- killed

Fix: hoist releaseWorktree from the ./lib/git.js factory into producerMocks and assert it here (ideally a hoisted execFileSync assertion too):

expect(producerMocks.releaseWorktree).not.toHaveBeenCalled();
中文说明

[建议] 拒绝测试的注释承诺"拒绝必须先于所有破坏性步骤",但其"什么都没发生"断言遗漏了 cleanStale 的 releaseWorktree/execFileSync——函数中最具破坏性的步骤。— 失败场景:经探针验证的存活变异体——把 cleanStale(prNumber) 移到锁检查之上,lease-lock 测试仍然全绿(2/2):releaseWorktree 是 ./lib/git.js mock 工厂里的匿名空 vi.fn(不在 producerMocks 中),且 refExists 被 mock 为 false 使分支删除被跳过,因此 cleanStale 不会在任何被断言的 mock 上留下痕迹。在生产中该变异体会在拒绝之前删除持有者的 worktree——正是本 PR 要阻止的 #9205 破坏。

证据:变异体(cleanStale 上移)对原测试 Tests 2 passed | 36 skipped (38)(存活);加上下方修复后 AssertionError: expected "spy" to not be called at all, but actually been called 1 times(被杀)。

修复:把 releaseWorktree 从 ./lib/git.js 工厂提升进 producerMocks,并在此断言它未被调用(最好同时提升并断言 execFileSync)。

— qwen3.8-max via Qwen Code /review (v0.21.11)

});

it('names the lease file to delete when the holder session is gone', async () => {
vi.mocked(readReviewWorktreeLease).mockReturnValueOnce(foreignLease);
vi.mocked(reviewLeaseHeldByAnotherSession).mockReturnValueOnce(true);

await expect(reportFor({})).rejects.toThrow(
'qwen-review-lease-pr-42.json',
);
});

it('lets the holding session re-fetch its own lease', async () => {
// Ownership is per session, not per prompt: a later round re-fetches
// while its own earlier prompt's lease is still on disk.
vi.mocked(readReviewWorktreeLease).mockReturnValueOnce({
...foreignLease,
sessionId: 'session-self',
promptId: 'prompt-earlier',
});
vi.mocked(reviewLeaseHeldByAnotherSession).mockReturnValueOnce(false);

await reportFor({});

expect(vi.mocked(createReviewWorktreeLease)).toHaveBeenCalledTimes(1);
});
});

// A handled failure after the lease write must roll the lease back with the
// rest of the state: the lock refuses any later session that finds another
// session's lease, so one left behind blocks every later review of this PR
// until it is deleted by hand.
describe('lease rollback on failure', () => {
it('clears the lease when the PR fetch fails', async () => {
producerMocks.git.mockImplementation(() => {
throw new Error('network down');
});

await expect(reportFor({})).rejects.toThrow(
'Failed to fetch PR #42 from remote "origin"',
);
expect(vi.mocked(clearReviewWorktreeLease)).toHaveBeenCalledWith(
process.cwd(),
'pr-42',
);
});

it('clears the lease when the metadata fetch fails', async () => {
producerMocks.gh.mockImplementation(() => {
throw new Error('gh unavailable');
});

await expect(reportFor({})).rejects.toThrow(
'Failed to fetch PR #42 metadata',
);
expect(producerMocks.execFileSync).toHaveBeenCalledWith(
'git',
['branch', '-D', 'qwen-review/pr-42'],
{ stdio: 'pipe' },
);
expect(vi.mocked(clearReviewWorktreeLease)).toHaveBeenCalledWith(
process.cwd(),
'pr-42',
);
});

it('clears the lease when the worktree add fails', async () => {
producerMocks.git.mockImplementation((...args: string[]) => {
if (args[0] === 'worktree') throw new Error('disk full');
return args[0] === 'rev-parse' ? 'f00df00d' : '';
});

await expect(reportFor({})).rejects.toThrow(
'Failed to create worktree at',
);
expect(vi.mocked(clearReviewWorktreeLease)).toHaveBeenCalledWith(
process.cwd(),
'pr-42',
);
});
});

it('preserves the earliest window opening across drift restarts of the same PR', async () => {
// A drift restart reruns fetch-pr and overwrites this report; the audit
// boundary must keep reaching back to the abandoned attempt's opening.
Expand Down
41 changes: 38 additions & 3 deletions packages/cli/src/commands/review/fetch-pr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,13 @@ import { execFileSync } from 'node:child_process';
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { writeStdoutLine, writeStderrLine } from '../../utils/stdioHelpers.js';
import { createReviewWorktreeLease } from '../../services/review-worktree-lease.js';
import {
clearReviewWorktreeLease,
createReviewWorktreeLease,
readReviewWorktreeLease,
reviewLeaseHeldByAnotherSession,
reviewLeasePath,
} from '../../services/review-worktree-lease.js';
import { ensureAuthenticated, gh, setGhHost } from './lib/gh.js';
import type { ReviewEffort } from './parse-args.js';
import { git, gitOpt, gitRaw, refExists, releaseWorktree } from './lib/git.js';
Expand Down Expand Up @@ -189,10 +195,33 @@ async function runFetchPr(args: FetchPrArgs): Promise<void> {

const ref = reviewBranch(prNumber);
const wt = worktreePath(prNumber);

// The lease is also a lock. The worktree path is fixed per PR number, so
// the stale-clean below would remove a worktree ANOTHER session is actively
// reviewing — that is precisely how #9205 destroyed a round-4 review mid-run.
// Refuse before touching anything; the refusal must precede both the lease
// write and `cleanStale`, because a fetch-pr that fails AFTER either one
// has still clobbered the holder's lease and state. Same-session re-fetches
// (drift restarts, later rounds of a multi-prompt review) pass: ownership
// is per session, not per prompt.
const leaseTarget = `pr-${prNumber}`;
const holder = readReviewWorktreeLease(process.cwd(), leaseTarget);
if (reviewLeaseHeldByAnotherSession(holder)) {
Comment on lines +642 to +643

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Suggestion] fetch-pr has no test that an existing lease held by the SAME session lets the fetch proceed — cleanup has the symmetric "proceeds when the lease belongs to this session" test, but this suite only exercises "no lease" and "foreign lease refuses". — Failure scenario: probe-verified surviving mutant — if (reviewLeaseHeldByAnotherSession(holder)) → if (holder) keeps 38/38 tests green (the refusal tests' holder is non-null; every other test's default read returns null), so lock-by-mere-presence ships. In production that locks a session out of its own lease: a later round of a multi-prompt review re-runs fetch-pr while the earlier prompt's lease is still on disk and refuses — contradicting the comment above ("ownership is per session, not per prompt").

Witness: under the if (holder) mutant, a same-session test fails with Error: PR #42 is already being reviewed by another session (session session-self) thrown at this line; against correct code 39/39 pass.

Fix: add a lease-lock test where readReviewWorktreeLease returns a lease whose sessionId equals QWEN_CODE_SESSION_ID and reviewLeaseHeldByAnotherSession returns false, asserting the run proceeds (no throw, createReviewWorktreeLease called).

中文说明

[建议] fetch-pr 没有测试"同一会话已持有租约时 fetch 应继续"——cleanup 有对称的"租约属于本会话时继续"测试,但 fetch-pr 的锁测试只覆盖"无租约"和"他会话租约拒绝"两种情况。— 失败场景:经探针验证的存活变异体——if (reviewLeaseHeldByAnotherSession(holder)) → if (holder) 仍使 38/38 测试全绿(拒绝测试的 holder 非空;其他测试的默认读取返回 null),因此"只要有租约就锁"的形态可以绿灯上线。在生产中这会把会话锁在自己的租约之外:多 prompt 审查的后续轮次在上一 prompt 的租约仍在磁盘上时重跑 fetch-pr 会被拒绝——与上方注释("所有权按会话而非 prompt 判定")矛盾。

证据:if (holder) 变异体下同会话测试失败,抛出 Error: PR #42 is already being reviewed by another session (session session-self);正确代码下 39/39 通过。

修复:新增锁测试——readReviewWorktreeLease 返回 sessionId 等于 QWEN_CODE_SESSION_ID 的租约且 reviewLeaseHeldByAnotherSession 返回 false,断言运行继续(不抛错、createReviewWorktreeLease 被调用)。

— qwen3.8-max via Qwen Code /review (v0.21.11)

throw new Error(
`PR #${prNumber} is already being reviewed by another session ` +
`(session ${holder.sessionId}). Same-PR reviews share one worktree ` +
`path and cannot run concurrently, so this run refuses rather than ` +
`destroy the other session's state. Wait for that session to finish ` +
`— its cleanup releases the lease — or, only if that session is ` +
`gone, delete ${reviewLeasePath(process.cwd(), leaseTarget)} and ` +
`re-run.`,
);
}

createReviewWorktreeLease({
sessionId: process.env['QWEN_CODE_SESSION_ID'],

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Suggestion] When fetch-pr fails after writing the lease, it rolls back the branch ref but not the lease — every post-lease-write failure path (git fetch failure, gh pr view failure, worktree-add failure) leaves qwen-review-lease-pr-<n>.json on disk. — Failure scenario: session A starts a review, the lease is written, then a transient git fetch failure throws. The ref is rolled back but the lease remains; the skill stops on fetch failure so the cleanup step never runs, and the end-of-prompt sweep only fires on cancel/error with an exact session+prompt match. A later session B's fetch-pr then refuses with "already being reviewed by another session (session A)" though nothing is reviewing, and B's cleanup skips the target wholesale — until someone deletes the lease file by hand. Unlike the documented hard-kill case, this is triggered by ordinary handled failures whose own function already rolls back sibling state.

Fix: call clearReviewWorktreeLease(process.cwd(), leaseTarget) on the post-lease-write failure paths, alongside the existing branch-ref rollbacks:

tryRemove(() => execFileSync('git', ['branch', '-D', ref], ...));
clearReviewWorktreeLease(process.cwd(), leaseTarget);

A same-session retry rewrites the lease freely, so this is safe.

中文说明

[建议] fetch-pr 在写入租约之后失败时只回滚分支引用、不回滚租约——写租约之后的所有失败路径(git fetch 失败、gh pr view 失败、worktree 创建失败)都会把 qwen-review-lease-pr-<n>.json 留在磁盘上。— 失败场景:会话 A 开始审查、租约已写入,随后一次瞬时的 git fetch 失败抛错。分支引用被回滚但租约留下;技能在 fetch 失败时即停止,因此清理步骤永远不会运行,而 prompt 结束清扫只在取消/出错且 session+prompt 完全匹配时触发。之后会话 B 的 fetch-pr 会以 "already being reviewed by another session (session A)" 拒绝——尽管实际没有任何审查在进行,且 B 的 cleanup 会整体跳过该目标——直到有人手动删除租约文件。与已记录的硬杀场景不同,这是由普通的、已处理的失败触发的,而该函数本已回滚了同批创建的其他状态。

修复:在写租约之后的失败路径上调用 clearReviewWorktreeLease(process.cwd(), leaseTarget),与现有的分支引用回滚并列。同会话重试会自由重写租约,因此该修复是安全的。

— qwen3.8-max via Qwen Code /review (v0.21.11)

promptId: process.env['QWEN_CODE_PROMPT_ID'],
target: `pr-${prNumber}`,
target: leaseTarget,
repositoryRoot: process.cwd(),
worktreePath: wt,
branch: ref,
Expand All @@ -205,6 +234,10 @@ async function runFetchPr(args: FetchPrArgs): Promise<void> {
try {
git('fetch', remote, `pull/${prNumber}/head:${ref}`);
} catch (err) {
// Roll back the lease too: the lock above refuses any later session that
// finds another session's lease, so one left behind by a handled failure
// would block every later review of this PR until deleted by hand.
clearReviewWorktreeLease(process.cwd(), leaseTarget);
throw new Error(
`Failed to fetch PR #${prNumber} from remote "${remote}": ${(err as Error).message}`,
);
Expand All @@ -226,10 +259,11 @@ async function runFetchPr(args: FetchPrArgs): Promise<void> {
);
meta = JSON.parse(json) as PrMetadata;
} catch (err) {
// Roll back the fetched ref so the next run starts clean.
// Roll back the fetched ref and the lease so the next run starts clean.
tryRemove(() =>
execFileSync('git', ['branch', '-D', ref], { stdio: 'pipe' }),
);
clearReviewWorktreeLease(process.cwd(), leaseTarget);
throw new Error(
`Failed to fetch PR #${prNumber} metadata: ${(err as Error).message}`,
);
Expand All @@ -243,6 +277,7 @@ async function runFetchPr(args: FetchPrArgs): Promise<void> {
tryRemove(() =>
execFileSync('git', ['branch', '-D', ref], { stdio: 'pipe' }),
);
clearReviewWorktreeLease(process.cwd(), leaseTarget);
throw new Error(
`Failed to create worktree at ${wt}: ${(err as Error).message}`,
);
Expand Down
Loading
Loading