sdd-layer 0.24.0

Spec-Driven Development CLI and agent harness
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
589
590
591
592
593
594
595
//! Estado durável do motor por demanda em `.sdd/state/<slug>.json` (SDD-OAD-004).
//!
//! Decisões da Tech Spec v2 honradas aqui:
//! - **Fonte primária de verdade** do motor (cursor, status, lock, approvals);
//! - escrita **atômica** (write-temp + rename) e `schema_version` obrigatório;
//! - **Opção A**: os estados ricos (`awaiting_approval`/`ready_for_exec`/`manual:*`)
//!   vivem SÓ aqui; o campo por-artefato do traceability-map nunca os recebe
//!   (ver `artifact_state_for_status`).

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};

use super::demand::validate_slug;

/// Versão do schema de estado. Incrementar exige rotina de migração.
pub const STATE_SCHEMA_VERSION: u32 = 1;

/// Status operacional rico do motor (vive só no `.sdd/state`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EngineStatus {
    Queued,
    Orchestrating,
    AwaitingApproval,
    ReadyForExec,
    Completed,
    Paused,
    Error,
    /// Etapa que precisa de preenchimento manual (provider sem headless).
    Manual(String),
    /// Modo card: Memory concluída + worktrees mergeados → aguarda validação manual
    /// no branch card-id antes de decidir entre ajuste (rework) ou PR final.
    ReadyForTesting,
}

impl EngineStatus {
    pub fn to_repr(&self) -> String {
        match self {
            Self::Queued => "queued".to_string(),
            Self::Orchestrating => "orchestrating".to_string(),
            Self::AwaitingApproval => "awaiting_approval".to_string(),
            Self::ReadyForExec => "ready_for_exec".to_string(),
            Self::Completed => "completed".to_string(),
            Self::Paused => "paused".to_string(),
            Self::Error => "error".to_string(),
            Self::Manual(stage) => format!("manual:{stage}"),
            Self::ReadyForTesting => "ready_for_testing".to_string(),
        }
    }

    pub fn from_repr(value: &str) -> std::result::Result<Self, String> {
        if let Some(stage) = value.strip_prefix("manual:") {
            if stage.is_empty() {
                return Err("status manual sem etapa".to_string());
            }
            return Ok(Self::Manual(stage.to_string()));
        }
        match value {
            "queued" => Ok(Self::Queued),
            "orchestrating" => Ok(Self::Orchestrating),
            "awaiting_approval" => Ok(Self::AwaitingApproval),
            "ready_for_exec" => Ok(Self::ReadyForExec),
            "completed" => Ok(Self::Completed),
            "paused" => Ok(Self::Paused),
            "error" => Ok(Self::Error),
            "ready_for_testing" => Ok(Self::ReadyForTesting),
            other => Err(format!("status de motor inválido: {other}")),
        }
    }
}

impl From<EngineStatus> for String {
    fn from(value: EngineStatus) -> Self {
        value.to_repr()
    }
}

impl TryFrom<String> for EngineStatus {
    type Error = String;
    fn try_from(value: String) -> std::result::Result<Self, String> {
        EngineStatus::from_repr(&value)
    }
}

/// Decisão sobre um gate (humana por padrão; automação explícita em modo unattended).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DecisionKind {
    Approve,
    Reject,
}

/// Canal pelo qual a decisão chegou.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Channel {
    Cli,
    Slack,
    Automation,
}

/// Registro de aprovação/reprovação de um gate. Inclui `slug` para correlação.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Approval {
    pub slug: String,
    pub gate: String,
    pub decision: DecisionKind,
    pub author: String,
    pub channel: Channel,
    pub ts: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// Estado durável por task de Execution. É preenchido progressivamente pelo
/// motor/runner e mantido compatível com estados antigos via `default`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TaskExecutionState {
    pub status: String,
    #[serde(default)]
    pub attempts: u32,
    #[serde(default)]
    pub evidence: Vec<String>,
    #[serde(default)]
    pub tests: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_error: Option<String>,
}

