A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
preserve user priority when moving queued input across lanes (#3637)
Sebastian Müller474fe5562d48
diff --git a/crates/pa-daemon/src/queue_commands.rs b/crates/pa-daemon/src/queue_commands.rsindex 6762bf6bda..3cae2d3dfd 100644--- a/crates/pa-daemon/src/queue_commands.rs+++ b/crates/pa-daemon/src/queue_commands.rs@@ -91,9 +91,9 @@ impl Worker {),};if status == "applied" {- // A replace onto another lane moves the item to the back- // of the target lane. The non-overlapping direction pairs- // only - `target != lane` holds for every reached arm.+ // A replace onto another lane is an arrival there: the item+ // keeps its priority and enqueues by it. The non-overlapping+ // direction pairs only - `target != lane` holds for every reached arm.if mutation_type == "replace" {if let Some(target) =wire_lane(mutation.get("lane")).filter(|target| *target != lane)@@ -104,10 +104,11 @@ impl Worker {_ => None,};if let Some(item) = item {- match target {- Lane::Steering => core.steering.push_back(item),- Lane::FollowUp => core.follow_up.push_back(item),- }+ let target_lane = match target {+ Lane::Steering => &mut core.steering,+ Lane::FollowUp => &mut core.follow_up,+ };+ crate::worker::enqueue_priority(target_lane, item);}}}@@ -676,4 +677,57 @@ mod tests {.map(|item| item.message.clone());assert_eq!(remaining.as_deref(), Some("plain prompt"));}++ /// A cross-lane replace is an arrival in the target lane: the edited user+ /// item lands after earlier user items and before parked agent messages.+ #[tokio::test]+ async fn cross_lane_replace_lands_before_parked_agent_messages() {+ for (source, target, source_command, target_command, delivery_mode) in [+ ("followUp", "steering", "follow_up", "steer", "steer"),+ ("steering", "followUp", "steer", "follow_up", "follow_up"),+ ] {+ let worker = created_worker().await;+ worker.core.lock().unwrap().busy = true;+ for (command, payload) in [+ (target_command, json!({ "message": "earlier" })),+ (+ "worker_deliver_message",+ json!({+ "targetActiveSessionId": "queue-session",+ "message": "the research is done",+ "sender": { "activeSessionId": "source-session" },+ "deliveryMode": delivery_mode,+ }),+ ),+ (source_command, json!({ "message": "draft" })),+ ] {+ let admitted = worker.dispatch(command, &payload).await;+ assert!(admitted.success, "{command}: {admitted:?}");+ }+ let replaced = worker+ .dispatch(+ "mutate_queued_message",+ &json!({+ "lane": source,+ "index": 0,+ "expectedText": "draft",+ "mutation": { "type": "replace", "text": "edited", "lane": target },+ }),+ )+ .await;+ assert_eq!(replaced.data, Some(json!({ "status": "applied" })));+ let queue = worker.dispatch("get_queue", &json!({})).await;+ let data = queue.data.expect("queue data");+ assert_eq!(data[source], json!([]), "{source} -> {target}");+ assert_eq!(+ data[target],+ json!([+ "earlier",+ "edited",+ "Agent message received: the research is done"+ ]),+ "{source} -> {target}"+ );+ }+ }}diff --git a/crates/pa-daemon/src/worker/agent_message_tests.rs b/crates/pa-daemon/src/worker/agent_message_tests.rsindex 778882c59c..e8afdb6943 100644--- a/crates/pa-daemon/src/worker/agent_message_tests.rs+++ b/crates/pa-daemon/src/worker/agent_message_tests.rs@@ -221,6 +221,56 @@ async fn deliver_message_while_busy_queues() {);}+/// Agent-message deliveries admit as background work: later user input jumps+/// them, FIFO behind earlier user input, on both lanes.+#[tokio::test]+async fn user_input_jumps_parked_agent_message_deliveries() {+ for (command, delivery_mode, lane) in [+ ("steer", "steer", "steering"),+ ("follow_up", "follow_up", "followUp"),+ ] {+ let worker = created_worker().await;+ worker.core.lock().unwrap().busy = true;+ for (text, user) in [+ ("first agent", false),+ ("second agent", false),+ ("first user", true),+ ("second user", true),+ ] {+ let response = if user {+ worker.dispatch(command, &json!({ "message": text })).await+ } else {+ worker+ .dispatch(+ "worker_deliver_message",+ &json!({+ "targetActiveSessionId": "target-session",+ "message": text,+ "sender": { "activeSessionId": "source-session" },+ "deliveryMode": delivery_mode,+ }),+ )+ .await+ };+ assert!(response.success, "{text}: {response:?}");+ if !user {+ assert_eq!(response.data.expect("receipt")["deliveryStatus"], "queued");+ }+ }+ let queue = worker.dispatch("get_queue", &json!({})).await;+ assert_eq!(+ queue.data.expect("queue data")[lane],+ json!([+ "first user",+ "second user",+ "Agent message received: first agent",+ "Agent message received: second agent"+ ]),+ "{lane}"+ );+ }+}+/// The pending-capacity guard fails with the TS error string.#[tokio::test]async fn deliver_message_respects_the_pending_capacity() {diff --git a/scripts/review_queue_priority_parity.py b/scripts/review_queue_priority_parity.pynew file mode 100644index 0000000000..d78e3233ae--- /dev/null+++ b/scripts/review_queue_priority_parity.py@@ -0,0 +1,141 @@+#!/usr/bin/env python3+"""Actual protocol-7 daemon comparison for a follow-up edited into steering.++Pinned TS appends a re-laned item; Rust preserves existing admission priority.+The measured intentional delta is retained, not normalized into equality. The+reverse move into a plain-user lane is a shared baseline. No model is external.+"""+import argparse+import json+import os+from pathlib import Path+import subprocess+import sys+import tempfile+import threading++from review_agent_bounce_parity import Client, Provider+from review_draft_disconnect_parity import digest, env_for, TS_ARCHIVE_SHA256+from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish++EARLIER, DRAFT, EDITED = 'QUEUE_PRIORITY_EARLIER', 'QUEUE_PRIORITY_DRAFT', 'QUEUE_PRIORITY_EDITED'+AGENT = 'QUEUE_PRIORITY_AGENT'+++def check_order(kind, queue, agent_preview):+ expected = [EARLIER, agent_preview, EDITED] if kind == 'ts' else [EARLIER, EDITED, agent_preview]+ assert queue == {'steering': expected, 'followUp': []}, queue+++def observe(binary, kind, root, observed):+ env = env_for(root, kind)+ env[TAG] = str(root)+ provider = Provider()+ threading.Thread(target=provider.serve_forever, daemon=True).start()+ models = {'providers': {'parity-local': {'api': 'openai-completions', 'apiKey': 'fixture-only',+ 'baseUrl': f'http://127.0.0.1:{provider.server_port}/v1', 'models': [{+ 'id': 'parity-1', 'name': 'Parity 1', 'reasoning': False, 'contextWindow': 128000, 'maxTokens': 4096}]}}}+ (root / 'agent/models.json').write_text(json.dumps(models))+ path = root / 'd.sock'+ scope = OwnedProcesses(binary, root, path)+ daemon = control = receiver = None+ log = open(root / 'daemon.log', 'wb')+ try:+ command = [str(binary), '--mode', 'daemon', '--daemon-socket', str(path)]+ daemon = subprocess.Popen(command, cwd=root, env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)+ scope.register(daemon, command)+ control = Client(path, daemon)+ receiver = Client(path, daemon)+ config = {'cwd': str(root), 'agentDir': str(root / 'agent'), 'provider': 'parity-local',+ 'model': 'parity-1', 'noExtensions': True, 'noSkills': True, 'noTools': True,+ 'noContextFiles': True, 'telemetryDisabled': True}+ active = []+ for client, name in [(control, 'queue-source'), (receiver, 'queue-target')]:+ row = client.call('create', name=name, config=config)+ ident = row.get('activeSessionId') or row.get('id')+ assert ident, row+ active.append(ident)+ client.call('attach', activeSessionId=ident)+ source, target = active+ receiver.call('prompt', activeSessionId=target, message='QUEUE_PRIORITY_HOLD')+ provider.wait_for('QUEUE_PRIORITY_HOLD')+ receiver.call('steer', activeSessionId=target, message=EARLIER)+ delivered = control.call('send_message', targetActiveSessionId=target,+ fromActiveSessionId=source, message=AGENT)+ observed['delivery_receipt'] = delivered+ assert delivered['deliveryStatus'] == 'queued', delivered+ receiver.call('follow_up', activeSessionId=target, message=DRAFT)+ before = receiver.call('get_queue', activeSessionId=target)+ observed['before'] = before+ assert before['followUp'] == [DRAFT] and len(before['steering']) == 2, before+ agent_preview = before['steering'][1]+ assert agent_preview == 'Agent message received: ' + AGENT, before+ assert before['steering'][0] == EARLIER, before+ mutation = {'lane': 'followUp', 'index': 0, 'expectedText': DRAFT,+ 'mutation': {'type': 'replace', 'text': EDITED, 'lane': 'steering'}}+ observed['mutation'] = mutation+ response = receiver.call('mutate_queued_message', activeSessionId=target, **mutation)+ assert response == {'status': 'applied'}, response+ after = receiver.call('get_queue', activeSessionId=target)+ observed['after'] = after+ check_order(kind, after, agent_preview)+ # Reverse direction retains existing users; internal target-lane admission+ # in BOTH directions remains covered by the worker integration regression.+ receiver.call('follow_up', activeSessionId=target, message='QUEUE_REVERSE_EARLIER')+ index = after['steering'].index(EDITED)+ reverse = {'lane': 'steering', 'index': index, 'expectedText': EDITED,+ 'mutation': {'type': 'replace', 'text': 'QUEUE_REVERSE_EDITED', 'lane': 'followUp'}}+ observed['reverse_mutation'] = reverse+ assert receiver.call('mutate_queued_message', activeSessionId=target, **reverse) == {'status': 'applied'}+ reverse_queue = receiver.call('get_queue', activeSessionId=target)+ observed['reverse_after'] = reverse_queue+ assert reverse_queue == {'steering': [EARLIER, agent_preview],+ 'followUp': ['QUEUE_REVERSE_EARLIER', 'QUEUE_REVERSE_EDITED']}, reverse_queue+ assert not provider.release.is_set(), 'held turn was released before observations'+ observed['behavior_verified'] = True+ finally:+ observed['provider_requests'] = list(provider.requests)+ observed['wire'] = {'source': list(control.wire) if control else [], 'receiver': list(receiver.wire) if receiver else []}+ if receiver:+ receiver.close()+ provider.release.set()+ finish(scope, control, daemon, observed)+ log.close()+ observed['daemon_log'] = (root / 'daemon.log').read_text(errors='replace')[-10000:]+ provider.shutdown()+ provider.server_close()+ assert observed['cleanup_verified'], observed+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--receipt', required=True, type=Path)+ args = parser.parse_args()+ receipt = {'verified': False, 'scope': __doc__, 'runs': {},+ 'not_verified': ['TUI key/render path', 'internal follow-up target lane (worker integration test covers it)',+ 'forced Esc batch execution', 'restart recovery', 'full wire byte equality (IDs/timestamps differ)']}+ try:+ assert sys.platform == 'linux', 'hosted Linux only'+ assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256, 'reference archive mismatch'+ receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256+ with tempfile.TemporaryDirectory(prefix='pa-qpriority-', dir='/tmp') as folder:+ for kind in ('ts', 'rust'):+ binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()+ observed = receipt['runs'][kind] = {'binary_sha256': digest(binary)}+ try:+ observe(binary, kind, Path(folder) / kind, observed)+ except Exception as error:+ observed['error'] = str(error)+ assert all(run.get('behavior_verified') and run.get('cleanup_verified') and 'error' not in run+ for run in receipt['runs'].values()), 'actual daemon observation failed'+ receipt['verified'] = True+ except Exception as error:+ receipt['error'] = str(error)+ args.receipt.parent.mkdir(parents=True, exist_ok=True)+ args.receipt.write_text(json.dumps(receipt, ensure_ascii=False, indent=2))+ print(json.dumps({'verified': receipt['verified'], 'error': receipt.get('error')}))+ return 0 if receipt['verified'] else 1+++if __name__ == '__main__':+ sys.exit(main())diff --git a/scripts/test_review_queue_priority_parity.py b/scripts/test_review_queue_priority_parity.pynew file mode 100644index 0000000000..3eabdc5f00--- /dev/null+++ b/scripts/test_review_queue_priority_parity.py@@ -0,0 +1,27 @@+import unittest+from review_queue_priority_parity import check_order, EARLIER, EDITED, AGENT+++class QueuePriorityGuardTest(unittest.TestCase):+ def test_records_the_intended_delta_instead_of_accepting_both_orders(self):+ ts = {'steering': [EARLIER, AGENT, EDITED], 'followUp': []}+ rust = {'steering': [EARLIER, EDITED, AGENT], 'followUp': []}+ check_order('ts', ts, AGENT)+ check_order('rust', rust, AGENT)+ with self.assertRaises(AssertionError):+ check_order('rust', ts, AGENT)+ with self.assertRaises(AssertionError):+ check_order('ts', rust, AGENT)++ def test_does_not_ignore_missing_duplicate_or_wrong_lane_items(self):+ for queue in [+ {'steering': [EDITED, AGENT], 'followUp': []},+ {'steering': [EARLIER, EDITED, AGENT, AGENT], 'followUp': []},+ {'steering': [EARLIER, EDITED, AGENT], 'followUp': [EDITED]},+ ]:+ with self.assertRaises(AssertionError):+ check_order('rust', queue, AGENT)+++if __name__ == '__main__':+ unittest.main()