Skip to main content

g8_planner/
lib.rs

1//! `g8-planner` — composite-query orchestration and recommendation derivation.
2//!
3//! This crate is a **pure deterministic transformer** over [`StoreConnection`].
4//! It calls **exactly one** store method — [`StoreConnection::planner_intent_check`]
5//! — and post-processes the six JSON payloads it receives into a structured
6//! [`FitReport`] with a deterministic [`Recommendation`].
7//!
8//! # Design constraints (from ARCHITECTURE.md §5 and §11)
9//!
10//! - **No LLM calls.** No async runtime. No HTTP. No direct file I/O.
11//! - **One store call per `plan_check` invocation.**  The composite-query
12//!   principle (SPEC §3 principle 2) forbids verb chains; all SQL work is done
13//!   inside `planner_intent_check` on the store side.
14//! - **Deterministic.** Same `PlanDraft` + same store contents → same `FitReport`
15//!   and `Recommendation` every time.
16//!
17//! # ARCHITECTURE_GAP
18//!
19//! `ARCHITECTURE.md §3.4` specifies `pub fn plan_check(store: &dyn StoreConnection, …)`.
20//! However, `StoreConnection` contains a generic method (`watch<F>`) which makes
21//! it object-unsafe (not dyn-compatible).  The equivalent and idiomatic Rust fix
22//! is to accept `store: &S where S: StoreConnection`, which is what this crate
23//! implements.  All call sites are unaffected.
24//!
25//! # Example
26//!
27//! ```no_run
28//! use g8_planner::Planner;
29//! use g8_core::{plan::PlanDraft, SpaceId};
30//! use g8_store::RusqliteStore;
31//!
32//! // In production the CLI opens a RusqliteStore and passes it here.
33//! let mut store = RusqliteStore::open_in_memory().unwrap();
34//! store.migrate().unwrap();
35//!
36//! let draft = PlanDraft {
37//!     title: "streaming-export".into(),
38//!     description: None,
39//!     substrate: Some("export-pipeline".into()),
40//!     touched_capabilities: vec![],
41//!     touched_paths: vec![],
42//!     space_id: SpaceId::derive(&["docs", "space"]),
43//!     project_id: None,
44//! };
45//! let report = Planner::plan_check(&store, &draft).unwrap();
46//! assert_eq!(report.recommendation, g8_core::Recommendation::Proceed);
47//! ```
48
49use g8_core::{
50    plan::{
51        BottleneckPlan, BudgetStatus, DecisionInput, DriftHint, ExistingMatch, FitReport,
52        IntentOverlap, ParkedIdeaMatch, PlanDraft,
53    },
54    recommend, G8Error,
55};
56use g8_store::{StoreConnection, StoreError};
57use tracing::instrument;
58
59// ── Error ────────────────────────────────────────────────────────────────────
60
61/// Errors produced by [`Planner::plan_check`].
62///
63/// The three variants map to the three failure modes:
64/// - The underlying store query failed.
65/// - Deserialization of a JSON payload column failed (store contract violation).
66/// - The `PlanDraft` itself is structurally invalid before the query runs.
67#[derive(Debug, thiserror::Error)]
68pub enum PlannerError {
69    /// An error propagated from the store layer.
70    #[error(transparent)]
71    Store(#[from] StoreError),
72    /// An `g8-core` error (e.g. a deserialized value failed a type contract).
73    #[error(transparent)]
74    Core(#[from] G8Error),
75    /// The draft is malformed and cannot be planned.
76    #[error("invalid draft: {0}")]
77    InvalidDraft(String),
78}
79
80// ── Planner ──────────────────────────────────────────────────────────────────
81
82/// Stateless planner that turns a [`PlanDraft`] into a [`FitReport`].
83///
84/// `Planner` is a unit struct; all behaviour is on the associated function
85/// [`Planner::plan_check`].  There is no state to initialise.
86///
87/// # Note on the store parameter
88///
89/// `plan_check` accepts `store: &S where S: StoreConnection`.
90/// `ARCHITECTURE.md §3.4` specifies `&dyn StoreConnection`, but
91/// `StoreConnection` is not object-safe (it contains a generic `watch<F>`
92/// method).  The generic-parameter form is semantically identical at all
93/// call sites.  See ARCHITECTURE_GAP in the crate docs.
94pub struct Planner;
95
96impl Planner {
97    /// Evaluate a [`PlanDraft`] against the store and return a [`FitReport`].
98    ///
99    /// This function makes **exactly one** store call:
100    /// [`StoreConnection::planner_intent_check`].  All other work is pure
101    /// in-memory deserialization and the deterministic `recommend` lookup.
102    ///
103    /// # Tracing
104    ///
105    /// Opens a span `planner.plan_check` with fields:
106    /// - `space_id` — from the draft
107    /// - `recommendation` — emitted on span exit
108    ///
109    /// # Errors
110    ///
111    /// Returns [`PlannerError::Store`] if the composite query fails.
112    /// Returns [`PlannerError::InvalidDraft`] if `draft.title` is empty or
113    /// whitespace-only.
114    ///
115    /// # Examples
116    ///
117    /// ```no_run
118    /// use g8_planner::Planner;
119    /// use g8_core::{plan::PlanDraft, SpaceId, Recommendation};
120    /// use g8_store::RusqliteStore;
121    ///
122    /// let mut store = RusqliteStore::open_in_memory().unwrap();
123    /// store.migrate().unwrap();
124    ///
125    /// let draft = PlanDraft {
126    ///     title: "new-feature".into(),
127    ///     description: None,
128    ///     substrate: None,
129    ///     touched_capabilities: vec![],
130    ///     touched_paths: vec![],
131    ///     space_id: SpaceId::derive(&["docs", "space"]),
132    ///     project_id: None,
133    /// };
134    /// let report = Planner::plan_check(&store, &draft).unwrap();
135    /// assert_eq!(report.recommendation, Recommendation::Proceed);
136    /// ```
137    #[instrument(
138        name = "planner.plan_check",
139        skip(store, draft),
140        fields(
141            space_id = %draft.space_id.as_str(),
142            recommendation = tracing::field::Empty,
143        )
144    )]
145    pub fn plan_check<S>(store: &S, draft: &PlanDraft) -> Result<FitReport, PlannerError>
146    where
147        S: StoreConnection,
148    {
149        // ── Input validation ───────────────────────────────────────────────
150        if draft.title.trim().is_empty() {
151            return Err(PlannerError::InvalidDraft(
152                "plan title must not be empty".into(),
153            ));
154        }
155
156        // ── SINGLE composite store call ────────────────────────────────────
157        // This is the only store call in the entire function.  The composite
158        // query returns six JSON columns in one read transaction.
159        let raw = store.planner_intent_check(draft)?;
160
161        // ── Deserialize six JSON payloads ──────────────────────────────────
162        let existing_matches: Vec<ExistingMatch> =
163            deserialize_array(raw.existing_matches, "existing_matches")?;
164        let budget_status: Option<BudgetStatus> = deserialize_optional(raw.budget, "budget")?;
165        let bottlenecks: Vec<BottleneckPlan> = deserialize_array(raw.bottlenecks, "bottlenecks")?;
166        let drift_hints: Vec<DriftHint> = deserialize_array(raw.drift_hints, "drift_hints")?;
167        let intent_overlaps: Vec<IntentOverlap> =
168            deserialize_array(raw.intent_overlaps, "intent_overlaps")?;
169        let parked_ideas: Vec<ParkedIdeaMatch> =
170            deserialize_array(raw.parked_ideas, "parked_ideas")?;
171
172        // ── Build DecisionInput from deserialized data ─────────────────────
173        let decision_input = DecisionInput {
174            any_over_budget: budget_status.as_ref().map(|b| b.at_cap).unwrap_or(false),
175            has_exact_match: existing_matches.iter().any(|m| m.title == draft.title),
176            near_match_count: existing_matches.len() as u32,
177            has_parked_match: !parked_ideas.is_empty(),
178            bottleneck_count: bottlenecks.len() as u32,
179        };
180
181        // ── Derive recommendation (pure lookup table) ──────────────────────
182        let recommendation = recommend(&decision_input);
183
184        // Record the recommendation on the tracing span for observability.
185        tracing::Span::current().record("recommendation", format!("{recommendation:?}").as_str());
186
187        Ok(FitReport {
188            draft: draft.clone(),
189            existing_matches,
190            budget_status,
191            bottlenecks,
192            drift_hints,
193            intent_overlaps,
194            parked_ideas,
195            decision_input,
196            recommendation,
197        })
198    }
199}
200
201// ── Private helpers ──────────────────────────────────────────────────────────
202
203/// Deserialize a JSON value that must be an array (possibly empty).
204///
205/// `json_group_array(...)` from SQLite returns `NULL` when there are no rows
206/// and a JSON array string otherwise.  We normalise both cases to `Vec<T>`.
207fn deserialize_array<T>(value: serde_json::Value, field: &str) -> Result<Vec<T>, PlannerError>
208where
209    T: serde::de::DeserializeOwned,
210{
211    match value {
212        serde_json::Value::Null => Ok(vec![]),
213        other => serde_json::from_value::<Vec<T>>(other).map_err(|e| deserialize_err(field, e)),
214    }
215}
216
217/// Deserialize a JSON value that represents an optional object.
218///
219/// `json_object(...)` from SQLite returns `NULL` when there are no matching
220/// budget rows; we convert that to `None`.
221fn deserialize_optional<T>(value: serde_json::Value, field: &str) -> Result<Option<T>, PlannerError>
222where
223    T: serde::de::DeserializeOwned,
224{
225    match value {
226        serde_json::Value::Null => Ok(None),
227        other => serde_json::from_value::<T>(other)
228            .map(Some)
229            .map_err(|e| deserialize_err(field, e)),
230    }
231}
232
233/// Convert a `serde_json::Error` into a `PlannerError` with a diagnostic
234/// message that includes the field name.
235///
236/// We roundtrip through a synthetic invalid JSON string to obtain a
237/// `serde_json::Error` carrying our message, then wrap it in `StoreError::Serde`.
238fn deserialize_err(field: &str, e: serde_json::Error) -> PlannerError {
239    let msg = format!("planner: failed to deserialize '{field}': {e}");
240    // serde_json::from_str on invalid JSON always produces an Err.
241    let inner: serde_json::Error = serde_json::from_str::<()>(&msg).unwrap_err();
242    PlannerError::Store(StoreError::Serde(inner))
243}