Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 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
33 changes: 33 additions & 0 deletions packages/cli/src/commands/review/compose-review.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -920,6 +920,39 @@ describe('composeReviewCommand handler (the CLI glue)', () => {
).toBe(true);
});

it('pins the persisted footer to the inherited startup version, not the resolved one', async () => {
// Same pin as `submit`: a shared runner rewrites installs under running
// processes, so the version resolved at compose time can disagree with
// the one the session started under. The archived verdict must carry the
// startup stamp, or it contradicts the review `submit` posts.
const dir = mkdtempSync(join(tmpdir(), 'compose-startup-'));
const inputPath = join(dir, 'compose.json');
const commentsPath = join(dir, 'comments.json');
const outPath = join(dir, 'composed.json');
writeFileSync(inputPath, JSON.stringify({ modelId: MODEL }), 'utf8');
writeFileSync(commentsPath, '[]', 'utf8');
const inherited = process.env['QWEN_CODE_STARTUP_VERSION'];
process.env['QWEN_CODE_STARTUP_VERSION'] = '0.21.1';
try {
await runComposeReviewCommand({
input: inputPath,
comments: commentsPath,
out: outPath,
});
const written = JSON.parse(
readFileSync(outPath, 'utf8'),
) as ComposeReviewResult;
expect(
written.body.endsWith(`_— ${MODEL} via Qwen Code /review (v0.21.1)_`),
).toBe(true);
} finally {
if (inherited === undefined)
delete process.env['QWEN_CODE_STARTUP_VERSION'];
else process.env['QWEN_CODE_STARTUP_VERSION'] = inherited;
rmSync(dir, { recursive: true, force: true });
}
});

it('routes its gh calls via the PR host — --host reaches setGhHost', async () => {
// The bilingual body-language recovery calls `gh pr view`; on GitHub Enterprise
// that call must hit the PR's host, or the composed body's language disagrees
Expand Down
7 changes: 5 additions & 2 deletions packages/cli/src/commands/review/compose-review.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import {
unmarkedComments,
type DraftedComment,
} from './lib/inline-counts.js';
import { reviewFooter } from './lib/review-footer.js';

export type ReviewEvent = 'APPROVE' | 'REQUEST_CHANGES' | 'COMMENT';

Expand Down Expand Up @@ -777,7 +778,7 @@ function composeReviewBody(
}
}

const footer = `_— ${modelId} via Qwen Code /review (v${cliVersion})_`;
const footer = reviewFooter(modelId, cliVersion);
// Bilingual rendering: when the plan (fetch-pr's report) says the PR
// description contains Han characters, the posted body carries the complete
// Chinese version collapsed under the English one — the shape this repo's
Expand Down Expand Up @@ -1725,7 +1726,9 @@ export const composeReviewCommand: CommandModule = {
...countInlineFindings(drafted),
draftedComments: drafted,
},
await getCliVersion(),
// Same pin as `submit`: the startup stamp, not a version resolved at
// compose time — a shared runner can rewrite the install mid-session.
process.env['QWEN_CODE_STARTUP_VERSION'] || (await getCliVersion()),
);
// The exact terminal verdict, persisted beside the fields it is computed
// from. `event` + `cappedBy` alone cannot reconstruct it — a presubmit
Expand Down
28 changes: 28 additions & 0 deletions packages/cli/src/commands/review/lib/review-footer.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/

import { describe, expect, it } from 'vitest';
import { REVIEW_FOOTER_RE, reviewFooter } from './review-footer.js';

describe('the review footer and the regex that strips it', () => {
it('the regex strips the exact output of the builder, versioned or not', () => {
// The sync guarantee: a wording edit to the builder that the regex no
// longer matches reddens here before it reaches a posted review.
for (const footer of [
reviewFooter('qwen3.7-max', '0.21.3'),
'_— qwen3.7-max via Qwen Code /review_',
]) {
expect(`a finding\n\n${footer}\n`.replace(REVIEW_FOOTER_RE, '')).toBe(
'a finding',
);
}
});

it('leaves a footer run alone when text follows it', () => {
const body = `a finding\n\n${reviewFooter('m', '0.21.3')}\n\na closing line`;
expect(body.replace(REVIEW_FOOTER_RE, '')).toBe(body);
});
});
36 changes: 36 additions & 0 deletions packages/cli/src/commands/review/lib/review-footer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/

// The attribution footer every posted review carries, stated once.
//
// `compose-review` composes it into the verdict body and `submit` strips
// forged copies before appending the real one to each inline comment — two
// producers by construction, plus the regex that must match both. They used
// to be side-by-side template literals with nothing asserting they stayed in
// step: a wording edit to one leaves the strip regex unable to match the
// composed footer (duplicates posted) or the summary carrying one version
// while the comments carry another — the exact attribution skew the startup
// version stamp exists to eliminate. Same shape as `inline-counts.ts`, which
// this directory already shares between the same two commands.

