pulpod 0.3.1

Pulpo daemon — manages agent sessions via tmux/Docker
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
use std::sync::Arc;

use pulpo_common::event::{PulpoEvent, SessionInterventionEvent};
use pulpo_common::session::{InterventionCode, Session};

use super::{ReadyContext, resolve_backend_id};
use crate::backend::Backend;
use crate::store::Store;

/// Emit a `PulpoEvent::Intervention` after a session was forcibly stopped (best-effort).
///
/// Mirrors the DB record written by `update_session_intervention`, so a forced stop shows
/// up on the event plane (SSE + webhooks), not only in the interventions table.
pub(super) fn emit_intervention(
    ready_ctx: &ReadyContext,
    session: &Session,
    code: InterventionCode,
    reason: &str,
) {
    if let Some(tx) = &ready_ctx.event_tx {
        let _ = tx.send(PulpoEvent::Intervention(SessionInterventionEvent {
            session_id: session.id.to_string(),
            session_name: session.name.clone(),
            node_name: ready_ctx.node_name.clone(),
            code: code.to_string(),
            reason: reason.to_owned(),
            timestamp: chrono::Utc::now().to_rfc3339(),
        }));
    }
}

/// Stop a session via the standard intervention path shared by every breaker
/// (budget, idle timeout):
///
/// 1. capture a final output snapshot (best-effort, warn on failure),
/// 2. kill the backend session (warn + return `false` on failure so the caller
///    can retry on the next tick — nothing is recorded for a still-alive session),
/// 3. record the intervention in the store (warn on failure),
/// 4. emit the `PulpoEvent::Intervention` event,
/// 5. clean up the session's worktree, if any.
///
/// `kill_fail_msg`/`record_fail_msg` preserve each call site's log wording.
/// Returns `true` when the session was killed (callers log their own success line).
#[cfg_attr(coverage, allow(unused_variables))]
pub(super) async fn stop_and_record(
    backend: &Arc<dyn Backend>,
    store: &Store,
    session: &Session,
    code: InterventionCode,
    reason: &str,
    ready_ctx: &ReadyContext,
    kill_fail_msg: &str,
    record_fail_msg: &str,
) -> bool {
    let bid = resolve_backend_id(session, backend.as_ref());
    match backend.capture_output(&bid, 500) {
        Ok(output) => {
            #[allow(unused_variables)]
            if let Err(error) = store
                .update_session_output_snapshot(&session.id.to_string(), &output)
                .await
            {
                coverage_warn!(
                    session_id = %session.id,
                    session_name = %session.name,
                    "Failed to save output snapshot: {error}"
                );
            }
        }
        #[allow(unused_variables)]
        Err(error) => {
            coverage_warn!(
                session_id = %session.id,
                session_name = %session.name,
                "Failed to capture output before intervention: {error}"
            );
        }
    }

    #[allow(unused_variables)]
    if let Err(error) = backend.kill_session(&bid) {
        coverage_warn!(
            session_id = %session.id,
            session_name = %session.name,
            "{kill_fail_msg}: {error}"
        );
        return false;
    }

    #[allow(unused_variables)]
    if let Err(error) = store
        .update_session_intervention(&session.id.to_string(), code, reason)
        .await
    {
        coverage_warn!(
            session_id = %session.id,
            session_name = %session.name,
            "{record_fail_msg}: {error}"
        );
    }
    emit_intervention(ready_ctx, session, code, reason);
    if let Some(ref wt_path) = session.worktree_path {
        // Mirror `session::manager`'s own guard on the normal stop/purge/cleanup
        // paths: a worktree `pulpo handoff` made two sessions share must survive a
        // forced intervention (budget/idle stop) on just one of them —
        // it's only reclaimed once every referencing session is dead.
        let in_use = store
            .worktree_in_use_elsewhere(wt_path, &session.id.to_string())
            .await
            .unwrap_or_else(|error| {
                coverage_warn!(
                    session_id = %session.id,
                    session_name = %session.name,
                    "Failed to check worktree usage before intervention cleanup, leaving worktree in place: {error}"
                );
                true
            });
        if in_use {
            tracing::debug!(
                session_id = %session.id,
                session_name = %session.name,
                path = %wt_path,
                "Skipping worktree cleanup on intervention — still referenced by another session"
            );
        } else {
            crate::session::manager::cleanup_worktree(wt_path, &session.workdir);
        }
    }
    true
}

