atman-runtime 1.12.1

atman flow execution runtime: evaluator, tool dispatch, provider dispatch, executor, memory stores
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
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
use std::path::PathBuf;
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use super::MemoryId;
use crate::error::RuntimeError;
use crate::index::AnchorIndex;

const PHASES: &[&str] = &[
    "research",
    "design",
    "implementation",
    "testing",
    "retrospective",
];

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SpecEntry {
    pub id: MemoryId,
    pub feature: String,
    pub phase: String,
    pub content: String,
    pub ts: chrono::DateTime<chrono::Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SpecDeviation {
    pub id: MemoryId,
    pub feature: String,
    pub section: String,
    pub delta: String,
    pub reason: String,
    pub ts: chrono::DateTime<chrono::Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SpecReview {
    pub feature: String,
    pub design_revision: String,
    pub approved: bool,
    pub ts: chrono::DateTime<chrono::Utc>,
}

#[derive(Clone)]
pub struct SpecStore {
    root: PathBuf,
    anchor_index: Option<Arc<AnchorIndex>>,
}

impl SpecStore {
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            root: root.into(),
            anchor_index: None,
        }
    }

    pub fn with_index(mut self, index: Arc<AnchorIndex>) -> Self {
        self.anchor_index = Some(index);
        self
    }

    fn feature_dir(&self, feature: &str) -> PathBuf {
        self.root.join(feature)
    }

    fn entries_path(&self, feature: &str) -> PathBuf {
        self.feature_dir(feature).join("entries.jsonl")
    }

    fn deviations_path(&self, feature: &str) -> PathBuf {
        self.feature_dir(feature).join("deviations.jsonl")
    }

    fn reviews_path(&self, feature: &str) -> PathBuf {
        self.feature_dir(feature).join("reviews.jsonl")
    }

    pub async fn design_revision(&self, feature: &str) -> Result<Option<String>, RuntimeError> {
        let entries = self.entries(feature).await?;
        if !entries.iter().any(|entry| entry.phase == "design") {
            return Ok(None);
        }
        Ok(Some(revision_for(&render_phase_markdown(
            feature, "design", &entries,
        ))))
    }

    pub async fn phase_markdown(&self, feature: &str, phase: &str) -> Result<String, RuntimeError> {
        validate_feature(feature)?;
        if !PHASES.contains(&phase) {
            return Err(RuntimeError::ToolFailed(format!(
                "spec.read: unknown phase `{phase}`"
            )));
        }
        let entries = self.entries(feature).await?;
        Ok(render_phase_markdown(feature, phase, &entries))
    }

    pub async fn phase_revision(
        &self,
        feature: &str,
        phase: &str,
    ) -> Result<Option<String>, RuntimeError> {
        let entries = self.entries(feature).await?;
        if !entries.iter().any(|entry| entry.phase == phase) {
            return Ok(None);
        }
        Ok(Some(revision_for(
            &self.phase_markdown(feature, phase).await?,
        )))
    }

    pub async fn materialized_revision(
        &self,
        feature: &str,
        phase: &str,
    ) -> Result<String, RuntimeError> {
        validate_feature(feature)?;
        if !PHASES.contains(&phase) {
            return Err(RuntimeError::ToolFailed(format!(
                "spec.read: unknown phase `{phase}`"
            )));
        }
        let filename = if phase == "implementation" {
            "IMPLEMENTATION.md".to_owned()
        } else {
            format!("{phase}.md")
        };
        let path = self.feature_dir(feature).join(filename);
        match tokio::fs::read_to_string(path).await {
            Ok(content) => Ok(revision_for(&content)),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
            Err(error) => Err(RuntimeError::ToolFailed(format!(
                "spec.read: materialized file: {error}"
            ))),
        }
    }

    pub async fn review(
        &self,
        feature: &str,
        design_revision: &str,
        approved: bool,
    ) -> Result<SpecReview, RuntimeError> {
        if self.design_revision(feature).await?.as_deref() != Some(design_revision) {
            return Err(RuntimeError::ToolFailed(
                "spec.review: design revision is missing or stale".into(),
            ));
        }
        let file_revision = self.materialized_revision(feature, "design").await?;
        if file_revision != design_revision {
            return Err(RuntimeError::ToolFailed(
                "spec.review: materialized design differs from the current revision".into(),
            ));
        }
        let review = SpecReview {
            feature: feature.into(),
            design_revision: design_revision.into(),
            approved,
            ts: chrono::Utc::now(),
        };
        super::append_jsonl(&self.reviews_path(feature), &review).await?;
        Ok(review)
    }

    pub async fn status(&self, feature: &str) -> Result<SpecStatus, RuntimeError> {
        validate_feature(feature)?;
        let entries: Vec<SpecEntry> = super::read_jsonl(&self.entries_path(feature)).await?;
        if entries.is_empty() {
            return Ok(SpecStatus {
                feature: feature.into(),
                phase: "not_started".into(),
                entry_count: 0,
                deviation_count: 0,
                design_revision: None,
                approved_design_revision: None,
            });
        }
        let latest = latest_phase(&entries);
        let dev_count = super::read_jsonl::<SpecDeviation>(&self.deviations_path(feature))
            .await?
            .len();
        let design_revision = entries
            .iter()
            .any(|entry| entry.phase == "design")
            .then(|| revision_for(&render_phase_markdown(feature, "design", &entries)));
        let reviews: Vec<SpecReview> = super::read_jsonl(&self.reviews_path(feature)).await?;
        let materialized_revision = self.materialized_revision(feature, "design").await?;
        let approved_design_revision =
            reviews
                .last()
                .filter(|review| review.approved)
                .and_then(|review| {
                    (design_revision.as_deref() == Some(review.design_revision.as_str())
                        && materialized_revision == review.design_revision)
                        .then(|| review.design_revision.clone())
                });
        Ok(SpecStatus {
            feature: feature.into(),
            phase: latest,
            entry_count: entries.len(),
            deviation_count: dev_count,
            design_revision,
            approved_design_revision,
        })
    }

    pub async fn update(
        &self,
        feature: &str,
        phase: &str,
        content: String,
    ) -> Result<SpecEntry, RuntimeError> {
        if !PHASES.contains(&phase) {
            return Err(RuntimeError::ToolFailed(format!(
                "spec.update: unknown phase `{phase}` (want one of {})",
                PHASES.join(", ")
            )));
        }
        let current = self.status(feature).await?;
        if let Err(msg) = check_phase_transition(&current.phase, phase) {
            return Err(RuntimeError::ToolFailed(format!("spec.update: {msg}")));
        }
        let entry = SpecEntry {
            id: MemoryId::now(),
            feature: feature.into(),
            phase: phase.into(),
            content,
            ts: chrono::Utc::now(),
        };
        super::append_jsonl(&self.entries_path(feature), &entry).await?;
        if let Some(idx) = &self.anchor_index
            && let Err(e) = insert_entry(idx, &entry)
        {
            let key = format!("spec.index.entry:{}", entry.id);
            crate::notify!(
                warn,
                location = Inline,
                stack = dedupe(key, 60_000),
                "spec entry index insert failed (id={}): {e}",
                entry.id
            );
        }
        Ok(entry)
    }

    pub async fn deviate(
        &self,
        feature: &str,
        section: String,
        delta: String,
        reason: String,
    ) -> Result<SpecDeviation, RuntimeError> {
        let current = self.status(feature).await?;
        if current.phase == "not_started" {
            return Err(RuntimeError::ToolFailed(
                "spec.deviate: feature has no entries yet, run spec.update first".into(),
            ));
        }
        let dev = SpecDeviation {
            id: MemoryId::now(),
            feature: feature.into(),
            section,
            delta,
            reason,
            ts: chrono::Utc::now(),
        };
        super::append_jsonl(&self.deviations_path(feature), &dev).await?;
        if let Some(idx) = &self.anchor_index
            && let Err(e) = insert_deviation(idx, &dev)
        {
            let key = format!("spec.index.deviation:{}", dev.id);
            crate::notify!(
                warn,
                location = Inline,
                stack = dedupe(key, 60_000),
                "spec deviation index insert failed (id={}): {e}",
                dev.id
            );
        }
        Ok(dev)
    }

    pub async fn deviations(&self, feature: &str) -> Result<Vec<SpecDeviation>, RuntimeError> {
        validate_feature(feature)?;
        super::read_jsonl(&self.deviations_path(feature)).await
    }

    pub async fn entries(&self, feature: &str) -> Result<Vec<SpecEntry>, RuntimeError> {
        validate_feature(feature)?;
        super::read_jsonl(&self.entries_path(feature)).await
    }
}