/// Lock por demanda — impede avanço concorrente da mesma demanda.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Lock {
    pub owner: String,
    pub acquired_at: String,
}

/// Modo de orquestração. Define se há maquinaria de card (Jira/Confluence/colunas)
/// ou se é um fluxo de texto-livre isolado em worktree próprio sem integrações.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OrchestrationMode {
    /// Card-id: worktree `<card>`, branch `<card>`, side-effects de Jira/Confluence.
    Card,
    /// Texto-livre: worktree `<slug>`, branch `<slug>`, sem integrações externas.
    #[default]
    FreeText,
}

/// Metadados de integração do card (modo `Card`). Preenchidos pelo agente via
/// `sdd card meta` — a CLI é o registro de verdade; o MCP só o agente acessa.
/// Lido por `next`/`done` para impor pré-condições (publicar Confluence, mover
/// coluna por ordem) com rigor "bloquear e refazer".
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CardMeta {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub space_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confluence_parent_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub assignee: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start_date: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub due_date: Option<String>,
    /// Mapeamento nome-da-transição → transition_id (resolvido uma vez no setup).
    #[serde(default)]
    pub transitions: BTreeMap<String, String>,
    /// Mapeamento índice-de-coluna (string, ex.: "1".."6") → transition_id.
    /// O agente move o card POR ORDEM, nunca por nome de coluna.
    #[serde(default)]
    pub columns: BTreeMap<String, String>,
}

/// Estado durável do motor para uma demanda.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EngineState {
    pub schema_version: u32,
    pub slug: String,
    /// Etapa corrente (stage key, ex.: "idea", "prd").
    pub cursor: String,
    #[serde(with = "engine_status_serde")]
    pub status: EngineStatus,
    /// Modo da orquestração (card vs texto-livre). Estados antigos sem o campo
    /// desserializam como `FreeText` via `#[serde(default)]`.
    #[serde(default)]
    pub mode: OrchestrationMode,
    /// Branch a partir do qual o worktree foi criado (destino do PR).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub branch_raiz: Option<String>,
    /// Branch intermediário `<CARD-ID>` criado a partir de `develop` (ou do branch-raiz
    /// solicitado). Os worktrees de subtask derivam deste branch; é aqui que os
    /// worktrees são mergeados após Memory para validação manual antes do PR.
    /// Exclusivo do modo card; None em texto-livre.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub card_branch: Option<String>,
    /// Metadados de card (só no modo `Card`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub card: Option<CardMeta>,
    /// Decisão explícita do usuário sobre uso de git worktrees (pergunta
    /// obrigatória no setup). `Some(false)` = fluxo direto no branch `<key>`,
    /// sem `.worktree/`. `None` em estados antigos (que sempre usavam worktree).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub use_worktrees: Option<bool>,
    /// Obrigações pós-aprovação pendentes (chaves de evidência que o agente
    /// precisa cumprir antes de prosseguir — ex.: `confluence`, `column`, `pr`).
    /// Populadas por `approve`, exigidas e limpas por `confirm`. Garante o rigor
    /// "bloquear e refazer" para side-effects que ocorrem após o checkpoint.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub pending_obligations: Vec<String>,
    /// Coluna-alvo do board (índice 1..6) quando há obrigação `column` pendente.
    /// O transition_id real vem de `CardMeta.columns[N]`; aqui guardamos só o N.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pending_column: Option<u8>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lock: Option<Lock>,
    #[serde(default)]
    pub approvals: Vec<Approval>,
    #[serde(default)]
    pub attempts: BTreeMap<String, u32>,
    #[serde(default)]
    pub tasks: BTreeMap<String, TaskExecutionState>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_error: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_tick: Option<String>,
}

