lifeloop-cli 0.2.0

Provider-neutral lifecycle abstraction and normalizer for AI harnesses
Documentation
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
//! End-to-end integration: Lifeloop drives a CCD-shaped callback
//! client over the process boundary (issue #8).
//!
//! This is the load-bearing proof that a CCD-style client can be
//! reached through Lifeloop's router stack without taking a Rust
//! dependency on it: the only contract is a JSON
//! [`lifeloop::CallbackRequest`] on stdin and a JSON
//! [`lifeloop::CallbackResponse`] on stdout. The fake client lives in
//! `src/bin/lifeloop-fake-ccd-client.rs` and is reached through the
//! cargo-provided `CARGO_BIN_EXE_lifeloop-fake-ccd-client` env var so
//! the path is portable across Linux and macOS.
//!
//! # Behavior corpus ownership
//!
//! Each assertion below is annotated as either **Lifeloop-owned**
//! (the contract or the router stack must guarantee it) or
//! **CCD-owned** (a real client implementation can vary the value).
//! The split mirrors the issue acceptance bullet — Lifeloop tests the
//! seam, not the client semantics.
//!
//! * `request.event` / `request.event_id` / `request.adapter_id` /
//!   `request.adapter_version` / `request.integration_mode` /
//!   `request.invocation_id` / `request.frame_context` /
//!   `request.payload_refs` / `request.idempotency_key` arriving on
//!   stdin → **Lifeloop-owned**: the router synthesizes the request
//!   from the validated [`lifeloop::router::RoutingPlan`] and the
//!   wire shape is pinned by `tests/wire_contract.rs`.
//! * The specific `payload_kind` (`ccd.instruction_frame`) and the
//!   payload `body` text returned by the fake → **CCD-owned**: a
//!   real client picks its own client-defined kinds and bodies.
//! * `response.status == Delivered` for `frame.opening` and
//!   `session.started` happy paths → **CCD-owned** behavior; the
//!   contract only requires that *some* valid status come back.
//! * `receipt.emitted` being rejected before spawn →
//!   **Lifeloop-owned**: the contract states `receipt.emitted` is a
//!   notification event and never produces a downstream invocation.
//! * Failure-class mapping for transport / parse / timeout / non-zero
//!   exit → **Lifeloop-owned**: the failure-class vocabulary is part
//!   of Lifeloop's surface and the router must map subprocess
//!   failures onto it deterministically.

use std::collections::BTreeMap;
use std::path::PathBuf;
use std::time::Duration;

use lifeloop::router::{
    AdapterRegistry, AdapterResolution, CallbackInvoker, RoutingPlan, SubprocessCallbackInvoker,
    SubprocessInvokerConfig, SubprocessInvokerError, route,
};
use lifeloop::{
    AcceptablePlacement, AdapterManifest, AdapterRole, CallbackRequest, ConformanceLevel,
    FailureClass, FrameContext, IntegrationMode, LifecycleEventKind, ManifestContextPressure,
    ManifestPlacementClass, ManifestPlacementSupport, ManifestReceipts, PayloadEnvelope,
    PayloadRef, PlacementClass, ReceiptStatus, RegisteredAdapter, RequirementLevel, SCHEMA_VERSION,
    SupportState,
};

const FAKE_ID: &str = "ccd";
const FAKE_VERSION: &str = "0.1.0";

fn fake_ccd_bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_lifeloop-fake-ccd-client"))
}

fn manifest() -> AdapterManifest {
    let mut placement = BTreeMap::new();
    placement.insert(
        ManifestPlacementClass::PreFrameTrailing,
        ManifestPlacementSupport {
            support: SupportState::Native,
            max_bytes: None,
        },
    );
    AdapterManifest {
        contract_version: SCHEMA_VERSION.to_string(),
        adapter_id: FAKE_ID.into(),
        adapter_version: FAKE_VERSION.into(),
        display_name: "Fake CCD".into(),
        role: AdapterRole::PrimaryWorker,
        integration_modes: vec![IntegrationMode::NativeHook],
        lifecycle_events: BTreeMap::new(),
        placement,
        context_pressure: ManifestContextPressure {
            support: SupportState::Native,
            evidence: None,
        },
        receipts: ManifestReceipts {
            native: false,
            lifeloop_synthesized: true,
            receipt_ledger: SupportState::Unavailable,
        },
        session_identity: None,
        session_rename: None,
        renewal: None,
        approval_surface: None,
        failure_modes: Vec::new(),
        telemetry_sources: Vec::new(),
        known_degradations: Vec::new(),
    }
}