#[cfg(test)]
mod tests {
    use super::*;
    use anyhow::Result;
    use pulpo_common::session::SessionStatus;
    use tokio::sync::broadcast;

    #[test]
    fn test_emit_intervention_sends_event_when_tx_present() {
        let (tx, mut rx) = broadcast::channel(8);
        let ctx = ReadyContext {
            event_tx: Some(tx),
            node_name: "node-x".into(),
        };
        let session = Session {
            name: "iv".into(),
            ..Default::default()
        };
        emit_intervention(
            &ctx,
            &session,
            InterventionCode::BudgetExceeded,
            "over budget",
        );
        match rx.try_recv().expect("intervention event") {
            PulpoEvent::Intervention(iv) => {
                assert_eq!(iv.code, "budget_exceeded");
                assert_eq!(iv.node_name, "node-x");
                assert_eq!(iv.reason, "over budget");
                assert_eq!(iv.session_name, "iv");
            }
            other => panic!("expected intervention, got {other:?}"),
        }
    }

    #[test]
    fn test_emit_intervention_is_noop_without_tx() {
        let ctx = ReadyContext {
            event_tx: None,
            node_name: "n".into(),
        };
        // No subscribers / no tx — must not panic.
        emit_intervention(
            &ctx,
            &Session::default(),
            InterventionCode::IdleTimeout,
            "idle",
        );
    }

    // -- stop_and_record: worktree cleanup must respect sharing --

    fn ready_ctx() -> ReadyContext {
        ReadyContext {
            event_tx: None,
            node_name: "test-node".into(),
        }
    }

    fn session_with_worktree(name: &str, worktree_path: &str) -> Session {
        Session {
            id: uuid::Uuid::new_v4(),
            name: name.into(),
            workdir: "/tmp/repo".into(),
            command: "claude".into(),
            status: SessionStatus::Active,
            backend_session_id: Some(name.into()),
            worktree_path: Some(worktree_path.into()),
            ..Default::default()
        }
    }

    #[tokio::test]
    async fn test_stop_and_record_preserves_worktree_shared_with_another_live_session() {
        // Two sessions (as `pulpo handoff` produces) sharing one worktree path — an
        // intervention (budget/idle stop) on one must not delete the
        // worktree (or its branch) out from under the other, still-live session.
        let store = crate::store::test_store().await;
        let tmp = tempfile::tempdir().unwrap();
        let wt_path = tmp.path().to_str().unwrap().to_owned();

        let session_a = session_with_worktree("shared-a", &wt_path);
        let session_b = session_with_worktree("shared-b", &wt_path);
        store.insert_session(&session_a).await.unwrap();
        store.insert_session(&session_b).await.unwrap();

        let backend: Arc<dyn Backend> = Arc::new(crate::backend::StubBackend);
        let stopped = stop_and_record(
            &backend,
            &store,
            &session_a,
            InterventionCode::IdleTimeout,
            "idle for too long",
            &ready_ctx(),
            "kill failed",
            "record failed",
        )
        .await;

        assert!(stopped);
        assert!(
            std::path::Path::new(&wt_path).exists(),
            "worktree shared with a still-live session must survive the intervention"
        );
    }

    #[tokio::test]
    async fn test_stop_and_record_cleans_up_worktree_when_not_shared() {
        // Sanity check for the guard above: a worktree with no other live session
        // referencing it is still cleaned up as before.
        let store = crate::store::test_store().await;
        let tmp = tempfile::tempdir().unwrap();
        let wt_path = tmp.path().to_str().unwrap().to_owned();

        let session = session_with_worktree("solo", &wt_path);
        store.insert_session(&session).await.unwrap();

        let backend: Arc<dyn Backend> = Arc::new(crate::backend::StubBackend);
        let stopped = stop_and_record(
            &backend,
            &store,
            &session,
            InterventionCode::IdleTimeout,
            "idle for too long",
            &ready_ctx(),
            "kill failed",
            "record failed",
        )
        .await;

        assert!(stopped);
        assert!(
            !std::path::Path::new(&wt_path).exists(),
            "an unshared worktree should still be cleaned up on intervention"
        );
    }