mod engine_status_serde {
    use super::EngineStatus;
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S: Serializer>(value: &EngineStatus, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(&value.to_repr())
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<EngineStatus, D::Error> {
        let raw = String::deserialize(d)?;
        EngineStatus::from_repr(&raw).map_err(serde::de::Error::custom)
    }
}

impl EngineState {
    /// Cria o estado inicial de uma demanda (cursor = `idea`, status `Queued`).
    pub fn new(slug: impl Into<String>) -> Result<Self> {
        let slug = slug.into();
        validate_slug(&slug)?;
        Ok(Self {
            schema_version: STATE_SCHEMA_VERSION,
            slug,
            cursor: "idea".to_string(),
            status: EngineStatus::Queued,
            mode: OrchestrationMode::default(),
            branch_raiz: None,
            card_branch: None,
            card: None,
            use_worktrees: None,
            pending_obligations: Vec::new(),
            pending_column: None,
            lock: None,
            approvals: Vec::new(),
            attempts: BTreeMap::new(),
            tasks: BTreeMap::new(),
            last_error: None,
            last_tick: None,
        })
    }
}

/// Diretório de estado para um root de projeto.
pub fn state_dir(root: &Path) -> PathBuf {
    root.join(".sdd").join("state")
}

fn state_path(root: &Path, slug: &str) -> Result<PathBuf> {
    validate_slug(slug)?;
    Ok(state_dir(root).join(format!("{slug}.json")))
}

/// Persiste o estado de forma atômica.
pub fn save(root: &Path, state: &EngineState) -> Result<()> {
    if state.schema_version != STATE_SCHEMA_VERSION {
        bail!(
            "schema_version de estado não suportado ao salvar: {} (esperado {})",
            state.schema_version,
            STATE_SCHEMA_VERSION
        );
    }
    let path = state_path(root, &state.slug)?;
    let body = serde_json::to_string_pretty(state).context("serializando estado do motor")?;
    super::write_atomic(&path, body.as_bytes())
}

/// Lista todos os estados persistidos em `.sdd/state/`.
#[allow(dead_code)]
pub fn list_states(root: &Path) -> Result<Vec<EngineState>> {
    let dir = state_dir(root);
    let mut out = Vec::new();
    let Ok(entries) = std::fs::read_dir(&dir) else {
        return Ok(out);
    };
    let mut paths: Vec<PathBuf> = entries
        .flatten()
        .map(|e| e.path())
        .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("json"))
        .collect();
    paths.sort();
    for path in paths {
        let text = fs_read(&path)?;
        let state: EngineState = serde_json::from_str(&text)
            .with_context(|| format!("desserializando estado {}", path.display()))?;
        if state.schema_version != STATE_SCHEMA_VERSION {
            continue; // skip incompatible versions instead of failing the list
        }
        out.push(state);
    }
    Ok(out)
}

/// Carrega o estado de uma demanda, ou `None` se não existir.
pub fn load(root: &Path, slug: &str) -> Result<Option<EngineState>> {
    let path = state_path(root, slug)?;
    if !path.exists() {
        return Ok(None);
    }
    let text = fs_read(&path)?;
    let state: EngineState = serde_json::from_str(&text)
        .with_context(|| format!("desserializando estado {}", path.display()))?;
    if state.schema_version != STATE_SCHEMA_VERSION {
        bail!(
            "schema_version de estado não suportado: {} (esperado {})",
            state.schema_version,
            STATE_SCHEMA_VERSION
        );
    }
    Ok(Some(state))
}

fn fs_read(path: &Path) -> Result<String> {
    std::fs::read_to_string(path).with_context(|| format!("lendo estado {}", path.display()))
}

/// Tenta adquirir o lock da demanda. Retorna `true` se adquirido (sem lock, ou
/// lock do mesmo `owner`), `false` se já está travado por outro owner.
/// Persiste o estado quando adquire.
pub fn acquire_lock(
    root: &Path,
    state: &mut EngineState,
    owner: impl Into<String>,
    now: impl Into<String>,
) -> Result<bool> {
    let owner = owner.into();
    if let Some(lock) = &state.lock {
        if lock.owner != owner {
            return Ok(false);
        }
    }
    state.lock = Some(Lock {
        owner,
        acquired_at: now.into(),
    });
    save(root, state)?;
    Ok(true)
}

