scsh 1.9.0

Scoped Skills Helper — preflight a git repo and run its scoped skills in ephemeral containers.
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
//! Pure event model for the scsh session browser daemon.

use std::collections::BTreeMap;

/// Default HTTP port (`scsh` on a numeric keypad: 7→s, 2→c, 7→s, 4→h).
pub const DEFAULT_PORT: u16 = 7274;

/// Ephemeral daemon idle timeout before shutdown when no clients are connected.
pub const EPHEMERAL_IDLE_SECS: u64 = 300;

/// Grace period with no alive clients before the browser shows an ephemeral shutdown countdown.
pub const EPHEMERAL_COUNTDOWN_AFTER_SECS: u64 = 5;

/// Silence threshold before a session without `ended_at` is marked terminated.
pub const SESSION_STALE_SECS: u64 = 10;

/// Maximum sessions retained in daemon state.
pub const MAX_STORED_SESSIONS: usize = 200;

/// How a daemon was started.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DaemonMode {
  /// `scsh daemon start` — runs until `scsh daemon stop`.
  Persistent,
  /// Auto-started alongside a `scsh run` — exits after idle timeout.
  Ephemeral,
}

impl DaemonMode {
  pub fn as_str(self) -> &'static str {
    match self {
      DaemonMode::Persistent => "persistent",
      DaemonMode::Ephemeral => "ephemeral",
    }
  }

  pub fn parse(s: &str) -> Option<Self> {
    match s {
      "persistent" => Some(DaemonMode::Persistent),
      "ephemeral" => Some(DaemonMode::Ephemeral),
      _ => None,
    }
  }
}

/// Index-page lifecycle for a `scsh run` session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionLifecycle {
  Running,
  Completed,
  Failed,
  Cancelled,
  Terminated,
}

impl SessionLifecycle {
  pub fn label(self) -> &'static str {
    match self {
      SessionLifecycle::Running => "running",
      SessionLifecycle::Completed => "completed",
      SessionLifecycle::Failed => "failed",
      SessionLifecycle::Cancelled => "cancelled",
      SessionLifecycle::Terminated => "terminated abruptly",
    }
  }

  pub fn css_class(self) -> &'static str {
    match self {
      SessionLifecycle::Running => "running",
      SessionLifecycle::Completed => "completed",
      SessionLifecycle::Failed => "failed",
      SessionLifecycle::Cancelled => "cancelled",
      SessionLifecycle::Terminated => "terminated",
    }
  }
}

/// Lifecycle status of one proc row (build or skill).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcStatus {
  Waiting,
  Running,
  Ok,
  Fail,
}

impl ProcStatus {
  pub fn as_str(self) -> &'static str {
    match self {
      ProcStatus::Waiting => "waiting",
      ProcStatus::Running => "running",
      ProcStatus::Ok => "ok",
      ProcStatus::Fail => "fail",
    }
  }

  pub fn parse(s: &str) -> Option<Self> {
    match s {
      "waiting" => Some(ProcStatus::Waiting),
      "running" => Some(ProcStatus::Running),
      "ok" => Some(ProcStatus::Ok),
      "fail" => Some(ProcStatus::Fail),
      _ => None,
    }
  }
}

/// Build vs skill row.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcKind {
  Build,
  Skill,
}

impl ProcKind {
  pub fn as_str(self) -> &'static str {
    match self {
      ProcKind::Build => "build",
      ProcKind::Skill => "skill",
    }
  }

  pub fn parse(s: &str) -> Option<Self> {
    match s {
      "build" => Some(ProcKind::Build),
      "skill" => Some(ProcKind::Skill),
      _ => None,
    }
  }
}

/// One timestamped output line from a proc.
#[derive(Debug, Clone, PartialEq)]
pub struct OutputLine {
  pub at: f64,
  pub text: String,
}

/// A collapsible row on the live board (image build or skill).
#[derive(Debug, Clone, PartialEq)]
pub struct ProcRecord {
  pub index: usize,
  pub label: String,
  pub kind: ProcKind,
  pub status: ProcStatus,
  pub skill_name: Option<String>,
  pub harness: Option<String>,
  pub model: Option<String>,
  /// Unix seconds when the proc entered `running` (for live elapsed / idle in the browser).
  pub started_at: Option<u64>,
  pub note: Option<String>,
  pub detail: Option<String>,
  pub elapsed: Option<f64>,
  pub lines: Vec<OutputLine>,
  pub container_name: Option<String>,
}

/// One skill listed in a session's start payload.
#[derive(Debug, Clone, PartialEq)]
pub struct SkillMeta {
  pub name: String,
  pub harness: String,
}

