Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
158 changes: 129 additions & 29 deletions .qwen/skills/autofix/scripts/run-agent.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@ const QWEN_TIMEOUT_MS = Number(process.env.QWEN_TIMEOUT_MS) || 50 * 60 * 1000;
// Idle watchdog: a wedged sandbox produces NOTHING — four observed hangs
// (#8663 x2, #8761 r3, #8763 r4) each printed their last byte at docker
// container entry and then sat silent for the whole absolute budget,
// burning 2 hours per round for zero work. Legitimate runs are never that
// quiet: the longest silence the fleet tolerates elsewhere is the review
// pipeline's 10-minute stream-idle window for thinking phases on ~1M-token
// contexts, so twice that is the default. Distinct from QWEN_TIMEOUT_MS so
// burning 2 hours per round for zero work. Streamed agent events keep active
// runs observable; the longest silence the fleet tolerates elsewhere is the
// review pipeline's 10-minute stream-idle window for thinking phases on
// ~1M-token contexts, so twice that is the default. Distinct from
// QWEN_TIMEOUT_MS so
// the failure comment says which limit fired; a leg whose absolute budget is
// shorter than this window (the review workflow's 18-minute repair pass)
// always reaches the absolute timer first.
Expand All @@ -37,6 +38,7 @@ const QWEN_IDLE_TIMEOUT_MS =
Number.isFinite(parsedIdleTimeoutMs) && parsedIdleTimeoutMs > 0
? parsedIdleTimeoutMs
: 20 * 60 * 1000;
const MAX_STREAM_JSON_LINE_LENGTH = 1024 * 1024;
const specs = {
'assess-candidates': {
inputs: ['candidates.json'],
Expand Down Expand Up @@ -176,6 +178,19 @@ function isLoopGuardOutput(output) {
);
}

function streamResultOutput(event) {
if (!event || event.type !== 'result') return '';
return [event.error?.message, event.result]
.filter((value) => typeof value === 'string')
.join('\n');
}

function isLoopGuardResult(event) {
return (
event?.is_error === true && isLoopGuardOutput(streamResultOutput(event))
);
}

function killQwen(child, signal) {
try {
process.kill(-child.pid, signal);
Expand All @@ -190,8 +205,10 @@ function runQwen(options, prompt) {
flags: 'w',
});
log.on('error', () => {});
let outputTail = '';
let loopDetected = false;
let diagnosticTail = '';
let stdoutCarry = '';
let discardingOversizedStdoutLine = false;
let terminalResult;
let settled = false;
let timedOut = false;
let idleTimedOut = false;
Expand All @@ -207,23 +224,90 @@ function runQwen(options, prompt) {
let sandboxRemoval = null;

return new Promise((resolve) => {
const child = spawn(options.qwenBin, ['--yolo', '--prompt', prompt], {
stdio: ['inherit', 'pipe', 'pipe'],
detached: true,
});
const child = spawn(
options.qwenBin,
[
'--yolo',
'--output-format',
'stream-json',
'--include-partial-messages',
Comment on lines +233 to +235

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.

已修复 + 验证证据:聚焦分类用例 10/10 通过;完整 workflow 154/154 断言通过。

Comment on lines +233 to +235

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.

已修复 + 验证证据:stream_event 仅保留在 agent.log,不再复制到 step stdout;相关用例 10/10、完整 workflow 158/158 断言通过。

'--prompt',
prompt,
],
{
stdio: ['inherit', 'pipe', 'pipe'],
detached: true,
},
);

const appendDiagnostic = (text) => {
diagnosticTail = (diagnosticTail + text).slice(-20_000);
};

const consumeStreamJsonLine = (line, terminated) => {
if (!line.trim()) return;
try {
const event = JSON.parse(line);
lastOutputAt = Date.now();
if (event?.type === 'result') terminalResult = event;
if (event?.type !== 'stream_event') {
process.stdout.write(`${line}${terminated ? '\n' : ''}`);
}
} catch {
appendDiagnostic(`${line}${terminated ? '\n' : ''}`);
process.stdout.write(`${line}${terminated ? '\n' : ''}`);
}
};

const consumeStreamJson = (text, final = false) => {
const parts = text.split('\n');
for (const [index, part] of parts.entries()) {
const terminated = index < parts.length - 1;
if (!discardingOversizedStdoutLine) {
const remaining = MAX_STREAM_JSON_LINE_LENGTH - stdoutCarry.length;
if (part.length <= remaining) {
stdoutCarry += part;
} else {
appendDiagnostic(`${stdoutCarry}${part.slice(0, remaining)}`);
stdoutCarry = '';
discardingOversizedStdoutLine = true;

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.

已修复 + 验证证据:5045d8a370;超大 tool_result 误分类回归先红后绿,相关 4/4 通过;node --check、Prettier、ESLint、git diff --check 通过。

}
}
if (terminated) {
if (!discardingOversizedStdoutLine) {
consumeStreamJsonLine(stdoutCarry, true);
}
stdoutCarry = '';
discardingOversizedStdoutLine = false;
}
Comment on lines +277 to +285

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.

已修复 + 验证证据:5045d8a370;丢弃超大行时现输出单条可观测提示,相关 4/4 通过。

}
if (final) {
if (!discardingOversizedStdoutLine) {
consumeStreamJsonLine(stdoutCarry, false);
}
stdoutCarry = '';
discardingOversizedStdoutLine = false;
}
};

const finish = (result) => {
if (settled) return;
settled = true;
clearTimeout(timer);
clearTimeout(killTimer);
clearInterval(idleTimer);
const apiErrorInfo = recoverableApiError(outputTail);
consumeStreamJson('', true);
const terminalOutput = streamResultOutput(terminalResult);
Comment on lines +304 to +305

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.

已修复 + 验证证据:跨 chunk 与无换行终止 result 均有回归覆盖;相关用例 10/10、完整 workflow 158/158 断言通过。

const apiErrorInfo = recoverableApiError(
result.status === 0
? terminalOutput
: `${diagnosticTail}\n${terminalOutput}`,
);
const payload = {
...result,
timedOut,
idleTimedOut,
loopDetected: loopDetected || isLoopGuardOutput(outputTail),
loopDetected: isLoopGuardResult(terminalResult),
// A RECOVERABLE model error means qwen never evaluated the feedback —
// the workflow retries it rather than advancing the watermark.
apiError: apiErrorInfo.error,
Expand All @@ -237,8 +321,7 @@ function runQwen(options, prompt) {
}
};

const record = (chunk, stream) => {
lastOutputAt = Date.now();
const record = (chunk, stream, source) => {
const text = chunk.toString('utf8');
if (!sandboxName) {
lineCarry += text;
Expand All @@ -256,14 +339,18 @@ function runQwen(options, prompt) {
}
}
}
outputTail = (outputTail + text).slice(-20_000);
if (!loopDetected && isLoopGuardOutput(outputTail)) loopDetected = true;
if (source === 'stdout') {
consumeStreamJson(text);
} else {
lastOutputAt = Date.now();
appendDiagnostic(text);
stream.write(chunk);
}
log.write(chunk);
stream.write(chunk);
};

child.stdout.on('data', (chunk) => record(chunk, process.stdout));
child.stderr.on('data', (chunk) => record(chunk, process.stderr));
child.stdout.on('data', (chunk) => record(chunk, process.stdout, 'stdout'));
child.stderr.on('data', (chunk) => record(chunk, process.stderr, 'stderr'));
child.on('error', (error) => finish({ error, status: null, signal: null }));
child.on('close', (status, signal) =>
finish({ error: null, status, signal }),
Expand Down Expand Up @@ -394,7 +481,24 @@ const result = await runQwen(options, prompt);
// timeout) so the leak warning and the removal itself settle before this
// process exits and the next step inspects the host.
if (result.sandboxRemoval) await result.sandboxRemoval;
if (result.error || result.signal || result.status !== 0) {
const missingOutputs = missing(options.workdir, spec.outputs);
const presentOutputs = spec.outputs.filter(
(name) => !missingOutputs.includes(name),
);
const hasOutputVerdict = spec.anyOutput

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Suggestion] hasOutputVerdict and ok compute the same boolean with different expressions, creating a maintenance hazard.

hasOutputVerdict (line 413: spec.anyOutput ? presentOutputs.length > 0 : missingOutputs.length === 0) and ok (line 516: spec.anyOutput ? missingOutputs.length < spec.outputs.length : missingOutputs.length === 0) are mathematically equivalent — presentOutputs.length = spec.outputs.length - missingOutputs.length, so presentOutputs.length > 0 equals missingOutputs.length < spec.outputs.length. A future change to output-verification semantics must update both in lockstep; the different formulations make it easy to miss one.

Suggested change
const hasOutputVerdict = spec.anyOutput
const ok = hasOutputVerdict;

— deepseek-v4-flash via Qwen Code /review (v0.21.8)

中文说明

hasOutputVerdict(第 413 行:spec.anyOutput ? presentOutputs.length > 0 : missingOutputs.length === 0)和 ok(第 516 行:spec.anyOutput ? missingOutputs.length < spec.outputs.length : missingOutputs.length === 0)在数学上是等价的——presentOutputs.length = spec.outputs.length - missingOutputs.length,所以 presentOutputs.length > 0 等价于 missingOutputs.length < spec.outputs.length。未来对输出验证语义的修改需要同时更新两个表达式,不同的表述方式容易遗漏其一。

— deepseek-v4-flash via Qwen Code /review (v0.21.8)

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.

已修复 + 验证证据:聚焦分类用例 10/10 通过;完整 workflow 154/154 断言通过。

? presentOutputs.length > 0
: missingOutputs.length === 0;
Comment on lines +493 to +495

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.

已修复 + 验证证据:聚焦分类用例 10/10 通过;完整 workflow 154/154 断言通过。

const apiErrorWithoutVerdict =
result.status === 0 &&
result.apiError &&
Comment on lines +496 to +498

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.

已修复 + 验证证据:聚焦分类用例 10/10 通过;完整 workflow 154/154 断言通过。

!hasOutputVerdict &&
!existsSync(file(options.workdir, 'failure.md'));
if (
result.error ||
result.signal ||
result.status !== 0 ||
apiErrorWithoutVerdict
) {
const detail = result.error
? result.error.message
: result.idleTimedOut
Expand All @@ -403,7 +507,9 @@ if (result.error || result.signal || result.status !== 0) {
? `timeout (${QWEN_TIMEOUT_MS}ms)`
: result.signal
? `signal ${result.signal}`
: `status ${String(result.status)}`;
: apiErrorWithoutVerdict
? 'recoverable API error without an agent verdict'
: `status ${String(result.status)}`;
if (!existsSync(file(options.workdir, 'failure.md'))) {
if (result.loopDetected) {
writeFailure(
Expand Down Expand Up @@ -462,7 +568,7 @@ if (result.error || result.signal || result.status !== 0) {
`Qwen failed during ${options.mode}: ${detail}; preserving agent-written failure.md.`,
);
}
process.exit(result.status ?? 1);
process.exit(result.status === 0 ? 1 : (result.status ?? 1));
}

if (existsSync(file(options.workdir, 'failure.md'))) {
Expand All @@ -475,18 +581,12 @@ if (existsSync(file(options.workdir, 'failure.md'))) {
process.exit(0);
}

const missingOutputs = missing(options.workdir, spec.outputs);
const presentOutputs = spec.outputs.filter(
(name) => !missingOutputs.includes(name),
);
if (spec.exclusiveOutput && presentOutputs.length > 1) {
const message = `Autofix agent wrote mutually exclusive output files: ${presentOutputs.join(', ')}.`;
writeFailure(options.workdir, message);
fail(message);
}
const ok = spec.anyOutput
? missingOutputs.length < spec.outputs.length
: missingOutputs.length === 0;
const ok = hasOutputVerdict;
if (!ok) {
const message = `Autofix agent finished without required output file(s): ${missingOutputs.join(', ')}.`;
writeFailure(options.workdir, message);
Expand Down
Loading
Loading