/** The footer naming the reviewing model and the CLI version it ran under. */
export function reviewFooter(modelId: string, cliVersion: string): string {
return `_— ${modelId} via Qwen Code /review (v${cliVersion})_`;
}

/**
* One or more trailing footers, with the whitespace around them.
*
* The leading `\s*` sits OUTSIDE the repeated group so each run of
* whitespace has exactly one owner. With it inside the group, the run
* between two footers could be split across iterations arbitrarily; when the
* trailing `$` then failed (a footer run followed by ordinary text — the
* natural output of a model looping on the same comment) the engine
* enumerated all those splits before giving up, growing ~27x per footer
* on the model-authored bodies this regex strips.
*/
export const REVIEW_FOOTER_RE =
/\s*(?:_— [^\n]* via Qwen Code \/review(?: \(v[^\n)]*\))?_\s*)+$/;
140 changes: 139 additions & 1 deletion packages/cli/src/commands/review/submit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,11 @@ vi.mock('../../utils/stdioHelpers.js', () => ({
writeStdoutLine: writeStdoutSpy,
writeStderrLine: vi.fn(),
}));
vi.mock('../../utils/version.js', () => ({
getCliVersion: vi.fn().mockResolvedValue('0.21.2'),
}));

const { runSubmit } = await import('./submit.js');
const { runSubmit, submitCommand } = await import('./submit.js');

let dir: string;
let savedSessionId: string | undefined;
Expand Down Expand Up @@ -460,6 +463,113 @@ describe('payload consistency — refuse before GitHub sees it', () => {
).toBe(true);
});

it('uses the inherited startup version instead of the resolved CLI version', async () => {
// Driven through the handler — the one production call site — with the
// stamp set: reverting the handler to a bare `getCliVersion()` reddens
// this, which is the exact regression the PR closes.
const inherited = process.env['QWEN_CODE_STARTUP_VERSION'];
process.env['QWEN_CODE_STARTUP_VERSION'] = '0.21.3';
try {
await submitCommand.handler?.(authorized({}) as never);
expect(posted().body).toContain('(v0.21.3)');
expect(posted().body).not.toContain('(v0.21.2)');
} finally {
if (inherited === undefined)
delete process.env['QWEN_CODE_STARTUP_VERSION'];
else process.env['QWEN_CODE_STARTUP_VERSION'] = inherited;
}
});

it('falls back to the resolved CLI version when no startup version is inherited', async () => {
const inherited = process.env['QWEN_CODE_STARTUP_VERSION'];
delete process.env['QWEN_CODE_STARTUP_VERSION'];
try {
await submitCommand.handler?.(authorized({}) as never);
expect(posted().body).toContain('(v0.21.2)');
} finally {
if (inherited === undefined)
delete process.env['QWEN_CODE_STARTUP_VERSION'];
else process.env['QWEN_CODE_STARTUP_VERSION'] = inherited;
}
});

it('normalizes summary and inline footers to the running CLI version', () => {
const review = file('footer-version.json', {
...REVIEW,
comments: [
{
path: 'a.ts',
line: 12,
body: '**[Suggestion]** tidy\n\n_— forged via Qwen Code /review (v0.21.4)_\n\n_— forged via Qwen Code /review (v0.21.4)_',
},
],
});

runSubmit(authorized({ review }), '0.21.3');

const body = posted().body as string;
const inline = posted().comments[0].body as string;
for (const text of [body, inline]) {
expect(text).toContain('(v0.21.3)');
expect(text).not.toContain('(v0.21.4)');
expect(text.match(/via Qwen Code \/review/g)).toHaveLength(1);
}
expect(inline.startsWith('**[Suggestion]**')).toBe(true);
});

it('strips a forged footer with no version suffix — the legacy shape', () => {
const review = file('footer-legacy.json', {
...REVIEW,
comments: [
{
path: 'a.ts',
line: 12,
body: '**[Suggestion]** tidy\n\n_— forged via Qwen Code /review_\n',
},
],
});

runSubmit(authorized({ review }), '0.21.3');

const inline = posted().comments[0].body as string;
expect(inline).not.toContain('forged');
expect(inline.match(/via Qwen Code \/review/g)).toHaveLength(1);
expect(inline).toContain('(v0.21.3)');
});

it('does not hang on a run of forged footers followed by text', () => {
// A model looping on the same comment emits exactly this shape: the same
// footer over and over, then a closing line. The strip is attempted on
// that model-authored body before anything posts, and the whitespace
// between footers used to be splittable across the regex's repeated
// group — exponential in the footer count. The match must stay linear:
// this shape timed out the suite before the whitespace had one owner.
const footers = Array.from(
{ length: 8 },
() => '_— forged via Qwen Code /review (v0.21.4)_',
).join(' '.repeat(25));
const review = file('footer-hang.json', {
...REVIEW,
comments: [
{
path: 'a.ts',
line: 12,
body: `**[Suggestion]** tidy ${footers} one closing line`,
},
],
});

runSubmit(authorized({ review }), '0.21.3');

// Text after the footer run anchors it away from the end, so nothing is
// stripped; the canonical footer is appended once.
const inline = posted().comments[0].body as string;
expect(inline).toContain('one closing line');
expect(
inline.endsWith('_— qwen3.7-max via Qwen Code /review (v0.21.3)_'),
).toBe(true);
});