/// One `scsh run` invocation — grouped by session id (six lowercase letters).
#[derive(Debug, Clone, PartialEq)]
pub struct Session {
  pub id: String,
  pub started_at: u64,
  /// Unix seconds when the `scsh run` client deregistered (run finished).
  pub ended_at: Option<u64>,
  pub profile: Option<String>,
  pub repo: String,
  /// Git branch checked out in the repo when the run started (`rev-parse --abbrev-ref HEAD`).
  pub branch: String,
  pub skills: Vec<SkillMeta>,
  pub procs: Vec<ProcRecord>,
  /// Last ping or session-scoped API event (unix seconds).
  pub last_seen_at: u64,
  /// True while the `scsh run` client is registered (between register and deregister).
  pub client_connected: bool,
}

/// Full daemon state persisted to disk and served over HTTP.
#[derive(Debug, Clone, PartialEq)]
pub struct Store {
  pub mode: DaemonMode,
  pub port: u16,
  /// When this daemon process started (unix seconds).
  pub started_at: u64,
  pub active_clients: u32,
  pub last_activity: u64,
  /// When `alive_clients` last dropped to zero (unix seconds); drives ephemeral shutdown.
  pub no_alive_since: Option<u64>,
  pub sessions: BTreeMap<String, Session>,
}

impl Store {
  pub fn new(mode: DaemonMode, port: u16, now: u64) -> Store {
    Store {
      mode,
      port,
      started_at: now,
      active_clients: 0,
      last_activity: now,
      no_alive_since: Some(now),
      sessions: BTreeMap::new(),
    }
  }

  pub fn touch(&mut self, now: u64) {
    self.last_activity = now;
  }

  /// Registered `scsh run` clients that are still sending pings (not stale / terminated).
  pub fn alive_clients(&self, now: u64) -> u32 {
    self
      .sessions
      .values()
      .filter(|s| s.client_connected && s.lifecycle_status(now) == SessionLifecycle::Running)
      .count() as u32
  }

  /// Drop stale registrations and refresh ephemeral idle tracking.
  pub fn reconcile(&mut self, now: u64) {
    for session in self.sessions.values_mut() {
      if session.client_connected && session.lifecycle_status(now) != SessionLifecycle::Running {
        session.client_connected = false;
      }
    }
    self.active_clients = self.sessions.values().filter(|s| s.client_connected).count() as u32;
    if self.alive_clients(now) > 0 {
      self.no_alive_since = None;
    } else if self.no_alive_since.is_none() {
      self.no_alive_since = Some(now);
    }
  }

  /// Seconds until ephemeral shutdown, once the no-alive grace period has elapsed.
  pub fn ephemeral_shutdown_in_secs(&self, now: u64) -> Option<u64> {
    if self.mode != DaemonMode::Ephemeral {
      return None;
    }
    let since = self.no_alive_since?;
    let idle = now.saturating_sub(since);
    if idle < EPHEMERAL_COUNTDOWN_AFTER_SECS {
      return None;
    }
    Some(EPHEMERAL_IDLE_SECS.saturating_sub(idle))
  }

  pub fn should_shutdown_ephemeral(&self, now: u64) -> bool {
    self.mode == DaemonMode::Ephemeral
      && self.alive_clients(now) == 0
      && self.no_alive_since.is_some_and(|since| now.saturating_sub(since) >= EPHEMERAL_IDLE_SECS)
  }

  pub fn session_mut(&mut self, id: &str) -> Option<&mut Session> {
    self.sessions.get_mut(id)
  }

  pub fn proc_mut(&mut self, session_id: &str, proc_index: usize) -> Option<&mut ProcRecord> {
    self.session_mut(session_id).and_then(|s| s.procs.iter_mut().find(|p| p.index == proc_index))
  }

  pub fn insert_session(&mut self, id: String, session: Session) {
    self.sessions.insert(id, session);
    trim_sessions_to_cap(&mut self.sessions);
  }
}

/// Drop oldest sessions when the map exceeds [`MAX_STORED_SESSIONS`] (same rule as `insert_session`).
pub fn trim_sessions_to_cap(sessions: &mut std::collections::BTreeMap<String, Session>) {
  while sessions.len() > MAX_STORED_SESSIONS {
    let Some(old_id) = sessions.iter().min_by_key(|(_, s)| s.started_at).map(|(id, _)| id.clone()) else {
      break;
    };
    sessions.remove(&old_id);
  }
}

/// Sessions sorted for the index page: running first, then by start time descending.
pub fn sessions_for_index<'a>(sessions: &'a BTreeMap<String, Session>, now: u64) -> Vec<&'a Session> {
  let mut list: Vec<&Session> = sessions.values().collect();
  list.sort_by(|a, b| {
    let a_live = a.lifecycle_status(now) == SessionLifecycle::Running;
    let b_live = b.lifecycle_status(now) == SessionLifecycle::Running;
    match (a_live, b_live) {
      (true, false) => std::cmp::Ordering::Less,
      (false, true) => std::cmp::Ordering::Greater,
      _ => b.started_at.cmp(&a.started_at),
    }
  });
  list
}

