1use std::path::PathBuf;
2use std::sync::Arc;
3
4use serde::{Deserialize, Serialize};
5
6use super::MemoryId;
7use crate::error::RuntimeError;
8use crate::index::AnchorIndex;
9
10const PHASES: &[&str] = &[
11 "research",
12 "design",
13 "implementation",
14 "testing",
15 "retrospective",
16];
17
18#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
19pub struct SpecEntry {
20 pub id: MemoryId,
21 pub feature: String,
22 pub phase: String,
23 pub content: String,
24 pub ts: chrono::DateTime<chrono::Utc>,
25}
26
27#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
28pub struct SpecDeviation {
29 pub id: MemoryId,
30 pub feature: String,
31 pub section: String,
32 pub delta: String,
33 pub reason: String,
34 pub ts: chrono::DateTime<chrono::Utc>,
35}
36
37#[derive(Clone)]
38pub struct SpecStore {
39 root: PathBuf,
40 anchor_index: Option<Arc<AnchorIndex>>,
41}
42
43impl SpecStore {
44 pub fn new(root: impl Into<PathBuf>) -> Self {
45 Self {
46 root: root.into(),
47 anchor_index: None,
48 }
49 }
50
51 pub fn with_index(mut self, index: Arc<AnchorIndex>) -> Self {
52 self.anchor_index = Some(index);
53 self
54 }
55
56 fn feature_dir(&self, feature: &str) -> PathBuf {
57 self.root.join(feature)
58 }
59
60 fn entries_path(&self, feature: &str) -> PathBuf {
61 self.feature_dir(feature).join("entries.jsonl")
62 }
63
64 fn deviations_path(&self, feature: &str) -> PathBuf {
65 self.feature_dir(feature).join("deviations.jsonl")
66 }
67
68 pub async fn status(&self, feature: &str) -> Result<SpecStatus, RuntimeError> {
69 let entries: Vec<SpecEntry> = super::read_jsonl(&self.entries_path(feature)).await?;
70 if entries.is_empty() {
71 return Ok(SpecStatus {
72 feature: feature.into(),
73 phase: "not_started".into(),
74 entry_count: 0,
75 deviation_count: 0,
76 });
77 }
78 let latest = latest_phase(&entries);
79 let dev_count = super::read_jsonl::<SpecDeviation>(&self.deviations_path(feature))
80 .await?
81 .len();
82 Ok(SpecStatus {
83 feature: feature.into(),
84 phase: latest,
85 entry_count: entries.len(),
86 deviation_count: dev_count,
87 })
88 }
89
90 pub async fn update(
91 &self,
92 feature: &str,
93 phase: &str,
94 content: String,
95 ) -> Result<SpecEntry, RuntimeError> {
96 if !PHASES.contains(&phase) {
97 return Err(RuntimeError::ToolFailed(format!(
98 "spec.update: unknown phase `{phase}` (want one of {})",
99 PHASES.join(", ")
100 )));
101 }
102 let current = self.status(feature).await?;
103 if let Err(msg) = check_phase_transition(¤t.phase, phase) {
104 return Err(RuntimeError::ToolFailed(format!("spec.update: {msg}")));
105 }
106 let entry = SpecEntry {
107 id: MemoryId::now(),
108 feature: feature.into(),
109 phase: phase.into(),
110 content,
111 ts: chrono::Utc::now(),
112 };
113 super::append_jsonl(&self.entries_path(feature), &entry).await?;
114 if let Some(idx) = &self.anchor_index
115 && let Err(e) = insert_entry(idx, &entry)
116 {
117 let key = format!("spec.index.entry:{}", entry.id);
118 crate::notify!(
119 warn,
120 location = Inline,
121 stack = dedupe(key, 60_000),
122 "spec entry index insert failed (id={}): {e}",
123 entry.id
124 );
125 }
126 Ok(entry)
127 }
128
129 pub async fn deviate(
130 &self,
131 feature: &str,
132 section: String,
133 delta: String,
134 reason: String,
135 ) -> Result<SpecDeviation, RuntimeError> {
136 let current = self.status(feature).await?;
137 if current.phase == "not_started" {
138 return Err(RuntimeError::ToolFailed(
139 "spec.deviate: feature has no entries yet, run spec.update first".into(),
140 ));
141 }
142 let dev = SpecDeviation {
143 id: MemoryId::now(),
144 feature: feature.into(),
145 section,
146 delta,
147 reason,
148 ts: chrono::Utc::now(),
149 };
150 super::append_jsonl(&self.deviations_path(feature), &dev).await?;
151 if let Some(idx) = &self.anchor_index
152 && let Err(e) = insert_deviation(idx, &dev)
153 {
154 let key = format!("spec.index.deviation:{}", dev.id);
155 crate::notify!(
156 warn,
157 location = Inline,
158 stack = dedupe(key, 60_000),
159 "spec deviation index insert failed (id={}): {e}",
160 dev.id
161 );
162 }
163 Ok(dev)
164 }
165
166 pub async fn deviations(&self, feature: &str) -> Result<Vec<SpecDeviation>, RuntimeError> {
167 super::read_jsonl(&self.deviations_path(feature)).await
168 }
169
170 pub async fn entries(&self, feature: &str) -> Result<Vec<SpecEntry>, RuntimeError> {
171 super::read_jsonl(&self.entries_path(feature)).await
172 }
173}
174
175fn insert_entry(index: &AnchorIndex, entry: &SpecEntry) -> rusqlite::Result<()> {
176 let conn = index.conn();
177 conn.execute(
178 "INSERT OR REPLACE INTO spec_entries (id, feature, phase, content, ts) VALUES (?, ?, ?, ?, ?)",
179 rusqlite::params![
180 entry.id.to_string(),
181 entry.feature,
182 entry.phase,
183 entry.content,
184 entry.ts.to_rfc3339(),
185 ],
186 )?;
187 let rowid = conn.last_insert_rowid();
188 conn.execute(
189 "INSERT OR REPLACE INTO spec_entries_fts (rowid, content) VALUES (?, ?)",
190 rusqlite::params![rowid, entry.content],
191 )?;
192 Ok(())
193}
194
195fn insert_deviation(index: &AnchorIndex, dev: &SpecDeviation) -> rusqlite::Result<()> {
196 let conn = index.conn();
197 conn.execute(
198 "INSERT OR REPLACE INTO spec_deviations (id, feature, section, delta, reason, ts) VALUES (?, ?, ?, ?, ?, ?)",
199 rusqlite::params![
200 dev.id.to_string(),
201 dev.feature,
202 dev.section,
203 dev.delta,
204 dev.reason,
205 dev.ts.to_rfc3339(),
206 ],
207 )?;
208 let rowid = conn.last_insert_rowid();
209 conn.execute(
210 "INSERT OR REPLACE INTO spec_deviations_fts (rowid, delta, reason) VALUES (?, ?, ?)",
211 rusqlite::params![rowid, dev.delta, dev.reason],
212 )?;
213 Ok(())
214}
215
216#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
217pub struct SpecStatus {
218 pub feature: String,
219 pub phase: String,
220 pub entry_count: usize,
221 pub deviation_count: usize,
222}
223
224fn latest_phase(entries: &[SpecEntry]) -> String {
225 let mut best = 0usize;
226 for e in entries {
227 if let Some(idx) = PHASES.iter().position(|p| *p == e.phase.as_str())
228 && idx + 1 > best
229 {
230 best = idx + 1;
231 }
232 }
233 if best == 0 {
234 "not_started".into()
235 } else {
236 PHASES[best - 1].into()
237 }
238}
239
240fn check_phase_transition(current: &str, next: &str) -> Result<(), String> {
241 let cur_idx = PHASES.iter().position(|p| *p == current).unwrap_or(0);
242 let next_idx = PHASES
243 .iter()
244 .position(|p| *p == next)
245 .ok_or_else(|| format!("unknown phase `{next}`"))?;
246 let is_first = current == "not_started";
247 if is_first && next != PHASES[0] {
248 return Err(format!(
249 "phase gate: must start with `{}`, not `{next}`",
250 PHASES[0]
251 ));
252 }
253 if !is_first && next_idx > cur_idx + 1 {
254 return Err(format!(
255 "phase gate: cannot skip from `{current}` to `{next}` (must go through {})",
256 PHASES[cur_idx + 1]
257 ));
258 }
259 Ok(())
260}
261
262#[cfg(test)]
263mod tests {
264 use super::*;
265
266 async fn store() -> (SpecStore, tempfile::TempDir) {
267 let dir = tempfile::tempdir().unwrap();
268 let store = SpecStore::new(dir.path().to_path_buf());
269 (store, dir)
270 }
271
272 #[tokio::test]
273 async fn new_feature_status_is_not_started() {
274 let (s, _dir) = store().await;
275 let st = s.status("x").await.unwrap();
276 assert_eq!(st.phase, "not_started");
277 assert_eq!(st.entry_count, 0);
278 }
279
280 #[tokio::test]
281 async fn update_advances_phase() {
282 let (s, _dir) = store().await;
283 s.update("x", "research", "notes".into()).await.unwrap();
284 assert_eq!(s.status("x").await.unwrap().phase, "research");
285 s.update("x", "design", "spec".into()).await.unwrap();
286 assert_eq!(s.status("x").await.unwrap().phase, "design");
287 }
288
289 #[tokio::test]
290 async fn phase_gate_rejects_skip() {
291 let (s, _dir) = store().await;
292 let err = s
293 .update("x", "implementation", "premature".into())
294 .await
295 .unwrap_err();
296 assert!(format!("{err}").contains("must start with `research`"));
297 }
298
299 #[tokio::test]
300 async fn phase_gate_rejects_backwards() {
301 let (s, _dir) = store().await;
302 s.update("x", "research", "r".into()).await.unwrap();
303 s.update("x", "design", "d".into()).await.unwrap();
304 let err = s
305 .update("x", "testing", "premature".into())
306 .await
307 .unwrap_err();
308 assert!(format!("{err}").contains("cannot skip"), "err: {err}");
309 }
310
311 #[tokio::test]
312 async fn deviate_requires_prior_entry() {
313 let (s, _dir) = store().await;
314 let err = s
315 .deviate("x", "sec".into(), "delta".into(), "why".into())
316 .await
317 .unwrap_err();
318 assert!(format!("{err}").contains("no entries"));
319 }
320
321 #[tokio::test]
322 async fn deviate_appends_to_deviations_file() {
323 let (s, _dir) = store().await;
324 s.update("x", "research", "r".into()).await.unwrap();
325 s.update("x", "design", "d".into()).await.unwrap();
326 s.deviate(
327 "x",
328 "data".into(),
329 "added field".into(),
330 "need array".into(),
331 )
332 .await
333 .unwrap();
334 s.deviate("x", "algo".into(), "changed loop".into(), "perf".into())
335 .await
336 .unwrap();
337 let devs = s.deviations("x").await.unwrap();
338 assert_eq!(devs.len(), 2);
339 assert_eq!(s.status("x").await.unwrap().deviation_count, 2);
340 }
341
342 #[tokio::test]
343 async fn update_and_deviate_dual_write_to_index() {
344 let dir = tempfile::tempdir().unwrap();
345 let index = std::sync::Arc::new(AnchorIndex::open_project(dir.path()).unwrap());
346 let s = SpecStore::new(dir.path().to_path_buf()).with_index(index.clone());
347 s.update(
348 "feat_x",
349 "research",
350 "supercalifragilistic research notes".into(),
351 )
352 .await
353 .unwrap();
354 s.update(
355 "feat_x",
356 "design",
357 "midordermetamorphosis design notes".into(),
358 )
359 .await
360 .unwrap();
361 s.deviate(
362 "feat_x",
363 "sec".into(),
364 "hyperloquacious delta text".into(),
365 "quintessentialpolyphony reason text".into(),
366 )
367 .await
368 .unwrap();
369
370 let conn = index.conn();
371 let entry_count: i64 = conn
372 .query_row(
373 "SELECT COUNT(*) FROM spec_entries",
374 rusqlite::params![],
375 |r| r.get(0),
376 )
377 .unwrap();
378 let dev_count: i64 = conn
379 .query_row(
380 "SELECT COUNT(*) FROM spec_deviations",
381 rusqlite::params![],
382 |r| r.get(0),
383 )
384 .unwrap();
385 assert_eq!(entry_count, 2);
386 assert_eq!(dev_count, 1);
387
388 let entry_fts: i64 = conn
389 .query_row(
390 "SELECT COUNT(*) FROM spec_entries_fts WHERE spec_entries_fts MATCH ?",
391 rusqlite::params!["supercalifragilistic"],
392 |r| r.get(0),
393 )
394 .unwrap();
395 assert_eq!(entry_fts, 1);
396
397 let dev_fts: i64 = conn
398 .query_row(
399 "SELECT COUNT(*) FROM spec_deviations_fts WHERE spec_deviations_fts MATCH ?",
400 rusqlite::params!["quintessentialpolyphony"],
401 |r| r.get(0),
402 )
403 .unwrap();
404 assert_eq!(dev_fts, 1);
405 }
406
407 #[tokio::test]
408 async fn unknown_phase_rejected() {
409 let (s, _dir) = store().await;
410 let err = s.update("x", "brainstorm", "n".into()).await.unwrap_err();
411 assert!(format!("{err}").contains("unknown phase"));
412 }
413}