From 63ff46e9ee3c1ea678c33891032c0e70eec67987 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:53:53 -0500 Subject: [PATCH] fix(verification): read back Qwen skill output before analysis (#13240) --- docs/development/client-verification.md | 6 +- scripts/verify-qwen-client.mjs | 68 ++++--- scripts/verify/clients/qwen-evidence.mjs | 129 ++++++++++++ .../process/qwenVerifierSkillBody.test.ts | 188 +++++++++++------- 4 files changed, 290 insertions(+), 101 deletions(-) create mode 100644 scripts/verify/clients/qwen-evidence.mjs diff --git a/docs/development/client-verification.md b/docs/development/client-verification.md index 0e8497f80b..378c2fead0 100644 --- a/docs/development/client-verification.md +++ b/docs/development/client-verification.md @@ -107,8 +107,10 @@ lanes require an installed native client. Select its executable with They configure disposable profiles through the public REA CLI, preserve caller settings and backups, and exercise real stdio MCP calls and skill loading. The `call` mode checks complete catalog discovery and actual JavaScript Evidence; -pass `-- chat` to check plain chat with REA enabled. Qwen also reads the full -result that its client offloads, and Pi exercises default codemode execution. +pass `-- chat` to check plain chat with REA enabled. When Qwen saves the installed +skill's tool output, the fixture uses native `read_file` pages and verifies the +complete body and reported digest before analysis. It also reads offloaded REA +Evidence. Pi exercises default codemode execution. Use `REA_VERIFY_RUNTIME_ROOT` to select a production-only installed REA package. Receipts retain client versions, result digests, host coverage and owned-process cleanup. These lanes use a deterministic loopback model and do not prove live diff --git a/scripts/verify-qwen-client.mjs b/scripts/verify-qwen-client.mjs index c67005a024..00176222b6 100644 --- a/scripts/verify-qwen-client.mjs +++ b/scripts/verify-qwen-client.mjs @@ -24,6 +24,13 @@ import { } from "./verify/clients/result-discovery.mjs"; import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs"; import { TOOL_CONTRACTS } from "../dist/contracts/toolContracts.js"; +import { + createQwenSkillReadback, + hasQwenSuccessfulResult, + qwenPersistedOutput, + qwenSavedSkillPath, + qwenToolResponseText, +} from "./verify/clients/qwen-evidence.mjs"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; const repo = fileURLToPath(new URL("..", import.meta.url)); @@ -61,9 +68,9 @@ let fixture; let passed = false; let evidenceSeen = false; let finalSeen = false; -let skillRequested = false; let skillCallId; let expectedSkillBody; +let skillRead; let searchCallId; let analysisCallId; let artifactReadByAgent = false; @@ -220,24 +227,18 @@ await withVerifierCleanup(async () => { directory: lab, prefix: `${client}-${mode}`, onRequest: async ({ body, tools, requestIndex }) => { - const messages = (body.messages ?? []).map((message) => ({ - role: message.role, - callId: message.tool_call_id, - text: - typeof message.content === "string" - ? message.content - : (message.content ?? []) - .map((part) => part.text ?? "") - .join("\n"), - })); + const messages = body.messages ?? []; const toolResponseText = (callId) => - messages.find( - (message) => message.role === "tool" && message.callId === callId, - )?.text ?? ""; + qwenToolResponseText(messages, callId); const expectedSkill = `Base directory for this skill: ${join(sharedSkills, "reverse-engineer-anything")}\nImportant: ALWAYS resolve absolute paths from this base directory when working with skills.\n\n${expectedSkillBody}\n`; - selectedSkillLoaded ||= - skillCallId !== undefined && - toolResponseText(skillCallId).includes(expectedSkill); + if (skillRead?.callId !== undefined && !selectedSkillLoaded) { + const reply = toolResponseText(skillRead.callId); + assert(reply, "Qwen did not return the requested skill file read."); + selectedSkillLoaded = skillRead.readback.receive(reply); + } else { + selectedSkillLoaded ||= + toolResponseText(skillCallId).includes(expectedSkill); + } const toolText = JSON.stringify( (body.messages ?? []).filter((m) => m.role === "tool"), ); @@ -306,15 +307,32 @@ await withVerifierCleanup(async () => { ], }); let message; - if (mode === "chat" || evidenceSeen) { + if (mode === "chat" || (evidenceSeen && selectedSkillLoaded)) { message = { role: "assistant", content: "REA_CLIENT_COMPATIBILITY_OK", }; - } else if (skill && !skillRequested) { - skillRequested = true; + } else if (skillCallId === undefined) { + assert(skill, "Qwen must expose its native skill tool."); message = call(skill.name, { skill: "reverse-engineer-anything" }); skillCallId = message.tool_calls[0].id; + } else if (!selectedSkillLoaded) { + if (skillRead === undefined) { + const saved = qwenPersistedOutput(toolResponseText(skillCallId)); + assert(saved, "Qwen did not load the installed skill."); + const path = await qwenSavedSkillPath(saved.path, runtime); + skillRead = { + path, + readback: createQwenSkillReadback(saved.digest, expectedSkill), + }; + } + const read = tools.find((tool) => tool.name === "read_file"); + assert(read, "Qwen must expose read_file for the saved skill."); + message = call(read.name, { + file_path: skillRead.path, + ...skillRead.readback.range, + }); + skillRead.callId = message.tool_calls[0].id; } else if (persisted && shell) { artifactPath = persisted[1]; assert( @@ -419,14 +437,10 @@ await withVerifierCleanup(async () => { "Qwen must discover the complete REA catalog", ); assert.equal(fixture.failure, undefined); - const result = events.findLast((event) => event.type === "result"); - assert.equal( - result?.subtype, - "success", - "Qwen must emit a successful terminal result", + assert( + hasQwenSuccessfulResult(events, "REA_CLIENT_COMPATIBILITY_OK"), + "Qwen must emit a successful terminal result with the expected answer.", ); - assert.equal(result.is_error, false); - assert.equal(result.result, "REA_CLIENT_COMPATIBILITY_OK"); finalSeen = true; if (mode === "call") { assert(evidenceSeen); diff --git a/scripts/verify/clients/qwen-evidence.mjs b/scripts/verify/clients/qwen-evidence.mjs new file mode 100644 index 0000000000..391048034d --- /dev/null +++ b/scripts/verify/clients/qwen-evidence.mjs @@ -0,0 +1,129 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { realpath } from "node:fs/promises"; +import { isAbsolute } from "node:path"; +import { isPathWithinRoot } from "../../../dist/domain/localPath.js"; + +/** + * @param {readonly {role?: string, tool_call_id?: string, content?: unknown}[]} messages + * @param {string | undefined} callId + */ +export function qwenToolResponseText(messages, callId) { + if (callId === undefined) return ""; + const content = messages.find( + (message) => message.role === "tool" && message.tool_call_id === callId, + )?.content; + if (typeof content === "string") return content; + if (!Array.isArray(content)) return ""; + return content + .filter((part) => typeof part?.text === "string") + .map((part) => part.text) + .join("\n"); +} + +/** @param {string} text */ +export function qwenPersistedOutput(text) { + if (!text.endsWith("\n")) return undefined; + const match = + /^\nOutput too large \([^)]+\)\. Full output saved to: ([^\r\n]+)\nFull output sha256: ([a-f0-9]{64})\n/u.exec( + text, + ); + return match === null ? undefined : { path: match[1], digest: match[2] }; +} + +/** @param {string} path @param {string} runtime */ +export async function qwenSavedSkillPath(path, runtime) { + assert(isAbsolute(path), "Qwen reported a relative saved-skill path."); + const [canonicalPath, root] = await Promise.all([ + realpath(path), + realpath(runtime), + ]); + assert( + canonicalPath !== root && isPathWithinRoot(root, canonicalPath), + "Qwen saved the skill outside the verifier's runtime.", + ); + return canonicalPath; +} + +/** + * @param {readonly {type?: string, subtype?: string, is_error?: boolean, result?: string}[]} events + * @param {string} answer + */ +export function hasQwenSuccessfulResult(events, answer) { + const result = events.findLast((event) => event.type === "result"); + return ( + result?.subtype === "success" && + result.is_error === false && + result.result === answer + ); +} + +/** + * Join Qwen's read_file pages from matched tool replies. Its byte limit can + * clip the last reported line of a page, so re-read that line with the next + * page. The saved-output digest proves the observed text is complete. + * @param {string} digest + * @param {string} expectedSkill + */ +export function createQwenSkillReadback(digest, expectedSkill) { + /** @type {string[]} */ + const chunks = []; + let offset = 0; + let total = 0; + return { + get range() { + return offset === 0 ? {} : { offset, limit: total - offset }; + }, + /** @param {string} reply */ + receive(reply) { + const page = + /^Showing lines (\d+)-(\d+) of (\d+) total lines\.\n\n---\n\n([\s\S]*)$/u.exec( + reply, + ); + if (page === null) { + assert(offset === 0, "Qwen omitted the saved-skill page range."); + chunks.push(reply); + } else { + const start = Number(page[1]); + const end = Number(page[2]); + const reportedTotal = Number(page[3]); + assert( + start === offset + 1 && + end >= start && + end <= reportedTotal && + Number.isSafeInteger(reportedTotal) && + (total === 0 || total === reportedTotal), + "Qwen returned an unexpected saved-skill page range.", + ); + total = reportedTotal; + const lines = page[4].split("\n"); + assert.equal( + lines.length, + end - start + 1, + "Qwen omitted saved-skill lines.", + ); + if (end < total) { + assert( + end > start, + "Qwen's read limit prevented a complete saved-skill line.", + ); + chunks.push(lines.slice(0, -1).join("\n")); + offset = end - 1; + return false; + } + chunks.push(page[4]); + } + const text = chunks.join("\n"); + assert.equal( + createHash("sha256").update(text).digest("hex"), + digest, + "Qwen did not return the complete saved skill to the model.", + ); + assert( + text.includes(expectedSkill), + "Qwen did not load the installed skill.", + ); + return true; + }, + }; +} diff --git a/tests/boundary/process/qwenVerifierSkillBody.test.ts b/tests/boundary/process/qwenVerifierSkillBody.test.ts index 79d2b40e97..08b426bd65 100644 --- a/tests/boundary/process/qwenVerifierSkillBody.test.ts +++ b/tests/boundary/process/qwenVerifierSkillBody.test.ts @@ -1,77 +1,121 @@ -import { spawnSync } from "node:child_process"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { createHash } from "node:crypto"; +import { mkdir, realpath, symlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { fileURLToPath } from "node:url"; import { expect, it } from "vitest"; + +import { + createQwenSkillReadback, + hasQwenSuccessfulResult, + qwenPersistedOutput, + qwenSavedSkillPath, + qwenToolResponseText, +} from "../../../scripts/verify/clients/qwen-evidence.mjs"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; -it.each([ - ["no skill tool", false], - ["user mention", false], - ["wrong id", false], - ["missing body", false], - ["split", false], - ["complete", true], - ["CRLF", true], - ["output missing result", false], - ["output missing marker", false], - ["output terminal failure", false], - ["output success", true], -] as const)("binds Qwen skill evidence for %s", async (mode, loaded) => { - const state = await createTestTempDirectory("rea-qwen-skill-"); - await writeFile( - join(state, "commands.mjs"), - "import {mkdir,readFile,writeFile} from 'node:fs/promises';import {join} from 'node:path';\nexport async function createVerifierCommands(){return {async exec(command,args,options={}){\n if(args.includes('--version'))return {stdout:'fake',stderr:''};\n const profile=options.env.QWEN_HOME;const config=join(profile,'settings.json');\n if(args.includes('setup')&&args.includes('--dry-run'))return {stdout:JSON.stringify({plannedActions:[{target:config}]}),stderr:''};\n if(args.includes('setup')){\n const original=await readFile(config,'utf8');await writeFile(config+'.rea.backup',original);\n const value=JSON.parse(original);value.mcpServers.rea={command:'/fake/rea',args:['mcp']};await writeFile(config,JSON.stringify(value));\n const skill=join(options.env.HOME,'.agents','skills','reverse-engineer-anything');await mkdir(skill,{recursive:true});\n const source='---\\nname: reverse-engineer-anything\\n---\\nQwen \"authored\" body\\nKeep a \\\\ literal\\n';\n await writeFile(join(skill,'SKILL.md'),process.env.MODE==='CRLF'?source.replaceAll('\\n','\\r\\n'):source);\n return {stdout:'{}',stderr:''};\n }\n if(args.includes('doctor'))return {stdout:'{}',stderr:''};\n if(process.env.MODE.startsWith('output ')){await globalThis.fakeRequest({body:{messages:[]},tools:[],requestIndex:1});const {TOOL_CONTRACTS}=await import(process.env.CONTRACTS);const events=[{type:'system',subtype:'init',tools:TOOL_CONTRACTS.map(c=>'mcp__rea__'+c.name)}];const success={type:'result',subtype:'success',is_error:false,result:process.env.MODE==='output missing marker'?'': 'REA_CLIENT_COMPATIBILITY_OK'};if(process.env.MODE!=='output missing result')events.push(success);if(process.env.MODE==='output terminal failure')events.push({type:'result',subtype:'error_during_execution',is_error:true});return {stdout:events.map(e=>JSON.stringify(e)).join('\\n')+'\\n',stderr:''};}\n const skill=join(options.env.HOME,'.agents','skills','reverse-engineer-anything');\n const content='Base directory for this skill: '+skill+'\\nImportant: ALWAYS resolve absolute paths from this base directory when working with skills.\\n\\nQwen \"authored\" body\\nKeep a \\\\ literal\\n';\n const tools=[...(process.env.MODE==='no skill tool'?[]:[{name:'skill'}]),{name:'mcp__rea__analyze_javascript_application'}];\n const first=await globalThis.fakeRequest({body:{messages:[]},tools,requestIndex:1});const callId=first.tool_calls[0].id;\n let messages=(process.env.MODE==='user mention'||process.env.MODE==='no skill tool')?[{role:'user',content:'Unrelated '+skill}]:[{role:'tool',tool_call_id:process.env.MODE==='wrong id'?'other':callId,content:process.env.MODE==='missing body'?'Base directory for this skill: '+skill:content}];\n if(process.env.MODE==='split')messages=[{role:'tool',tool_call_id:callId,content:'Base directory for this skill: '+skill},{role:'tool',tool_call_id:'other',content}];\n const second=await globalThis.fakeRequest({body:{messages},tools,requestIndex:2});await writeFile(process.env.STATE+'/observed.json',JSON.stringify({first,second,messages}));throw Error('intentional stop before client output');\n},async close(){}};}\n", - ); - await writeFile( - join(state, "fixture.mjs"), - "export async function createOpenAiModelFixture({onRequest}){globalThis.fakeRequest=onRequest;return {baseUrl:'http://127.0.0.1:1',async close(){}};}\n", - ); - await writeFile( - join(state, "hook.mjs"), - "import {registerHooks}from'node:module';import{pathToFileURL}from'node:url';registerHooks({resolve(specifier,context,next){if(context.parentURL?.endsWith('/scripts/verify-qwen-client.mjs')){let f;if(specifier==='./lib/verify-commands.mjs')f='commands.mjs';if(specifier==='./verify/clients/model-fixture.mjs')f='fixture.mjs';if(f)return{url:pathToFileURL(process.env.STATE+'/'+f).href,shortCircuit:true};}return next(specifier,context);}});\n", - ); - const script = fileURLToPath( - new URL("../../../scripts/verify-qwen-client.mjs", import.meta.url), - ); - const result = spawnSync( - process.execPath, - [ - "--import", - join(state, "hook.mjs"), - script, - ...(mode.startsWith("output ") ? ["chat"] : []), - ], - { - encoding: "utf8", - timeout: 10_000, - env: { - ...process.env, - STATE: state, - MODE: mode, - CONTRACTS: new URL( - "../../../dist/contracts/toolContracts.js", - import.meta.url, - ).href, - TMPDIR: state, - TMP: state, - TEMP: state, - }, - }, - ); - if (mode.startsWith("output ")) { - // Authored stream result shape from Qwen's BaseJsonOutputAdapter at - // QwenLM/qwen-code c238beb56fa3c65a0f62ad7a3b2cd14db978b998. - expect(result.status, result.stderr).toBe(loaded ? 0 : 1); - const receipt = JSON.parse(result.stdout.trim().split("\n")[0] ?? ""); - expect(receipt.finalSeen).toBe(loaded); - expect(receipt.passed).toBe(loaded); - return; - } - expect(result.status).not.toBe(0); - expect(result.stderr).toContain("intentional stop before client output"); - const receipt = JSON.parse(result.stdout.trim().split("\n")[0] ?? ""); - expect(receipt.selectedSkillLoaded).toBe(loaded); - expect(receipt.passed).toBe(false); +it("binds Qwen skill text to the selected native tool reply", () => { + const skill = "Base directory for this skill: /owned/skill"; + const body = "The complete authored skill body."; + const reply = { role: "tool", tool_call_id: "selected" }; + const unrelated = [ + { ...reply, role: "user", content: body }, + { ...reply, tool_call_id: "other", content: body }, + { ...reply, content: skill }, + ]; + + expect(qwenToolResponseText(unrelated, undefined)).toBe(""); + expect(qwenToolResponseText(unrelated, "selected")).toBe(skill); + expect( + qwenToolResponseText( + [{ ...reply, content: [{ text: skill }, { text: body }] }, ...unrelated], + "selected", + ), + ).toBe(`${skill}\n${body}`); +}); + +it("re-reads Qwen's clipped final line and verifies the complete skill", () => { + const expected = + "Base directory for this skill: /owned/skill\nKeep paths literal.\n"; + const text = expected + "Next instruction.\n"; + const digest = createHash("sha256").update(text).digest("hex"); + const notice = ` +Output too large (47 KB). Full output saved to: /owned/saved +Full output sha256: ${digest} +Preview (up to 2000 chars): +${expected} +`; + expect(qwenPersistedOutput(notice)).toEqual({ path: "/owned/saved", digest }); + expect( + qwenPersistedOutput(notice.replace("sha256:", "unknown:")), + ).toBeUndefined(); + expect(qwenPersistedOutput(notice.slice(19))).toBeUndefined(); + + const readback = createQwenSkillReadback(digest, expected); + expect(readback.range).toEqual({}); + const clipped = + "Showing lines 1-2 of 4 total lines.\n\n---\n\nBase directory for this skill: /owned/skill\nKeep"; + expect(readback.receive(clipped)).toBe(false); + expect(readback.range).toEqual({ offset: 1, limit: 3 }); + expect(() => + readback.receive( + "Showing lines 3-4 of 4 total lines.\n\n---\n\nNext instruction.\n", + ), + ).toThrow("unexpected saved-skill page range"); + expect( + readback.receive( + "Showing lines 2-4 of 4 total lines.\n\n---\n\nKeep paths literal.\nNext instruction.\n", + ), + ).toBe(true); + expect(createQwenSkillReadback(digest, expected).receive(text)).toBe(true); + expect(() => + createQwenSkillReadback(digest, expected).receive( + text.replace("Next", "Other"), + ), + ).toThrow("did not return the complete saved skill"); +}); + +it.skipIf(process.platform === "win32")( + "rejects a saved-skill alias outside the owned runtime", + async () => { + const parent = await createTestTempDirectory("rea-qwen-skill-path-"); + const runtime = join(parent, "runtime"); + const saved = join(runtime, "owned"); + const foreign = join(parent, "foreign"); + const alias = join(runtime, "alias"); + await mkdir(runtime); + await Promise.all([ + writeFile(saved, "owned"), + writeFile(foreign, "foreign"), + ]); + await symlink(foreign, alias); + + await expect(qwenSavedSkillPath(saved, runtime)).resolves.toBe( + await realpath(saved), + ); + await expect(qwenSavedSkillPath(alias, runtime)).rejects.toThrow( + "outside the verifier's runtime", + ); + }, +); + +it("requires Qwen's last result to confirm the exact final answer", () => { + const init = { type: "system", subtype: "init" }; + const success = { + type: "result", + subtype: "success", + is_error: false, + result: "answer", + }; + const failed = { + type: "result", + subtype: "error_during_execution", + is_error: true, + }; + expect(hasQwenSuccessfulResult([init, success], "answer")).toBe(true); + expect(hasQwenSuccessfulResult([init], "answer")).toBe(false); + expect( + hasQwenSuccessfulResult([init, { ...success, result: "" }], "answer"), + ).toBe(false); + expect(hasQwenSuccessfulResult([init, success, failed], "answer")).toBe( + false, + ); });