struct Fixture(AdapterManifest);

impl AdapterRegistry for Fixture {
    fn resolve(&self, id: &str, version: &str) -> AdapterResolution {
        if id != self.0.adapter_id {
            return AdapterResolution::UnknownId;
        }
        if version != self.0.adapter_version {
            return AdapterResolution::VersionMismatch {
                registered_version: self.0.adapter_version.clone(),
            };
        }
        AdapterResolution::Found(RegisteredAdapter {
            manifest: self.0.clone(),
            conformance: ConformanceLevel::PreConformance,
        })
    }
}

fn frame_request() -> CallbackRequest {
    CallbackRequest {
        schema_version: SCHEMA_VERSION.to_string(),
        event: LifecycleEventKind::FrameOpening,
        event_id: "evt-e2e-1".into(),
        adapter_id: FAKE_ID.into(),
        adapter_version: FAKE_VERSION.into(),
        integration_mode: IntegrationMode::NativeHook,
        invocation_id: "inv-e2e-1".into(),
        harness_session_id: Some("sess-e2e-1".into()),
        harness_run_id: Some("run-e2e-1".into()),
        harness_task_id: None,
        frame_context: Some(FrameContext::top_level("frm-e2e-1")),
        capability_snapshot_ref: None,
        payload_refs: vec![PayloadRef {
            payload_id: "pay-ref-1".into(),
            payload_kind: "instruction_frame".into(),
            content_digest: None,
            byte_size: Some(11),
        }],
        sequence: None,
        idempotency_key: Some("idem-e2e-1".into()),
        metadata: serde_json::Map::new(),
    }
}

fn build_plan(req: &CallbackRequest) -> RoutingPlan {
    let fx = Fixture(manifest());
    route(req, &fx).expect("plan builds")
}

fn invoker_with(behavior: &str, timeout: Duration) -> SubprocessCallbackInvoker {
    // Behavior is carried by a CLI arg so each spawn is independent
    // of process-global env state — cargo runs integration tests in
    // parallel and env vars would race.
    let cfg = SubprocessInvokerConfig::new(fake_ccd_bin(), timeout).arg(behavior);
    SubprocessCallbackInvoker::new(cfg)
}

// ---------------------------------------------------------------------------
// Happy paths
// ---------------------------------------------------------------------------

#[test]
fn frame_opening_returns_delivered_with_payload() {
    // Lifeloop-owned: the request shape on stdin matches the validated plan.
    // CCD-owned: the specific payload_kind/body returned.
    let invoker = invoker_with("ok", Duration::from_secs(5));
    let req = frame_request();
    let plan = build_plan(&req);
    let resp = invoker.invoke(&plan, &[]).expect("subprocess returns ok");
    assert_eq!(resp.status, ReceiptStatus::Delivered); // Lifeloop-owned (valid status)
    assert_eq!(resp.client_payloads.len(), 1); // CCD-owned (count is up to client)
    let p = &resp.client_payloads[0];
    assert_eq!(p.client_id, "ccd"); // CCD-owned
    assert_eq!(p.payload_kind, "ccd.instruction_frame"); // CCD-owned
    assert_eq!(p.idempotency_key.as_deref(), Some("idem-e2e-1")); // Lifeloop-owned (mirrored from request)
}

#[test]
fn frame_opening_delivers_payload_envelope_to_subprocess() {
    // Lifeloop-owned (issue #22): payload envelopes pass through the
    // subprocess boundary verbatim. The fake client echoes the first
    // delivered payload's body and kind into its response so we can
    // prove the bytes travelled, not that the request envelope merely
    // contained matching payload_refs.
    let invoker = invoker_with("ok", Duration::from_secs(5));
    let req = frame_request();
    let plan = build_plan(&req);

    let body = "round-trip-body-from-e2e";
    let payload = PayloadEnvelope {
        schema_version: SCHEMA_VERSION.to_string(),
        payload_id: "pay-e2e-payload-1".into(),
        client_id: "ccd".into(),
        payload_kind: "ccd.test_frame".into(),
        format: "client-defined".into(),
        content_encoding: "utf8".into(),
        body: Some(body.into()),
        body_ref: None,
        byte_size: body.len() as u64,
        content_digest: None,
        acceptable_placements: vec![AcceptablePlacement {
            placement: PlacementClass::PrePromptFrame,
            requirement: RequirementLevel::Preferred,
        }],
        idempotency_key: None,
        expires_at_epoch_s: None,
        redaction: None,
        metadata: serde_json::Map::new(),
    };

    let resp = invoker
        .invoke(&plan, std::slice::from_ref(&payload))
        .expect("subprocess returns ok");
    assert_eq!(resp.status, ReceiptStatus::Delivered);
    assert_eq!(resp.client_payloads.len(), 1);
    let echoed = &resp.client_payloads[0];
    // The fake client mirrors the delivered body and kind back —
    // proving the dispatch envelope's payloads slot reached the
    // child process and was deserializable on the client side.
    assert_eq!(echoed.payload_kind, "ccd.test_frame");
    assert_eq!(echoed.body.as_deref(), Some(body));
}

