From 34c69f606dd5032089de091adaefd6f179afb059 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 21 Nov 2026 19:00:18 -0500
Subject: [PATCH] fix(verification): require Gemini native answer and skill
provenance (#13241)
---
scripts/verify-gemini-client.mjs | 50 ++----
scripts/verify/clients/gemini-evidence.mjs | 62 +++++++
.../process/geminiVerifierSkillBody.test.ts | 169 ++++++++++--------
3 files changed, 176 insertions(+), 105 deletions(-)
create mode 100644 scripts/verify/clients/gemini-evidence.mjs
diff --git a/scripts/verify-gemini-client.mjs b/scripts/verify-gemini-client.mjs
index f5c404f0f4..a473997fe6 100644
--- a/scripts/verify-gemini-client.mjs
+++ b/scripts/verify-gemini-client.mjs
@@ -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 = `\n \n ${expectedSkillBody}\n \n\n \n `;
- const at = output.indexOf(start);
- if (at < 0) return false;
- const resourcesStart = at + start.length;
- const resourcesEnd = output.indexOf(
- "\n \n",
- resourcesStart,
- );
- if (resourcesEnd < 0) return false;
- const resources = output.slice(resourcesStart, resourcesEnd);
- return (
- !resources.includes("") &&
- !resources.includes("") &&
- 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,
diff --git a/scripts/verify/clients/gemini-evidence.mjs b/scripts/verify/clients/gemini-evidence.mjs
new file mode 100644
index 0000000000..cea463e2ce
--- /dev/null
+++ b/scripts/verify/clients/gemini-evidence.mjs
@@ -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 = `\n \n ${body}\n \n\n \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 \n",
+ first,
+ );
+ if (last < 0) return false;
+ const resources = output.slice(first, last);
+ const [, blank, root] = resources.split("\n", 3);
+ return (
+ !resources.includes("") &&
+ !resources.includes("") &&
+ 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;
+}
diff --git a/tests/boundary/process/geminiVerifierSkillBody.test.ts b/tests/boundary/process/geminiVerifierSkillBody.test.ts
index c1d1e3ab9c..7283ec4892 100644
--- a/tests/boundary/process/geminiVerifierSkillBody.test.ts
+++ b/tests/boundary/process/geminiVerifierSkillBody.test.ts
@@ -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 and \\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 and \\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?' \\n '+body+'\\n \\n\\n':'';\nconst output='\\n'+instructions+' \\n '+skill+(process.env.BODY==='closed early'?'':'')+(process.env.BODY==='inside resources'?body:'')+'\\n \\n'+(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 = `
+
+ ${instructions}
+
+
+
+ Showing up to 200 items (files + folders).
+
+${directory}${sep}
+└───SKILL.md
+
+`;
+ const reply = (output: string, name = "activate_skill") => ({
+ name,
+ response: { output },
+ });
+ expect(hasGeminiSkillBody([reply(payload)], directory, instructions)).toBe(
+ true,
+ );
+ const literalTags = `Literal and \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", ""))],
+ ],
+ ["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",
- );
- },
-);
+});