sdd-layer 0.25.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
//! Aprovação de gates (SDD-OAD-008).
//!
//! Regras inegociáveis (Tech Spec v2 / RN-02):
//! - **default-deny**: allowlist vazia nega; autor precisa estar na allowlist do
//!   canal;
//! - **autoria separada**: o MOTOR (`engine::tick`) nunca chama este módulo —
//!   só a CLI (`sdd demand approve/reject`, SDD-OAD-012), o callback Slack
//!   verificado (SDD-OAD-014) e o modo CLI explícito `auto run --unattended`
//!   criam uma `Decision`.

use std::{fs, path::Path};

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

use crate::tui::stage::Stage;

use super::engine::{is_planning, next_stage};
use super::state::{self, Approval, Channel, DecisionKind, EngineStatus};

/// Allowlist de aprovadores por canal (carregada de `sdd.config.yaml` na CLI).
#[derive(Clone, Debug, Default, Deserialize)]
pub struct Approvers {
    #[serde(default)]
    pub cli: Vec<String>,
    #[serde(default)]
    pub slack: Vec<String>,
}

impl Approvers {
    fn list(&self, channel: Channel) -> &[String] {
        match channel {
            Channel::Cli => &self.cli,
            Channel::Slack => &self.slack,
            Channel::Automation => &[],
        }
    }
}

/// Autoriza uma decisão (default-deny). Allowlist vazia ⇒ nega.
pub fn authorize(approvers: &Approvers, channel: Channel, author: &str) -> Result<()> {
    let list = approvers.list(channel);
    if list.is_empty() {
        bail!("default-deny: nenhum aprovador configurado para o canal {channel:?}");
    }
    if !list.iter().any(|a| a == author) {
        bail!("autor '{author}' não autorizado no canal {channel:?}");
    }
    Ok(())
}

/// Efeito de uma decisão aplicada.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DecisionOutcome {
    /// Aprovado e avançou para a próxima etapa de planejamento.
    Advanced,
    /// Aprovado o último gate (Refinamento) — pronto para handoff de execução.
    ReadyForExec,
    /// Reprovado — etapa do gate reaberta para regeneração.
    Reopened,
}

/// Aplica uma decisão humana a um gate. Valida autorização e o estado atual,
/// registra a `Approval` e atualiza cursor/status + o traceability-map.
#[allow(clippy::too_many_arguments)]
pub fn apply_decision(
    root: &Path,
    slug: &str,
    gate: Stage,
    decision: DecisionKind,
    author: &str,
    channel: Channel,
    ts: &str,
    reason: Option<String>,
    approvers: &Approvers,
) -> Result<DecisionOutcome> {
    authorize(approvers, channel, author)?;
    apply_decision_recorded(root, slug, gate, decision, author, channel, ts, reason)
}

/// Aplica uma aceitação automática explícita para `sdd auto run --unattended`.
///
/// Este caminho não passa pela allowlist humana porque ele não representa uma
/// aprovação humana. A origem fica preservada em `channel: automation`.
pub fn apply_automatic_acceptance(
    root: &Path,
    slug: &str,
    gate: Stage,
    ts: &str,
    reason: Option<String>,
) -> Result<DecisionOutcome> {
    apply_decision_recorded(
        root,
        slug,
        gate,
        DecisionKind::Approve,
        "sdd-auto",
        Channel::Automation,
        ts,
        reason,
    )
}