impl Session {
  /// True while any proc has not reached a terminal state (ok/fail).
  pub fn has_incomplete_procs(&self) -> bool {
    self.procs.iter().any(|p| p.status == ProcStatus::Running || p.status == ProcStatus::Waiting)
  }

  pub fn lifecycle_status(&self, now: u64) -> SessionLifecycle {
    if self.ended_at.is_some() {
      if self.has_incomplete_procs() {
        return SessionLifecycle::Cancelled;
      }
      if self.procs.iter().any(|p| p.status == ProcStatus::Fail) {
        return SessionLifecycle::Failed;
      }
      return SessionLifecycle::Completed;
    }
    if now.saturating_sub(self.last_seen_at) > SESSION_STALE_SECS {
      return SessionLifecycle::Terminated;
    }
    SessionLifecycle::Running
  }

  pub fn duration_secs(&self, now: u64) -> Option<u64> {
    if let Some(end) = self.ended_at {
      return Some(end.saturating_sub(self.started_at));
    }
    let lifecycle = self.lifecycle_status(now);
    if lifecycle == SessionLifecycle::Running {
      return Some(now.saturating_sub(self.started_at));
    }
    if lifecycle == SessionLifecycle::Terminated {
      return Some(self.last_seen_at.saturating_sub(self.started_at));
    }
    None
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn lifecycle_completed_when_ended_cleanly() {
    let session = Session {
      id: "done".into(),
      started_at: 100,
      ended_at: Some(200),
      profile: None,
      repo: "/r".into(),
      branch: "main".into(),
      skills: Vec::new(),
      procs: vec![ProcRecord {
        index: 0,
        label: "skill".into(),
        kind: ProcKind::Skill,
        status: ProcStatus::Ok,
        skill_name: None,
        harness: None,
        model: None,
        started_at: Some(100),
        note: None,
        detail: None,
        elapsed: Some(5.0),
        lines: Vec::new(),
        container_name: None,
      }],
      last_seen_at: 200,
      client_connected: false,
    };
    assert_eq!(session.lifecycle_status(200), SessionLifecycle::Completed);
    assert_eq!(session.duration_secs(200), Some(100));
  }

  #[test]
  fn lifecycle_terminated_when_stale_without_ended_at() {
    let session = Session {
      id: "stale".into(),
      started_at: 100,
      ended_at: None,
      profile: None,
      repo: "/r".into(),
      branch: "main".into(),
      skills: Vec::new(),
      procs: Vec::new(),
      last_seen_at: 100,
      client_connected: true,
    };
    assert_eq!(session.lifecycle_status(110), SessionLifecycle::Running);
    assert_eq!(session.lifecycle_status(111), SessionLifecycle::Terminated);
  }

  #[test]
  fn lifecycle_cancelled_when_ended_with_incomplete_procs() {
    let session = Session {
      id: "cancel".into(),
      started_at: 1,
      ended_at: Some(50),
      profile: None,
      repo: "/r".into(),
      branch: "main".into(),
      skills: Vec::new(),
      procs: vec![ProcRecord {
        index: 0,
        label: "skill".into(),
        kind: ProcKind::Skill,
        status: ProcStatus::Running,
        skill_name: None,
        harness: None,
        model: None,
        started_at: Some(1),
        note: None,
        detail: None,
        elapsed: None,
        lines: Vec::new(),
        container_name: None,
      }],
      last_seen_at: 50,
      client_connected: false,
    };
    assert_eq!(session.lifecycle_status(50), SessionLifecycle::Cancelled);
  }

  #[test]
  fn lifecycle_running_while_incomplete_procs_and_recent() {
    let session = Session {
      id: "test".into(),
      started_at: 1,
      ended_at: None,
      profile: None,
      repo: "/repo".into(),
      branch: "main".into(),
      skills: Vec::new(),
      procs: vec![
        ProcRecord {
          index: 0,
          label: "done".into(),
          kind: ProcKind::Skill,
          status: ProcStatus::Ok,
          skill_name: None,
          harness: None,
          model: None,
          started_at: None,
          note: None,
          detail: None,
          elapsed: None,
          lines: Vec::new(),
          container_name: None,
        },
        ProcRecord {
          index: 1,
          label: "still going".into(),
          kind: ProcKind::Skill,
          status: ProcStatus::Waiting,
          skill_name: None,
          harness: None,
          model: None,
          started_at: None,
          note: None,
          detail: None,
          elapsed: None,
          lines: Vec::new(),
          container_name: None,
        },
      ],
      last_seen_at: 1,
      client_connected: true,
    };
    assert!(session.has_incomplete_procs());
    assert_eq!(session.lifecycle_status(2), SessionLifecycle::Running);
  }

  #[test]
  fn sessions_for_index_puts_running_first_then_recent() {
    let running = Session {
      id: "run".into(),
      started_at: 10,
      ended_at: None,
      profile: None,
      repo: "/r".into(),
      branch: "main".into(),
      skills: Vec::new(),
      procs: Vec::new(),
      last_seen_at: 100,
      client_connected: true,
    };
    let done = Session {
      id: "done".into(),
      started_at: 200,
      ended_at: Some(250),
      profile: None,
      repo: "/r".into(),
      branch: "main".into(),
      skills: Vec::new(),
      procs: Vec::new(),
      last_seen_at: 250,
      client_connected: false,
    };
    let mut sessions = BTreeMap::new();
    sessions.insert(done.id.clone(), done);
    sessions.insert(running.id.clone(), running);
    let ordered = sessions_for_index(&sessions, 100);
    assert_eq!(ordered.len(), 2);
    assert_eq!(ordered[0].id, "run");
    assert_eq!(ordered[1].id, "done");
  }

  #[test]
  fn insert_session_evicts_oldest_when_over_cap() {
    let mut store = Store::new(DaemonMode::Persistent, DEFAULT_PORT, 0);
    for i in 0..=MAX_STORED_SESSIONS {
      store.insert_session(
        format!("{i:06}"),
        Session {
          id: format!("{i:06}"),
          started_at: i as u64,
          ended_at: None,
          profile: None,
          repo: "/r".into(),
          branch: "main".into(),
          skills: Vec::new(),
          procs: Vec::new(),
          last_seen_at: i as u64,
          client_connected: false,
        },
      );
    }
    assert_eq!(store.sessions.len(), MAX_STORED_SESSIONS);
    assert!(!store.sessions.contains_key("000000"));
    assert!(store.sessions.contains_key(&format!("{MAX_STORED_SESSIONS:06}")));
  }

  #[test]
  fn session_id_is_six_lowercase_letters() {
    let id = crate::runtime::random_nonce_6();
    assert_eq!(id.len(), 6);
    assert!(id.chars().all(|c| c.is_ascii_lowercase()));
  }

  #[test]
  fn ephemeral_shutdown_after_idle() {
    let now = 1_000_000;
    let mut store = Store::new(DaemonMode::Ephemeral, DEFAULT_PORT, now);
    store.reconcile(now + 100);
    assert!(!store.should_shutdown_ephemeral(now + 100));
    assert!(!store.should_shutdown_ephemeral(now + EPHEMERAL_IDLE_SECS - 1));
    assert!(store.should_shutdown_ephemeral(now + EPHEMERAL_IDLE_SECS));
  }

  #[test]
  fn terminated_client_not_counted_alive() {
    let now = 100;
    let mut store = Store::new(DaemonMode::Ephemeral, DEFAULT_PORT, now);
    store.insert_session(
      "stale".into(),
      Session {
        id: "stale".into(),
        started_at: now,
        ended_at: None,
        profile: None,
        repo: "/r".into(),
        branch: "main".into(),
        skills: Vec::new(),
        procs: Vec::new(),
        last_seen_at: now,
        client_connected: true,
      },
    );
    assert_eq!(store.alive_clients(now + SESSION_STALE_SECS), 1);
    assert_eq!(store.alive_clients(now + SESSION_STALE_SECS + 1), 0);
    store.reconcile(now + SESSION_STALE_SECS + 1);
    assert_eq!(store.active_clients, 0);
    assert!(store.no_alive_since.is_some());
  }

  #[test]
  fn ephemeral_countdown_after_no_alive_grace() {
    let now = 0;
    let store = Store::new(DaemonMode::Ephemeral, DEFAULT_PORT, now);
    assert!(store.ephemeral_shutdown_in_secs(now + EPHEMERAL_COUNTDOWN_AFTER_SECS - 1).is_none());
    assert_eq!(
      store.ephemeral_shutdown_in_secs(now + EPHEMERAL_COUNTDOWN_AFTER_SECS),
      Some(EPHEMERAL_IDLE_SECS - EPHEMERAL_COUNTDOWN_AFTER_SECS)
    );
    assert_eq!(store.ephemeral_shutdown_in_secs(now + EPHEMERAL_IDLE_SECS), Some(0));
  }

  #[test]
  fn persistent_never_auto_shutdown() {
    let store = Store::new(DaemonMode::Persistent, DEFAULT_PORT, 0);
    assert!(!store.should_shutdown_ephemeral(u64::MAX));
  }
}