fn insert_entry(index: &AnchorIndex, entry: &SpecEntry) -> rusqlite::Result<()> {
    let conn = index.conn();
    conn.execute(
        "INSERT OR REPLACE INTO spec_entries (id, feature, phase, content, ts) VALUES (?, ?, ?, ?, ?)",
        rusqlite::params![
            entry.id.to_string(),
            entry.feature,
            entry.phase,
            entry.content,
            entry.ts.to_rfc3339(),
        ],
    )?;
    let rowid = conn.last_insert_rowid();
    conn.execute(
        "INSERT OR REPLACE INTO spec_entries_fts (rowid, content) VALUES (?, ?)",
        rusqlite::params![rowid, entry.content],
    )?;
    Ok(())
}

fn insert_deviation(index: &AnchorIndex, dev: &SpecDeviation) -> rusqlite::Result<()> {
    let conn = index.conn();
    conn.execute(
        "INSERT OR REPLACE INTO spec_deviations (id, feature, section, delta, reason, ts) VALUES (?, ?, ?, ?, ?, ?)",
        rusqlite::params![
            dev.id.to_string(),
            dev.feature,
            dev.section,
            dev.delta,
            dev.reason,
            dev.ts.to_rfc3339(),
        ],
    )?;
    let rowid = conn.last_insert_rowid();
    conn.execute(
        "INSERT OR REPLACE INTO spec_deviations_fts (rowid, delta, reason) VALUES (?, ?, ?)",
        rusqlite::params![rowid, dev.delta, dev.reason],
    )?;
    Ok(())
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SpecStatus {
    pub feature: String,
    pub phase: String,
    pub entry_count: usize,
    pub deviation_count: usize,
    pub design_revision: Option<String>,
    pub approved_design_revision: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SpecMaterializeResult {
    pub path: PathBuf,
    pub revision: String,
    pub changed: bool,
}

impl SpecStore {
    pub async fn materialize(
        &self,
        feature: &str,
        expected_revision: Option<&str>,
    ) -> Result<SpecMaterializeResult, RuntimeError> {
        self.materialize_phase(feature, None, expected_revision)
            .await
    }

    pub async fn materialize_phase(
        &self,
        feature: &str,
        phase: Option<&str>,
        expected_revision: Option<&str>,
    ) -> Result<SpecMaterializeResult, RuntimeError> {
        validate_feature(feature)?;
        if let Some(phase) = phase
            && !PHASES.contains(&phase)
        {
            return Err(RuntimeError::ToolFailed(format!(
                "spec.materialize: unknown phase `{phase}`"
            )));
        }
        let entries: Vec<SpecEntry> = super::read_jsonl(&self.entries_path(feature)).await?;
        let deviations: Vec<SpecDeviation> =
            super::read_jsonl(&self.deviations_path(feature)).await?;
        let markdown = match phase {
            Some(phase) if phase != "implementation" => {
                render_phase_markdown(feature, phase, &entries)
            }
            _ => render_materialized_markdown(feature, &entries, &deviations),
        };
        let revision = revision_for(&markdown);
        let filename = match phase {
            Some(phase) if phase != "implementation" => format!("{phase}.md"),
            _ => "IMPLEMENTATION.md".into(),
        };
        let path = self.feature_dir(feature).join(filename);
        let existing = tokio::fs::read_to_string(&path).await.ok();
        if let Some(expected) = expected_revision
            && existing
                .as_deref()
                .is_some_and(|text| revision_for(text) != expected)
        {
            return Err(RuntimeError::ToolFailed(format!(
                "spec.materialize: revision conflict (expected {expected})"
            )));
        }
        if existing.as_deref() == Some(markdown.as_str()) {
            return Ok(SpecMaterializeResult {
                path,
                revision,
                changed: false,
            });
        }
        tokio::fs::create_dir_all(self.feature_dir(feature))
            .await
            .map_err(|e| {
                RuntimeError::ToolFailed(format!("spec.materialize: create feature dir: {e}"))
            })?;
        let tmp = path.with_extension("md.tmp");
        tokio::fs::write(&tmp, markdown.as_bytes())
            .await
            .map_err(|e| {
                RuntimeError::ToolFailed(format!("spec.materialize: write temp file: {e}"))
            })?;
        tokio::fs::rename(&tmp, &path).await.map_err(|e| {
            RuntimeError::ToolFailed(format!("spec.materialize: replace file: {e}"))
        })?;
        Ok(SpecMaterializeResult {
            path,
            revision,
            changed: true,
        })
    }
}

fn validate_feature(feature: &str) -> Result<(), RuntimeError> {
    if feature.is_empty()
        || feature == "."
        || feature == ".."
        || feature.contains('/')
        || feature.contains('\\')
        || feature.chars().any(char::is_control)
    {
        return Err(RuntimeError::ToolFailed(
            "spec feature must be a single directory name".into(),
        ));
    }
    Ok(())
}

fn render_phase_markdown(feature: &str, phase: &str, entries: &[SpecEntry]) -> String {
    let mut out = format!("# {phase} — {feature}\n\n");
    for entry in entries.iter().filter(|entry| entry.phase == phase) {
        out.push_str(&format!("## {}\n\n{}\n\n", entry.id.0, entry.content));
    }
    out
}

fn revision_for(text: &str) -> String {
    use sha2::{Digest, Sha256};
    let digest = Sha256::digest(text.as_bytes());
    digest[..8]
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

fn render_materialized_markdown(
    feature: &str,
    entries: &[SpecEntry],
    deviations: &[SpecDeviation],
) -> String {
    let mut out = format!("# Implementation — {feature}\n\n");
    for entry in entries {
        out.push_str(&format!(
            "## {} — {}\n\n{}\n\n",
            entry.phase, entry.id.0, entry.content
        ));
    }
    if !deviations.is_empty() {
        out.push_str("## Deviations\n\n");
        for deviation in deviations {
            out.push_str(&format!(
                "- **{}**: {} — {}\n",
                deviation.section, deviation.delta, deviation.reason
            ));
        }
    }
    out
}

fn latest_phase(entries: &[SpecEntry]) -> String {
    let mut best = 0usize;
    for e in entries {
        if let Some(idx) = PHASES.iter().position(|p| *p == e.phase.as_str())
            && idx + 1 > best
        {
            best = idx + 1;
        }
    }
    if best == 0 {
        "not_started".into()
    } else {
        PHASES[best - 1].into()
    }
}

fn check_phase_transition(current: &str, next: &str) -> Result<(), String> {
    let cur_idx = PHASES.iter().position(|p| *p == current).unwrap_or(0);
    let next_idx = PHASES
        .iter()
        .position(|p| *p == next)
        .ok_or_else(|| format!("unknown phase `{next}`"))?;
    let is_first = current == "not_started";
    if is_first && next != PHASES[0] {
        return Err(format!(
            "phase gate: must start with `{}`, not `{next}`",
            PHASES[0]
        ));
    }
    if !is_first && next_idx > cur_idx + 1 {
        return Err(format!(
            "phase gate: cannot skip from `{current}` to `{next}` (must go through {})",
            PHASES[cur_idx + 1]
        ));
    }
    Ok(())
}

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

    async fn store() -> (SpecStore, tempfile::TempDir) {
        let dir = tempfile::tempdir().unwrap();
        let store = SpecStore::new(dir.path().to_path_buf());
        (store, dir)
    }

    #[tokio::test]
    async fn new_feature_status_is_not_started() {
        let (s, _dir) = store().await;
        let st = s.status("x").await.unwrap();
        assert_eq!(st.phase, "not_started");
        assert_eq!(st.entry_count, 0);
    }

    #[tokio::test]
    async fn materialize_is_idempotent_and_detects_revision_conflicts() {
        let (s, dir) = store().await;
        s.update("x", "research", "notes".into()).await.unwrap();
        let first = s.materialize("x", None).await.unwrap();
        assert!(first.changed);
        assert!(first.path.exists());
        let second = s.materialize("x", Some(&first.revision)).await.unwrap();
        assert!(!second.changed);
        assert_eq!(first.revision, second.revision);
        tokio::fs::write(&first.path, "user edit\n").await.unwrap();
        let error = s.materialize("x", Some(&first.revision)).await.unwrap_err();
        assert!(error.to_string().contains("revision conflict"));
        assert_eq!(
            tokio::fs::read_to_string(dir.path().join("x/IMPLEMENTATION.md"))
                .await
                .unwrap(),
            "user edit\n"
        );
    }

    #[tokio::test]
    async fn materialize_phase_keeps_phase_documents_in_the_store() {
        let (s, dir) = store().await;
        s.update("x", "research", "Observed behavior".into())
            .await
            .unwrap();
        s.update("x", "design", "Chosen design".into())
            .await
            .unwrap();
        let research = s
            .materialize_phase("x", Some("research"), None)
            .await
            .unwrap();
        let design = s
            .materialize_phase("x", Some("design"), None)
            .await
            .unwrap();
        assert_eq!(research.path, dir.path().join("x/research.md"));
        assert_eq!(design.path, dir.path().join("x/design.md"));
        assert!(
            tokio::fs::read_to_string(&research.path)
                .await
                .unwrap()
                .contains("Observed behavior")
        );
        assert!(
            !tokio::fs::read_to_string(&research.path)
                .await
                .unwrap()
                .contains("Chosen design")
        );
        assert!(
            tokio::fs::read_to_string(&design.path)
                .await
                .unwrap()
                .contains("Chosen design")
        );
        assert_eq!(
            s.materialize_phase("x", Some("implementation"), None)
                .await
                .unwrap()
                .path,
            dir.path().join("x/IMPLEMENTATION.md")
        );
    }

    #[tokio::test]
    async fn feature_cannot_escape_spec_root() {
        let (s, _dir) = store().await;
        assert!(s.status("../outside").await.is_err());
        assert!(s.materialize("..", None).await.is_err());
    }

    #[tokio::test]
    async fn update_advances_phase() {
        let (s, _dir) = store().await;
        s.update("x", "research", "notes".into()).await.unwrap();
        assert_eq!(s.status("x").await.unwrap().phase, "research");
        s.update("x", "design", "spec".into()).await.unwrap();
        assert_eq!(s.status("x").await.unwrap().phase, "design");
    }

    #[tokio::test]
    async fn approval_tracks_only_the_current_design_revision() {
        let (s, dir) = store().await;
        s.update("x", "research", "observations".into())
            .await
            .unwrap();
        s.update("x", "design", "first design".into())
            .await
            .unwrap();
        s.materialize_phase("x", Some("design"), Some(""))
            .await
            .unwrap();
        let first = s.status("x").await.unwrap().design_revision.unwrap();
        assert!(s.review("x", "stale", true).await.is_err());
        s.review("x", &first, true).await.unwrap();
        assert_eq!(
            s.status("x").await.unwrap().approved_design_revision,
            Some(first.clone())
        );
        s.update("x", "design", "changed design".into())
            .await
            .unwrap();
        assert_eq!(s.status("x").await.unwrap().approved_design_revision, None);
        s.materialize_phase("x", Some("design"), Some(&first))
            .await
            .unwrap();
        let second = s.status("x").await.unwrap().design_revision.unwrap();
        s.review("x", &second, false).await.unwrap();
        assert_eq!(s.status("x").await.unwrap().approved_design_revision, None);
        s.review("x", &second, true).await.unwrap();
        assert_eq!(
            s.status("x").await.unwrap().approved_design_revision,
            Some(second)
        );
        tokio::fs::write(dir.path().join("x/design.md"), "external edit")
            .await
            .unwrap();
        assert_eq!(s.status("x").await.unwrap().approved_design_revision, None);
    }

    #[tokio::test]
    async fn phase_gate_rejects_skip() {
        let (s, _dir) = store().await;
        let err = s
            .update("x", "implementation", "premature".into())
            .await
            .unwrap_err();
        assert!(format!("{err}").contains("must start with `research`"));
    }

    #[tokio::test]
    async fn phase_gate_rejects_backwards() {
        let (s, _dir) = store().await;
        s.update("x", "research", "r".into()).await.unwrap();
        s.update("x", "design", "d".into()).await.unwrap();
        let err = s
            .update("x", "testing", "premature".into())
            .await
            .unwrap_err();
        assert!(format!("{err}").contains("cannot skip"), "err: {err}");
    }

    #[tokio::test]
    async fn deviate_requires_prior_entry() {
        let (s, _dir) = store().await;
        let err = s
            .deviate("x", "sec".into(), "delta".into(), "why".into())
            .await
            .unwrap_err();
        assert!(format!("{err}").contains("no entries"));
    }

    #[tokio::test]
    async fn deviate_appends_to_deviations_file() {
        let (s, _dir) = store().await;
        s.update("x", "research", "r".into()).await.unwrap();
        s.update("x", "design", "d".into()).await.unwrap();
        s.deviate(
            "x",
            "data".into(),
            "added field".into(),
            "need array".into(),
        )
        .await
        .unwrap();
        s.deviate("x", "algo".into(), "changed loop".into(), "perf".into())
            .await
            .unwrap();
        let devs = s.deviations("x").await.unwrap();
        assert_eq!(devs.len(), 2);
        assert_eq!(s.status("x").await.unwrap().deviation_count, 2);
    }

    #[tokio::test]
    async fn update_and_deviate_dual_write_to_index() {
        let dir = tempfile::tempdir().unwrap();
        let index = std::sync::Arc::new(AnchorIndex::open_project(dir.path()).unwrap());
        let s = SpecStore::new(dir.path().to_path_buf()).with_index(index.clone());
        s.update(
            "feat_x",
            "research",
            "supercalifragilistic research notes".into(),
        )
        .await
        .unwrap();
        s.update(
            "feat_x",
            "design",
            "midordermetamorphosis design notes".into(),
        )
        .await
        .unwrap();
        s.deviate(
            "feat_x",
            "sec".into(),
            "hyperloquacious delta text".into(),
            "quintessentialpolyphony reason text".into(),
        )
        .await
        .unwrap();

        let conn = index.conn();
        let entry_count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM spec_entries",
                rusqlite::params![],
                |r| r.get(0),
            )
            .unwrap();
        let dev_count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM spec_deviations",
                rusqlite::params![],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(entry_count, 2);
        assert_eq!(dev_count, 1);

        let entry_fts: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM spec_entries_fts WHERE spec_entries_fts MATCH ?",
                rusqlite::params!["supercalifragilistic"],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(entry_fts, 1);

        let dev_fts: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM spec_deviations_fts WHERE spec_deviations_fts MATCH ?",
                rusqlite::params!["quintessentialpolyphony"],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(dev_fts, 1);
    }

    #[tokio::test]
    async fn unknown_phase_rejected() {
        let (s, _dir) = store().await;
        let err = s.update("x", "brainstorm", "n".into()).await.unwrap_err();
        assert!(format!("{err}").contains("unknown phase"));
    }
}