1use std::path::{Path, PathBuf};
6use std::sync::{Arc, Mutex};
7
8use chrono::NaiveDate;
9use rusqlite::{params, Connection, OptionalExtension};
10use serde::{Deserialize, Serialize};
11use tracing::instrument;
12
13use crate::migrations;
14
15use g8_core::{
16 model::{
17 Capability, CapabilityStatus, ConvergenceSpace, Decision, DecisionStatus, Intent,
18 IntentKind, IntentSourceKind, Plan, Project,
19 },
20 owner::Owner,
21 plan::{OverlapKind, PlanDraft, PlanIntentRelation, PlanStatus},
22 substrate::SubstrateBudget,
23 AnnotationId, CapabilityId, DecisionId, EpochMillis, G8Error, IntentId, PlanId, ProjectId,
24 SpaceId,
25};
26
27#[derive(Debug, thiserror::Error)]
31pub enum StoreError {
32 #[error("sqlite: {0}")]
33 Sqlite(#[from] rusqlite::Error),
34 #[error("migration: {0}")]
35 Migration(String),
36 #[error("not found: {0}")]
37 NotFound(String),
38 #[error("invalid state transition: {0}")]
39 InvalidTransition(String),
40 #[error("serialization: {0}")]
41 Serde(#[from] serde_json::Error),
42 #[error("g8-core: {0}")]
43 Core(#[from] G8Error),
44 #[error("io: {0}")]
45 Io(#[from] std::io::Error),
46 #[error("notify: {0}")]
47 Notify(String),
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct ApplyScanReport {
55 pub inserted_capabilities: u32,
56 pub inserted_intents: u32,
57 pub inserted_decisions: u32,
58 pub deleted_capabilities: u32,
59 pub deleted_intents: u32,
60 pub warnings: Vec<String>,
61}
62
63#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct RawIntentCheckPayload {
68 pub existing_matches: serde_json::Value,
69 pub budget: serde_json::Value,
70 pub bottlenecks: serde_json::Value,
71 pub drift_hints: serde_json::Value,
72 pub intent_overlaps: serde_json::Value,
73 pub parked_ideas: serde_json::Value,
74}
75
76#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct PairingError {
79 pub capability: String,
80 pub file: PathBuf,
81 pub line: u32,
82 pub reason: PairingErrorReason,
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "snake_case")]
88pub enum PairingErrorReason {
89 NoMatchingConvergenceTest,
90 StubExpired,
91 StubMissingSince,
92 DuplicateCapabilityName,
93}
94
95#[derive(Debug, Clone, Default, Serialize, Deserialize)]
97pub struct PlanFilter {
98 pub status: Option<Vec<PlanStatus>>,
99 pub substrate: Option<String>,
100 pub project: Option<ProjectId>,
101 pub limit: Option<u32>,
102}
103
104#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct StalePlanCandidate {
107 pub plan_id: PlanId,
108 pub title: String,
109 pub substrate: Option<String>,
110 pub dispatched_at: EpochMillis,
111 pub days_stale: i64,
112}
113
114pub struct WatchHandle {
118 _watcher: Arc<Mutex<Option<notify::RecommendedWatcher>>>,
119}
120
121impl WatchHandle {
122 fn new(watcher: notify::RecommendedWatcher) -> Self {
123 Self {
124 _watcher: Arc::new(Mutex::new(Some(watcher))),
125 }
126 }
127}
128
129#[derive(Debug, Clone, Default)]
136pub struct ScanResult {
137 pub annotations: Vec<g8_core::annotation::Annotation>,
138 pub warnings: Vec<String>,
139}
140
141pub trait StoreConnection: Send + Sync {
148 fn init_space(&mut self, space: &ConvergenceSpace) -> Result<(), StoreError>;
151 fn get_space(&self, id: &SpaceId) -> Result<Option<ConvergenceSpace>, StoreError>;
152 fn get_default_space(&self) -> Result<Option<ConvergenceSpace>, StoreError>;
153 fn upsert_project(&mut self, project: &Project) -> Result<(), StoreError>;
154 fn get_project(&self, id: &ProjectId) -> Result<Option<Project>, StoreError>;
155 fn list_projects(&self, space: &SpaceId) -> Result<Vec<Project>, StoreError>;
156 fn find_project_by_name(
158 &self,
159 space: &SpaceId,
160 name: &str,
161 ) -> Result<Option<Project>, StoreError>;
162 fn delete_project(&mut self, id: &ProjectId) -> Result<(), StoreError>;
164
165 fn apply_scan(
171 &mut self,
172 project: &ProjectId,
173 scan: ScanResult,
174 ) -> Result<ApplyScanReport, StoreError>;
175
176 fn upsert_capability(&mut self, cap: &Capability) -> Result<(), StoreError>;
179 fn get_capability(&self, id: &CapabilityId) -> Result<Option<Capability>, StoreError>;
180 fn find_capability_by_name(
181 &self,
182 project: &ProjectId,
183 name: &str,
184 ) -> Result<Option<Capability>, StoreError>;
185 fn list_capabilities(&self, project: &ProjectId) -> Result<Vec<Capability>, StoreError>;
186 fn delete_capabilities_for_project(&mut self, project: &ProjectId) -> Result<u64, StoreError>;
187
188 fn upsert_intent(&mut self, intent: &Intent) -> Result<(), StoreError>;
191 fn list_intents_at_path(&self, space: &SpaceId, path: &Path)
193 -> Result<Vec<Intent>, StoreError>;
194 fn delete_intents_for_project(&mut self, project: &ProjectId) -> Result<u64, StoreError>;
195
196 fn create_plan(&mut self, plan: &Plan) -> Result<(), StoreError>;
199 fn get_plan(&self, id: &PlanId) -> Result<Option<Plan>, StoreError>;
200 fn list_plans(&self, space: &SpaceId, filter: PlanFilter) -> Result<Vec<Plan>, StoreError>;
201 fn update_plan_status(
202 &mut self,
203 id: &PlanId,
204 new_status: PlanStatus,
205 reason: Option<String>,
206 ) -> Result<(), StoreError>;
207 fn link_plan_capability(
208 &mut self,
209 plan: &PlanId,
210 capability: &CapabilityId,
211 overlap_kind: OverlapKind,
212 ) -> Result<(), StoreError>;
213 fn link_plan_intent(
214 &mut self,
215 plan: &PlanId,
216 intent: &IntentId,
217 relation: PlanIntentRelation,
218 ) -> Result<(), StoreError>;
219
220 fn upsert_decision(&mut self, decision: &Decision) -> Result<(), StoreError>;
223 fn list_decisions(&self, space: &SpaceId) -> Result<Vec<Decision>, StoreError>;
224
225 fn set_substrate_budget(
228 &mut self,
229 space: &SpaceId,
230 substrate: &str,
231 wip_cap: u32,
232 stale_threshold_days: u32,
233 ) -> Result<(), StoreError>;
234 fn get_substrate_budget(
236 &self,
237 space: &SpaceId,
238 substrate: &str,
239 ) -> Result<SubstrateBudget, StoreError>;
240 fn list_substrate_budgets(&self, space: &SpaceId) -> Result<Vec<SubstrateBudget>, StoreError>;
244
245 fn add_capability_alias(&mut self, canonical: &str, alias: &str) -> Result<(), StoreError>;
248 fn resolve_canonical(&self, ref_name: &str) -> Result<String, StoreError>;
249
250 fn planner_intent_check(&self, draft: &PlanDraft) -> Result<RawIntentCheckPayload, StoreError>;
256
257 fn pairing_check(&self, project: Option<&ProjectId>) -> Result<Vec<PairingError>, StoreError>;
259
260 fn stale_dispatched_plans(
262 &self,
263 space: &SpaceId,
264 ) -> Result<Vec<StalePlanCandidate>, StoreError>;
265
266 fn attach_remote_store(&mut self, alias: &str, path: &Path) -> Result<(), StoreError>;
270 fn detach_remote_store(&mut self, alias: &str) -> Result<(), StoreError>;
271
272 fn watch<F>(&self, callback: F) -> Result<WatchHandle, StoreError>
278 where
279 F: Fn() + Send + 'static;
280}
281
282pub struct RusqliteStore {
289 conn: Mutex<Connection>,
290 store_path: PathBuf,
291}
292
293impl RusqliteStore {
294 pub fn open(path: &Path) -> Result<Self, StoreError> {
301 let conn = Connection::open(path)?;
302 Self::apply_pragmas(&conn)?;
303 Ok(Self {
304 conn: Mutex::new(conn),
305 store_path: path.to_path_buf(),
306 })
307 }
308
309 pub fn open_in_memory() -> Result<Self, StoreError> {
311 let conn = Connection::open_in_memory()?;
312 Self::apply_pragmas(&conn)?;
313 Ok(Self {
314 conn: Mutex::new(conn),
315 store_path: PathBuf::from(":memory:"),
316 })
317 }
318
319 pub fn migrate(&mut self) -> Result<(), StoreError> {
331 let mut conn = self.conn.lock().unwrap();
332 conn.execute_batch("PRAGMA foreign_keys=OFF;")?;
333 let outcome = Self::run_migrations(&mut conn);
334 let restored = conn.execute_batch("PRAGMA foreign_keys=ON;");
335 outcome?;
336 restored?;
337 Ok(())
338 }
339
340 fn run_migrations(conn: &mut Connection) -> Result<(), StoreError> {
341 Self::adopt_g8_0_1_0_v1(conn)?;
342 migrations::migrations::runner()
343 .run(conn)
344 .map_err(|e| StoreError::Migration(e.to_string()))?;
345 let violations: i64 =
346 conn.query_row("SELECT count(*) FROM pragma_foreign_key_check", [], |r| {
347 r.get(0)
348 })?;
349 if violations > 0 {
350 return Err(StoreError::Migration(format!(
351 "{violations} foreign key violation(s) after migrations (PRAGMA foreign_key_check)"
352 )));
353 }
354 Ok(())
355 }
356
357 fn adopt_g8_0_1_0_v1(conn: &Connection) -> Result<(), StoreError> {
368 let has_history: bool = conn.query_row(
369 "SELECT EXISTS (SELECT 1 FROM sqlite_master \
370 WHERE type='table' AND name='refinery_schema_history')",
371 [],
372 |r| r.get(0),
373 )?;
374 if !has_history {
375 return Ok(());
376 }
377 conn.execute(
378 "UPDATE refinery_schema_history SET checksum = ?1 \
379 WHERE version = 1 AND checksum = ?2",
380 params![
381 migrations::GOVERN_0_1_0_V1_CHECKSUM.to_string(),
382 migrations::G8_0_1_0_V1_CHECKSUM.to_string()
383 ],
384 )?;
385 Ok(())
386 }
387
388 fn apply_pragmas(conn: &Connection) -> Result<(), StoreError> {
391 conn.execute_batch(
392 "PRAGMA journal_mode=WAL;
393 PRAGMA foreign_keys=ON;
394 PRAGMA synchronous=NORMAL;
395 PRAGMA busy_timeout=5000;
396 PRAGMA cache_size=-8000;",
397 )?;
398 Ok(())
399 }
400
401 fn now() -> i64 {
402 use std::time::{SystemTime, UNIX_EPOCH};
403 SystemTime::now()
404 .duration_since(UNIX_EPOCH)
405 .unwrap_or_default()
406 .as_millis() as i64
407 }
408
409 fn lock(&self) -> std::sync::MutexGuard<'_, Connection> {
412 self.conn.lock().unwrap()
413 }
414}
415
416fn capability_status_to_str(s: CapabilityStatus) -> &'static str {
419 match s {
420 CapabilityStatus::Proposed => "proposed",
421 CapabilityStatus::InFlight => "in_flight",
422 CapabilityStatus::Landed => "landed",
423 CapabilityStatus::Stale => "stale",
424 CapabilityStatus::Superseded => "superseded",
425 CapabilityStatus::Parked => "parked",
426 }
427}
428
429fn capability_status_from_str(s: &str) -> Result<CapabilityStatus, StoreError> {
430 match s {
431 "proposed" => Ok(CapabilityStatus::Proposed),
432 "in_flight" => Ok(CapabilityStatus::InFlight),
433 "landed" => Ok(CapabilityStatus::Landed),
434 "stale" => Ok(CapabilityStatus::Stale),
435 "superseded" => Ok(CapabilityStatus::Superseded),
436 "parked" => Ok(CapabilityStatus::Parked),
437 other => Err(StoreError::NotFound(format!(
438 "unknown capability status: {other}"
439 ))),
440 }
441}
442
443fn plan_status_to_str(s: PlanStatus) -> &'static str {
444 match s {
445 PlanStatus::Idea => "Idea",
446 PlanStatus::Scoped => "Scoped",
447 PlanStatus::Dispatched => "Dispatched",
448 PlanStatus::Blocked => "Blocked",
449 PlanStatus::Done => "Done",
450 PlanStatus::Parked => "Parked",
451 }
452}
453
454fn encode_uri_path(path: &str) -> String {
460 let mut out = String::with_capacity(path.len());
461 for ch in path.chars() {
462 match ch {
463 '%' => out.push_str("%25"),
464 '?' => out.push_str("%3F"),
465 '#' => out.push_str("%23"),
466 ' ' => out.push_str("%20"),
467 c if (c as u32) < 0x20 => out.push_str(&format!("%{:02X}", c as u32)),
468 c => out.push(c),
469 }
470 }
471 out
472}
473
474fn plan_status_from_str(s: &str) -> Result<PlanStatus, StoreError> {
475 match s {
476 "Idea" => Ok(PlanStatus::Idea),
477 "Scoped" => Ok(PlanStatus::Scoped),
478 "Dispatched" => Ok(PlanStatus::Dispatched),
479 "Blocked" => Ok(PlanStatus::Blocked),
480 "Done" => Ok(PlanStatus::Done),
481 "Parked" => Ok(PlanStatus::Parked),
482 other => Err(StoreError::NotFound(format!(
483 "unknown plan status: {other}"
484 ))),
485 }
486}
487
488fn intent_kind_to_str(k: IntentKind) -> &'static str {
489 match k {
490 IntentKind::ArchitecturalScope => "architectural_scope",
491 IntentKind::Boundary => "boundary",
492 IntentKind::Operational => "operational",
493 IntentKind::TechStack => "tech_stack",
494 IntentKind::ExplicitIntent => "explicit_intent",
495 IntentKind::Unclassified => "unclassified",
496 }
497}
498
499fn intent_kind_from_str(s: &str) -> Result<IntentKind, StoreError> {
500 match s {
501 "architectural_scope" => Ok(IntentKind::ArchitecturalScope),
502 "boundary" => Ok(IntentKind::Boundary),
503 "operational" => Ok(IntentKind::Operational),
504 "tech_stack" => Ok(IntentKind::TechStack),
505 "explicit_intent" => Ok(IntentKind::ExplicitIntent),
506 _ => Ok(IntentKind::Unclassified),
507 }
508}
509
510fn intent_source_kind_to_str(k: IntentSourceKind) -> &'static str {
511 match k {
512 IntentSourceKind::AgentsMd => "agents_md",
513 IntentSourceKind::ClaudeMd => "claude_md",
514 IntentSourceKind::G8Sidecar => "g8_sidecar",
515 IntentSourceKind::InlineComment => "inline_comment",
516 IntentSourceKind::Manual => "manual",
517 }
518}
519
520fn intent_source_kind_from_str(s: &str) -> Result<IntentSourceKind, StoreError> {
521 match s {
522 "agents_md" => Ok(IntentSourceKind::AgentsMd),
523 "claude_md" => Ok(IntentSourceKind::ClaudeMd),
524 "g8_sidecar" => Ok(IntentSourceKind::G8Sidecar),
525 "inline_comment" => Ok(IntentSourceKind::InlineComment),
526 _ => Ok(IntentSourceKind::Manual),
527 }
528}
529
530fn decision_status_to_str(s: DecisionStatus) -> &'static str {
531 match s {
532 DecisionStatus::Proposed => "proposed",
533 DecisionStatus::Accepted => "accepted",
534 DecisionStatus::Rejected => "rejected",
535 DecisionStatus::Superseded => "superseded",
536 DecisionStatus::RuledOut => "ruled_out",
537 }
538}
539
540fn decision_status_from_str(s: &str) -> Result<DecisionStatus, StoreError> {
541 match s {
542 "proposed" => Ok(DecisionStatus::Proposed),
543 "accepted" => Ok(DecisionStatus::Accepted),
544 "rejected" => Ok(DecisionStatus::Rejected),
545 "superseded" => Ok(DecisionStatus::Superseded),
546 "ruled_out" => Ok(DecisionStatus::RuledOut),
547 other => Err(StoreError::NotFound(format!(
548 "unknown decision status: {other}"
549 ))),
550 }
551}
552
553fn overlap_kind_to_str(k: OverlapKind) -> &'static str {
554 match k {
555 OverlapKind::Touches => "touches",
556 OverlapKind::Extends => "extends",
557 OverlapKind::Replaces => "replaces",
558 OverlapKind::Conflicts => "conflicts",
559 }
560}
561
562fn plan_intent_relation_to_str(r: PlanIntentRelation) -> &'static str {
563 match r {
564 PlanIntentRelation::Satisfies => "satisfies",
565 PlanIntentRelation::Contradicts => "contradicts",
566 PlanIntentRelation::Extends => "extends",
567 PlanIntentRelation::DerivedFrom => "derived_from",
568 }
569}
570
571fn row_to_capability(row: &rusqlite::Row<'_>) -> rusqlite::Result<Capability> {
574 let id_str: String = row.get(0)?;
575 let project_id_str: String = row.get(1)?;
576 let name: String = row.get(2)?;
577 let description: Option<String> = row.get(3)?;
578 let substrate: Option<String> = row.get(4)?;
579 let consumes_json: String = row.get(5)?;
580 let produces_json: String = row.get(6)?;
581 let status_str: String = row.get(7)?;
582 let stub: bool = row.get::<_, i64>(8).map(|v| v != 0)?;
583 let stub_since_str: Option<String> = row.get(9)?;
584 let owner_agent: Option<String> = row.get(10)?;
585 let owner_team: Option<String> = row.get(11)?;
586 let owner_contact: Option<String> = row.get(12)?;
587 let file_path_str: Option<String> = row.get(13)?;
588 let line_number: Option<u32> = row.get(14)?;
589 let column_number: Option<u32> = row.get(15)?;
590 let annotation_raw: Option<String> = row.get(16)?;
591 let conditional: bool = row.get::<_, i64>(17).map(|v| v != 0)?;
592 let created_at: i64 = row.get(18)?;
593 let updated_at: i64 = row.get(19)?;
594 let meta_json: Option<String> = row.get(20)?;
595
596 let consumes: Vec<String> = serde_json::from_str(&consumes_json).unwrap_or_default();
597 let produces: Vec<String> = serde_json::from_str(&produces_json).unwrap_or_default();
598
599 let stub_since = stub_since_str
600 .as_deref()
601 .and_then(|s| NaiveDate::parse_from_str(s, "%Y-%m-%d").ok());
602
603 let owner = if owner_agent.is_some() || owner_team.is_some() || owner_contact.is_some() {
604 Some(Owner {
605 agent: owner_agent,
606 team: owner_team,
607 contact: owner_contact,
608 })
609 } else {
610 None
611 };
612
613 let source = g8_core::annotation::SourceLocation {
614 file: file_path_str
615 .map(PathBuf::from)
616 .unwrap_or_else(|| PathBuf::from("")),
617 line: line_number.unwrap_or(0),
618 column: column_number.unwrap_or(0),
619 };
620
621 let meta = meta_json
622 .as_deref()
623 .and_then(|s| serde_json::from_str(s).ok());
624
625 Ok(Capability {
626 id: CapabilityId::from_string(id_str)
627 .map_err(|e| rusqlite::Error::InvalidParameterName(e.to_string()))?,
628 project_id: ProjectId::from_string(project_id_str)
629 .map_err(|e| rusqlite::Error::InvalidParameterName(e.to_string()))?,
630 name,
631 description,
632 substrate,
633 consumes,
634 produces,
635 status: capability_status_from_str(&status_str).unwrap_or(CapabilityStatus::InFlight),
636 stub,
637 stub_since,
638 owner,
639 source,
640 annotation_raw: annotation_raw.unwrap_or_default(),
641 conditional,
642 created_at: EpochMillis::from_i64(created_at),
643 updated_at: EpochMillis::from_i64(updated_at),
644 meta,
645 })
646}
647
648fn row_to_project(row: &rusqlite::Row<'_>) -> rusqlite::Result<Project> {
649 let id_str: String = row.get(0)?;
650 let space_id_str: String = row.get(1)?;
651 let name: String = row.get(2)?;
652 let description: Option<String> = row.get(3)?;
653 let root_path_str: String = row.get(4)?;
654 let language: Option<String> = row.get(5)?;
655 let created_at: i64 = row.get(6)?;
656 let updated_at: i64 = row.get(7)?;
657 let meta_json: Option<String> = row.get(8)?;
658 let meta = meta_json
659 .as_deref()
660 .and_then(|s| serde_json::from_str(s).ok());
661
662 Ok(Project {
663 id: ProjectId::from_string(id_str)
664 .map_err(|e| rusqlite::Error::InvalidParameterName(e.to_string()))?,
665 space_id: SpaceId::from_string(space_id_str)
666 .map_err(|e| rusqlite::Error::InvalidParameterName(e.to_string()))?,
667 name,
668 description,
669 root_path: PathBuf::from(root_path_str),
670 language,
671 created_at: EpochMillis::from_i64(created_at),
672 updated_at: EpochMillis::from_i64(updated_at),
673 meta,
674 })
675}
676
677fn row_to_plan(row: &rusqlite::Row<'_>) -> rusqlite::Result<Plan> {
678 let id_str: String = row.get(0)?;
679 let space_id_str: String = row.get(1)?;
680 let project_id_str: Option<String> = row.get(2)?;
681 let title: String = row.get(3)?;
682 let description: Option<String> = row.get(4)?;
683 let status_str: String = row.get(5)?;
684 let substrate: Option<String> = row.get(6)?;
685 let wip_weight: u32 = row.get(7)?;
686 let parked_reason: Option<String> = row.get(8)?;
687 let blocked_reason: Option<String> = row.get(9)?;
688 let dispatched_at: Option<i64> = row.get(10)?;
689 let completed_at: Option<i64> = row.get(11)?;
690 let created_at: i64 = row.get(12)?;
691 let updated_at: i64 = row.get(13)?;
692 let meta_json: Option<String> = row.get(14)?;
693 let meta = meta_json
694 .as_deref()
695 .and_then(|s| serde_json::from_str(s).ok());
696
697 Ok(Plan {
700 id: PlanId::from_string(id_str)
701 .map_err(|e| rusqlite::Error::InvalidParameterName(e.to_string()))?,
702 space_id: SpaceId::from_string(space_id_str)
703 .map_err(|e| rusqlite::Error::InvalidParameterName(e.to_string()))?,
704 project_id: project_id_str
705 .map(ProjectId::from_string)
706 .transpose()
707 .map_err(|e: G8Error| rusqlite::Error::InvalidParameterName(e.to_string()))?,
708 title,
709 description,
710 status: plan_status_from_str(&status_str).unwrap_or(PlanStatus::Idea),
711 substrate,
712 touched_capabilities: vec![],
713 derived_from_intents: vec![],
714 governed_by_decisions: vec![],
715 wip_weight,
716 parked_reason,
717 blocked_reason,
718 dispatched_at: dispatched_at.map(EpochMillis::from_i64),
719 completed_at: completed_at.map(EpochMillis::from_i64),
720 created_at: EpochMillis::from_i64(created_at),
721 updated_at: EpochMillis::from_i64(updated_at),
722 meta,
723 })
724}
725
726fn row_to_intent_with_project(row: &rusqlite::Row<'_>) -> rusqlite::Result<Intent> {
727 let id_str: String = row.get(0)?;
728 let space_id_str: String = row.get(1)?;
729 let project_id_str: Option<String> = row.get(2)?;
730 let kind_str: String = row.get(3)?;
731 let heading: String = row.get(4)?;
732 let description: String = row.get(5)?;
733 let scope_path_str: String = row.get(6)?;
734 let scope_depth: u32 = row.get(7)?;
735 let substrate: Option<String> = row.get(8)?;
736 let owner_agent: Option<String> = row.get(9)?;
737 let owner_team: Option<String> = row.get(10)?;
738 let owner_contact: Option<String> = row.get(11)?;
739 let source_file_str: String = row.get(12)?;
740 let source_line: Option<u32> = row.get(13)?;
741 let source_kind_str: String = row.get(14)?;
742 let created_at: i64 = row.get(15)?;
743 let updated_at: i64 = row.get(16)?;
744 let meta_json: Option<String> = row.get(17)?;
745 let meta = meta_json
746 .as_deref()
747 .and_then(|s| serde_json::from_str(s).ok());
748
749 let owner = if owner_agent.is_some() || owner_team.is_some() || owner_contact.is_some() {
750 Some(Owner {
751 agent: owner_agent,
752 team: owner_team,
753 contact: owner_contact,
754 })
755 } else {
756 None
757 };
758
759 let project_id = project_id_str.and_then(|s| ProjectId::from_string(s).ok());
760
761 Ok(Intent {
762 id: IntentId::from_string(id_str)
763 .map_err(|e| rusqlite::Error::InvalidParameterName(e.to_string()))?,
764 space_id: SpaceId::from_string(space_id_str)
765 .map_err(|e| rusqlite::Error::InvalidParameterName(e.to_string()))?,
766 project_id,
767 kind: intent_kind_from_str(&kind_str).unwrap_or(IntentKind::Unclassified),
768 heading,
769 description,
770 scope_path: PathBuf::from(scope_path_str),
771 scope_depth,
772 substrate,
773 owner,
774 source: g8_core::annotation::SourceLocation {
775 file: PathBuf::from(&source_file_str),
776 line: source_line.unwrap_or(0),
777 column: 0,
778 },
779 source_kind: intent_source_kind_from_str(&source_kind_str)
780 .unwrap_or(IntentSourceKind::Manual),
781 created_at: EpochMillis::from_i64(created_at),
782 updated_at: EpochMillis::from_i64(updated_at),
783 meta,
784 })
785}
786
787fn row_to_decision(row: &rusqlite::Row<'_>) -> rusqlite::Result<Decision> {
788 let id_str: String = row.get(0)?;
789 let space_id_str: String = row.get(1)?;
790 let title: String = row.get(2)?;
791 let status_str: String = row.get(3)?;
792 let context: Option<String> = row.get(4)?;
793 let body: String = row.get(5)?;
794 let source_file_str: Option<String> = row.get(6)?;
795 let created_at: i64 = row.get(7)?;
796 let updated_at: i64 = row.get(8)?;
797 let meta_json: Option<String> = row.get(9)?;
798 let meta = meta_json
799 .as_deref()
800 .and_then(|s| serde_json::from_str(s).ok());
801
802 Ok(Decision {
803 id: DecisionId::from_string(id_str)
804 .map_err(|e| rusqlite::Error::InvalidParameterName(e.to_string()))?,
805 space_id: SpaceId::from_string(space_id_str)
806 .map_err(|e| rusqlite::Error::InvalidParameterName(e.to_string()))?,
807 title,
808 status: decision_status_from_str(&status_str).unwrap_or(DecisionStatus::Proposed),
809 context,
810 body,
811 source_file: source_file_str.map(PathBuf::from),
812 created_at: EpochMillis::from_i64(created_at),
813 updated_at: EpochMillis::from_i64(updated_at),
814 meta,
815 })
816}
817
818impl StoreConnection for RusqliteStore {
821 #[instrument(skip(self, space), fields(space_id = space.id.as_str()))]
824 fn init_space(&mut self, space: &ConvergenceSpace) -> Result<(), StoreError> {
825 let meta = space.meta.as_ref().map(|v| v.to_string());
826 self.lock().execute(
827 "INSERT INTO convergence_space (id, name, root_path, created_at, updated_at, meta)
828 VALUES (?1, ?2, ?3, ?4, ?5, ?6)
829 ON CONFLICT(id) DO UPDATE SET
830 name = excluded.name,
831 root_path = excluded.root_path,
832 updated_at = excluded.updated_at,
833 meta = excluded.meta",
834 params![
835 space.id.as_str(),
836 space.name,
837 space.root_path.to_string_lossy().as_ref(),
838 space.created_at.as_i64(),
839 space.updated_at.as_i64(),
840 meta,
841 ],
842 )?;
843 Ok(())
844 }
845
846 #[instrument(skip(self), fields(space_id = id.as_str()))]
847 fn get_space(&self, id: &SpaceId) -> Result<Option<ConvergenceSpace>, StoreError> {
848 let conn = self.lock();
849 let result = conn
850 .query_row(
851 "SELECT id, name, root_path, created_at, updated_at, meta
852 FROM convergence_space WHERE id = ?1",
853 params![id.as_str()],
854 |row| {
855 let id_str: String = row.get(0)?;
856 let name: String = row.get(1)?;
857 let root_path_str: String = row.get(2)?;
858 let created_at: i64 = row.get(3)?;
859 let updated_at: i64 = row.get(4)?;
860 let meta_json: Option<String> = row.get(5)?;
861 Ok((
862 id_str,
863 name,
864 root_path_str,
865 created_at,
866 updated_at,
867 meta_json,
868 ))
869 },
870 )
871 .optional()?;
872
873 if let Some((id_str, name, root_path_str, created_at, updated_at, meta_json)) = result {
874 let mut stmt =
876 conn.prepare("SELECT id FROM project WHERE space_id = ?1 ORDER BY created_at")?;
877 let members: Vec<ProjectId> = stmt
878 .query_map(params![id_str.as_str()], |row| {
879 let s: String = row.get(0)?;
880 Ok(s)
881 })?
882 .filter_map(|r| r.ok())
883 .filter_map(|s| ProjectId::from_string(s).ok())
884 .collect();
885
886 let meta = meta_json
887 .as_deref()
888 .and_then(|s| serde_json::from_str(s).ok());
889
890 Ok(Some(ConvergenceSpace {
891 id: SpaceId::from_string(id_str)?,
892 name,
893 root_path: PathBuf::from(root_path_str),
894 created_at: EpochMillis::from_i64(created_at),
895 updated_at: EpochMillis::from_i64(updated_at),
896 members,
897 meta,
898 }))
899 } else {
900 Ok(None)
901 }
902 }
903
904 #[instrument(skip(self))]
905 fn get_default_space(&self) -> Result<Option<ConvergenceSpace>, StoreError> {
906 let id_opt: Option<String> = self
907 .lock()
908 .query_row(
909 "SELECT id FROM convergence_space ORDER BY created_at LIMIT 1",
910 [],
911 |row| row.get(0),
912 )
913 .optional()?;
914
915 match id_opt {
916 Some(id_str) => {
917 let sid = SpaceId::from_string(id_str)?;
918 self.get_space(&sid)
919 }
920 None => Ok(None),
921 }
922 }
923
924 #[instrument(skip(self, project), fields(project_id = project.id.as_str()))]
925 fn upsert_project(&mut self, project: &Project) -> Result<(), StoreError> {
926 let meta = project.meta.as_ref().map(|v| v.to_string());
927 self.lock().execute(
928 "INSERT INTO project
929 (id, space_id, name, description, root_path, language, created_at, updated_at, meta)
930 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)
931 ON CONFLICT(id) DO UPDATE SET
932 space_id = excluded.space_id,
933 name = excluded.name,
934 description = excluded.description,
935 root_path = excluded.root_path,
936 language = excluded.language,
937 updated_at = excluded.updated_at,
938 meta = excluded.meta",
939 params![
940 project.id.as_str(),
941 project.space_id.as_str(),
942 project.name,
943 project.description,
944 project.root_path.to_string_lossy().as_ref(),
945 project.language,
946 project.created_at.as_i64(),
947 project.updated_at.as_i64(),
948 meta,
949 ],
950 )?;
951 Ok(())
952 }
953
954 #[instrument(skip(self), fields(project_id = id.as_str()))]
955 fn get_project(&self, id: &ProjectId) -> Result<Option<Project>, StoreError> {
956 self.lock()
957 .query_row(
958 "SELECT id, space_id, name, description, root_path, language,
959 created_at, updated_at, meta
960 FROM project WHERE id = ?1",
961 params![id.as_str()],
962 row_to_project,
963 )
964 .optional()
965 .map_err(Into::into)
966 }
967
968 #[instrument(skip(self), fields(space_id = space.as_str()))]
969 fn list_projects(&self, space: &SpaceId) -> Result<Vec<Project>, StoreError> {
970 let conn = self.lock();
971 let mut stmt = conn.prepare(
972 "SELECT id, space_id, name, description, root_path, language,
973 created_at, updated_at, meta
974 FROM project WHERE space_id = ?1 ORDER BY created_at",
975 )?;
976 let rows = stmt
977 .query_map(params![space.as_str()], row_to_project)?
978 .collect::<rusqlite::Result<Vec<_>>>()?;
979 Ok(rows)
980 }
981
982 #[instrument(skip(self), fields(space_id = space.as_str(), name))]
983 fn find_project_by_name(
984 &self,
985 space: &SpaceId,
986 name: &str,
987 ) -> Result<Option<Project>, StoreError> {
988 let conn = self.lock();
989 let project_opt = conn
990 .query_row(
991 "SELECT id, space_id, name, description, root_path, language,
992 created_at, updated_at, meta
993 FROM project WHERE space_id = ?1 AND name = ?2",
994 params![space.as_str(), name],
995 row_to_project,
996 )
997 .optional()?;
998 Ok(project_opt)
999 }
1000
1001 #[instrument(skip(self), fields(project_id = id.as_str()))]
1002 fn delete_project(&mut self, id: &ProjectId) -> Result<(), StoreError> {
1003 let n = self
1004 .lock()
1005 .execute("DELETE FROM project WHERE id = ?1", params![id.as_str()])?;
1006 if n == 0 {
1007 return Err(StoreError::NotFound(format!("project {}", id.as_str())));
1008 }
1009 Ok(())
1010 }
1011
1012 #[instrument(skip(self, scan), fields(project_id = project.as_str()))]
1015 fn apply_scan(
1016 &mut self,
1017 project: &ProjectId,
1018 scan: ScanResult,
1019 ) -> Result<ApplyScanReport, StoreError> {
1020 let mut conn = self.lock();
1021 let now = Self::now();
1022 let mut report = ApplyScanReport {
1023 inserted_capabilities: 0,
1024 inserted_intents: 0,
1025 inserted_decisions: 0,
1026 deleted_capabilities: 0,
1027 deleted_intents: 0,
1028 warnings: scan.warnings,
1029 };
1030
1031 let tx = conn.transaction()?;
1033
1034 let del_caps = tx.execute(
1038 "DELETE FROM capability WHERE project_id = ?1",
1039 params![project.as_str()],
1040 )?;
1041 report.deleted_capabilities = del_caps as u32;
1042
1043 let del_intents = tx.execute(
1044 "DELETE FROM intent WHERE project_id = ?1",
1045 params![project.as_str()],
1046 )?;
1047 report.deleted_intents = del_intents as u32;
1048
1049 tx.execute(
1050 "DELETE FROM annotation WHERE project_id = ?1",
1051 params![project.as_str()],
1052 )?;
1053
1054 let space_id_str: Option<String> = tx
1056 .query_row(
1057 "SELECT space_id FROM project WHERE id = ?1",
1058 params![project.as_str()],
1059 |row| row.get(0),
1060 )
1061 .optional()?;
1062 let space_id_str =
1063 space_id_str.ok_or_else(|| StoreError::NotFound(format!("project {project}")))?;
1064
1065 for ann in &scan.annotations {
1066 use g8_core::annotation::AnnotationKind;
1067
1068 let kind = match ann.kind {
1069 AnnotationKind::Capability => "capability",
1070 AnnotationKind::Intent => "intent",
1071 AnnotationKind::ConvergenceTest => "convergence_test",
1072 AnnotationKind::Decision => "decision",
1073 AnnotationKind::Plan => "plan",
1074 };
1075 let annotation_id = AnnotationId::derive(&[
1076 project.as_str(),
1077 kind,
1078 ann.source.file.to_string_lossy().as_ref(),
1079 &ann.source.line.to_string(),
1080 &ann.source.column.to_string(),
1081 ]);
1082 let payload = serde_json::to_string(&ann.fields)?;
1083 let source_lang = ann
1084 .source
1085 .file
1086 .extension()
1087 .and_then(|extension| extension.to_str());
1088 tx.execute(
1089 "INSERT INTO annotation
1090 (id, project_id, kind, payload, file_path, line_number,
1091 column_number, source_lang, source_kind, conditional,
1092 extracted_at, meta)
1093 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,NULL)",
1094 params![
1095 annotation_id.as_str(),
1096 project.as_str(),
1097 kind,
1098 payload,
1099 ann.source.file.to_string_lossy().as_ref(),
1100 ann.source.line,
1101 ann.source.column,
1102 source_lang,
1103 intent_source_kind_to_str(ann.source_kind),
1104 ann.conditional as i64,
1105 now,
1106 ],
1107 )?;
1108
1109 match ann.kind {
1110 AnnotationKind::Capability => {
1111 let name = ann.name.clone().unwrap_or_default();
1112 if name.is_empty() {
1113 continue;
1114 }
1115 let id = AnnotationId::derive(&[
1119 project.as_str(),
1120 "capability",
1121 &name,
1122 ann.source.file.to_string_lossy().as_ref(),
1123 &ann.source.line.to_string(),
1124 ])
1125 .as_str()
1126 .to_owned();
1127 let status = ann
1128 .fields
1129 .get("status")
1130 .and_then(|v| {
1131 if let g8_core::annotation::AnnotationValue::String(s) = v {
1132 Some(s.as_str())
1133 } else {
1134 None
1135 }
1136 })
1137 .unwrap_or("in_flight");
1138 let stub = ann
1139 .fields
1140 .get("stub")
1141 .and_then(|v| {
1142 if let g8_core::annotation::AnnotationValue::Bool(b) = v {
1143 Some(*b)
1144 } else {
1145 None
1146 }
1147 })
1148 .unwrap_or(false);
1149 let stub_since = ann.fields.get("since").and_then(|v| {
1150 if let g8_core::annotation::AnnotationValue::String(s) = v {
1151 Some(s.clone())
1152 } else {
1153 None
1154 }
1155 });
1156 let substrate = ann.fields.get("substrate").and_then(|v| {
1157 if let g8_core::annotation::AnnotationValue::String(s) = v {
1158 Some(s.clone())
1159 } else {
1160 None
1161 }
1162 });
1163 let description = ann.fields.get("description").and_then(|v| {
1164 if let g8_core::annotation::AnnotationValue::String(s) = v {
1165 Some(s.clone())
1166 } else {
1167 None
1168 }
1169 });
1170 let consumes = ann
1171 .fields
1172 .get("consumes")
1173 .and_then(|v| {
1174 if let g8_core::annotation::AnnotationValue::List(l) = v {
1175 Some(serde_json::to_string(l).unwrap_or_else(|_| "[]".to_owned()))
1176 } else {
1177 None
1178 }
1179 })
1180 .unwrap_or_else(|| "[]".to_owned());
1181 let produces = ann
1182 .fields
1183 .get("produces")
1184 .and_then(|v| {
1185 if let g8_core::annotation::AnnotationValue::List(l) = v {
1186 Some(serde_json::to_string(l).unwrap_or_else(|_| "[]".to_owned()))
1187 } else {
1188 None
1189 }
1190 })
1191 .unwrap_or_else(|| "[]".to_owned());
1192
1193 tx.execute(
1194 "INSERT INTO capability
1195 (id, project_id, name, description, substrate, consumes, produces,
1196 status, stub, stub_since, file_path, line_number, column_number,
1197 annotation_raw, conditional, created_at, updated_at)
1198 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17)",
1199 params![
1200 id,
1201 project.as_str(),
1202 name,
1203 description,
1204 substrate,
1205 consumes,
1206 produces,
1207 status,
1208 stub as i64,
1209 stub_since,
1210 ann.source.file.to_string_lossy().as_ref(),
1211 ann.source.line,
1212 ann.source.column,
1213 ann.raw_text,
1214 ann.conditional as i64,
1215 now,
1216 now,
1217 ],
1218 )?;
1219 report.inserted_capabilities += 1;
1220 }
1221 AnnotationKind::Intent => {
1222 let heading = ann
1223 .heading
1224 .clone()
1225 .or_else(|| ann.name.clone())
1226 .unwrap_or_default();
1227 if heading.is_empty() {
1228 continue;
1229 }
1230 let id = AnnotationId::derive(&[
1231 project.as_str(),
1232 "intent",
1233 &heading,
1234 ann.source.file.to_string_lossy().as_ref(),
1235 &ann.source.line.to_string(),
1236 ])
1237 .as_str()
1238 .to_owned();
1239 let scope_path = ann
1240 .source
1241 .file
1242 .parent()
1243 .unwrap_or(Path::new(""))
1244 .to_string_lossy()
1245 .to_string();
1246 let scope_depth = ann.source.file.components().count() as u32;
1247 let source_kind = intent_source_kind_to_str(ann.source_kind);
1248 let substrate = ann.fields.get("substrate").and_then(|v| {
1249 if let g8_core::annotation::AnnotationValue::String(s) = v {
1250 Some(s.clone())
1251 } else {
1252 None
1253 }
1254 });
1255 let description = ann
1256 .fields
1257 .get("description")
1258 .and_then(|v| {
1259 if let g8_core::annotation::AnnotationValue::String(s) = v {
1260 Some(s.clone())
1261 } else {
1262 None
1263 }
1264 })
1265 .unwrap_or_default();
1266 let intent_kind = ann
1272 .fields
1273 .get("intent_kind")
1274 .and_then(|v| {
1275 if let g8_core::annotation::AnnotationValue::String(s) = v {
1276 Some(s.clone())
1277 } else {
1278 None
1279 }
1280 })
1281 .unwrap_or_else(|| "unclassified".to_string());
1282
1283 tx.execute(
1284 "INSERT INTO intent
1285 (id, space_id, project_id, kind, heading, description,
1286 scope_path, scope_depth, substrate, source_file, source_line,
1287 source_kind, created_at, updated_at)
1288 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14)",
1289 params![
1290 id,
1291 space_id_str,
1292 project.as_str(),
1293 intent_kind,
1294 heading,
1295 description,
1296 scope_path,
1297 scope_depth,
1298 substrate,
1299 ann.source.file.to_string_lossy().as_ref(),
1300 ann.source.line,
1301 source_kind,
1302 now,
1303 now,
1304 ],
1305 )?;
1306 report.inserted_intents += 1;
1307 }
1308 AnnotationKind::Decision => {
1309 let title = ann
1310 .fields
1311 .get("title")
1312 .and_then(|v| {
1313 if let g8_core::annotation::AnnotationValue::String(s) = v {
1314 Some(s.clone())
1315 } else {
1316 None
1317 }
1318 })
1319 .or_else(|| ann.name.clone())
1320 .unwrap_or_default();
1321 if title.is_empty() {
1322 continue;
1323 }
1324 let id = AnnotationId::derive(&[
1325 &space_id_str,
1326 "decision",
1327 &title,
1328 ann.source.file.to_string_lossy().as_ref(),
1329 &ann.source.line.to_string(),
1330 ])
1331 .as_str()
1332 .to_owned();
1333 let body = ann
1334 .fields
1335 .get("body")
1336 .and_then(|v| {
1337 if let g8_core::annotation::AnnotationValue::String(s) = v {
1338 Some(s.clone())
1339 } else {
1340 None
1341 }
1342 })
1343 .unwrap_or_default();
1344 let status = ann
1345 .fields
1346 .get("status")
1347 .and_then(|v| {
1348 if let g8_core::annotation::AnnotationValue::String(s) = v {
1349 Some(s.clone())
1350 } else {
1351 None
1352 }
1353 })
1354 .unwrap_or_else(|| "proposed".to_owned());
1355
1356 tx.execute(
1357 "INSERT INTO decision
1358 (id, space_id, title, status, body, source_file, created_at, updated_at)
1359 VALUES (?1,?2,?3,?4,?5,?6,?7,?8)
1360 ON CONFLICT DO NOTHING",
1361 params![
1362 id,
1363 space_id_str,
1364 title,
1365 status,
1366 body,
1367 ann.source.file.to_string_lossy().as_ref(),
1368 now,
1369 now,
1370 ],
1371 )?;
1372 report.inserted_decisions += 1;
1373 }
1374 AnnotationKind::ConvergenceTest | AnnotationKind::Plan => {}
1378 }
1379 }
1380
1381 tx.commit()?;
1382 Ok(report)
1383 }
1384
1385 #[instrument(skip(self, cap), fields(capability_id = cap.id.as_str()))]
1388 fn upsert_capability(&mut self, cap: &Capability) -> Result<(), StoreError> {
1389 let now = Self::now();
1390 let meta = cap.meta.as_ref().map(|v| v.to_string());
1391 let consumes = serde_json::to_string(&cap.consumes)?;
1392 let produces = serde_json::to_string(&cap.produces)?;
1393 let stub_since = cap.stub_since.map(|d| d.format("%Y-%m-%d").to_string());
1394 self.lock().execute(
1395 "INSERT INTO capability
1396 (id, project_id, name, description, substrate, consumes, produces, status,
1397 stub, stub_since, owner_agent, owner_team, owner_contact, file_path,
1398 line_number, column_number, annotation_raw, conditional, created_at, updated_at, meta)
1399 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20,?21)
1400 ON CONFLICT(id) DO UPDATE SET
1401 name = excluded.name,
1402 description = excluded.description,
1403 substrate = excluded.substrate,
1404 consumes = excluded.consumes,
1405 produces = excluded.produces,
1406 status = excluded.status,
1407 stub = excluded.stub,
1408 stub_since = excluded.stub_since,
1409 owner_agent = excluded.owner_agent,
1410 owner_team = excluded.owner_team,
1411 owner_contact = excluded.owner_contact,
1412 file_path = excluded.file_path,
1413 line_number = excluded.line_number,
1414 column_number = excluded.column_number,
1415 annotation_raw= excluded.annotation_raw,
1416 conditional = excluded.conditional,
1417 updated_at = excluded.updated_at,
1418 meta = excluded.meta",
1419 params![
1420 cap.id.as_str(),
1421 cap.project_id.as_str(),
1422 cap.name,
1423 cap.description,
1424 cap.substrate,
1425 consumes,
1426 produces,
1427 capability_status_to_str(cap.status),
1428 cap.stub as i64,
1429 stub_since,
1430 cap.owner.as_ref().and_then(|o| o.agent.as_deref()),
1431 cap.owner.as_ref().and_then(|o| o.team.as_deref()),
1432 cap.owner.as_ref().and_then(|o| o.contact.as_deref()),
1433 cap.source.file.to_string_lossy().as_ref(),
1434 cap.source.line,
1435 cap.source.column,
1436 cap.annotation_raw,
1437 cap.conditional as i64,
1438 cap.created_at.as_i64(),
1439 now,
1440 meta,
1441 ],
1442 )?;
1443 Ok(())
1444 }
1445
1446 #[instrument(skip(self), fields(capability_id = id.as_str()))]
1447 fn get_capability(&self, id: &CapabilityId) -> Result<Option<Capability>, StoreError> {
1448 self.lock()
1449 .query_row(
1450 "SELECT id, project_id, name, description, substrate, consumes, produces,
1451 status, stub, stub_since, owner_agent, owner_team, owner_contact,
1452 file_path, line_number, column_number, annotation_raw, conditional,
1453 created_at, updated_at, meta
1454 FROM capability WHERE id = ?1",
1455 params![id.as_str()],
1456 row_to_capability,
1457 )
1458 .optional()
1459 .map_err(Into::into)
1460 }
1461
1462 #[instrument(skip(self), fields(project_id = project.as_str(), name))]
1463 fn find_capability_by_name(
1464 &self,
1465 project: &ProjectId,
1466 name: &str,
1467 ) -> Result<Option<Capability>, StoreError> {
1468 self.lock()
1469 .query_row(
1470 "SELECT id, project_id, name, description, substrate, consumes, produces,
1471 status, stub, stub_since, owner_agent, owner_team, owner_contact,
1472 file_path, line_number, column_number, annotation_raw, conditional,
1473 created_at, updated_at, meta
1474 FROM capability WHERE project_id = ?1 AND name = ?2 LIMIT 1",
1475 params![project.as_str(), name],
1476 row_to_capability,
1477 )
1478 .optional()
1479 .map_err(Into::into)
1480 }
1481
1482 #[instrument(skip(self), fields(project_id = project.as_str()))]
1483 fn list_capabilities(&self, project: &ProjectId) -> Result<Vec<Capability>, StoreError> {
1484 let conn = self.lock();
1485 let mut stmt = conn.prepare(
1486 "SELECT id, project_id, name, description, substrate, consumes, produces,
1487 status, stub, stub_since, owner_agent, owner_team, owner_contact,
1488 file_path, line_number, column_number, annotation_raw, conditional,
1489 created_at, updated_at, meta
1490 FROM capability WHERE project_id = ?1 ORDER BY name",
1491 )?;
1492 let rows = stmt
1493 .query_map(params![project.as_str()], row_to_capability)?
1494 .collect::<rusqlite::Result<Vec<_>>>()?;
1495 Ok(rows)
1496 }
1497
1498 #[instrument(skip(self), fields(project_id = project.as_str()))]
1499 fn delete_capabilities_for_project(&mut self, project: &ProjectId) -> Result<u64, StoreError> {
1500 let n = self.lock().execute(
1501 "DELETE FROM capability WHERE project_id = ?1",
1502 params![project.as_str()],
1503 )?;
1504 Ok(n as u64)
1505 }
1506
1507 #[instrument(skip(self, intent), fields(intent_id = intent.id.as_str()))]
1510 fn upsert_intent(&mut self, intent: &Intent) -> Result<(), StoreError> {
1511 let now = Self::now();
1512 let meta = intent.meta.as_ref().map(|v| v.to_string());
1513 self.lock().execute(
1514 "INSERT INTO intent
1515 (id, space_id, project_id, kind, heading, description, scope_path, scope_depth,
1516 substrate, owner_agent, owner_team, owner_contact, source_file, source_line,
1517 source_kind, created_at, updated_at, meta)
1518 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18)
1519 ON CONFLICT(id) DO UPDATE SET
1520 kind = excluded.kind,
1521 heading = excluded.heading,
1522 description = excluded.description,
1523 scope_path = excluded.scope_path,
1524 scope_depth = excluded.scope_depth,
1525 substrate = excluded.substrate,
1526 owner_agent = excluded.owner_agent,
1527 owner_team = excluded.owner_team,
1528 owner_contact = excluded.owner_contact,
1529 source_file = excluded.source_file,
1530 source_line = excluded.source_line,
1531 source_kind = excluded.source_kind,
1532 updated_at = excluded.updated_at,
1533 meta = excluded.meta",
1534 params![
1535 intent.id.as_str(),
1536 intent.space_id.as_str(),
1537 intent.project_id.as_ref().map(|p| p.as_str()),
1538 intent_kind_to_str(intent.kind),
1539 intent.heading,
1540 intent.description,
1541 intent.scope_path.to_string_lossy().as_ref(),
1542 intent.scope_depth,
1543 intent.substrate,
1544 intent.owner.as_ref().and_then(|o| o.agent.as_deref()),
1545 intent.owner.as_ref().and_then(|o| o.team.as_deref()),
1546 intent.owner.as_ref().and_then(|o| o.contact.as_deref()),
1547 intent.source.file.to_string_lossy().as_ref(),
1548 intent.source.line,
1549 intent_source_kind_to_str(intent.source_kind),
1550 intent.created_at.as_i64(),
1551 now,
1552 meta,
1553 ],
1554 )?;
1555 Ok(())
1556 }
1557
1558 #[instrument(skip(self), fields(space_id = space.as_str()))]
1559 fn list_intents_at_path(
1560 &self,
1561 space: &SpaceId,
1562 path: &Path,
1563 ) -> Result<Vec<Intent>, StoreError> {
1564 let conn = self.lock();
1565 let path_str = path.to_string_lossy();
1566 if path_str.is_empty() {
1569 let mut stmt = conn.prepare(
1570 "SELECT id, space_id, project_id, kind, heading, description, scope_path,
1571 scope_depth, substrate, owner_agent, owner_team, owner_contact,
1572 source_file, source_line, source_kind, created_at, updated_at, meta
1573 FROM intent
1574 WHERE space_id = ?1
1575 ORDER BY scope_depth DESC",
1576 )?;
1577 let rows = stmt
1578 .query_map(params![space.as_str()], row_to_intent_with_project)?
1579 .collect::<rusqlite::Result<Vec<_>>>()?;
1580 Ok(rows)
1581 } else {
1582 let mut stmt = conn.prepare(
1583 "SELECT id, space_id, project_id, kind, heading, description, scope_path,
1584 scope_depth, substrate, owner_agent, owner_team, owner_contact,
1585 source_file, source_line, source_kind, created_at, updated_at, meta
1586 FROM intent
1587 WHERE space_id = ?1 AND ?2 LIKE scope_path || '%'
1588 ORDER BY scope_depth DESC",
1589 )?;
1590 let rows = stmt
1591 .query_map(
1592 params![space.as_str(), path_str.as_ref()],
1593 row_to_intent_with_project,
1594 )?
1595 .collect::<rusqlite::Result<Vec<_>>>()?;
1596 Ok(rows)
1597 }
1598 }
1599
1600 #[instrument(skip(self), fields(project_id = project.as_str()))]
1601 fn delete_intents_for_project(&mut self, project: &ProjectId) -> Result<u64, StoreError> {
1602 let n = self.lock().execute(
1603 "DELETE FROM intent WHERE project_id = ?1",
1604 params![project.as_str()],
1605 )?;
1606 Ok(n as u64)
1607 }
1608
1609 #[instrument(skip(self, plan), fields(plan_id = plan.id.as_str()))]
1612 fn create_plan(&mut self, plan: &Plan) -> Result<(), StoreError> {
1613 let meta = plan.meta.as_ref().map(|v| v.to_string());
1614 self.lock().execute(
1615 "INSERT INTO plan
1616 (id, space_id, project_id, title, description, status, substrate,
1617 wip_weight, parked_reason, blocked_reason, dispatched_at, completed_at,
1618 created_at, updated_at, meta)
1619 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15)",
1620 params![
1621 plan.id.as_str(),
1622 plan.space_id.as_str(),
1623 plan.project_id.as_ref().map(|p| p.as_str()),
1624 plan.title,
1625 plan.description,
1626 plan_status_to_str(plan.status),
1627 plan.substrate,
1628 plan.wip_weight,
1629 plan.parked_reason,
1630 plan.blocked_reason,
1631 plan.dispatched_at.as_ref().map(|e| e.as_i64()),
1632 plan.completed_at.as_ref().map(|e| e.as_i64()),
1633 plan.created_at.as_i64(),
1634 plan.updated_at.as_i64(),
1635 meta,
1636 ],
1637 )?;
1638 Ok(())
1639 }
1640
1641 #[instrument(skip(self), fields(plan_id = id.as_str()))]
1642 fn get_plan(&self, id: &PlanId) -> Result<Option<Plan>, StoreError> {
1643 let conn = self.lock();
1644 let plan_opt = conn
1645 .query_row(
1646 "SELECT id, space_id, project_id, title, description, status, substrate,
1647 wip_weight, parked_reason, blocked_reason, dispatched_at, completed_at,
1648 created_at, updated_at, meta
1649 FROM plan WHERE id = ?1",
1650 params![id.as_str()],
1651 row_to_plan,
1652 )
1653 .optional()?;
1654
1655 if let Some(mut plan) = plan_opt {
1656 let mut stmt =
1658 conn.prepare("SELECT capability_id FROM plan_capability WHERE plan_id = ?1")?;
1659 plan.touched_capabilities = stmt
1660 .query_map(params![id.as_str()], |row| row.get::<_, String>(0))?
1661 .filter_map(|r| r.ok())
1662 .filter_map(|s| CapabilityId::from_string(s).ok())
1663 .collect();
1664
1665 let mut stmt = conn.prepare("SELECT intent_id FROM plan_intent WHERE plan_id = ?1")?;
1667 plan.derived_from_intents = stmt
1668 .query_map(params![id.as_str()], |row| row.get::<_, String>(0))?
1669 .filter_map(|r| r.ok())
1670 .filter_map(|s| IntentId::from_string(s).ok())
1671 .collect();
1672
1673 let mut stmt =
1675 conn.prepare("SELECT decision_id FROM plan_decision WHERE plan_id = ?1")?;
1676 plan.governed_by_decisions = stmt
1677 .query_map(params![id.as_str()], |row| row.get::<_, String>(0))?
1678 .filter_map(|r| r.ok())
1679 .filter_map(|s| DecisionId::from_string(s).ok())
1680 .collect();
1681
1682 Ok(Some(plan))
1683 } else {
1684 Ok(None)
1685 }
1686 }
1687
1688 #[instrument(skip(self, filter), fields(space_id = space.as_str()))]
1689 fn list_plans(&self, space: &SpaceId, filter: PlanFilter) -> Result<Vec<Plan>, StoreError> {
1690 let conn = self.lock();
1691 let mut sql = String::from(
1693 "SELECT id, space_id, project_id, title, description, status, substrate,
1694 wip_weight, parked_reason, blocked_reason, dispatched_at, completed_at,
1695 created_at, updated_at, meta
1696 FROM plan WHERE space_id = ?1",
1697 );
1698 let mut bindings: Vec<Box<dyn rusqlite::ToSql>> = vec![Box::new(space.as_str().to_owned())];
1699
1700 if let Some(ref statuses) = filter.status {
1701 if !statuses.is_empty() {
1702 let placeholders: Vec<String> = statuses
1703 .iter()
1704 .enumerate()
1705 .map(|(i, _)| format!("?{}", i + 2))
1706 .collect();
1707 sql.push_str(&format!(" AND status IN ({})", placeholders.join(",")));
1708 for s in statuses {
1709 bindings.push(Box::new(plan_status_to_str(*s).to_owned()));
1710 }
1711 }
1712 }
1713 if let Some(ref sub) = filter.substrate {
1714 let idx = bindings.len() + 1;
1715 sql.push_str(&format!(" AND substrate = ?{idx}"));
1716 bindings.push(Box::new(sub.clone()));
1717 }
1718 if let Some(ref proj) = filter.project {
1719 let idx = bindings.len() + 1;
1720 sql.push_str(&format!(" AND project_id = ?{idx}"));
1721 bindings.push(Box::new(proj.as_str().to_owned()));
1722 }
1723 sql.push_str(" ORDER BY updated_at DESC");
1724 if let Some(lim) = filter.limit {
1725 let idx = bindings.len() + 1;
1726 sql.push_str(&format!(" LIMIT ?{idx}"));
1727 bindings.push(Box::new(lim));
1728 }
1729
1730 let mut stmt = conn.prepare(&sql)?;
1731 let params_refs: Vec<&dyn rusqlite::ToSql> = bindings.iter().map(|b| b.as_ref()).collect();
1732 let rows = stmt
1733 .query_map(params_refs.as_slice(), row_to_plan)?
1734 .collect::<rusqlite::Result<Vec<_>>>()?;
1735 Ok(rows)
1736 }
1737
1738 #[instrument(skip(self), fields(plan_id = id.as_str()))]
1739 fn update_plan_status(
1740 &mut self,
1741 id: &PlanId,
1742 new_status: PlanStatus,
1743 reason: Option<String>,
1744 ) -> Result<(), StoreError> {
1745 let conn = self.lock();
1746 let current_status: String = conn
1752 .query_row(
1753 "SELECT status FROM plan WHERE id = ?1",
1754 params![id.as_str()],
1755 |row| row.get(0),
1756 )
1757 .optional()?
1758 .ok_or_else(|| StoreError::NotFound(format!("plan {}", id.as_str())))?;
1759 let from = plan_status_from_str(¤t_status).map_err(|e| {
1760 StoreError::InvalidTransition(format!("unknown current status '{current_status}': {e}"))
1761 })?;
1762 if from != new_status {
1763 g8_core::validate_status_transition(from, new_status).map_err(|e| {
1764 StoreError::InvalidTransition(format!(
1765 "{from:?} → {new_status:?} is not a legal transition: {e}"
1766 ))
1767 })?;
1768 }
1769 let now = Self::now();
1770 let status_str = plan_status_to_str(new_status);
1771 match new_status {
1772 PlanStatus::Parked => {
1773 conn.execute(
1774 "UPDATE plan SET status = ?1, parked_reason = ?2, updated_at = ?3 WHERE id = ?4",
1775 params![status_str, reason, now, id.as_str()],
1776 )?;
1777 }
1778 PlanStatus::Blocked => {
1779 conn.execute(
1780 "UPDATE plan SET status = ?1, blocked_reason = ?2, updated_at = ?3 WHERE id = ?4",
1781 params![status_str, reason, now, id.as_str()],
1782 )?;
1783 }
1784 PlanStatus::Dispatched => {
1785 conn.execute(
1786 "UPDATE plan SET status = ?1, dispatched_at = ?2, updated_at = ?2 WHERE id = ?3",
1787 params![status_str, now, id.as_str()],
1788 )?;
1789 }
1790 PlanStatus::Done => {
1791 conn.execute(
1792 "UPDATE plan SET status = ?1, completed_at = ?2, updated_at = ?2 WHERE id = ?3",
1793 params![status_str, now, id.as_str()],
1794 )?;
1795 }
1796 _ => {
1797 conn.execute(
1798 "UPDATE plan SET status = ?1, updated_at = ?2 WHERE id = ?3",
1799 params![status_str, now, id.as_str()],
1800 )?;
1801 }
1802 }
1803 Ok(())
1804 }
1805
1806 #[instrument(skip(self), fields(plan_id = plan.as_str(), capability_id = capability.as_str()))]
1807 fn link_plan_capability(
1808 &mut self,
1809 plan: &PlanId,
1810 capability: &CapabilityId,
1811 overlap_kind: OverlapKind,
1812 ) -> Result<(), StoreError> {
1813 self.lock().execute(
1814 "INSERT INTO plan_capability (plan_id, capability_id, overlap_kind)
1815 VALUES (?1, ?2, ?3)
1816 ON CONFLICT DO NOTHING",
1817 params![
1818 plan.as_str(),
1819 capability.as_str(),
1820 overlap_kind_to_str(overlap_kind),
1821 ],
1822 )?;
1823 Ok(())
1824 }
1825
1826 #[instrument(skip(self), fields(plan_id = plan.as_str(), intent_id = intent.as_str()))]
1827 fn link_plan_intent(
1828 &mut self,
1829 plan: &PlanId,
1830 intent: &IntentId,
1831 relation: PlanIntentRelation,
1832 ) -> Result<(), StoreError> {
1833 self.lock().execute(
1834 "INSERT INTO plan_intent (plan_id, intent_id, relation)
1835 VALUES (?1, ?2, ?3)
1836 ON CONFLICT DO NOTHING",
1837 params![
1838 plan.as_str(),
1839 intent.as_str(),
1840 plan_intent_relation_to_str(relation),
1841 ],
1842 )?;
1843 Ok(())
1844 }
1845
1846 #[instrument(skip(self, decision), fields(decision_id = decision.id.as_str()))]
1849 fn upsert_decision(&mut self, decision: &Decision) -> Result<(), StoreError> {
1850 let now = Self::now();
1851 let meta = decision.meta.as_ref().map(|v| v.to_string());
1852 self.lock().execute(
1853 "INSERT INTO decision
1854 (id, space_id, title, status, context, body, source_file, created_at, updated_at, meta)
1855 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10)
1856 ON CONFLICT(id) DO UPDATE SET
1857 title = excluded.title,
1858 status = excluded.status,
1859 context = excluded.context,
1860 body = excluded.body,
1861 source_file= excluded.source_file,
1862 updated_at = excluded.updated_at,
1863 meta = excluded.meta",
1864 params![
1865 decision.id.as_str(),
1866 decision.space_id.as_str(),
1867 decision.title,
1868 decision_status_to_str(decision.status),
1869 decision.context,
1870 decision.body,
1871 decision.source_file.as_ref().map(|p| p.to_string_lossy().into_owned()),
1872 decision.created_at.as_i64(),
1873 now,
1874 meta,
1875 ],
1876 )?;
1877 Ok(())
1878 }
1879
1880 #[instrument(skip(self), fields(space_id = space.as_str()))]
1881 fn list_decisions(&self, space: &SpaceId) -> Result<Vec<Decision>, StoreError> {
1882 let conn = self.lock();
1883 let mut stmt = conn.prepare(
1884 "SELECT id, space_id, title, status, context, body, source_file,
1885 created_at, updated_at, meta
1886 FROM decision WHERE space_id = ?1 ORDER BY created_at",
1887 )?;
1888 let rows = stmt
1889 .query_map(params![space.as_str()], row_to_decision)?
1890 .collect::<rusqlite::Result<Vec<_>>>()?;
1891 Ok(rows)
1892 }
1893
1894 #[instrument(skip(self), fields(space_id = space.as_str(), substrate))]
1897 fn set_substrate_budget(
1898 &mut self,
1899 space: &SpaceId,
1900 substrate: &str,
1901 wip_cap: u32,
1902 stale_threshold_days: u32,
1903 ) -> Result<(), StoreError> {
1904 let now = Self::now();
1905 self.lock().execute(
1906 "INSERT INTO substrate_budget
1907 (space_id, substrate, wip_cap, stale_threshold_days, last_updated)
1908 VALUES (?1,?2,?3,?4,?5)
1909 ON CONFLICT(space_id, substrate) DO UPDATE SET
1910 wip_cap = excluded.wip_cap,
1911 stale_threshold_days = excluded.stale_threshold_days,
1912 last_updated = excluded.last_updated",
1913 params![
1914 space.as_str(),
1915 substrate,
1916 wip_cap,
1917 stale_threshold_days,
1918 now
1919 ],
1920 )?;
1921 Ok(())
1922 }
1923
1924 #[instrument(skip(self), fields(space_id = space.as_str(), substrate))]
1925 fn get_substrate_budget(
1926 &self,
1927 space: &SpaceId,
1928 substrate: &str,
1929 ) -> Result<SubstrateBudget, StoreError> {
1930 let result = self
1931 .lock()
1932 .query_row(
1933 "SELECT substrate, wip_cap, stale_threshold_days
1934 FROM substrate_budget WHERE space_id = ?1 AND substrate = ?2",
1935 params![space.as_str(), substrate],
1936 |row| {
1937 Ok(SubstrateBudget {
1938 substrate: row.get(0)?,
1939 wip_cap: row.get(1)?,
1940 stale_threshold_days: row.get(2)?,
1941 })
1942 },
1943 )
1944 .optional()?;
1945
1946 Ok(result.unwrap_or_else(|| SubstrateBudget::default_for(substrate)))
1947 }
1948
1949 #[instrument(skip(self), fields(space_id = space.as_str()))]
1950 fn list_substrate_budgets(&self, space: &SpaceId) -> Result<Vec<SubstrateBudget>, StoreError> {
1951 let conn = self.lock();
1952 let mut stmt = conn.prepare(
1953 "SELECT substrate, wip_cap, stale_threshold_days
1954 FROM substrate_budget WHERE space_id = ?1 ORDER BY substrate",
1955 )?;
1956 let rows = stmt
1957 .query_map(params![space.as_str()], |row| {
1958 Ok(SubstrateBudget {
1959 substrate: row.get(0)?,
1960 wip_cap: row.get(1)?,
1961 stale_threshold_days: row.get(2)?,
1962 })
1963 })?
1964 .collect::<rusqlite::Result<Vec<_>>>()?;
1965 Ok(rows)
1966 }
1967
1968 #[instrument(skip(self), fields(canonical, alias))]
1971 fn add_capability_alias(&mut self, canonical: &str, alias: &str) -> Result<(), StoreError> {
1972 let now = Self::now();
1973 self.lock().execute(
1974 "INSERT INTO capability_alias (canonical, alias, created_at)
1975 VALUES (?1, ?2, ?3)
1976 ON CONFLICT DO NOTHING",
1977 params![canonical, alias, now],
1978 )?;
1979 Ok(())
1980 }
1981
1982 #[instrument(skip(self), fields(ref_name))]
1983 fn resolve_canonical(&self, ref_name: &str) -> Result<String, StoreError> {
1984 let result: Option<String> = self
1986 .lock()
1987 .query_row(
1988 "SELECT canonical FROM capability_alias WHERE alias = ?1 LIMIT 1",
1989 params![ref_name],
1990 |row| row.get(0),
1991 )
1992 .optional()?;
1993 Ok(result.unwrap_or_else(|| ref_name.to_owned()))
1994 }
1995
1996 #[instrument(skip(self, draft),
2003 fields(
2004 space_id = draft.space_id.as_str(),
2005 substrate = draft.substrate.as_deref().unwrap_or(""),
2006 cap_names_count = draft.touched_capabilities.len()
2007 ))]
2008 fn planner_intent_check(&self, draft: &PlanDraft) -> Result<RawIntentCheckPayload, StoreError> {
2009 let space_id = draft.space_id.as_str();
2010 let substrate = draft.substrate.as_deref().unwrap_or("");
2011 let title = draft.title.as_str();
2012 let _cap_names_json = serde_json::to_string(&draft.touched_capabilities)?;
2013
2014 let resolved_caps: Vec<String> = draft
2016 .touched_capabilities
2017 .iter()
2018 .map(|n| self.resolve_canonical(n).unwrap_or_else(|_| n.clone()))
2019 .collect();
2020 let resolved_caps_json = serde_json::to_string(&resolved_caps)?;
2021
2022 let sql = r#"
2023WITH
2024
2025existing_matches AS (
2026 SELECT
2027 p.id,
2028 p.title,
2029 p.status,
2030 p.substrate,
2031 p.wip_weight,
2032 p.updated_at,
2033 'substrate_overlap' AS match_kind
2034 FROM plan p
2035 WHERE p.space_id = ?1
2036 AND p.status NOT IN ('Done', 'Parked')
2037 AND (
2038 p.substrate = ?2
2039 OR p.title LIKE '%' || ?3 || '%'
2040 OR ?3 LIKE '%' || p.title || '%'
2041 )
2042
2043 UNION
2044
2045 SELECT
2046 p.id, p.title, p.status, p.substrate, p.wip_weight, p.updated_at,
2047 'capability_overlap' AS match_kind
2048 FROM plan p
2049 JOIN plan_capability pc ON pc.plan_id = p.id
2050 JOIN capability c ON c.id = pc.capability_id
2051 WHERE p.space_id = ?1
2052 AND p.status NOT IN ('Done', 'Parked')
2053 AND EXISTS (
2054 SELECT 1 FROM json_each(?4) jn WHERE jn.value = c.name
2055 )
2056),
2057
2058budget AS (
2059 -- Returns one row whenever ?2 (substrate) is non-empty, falling back to
2060 -- the defaults from g8_core (wip_cap=3, stale_threshold_days=14) when
2061 -- no substrate_budget row has been registered yet.
2062 SELECT
2063 ?2 AS substrate,
2064 cap.wip_cap,
2065 cap.stale_threshold_days,
2066 cnt.wip_current,
2067 (cap.wip_cap - cnt.wip_current) AS wip_remaining,
2068 CASE WHEN cnt.wip_current >= cap.wip_cap THEN 1 ELSE 0 END AS at_cap
2069 FROM
2070 (SELECT
2071 COALESCE(
2072 (SELECT wip_cap FROM substrate_budget
2073 WHERE space_id = ?1 AND substrate = ?2),
2074 3
2075 ) AS wip_cap,
2076 COALESCE(
2077 (SELECT stale_threshold_days FROM substrate_budget
2078 WHERE space_id = ?1 AND substrate = ?2),
2079 14
2080 ) AS stale_threshold_days
2081 ) AS cap,
2082 -- WIP counts both Dispatched AND Blocked plans: per SPEC §7, "Blocked
2083 -- doesn't free a slot — blocked work still occupies the substrate's
2084 -- attention surface." Counting only Dispatched would let a Blocked plan
2085 -- silently free a slot, contradicting that intent (and the `bottlenecks`
2086 -- CTE below, which already counts both).
2087 (SELECT COUNT(*) AS wip_current
2088 FROM plan
2089 WHERE space_id = ?1
2090 AND substrate = ?2
2091 AND status IN ('Dispatched', 'Blocked')
2092 ) AS cnt
2093 WHERE ?2 != ''
2094),
2095
2096bottlenecks AS (
2097 SELECT
2098 p.id, p.title, p.status, p.blocked_reason,
2099 p.dispatched_at, p.updated_at,
2100 CASE WHEN p.dispatched_at IS NOT NULL
2101 THEN (unixepoch('now') * 1000 - p.dispatched_at) / 86400000
2102 ELSE NULL END AS days_in_flight
2103 FROM plan p
2104 WHERE p.space_id = ?1
2105 AND p.substrate = ?2
2106 AND p.status IN ('Dispatched', 'Blocked')
2107 ORDER BY p.dispatched_at ASC
2108 LIMIT 3
2109),
2110
2111drift_hints AS (
2112 SELECT
2113 p.id, p.title, p.status, p.updated_at,
2114 (unixepoch('now') * 1000 - p.updated_at) / 86400000 AS days_stale
2115 FROM plan p
2116 JOIN substrate_budget sb
2117 ON sb.space_id = p.space_id
2118 AND sb.substrate = p.substrate
2119 WHERE p.space_id = ?1
2120 AND p.substrate = ?2
2121 AND p.status NOT IN ('Done', 'Parked')
2122 AND ((unixepoch('now') * 1000 - p.updated_at) / 86400000)
2123 > sb.stale_threshold_days
2124),
2125
2126intent_overlaps AS (
2127 SELECT
2128 i.id, i.heading AS title, i.substrate, i.source_kind, i.source_file,
2129 pr.name AS project_name
2130 FROM intent i
2131 LEFT JOIN project pr ON pr.id = i.project_id
2132 WHERE i.space_id = ?1
2133 AND i.kind != 'operational'
2134 AND (
2135 i.substrate = ?2
2136 OR i.heading LIKE '%' || ?3 || '%'
2137 )
2138 ORDER BY i.scope_depth DESC, i.updated_at DESC
2139 LIMIT 20
2140),
2141
2142parked_ideas AS (
2143 SELECT
2144 p.id, p.title, p.parked_reason, p.updated_at
2145 FROM plan p
2146 WHERE p.space_id = ?1
2147 AND p.status = 'Parked'
2148 AND (
2149 p.substrate = ?2
2150 OR p.title LIKE '%' || ?3 || '%'
2151 )
2152 ORDER BY p.updated_at DESC
2153 LIMIT 10
2154)
2155
2156SELECT
2157 (SELECT json_group_array(json_object(
2158 'id', em.id, 'title', em.title, 'status', em.status,
2159 'substrate', em.substrate, 'match_kind', em.match_kind
2160 )) FROM existing_matches em) AS existing_matches,
2161
2162 (SELECT json_object(
2163 'substrate', b.substrate,
2164 'wip_cap', b.wip_cap,
2165 'wip_current', b.wip_current,
2166 'wip_remaining', b.wip_remaining,
2167 -- json('true'/'false') ensures a real JSON boolean, not 0/1 ints
2168 -- (BudgetStatus.at_cap is bool — int trips serde deserialization).
2169 'at_cap', json(CASE WHEN b.at_cap = 1 THEN 'true' ELSE 'false' END)
2170 ) FROM budget b LIMIT 1) AS budget,
2171
2172 (SELECT json_group_array(json_object(
2173 'id', bn.id, 'title', bn.title, 'status', bn.status,
2174 'blocked_reason', bn.blocked_reason,
2175 'days_in_flight', bn.days_in_flight
2176 )) FROM bottlenecks bn) AS bottlenecks,
2177
2178 (SELECT json_group_array(json_object(
2179 'id', dh.id, 'title', dh.title, 'status', dh.status,
2180 'days_stale', dh.days_stale
2181 )) FROM drift_hints dh) AS drift_hints,
2182
2183 (SELECT json_group_array(json_object(
2184 'id', io.id, 'title', io.title, 'substrate', io.substrate,
2185 'source_kind', io.source_kind, 'project', io.project_name
2186 )) FROM intent_overlaps io) AS intent_overlaps,
2187
2188 (SELECT json_group_array(json_object(
2189 'id', pk.id, 'title', pk.title, 'parked_reason', pk.parked_reason
2190 )) FROM parked_ideas pk) AS parked_ideas
2191"#;
2192
2193 let result = self.lock().query_row(
2194 sql,
2195 params![space_id, substrate, title, resolved_caps_json],
2196 |row| {
2197 let existing_matches_str: Option<String> = row.get(0)?;
2198 let budget_str: Option<String> = row.get(1)?;
2199 let bottlenecks_str: Option<String> = row.get(2)?;
2200 let drift_hints_str: Option<String> = row.get(3)?;
2201 let intent_overlaps_str: Option<String> = row.get(4)?;
2202 let parked_ideas_str: Option<String> = row.get(5)?;
2203 Ok((
2204 existing_matches_str,
2205 budget_str,
2206 bottlenecks_str,
2207 drift_hints_str,
2208 intent_overlaps_str,
2209 parked_ideas_str,
2210 ))
2211 },
2212 )?;
2213
2214 let (
2215 existing_matches_str,
2216 budget_str,
2217 bottlenecks_str,
2218 drift_hints_str,
2219 intent_overlaps_str,
2220 parked_ideas_str,
2221 ) = result;
2222
2223 let parse_array = |s: Option<String>| -> serde_json::Value {
2224 s.and_then(|s| serde_json::from_str(&s).ok())
2225 .unwrap_or(serde_json::Value::Array(vec![]))
2226 };
2227 let parse_obj = |s: Option<String>| -> serde_json::Value {
2228 s.and_then(|s| serde_json::from_str(&s).ok())
2229 .unwrap_or(serde_json::Value::Null)
2230 };
2231
2232 Ok(RawIntentCheckPayload {
2233 existing_matches: parse_array(existing_matches_str),
2234 budget: parse_obj(budget_str),
2235 bottlenecks: parse_array(bottlenecks_str),
2236 drift_hints: parse_array(drift_hints_str),
2237 intent_overlaps: parse_array(intent_overlaps_str),
2238 parked_ideas: parse_array(parked_ideas_str),
2239 })
2240 }
2241
2242 #[instrument(skip(self), fields(project = project.as_ref().map(|p| p.as_str()).unwrap_or("all")))]
2245 fn pairing_check(&self, project: Option<&ProjectId>) -> Result<Vec<PairingError>, StoreError> {
2246 let conn = self.lock();
2247 let mut errors: Vec<PairingError> = Vec::new();
2248 let now_ms = Self::now();
2249 let seven_days_ms: i64 = 7 * 24 * 60 * 60 * 1000;
2250
2251 let (cap_sql, cap_params): (String, Vec<String>) = if let Some(proj) = project {
2253 (
2254 "SELECT id, name, stub, stub_since, file_path, line_number, project_id
2255 FROM capability WHERE project_id = ?1 AND conditional = 0"
2256 .to_owned(),
2257 vec![proj.as_str().to_owned()],
2258 )
2259 } else {
2260 (
2261 "SELECT id, name, stub, stub_since, file_path, line_number, project_id
2262 FROM capability WHERE conditional = 0"
2263 .to_owned(),
2264 vec![],
2265 )
2266 };
2267
2268 let mut stmt = conn.prepare(&cap_sql)?;
2269 let cap_refs: Vec<&dyn rusqlite::ToSql> = cap_params
2270 .iter()
2271 .map(|s| s as &dyn rusqlite::ToSql)
2272 .collect();
2273
2274 struct CapRow {
2275 id: String,
2276 name: String,
2277 stub: bool,
2278 stub_since: Option<String>,
2279 file_path: String,
2280 line_number: u32,
2281 project_id: String,
2282 }
2283
2284 let capabilities: Vec<CapRow> = stmt
2285 .query_map(cap_refs.as_slice(), |row| {
2286 Ok(CapRow {
2287 id: row.get(0)?,
2288 name: row.get(1)?,
2289 stub: row.get::<_, i64>(2).map(|v| v != 0)?,
2290 stub_since: row.get(3)?,
2291 file_path: row.get::<_, Option<String>>(4)?.unwrap_or_default(),
2292 line_number: row.get::<_, Option<u32>>(5)?.unwrap_or(0),
2293 project_id: row.get(6)?,
2294 })
2295 })?
2296 .collect::<rusqlite::Result<Vec<_>>>()?;
2297
2298 {
2300 type NameCountMap =
2301 std::collections::HashMap<(String, String), Vec<(String, String, u32)>>;
2302 let mut name_counts: NameCountMap = std::collections::HashMap::new();
2303 for cap in &capabilities {
2304 name_counts
2305 .entry((cap.project_id.clone(), cap.name.clone()))
2306 .or_default()
2307 .push((cap.id.clone(), cap.file_path.clone(), cap.line_number));
2308 }
2309 for ((_, name), entries) in &name_counts {
2310 if entries.len() > 1 {
2311 for (_, file_path, line_number) in entries {
2312 errors.push(PairingError {
2313 capability: name.clone(),
2314 file: PathBuf::from(file_path),
2315 line: *line_number,
2316 reason: PairingErrorReason::DuplicateCapabilityName,
2317 });
2318 }
2319 }
2320 }
2321 }
2322
2323 for cap in &capabilities {
2325 if cap.stub {
2326 match &cap.stub_since {
2327 None => {
2328 errors.push(PairingError {
2329 capability: cap.name.clone(),
2330 file: PathBuf::from(&cap.file_path),
2331 line: cap.line_number,
2332 reason: PairingErrorReason::StubMissingSince,
2333 });
2334 continue;
2335 }
2336 Some(since_str) => {
2337 if let Ok(since_date) = NaiveDate::parse_from_str(since_str, "%Y-%m-%d") {
2338 let since_ts = since_date
2339 .and_hms_opt(0, 0, 0)
2340 .map(|dt| dt.and_utc().timestamp_millis())
2341 .unwrap_or(0);
2342 if now_ms - since_ts > seven_days_ms {
2343 errors.push(PairingError {
2344 capability: cap.name.clone(),
2345 file: PathBuf::from(&cap.file_path),
2346 line: cap.line_number,
2347 reason: PairingErrorReason::StubExpired,
2348 });
2349 }
2350 }
2351 continue;
2353 }
2354 }
2355 }
2356
2357 let has_test: bool = conn
2359 .query_row(
2360 "SELECT COUNT(*) FROM annotation
2361 WHERE project_id = ?1
2362 AND kind = 'convergence_test'
2363 AND json_extract(payload, '$.for_capability') = ?2",
2364 params![cap.project_id, cap.name],
2365 |row| row.get::<_, i64>(0),
2366 )
2367 .unwrap_or(0)
2368 > 0;
2369
2370 if !has_test {
2371 errors.push(PairingError {
2372 capability: cap.name.clone(),
2373 file: PathBuf::from(&cap.file_path),
2374 line: cap.line_number,
2375 reason: PairingErrorReason::NoMatchingConvergenceTest,
2376 });
2377 }
2378 }
2379
2380 Ok(errors)
2381 }
2382
2383 #[instrument(skip(self), fields(space_id = space.as_str()))]
2386 fn stale_dispatched_plans(
2387 &self,
2388 space: &SpaceId,
2389 ) -> Result<Vec<StalePlanCandidate>, StoreError> {
2390 let conn = self.lock();
2391 let mut stmt = conn.prepare(
2392 "SELECT p.id, p.title, p.substrate, p.dispatched_at,
2393 (unixepoch('now') * 1000 - p.dispatched_at) / 86400000 AS days_stale
2394 FROM plan p
2395 JOIN substrate_budget sb
2396 ON sb.space_id = p.space_id
2397 AND sb.substrate = p.substrate
2398 WHERE p.space_id = ?1
2399 AND p.status = 'Dispatched'
2400 AND p.dispatched_at IS NOT NULL
2401 AND ((unixepoch('now') * 1000 - p.dispatched_at) / 86400000) > sb.stale_threshold_days
2402 ORDER BY days_stale DESC",
2403 )?;
2404 let rows = stmt
2405 .query_map(params![space.as_str()], |row| {
2406 let id_str: String = row.get(0)?;
2407 let title: String = row.get(1)?;
2408 let substrate: Option<String> = row.get(2)?;
2409 let dispatched_at: i64 = row.get(3)?;
2410 let days_stale: i64 = row.get(4)?;
2411 Ok((id_str, title, substrate, dispatched_at, days_stale))
2412 })?
2413 .collect::<rusqlite::Result<Vec<_>>>()?;
2414
2415 rows.into_iter()
2416 .map(|(id_str, title, substrate, dispatched_at, days_stale)| {
2417 Ok(StalePlanCandidate {
2418 plan_id: PlanId::from_string(id_str)?,
2419 title,
2420 substrate,
2421 dispatched_at: EpochMillis::from_i64(dispatched_at),
2422 days_stale,
2423 })
2424 })
2425 .collect()
2426 }
2427
2428 #[instrument(skip(self), fields(alias, path = path.display().to_string().as_str()))]
2431 fn attach_remote_store(&mut self, alias: &str, path: &Path) -> Result<(), StoreError> {
2432 if alias.is_empty() || !alias.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
2443 return Err(StoreError::InvalidTransition(format!(
2444 "attach alias '{alias}' must be a non-empty [A-Za-z0-9_] identifier"
2445 )));
2446 }
2447 let uri = format!("file:{}?mode=ro", encode_uri_path(&path.to_string_lossy()));
2448 self.lock()
2449 .execute(&format!("ATTACH DATABASE ?1 AS \"{alias}\""), params![uri])?;
2450 Ok(())
2451 }
2452
2453 #[instrument(skip(self), fields(alias))]
2454 fn detach_remote_store(&mut self, alias: &str) -> Result<(), StoreError> {
2455 self.lock()
2456 .execute_batch(&format!("DETACH DATABASE \"{alias}\""))?;
2457 Ok(())
2458 }
2459
2460 fn watch<F>(&self, callback: F) -> Result<WatchHandle, StoreError>
2463 where
2464 F: Fn() + Send + 'static,
2465 {
2466 use notify::{Event, EventKind, RecursiveMode, Watcher};
2467
2468 let mut watcher = notify::recommended_watcher(move |res: notify::Result<Event>| {
2469 if let Ok(event) = res {
2470 match event.kind {
2471 EventKind::Modify(_) | EventKind::Create(_) | EventKind::Remove(_) => {
2472 callback();
2473 }
2474 _ => {}
2475 }
2476 }
2477 })
2478 .map_err(|e| StoreError::Notify(e.to_string()))?;
2479
2480 if self.store_path.as_os_str() != ":memory:" {
2481 watcher
2482 .watch(&self.store_path, RecursiveMode::NonRecursive)
2483 .map_err(|e| StoreError::Notify(e.to_string()))?;
2484 }
2485
2486 Ok(WatchHandle::new(watcher))
2487 }
2488}
2489
2490