Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
170 changes: 169 additions & 1 deletion packages/cli/src/commands/review/agent-prompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3649,6 +3649,10 @@ describe('per-chunk retirement — cold territories stop costing a round', () =>
beforeEach(() => {
(writeStdoutLine as unknown as Mock).mockClear();
(writeStderrLine as unknown as Mock).mockClear();
// Cleared beside its throwing siblings (#9259): uncleared, every
// assertion below read the ACCUMULATED output of earlier tests — an
// order-dependent oracle that passed on residue alone.
(writeStderrLineSafe as unknown as Mock).mockClear();
Comment thread
wenshao marked this conversation as resolved.
Resolved
dir = mkdtempSync(join(tmpdir(), 'ap-retire-'));
dirs.push(dir);
plan = join(dir, 'plan.json');
Expand All @@ -3659,11 +3663,25 @@ describe('per-chunk retirement — cold territories stop costing a round', () =>
utimesSync(plan, old, old);
findings = join(dir, 'findings.md');
writeFileSync(findings, '');
for (const k of ['QWEN_CODE_PROJECT_DIR', 'QWEN_CODE_SESSION_ID']) {
for (const k of [
'QWEN_CODE_PROJECT_DIR',
'QWEN_CODE_SESSION_ID',
// The budget gate reads these three straight from process.env on
// every admission the tests below drive (#9272): an ambient value
// inherited from a concurrent review makes admission
// environment-dependent — the same isolation the repro harness
// carries (#9259), on the describe that actually needs it.
'QWEN_REVIEW_DEADLINE_EPOCH',
'QWEN_REVIEW_DEADLINE_RESERVE_SECONDS',
'QWEN_CODE_MAX_TOOL_CONCURRENCY',
Comment thread
wenshao marked this conversation as resolved.
Resolved
]) {
SAVED[k] = process.env[k];
}
process.env['QWEN_CODE_PROJECT_DIR'] = dir;
process.env['QWEN_CODE_SESSION_ID'] = 'S1';
delete process.env['QWEN_REVIEW_DEADLINE_EPOCH'];
delete process.env['QWEN_REVIEW_DEADLINE_RESERVE_SECONDS'];
delete process.env['QWEN_CODE_MAX_TOOL_CONCURRENCY'];
mkdirSync(join(dir, 'subagents', 'S1'), { recursive: true });
});
afterEach(() => {
Expand Down Expand Up @@ -4707,6 +4725,12 @@ describe('per-chunk retirement — cold territories stop costing a round', () =>
expect(err).toContain(
'chunk 13 \u2014 round 1: no matching transcript; round 2: no matching transcript',
);
// The narrowing's absence half (#9259): chunk 14's failures exist in
// the same schedule but must NOT ride chunk 13's build — an
// unfiltered `schedule.diagnostics` here prints every chunk's note on
// every build, and the count lies about the coverage.
expect(err).not.toContain('chunk 14 \u2014');
expect(err).toContain('1 twice-audited chunk(s)');
// The first build admitted the round — its stamp is what used to gate
// the second build's diagnostic out.
expect(readRoundStamps(plan).some((s) => s.round === 3)).toBe(true);
Expand Down Expand Up @@ -4840,6 +4864,150 @@ describe('per-chunk retirement — cold territories stop costing a round', () =>
}
});

it('a refused round prints no audit NOTE — the round builder defers the catch note past the gate (#9259)', () => {
// Cap-3 plan, rounds 1-3 non-converging, transcripts unreadable: the
// schedule read dies AND round 4 is refused. The stderr must carry
// the ROUND CAP refusal only — a `auditing every chunk.` NOTE here
// promises an audit that never happens.
writeFileSync(
plan,
JSON.stringify({ ...PLAN, budget: { reverseAuditRounds: 3 } }),
);
const old = new Date(2020, 0, 1);
utimesSync(plan, old, old);
answerRound(1, { 13: YIELD, 14: YIELD, 15: YIELD });
answerRound(2, { 13: YIELD, 14: YIELD, 15: YIELD });
answerRound(3, { 13: YIELD, 14: YIELD, 15: YIELD });
delete process.env['QWEN_CODE_SESSION_ID'];
(writeStderrLineSafe as unknown as Mock).mockClear();

const out = runRound(4);

expect(process.exitCode).toBe(4);
expect(out).toBe('');
expect(keysOf(4)).toHaveLength(0);
const msg = (writeStderrLine as unknown as Mock).mock.calls
.map((c) => c[0])
.join('\n');
expect(msg).toContain('ROUND CAP');
const safe = (writeStderrLineSafe as unknown as Mock).mock.calls
.map((c) => String(c[0]))
.join('\n');
expect(safe).not.toContain('reverse-audit retirement unavailable');
});

it('a refused per-chunk build prints no audit NOTE either (#9259)', () => {
// The --chunk twin of the gate-side truthfulness: an unadmitted round
// 4 at cap 3 with an unreadable history is refused, and the refusal
// is the only thing stderr says about the round.
writeFileSync(
plan,
JSON.stringify({ ...PLAN, budget: { reverseAuditRounds: 3 } }),
);
const old = new Date(2020, 0, 1);
utimesSync(plan, old, old);
answerRound(1, { 13: YIELD, 14: YIELD, 15: YIELD });
answerRound(2, { 13: YIELD, 14: YIELD, 15: YIELD });
answerRound(3, { 13: YIELD, 14: YIELD, 15: YIELD });
delete process.env['QWEN_CODE_SESSION_ID'];
(writeStderrLineSafe as unknown as Mock).mockClear();

(agentPromptCommand.handler as (a: unknown) => void)({
plan,
role: 'reverse-audit',
findings,
chunk: 13,
round: 4,
});

expect(process.exitCode).toBe(4);
const msg = (writeStderrLine as unknown as Mock).mock.calls
.map((c) => c[0])
.join('\n');
expect(msg).toContain('ROUND CAP');
const safe = (writeStderrLineSafe as unknown as Mock).mock.calls
.map((c) => String(c[0]))
.join('\n');
expect(safe).not.toContain('reverse-audit retirement unavailable');
});

it('a repair build whose schedule begins to throw still names the degradation — once per round (#9259)', () => {
// Round 3's admission build (chunk 13) reads cleanly: stamp lands,
// nothing said. Then the history dies, and chunk 14's repair build
// must still print the NOTE — the stamp-keyed suppression this
// replaces silenced exactly this shape. Chunk 15's build repeats the
// failure and stays silent: the note earns its place once per round
// per process.
answerRound(1, { 13: DRY, 14: DRY, 15: YIELD });
answerRound(2, { 13: DRY, 14: DRY, 15: YIELD });
(writeStderrLineSafe as unknown as Mock).mockClear();
(agentPromptCommand.handler as (a: unknown) => void)({
plan,
role: 'reverse-audit',
findings,
chunk: 13,
round: 3,
});
expect(readRoundStamps(plan).some((s) => s.round === 3)).toBe(true);
expect(
(writeStderrLineSafe as unknown as Mock).mock.calls
.map((c) => String(c[0]))
.join('\n'),
).not.toContain('reverse-audit retirement unavailable');

delete process.env['QWEN_CODE_SESSION_ID'];
(writeStderrLineSafe as unknown as Mock).mockClear();
(agentPromptCommand.handler as (a: unknown) => void)({
plan,
role: 'reverse-audit',
findings,
chunk: 14,
round: 3,
});
let safe = (writeStderrLineSafe as unknown as Mock).mock.calls
.map((c) => String(c[0]))
.join('\n');
expect(safe).toContain('reverse-audit retirement unavailable');
expect(safe).toContain('auditing the chunk');
// The NOTE's middle carries the WHY — the underlying failure's own
// message, not an empty dash (#9272): the constant prefix and suffix
// alone would print `unavailable this round — — auditing the chunk.`
// and name nothing.
expect(safe).toMatch(/unavailable this round — .+ — auditing the chunk\./);

(writeStderrLineSafe as unknown as Mock).mockClear();
(agentPromptCommand.handler as (a: unknown) => void)({
plan,
role: 'reverse-audit',
findings,
chunk: 15,
round: 3,
});
safe = (writeStderrLineSafe as unknown as Mock).mock.calls
.map((c) => String(c[0]))
.join('\n');
expect(safe).not.toContain('reverse-audit retirement unavailable');
// Every repair still builds its chunk — the safe direction stands.
expect(keysOf(3)).toHaveLength(3);

// The claim is per ROUND (#9272): the same failure beginning in a
// LATER round of the same run earns its own NOTE — a plan-only key
// would silence it forever. Round 4 is under the default cap, and
// the history is still unreadable.
(writeStderrLineSafe as unknown as Mock).mockClear();
(agentPromptCommand.handler as (a: unknown) => void)({
plan,
role: 'reverse-audit',
findings,
chunk: 13,
round: 4,
});
safe = (writeStderrLineSafe as unknown as Mock).mock.calls
.map((c) => String(c[0]))
.join('\n');
expect(safe).toContain('reverse-audit retirement unavailable');
});

it('the #9242 note stays below the convergence gate — a converged round notes nothing', () => {
// A plan whose own numbers say Step 3A: rounds 1 and 2 note the
// mismatch as they build, but round 3 converges and builds nothing —
Expand Down
141 changes: 92 additions & 49 deletions packages/cli/src/commands/review/agent-prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import {
import { launchToolBudget, reverseAuditRoundCap } from './lib/budget.js';
import {
clearBudgetStop,
claimRetirementDegradeNote,
expectedAdmissionSeconds,
readRoundStamps,
reverseAuditBudgetExhausted,
Expand Down Expand Up @@ -2107,6 +2108,45 @@ function noteUncertifiedChunks(planPath: string, diagnostics: string[]): void {
);
}

/**
* The schedule read shared by the round builder and the per-chunk path
* (#9272 — hand-rolled at both sites and edited in lockstep across three
* consecutive PRs: the naming, the repair suppression, the deferral): a
* throwing read degrades to "everything is due" — never to fewer
* auditors — and composes the round's degrade NOTE, which the caller
* prints only once the round is admitted (#9259: printed before the
* gate, it promised an audit the gate then refused). `noteTail` names
* the build's own scope.
*/
function reverseAuditScheduleOrNote(
planPath: string,
chunkIds: number[],
round: number,
env: NodeJS.ProcessEnv,
diffPathAbsolute: unknown,
noteTail: string,
): { schedule: RoundSchedule | null; scheduleNote: string | null } {
try {
return {
schedule: scheduleReverseAuditRound(
planPath,
chunkIds,
round,
env,
typeof diffPathAbsolute === 'string' ? diffPathAbsolute : undefined,
),
scheduleNote: null,
};
} catch (err) {
return {
schedule: null,
scheduleNote:
`NOTE: reverse-audit retirement unavailable this round — ` +
`${(err as Error).message ?? String(err)} — ${noteTail}`,
};
}
}

/**
* Topology anomaly note (#9242): the plan's own size fields decide the
* topology (Step 3A whole-diff vs Step 3B territory fan-out), and the
Expand Down Expand Up @@ -2162,6 +2202,11 @@ function runAllChunks(
// three yielded in most: the loop earns its keep in the hot territories,
// and the cold ones were a third of its bill.
let schedule: RoundSchedule | null = null;
// The catch NOTE is deferred until the round is ADMITTED (#9259): a
// note printed before the budget/round-cap gate promises `auditing
// every chunk.` on a round the gate then refuses — a false continuation
// claim on the diagnostic channel this exists to keep truthful.
let scheduleNote: string | null = null;
// Retirement needs two consecutive dry audits, so nothing retires before
// round 3 (the scheduler's own guard says the same).
const retirementReadsFrom = 3;
Expand All @@ -2170,29 +2215,16 @@ function runAllChunks(
round !== undefined &&
round >= retirementReadsFrom
) {
try {
schedule = scheduleReverseAuditRound(
planPath,
chunks.map((c) => c.id),
round,
process.env,
typeof report.diffPathAbsolute === 'string'
? report.diffPathAbsolute
: undefined,
);
} catch (err) {
// Transcripts unavailable, an unreadable plan stat, anything: the
// schedule is an optimization, and a broken optimizer must degrade to
// today's behaviour — every territory audited — never to fewer
// auditors. `null` below means "everything is due". But not SILENTLY
// (#9206): a schedule that dies here retires nothing for the rest of
// the run, and the round's own output is where the reader can see it.
schedule = null;
writeStderrLineSafe(
`NOTE: reverse-audit retirement unavailable this round — ` +
`${(err as Error).message ?? String(err)} — auditing every chunk.`,
);
}
const read = reverseAuditScheduleOrNote(
planPath,
chunks.map((c) => c.id),
round,
process.env,
report.diffPathAbsolute,
'auditing every chunk.',
);
schedule = read.schedule;
scheduleNote = read.scheduleNote;
}

if (schedule !== null && schedule.converged) {
Expand Down Expand Up @@ -2230,6 +2262,13 @@ function runAllChunks(
) {
return;
}
// The admission succeeded, so the round IS being built — now the
// deferred catch NOTE tells the truth (#9259), claimed cross-process
// so a dead-schedule round's per-chunk builds print it exactly once
// (#9272).
if (scheduleNote !== null && claimRetirementDegradeNote(planPath, round)) {
writeStderrLineSafe(scheduleNote);
}

const dueSet = schedule === null ? null : new Set(schedule.due);
const dueChunks =
Expand Down Expand Up @@ -2707,33 +2746,27 @@ function runAgentPrompt(args: AgentPromptArgs): void {
)
.map((c) => c?.id)
.filter((id): id is number => typeof id === 'number');
// The catch NOTE is deferred past the admission gate (#9259 — a note
// printed before it promises an audit the gate can then refuse) and
// claimed cross-process via the record-dir sidecar, never keyed on
// the stamp: the stamp lands on the admission build whether or not
// that build's schedule read failed, so stamp-keyed suppression
// silenced a round whose admission build read cleanly and whose
// LATER builds began to throw — the never-retire shape with no word
// (#9259). The sidecar is run-epoch fenced, so a retried headless
// run re-prints — the safe side.
let scheduleNote: string | null = null;
if (args.round !== undefined) {
let schedule: RoundSchedule | null = null;
try {
schedule = scheduleReverseAuditRound(
args.plan,
planChunkIds,
args.round,
process.env,
typeof report.diffPathAbsolute === 'string'
? report.diffPathAbsolute
: undefined,
);
} catch (err) {
// Same degradation as the round builder: an unreadable history must
// fall back to building the auditor, never to refusing it — named,
// as the round builder names it (#9206). Named only on the builds
// that are NOT repairs: the round's admission build (its first
// chunk build, or the round builder itself) already spoke for it,
// and a repair stays the clean rebuild its exemption promises.
schedule = null;
if (!roundAdmitted) {
writeStderrLineSafe(
`NOTE: reverse-audit retirement unavailable this round — ` +
`${(err as Error).message ?? String(err)} — auditing the chunk.`,
);
}
}
const read = reverseAuditScheduleOrNote(
args.plan,
planChunkIds,
args.round,
process.env,
report.diffPathAbsolute,
'auditing the chunk.',
);
const schedule = read.schedule;
scheduleNote = read.scheduleNote;
if (!roundAdmitted && schedule !== null && schedule.converged) {
refuseConverged(args.plan);
return;
Expand All @@ -2760,6 +2793,16 @@ function runAgentPrompt(args: AgentPromptArgs): void {
)
)
return;
// Admitted (or a stamped repair): the audit IS happening, so the
// deferred NOTE tells the truth now (#9259) — once per round per
// RUN, across the per-chunk processes, via the sidecar claim
// (#9272).
if (
scheduleNote !== null &&
claimRetirementDegradeNote(args.plan, args.round)
) {
Comment thread
wenshao marked this conversation as resolved.
Resolved
writeStderrLineSafe(scheduleNote);
}
// The note belongs to the round's ADMISSION — a stamped rebuild
// was ruled on when the round was admitted, so it stays silent.
if (!roundAdmitted) {
Expand Down
Loading
Loading