#[allow(clippy::too_many_arguments)]
fn apply_decision_recorded(
    root: &Path,
    slug: &str,
    gate: Stage,
    decision: DecisionKind,
    author: &str,
    channel: Channel,
    ts: &str,
    reason: Option<String>,
) -> Result<DecisionOutcome> {
    let mut st = state::load(root, slug)?.ok_or_else(|| anyhow!("demanda '{slug}' sem estado"))?;
    if st.status != EngineStatus::AwaitingApproval {
        bail!("demanda '{slug}' não está aguardando aprovação");
    }
    if st.cursor != gate.key() {
        bail!(
            "gate '{}' não corresponde ao cursor '{}'",
            gate.key(),
            st.cursor
        );
    }

    st.approvals.push(Approval {
        slug: slug.to_string(),
        gate: gate.key().to_string(),
        decision,
        author: author.to_string(),
        channel,
        ts: ts.to_string(),
        reason,
    });

    let outcome = match decision {
        DecisionKind::Approve => {
            let store = crate::worktree_store_dir(root, slug);
            let filename = crate::stage_file(gate.key())
                .ok_or_else(|| anyhow!("etapa de aprovação desconhecida: {}", gate.key()))?;
            let artifact = store.join(filename);
            let content = fs::read_to_string(&artifact).map_err(|error| {
                anyhow!(
                    "lendo artefato para aprovação {}: {error}",
                    artifact.display()
                )
            })?;
            let expected = crate::sha256_hex(content.as_bytes());
            crate::persist_generated_stage_if_match(
                root,
                slug,
                gate.key(),
                &content,
                "approved",
                true,
                false,
                false,
                Some(&expected),
            )?;
            match next_stage(gate) {
                Some(next) if is_planning(next) => {
                    st.cursor = next.key().to_string();
                    st.status = EngineStatus::Orchestrating;
                    DecisionOutcome::Advanced
                }
                _ => {
                    st.status = EngineStatus::ReadyForExec;
                    DecisionOutcome::ReadyForExec
                }
            }
        }
        DecisionKind::Reject => {
            // Reabre a etapa do gate (cursor permanece) para regeneração.
            st.status = EngineStatus::Orchestrating;
            DecisionOutcome::Reopened
        }
    };

    state::save(root, &st)?;
    Ok(outcome)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::orchestrator::demand::{Demand, DemandSource, DemandType};
    use crate::domain::orchestrator::engine::{tick, FakeRunner};
    use crate::domain::orchestrator::{queue, state};

    fn approvers() -> Approvers {
        Approvers {
            cli: vec!["alan".to_string()],
            slack: vec![],
        }
    }

    fn enqueue(root: &Path) -> String {
        let d = Demand::new(
            "DEM-1",
            DemandType::Story,
            "Esteira Autônoma",
            "desc",
            DemandSource::Cli,
            None,
            "2026-06-08T00:00:00Z",
        )
        .unwrap();
        queue::enqueue(root, &d).unwrap();
        d.slug
    }

    /// Avança o motor até pausar no gate do PRD.
    fn drive_to_prd_gate(root: &Path) -> String {
        let slug = enqueue(root);
        tick(root, &FakeRunner, "tick", "t0").unwrap(); // idea
        tick(root, &FakeRunner, "tick", "t1").unwrap(); // prd → gate
        let st = state::load(root, &slug).unwrap().unwrap();
        assert_eq!(st.status, EngineStatus::AwaitingApproval);
        slug
    }

    #[test]
    fn authorize_is_default_deny() {
        let a = approvers();
        assert!(authorize(&a, Channel::Cli, "alan").is_ok());
        assert!(authorize(&a, Channel::Cli, "mallory").is_err());
        // Canal sem aprovadores configurados nega tudo.
        assert!(authorize(&a, Channel::Slack, "alan").is_err());
        assert!(authorize(&Approvers::default(), Channel::Cli, "alan").is_err());
    }

    #[test]
    fn engine_never_self_approves() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let slug = drive_to_prd_gate(root);
        let st = state::load(root, &slug).unwrap().unwrap();
        assert!(
            st.approvals.is_empty(),
            "o motor não pode criar registros de aprovação"
        );
    }

    #[test]
    fn approve_prd_advances_to_techspec() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let slug = drive_to_prd_gate(root);

        let outcome = apply_decision(
            root,
            &slug,
            Stage::Prd,
            DecisionKind::Approve,
            "alan",
            Channel::Cli,
            "t2",
            None,
            &approvers(),
        )
        .unwrap();
        assert_eq!(outcome, DecisionOutcome::Advanced);

        let st = state::load(root, &slug).unwrap().unwrap();
        assert_eq!(st.status, EngineStatus::Orchestrating);
        assert_eq!(st.cursor, "techspec");
        assert_eq!(st.approvals.len(), 1);

        let map =
            std::fs::read_to_string(root.join("docs").join(&slug).join("traceability-map.yaml"))
                .unwrap();
        let prd_block = map.split("prd:").nth(1).unwrap();
        assert!(prd_block.contains("state: approved"));
    }

    #[test]
    fn unauthorized_author_is_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let slug = drive_to_prd_gate(root);
        let err = apply_decision(
            root,
            &slug,
            Stage::Prd,
            DecisionKind::Approve,
            "mallory",
            Channel::Cli,
            "t2",
            None,
            &approvers(),
        )
        .unwrap_err();
        assert!(err.to_string().contains("não autorizado"));
        // Nenhuma aprovação registrada.
        let st = state::load(root, &slug).unwrap().unwrap();
        assert!(st.approvals.is_empty());
        assert_eq!(st.status, EngineStatus::AwaitingApproval);
    }

    #[test]
    fn approving_when_not_awaiting_fails() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let slug = enqueue(root);
        tick(root, &FakeRunner, "tick", "t0").unwrap(); // idea → Orchestrating (não awaiting)
        let err = apply_decision(
            root,
            &slug,
            Stage::Prd,
            DecisionKind::Approve,
            "alan",
            Channel::Cli,
            "t1",
            None,
            &approvers(),
        )
        .unwrap_err();
        assert!(err.to_string().contains("aguardando aprovação"));
    }

    #[test]
    fn reject_reopens_gate_for_regeneration() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let slug = drive_to_prd_gate(root);
        let outcome = apply_decision(
            root,
            &slug,
            Stage::Prd,
            DecisionKind::Reject,
            "alan",
            Channel::Cli,
            "t2",
            Some("escopo amplo demais".to_string()),
            &approvers(),
        )
        .unwrap();
        assert_eq!(outcome, DecisionOutcome::Reopened);
        let st = state::load(root, &slug).unwrap().unwrap();
        assert_eq!(st.status, EngineStatus::Orchestrating);
        assert_eq!(st.cursor, "prd", "cursor permanece para regenerar a etapa");
        assert_eq!(
            st.approvals.last().unwrap().reason.as_deref(),
            Some("escopo amplo demais")
        );
        // Próximo tick re-produz o PRD.
        let report = tick(root, &FakeRunner, "tick", "t3").unwrap();
        assert_eq!(report.produced, vec![(slug.clone(), "prd".to_string())]);
    }

    #[test]
    fn full_planning_loop_reaches_ready_for_exec() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let slug = drive_to_prd_gate(root);
        let a = approvers();

        // Aprova PRD → tick TechSpec (gate) → aprova → tick Tasks (não gate) →
        // tick Refinamento (gate) → aprova → ReadyForExec.
        assert_eq!(
            apply_decision(
                root,
                &slug,
                Stage::Prd,
                DecisionKind::Approve,
                "alan",
                Channel::Cli,
                "t2",
                None,
                &a
            )
            .unwrap(),
            DecisionOutcome::Advanced
        );
        tick(root, &FakeRunner, "tick", "t3").unwrap(); // techspec → gate
        assert_eq!(
            apply_decision(
                root,
                &slug,
                Stage::Techspec,
                DecisionKind::Approve,
                "alan",
                Channel::Cli,
                "t4",
                None,
                &a
            )
            .unwrap(),
            DecisionOutcome::Advanced
        );
        tick(root, &FakeRunner, "tick", "t5").unwrap(); // tasks (não gate) → cursor refinement
        let st = state::load(root, &slug).unwrap().unwrap();
        assert_eq!(st.cursor, "refinement");
        assert_eq!(st.status, EngineStatus::Orchestrating);
        tick(root, &FakeRunner, "tick", "t6").unwrap(); // refinement → gate
        assert_eq!(
            apply_decision(
                root,
                &slug,
                Stage::Refinement,
                DecisionKind::Approve,
                "alan",
                Channel::Cli,
                "t7",
                None,
                &a
            )
            .unwrap(),
            DecisionOutcome::ReadyForExec
        );

        let st = state::load(root, &slug).unwrap().unwrap();
        assert_eq!(st.status, EngineStatus::ReadyForExec);
        assert_eq!(st.approvals.len(), 3);

        let dest = root.join("docs").join(&slug);
        for f in [
            "01-idea.md",
            "02-prd.md",
            "03-techspec.md",
            "04-tasks.md",
            "05-refinement.md",
        ] {
            assert!(dest.join(f).is_file(), "faltou {f}");
        }
    }
}