| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183 |
- """No-network regressions: inputs and old failed queues never become new outputs."""
- import contextlib
- import copy
- import hashlib
- import importlib.util
- import io
- import json
- import os
- from pathlib import Path
- import sys
- import tempfile
- import time
- import unittest
- from unittest.mock import patch
- ROOT = Path(__file__).resolve().parents[2]
- RUNTIME = ROOT / 'cloud/onboarding/runtime'
- def load(name, file, package=False):
- spec = importlib.util.spec_from_file_location(name, file, submodule_search_locations=[str(file.parent)] if package else None)
- module = importlib.util.module_from_spec(spec)
- if package:
- sys.modules[name] = module
- spec.loader.exec_module(module)
- return module
- class DeliveryScopeTests(unittest.TestCase):
- def setUp(self):
- self.m = load('delivery_scope_hook', RUNTIME / 'scripts/fmode-deliverable-hook.py')
- self.m.log = lambda text: None
- self.now = time.time()
- def test_user_input_directory_is_denied_before_marked_extension(self):
- # Normalize using the runtime's OS rather than constructing actual /opt/data files.
- path = os.path.abspath('/opt/data/work/uploads/original/report.md')
- self.m.STATE_DIR_DENY = (os.path.abspath('/opt/data/work/uploads').replace('\\', '/') + '/',)
- with patch.object(self.m.os.path, 'abspath', side_effect=lambda p: str(p).replace('\\', '/')):
- self.assertFalse(self.m.classify(path.replace('\\', '/'), 123)[0])
- def test_old_tagged_and_untagged_queue_cannot_be_reclaimed_by_new_turn(self):
- self.assertFalse(self.m._queued_in_round({'turn_id': 'old', 'ts': self.now}, 'new'))
- self.assertFalse(self.m._queued_in_round({'ts': self.now - 60}, 'new'))
- self.assertFalse(self.m._queued_in_round({'ts': self.now}, 'new'))
- self.assertFalse(self.m._queued_in_round({'ts': self.now}, ''))
- self.assertTrue(self.m._queued_in_round({'turn_id': 'new', 'ts': self.now}, 'new'))
- def test_plain_text_new_turn_preserves_failed_queue_without_uploading(self):
- state = {'queued': [{'path': '/kept/report.md', 'turn_id': 'old', 'ts': self.now - 30}], 'pushed': []}
- original = copy.deepcopy(state)
- self.m.load_round = lambda sid: {'turn_id': 'new', 'start_ts': self.now}
- self.m.load_state = lambda sid: state
- self.m._denied = lambda path: None
- self.m.upload_and_register = lambda *args: self.fail('old failed queue must not cause network upload')
- self.m.save_state = lambda *args: self.fail('old failed queue must remain unchanged')
- out = io.StringIO()
- with patch.object(self.m.os.path, 'isfile', return_value=True), contextlib.redirect_stdout(out):
- self.m.handle_transform_llm_output({'session_id': 'fixture', 'response_text': 'ONLY_NEW_REPLY'})
- self.assertEqual(json.loads(out.getvalue())['response_text'], 'ONLY_NEW_REPLY')
- self.assertEqual(state, original)
- def test_direct_tool_candidate_records_current_turn(self):
- state = {'queued': [{'path': '/kept/report.md', 'turn_id': 'old', 'ts': self.now - 60}], 'pushed': []}
- self.m.load_round = lambda sid: {'turn_id': 'current', 'start_ts': self.now}
- self.m.load_state = lambda sid: state
- self.m._spawn_process_notice = lambda *args: None
- self.m.sweep_new_files = lambda *args: []
- self.m.paths_from_tool = lambda *args: ['/kept/report.md']
- self.m.classify = lambda *args: (True, 'fixture')
- self.m.save_state = lambda *args: None
- with patch.object(self.m.os.path, 'isfile', return_value=True), patch.object(self.m.os.path, 'getsize', return_value=12):
- self.m.handle_post_tool_call({'session_id': 'fixture', 'tool_name': 'write_file', 'tool_input': {}})
- self.assertEqual(state['queued'][0]['turn_id'], 'old')
- self.assertEqual(state['queued'][1]['turn_id'], 'current')
- def test_same_turn_failed_output_can_still_retry(self):
- old_failed = {'path': '/kept/report.md', 'turn_id': 'old', 'ts': self.now - 60}
- state = {'queued': [old_failed, {'path': '/kept/report.md', 'turn_id': 'current', 'ts': self.now}],
- 'pushed': [{'path': '/kept/report.md', 'turn_id': 'older-success', 'url': 'https://s3.fmode.cn/deliverables/old.md'}]}
- self.m.load_round = lambda sid: {'turn_id': 'current', 'start_ts': self.now}
- self.m.load_state = lambda sid: state
- self.m._denied = lambda path: None
- self.m.save_state = lambda *args: None
- self.m.LEDGER = Path(tempfile.gettempdir()) / 'nonexistent-delivery-scope-dir' / 'ledger.jsonl'
- calls = []
- def upload(items, *args):
- calls.append(items)
- return [{'path': '/kept/report.md', 'ok': True, 'url': 'https://s3.fmode.cn/deliverables/result.md', 'hub': {'ok': True}}]
- self.m.upload_and_register = upload
- # Suppress optional ledger output; no test artifacts escape the fixture.
- with tempfile.TemporaryDirectory() as directory:
- self.m.LEDGER = Path(directory) / 'ledger.jsonl'
- with patch.object(self.m.os.path, 'isfile', return_value=True), contextlib.redirect_stdout(io.StringIO()):
- self.m.handle_transform_llm_output({'session_id': 'fixture', 'response_text': 'done'})
- self.assertEqual(len(calls), 1)
- self.assertEqual(state['pushed'][-1]['turn_id'], 'current')
- self.assertEqual(state['queued'], [old_failed])
- def test_already_pushed_current_round_does_not_clear_old_failed_queue(self):
- old_failed = {'path': '/kept/old-failure.md', 'turn_id': 'old'}
- state = {'queued': [old_failed, {'path': '/kept/done.md', 'turn_id': 'now'}],
- 'pushed': [{'path': '/kept/done.md', 'url': 'https://s3.fmode.cn/deliverables/done.md', 'turn_id': 'now'}]}
- self.m.load_round = lambda sid: {'turn_id': 'now'}
- self.m.load_state = lambda sid: state
- self.m.save_state = lambda *args: None
- self.m._denied = lambda path: None
- self.m.upload_and_register = lambda *args: self.fail('current completed output cannot upload again')
- self.m._pushed_current_paths = lambda *args: {'/kept/done.md'}
- with patch.object(self.m.os.path, 'isfile', return_value=True), contextlib.redirect_stdout(io.StringIO()):
- self.m.handle_transform_llm_output({'session_id': 'fixture', 'response_text': 'done'})
- self.assertEqual(state['queued'], [old_failed])
- def test_current_round_path_skip_requires_verified_unchanged_bytes(self):
- with tempfile.TemporaryDirectory() as directory:
- file = Path(directory) / 'report.md'
- file.write_bytes(b'first version')
- state = {'pushed': [{'path': str(file), 'turn_id': 'now', 'url': 'https://s3.fmode.cn/deliverables/report.md', 'sha256': hashlib.sha256(file.read_bytes()).hexdigest()}]}
- self.assertEqual(self.m._pushed_current_paths(state, 'now'), {str(file)})
- file.write_bytes(b'new version')
- self.assertEqual(self.m._pushed_current_paths(state, 'now'), set())
- self.assertEqual(self.m._pushed_current_paths(state, 'different-turn'), set())
- def test_poisoned_current_pushed_input_url_cannot_suppress_real_output(self):
- with tempfile.TemporaryDirectory() as directory:
- file = Path(directory) / 'report.md'
- file.write_bytes(b'actual result')
- bad_url = 'https://s3.fmode.cn/user/owner/chat/report.md'
- good_url = 'https://s3.fmode.cn/deliverables/report.md'
- state = {'queued': [{'path': str(file), 'turn_id': 'now'}], 'pushed': [
- {'path': str(file), 'turn_id': 'now', 'url': bad_url, 'sha256': hashlib.sha256(file.read_bytes()).hexdigest()}]}
- self.m.load_round = lambda sid: {'turn_id': 'now'}
- self.m.load_state = lambda sid: state
- self.m.save_state = lambda *args: None
- self.m.LEDGER = Path(directory) / 'ledger.jsonl'
- calls = []
- def upload(items, *args):
- calls.append(items)
- return [{'path': str(file), 'ok': True, 'url': good_url, 'hub': {'ok': True}, 'sha256': hashlib.sha256(file.read_bytes()).hexdigest()}]
- self.m.upload_and_register = upload
- out = io.StringIO()
- with contextlib.redirect_stdout(out):
- self.m.handle_transform_llm_output({'session_id': 'fixture', 'response_text': 'done ' + bad_url})
- text = json.loads(out.getvalue())['response_text']
- self.assertEqual(len(calls), 1)
- self.assertIn(good_url, text)
- self.assertNotIn(bad_url, text)
- def test_user_upload_urls_never_qualify_for_output_reuse(self):
- self.assertTrue(self.m._user_upload_url('https://s3.fmode.cn/user/owner/chat/202611/input.md'))
- self.assertTrue(self.m._user_upload_url('https://file-cloud.fmode.cn/user/owner/chat/input.md'))
- self.assertFalse(self.m._user_upload_url('https://s3.fmode.cn/deliverables/agent/result.md'))
- self.assertFalse(self.m._user_upload_url('https://s3.fmode.cn/user/owner/avatar/picture.png'))
- class InjectionScopeTests(unittest.TestCase):
- def setUp(self):
- self.m = load('delivery_scope_plugin', RUNTIME / 'plugins/plugin-deliverable-inject/__init__.py', True)
- self.addCleanup(lambda: [sys.modules.pop(name, None) for name in list(sys.modules)
- if name == 'delivery_scope_plugin' or name.startswith('delivery_scope_plugin.')])
- def test_old_bad_pushed_inputs_are_not_injected_even_when_turn_matches(self):
- state = {'pushed': [
- {'path': '/opt/data/work/uploads/input.md', 'url': 'https://s3.fmode.cn/shared.md', 'turn_id': 'now'},
- {'path': '/opt/data/work/report.md', 'url': 'https://s3.fmode.cn/user/owner/chat/202611/report.md', 'turn_id': 'now'},
- {'path': '/opt/data/work/deliverables/report.md', 'url': 'https://s3.fmode.cn/deliverables/result.md', 'turn_id': 'now'},
- ]}
- self.assertEqual(self.m._collect_urls(state, 'now'), ['https://s3.fmode.cn/deliverables/result.md'])
- self.assertEqual(self.m._collect_pushed_paths(state, 'now'), ['/opt/data/work/deliverables/report.md'])
- self.assertIsNone(self.m._find_pushed_url('input.md', state['pushed'], 'now'))
- def test_plain_reply_does_not_gain_links_from_legacy_poisoned_state(self):
- self.m._load_state = lambda sid: {'pushed': [{'path': '/opt/data/work/uploads/input.txt', 'url': 'https://s3.fmode.cn/user/owner/chat/input.txt', 'turn_id': 'current'}]}
- result = self.m._on_transform_llm_output(response_text='ONLY_CURRENT_REPLY', session_id='fixture', turn_id='current')
- self.assertIn(result, (None, 'ONLY_CURRENT_REPLY'))
- def test_legacy_output_without_turn_tag_cannot_leak_into_new_reply(self):
- record = {'path': '/opt/data/work/deliverables/old.md', 'url': 'https://s3.fmode.cn/deliverables/old.md', 'ts': time.time()}
- self.assertEqual(self.m._collect_urls({'pushed': [record]}, 'new'), [])
- if __name__ == '__main__':
- unittest.main()
|