Skip to content
6 changes: 4 additions & 2 deletions packages/cli/src/commands/review/cleanup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { writeStdoutLine, writeStderrLine } from '../../utils/stdioHelpers.js';
import { refExists, releaseWorktree } from './lib/git.js';
import {
worktreePath,
probeWorktreePath,
reviewBranch,
REVIEW_TMP_DIR,
tmpPrefix,
Expand Down Expand Up @@ -46,8 +47,9 @@ function runCleanup(target: string): void {

// The test-efficacy probe runs in a disposable sibling worktree and removes
// it itself; sweep one a crashed probe left behind so it does not block the
// next run's `git worktree add` (see #6832 / test-efficacy.ts).
const probeWt = `${wt}-probe`;
// next run's `git worktree add` (see #6832 / test-efficacy.ts). Shares the
// path helper with the probe so the suffix cannot drift between the two.
const probeWt = probeWorktreePath(wt);
if (releaseWorktree(probeWt)) {
Comment thread
wenshao marked this conversation as resolved.
Resolved
writeStdoutLine(`Removed probe worktree: ${probeWt}`);
removedAny = true;
Expand Down
28 changes: 27 additions & 1 deletion packages/cli/src/commands/review/lib/paths.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
*/

import { describe, it, expect } from 'vitest';
import { tmpFile } from './paths.js';
import { resolve } from 'node:path';
import { tmpFile, probeWorktreePath, worktreePath } from './paths.js';

describe('tmpFile — target is a single safe component', () => {
it('keeps ordinary labels intact', () => {
Expand Down Expand Up @@ -34,3 +35,28 @@ describe('tmpFile — target is a single safe component', () => {
expect(p.split('.qwen/tmp/')[1]).not.toContain('/');
});
});

describe('probeWorktreePath', () => {
it('appends -probe to an absolute worktree path', () => {
expect(probeWorktreePath('/a/b/review-pr-1')).toBe(
'/a/b/review-pr-1-probe',
);
});

it('resolves a relative worktree to absolute so it never depends on cwd', () => {
// The probe drives `git worktree add` with the shared worktree as cwd, so a
// relative probe path would resolve against that worktree and nest the probe
// tree inside it. Absolute keeps it a sibling wherever it is called from.
expect(probeWorktreePath('.qwen/tmp/review-pr-1')).toBe(
`${resolve('.qwen/tmp/review-pr-1')}-probe`,
);
});

it('is the single source of the -probe suffix both call sites share', () => {
// cleanup.ts sweeps `probeWorktreePath(worktreePath(n))`; the probe creates
// `probeWorktreePath(worktree)`. One helper, one suffix — they cannot drift.
expect(probeWorktreePath(worktreePath(7))).toBe(
`${resolve(worktreePath(7))}-probe`,
);
});
});
19 changes: 18 additions & 1 deletion packages/cli/src/commands/review/lib/paths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
// when the command is invoked). Use `path.join` rather than string
// concatenation so Windows backslashes are produced when needed.

import { join } from 'node:path';
import { join, resolve } from 'node:path';

export const REVIEW_TMP_DIR = join('.qwen', 'tmp');
export const REVIEWS_DIR = join('.qwen', 'reviews');
Expand All @@ -20,6 +20,23 @@ export function worktreePath(prNumber: string | number): string {
return join(REVIEW_TMP_DIR, `review-pr-${prNumber}`);
}

/**
* The disposable worktree the test-efficacy probe runs in — a sibling of the
* shared review worktree, discarded wholesale when the probe finishes (#6832).
*
* The one exception to this file's "paths are relative to the project root"
* rule: this returns an ABSOLUTE path. The probe drives `git worktree add`/
* `remove` with the shared worktree as cwd, so a relative path would resolve
* against that worktree, not the repo root, and land the probe tree nested
* inside the tree it is meant to sit beside. Both call sites — the probe and
* `cleanup.ts`'s stale-tree sweep — go through here so the `-probe` suffix and
* this normalisation stay in one place; renaming the suffix in one file used to
* silently stop the other from sweeping.
*/
export function probeWorktreePath(worktree: string): string {
Comment thread
wenshao marked this conversation as resolved.
Resolved
return `${resolve(worktree)}-probe`;
}

/** Local branch ref name for a fetched PR head. */
export function reviewBranch(prNumber: string | number): string {
return `qwen-review/pr-${prNumber}`;
Expand Down
111 changes: 90 additions & 21 deletions packages/cli/src/commands/review/test-efficacy.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,35 @@ function treeState(wt: string): string {
);
}

/**
* A minimal same-repo PR: source `f` changes 1→2, with a reachable test that
* passes regardless (so a revert probe reads it as inert). Returns the shared
Comment thread
wenshao marked this conversation as resolved.
Resolved
* worktree and base SHA, with the report already written to `report.json`.
*/
function scaffoldModifiedPr(): { wt: string; base: string } {
write('package.json', '{"private":true,"workspaces":["packages/*"]}\n');
write('packages/lib/src/f.ts', 'export const f = () => 1;\n');
const base = commitAll('base');
write('packages/lib/src/f.ts', 'export const f = () => 2;\n');
write(
'packages/lib/src/f.test.ts',
'import { f } from "./f.js"; import { it, expect } from "vitest"; it("t", () => expect(typeof f).toBe("function"));\n',
);
commitAll('pr');
const wt = join(repo, 'wt');
git(repo, 'worktree', 'add', '-q', '--detach', wt, 'HEAD');
writeFileSync(
join(repo, 'report.json'),
JSON.stringify({
files: [
{ path: 'packages/lib/src/f.ts', kind: 'source' },
{ path: 'packages/lib/src/f.test.ts', kind: 'test' },
],
}),
);
return { wt, base };
}

beforeEach(() => {
repo = mkdtempSync(join(tmpdir(), 'efficacy-iso-'));
outside = mkdtempSync(join(tmpdir(), 'efficacy-outside-'));
Expand Down Expand Up @@ -111,27 +140,7 @@ afterEach(() => {

describe('test-efficacy probe isolation (#6832)', () => {
it('probes in a disposable worktree and never mutates the shared one', async () => {
write('package.json', '{"private":true,"workspaces":["packages/*"]}\n');
write('packages/lib/src/f.ts', 'export const f = () => 1;\n');
const base = commitAll('base');
write('packages/lib/src/f.ts', 'export const f = () => 2;\n');
write(
'packages/lib/src/f.test.ts',
'import { f } from "./f.js"; import { it, expect } from "vitest"; it("t", () => expect(typeof f).toBe("function"));\n',
);
commitAll('pr');

const wt = join(repo, 'wt');
git(repo, 'worktree', 'add', '-q', '--detach', wt, 'HEAD');
writeFileSync(
join(repo, 'report.json'),
JSON.stringify({
files: [
{ path: 'packages/lib/src/f.ts', kind: 'source' },
{ path: 'packages/lib/src/f.test.ts', kind: 'test' },
],
}),
);
const { wt, base } = scaffoldModifiedPr();

const before = treeState(wt);
await runHandler({
Expand Down Expand Up @@ -215,4 +224,64 @@ describe('test-efficacy probe isolation (#6832)', () => {
expect(treeState(wt)).toBe(before);
expect(existsSync(join(repo, 'wt-probe'))).toBe(false);
});

it('sweeps a stale REGISTERED probe worktree left by a crashed run', async () => {
const { wt, base } = scaffoldModifiedPr();
// A prior probe crashed after `worktree add` but before its cleanup, leaving
// the probe tree registered. The pre-sweep must unregister and replace it,
// not fail `add` on the collision.
git(
repo,
'worktree',
'add',
'-q',
'--detach',
join(repo, 'wt-probe'),
'HEAD',
);
expect(existsSync(join(repo, 'wt-probe'))).toBe(true);

await runHandler({
report: join(repo, 'report.json'),
worktree: wt,
base,
out: join(repo, 'out.json'),
});

// The probe ran (a real verdict, not a "could not be created" inconclusive)
// and left the tree cleaned up.
const out = JSON.parse(readFileSync(join(repo, 'out.json'), 'utf8'));
expect(out.findings.map((f: { file: string }) => f.file)).toContain(
'packages/lib/src/f.test.ts',
);
expect(existsSync(join(repo, 'wt-probe'))).toBe(false);
});

it('clears an UNREGISTERED non-empty leftover so the probe is not wedged', async () => {
const { wt, base } = scaffoldModifiedPr();
// A partial cleanup left a directory at the probe path that git no longer
// tracks as a worktree, and it is non-empty. `git worktree remove` cannot
// clear it ("not a working tree"), and without the rmSync fallback the next
// `git worktree add` fails "already exists" — wedging every probe as
// inconclusive until someone clears it by hand.
mkdirSync(join(repo, 'wt-probe', 'junk'), { recursive: true });
writeFileSync(join(repo, 'wt-probe', 'junk', 'f'), 'x');

await runHandler({
report: join(repo, 'report.json'),
worktree: wt,
base,
out: join(repo, 'out.json'),
});

const out = JSON.parse(readFileSync(join(repo, 'out.json'), 'utf8'));
const details = (out.probed as Array<{ detail?: string }>).map(
(p) => p.detail ?? '',
);
expect(details.join('\n')).not.toMatch(/could not be created/);
expect(out.findings.map((f: { file: string }) => f.file)).toContain(
'packages/lib/src/f.test.ts',
);
expect(existsSync(join(repo, 'wt-probe'))).toBe(false);
});
});
34 changes: 27 additions & 7 deletions packages/cli/src/commands/review/test-efficacy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,9 @@ import {
rmSync,
lstatSync,
} from 'node:fs';
import { dirname, join, isAbsolute, resolve, sep } from 'node:path';
import { dirname, join, isAbsolute, sep } from 'node:path';
import { writeStdoutLine, writeStderrLine } from '../../utils/stdioHelpers.js';
import { probeWorktreePath } from './lib/paths.js';

export type ProbeVerdict = 'gated' | 'inert' | 'inconclusive';

Expand Down Expand Up @@ -396,22 +397,41 @@ async function runTestEfficacy(args: TestEfficacyArgs): Promise<void> {
// repo-root `node_modules` — exactly how the shared review worktree already
// runs vitest.
const headSha = gitOut(worktree, 'rev-parse', 'HEAD');
const probeTree = `${resolve(worktree)}-probe`;
const probeTree = probeWorktreePath(worktree);
let created = false;
let sweep: ReturnType<typeof spawnSync> | undefined;
try {
// Sweep a stale probe tree left by a crashed run — it would fail `add`.
// Best-effort (no stale tree is the normal case), so it does not go through
// the throwing `git()` wrapper.
spawnSync('git', ['worktree', 'remove', '--force', probeTree], {
// Two ways it can be stale, and `worktree remove` only clears one:
// - REGISTERED (metadata intact) — `worktree remove --force` unregisters
// it and deletes the dir.
// - an UNREGISTERED directory (metadata lost, or a partial cleanup) —
// `worktree remove` says "not a working tree" and leaves it, and then a
// *non-empty* leftover makes `worktree add` fail `already exists`,
// wedging every probe as `inconclusive` until someone clears it by hand.
// So follow the unregister sweep with a plain remove of whatever dir is
// still there. Both are best-effort — no stale tree is the normal case — so
// the unregister does not go through the throwing `git()` wrapper, and its
// stderr is kept to explain a subsequent `add` failure. `rmSync` on the
// path unlinks a symlink rather than following it, so even a tampered
// leftover cannot redirect the delete outside `probeTree`.
sweep = spawnSync('git', ['worktree', 'remove', '--force', probeTree], {
cwd: worktree,
encoding: 'utf8',
});
rmSync(probeTree, { recursive: true, force: true });
Comment thread
wenshao marked this conversation as resolved.
Resolved
git(worktree, 'worktree', 'add', '--detach', probeTree, headSha);
created = true;
} catch (e) {
// Could not isolate — probe nothing rather than fall back to mutating the
// shared tree. Probes are inconclusive; the unreachable findings, which
Comment thread
wenshao marked this conversation as resolved.
Resolved
// need no probe, still ship.
const detail = `probe worktree could not be created: ${e instanceof Error ? e.message : String(e)}`;
// need no probe, still ship. Surface the stale-sweep's stderr too: when the
// `add` fails on a leftover the sweep could not clear, that is the context
// that explains why.
const sweepErr = String(sweep?.stderr ?? '').trim();
const detail =
`probe worktree could not be created: ${e instanceof Error ? e.message : String(e)}` +
(sweepErr ? ` (stale-tree sweep also reported: ${sweepErr})` : '');
for (const file of probes) {
results.push({ file, verdict: 'inconclusive' as const, detail });
}
Expand Down
Loading