/// Libera o lock e persiste.
pub fn release_lock(root: &Path, state: &mut EngineState) -> Result<()> {
    state.lock = None;
    save(root, state)
}

/// **Opção A**: traduz o status do motor para um valor de `state` por-artefato
/// que `StageStatus::from_yaml` entende. NUNCA retorna um estado rico.
// Guarda de invariante (testada); consumida ao espelhar status no map (SDD-OAD-014).
#[allow(dead_code)]
pub fn artifact_state_for_status(status: &EngineStatus) -> &'static str {
    match status {
        EngineStatus::ReadyForExec | EngineStatus::Completed => "approved",
        EngineStatus::Error => "recorded",
        _ => "in_progress",
    }
}

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

    fn fresh(root: &Path) -> EngineState {
        let mut st = EngineState::new("dem-1").unwrap();
        st.last_tick = Some("2026-06-08T00:00:00Z".to_string());
        save(root, &st).unwrap();
        st
    }

    #[test]
    fn new_state_defaults() {
        let st = EngineState::new("dem-1").unwrap();
        assert_eq!(st.schema_version, STATE_SCHEMA_VERSION);
        assert_eq!(st.cursor, "idea");
        assert_eq!(st.status, EngineStatus::Queued);
        assert!(st.lock.is_none());
        assert!(EngineState::new("../escape").is_err());
    }

    #[test]
    fn save_and_load_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let mut st = fresh(root);
        st.status = EngineStatus::AwaitingApproval;
        st.cursor = "prd".to_string();
        st.approvals.push(Approval {
            slug: "dem-1".to_string(),
            gate: "prd".to_string(),
            decision: DecisionKind::Approve,
            author: "alan@x".to_string(),
            channel: Channel::Cli,
            ts: "2026-06-08T01:00:00Z".to_string(),
            reason: None,
        });
        *st.attempts.entry("techspec".to_string()).or_insert(0) += 1;
        save(root, &st).unwrap();
        let back = load(root, "dem-1").unwrap().unwrap();
        assert_eq!(st, back);
        assert!(state_dir(root).join("dem-1.json").is_file());
    }

    #[test]
    fn load_missing_is_none() {
        let dir = tempfile::tempdir().unwrap();
        assert!(load(dir.path(), "nope").unwrap().is_none());
    }

    #[test]
    fn divergent_schema_version_is_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::create_dir_all(state_dir(root)).unwrap();
        let bad = r#"{ "schema_version": 99, "slug": "dem-1", "cursor": "idea",
            "status": "queued", "approvals": [], "attempts": {} }"#;
        std::fs::write(state_dir(root).join("dem-1.json"), bad).unwrap();
        assert!(load(root, "dem-1")
            .unwrap_err()
            .to_string()
            .contains("schema_version"));
    }

    #[test]
    fn lock_is_exclusive_per_owner() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let mut st = fresh(root);
        assert!(acquire_lock(root, &mut st, "tick-1", "t0").unwrap());
        // Outro owner não consegue enquanto travado.
        let mut other = load(root, "dem-1").unwrap().unwrap();
        assert!(!acquire_lock(root, &mut other, "tick-2", "t1").unwrap());
        // Mesmo owner re-adquire.
        assert!(acquire_lock(root, &mut st, "tick-1", "t2").unwrap());
        // Após liberar, outro consegue.
        release_lock(root, &mut st).unwrap();
        let mut third = load(root, "dem-1").unwrap().unwrap();
        assert!(acquire_lock(root, &mut third, "tick-2", "t3").unwrap());
    }

    #[test]
    fn status_repr_round_trip_including_manual() {
        for s in [
            EngineStatus::Queued,
            EngineStatus::AwaitingApproval,
            EngineStatus::ReadyForExec,
            EngineStatus::Manual("techspec".to_string()),
        ] {
            let repr = s.to_repr();
            assert_eq!(EngineStatus::from_repr(&repr).unwrap(), s);
        }
        assert_eq!(
            EngineStatus::Manual("techspec".to_string()).to_repr(),
            "manual:techspec"
        );
        assert!(EngineStatus::from_repr("bogus").is_err());
    }

    #[test]
    fn option_a_never_emits_rich_artifact_state() {
        let safe = ["recorded", "in_progress", "approved", "skipped"];
        for s in [
            EngineStatus::Queued,
            EngineStatus::Orchestrating,
            EngineStatus::AwaitingApproval,
            EngineStatus::ReadyForExec,
            EngineStatus::Paused,
            EngineStatus::Error,
            EngineStatus::Manual("prd".to_string()),
        ] {
            assert!(
                safe.contains(&artifact_state_for_status(&s)),
                "status {s:?} vazou estado rico para o map"
            );
        }
    }

    #[test]
    fn legacy_state_without_mode_defaults_to_free_text() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::create_dir_all(state_dir(root)).unwrap();
        // Estado antigo: sem mode/branch_raiz/card.
        let legacy = r#"{ "schema_version": 1, "slug": "dem-1", "cursor": "idea",
            "status": "queued", "approvals": [], "attempts": {} }"#;
        std::fs::write(state_dir(root).join("dem-1.json"), legacy).unwrap();
        let st = load(root, "dem-1").unwrap().unwrap();
        assert_eq!(st.mode, OrchestrationMode::FreeText);
        assert!(st.branch_raiz.is_none());
        assert!(st.card.is_none());
    }

    #[test]
    fn card_mode_and_meta_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let mut st = fresh(root);
        st.mode = OrchestrationMode::Card;
        st.branch_raiz = Some("main".to_string());
        let mut meta = CardMeta {
            space_key: Some("ENG".to_string()),
            confluence_parent_id: Some("12345".to_string()),
            ..Default::default()
        };
        meta.columns.insert("1".to_string(), "11".to_string());
        meta.transitions
            .insert("In Progress".to_string(), "11".to_string());
        st.card = Some(meta);
        save(root, &st).unwrap();
        let back = load(root, "dem-1").unwrap().unwrap();
        assert_eq!(st, back);
        assert_eq!(back.mode, OrchestrationMode::Card);
        assert_eq!(back.card.unwrap().columns.get("1").unwrap(), "11");
    }

    #[test]
    fn use_worktrees_round_trip_and_legacy_default() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let mut st = fresh(root);
        assert!(st.use_worktrees.is_none());
        st.use_worktrees = Some(false);
        save(root, &st).unwrap();
        let back = load(root, "dem-1").unwrap().unwrap();
        assert_eq!(back.use_worktrees, Some(false));
        // Estado antigo sem o campo → None (legado sempre usava worktree).
        let legacy = r#"{ "schema_version": 1, "slug": "dem-2", "cursor": "idea",
            "status": "queued", "approvals": [], "attempts": {} }"#;
        std::fs::write(state_dir(root).join("dem-2.json"), legacy).unwrap();
        assert!(load(root, "dem-2")
            .unwrap()
            .unwrap()
            .use_worktrees
            .is_none());
    }

    #[test]
    fn status_serializes_as_string_in_json() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let mut st = fresh(root);
        st.status = EngineStatus::Manual("techspec".to_string());
        save(root, &st).unwrap();
        let raw = std::fs::read_to_string(state_dir(root).join("dem-1.json")).unwrap();
        assert!(raw.contains("\"status\": \"manual:techspec\""));
    }

    #[test]
    fn list_states_returns_sorted_states() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let mut st1 = EngineState::new("alpha").unwrap();
        st1.cursor = "prd".to_string();
        save(root, &st1).unwrap();
        let mut st2 = EngineState::new("beta").unwrap();
        st2.cursor = "techspec".to_string();
        save(root, &st2).unwrap();

        let states = list_states(root).unwrap();
        assert_eq!(states.len(), 2);
        assert_eq!(states[0].slug, "alpha");
        assert_eq!(states[1].slug, "beta");
    }

    #[test]
    fn list_states_empty_when_no_state_dir() {
        let dir = tempfile::tempdir().unwrap();
        assert!(list_states(dir.path()).unwrap().is_empty());
    }
}