    // -- stop_and_record: capture/record failures degrade gracefully --

    fn plain_session(name: &str) -> Session {
        Session {
            id: uuid::Uuid::new_v4(),
            name: name.into(),
            workdir: "/tmp/repo".into(),
            command: "claude".into(),
            status: SessionStatus::Active,
            backend_session_id: Some(name.into()),
            ..Default::default()
        }
    }

    /// Backend whose `capture_output` always fails but whose `kill_session`
    /// succeeds — exercises `stop_and_record`'s "best-effort" snapshot path.
    struct FailingCaptureBackend;

    impl Backend for FailingCaptureBackend {
        fn create_session(&self, _: &str, _: &str, _: &str) -> Result<()> {
            Ok(())
        }
        fn kill_session(&self, _: &str) -> Result<()> {
            Ok(())
        }
        fn is_alive(&self, _: &str) -> Result<bool> {
            Ok(true)
        }
        fn capture_output(&self, _: &str, _: usize) -> Result<String> {
            anyhow::bail!("capture failed")
        }
        fn send_input(&self, _: &str, _: &str) -> Result<()> {
            Ok(())
        }
        fn setup_logging(&self, _: &str, _: &str) -> Result<()> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn test_stop_and_record_kills_despite_capture_failure() {
        let store = crate::store::test_store().await;
        let session = plain_session("cap-fail");
        store.insert_session(&session).await.unwrap();

        let backend: Arc<dyn Backend> = Arc::new(FailingCaptureBackend);
        let stopped = stop_and_record(
            &backend,
            &store,
            &session,
            InterventionCode::IdleTimeout,
            "idle for too long",
            &ready_ctx(),
            "kill failed",
            "record failed",
        )
        .await;

        assert!(stopped, "kill must still succeed despite capture failure");
        let fetched = store
            .get_session(&session.id.to_string())
            .await
            .unwrap()
            .unwrap();
        // No snapshot saved since capture failed, but the intervention still lands.
        assert!(fetched.output_snapshot.is_none());
        assert!(fetched.intervention_reason.is_some());
    }

    #[tokio::test]
    async fn test_stop_and_record_kills_despite_snapshot_save_failure() {
        let store = crate::store::test_store().await;
        let session = plain_session("snap-fail");
        store.insert_session(&session).await.unwrap();

        // Break `update_session_output_snapshot`'s UPDATE query by renaming the
        // column it writes. `StubBackend::capture_output` still succeeds, so this
        // exercises the "capture ok, but snapshot save fails" branch specifically
        // (distinct from `check_session_idle`'s own — earlier, unrelated — call to
        // the same store method).
        sqlx::query("ALTER TABLE sessions RENAME COLUMN output_snapshot TO output_snapshot_old")
            .execute(store.pool())
            .await
            .unwrap();

        let backend: Arc<dyn Backend> = Arc::new(crate::backend::StubBackend);
        let stopped = stop_and_record(
            &backend,
            &store,
            &session,
            InterventionCode::IdleTimeout,
            "idle for too long",
            &ready_ctx(),
            "kill failed",
            "record failed",
        )
        .await;

        assert!(
            stopped,
            "kill must still succeed despite output snapshot save failure"
        );
    }

    #[tokio::test]
    async fn test_stop_and_record_kills_despite_intervention_record_failure() {
        let store = crate::store::test_store().await;
        let session = plain_session("record-fail");
        store.insert_session(&session).await.unwrap();

        // Break `update_session_intervention`'s UPDATE query by renaming the
        // column it writes.
        sqlx::query(
            "ALTER TABLE sessions RENAME COLUMN intervention_reason TO intervention_reason_old",
        )
        .execute(store.pool())
        .await
        .unwrap();

        let backend: Arc<dyn Backend> = Arc::new(crate::backend::StubBackend);
        let stopped = stop_and_record(
            &backend,
            &store,
            &session,
            InterventionCode::IdleTimeout,
            "idle for too long",
            &ready_ctx(),
            "kill failed",
            "record failed",
        )
        .await;

        assert!(
            stopped,
            "kill must still succeed despite intervention record failure"
        );
    }
}