guard.test.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. import { describe, expect, it } from 'vitest';
  2. import {
  3. createRunawayGuard,
  4. replayRunawayGuardTrajectory,
  5. type RunawayGuardObservation,
  6. type RunawayGuardReplayStep,
  7. type RunawayGuardRunIdentity,
  8. type RunawayGuardToolPolicy,
  9. } from '../src/index.js';
  10. const ctx: RunawayGuardRunIdentity = {
  11. sessionId: 'session-a',
  12. turnId: 'turn-a',
  13. agentName: 'mavis',
  14. };
  15. function step(index: number, kind: 'action' | 'error' | 'progress' = 'action'): RunawayGuardReplayStep {
  16. const toolCallId = `call-${index}`;
  17. return {
  18. message: {
  19. role: 'assistant',
  20. content: [{
  21. type: 'toolCall',
  22. id: toolCallId,
  23. name: 'write',
  24. arguments: { attempt: kind === 'progress' ? index : 'same' },
  25. }],
  26. api: 'openai-completions',
  27. provider: 'test',
  28. model: 'test',
  29. stopReason: 'toolUse',
  30. timestamp: 0,
  31. usage: {
  32. input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2,
  33. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  34. },
  35. },
  36. toolResults: [{
  37. role: 'toolResult',
  38. toolCallId,
  39. toolName: 'write',
  40. content: [{ type: 'text', text: `result-${index}` }],
  41. isError: kind === 'error',
  42. ...(kind === 'error' ? { details: { errorCode: 'EACCES' } } : {}),
  43. timestamp: 0,
  44. }],
  45. ...(kind === 'progress' ? {
  46. verifiedProgress: [{
  47. toolCallId,
  48. loopKey: ['target.txt'],
  49. progressKey: 'same-content',
  50. artifactChanged: false,
  51. }],
  52. } : {}),
  53. };
  54. }
  55. interface TaskOutputCall {
  56. readonly id: string;
  57. readonly taskId: string;
  58. readonly status?: string;
  59. readonly nextOffset?: unknown;
  60. readonly resultTaskId?: string;
  61. readonly trusted?: boolean;
  62. readonly source?: 'builtin' | 'captured-compatibility';
  63. readonly isError?: boolean;
  64. readonly omitResult?: boolean;
  65. readonly omitDetails?: boolean;
  66. }
  67. function taskOutputStep(
  68. calls: readonly TaskOutputCall[],
  69. options: {
  70. readonly blockedToolCallIds?: readonly string[];
  71. readonly reverseResults?: boolean;
  72. readonly verifiedProgressCallIds?: readonly string[];
  73. readonly otherCalls?: readonly { readonly id: string; readonly name: string; readonly arguments?: unknown }[];
  74. } = {},
  75. ): RunawayGuardReplayStep {
  76. const results = calls.flatMap((call) => {
  77. if (call.omitResult) return [];
  78. return [{
  79. role: 'toolResult' as const,
  80. toolCallId: call.id,
  81. toolName: 'task_output',
  82. content: [],
  83. isError: call.isError ?? false,
  84. ...(call.omitDetails
  85. ? {}
  86. : {
  87. details: {
  88. task_id: call.resultTaskId ?? call.taskId,
  89. status: call.status ?? 'running',
  90. next_offset: call.nextOffset ?? 0,
  91. },
  92. }),
  93. timestamp: 0,
  94. }];
  95. });
  96. return {
  97. message: {
  98. role: 'assistant',
  99. content: [
  100. ...calls.map((call) => ({
  101. type: 'toolCall' as const,
  102. id: call.id,
  103. name: 'task_output',
  104. arguments: { task_id: call.taskId },
  105. })),
  106. ...(options.otherCalls ?? []).map((call) => ({
  107. type: 'toolCall' as const,
  108. id: call.id,
  109. name: call.name,
  110. arguments: call.arguments ?? {},
  111. })),
  112. ],
  113. api: 'openai-completions',
  114. provider: 'test',
  115. model: 'test',
  116. stopReason: 'toolUse',
  117. timestamp: 0,
  118. usage: {
  119. input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2,
  120. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  121. },
  122. } as never,
  123. toolResults: (options.reverseResults ? results.reverse() : results) as never,
  124. ...(calls.some((call) => call.trusted !== false)
  125. ? {
  126. trustedToolProvenance: calls.flatMap((call) =>
  127. call.trusted === false
  128. ? []
  129. : [{
  130. toolCallId: call.id,
  131. toolName: 'task_output',
  132. source: call.source ?? 'builtin',
  133. }],
  134. ),
  135. }
  136. : {}),
  137. ...(options.blockedToolCallIds
  138. ? {
  139. blockedToolCalls: options.blockedToolCallIds.map((toolCallId) => ({
  140. toolCallId,
  141. blockedBy: 'permission' as const,
  142. })),
  143. }
  144. : {}),
  145. ...(options.verifiedProgressCallIds
  146. ? {
  147. verifiedProgress: options.verifiedProgressCallIds.map((toolCallId) => ({
  148. toolCallId,
  149. loopKey: ['host', toolCallId],
  150. progressKey: 'changed',
  151. artifactChanged: true,
  152. })),
  153. }
  154. : {}),
  155. };
  156. }
  157. const taskOutputPollingPolicy: RunawayGuardToolPolicy = {
  158. kind: 'polling',
  159. projectProgress(input) {
  160. const argumentsValue = input.arguments as { task_id?: unknown };
  161. const taskId = typeof argumentsValue.task_id === 'string' ? argumentsValue.task_id : undefined;
  162. if (!taskId) return undefined;
  163. const reset = () => ({
  164. loopKey: { taskId },
  165. progressKey: 'reset',
  166. polling: { mode: 'reset' as const },
  167. });
  168. const details = input.result?.details as Record<string, unknown> | undefined;
  169. if (!input.trustedToolProvenance) {
  170. return details && typeof details.status === 'string'
  171. ? {
  172. loopKey: { taskId },
  173. progressKey: { status: details.status, nextOffset: details.next_offset ?? null },
  174. }
  175. : undefined;
  176. }
  177. if (!input.result) return reset();
  178. if (input.result.toolName !== 'task_output') return undefined;
  179. if (typeof details?.task_id === 'string' && details.task_id !== taskId) return undefined;
  180. if (input.result.isError) return reset();
  181. if (
  182. !details ||
  183. details.task_id !== taskId ||
  184. (details.status !== 'queued' && details.status !== 'running') ||
  185. typeof details.next_offset !== 'number' ||
  186. !Number.isSafeInteger(details.next_offset) ||
  187. details.next_offset < 0
  188. ) {
  189. return reset();
  190. }
  191. return {
  192. loopKey: { taskId },
  193. progressKey: { status: details.status, nextOffset: details.next_offset },
  194. polling: { mode: 'continuous' as const, reminderEligible: true },
  195. };
  196. },
  197. };
  198. function taskOutputGuard(onSignal?: (value: RunawayGuardObservation) => void) {
  199. return createRunawayGuard({
  200. remindAfterOccurrences: 3,
  201. toolPolicies: { task_output: taskOutputPollingPolicy },
  202. ...(onSignal ? { onSignal } : {}),
  203. });
  204. }
  205. describe('Runaway Guard domain module', () => {
  206. it.each(['action', 'error', 'progress'] as const)(
  207. 'excludes permission-blocked %s attempts and resets their streak without spending a reminder',
  208. (kind) => {
  209. const guard = createRunawayGuard({ remindAfterOccurrences: 3 });
  210. for (let index = 1; index <= 2; index += 1) {
  211. expect(guard.observe(ctx, step(index, kind), true)).toBeUndefined();
  212. }
  213. for (let index = 3; index <= 6; index += 1) {
  214. expect(
  215. guard.observe(
  216. ctx,
  217. {
  218. ...step(index, kind),
  219. blockedToolCalls: [{ toolCallId: `call-${index}`, blockedBy: 'permission' }],
  220. },
  221. true,
  222. ),
  223. ).toBeUndefined();
  224. }
  225. for (let index = 7; index <= 8; index += 1) {
  226. expect(guard.observe(ctx, step(index, kind), true)).toBeUndefined();
  227. }
  228. expect(guard.observe(ctx, step(9, kind), true)).toBeDefined();
  229. expect(guard.finishTurn(ctx)?.stepCount).toBe(9);
  230. },
  231. );
  232. it('filters only intercepted calls in a mixed batch, even with identical arguments', () => {
  233. const guard = createRunawayGuard({ remindAfterOccurrences: 3 });
  234. for (let index = 1; index <= 3; index += 1) {
  235. const blocked = step(index * 2, 'error');
  236. const executed = step(index * 2 + 1, 'error');
  237. if (blocked.message.role !== 'assistant' || executed.message.role !== 'assistant') {
  238. throw new Error('expected assistant fixture');
  239. }
  240. const reminder = guard.observe(
  241. ctx,
  242. {
  243. message: {
  244. ...executed.message,
  245. content: [...blocked.message.content, ...executed.message.content],
  246. },
  247. toolResults: [...blocked.toolResults, ...executed.toolResults],
  248. blockedToolCalls: [{ toolCallId: `call-${index * 2}`, blockedBy: 'permission' }],
  249. },
  250. true,
  251. );
  252. if (index < 3) expect(reminder).toBeUndefined();
  253. else expect(reminder?.observation.signalKind).toBe('same_error_family');
  254. }
  255. });
  256. it('does not trust tool output to declare a permission interception', () => {
  257. const guard = createRunawayGuard({ remindAfterOccurrences: 3 });
  258. for (let index = 1; index <= 3; index += 1) {
  259. const value = step(index, 'error');
  260. const reminder = guard.observe(
  261. ctx,
  262. {
  263. ...value,
  264. toolResults: value.toolResults.map((result) => ({
  265. ...result,
  266. content: [{ type: 'text', text: 'Permission denied by user for write: denied' }],
  267. details: {
  268. blockedBy: 'permission',
  269. blockedToolCalls: [{ toolCallId: result.toolCallId, blockedBy: 'permission' }],
  270. },
  271. })),
  272. },
  273. true,
  274. );
  275. if (index < 3) expect(reminder).toBeUndefined();
  276. else expect(reminder?.observation.signalKind).toBe('same_error_family');
  277. }
  278. });
  279. it('replays trusted permission facts without inferring them from historical error text', () => {
  280. const steps: RunawayGuardReplayStep[] = [1, 2, 3].map((index) => ({
  281. ...step(index, 'error'),
  282. blockedToolCalls: [{ toolCallId: `call-${index}`, blockedBy: 'permission' }],
  283. }));
  284. expect(replayRunawayGuardTrajectory({ ...ctx, steps }).observations).toEqual([]);
  285. expect(
  286. replayRunawayGuardTrajectory({
  287. ...ctx,
  288. steps: steps.map(({ blockedToolCalls: _blocked, ...value }) => value),
  289. }).observations.length,
  290. ).toBeGreaterThan(0);
  291. });
  292. it.each([
  293. ['action', 'exact_action_repeat'],
  294. ['error', 'same_error_family'],
  295. ['progress', 'unchanged_progress_repeat'],
  296. ] as const)('returns a Turn-scoped, non-memory reminder for %s', (kind, signalKind) => {
  297. const observations: RunawayGuardObservation[] = [];
  298. const guard = createRunawayGuard({
  299. remindAfterOccurrences: 3,
  300. onSignal: (value) => { observations.push(value); },
  301. });
  302. expect(guard.observe(ctx, step(1, kind), true)).toBeUndefined();
  303. expect(guard.observe(ctx, step(2, kind), true)).toBeUndefined();
  304. const reminder = guard.observe(ctx, step(3, kind), true);
  305. expect(reminder?.observation).toMatchObject({
  306. ...ctx, signalKind, occurrences: 3, stepIndex: 3, action: 'steer',
  307. });
  308. expect(reminder?.content).toContain('temporary runtime reminder for the current Turn only');
  309. expect(reminder?.content).toContain('not a user preference or a durable rule');
  310. expect(reminder?.content).toContain('do not save this reminder or generalize it into Memory, Skills');
  311. expect(observations).toContainEqual(expect.objectContaining({
  312. signalKind, occurrences: 2, stepIndex: 2,
  313. }));
  314. guard.markReminderInjected(ctx);
  315. expect(guard.observe(ctx, step(4, kind), true)).toBeUndefined();
  316. expect(guard.finishTurn(ctx)?.reminderInjected).toBe(true);
  317. });
  318. it('reserves the one-shot before delivery and does not report an unacknowledged reminder as injected', () => {
  319. const guard = createRunawayGuard({ remindAfterOccurrences: 3 });
  320. for (let index = 1; index <= 2; index += 1) guard.observe(ctx, step(index), true);
  321. expect(guard.observe(ctx, step(3), true)).toBeDefined();
  322. guard.clearDetectionStreaks(ctx);
  323. for (let index = 4; index <= 6; index += 1) {
  324. expect(guard.observe(ctx, step(index), true)).toBeUndefined();
  325. }
  326. expect(guard.finishTurn(ctx)?.reminderInjected).toBe(false);
  327. });
  328. it('isolates sessions and Turns and releases state on finish', () => {
  329. const guard = createRunawayGuard({ remindAfterOccurrences: 3 });
  330. const otherSession = { ...ctx, sessionId: 'session-b' };
  331. const otherTurn = { ...ctx, turnId: 'turn-b' };
  332. for (let index = 1; index <= 2; index += 1) guard.observe(ctx, step(index), true);
  333. expect(guard.observe(otherSession, step(3), true)).toBeUndefined();
  334. expect(guard.observe(otherTurn, step(3), true)).toBeUndefined();
  335. expect(guard.observe(ctx, step(3), true)).toBeDefined();
  336. expect(guard.finishTurn(ctx)?.stepCount).toBe(3);
  337. expect(guard.finishTurn(ctx)).toBeUndefined();
  338. expect(guard.observe(ctx, step(4), true)).toBeUndefined();
  339. expect(guard.finishTurn(otherSession)?.stepCount).toBe(1);
  340. expect(guard.finishTurn(otherTurn)?.stepCount).toBe(1);
  341. });
  342. it('uses the same projection and observations for live Shadow and offline replay', () => {
  343. const observations: RunawayGuardObservation[] = [];
  344. const guard = createRunawayGuard({ onSignal: (value) => { observations.push(value); } });
  345. const steps = [step(1, 'error'), step(2, 'error'), step(3, 'error')];
  346. for (const value of steps) expect(guard.observe(ctx, value, true)).toBeUndefined();
  347. const replay = replayRunawayGuardTrajectory({ ...ctx, steps });
  348. expect(observations).toEqual(replay.observations);
  349. expect(guard.finishTurn(ctx)).toEqual(replay.summary);
  350. });
  351. it('does not let malformed progress suppress mechanical observations', () => {
  352. const observations: RunawayGuardObservation[] = [];
  353. const guard = createRunawayGuard({ onSignal: (value) => { observations.push(value); } });
  354. for (let index = 1; index <= 2; index += 1) {
  355. guard.observe(ctx, { ...step(index), verifiedProgress: {} as never }, false);
  356. }
  357. expect(observations).toContainEqual(expect.objectContaining({
  358. signalKind: 'exact_action_repeat', occurrences: 2,
  359. }));
  360. });
  361. });
  362. describe('trusted task_output polling in the shared Guard', () => {
  363. it('counts same-task reads across interleaved tasks and pairs reverse-order results by call id', () => {
  364. const guard = taskOutputGuard();
  365. const readBoth = (batch: number) => guard.observe(
  366. ctx,
  367. taskOutputStep([
  368. { id: `a-${batch}`, taskId: 'task-a' },
  369. { id: `b-${batch}`, taskId: 'task-b' },
  370. ], { reverseResults: true }),
  371. true,
  372. );
  373. expect(readBoth(1)).toBeUndefined();
  374. expect(readBoth(2)).toBeUndefined();
  375. const reminder = readBoth(3);
  376. expect(reminder?.observation).toMatchObject({ signalKind: 'polling_repeat', occurrences: 3 });
  377. expect(reminder?.content).toBe(`<system-reminder>
  378. Three task_output reads for the same task have returned an unchanged status and output cursor. Avoid repeated polling; you will be notified automatically and this conversation will resume when the background task completes.
  379. This reminder applies only to the current Turn. Do not save or generalize it into Memory, Skills, or other persistent instructions.
  380. </system-reminder>`);
  381. });
  382. it('updates one task at a time inside a batch and rebuilds its baseline after changed output facts', () => {
  383. const guard = taskOutputGuard();
  384. expect(guard.observe(ctx, taskOutputStep([
  385. { id: 'same-1', taskId: 'task-a' },
  386. { id: 'same-2', taskId: 'task-a' },
  387. { id: 'same-3', taskId: 'task-a' },
  388. ], { reverseResults: true }), true)?.observation.signalKind).toBe('polling_repeat');
  389. const cursorGuard = taskOutputGuard();
  390. expect(cursorGuard.observe(ctx, taskOutputStep([{ id: 'cursor-1', taskId: 'task-a', nextOffset: 10 }]), true)).toBeUndefined();
  391. expect(cursorGuard.observe(ctx, taskOutputStep([{ id: 'cursor-2', taskId: 'task-a', nextOffset: 20 }]), true)).toBeUndefined();
  392. expect(cursorGuard.observe(ctx, taskOutputStep([{ id: 'cursor-3', taskId: 'task-a', nextOffset: 20 }]), true)).toBeUndefined();
  393. expect(cursorGuard.observe(ctx, taskOutputStep([{ id: 'cursor-4', taskId: 'task-a', nextOffset: 20 }]), true)?.observation.signalKind).toBe('polling_repeat');
  394. });
  395. it('keeps a qualified task through a text-only step', () => {
  396. const guard = taskOutputGuard();
  397. expect(guard.observe(ctx, taskOutputStep([{ id: 'text-1', taskId: 'task-a' }]), true)).toBeUndefined();
  398. expect(guard.observe(ctx, {
  399. message: {
  400. role: 'assistant',
  401. content: [{ type: 'text', text: 'I will wait for the task.' }],
  402. api: 'openai-completions', provider: 'test', model: 'test', stopReason: 'stop', timestamp: 0,
  403. usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
  404. } as never,
  405. toolResults: [],
  406. }, true)).toBeUndefined();
  407. expect(guard.observe(ctx, taskOutputStep([{ id: 'text-2', taskId: 'task-a' }]), true)).toBeUndefined();
  408. expect(guard.observe(ctx, taskOutputStep([{ id: 'text-3', taskId: 'task-a' }]), true)?.observation.signalKind).toBe('polling_repeat');
  409. });
  410. it('does not qualify distinct tasks or observations without trusted execution provenance', () => {
  411. const distinct = taskOutputGuard();
  412. for (const taskId of ['task-a', 'task-b', 'task-c']) {
  413. expect(distinct.observe(ctx, taskOutputStep([{ id: `${taskId}-first`, taskId }]), true)).toBeUndefined();
  414. }
  415. const untrusted = taskOutputGuard();
  416. for (let index = 1; index <= 3; index += 1) {
  417. expect(untrusted.observe(ctx, taskOutputStep([
  418. { id: `untrusted-${index}`, taskId: 'task-a', trusted: false },
  419. ]), true)).toBeUndefined();
  420. }
  421. });
  422. it('starts a new native baseline after an untrusted same-task observation interrupts the segment', () => {
  423. const guard = taskOutputGuard();
  424. expect(guard.observe(ctx, taskOutputStep([{ id: 'trusted-a-1', taskId: 'task-a' }]), true)).toBeUndefined();
  425. expect(guard.observe(ctx, taskOutputStep([
  426. { id: 'untrusted-a-2', taskId: 'task-a', trusted: false },
  427. { id: 'trusted-a-3', taskId: 'task-a' },
  428. ]), true)).toBeUndefined();
  429. expect(guard.observe(ctx, taskOutputStep([{ id: 'trusted-a-4', taskId: 'task-a' }]), true)).toBeUndefined();
  430. expect(guard.observe(ctx, taskOutputStep([{ id: 'trusted-a-5', taskId: 'task-a' }]), true)?.observation.signalKind).toBe('polling_repeat');
  431. });
  432. it('withdraws only the reset task candidate and retains another task candidate', () => {
  433. const sameTaskReset = taskOutputGuard();
  434. expect(sameTaskReset.observe(ctx, taskOutputStep([{ id: 'reset-a-1', taskId: 'task-a' }]), true)).toBeUndefined();
  435. expect(sameTaskReset.observe(ctx, taskOutputStep([{ id: 'reset-a-2', taskId: 'task-a' }]), true)).toBeUndefined();
  436. expect(sameTaskReset.observe(ctx, taskOutputStep([
  437. { id: 'reset-a-3', taskId: 'task-a' },
  438. { id: 'reset-a-terminal', taskId: 'task-a', status: 'completed' },
  439. ]), true)).toBeUndefined();
  440. expect(sameTaskReset.observe(ctx, taskOutputStep([{ id: 'reset-a-4', taskId: 'task-a' }]), true)).toBeUndefined();
  441. expect(sameTaskReset.observe(ctx, taskOutputStep([{ id: 'reset-a-5', taskId: 'task-a' }]), true)).toBeUndefined();
  442. expect(sameTaskReset.observe(ctx, taskOutputStep([{ id: 'reset-a-6', taskId: 'task-a' }]), true)?.observation.signalKind).toBe('polling_repeat');
  443. const otherTaskReset = taskOutputGuard();
  444. expect(otherTaskReset.observe(ctx, taskOutputStep([{ id: 'other-a-1', taskId: 'task-a' }]), true)).toBeUndefined();
  445. expect(otherTaskReset.observe(ctx, taskOutputStep([{ id: 'other-a-2', taskId: 'task-a' }]), true)).toBeUndefined();
  446. expect(otherTaskReset.observe(ctx, taskOutputStep([
  447. { id: 'other-a-3', taskId: 'task-a' },
  448. { id: 'other-b-stopping', taskId: 'task-b', status: 'stopping' },
  449. ]), true)?.observation.signalKind).toBe('polling_repeat');
  450. });
  451. it('withdraws a same-task candidate after new output but keeps it through another task’s output', () => {
  452. const sameTaskProgress = taskOutputGuard();
  453. expect(sameTaskProgress.observe(ctx, taskOutputStep([{ id: 'progress-a-1', taskId: 'task-a' }]), true)).toBeUndefined();
  454. expect(sameTaskProgress.observe(ctx, taskOutputStep([{ id: 'progress-a-2', taskId: 'task-a' }]), true)).toBeUndefined();
  455. expect(sameTaskProgress.observe(ctx, taskOutputStep([
  456. { id: 'progress-a-3', taskId: 'task-a' },
  457. { id: 'progress-a-4', taskId: 'task-a', nextOffset: 10 },
  458. ]), true)).toBeUndefined();
  459. expect(sameTaskProgress.observe(ctx, taskOutputStep([{ id: 'progress-a-5', taskId: 'task-a', nextOffset: 10 }]), true)).toBeUndefined();
  460. expect(sameTaskProgress.observe(ctx, taskOutputStep([{ id: 'progress-a-6', taskId: 'task-a', nextOffset: 10 }]), true)?.observation.signalKind).toBe('polling_repeat');
  461. const otherTaskProgress = taskOutputGuard();
  462. for (const batch of [1, 2]) {
  463. expect(otherTaskProgress.observe(ctx, taskOutputStep([
  464. { id: `other-progress-a-${batch}`, taskId: 'task-a' },
  465. { id: `other-progress-b-${batch}`, taskId: 'task-b' },
  466. ]), true)).toBeUndefined();
  467. }
  468. expect(otherTaskProgress.observe(ctx, taskOutputStep([
  469. { id: 'other-progress-a-3', taskId: 'task-a' },
  470. { id: 'other-progress-b-3', taskId: 'task-b', nextOffset: 10 },
  471. ]), true)?.observation.signalKind).toBe('polling_repeat');
  472. });
  473. it('lets a known error without a receipt reset only its own task', () => {
  474. const guard = taskOutputGuard();
  475. expect(guard.observe(ctx, taskOutputStep([{ id: 'error-a-1', taskId: 'task-a' }]), true)).toBeUndefined();
  476. expect(guard.observe(ctx, taskOutputStep([{ id: 'error-a-2', taskId: 'task-a' }]), true)).toBeUndefined();
  477. expect(guard.observe(ctx, taskOutputStep([
  478. { id: 'error-a-3', taskId: 'task-a' },
  479. { id: 'error-b', taskId: 'task-b', isError: true, omitDetails: true },
  480. ]), true)?.observation.signalKind).toBe('polling_repeat');
  481. const conflict = taskOutputGuard();
  482. expect(conflict.observe(ctx, taskOutputStep([{ id: 'conflict-a-1', taskId: 'task-a' }]), true)).toBeUndefined();
  483. expect(conflict.observe(ctx, taskOutputStep([{ id: 'conflict-a-2', taskId: 'task-a' }]), true)).toBeUndefined();
  484. expect(conflict.observe(ctx, taskOutputStep([
  485. { id: 'conflict-a-3', taskId: 'task-a' },
  486. { id: 'conflict-b-error', taskId: 'task-b', isError: true, resultTaskId: 'foreign-task' },
  487. ]), true)).toBeUndefined();
  488. expect(conflict.observe(ctx, taskOutputStep([{ id: 'conflict-a-4', taskId: 'task-a' }]), true)).toBeUndefined();
  489. expect(conflict.observe(ctx, taskOutputStep([{ id: 'conflict-a-5', taskId: 'task-a' }]), true)).toBeUndefined();
  490. expect(conflict.observe(ctx, taskOutputStep([{ id: 'conflict-a-6', taskId: 'task-a' }]), true)?.observation.signalKind).toBe('polling_repeat');
  491. });
  492. it('breaks a qualified segment for another tool and resets a permission-blocked native call', () => {
  493. const interrupted = taskOutputGuard();
  494. expect(interrupted.observe(ctx, taskOutputStep([{ id: 'interrupt-1', taskId: 'task-a' }]), true)).toBeUndefined();
  495. expect(interrupted.observe(ctx, taskOutputStep([{ id: 'interrupt-2', taskId: 'task-a' }]), true)).toBeUndefined();
  496. expect(interrupted.observe(ctx, taskOutputStep(
  497. [{ id: 'interrupt-3', taskId: 'task-a' }],
  498. { otherCalls: [{ id: 'bash', name: 'bash', arguments: { command: 'date' } }] },
  499. ), true)).toBeUndefined();
  500. expect(interrupted.observe(ctx, taskOutputStep([{ id: 'interrupt-4', taskId: 'task-a' }]), true)).toBeUndefined();
  501. expect(interrupted.observe(ctx, taskOutputStep([{ id: 'interrupt-5', taskId: 'task-a' }]), true)).toBeUndefined();
  502. expect(interrupted.observe(ctx, taskOutputStep([{ id: 'interrupt-6', taskId: 'task-a' }]), true)?.observation.signalKind).toBe('polling_repeat');
  503. const blocked = taskOutputGuard();
  504. expect(blocked.observe(ctx, taskOutputStep([{ id: 'blocked-1', taskId: 'task-a' }]), true)).toBeUndefined();
  505. expect(blocked.observe(ctx, taskOutputStep([{ id: 'blocked-2', taskId: 'task-a' }]), true)).toBeUndefined();
  506. expect(blocked.observe(ctx, taskOutputStep(
  507. [{ id: 'blocked-3', taskId: 'task-a' }],
  508. { blockedToolCallIds: ['blocked-3'] },
  509. ), true)).toBeUndefined();
  510. expect(blocked.observe(ctx, taskOutputStep([{ id: 'blocked-4', taskId: 'task-a' }]), true)).toBeUndefined();
  511. expect(blocked.observe(ctx, taskOutputStep([{ id: 'blocked-5', taskId: 'task-a' }]), true)).toBeUndefined();
  512. expect(blocked.observe(ctx, taskOutputStep([{ id: 'blocked-6', taskId: 'task-a' }]), true)?.observation.signalKind).toBe('polling_repeat');
  513. });
  514. it('applies positive host progress only to the matching trusted task and preserves old detect progress', () => {
  515. const vetoed = taskOutputGuard();
  516. expect(vetoed.observe(ctx, taskOutputStep([{ id: 'veto-a-1', taskId: 'task-a' }]), true)).toBeUndefined();
  517. expect(vetoed.observe(ctx, taskOutputStep([{ id: 'veto-a-2', taskId: 'task-a' }]), true)).toBeUndefined();
  518. expect(vetoed.observe(ctx, taskOutputStep(
  519. [{ id: 'veto-a-3', taskId: 'task-a' }],
  520. { verifiedProgressCallIds: ['veto-a-3'] },
  521. ), true)).toBeUndefined();
  522. const observations: RunawayGuardObservation[] = [];
  523. const mixed = createRunawayGuard({
  524. onSignal: (value) => { observations.push(value); },
  525. toolPolicies: {
  526. task_output: taskOutputPollingPolicy,
  527. inspect: {
  528. kind: 'detect',
  529. projectProgress: () => ({ loopKey: 'workspace', progressKey: 'unchanged' }),
  530. },
  531. watch: { kind: 'exempt' },
  532. },
  533. });
  534. const inspectStep = (id: string, includePolling: boolean) => ({
  535. message: {
  536. role: 'assistant' as const,
  537. content: [
  538. { type: 'toolCall' as const, id, name: 'inspect', arguments: { revision: 1 } },
  539. ...(includePolling
  540. ? [{ type: 'toolCall' as const, id: `${id}-poll`, name: 'task_output', arguments: { task_id: 'task-a' } }]
  541. : []),
  542. { type: 'toolCall' as const, id: `${id}-watch`, name: 'watch', arguments: {} },
  543. ],
  544. api: 'openai-completions', provider: 'test', model: 'test', stopReason: 'toolUse', timestamp: 0,
  545. usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
  546. } as never,
  547. toolResults: [],
  548. ...(includePolling ? {
  549. trustedToolProvenance: [{ toolCallId: `${id}-poll`, toolName: 'task_output', source: 'builtin' as const }],
  550. } : {}),
  551. });
  552. mixed.observe(ctx, inspectStep('inspect-1', false), false);
  553. mixed.observe(ctx, inspectStep('inspect-2', true), false);
  554. expect(observations).toContainEqual(expect.objectContaining({
  555. signalKind: 'unchanged_progress_repeat', occurrences: 2,
  556. }));
  557. });
  558. it('uses the existing detector priority and one-shot when both signals qualify in one batch', () => {
  559. const guard = createRunawayGuard({
  560. remindAfterOccurrences: 3,
  561. toolPolicies: {
  562. inspect: {
  563. kind: 'detect',
  564. projectProgress: () => ({ loopKey: 'workspace', progressKey: 'unchanged' }),
  565. },
  566. task_output: taskOutputPollingPolicy,
  567. },
  568. });
  569. const inspectStep = (id: string) => ({
  570. message: {
  571. role: 'assistant' as const,
  572. content: [{ type: 'toolCall' as const, id, name: 'inspect', arguments: { target: 'workspace' } }],
  573. api: 'openai-completions', provider: 'test', model: 'test', stopReason: 'toolUse', timestamp: 0,
  574. usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
  575. } as never,
  576. toolResults: [],
  577. });
  578. expect(guard.observe(ctx, inspectStep('inspect-1'), true)).toBeUndefined();
  579. expect(guard.observe(ctx, inspectStep('inspect-2'), true)).toBeUndefined();
  580. const calls = [
  581. { type: 'toolCall' as const, id: 'inspect-3', name: 'inspect', arguments: { target: 'workspace' } },
  582. ...['poll-1', 'poll-2', 'poll-3'].map((id) => ({
  583. type: 'toolCall' as const, id, name: 'task_output', arguments: { task_id: 'task-a' },
  584. })),
  585. ];
  586. const reminder = guard.observe(ctx, {
  587. message: {
  588. role: 'assistant',
  589. content: calls,
  590. api: 'openai-completions', provider: 'test', model: 'test', stopReason: 'toolUse', timestamp: 0,
  591. usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
  592. } as never,
  593. toolResults: ['poll-1', 'poll-2', 'poll-3'].map((id) => ({
  594. role: 'toolResult' as const,
  595. toolCallId: id,
  596. toolName: 'task_output',
  597. content: [],
  598. details: { task_id: 'task-a', status: 'running', next_offset: 0 },
  599. isError: false,
  600. timestamp: 0,
  601. })) as never,
  602. trustedToolProvenance: ['poll-1', 'poll-2', 'poll-3'].map((toolCallId) => ({
  603. toolCallId, toolName: 'task_output', source: 'builtin' as const,
  604. })),
  605. }, true);
  606. expect(reminder?.observation.signalKind).toBe('unchanged_progress_repeat');
  607. expect(guard.observe(ctx, taskOutputStep([{ id: 'after-priority', taskId: 'task-a' }]), true)).toBeUndefined();
  608. });
  609. it('does not let host-verified polling fields opt into a task_output reminder', () => {
  610. const guard = createRunawayGuard({
  611. remindAfterOccurrences: 3,
  612. toolPolicies: { task_output: { kind: 'polling' } },
  613. });
  614. for (const id of ['host-1', 'host-2', 'host-3']) {
  615. const value = taskOutputStep([{ id, taskId: 'task-a', trusted: false }]);
  616. expect(guard.observe(ctx, {
  617. ...value,
  618. verifiedProgress: [{
  619. toolCallId: id,
  620. loopKey: { taskId: 'task-a' },
  621. progressKey: { status: 'running', nextOffset: 0 },
  622. polling: { mode: 'continuous', reminderEligible: true },
  623. }],
  624. }, true)).toBeUndefined();
  625. }
  626. expect(guard.finishTurn(ctx)?.signals.polling_repeat.maxOccurrences).toBe(3);
  627. });
  628. });