#[test]
fn session_started_returns_delivered_with_no_payload() {
    let invoker = invoker_with("ok", Duration::from_secs(5));
    let mut req = frame_request();
    req.event = LifecycleEventKind::SessionStarted;
    req.frame_context = None; // not frame-scoped
    let plan = build_plan(&req);
    let resp = invoker.invoke(&plan, &[]).expect("subprocess returns ok");
    assert_eq!(resp.status, ReceiptStatus::Delivered);
    assert!(resp.client_payloads.is_empty()); // CCD-owned
}

// ---------------------------------------------------------------------------
// Failure paths
// ---------------------------------------------------------------------------

#[test]
fn malformed_stdout_maps_to_invalid_request() {
    // Lifeloop-owned: a malformed wire response is invalid_request, not
    // transport_error — the bytes were delivered, they just don't speak
    // the contract.
    let invoker = invoker_with("malformed", Duration::from_secs(5));
    let plan = build_plan(&frame_request());
    let err = invoker.invoke(&plan, &[]).unwrap_err();
    assert!(
        matches!(err, SubprocessInvokerError::ParseResponse(_)),
        "expected ParseResponse, got {err:?}"
    );
    let fc: FailureClass = (&err).into();
    assert_eq!(fc, FailureClass::InvalidRequest);
}

#[test]
fn nonzero_exit_maps_to_transport_error() {
    // Lifeloop-owned: a non-zero child is a transport-class failure; the
    // shared FailureClass vocabulary already has TransportError, no new
    // variant needed.
    let invoker = invoker_with("nonzero", Duration::from_secs(5));
    let plan = build_plan(&frame_request());
    let err = invoker.invoke(&plan, &[]).unwrap_err();
    match &err {
        SubprocessInvokerError::NonZeroExit { code, stderr } => {
            assert_eq!(*code, Some(7));
            assert!(stderr.contains("simulated transport failure"));
        }
        other => panic!("expected NonZeroExit, got {other:?}"),
    }
    let fc: FailureClass = (&err).into();
    assert_eq!(fc, FailureClass::TransportError);
}

#[test]
fn nonzero_exit_dominates_broken_pipe_from_large_request() {
    let invoker = invoker_with("nonzero", Duration::from_secs(5));
    let plan = build_plan(&frame_request());
    let body = "x".repeat(2 * 1024 * 1024);
    let payload = PayloadEnvelope {
        schema_version: SCHEMA_VERSION.to_string(),
        payload_id: "pay-large-broken-pipe".into(),
        client_id: "ccd".into(),
        payload_kind: "ccd.large_request".into(),
        format: "client-defined".into(),
        content_encoding: "utf8".into(),
        body: Some(body.clone()),
        body_ref: None,
        byte_size: body.len() as u64,
        content_digest: None,
        acceptable_placements: vec![AcceptablePlacement {
            placement: PlacementClass::PrePromptFrame,
            requirement: RequirementLevel::Preferred,
        }],
        idempotency_key: None,
        expires_at_epoch_s: None,
        redaction: None,
        metadata: serde_json::Map::new(),
    };

    let err = invoker
        .invoke(&plan, std::slice::from_ref(&payload))
        .unwrap_err();
    match &err {
        SubprocessInvokerError::NonZeroExit { code, stderr } => {
            assert_eq!(*code, Some(7));
            assert!(stderr.contains("simulated transport failure"));
        }
        other => panic!("expected NonZeroExit to dominate BrokenPipe, got {other:?}"),
    }
    let fc: FailureClass = (&err).into();
    assert_eq!(fc, FailureClass::TransportError);
}

