local-output-safety-writer-v2-guide-review.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /**
  2. * LocalOutputSafetyEventWriter × SafetyCheckV2 guide review path.
  3. *
  4. * Coverage:
  5. * - Explicit V2 Review preserves a model-only guide and blocks the draft.
  6. * - V1 ignores guide fields and retains its original SR regeneration path.
  7. * - Guidance may appear only at the system_prompt boundary, never in final AgentMessage or
  8. * user-visible stream events (hard boundary).
  9. * - consumeGuidePrompt / resetGuideReview state machine.
  10. * - Metrics counting (`output_safety_check_total{decision=guide_review}`).
  11. */
  12. import { describe, it, expect, vi } from 'vitest';
  13. import { RespDataType } from '@mavis/agent-core/protocol/agent-message';
  14. import { RuntimeEventType, type IRuntimeEvent } from '@mavis/protocol';
  15. import { LocalOutputSafetyEventWriter } from '../../src/runtime/output-safety-writer.js';
  16. import {
  17. createLocalRuntimeMetricsClient,
  18. type LocalRuntimeMetricsClient,
  19. } from '../../src/common/metrics.js';
  20. import {
  21. callSafetyApi,
  22. SAFETY_SCENE,
  23. type SafetyCheckResult,
  24. } from '../../src/content-safety/api.js';
  25. import { LocalRuntimeHost, type LocalTurnRunner } from '../../src/runtime/host.js';
  26. import { OUTPUT_REVISION_INSTRUCTION } from '../../src/runtime/output-safety-policy.js';
  27. function contentChunk(text: string, msgId = 'msg_1'): IRuntimeEvent {
  28. return {
  29. schema: 'runtime.event/v1',
  30. event_id: `evt_${Math.random().toString(36).slice(2)}`,
  31. session_id: 'ses_1',
  32. turn_id: 'turn_1',
  33. type: RuntimeEventType.STREAM_RESP,
  34. payload: {
  35. stream_resp: JSON.stringify({
  36. type: RespDataType.AgentMessageChunk,
  37. agent_message_chunk: { msg_id: msgId, msg_content: text },
  38. }),
  39. },
  40. } as IRuntimeEvent;
  41. }
  42. function finalMessageEvent(content: string, msgId = 'msg_1'): IRuntimeEvent {
  43. return {
  44. schema: 'runtime.event/v1',
  45. event_id: `evt_${Math.random().toString(36).slice(2)}`,
  46. session_id: 'ses_1',
  47. turn_id: 'turn_1',
  48. type: RuntimeEventType.STREAM_RESP,
  49. payload: {
  50. stream_resp: JSON.stringify({
  51. type: RespDataType.AgentMessage,
  52. agent_message: { msg_id: msgId, msg_content: content },
  53. }),
  54. },
  55. } as IRuntimeEvent;
  56. }
  57. interface CapturedSinkEvent {
  58. type: RuntimeEventType;
  59. text: string;
  60. }
  61. function makeSink(): {
  62. inner: {
  63. pushRuntime: (e: IRuntimeEvent) => Promise<void>;
  64. appendEvents: (e: IRuntimeEvent[]) => Promise<void>;
  65. };
  66. captured: CapturedSinkEvent[];
  67. } {
  68. const captured: CapturedSinkEvent[] = [];
  69. const inner = {
  70. async pushRuntime(event: IRuntimeEvent): Promise<void> {
  71. const raw = event.payload?.stream_resp;
  72. if (typeof raw === 'string') {
  73. try {
  74. const parsed = JSON.parse(raw) as {
  75. type: number;
  76. agent_message?: { msg_content?: string };
  77. };
  78. if (parsed.type === RespDataType.AgentMessage && parsed.agent_message) {
  79. captured.push({ type: event.type, text: parsed.agent_message.msg_content ?? '' });
  80. }
  81. } catch {
  82. // ignore parse error
  83. }
  84. }
  85. },
  86. async appendEvents(events: IRuntimeEvent[]): Promise<void> {
  87. for (const e of events) await inner.pushRuntime(e);
  88. },
  89. };
  90. return { inner, captured };
  91. }
  92. const SENTINEL_GUIDE_PROMPT = 'V2-SECRET-GUIDE-PROMPT-DO-NOT-LEAK';
  93. describe('LocalOutputSafetyEventWriter — V2 guide review', () => {
  94. it('explicit Review with guide_prompt blocks the draft and preserves the next attempt guide', async () => {
  95. const checkText = vi.fn(
  96. async (): Promise<SafetyCheckResult> => ({
  97. pass: false,
  98. action: 'guide',
  99. guide_prompt: SENTINEL_GUIDE_PROMPT,
  100. errorKind: 'rejected',
  101. }),
  102. );
  103. const { inner } = makeSink();
  104. const sinkSpy = vi.spyOn(inner, 'pushRuntime');
  105. const onBlocked = vi.fn();
  106. const writer = new LocalOutputSafetyEventWriter(inner, {
  107. checkText,
  108. chunkThreshold: 0,
  109. onBlocked,
  110. });
  111. await writer.pushRuntime(contentChunk('rejected draft'));
  112. await writer.pushRuntime(finalMessageEvent('rejected final'));
  113. expect(writer.blocked).toBe(true);
  114. expect(writer.guideReviewed).toBe(true);
  115. expect(onBlocked).toHaveBeenCalledOnce();
  116. expect(sinkSpy).not.toHaveBeenCalled();
  117. expect(checkText).toHaveBeenCalledOnce();
  118. expect(writer.consumeGuidePrompt()).toBe(SENTINEL_GUIDE_PROMPT);
  119. });
  120. it('reject without guide_prompt → 走原 block 路径', async () => {
  121. const checkText = vi.fn(
  122. async (): Promise<SafetyCheckResult> => ({
  123. pass: false,
  124. reason: 'rejected',
  125. errorKind: 'rejected',
  126. }),
  127. );
  128. const { inner } = makeSink();
  129. const writer = new LocalOutputSafetyEventWriter(inner, {
  130. checkText,
  131. chunkThreshold: 0,
  132. });
  133. await writer.pushRuntime(contentChunk('内容'));
  134. expect(writer.blocked).toBe(true);
  135. expect(writer.guideReviewed).toBe(false);
  136. expect(writer.consumeGuidePrompt()).toBeUndefined();
  137. });
  138. it('reject + 空字符串 guide_prompt → 当作缺失,走 block 路径(防御性)', async () => {
  139. const checkText = vi.fn(
  140. async (): Promise<SafetyCheckResult> => ({
  141. pass: false,
  142. action: 'guide',
  143. reason: 'rejected',
  144. guide_prompt: '',
  145. errorKind: 'rejected',
  146. }),
  147. );
  148. const { inner } = makeSink();
  149. const writer = new LocalOutputSafetyEventWriter(inner, {
  150. checkText,
  151. chunkThreshold: 0,
  152. });
  153. await writer.pushRuntime(contentChunk('内容'));
  154. expect(writer.blocked).toBe(true);
  155. expect(writer.guideReviewed).toBe(false);
  156. });
  157. it('clean pass + 有 guide_prompt → 不动 guide state(guide_prompt 只在 reject 时有效)', async () => {
  158. const checkText = vi.fn(
  159. async (): Promise<SafetyCheckResult> => ({
  160. pass: true,
  161. guide_prompt: SENTINEL_GUIDE_PROMPT,
  162. }),
  163. );
  164. const { inner } = makeSink();
  165. const writer = new LocalOutputSafetyEventWriter(inner, {
  166. checkText,
  167. chunkThreshold: 0,
  168. });
  169. await writer.pushRuntime(contentChunk('OK'));
  170. expect(writer.blocked).toBe(false);
  171. expect(writer.guideReviewed).toBe(false);
  172. expect(writer.consumeGuidePrompt()).toBeUndefined();
  173. });
  174. it('consumeGuidePrompt() 调用后清空状态(避免跨 attempt 残留)', async () => {
  175. const checkText = vi.fn(
  176. async (): Promise<SafetyCheckResult> => ({
  177. pass: false,
  178. action: 'guide',
  179. reason: 'rejected',
  180. guide_prompt: SENTINEL_GUIDE_PROMPT,
  181. errorKind: 'rejected',
  182. }),
  183. );
  184. const { inner } = makeSink();
  185. const writer = new LocalOutputSafetyEventWriter(inner, {
  186. checkText,
  187. chunkThreshold: 0,
  188. });
  189. await writer.pushRuntime(contentChunk('问题内容'));
  190. expect(writer.guideReviewed).toBe(true);
  191. expect(writer.consumeGuidePrompt()).toBe(SENTINEL_GUIDE_PROMPT);
  192. expect(writer.consumeGuidePrompt()).toBeUndefined();
  193. expect(writer.guideReviewed).toBe(false);
  194. });
  195. it('resetGuideReview() 清空状态(host 每个 attempt 边界调一次)', async () => {
  196. const checkText = vi.fn(
  197. async (): Promise<SafetyCheckResult> => ({
  198. pass: false,
  199. action: 'guide',
  200. reason: 'rejected',
  201. guide_prompt: SENTINEL_GUIDE_PROMPT,
  202. errorKind: 'rejected',
  203. }),
  204. );
  205. const { inner } = makeSink();
  206. const writer = new LocalOutputSafetyEventWriter(inner, {
  207. checkText,
  208. chunkThreshold: 0,
  209. });
  210. await writer.pushRuntime(contentChunk('问题内容'));
  211. expect(writer.guideReviewed).toBe(true);
  212. writer.resetGuideReview();
  213. expect(writer.guideReviewed).toBe(false);
  214. expect(writer.consumeGuidePrompt()).toBeUndefined();
  215. });
  216. it('CRITICAL: V2 guide_prompt 绝不出现在 final AgentMessage / user-visible 流事件里', async () => {
  217. const checkText = vi.fn(
  218. async (): Promise<SafetyCheckResult> => ({
  219. pass: false,
  220. action: 'guide',
  221. reason: 'rejected',
  222. guide_prompt: SENTINEL_GUIDE_PROMPT,
  223. errorKind: 'rejected',
  224. }),
  225. );
  226. const { inner, captured } = makeSink();
  227. const writer = new LocalOutputSafetyEventWriter(inner, {
  228. checkText,
  229. chunkThreshold: 0,
  230. });
  231. const sinkSpy = vi.spyOn(inner, 'pushRuntime');
  232. await writer.pushRuntime(contentChunk('问题内容1'));
  233. await writer.pushRuntime(finalMessageEvent('问题内容 final', 'msg_1'));
  234. expect(sinkSpy).not.toHaveBeenCalled();
  235. expect(captured).toEqual([]);
  236. // guide_prompt remains readable from internal writer state for the host to assemble systemPrompt.
  237. expect(writer.guideReviewed).toBe(true);
  238. expect(writer.consumeGuidePrompt()).toBe(SENTINEL_GUIDE_PROMPT);
  239. });
  240. it('metrics: guide review 决策记 decision=guide_review, 不计 output_safety_block_total', async () => {
  241. const checkText = vi.fn(
  242. async (): Promise<SafetyCheckResult> => ({
  243. pass: false,
  244. action: 'guide',
  245. reason: 'rejected',
  246. guide_prompt: SENTINEL_GUIDE_PROMPT,
  247. errorKind: 'rejected',
  248. }),
  249. );
  250. const { inner } = makeSink();
  251. const metrics = createLocalRuntimeMetricsClient({ runtimeOwnerKind: 'test' });
  252. const counterSpy = vi.spyOn(metrics, 'counter');
  253. const writer = new LocalOutputSafetyEventWriter(inner, {
  254. checkText,
  255. chunkThreshold: 0,
  256. metricsClient: metrics as LocalRuntimeMetricsClient,
  257. });
  258. await writer.pushRuntime(contentChunk('问题内容'));
  259. // Find the guide_review decision.
  260. const guideReviewCalls = counterSpy.mock.calls.filter(
  261. (c) =>
  262. c[0] === 'output_safety_check_total' &&
  263. (c[2] as { decision?: string } | undefined)?.decision === 'guide_review',
  264. );
  265. expect(guideReviewCalls.length).toBeGreaterThan(0);
  266. // There must be no decision=block.
  267. const blockCalls = counterSpy.mock.calls.filter(
  268. (c) =>
  269. c[0] === 'output_safety_check_total' &&
  270. (c[2] as { decision?: string } | undefined)?.decision === 'block',
  271. );
  272. expect(blockCalls.length).toBe(0);
  273. // Do not increment output_safety_block_total; guide review is not a hard block.
  274. const blockTotalCalls = counterSpy.mock.calls.filter(
  275. (c) => c[0] === 'output_safety_block_total',
  276. );
  277. expect(blockTotalCalls.length).toBe(0);
  278. });
  279. it('ignores a guide without an explicit Review and leaves the SR fallback active', async () => {
  280. const { inner } = makeSink();
  281. const writer = new LocalOutputSafetyEventWriter(inner, {
  282. checkText: async () => ({
  283. pass: false,
  284. errorKind: 'rejected',
  285. guide_prompt: SENTINEL_GUIDE_PROMPT,
  286. }),
  287. chunkThreshold: 0,
  288. });
  289. await writer.pushRuntime(contentChunk('legacy rejected draft'));
  290. expect(writer.blocked).toBe(true);
  291. expect(writer.immediateBlock).toBe(false);
  292. expect(writer.guideReviewed).toBe(false);
  293. expect(writer.consumeGuidePrompt()).toBeUndefined();
  294. });
  295. it.each([
  296. { apiVersion: undefined, instruction: OUTPUT_REVISION_INSTRUCTION },
  297. { apiVersion: 'v2' as const, instruction: SENTINEL_GUIDE_PROMPT },
  298. ])(
  299. 'uses the correct regeneration instruction for API $apiVersion',
  300. async ({ apiVersion, instruction }) => {
  301. const prompts: string[] = [];
  302. let reviews = 0;
  303. const fetchImpl = vi
  304. .fn<typeof fetch>()
  305. .mockImplementation(async () => {
  306. const rejected = reviews++ === 0;
  307. if (apiVersion === 'v2') {
  308. return Response.json(
  309. rejected
  310. ? { action: 4, errorCode: 50201, guide_prompt: SENTINEL_GUIDE_PROMPT }
  311. : { action: 1 },
  312. );
  313. }
  314. return Response.json(
  315. rejected
  316. ? {
  317. pass: false,
  318. decision: 'review',
  319. errorCode: 50201,
  320. guide_prompt: SENTINEL_GUIDE_PROMPT,
  321. }
  322. : { pass: true, decision: 'pass' },
  323. );
  324. });
  325. const piRunner: LocalTurnRunner = {
  326. async runTurn(input) {
  327. prompts.push(input.systemPrompt);
  328. await input.eventWriter.pushRuntime(finalMessageEvent('draft'));
  329. },
  330. };
  331. const host = new LocalRuntimeHost({ piRunner, fetchImpl, safetyApiVersion: apiVersion });
  332. const output = await host.runTurn({
  333. sessionId: 'ses_1',
  334. turnId: 'turn_1',
  335. workspaceDir: '/tmp/workspace',
  336. systemPrompt: 'base prompt',
  337. userMessage: { text: 'hello' },
  338. llm: { model: {} as never },
  339. rewindPiHistory: async () => {},
  340. });
  341. expect(prompts).toEqual(['base prompt', `base prompt\n\n${instruction}`]);
  342. expect(output.retracted).toBe(false);
  343. expect(fetchImpl.mock.calls[0]?.[0]).toMatch(
  344. apiVersion === 'v2' ? /\/v2\/content\?require_auth=true$/ : /\/v1\/content$/,
  345. );
  346. expect(JSON.stringify(output.events)).not.toContain(SENTINEL_GUIDE_PROMPT);
  347. },
  348. );
  349. });
  350. describe('callSafetyApi preserves the V1 response contract', () => {
  351. it.each([
  352. { pass: false, guide: SENTINEL_GUIDE_PROMPT },
  353. { pass: true, guide: SENTINEL_GUIDE_PROMPT },
  354. { pass: false, guide: '' },
  355. { pass: false, guide: ' ' },
  356. { pass: false, guide: 12345 },
  357. { pass: false, guide: null },
  358. ])('ignores V2-only fields from a V1 response: %j', async ({ pass, guide }) => {
  359. const fetchImpl = vi.fn<typeof fetch>().mockImplementation(async () =>
  360. Response.json({
  361. pass,
  362. decision: 'review',
  363. action: 'guide',
  364. guide_prompt: guide,
  365. ...(pass ? {} : { errorCode: 50201 }),
  366. }),
  367. );
  368. const result = await callSafetyApi({
  369. content: 'test',
  370. scene: SAFETY_SCENE.MessageOutput,
  371. fetchImpl,
  372. region: () => 'cn',
  373. buildEnv: () => 'test',
  374. });
  375. expect(result.pass).toBe(pass);
  376. expect(result).not.toHaveProperty('guide_prompt');
  377. expect(result).not.toHaveProperty('decision');
  378. expect(result).not.toHaveProperty('action');
  379. expect(result.errorKind).toBe(pass ? undefined : 'rejected');
  380. expect(fetchImpl.mock.calls[0]?.[0]).toMatch(/\/v1\/content$/);
  381. });
  382. });