1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! `impl ExecutionService for AppService` — thin delegation to [`SessionRegistryV2`].
//!
//! All six verbs (`spawn`, `state`, `resume`, `cancel`, `observe`, `await_terminal`)
//! delegate directly to `self.execution_registry` with no additional logic.
//!
//! # Crux constraints honoured
//!
//! - **R1 (Wire-concept exclusion)**: This file imports nothing from `rmcp`, contains
//! no `progressToken`, `_meta`, `notifications/`, or `mcp_`-prefixed identifiers.
//! - **R2 (Cooperative cancellation)**: `cancel` calls
//! `execution_registry.cancel(id, reason)` only; no `JoinHandle::abort()` or
//! process-kill path exists in this file.
//! - **R3 (Sink-free broadcast fan-out)**: `observe` is a sync `fn` that delegates
//! to `execution_registry.observe(id)`. Multi-subscriber behaviour is verified by
//! `observe_multi_subscriber_fan_out_via_appservice` and
//! `observe_sink_free_when_no_subscribers` in the tests below.
use algocline_core::execution::{
AwaitError, CancelError, CancelReason, ExecutionService, ExecutionState, ObserveError,
ObserverHandle, ResumeError, ResumeOutcome, ResumePayload, SessionId, SessionSpec, SpawnError,
StateError, TerminalOutcome,
};
use async_trait::async_trait;
use crate::service::AppService;
#[async_trait]
impl ExecutionService for AppService {
async fn spawn(&self, spec: SessionSpec) -> Result<SessionId, SpawnError> {
self.execution_registry.spawn_v2(spec).await
}
async fn state(&self, id: &SessionId) -> Result<ExecutionState, StateError> {
self.execution_registry.state(id).await
}
async fn resume(
&self,
id: &SessionId,
payload: ResumePayload,
) -> Result<ResumeOutcome, ResumeError> {
self.execution_registry.resume(id, payload).await
}
async fn cancel(&self, id: &SessionId, reason: CancelReason) -> Result<(), CancelError> {
self.execution_registry.cancel(id, reason).await
}
fn observe(&self, id: &SessionId) -> Result<Box<dyn ObserverHandle>, ObserveError> {
self.execution_registry.observe(id)
}
async fn await_terminal(&self, id: &SessionId) -> Result<TerminalOutcome, AwaitError> {
self.execution_registry.await_terminal(id).await
}
}
#[cfg(test)]
mod tests {
use algocline_core::execution::{
CancelCode, CancelReason, ExecutionService, ExecutionState, ObserverRecvError,
ProgressEvent, ResumePayload, SessionSpec, SpecKind, TerminalOutcome,
};
use crate::service::test_support::make_app_service;
fn simple_spec(code: &str) -> SessionSpec {
SessionSpec {
kind: SpecKind::Run {
code: code.to_owned(),
},
project_root: None,
ctx: None,
}
}
fn user_cancel_reason() -> CancelReason {
CancelReason {
code: CancelCode::User,
detail: None,
requested_at: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as i64,
}
}
// -----------------------------------------------------------------------
// spawn_returns_session_id_and_running_state
// -----------------------------------------------------------------------
/// `spawn()` → `state()` immediately returns Running (or Paused for LLM-touching scripts).
#[tokio::test]
async fn spawn_returns_session_id_and_running_state() {
let svc = make_app_service().await;
// Use a Lua script that pauses so we can observe the state before completion.
let sid = svc
.spawn(simple_spec(r#"return alc.llm("q")"#))
.await
.expect("spawn must succeed");
// Wait a short time for the driver to start.
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
let state = svc.state(&sid).await.expect("state must succeed");
assert!(
matches!(state, ExecutionState::Running | ExecutionState::Paused(_)),
"state immediately after spawn must be Running or Paused, got: {:?}",
state.tag()
);
}
// -----------------------------------------------------------------------
// spawn_run_lua_to_completion
// -----------------------------------------------------------------------
/// `SpecKind::Run { code: "return 42" }` → `await_terminal()` → `Terminal(Done(value=42))`.
#[tokio::test]
async fn spawn_run_lua_to_completion() {
let svc = make_app_service().await;
let sid = svc
.spawn(simple_spec("return 42"))
.await
.expect("spawn must succeed");
let outcome =
tokio::time::timeout(std::time::Duration::from_secs(5), svc.await_terminal(&sid))
.await
.expect("await_terminal must not timeout")
.expect("await_terminal must succeed");
match outcome {
TerminalOutcome::Done(result) => {
assert_eq!(
result.value,
serde_json::json!(42),
"Done result value must be 42"
);
}
other => panic!("expected Done, got: {other:?}"),
}
}
// -----------------------------------------------------------------------
// spawn_lua_pause_publishes_progress_event
// -----------------------------------------------------------------------
/// Lua `alc.llm(...)` causes a pause → `observe()` receiver gets `ProgressEvent::PauseRequested`.
#[tokio::test]
async fn spawn_lua_pause_publishes_progress_event() {
let svc = make_app_service().await;
let sid = svc
.spawn(simple_spec(r#"return alc.llm("tell me something")"#))
.await
.expect("spawn must succeed");
// Subscribe before the pause event is published.
let mut handle = svc.observe(&sid).expect("observe must succeed");
// Wait for the PauseRequested event (with timeout).
let got_pause = tokio::time::timeout(std::time::Duration::from_secs(5), async {
loop {
match handle.recv().await {
Ok(ProgressEvent::PauseRequested { .. }) => return true,
Ok(_) => {}
Err(ObserverRecvError::Closed) => return false,
Err(ObserverRecvError::Lagged(_)) => {}
}
}
})
.await
.expect("must not timeout waiting for PauseRequested");
assert!(got_pause, "must receive PauseRequested event");
}
// -----------------------------------------------------------------------
// resume_continues_paused_session
// -----------------------------------------------------------------------
/// Pause → resume(`ResumePayload::Single { response, ... }`) → `ResumeOutcome::Continued`
/// and session eventually reaches `Done`.
#[tokio::test]
async fn resume_continues_paused_session() {
use algocline_core::execution::ResumeOutcome;
let svc = make_app_service().await;
// Strategy that calls alc.llm once and returns the response.
let sid = svc
.spawn(simple_spec(r#"return alc.llm("what is 1+1?")"#))
.await
.expect("spawn must succeed");
// Wait until the session reaches Paused, capturing the query_id.
let query_id = tokio::time::timeout(std::time::Duration::from_secs(5), async {
loop {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
let state = svc.state(&sid).await.expect("state");
if let ExecutionState::Paused(info) = state {
// The query id is the first pending prompt's id.
if let Some(prompt) = info.prompts.first() {
return prompt.query_id.clone();
}
}
}
})
.await
.expect("must reach Paused state within timeout");
let outcome = svc
.resume(
&sid,
ResumePayload::Single {
query_id,
response: "2".into(),
usage: None,
},
)
.await
.expect("resume must succeed");
assert!(
matches!(outcome, ResumeOutcome::Continued),
"resume must return Continued, got: {outcome:?}"
);
// The session should now complete.
let terminal =
tokio::time::timeout(std::time::Duration::from_secs(5), svc.await_terminal(&sid))
.await
.expect("await_terminal must not timeout")
.expect("await_terminal must succeed");
assert!(
matches!(terminal, TerminalOutcome::Done(_)),
"session must complete as Done after resume, got: {terminal:?}"
);
}
// -----------------------------------------------------------------------
// cancel_running_session_transitions_to_cancelled
// -----------------------------------------------------------------------
/// Paused Lua session → `cancel()` → `await_terminal()` → `Cancelled(info)`
/// with `info.reason.code == CancelCode::User`.
///
/// Uses `alc.llm(...)` to enter Paused state so that `cancel()` can exercise
/// the direct Paused→Cancelled transition in `registry::cancel()` without
/// requiring the driver to reach a cooperative-cancellation checkpoint
/// (which a tight CPU loop would never yield to).
#[tokio::test]
async fn cancel_running_session_transitions_to_cancelled() {
let svc = make_app_service().await;
// Spawn a session that pauses waiting for an LLM response.
let sid = svc
.spawn(simple_spec(r#"return alc.llm("cancel me")"#))
.await
.expect("spawn must succeed");
// Wait until the session reaches Paused state.
tokio::time::timeout(std::time::Duration::from_secs(5), async {
loop {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
let state = svc.state(&sid).await.expect("state");
if matches!(state, ExecutionState::Paused(_)) {
return;
}
}
})
.await
.expect("session must reach Paused state within timeout");
svc.cancel(&sid, user_cancel_reason())
.await
.expect("cancel must succeed");
let terminal =
tokio::time::timeout(std::time::Duration::from_secs(5), svc.await_terminal(&sid))
.await
.expect("await_terminal must not timeout")
.expect("await_terminal must succeed");
match terminal {
TerminalOutcome::Cancelled(info) => {
assert_eq!(
info.reason.code,
CancelCode::User,
"cancel code must be User"
);
}
other => panic!("expected Cancelled, got: {other:?}"),
}
}
// -----------------------------------------------------------------------
// cancel_idempotent_returns_ok (Crux R2)
// -----------------------------------------------------------------------
/// Calling `cancel()` twice on the same paused session must both return `Ok(())`.
/// The first `CancelInfo` must remain in the terminal state.
#[tokio::test]
async fn cancel_idempotent_returns_ok() {
let svc = make_app_service().await;
// Spawn a session that pauses waiting for an LLM response.
let sid = svc
.spawn(simple_spec(r#"return alc.llm("cancel me")"#))
.await
.expect("spawn must succeed");
// Wait until the session reaches Paused state.
tokio::time::timeout(std::time::Duration::from_secs(5), async {
loop {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
let state = svc.state(&sid).await.expect("state");
if matches!(state, ExecutionState::Paused(_)) {
return;
}
}
})
.await
.expect("session must reach Paused state within timeout");
svc.cancel(&sid, user_cancel_reason())
.await
.expect("first cancel must return Ok");
// Second cancel on the same session must also return Ok.
svc.cancel(&sid, user_cancel_reason())
.await
.expect("second cancel must return Ok (idempotent)");
// State must reflect the first cancel's info.
let terminal =
tokio::time::timeout(std::time::Duration::from_secs(5), svc.await_terminal(&sid))
.await
.expect("await_terminal must not timeout")
.expect("await_terminal must succeed");
assert!(
matches!(terminal, TerminalOutcome::Cancelled(_)),
"session must be Cancelled, got: {terminal:?}"
);
}
// -----------------------------------------------------------------------
// observe_multi_subscriber_fan_out_via_appservice (Crux R3)
// -----------------------------------------------------------------------
/// Two independent `observe()` calls must each receive the full event stream.
/// Neither subscriber affects the other.
#[tokio::test]
async fn observe_multi_subscriber_fan_out_via_appservice() {
let svc = make_app_service().await;
let sid = svc
.spawn(simple_spec("return 99"))
.await
.expect("spawn must succeed");
// Subscribe two independent handles before the session terminates.
let mut h1 = svc.observe(&sid).expect("observe h1 must succeed");
let mut h2 = svc.observe(&sid).expect("observe h2 must succeed");
// Wait for terminal so events have been published.
let _ = tokio::time::timeout(std::time::Duration::from_secs(5), svc.await_terminal(&sid))
.await
.expect("await_terminal must not timeout");
// Each handle must receive at least one StateTransition event.
//
// The recv loop is bounded by a 100ms idle-timeout per receive:
// `SessionRegistryV2` is sink-free (registry retains `bus_tx` so late
// `observe()` calls can still subscribe), so `bus_tx` does NOT drop
// when the session reaches a terminal state — `Closed` would never
// fire and a bare `loop { recv().await }` blocks forever (the
// observed 7-min worktree hang). Timeout exit is correct: after
// `await_terminal()` succeeded, all events have been published, so
// a 100ms idle window past the last event proves nothing more is
// coming.
use std::time::Duration;
for (label, handle) in [("h1", &mut h1), ("h2", &mut h2)] {
let mut got_transition = false;
loop {
match tokio::time::timeout(Duration::from_millis(100), handle.recv()).await {
Ok(Ok(ProgressEvent::StateTransition { .. })) => got_transition = true,
Ok(Ok(_)) => {}
Ok(Err(ObserverRecvError::Closed)) => break,
Ok(Err(ObserverRecvError::Lagged(_))) => {}
Err(_) => break, // idle-timeout: no more events coming
}
}
assert!(
got_transition,
"{label}: must receive at least one StateTransition event"
);
}
}
// -----------------------------------------------------------------------
// observe_sink_free_when_no_subscribers (Crux R3)
// -----------------------------------------------------------------------
/// Spawn a session without calling `observe()` first. `await_terminal()` must
/// complete normally (sink-free: 0 observers do not stall execution).
/// After terminal, `observe()` must either return a valid handle
/// (if session still in registry) or `ObserveError::NotFound` (if GC'd).
#[tokio::test]
async fn observe_sink_free_when_no_subscribers() {
use algocline_core::execution::ObserveError;
let svc = make_app_service().await;
let sid = svc
.spawn(simple_spec("return 1"))
.await
.expect("spawn must succeed");
// Do NOT observe — no subscribers at all.
let terminal =
tokio::time::timeout(std::time::Duration::from_secs(5), svc.await_terminal(&sid))
.await
.expect("await_terminal must not timeout even with 0 observers")
.expect("await_terminal must succeed");
assert!(
matches!(terminal, TerminalOutcome::Done(_)),
"session must complete as Done, got: {terminal:?}"
);
// After terminal, observe either returns a valid handle (session still alive)
// or NotFound (session GC'd) — both are acceptable per the spec.
match svc.observe(&sid) {
Ok(_handle) => {
// Session still in registry — valid.
}
Err(ObserveError::NotFound(_)) => {
// Session GC'd — also valid.
}
}
}
}