#[test]
fn zero_exit_broken_pipe_surfaces_write_request() {
    let invoker = invoker_with("exit_zero_no_read", Duration::from_secs(5));
    let plan = build_plan(&frame_request());
    let body = "x".repeat(2 * 1024 * 1024);
    let payload = PayloadEnvelope {
        schema_version: SCHEMA_VERSION.to_string(),
        payload_id: "pay-large-zero-broken-pipe".into(),
        client_id: "ccd".into(),
        payload_kind: "ccd.large_request".into(),
        format: "client-defined".into(),
        content_encoding: "utf8".into(),
        body: Some(body.clone()),
        body_ref: None,
        byte_size: body.len() as u64,
        content_digest: None,
        acceptable_placements: vec![AcceptablePlacement {
            placement: PlacementClass::PrePromptFrame,
            requirement: RequirementLevel::Preferred,
        }],
        idempotency_key: None,
        expires_at_epoch_s: None,
        redaction: None,
        metadata: serde_json::Map::new(),
    };

    let err = invoker
        .invoke(&plan, std::slice::from_ref(&payload))
        .unwrap_err();
    match &err {
        SubprocessInvokerError::WriteRequest(e) if e.kind() == std::io::ErrorKind::BrokenPipe => {}
        other => panic!("expected WriteRequest(BrokenPipe), got {other:?}"),
    }
    let fc: FailureClass = (&err).into();
    assert_eq!(fc, FailureClass::TransportError);
}

#[test]
fn hung_subprocess_is_killed_after_timeout() {
    // Lifeloop-owned: a hang past the deadline is mapped to Timeout and
    // the child is killed (the test process must not leak it).
    let invoker = invoker_with("hang", Duration::from_millis(150));
    let plan = build_plan(&frame_request());
    let err = invoker.invoke(&plan, &[]).unwrap_err();
    assert!(
        matches!(err, SubprocessInvokerError::Timeout),
        "expected Timeout, got {err:?}"
    );
    let fc: FailureClass = (&err).into();
    assert_eq!(fc, FailureClass::Timeout);
}

#[test]
fn oversized_stdout_is_rejected_without_parsing() {
    let invoker = invoker_with("huge_stdout", Duration::from_secs(5));
    let plan = build_plan(&frame_request());
    let err = invoker.invoke(&plan, &[]).unwrap_err();
    assert!(
        matches!(err, SubprocessInvokerError::ReadResponse(_)),
        "expected ReadResponse for oversized stdout, got {err:?}"
    );
    let fc: FailureClass = (&err).into();
    assert_eq!(fc, FailureClass::TransportError);
}

#[cfg(unix)]
#[test]
fn inherited_stdout_pipe_times_out_and_is_cleaned_up() {
    let invoker = invoker_with("hold_stdout_open", Duration::from_millis(150));
    let plan = build_plan(&frame_request());
    let err = invoker.invoke(&plan, &[]).unwrap_err();
    assert!(
        matches!(err, SubprocessInvokerError::Timeout),
        "expected Timeout for inherited stdout pipe, got {err:?}"
    );
}

#[test]
fn receipt_emitted_is_rejected_before_spawn() {
    // Lifeloop-owned: receipt.emitted is a notification event; the
    // invoker must refuse it without spawning a child. We point the
    // config at a path that does NOT exist — if the invoker tried to
    // spawn we would see a Spawn error; instead we should see
    // ReceiptEmittedRejected.
    let cfg = SubprocessInvokerConfig::new(
        PathBuf::from("/definitely/does/not/exist/lifeloop-fake-ccd-client-missing"),
        Duration::from_secs(5),
    );
    let invoker = SubprocessCallbackInvoker::new(cfg);

    let mut req = frame_request();
    req.event = LifecycleEventKind::ReceiptEmitted;
    req.frame_context = None;
    req.idempotency_key = None; // notification events do not carry idempotency keys
    let plan = build_plan(&req);

    let err = invoker.invoke(&plan, &[]).unwrap_err();
    assert!(
        matches!(err, SubprocessInvokerError::ReceiptEmittedRejected(_)),
        "expected ReceiptEmittedRejected (pre-spawn guard), got {err:?}"
    );
    let fc: FailureClass = (&err).into();
    assert_eq!(fc, FailureClass::InvalidRequest);
}