it('counts the blockers it is actually carrying, not the ones it was told about', () => {
// A Critical attached inline is a Critical, whatever the state says. There is
// no `criticalsInline` field to under-report it with — and one supplied
Expand Down Expand Up @@ -629,6 +739,34 @@ describe('payload consistency — refuse before GitHub sees it', () => {
expect(ghMock).not.toHaveBeenCalled();
});

it('refuses an empty-string body as empty, not as unmarked', () => {
// Normalisation runs before the consistency check; a footer pasted onto
// '' would turn the precise 'empty comment' refusal into a misleading
// 'missing severity marker' one.
const review = file('empty-body.json', {
...REVIEW,
comments: [{ path: 'a.ts', line: 12, body: '' }],
});

expect(() => runSubmit(authorized({ review }))).toThrow(/empty comment/);
expect(ghMock).not.toHaveBeenCalled();
});

it('refuses a `comments` field that is present but not an array', () => {
// `"comments": {}` used to escape normalisation — which runs outside
// `compose`'s try/catch — as a bare TypeError instead of the structured
// refusal the re-compose loop parses.
const review = file('comments-not-array.json', {
...REVIEW,
comments: {},
});

expect(() => runSubmit(authorized({ review }))).toThrow(
/`comments` is not an array/,
);
expect(ghMock).not.toHaveBeenCalled();
});

it('rejects a comment with no body', () => {
const review = file('bad-9.json', {
...REVIEW,
Expand Down
46 changes: 45 additions & 1 deletion packages/cli/src/commands/review/submit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ import {
countInlineFindings,
severityOf,
} from './lib/inline-counts.js';
import { REVIEW_FOOTER_RE, reviewFooter } from './lib/review-footer.js';

/** The only events GitHub's Create Review API accepts. */
const EVENTS = new Set(['APPROVE', 'REQUEST_CHANGES', 'COMMENT']);
Expand Down Expand Up @@ -123,6 +124,26 @@ interface ReviewPayload {
body?: unknown;
}

function normalizeInlineComments(
comments: ReviewComment[],
modelId: unknown,
cliVersion: string,
): ReviewComment[] {
if (typeof modelId !== 'string' || modelId.trim() === '') return comments;
const footer = reviewFooter(modelId, cliVersion);
return comments.map((comment) =>
// An empty body stays empty: this runs BEFORE the consistency check, and
// a footer pasted onto '' would hide the emptiness from the refusal that
// names it ('has no body — an empty comment').
typeof comment.body === 'string' && comment.body.trim() !== ''
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
? {
...comment,
body: `${comment.body.replace(REVIEW_FOOTER_RE, '')}\n\n${footer}`,
}
: comment,
);
}

// The severity prefixes and the counting live in `lib/inline-counts.ts`,
// shared with `compose-review`: the Step 6 verdict line and the Step 7 posted
// verdict must be the same computation on the same source, and two counting
Expand Down Expand Up @@ -221,6 +242,17 @@ function structuralProblems(payload: ReviewPayload): string[] {

if (!payload.commit_id) problems.push('`commit_id` is missing');

// The review JSON is a document the model writes, and `comments` reaches
// `.map` in the normalisation below — OUTSIDE `compose`'s try/catch. Any
// other shape is refused here as the structured refusal the re-compose
// loop parses, not a bare TypeError.
if (payload.comments !== undefined && !Array.isArray(payload.comments)) {
problems.push(
'`comments` is not an array — it is the list of findings this post ' +
'carries; any other shape is not a list of findings.',
);
}

// The verdict is not the caller's to write. Refusing is deliberate: silently
// ignoring a hand-written `event` would let a run believe it had posted the
// verdict it typed, and go on saying so in the terminal.
Expand Down Expand Up @@ -400,6 +432,15 @@ export function runSubmit(args: SubmitArgs, cliVersion = 'unknown'): void {
);
}

payload = {
...payload,
comments: normalizeInlineComments(
payload.comments ?? [],
payload.state?.modelId,
cliVersion,
),
};

// The verdict, computed here. It was never in the payload.
let event: string;
let body: string;
Expand Down Expand Up @@ -549,6 +590,9 @@ export const submitCommand: CommandModule = {
describe: 'Check authorisation and payload consistency, then stop.',
}),
handler: async (argv) => {
runSubmit(argv as unknown as SubmitArgs, await getCliVersion());
// Do not use CLI_VERSION here: esbuild replaces it with a build-time value.
const cliVersion =
process.env['QWEN_CODE_STARTUP_VERSION'] || (await getCliVersion());
runSubmit(argv as unknown as SubmitArgs, cliVersion);
},
};
Loading
Loading