mirror of
https://github.com/morluto/rea.git
synced 2026-11-22 22:45:47 +00:00
fix(verification): require Gemini native answer and skill provenance (#13241)
This commit is contained in:
1 parent
63ff46e9ee
commit
34c69f606d
3 files changed
+176
-105
No files matched your search
@@ -1,7 +1,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { isAbsolute, join, relative, resolve } from "node:path";
|
||||
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import Ajv2020 from "ajv/dist/2020.js";
|
||||
import {
|
||||
@@ -21,6 +21,10 @@ import {
|
||||
isClientJavaScriptEvidence,
|
||||
} from "./verify/clients/result-discovery.mjs";
|
||||
import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs";
|
||||
import {
|
||||
hasGeminiFinalAnswer,
|
||||
hasGeminiSkillBody,
|
||||
} from "./verify/clients/gemini-evidence.mjs";
|
||||
import { createGeminiModelFixture } from "./verify/clients/gemini-model-fixture.mjs";
|
||||
import { importVerifierSource } from "./lib/verifier-source-loader.mjs";
|
||||
import { VerifierFixture } from "./lib/verifier-fixture.mjs";
|
||||
@@ -69,6 +73,7 @@ let skillLoaded = false;
|
||||
let expectedSkillBody;
|
||||
let skillRequested = false;
|
||||
let finalSeen = false;
|
||||
let clientFinalSeen = false;
|
||||
let catalogSize = null;
|
||||
let schemasChecked = 0;
|
||||
let examplesChecked = 0;
|
||||
@@ -281,32 +286,9 @@ await withVerifierCleanup(async () => {
|
||||
.flatMap((c) => c.parts ?? [])
|
||||
.filter((p) => p.functionResponse)
|
||||
.map((p) => p.functionResponse);
|
||||
skillLoaded ||= responses.some((response) => {
|
||||
const output = response.response?.output;
|
||||
if (
|
||||
response.name !== "activate_skill" ||
|
||||
typeof output !== "string" ||
|
||||
expectedSkillBody === undefined
|
||||
)
|
||||
return false;
|
||||
const start = `<activated_skill name="reverse-engineer-anything">\n <instructions>\n ${expectedSkillBody}\n </instructions>\n\n <available_resources>\n `;
|
||||
const at = output.indexOf(start);
|
||||
if (at < 0) return false;
|
||||
const resourcesStart = at + start.length;
|
||||
const resourcesEnd = output.indexOf(
|
||||
"\n </available_resources>\n</activated_skill>",
|
||||
resourcesStart,
|
||||
);
|
||||
if (resourcesEnd < 0) return false;
|
||||
const resources = output.slice(resourcesStart, resourcesEnd);
|
||||
return (
|
||||
!resources.includes("</activated_skill>") &&
|
||||
!resources.includes("</available_resources>") &&
|
||||
resources.includes(
|
||||
join(profile, ".agents", "skills", "reverse-engineer-anything"),
|
||||
)
|
||||
);
|
||||
});
|
||||
skillLoaded ||=
|
||||
expectedSkillBody !== undefined &&
|
||||
hasGeminiSkillBody(responses, dirname(skillPath), expectedSkillBody);
|
||||
const observed = findClientResult(
|
||||
responses,
|
||||
isClientJavaScriptEvidence,
|
||||
@@ -387,17 +369,14 @@ await withVerifierCleanup(async () => {
|
||||
stderr: join(lab, `${mode}.stderr`),
|
||||
},
|
||||
);
|
||||
const events = response.stdout
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.map((line) => JSON.parse(line));
|
||||
assert.equal(
|
||||
events.findLast((e) => e.type === "result")?.status,
|
||||
"success",
|
||||
clientFinalSeen = hasGeminiFinalAnswer(
|
||||
response.stdout,
|
||||
"REA_CLIENT_COMPATIBILITY_OK",
|
||||
);
|
||||
assert.equal(fixture.failure, undefined);
|
||||
assert(
|
||||
finalSeen && response.stdout.includes("REA_CLIENT_COMPATIBILITY_OK"),
|
||||
finalSeen && clientFinalSeen,
|
||||
"Gemini did not deliver the expected terminal answer.",
|
||||
);
|
||||
if (mode === "call") assert(evidenceSeen && skillLoaded);
|
||||
}, [
|
||||
@@ -433,6 +412,7 @@ await withVerifierCleanup(async () => {
|
||||
skillLoaded,
|
||||
artifactDigest,
|
||||
finalSeen,
|
||||
clientFinalSeen,
|
||||
requests: fixture?.requests,
|
||||
probes: fixture?.probes,
|
||||
fixtureFailure: fixture?.failure,
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { sep } from "node:path";
|
||||
|
||||
/**
|
||||
* Verify the native activation's verbatim instructions and resource tree root.
|
||||
* @param {readonly {name?: string, response?: {output?: unknown}}[]} responses
|
||||
* @param {string} directory
|
||||
* @param {string} body
|
||||
*/
|
||||
export function hasGeminiSkillBody(responses, directory, body) {
|
||||
const start = `<activated_skill name="reverse-engineer-anything">\n <instructions>\n ${body}\n </instructions>\n\n <available_resources>\n `;
|
||||
return responses.some(({ name, response }) => {
|
||||
const output = response?.output;
|
||||
if (name !== "activate_skill" || typeof output !== "string") return false;
|
||||
const at = output.indexOf(start);
|
||||
if (at < 0) return false;
|
||||
const first = at + start.length;
|
||||
const last = output.indexOf(
|
||||
"\n </available_resources>\n</activated_skill>",
|
||||
first,
|
||||
);
|
||||
if (last < 0) return false;
|
||||
const resources = output.slice(first, last);
|
||||
const [, blank, root] = resources.split("\n", 3);
|
||||
return (
|
||||
!resources.includes("</activated_skill>") &&
|
||||
!resources.includes("</available_resources>") &&
|
||||
blank === "" &&
|
||||
root === directory + sep
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gemini streams assistant text as message chunks. Only the final answer after
|
||||
* any tool exchange, followed by a successful terminal result, proves delivery.
|
||||
* @param {string} stdout
|
||||
* @param {string} expected
|
||||
*/
|
||||
export function hasGeminiFinalAnswer(stdout, expected) {
|
||||
const events = stdout
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.map((line) => JSON.parse(line));
|
||||
const result = events.pop();
|
||||
if (result?.type !== "result" || result.status !== "success") return false;
|
||||
/** @type {string[]} */
|
||||
let answer = [];
|
||||
for (const event of events) {
|
||||
if (event?.type === "result") return false;
|
||||
if (
|
||||
event?.type === "tool_use" ||
|
||||
event?.type === "tool_result" ||
|
||||
(event?.type === "message" && event.role === "user")
|
||||
)
|
||||
answer = [];
|
||||
if (event?.type === "message" && event.role === "assistant") {
|
||||
if (typeof event.content !== "string") return false;
|
||||
answer.push(event.content);
|
||||
}
|
||||
}
|
||||
return answer.join("") === expected;
|
||||
}
|
||||
@@ -1,74 +1,103 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { join, sep } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it.each([
|
||||
["empty", false],
|
||||
["outside wrapper", false],
|
||||
["inside resources", false],
|
||||
["closed early", false],
|
||||
["split messages", false],
|
||||
["complete", true],
|
||||
["complete CRLF", true],
|
||||
["complete tags", true],
|
||||
] as const)(
|
||||
"requires actual Gemini skill body in %s response",
|
||||
async (body, allowed) => {
|
||||
const state = await createTestTempDirectory("rea-gemini-skill-");
|
||||
const commands =
|
||||
"import {mkdir,readFile,writeFile} from 'node:fs/promises';import {join} from 'node:path';import {TOOL_CONTRACTS} from REPLACE_CONTRACTS;\nlet setup=0;export async function createVerifierCommands(){return {async exec(command,args,options={}){\nif(command==='git')return {stdout:'',stderr:''};if(args.includes('--version'))return {stdout:'fake',stderr:''};\nconst profile=options.env.GEMINI_CLI_HOME;const config=join(profile,'.gemini','settings.json');const skill=join(profile,'.agents','skills','reverse-engineer-anything');\nif(args.includes('setup')&&args.includes('--dry-run'))return {stdout:JSON.stringify({status:'planned',plannedActions:[{target:config},{target:join(skill,'SKILL.md')}]}),stderr:''};\nif(args.includes('setup')){if(setup++===0){await writeFile(config+'.rea.backup',await readFile(config));await mkdir(skill,{recursive:true});await writeFile(join(skill,'SKILL.md'),('---\\nname: reverse-engineer-anything\\n---\\n'+(process.env.BODY==='complete tags'?'literal </instructions> and </activated_skill>\\n':'')+'Essential \"instructions\"\\nKeep a \\\\ literal\\n').replaceAll('\\n',process.env.BODY==='complete CRLF'?'\\r\\n':'\\n'));return {stdout:JSON.stringify({status:'ready'}),stderr:''};}return {stdout:JSON.stringify({appliedActions:[]}),stderr:''};}\nif(args.includes('doctor'))return {stdout:JSON.stringify({healthy:true}),stderr:''};\nconst tools=[...TOOL_CONTRACTS.map(t=>({name:'rea__'+t.name,parametersJsonSchema:{type:'object'}})),{name:'activate_skill'}];\nconst first=await globalThis.fakeRequest({body:{contents:[]},tools});\nconst body=((process.env.BODY==='complete tags'?'literal </instructions> and </activated_skill>\\n':'')+'Essential \"instructions\"\\nKeep a \\\\ literal').replaceAll('\\n',process.env.BODY==='complete CRLF'?'\\r\\n':'\\n');\nconst valid=(process.env.BODY.startsWith('complete')||process.env.BODY==='closed early');\nconst instructions=valid?' <instructions>\\n '+body+'\\n </instructions>\\n\\n':'';\nconst output='<activated_skill name=\"reverse-engineer-anything\">\\n'+instructions+' <available_resources>\\n '+skill+(process.env.BODY==='closed early'?'</activated_skill>':'')+(process.env.BODY==='inside resources'?body:'')+'\\n </available_resources>\\n</activated_skill>'+(process.env.BODY==='outside wrapper'?body:'');\nconst responses=[{functionResponse:{name:'activate_skill',response:{output}}},...(process.env.BODY==='split messages'?[{functionResponse:{name:'activate_skill',response:{output:body}}}]:[])];\nconst second=await globalThis.fakeRequest({body:{contents:[{parts:responses}]},tools});const payload=output;\nawait writeFile(process.env.STATE+'/observed.json',JSON.stringify({first,second,payload}));throw Error('intentional stop before client mutation');},async close(){}};}\n".replace(
|
||||
"REPLACE_CONTRACTS",
|
||||
JSON.stringify(
|
||||
new URL("../../../dist/contracts/toolContracts.js", import.meta.url)
|
||||
.href,
|
||||
),
|
||||
);
|
||||
await writeFile(join(state, "commands.mjs"), commands);
|
||||
await writeFile(
|
||||
join(state, "fixture.mjs"),
|
||||
"export async function createGeminiModelFixture({onRequest}){globalThis.fakeRequest=onRequest;return {baseUrl:'http://127.0.0.1:1',async close(){}};}\n",
|
||||
import {
|
||||
hasGeminiFinalAnswer,
|
||||
hasGeminiSkillBody,
|
||||
} from "../../../scripts/verify/clients/gemini-evidence.mjs";
|
||||
|
||||
it("binds Gemini's native activation to its instructions and resource root", () => {
|
||||
const directory = join("fixture", "selected profile", "skill");
|
||||
const instructions = 'Essential "instructions"\r\nKeep a \\ literal';
|
||||
const payload = `<activated_skill name="reverse-engineer-anything">
|
||||
<instructions>
|
||||
${instructions}
|
||||
</instructions>
|
||||
|
||||
<available_resources>
|
||||
Showing up to 200 items (files + folders).
|
||||
|
||||
${directory}${sep}
|
||||
└───SKILL.md
|
||||
</available_resources>
|
||||
</activated_skill>`;
|
||||
const reply = (output: string, name = "activate_skill") => ({
|
||||
name,
|
||||
response: { output },
|
||||
});
|
||||
expect(hasGeminiSkillBody([reply(payload)], directory, instructions)).toBe(
|
||||
true,
|
||||
);
|
||||
const literalTags = `Literal </instructions> and </activated_skill>\r\n${instructions}`;
|
||||
expect(
|
||||
hasGeminiSkillBody(
|
||||
[reply(payload.replace(instructions, literalTags))],
|
||||
directory,
|
||||
literalTags,
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
const withoutBody = payload.replace(instructions, "");
|
||||
for (const [label, responses] of [
|
||||
["empty", [reply("")]],
|
||||
["wrong tool", [reply(payload, "read_file")]],
|
||||
[
|
||||
"neighboring root",
|
||||
[reply(payload.replace(directory, directory + "-other"))],
|
||||
],
|
||||
[
|
||||
"early close",
|
||||
[reply(payload.replace("└───SKILL.md", "</activated_skill>"))],
|
||||
],
|
||||
["outside wrapper", [reply(withoutBody + instructions)]],
|
||||
[
|
||||
"inside resources",
|
||||
[reply(withoutBody.replace("└───SKILL.md", instructions))],
|
||||
],
|
||||
["split responses", [reply(withoutBody), reply(instructions)]],
|
||||
] as const)
|
||||
expect(hasGeminiSkillBody(responses, directory, instructions), label).toBe(
|
||||
false,
|
||||
);
|
||||
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-gemini-client.mjs')){let f;if(specifier==='./lib/verify-commands.mjs')f='commands.mjs';if(specifier==='./verify/clients/gemini-model-fixture.mjs')f='fixture.mjs';if(f)return{url:pathToFileURL(process.env.STATE+'/'+f).href,shortCircuit:true};}return next(specifier,context);}});\n",
|
||||
});
|
||||
|
||||
it("requires the final Gemini assistant text and a terminal success event", () => {
|
||||
const message = (role: string, content: string) => ({
|
||||
type: "message",
|
||||
role,
|
||||
content,
|
||||
delta: true,
|
||||
});
|
||||
const tool = { type: "tool_result", output: "expected answer" };
|
||||
const result = { type: "result", status: "success" };
|
||||
const stream = (frames: readonly object[]) =>
|
||||
frames.map((frame) => JSON.stringify(frame) + "\n").join("");
|
||||
const answer = message("assistant", "expected answer");
|
||||
expect(
|
||||
hasGeminiFinalAnswer(
|
||||
stream([
|
||||
answer,
|
||||
tool,
|
||||
message("assistant", "expected "),
|
||||
message("assistant", "answer"),
|
||||
result,
|
||||
]),
|
||||
"expected answer",
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
for (const [label, frames] of [
|
||||
["marker on a user frame", [message("user", "expected answer"), result]],
|
||||
["marker in a tool result", [tool, message("assistant", "wrong"), result]],
|
||||
["assistant before tool", [answer, tool, result]],
|
||||
["failed result", [answer, { ...result, status: "error" }]],
|
||||
[
|
||||
"later event",
|
||||
[answer, result, { type: "error", message: "late failure" }],
|
||||
],
|
||||
["two results", [answer, result, result]],
|
||||
] as const)
|
||||
expect(hasGeminiFinalAnswer(stream(frames), "expected answer"), label).toBe(
|
||||
false,
|
||||
);
|
||||
const script = fileURLToPath(
|
||||
new URL("../../../scripts/verify-gemini-client.mjs", import.meta.url),
|
||||
);
|
||||
const result = spawnSync(
|
||||
process.execPath,
|
||||
["--import", join(state, "hook.mjs"), script],
|
||||
{
|
||||
encoding: "utf8",
|
||||
timeout: 10_000,
|
||||
env: {
|
||||
...process.env,
|
||||
STATE: state,
|
||||
BODY: body,
|
||||
TMPDIR: state,
|
||||
TMP: state,
|
||||
TEMP: state,
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(result.status).not.toBe(0);
|
||||
const observed = await readFile(join(state, "observed.json"), "utf8").then(
|
||||
JSON.parse,
|
||||
() => null,
|
||||
);
|
||||
expect(observed !== null).toBe(allowed);
|
||||
if (allowed)
|
||||
expect(observed.second[0].functionCall.name).toBe(
|
||||
"rea__analyze_javascript_application",
|
||||
);
|
||||
expect(result.stderr).toContain(
|
||||
allowed
|
||||
? "intentional stop before client mutation"
|
||||
: "Gemini must load the installed personal REA skill",
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user