1use std::sync::Arc;
8
9use derive_more::{Display, From};
10use indexmap::IndexMap;
11#[cfg(feature = "schemars")]
12use schemars::Schema;
13use serde::{Deserialize, Serialize};
14use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none};
15
16use super::{AbsolutePath, Meta};
17use crate::IntoOption;
18
19#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
21#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
22#[serde(transparent)]
23#[from(forward)]
24#[non_exhaustive]
25pub struct PlanId(pub Arc<str>);
26
27impl PlanId {
28 #[must_use]
30 pub fn new(id: impl Into<Self>) -> Self {
31 id.into()
32 }
33}
34
35#[serde_as]
37#[skip_serializing_none]
38#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
39#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
40#[serde(rename_all = "camelCase")]
41#[non_exhaustive]
42pub struct PlanUpdate {
43 pub plan: PlanUpdateContent,
45 #[serde_as(deserialize_as = "DefaultOnError")]
51 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
52 #[serde(default)]
53 #[serde(rename = "_meta")]
54 pub meta: Option<Meta>,
55}
56
57impl PlanUpdate {
58 #[must_use]
60 pub fn new(plan: PlanUpdateContent) -> Self {
61 Self { plan, meta: None }
62 }
63
64 #[must_use]
70 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
71 self.meta = meta.into_option();
72 self
73 }
74}
75
76#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
78#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
79#[serde(tag = "type", rename_all = "snake_case")]
80#[non_exhaustive]
81pub enum PlanUpdateContent {
82 Items(PlanItems),
84 Markdown(PlanMarkdown),
86 #[serde(untagged)]
97 Other(OtherPlanUpdateContent),
98}
99
100#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
102#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
103#[cfg_attr(feature = "schemars", schemars(inline))]
104#[cfg_attr(feature = "schemars", schemars(transform = other_plan_update_content_schema))]
105#[serde(rename_all = "camelCase")]
106#[non_exhaustive]
107pub struct OtherPlanUpdateContent {
108 #[serde(rename = "type")]
114 pub type_: String,
115 pub plan_id: PlanId,
117 #[serde(flatten)]
119 pub fields: IndexMap<String, serde_json::Value>,
120}
121
122impl OtherPlanUpdateContent {
123 #[must_use]
125 pub fn new(
126 type_: impl Into<String>,
127 plan_id: impl Into<PlanId>,
128 mut fields: IndexMap<String, serde_json::Value>,
129 ) -> Self {
130 fields.shift_remove("type");
131 fields.shift_remove("planId");
132 Self {
133 type_: type_.into(),
134 plan_id: plan_id.into(),
135 fields,
136 }
137 }
138}
139
140impl<'de> Deserialize<'de> for OtherPlanUpdateContent {
141 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
142 where
143 D: serde::Deserializer<'de>,
144 {
145 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
146 let type_ = fields
147 .shift_remove("type")
148 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
149 let serde_json::Value::String(type_) = type_ else {
150 return Err(serde::de::Error::custom("`type` must be a string"));
151 };
152 let plan_id = fields
153 .shift_remove("planId")
154 .ok_or_else(|| serde::de::Error::missing_field("planId"))?;
155 let serde_json::Value::String(plan_id) = plan_id else {
156 return Err(serde::de::Error::custom("`planId` must be a string"));
157 };
158
159 if is_known_plan_update_content_type(&type_) {
160 return Err(serde::de::Error::custom(format!(
161 "known plan update content `{type_}` did not match its schema"
162 )));
163 }
164
165 Ok(Self {
166 type_,
167 plan_id: PlanId::new(plan_id),
168 fields,
169 })
170 }
171}
172
173fn is_known_plan_update_content_type(type_: &str) -> bool {
174 KNOWN_PLAN_UPDATE_CONTENT_TYPES.contains(&type_)
175}
176
177#[cfg(feature = "schemars")]
178fn other_plan_update_content_schema(schema: &mut Schema) {
179 super::schema_util::reject_known_string_discriminators(
180 schema,
181 "type",
182 KNOWN_PLAN_UPDATE_CONTENT_TYPES,
183 );
184}
185
186const KNOWN_PLAN_UPDATE_CONTENT_TYPES: &[&str] = &["items", "markdown"];
187
188impl PlanUpdateContent {
189 #[must_use]
191 pub fn items(plan_id: impl Into<PlanId>, entries: Vec<PlanEntry>) -> Self {
192 Self::Items(PlanItems::new(plan_id, entries))
193 }
194
195 #[must_use]
200 pub fn markdown(plan_id: impl Into<PlanId>, content: impl Into<String>) -> Self {
201 Self::Markdown(PlanMarkdown::new(plan_id, content))
202 }
203}
204
205#[serde_as]
207#[skip_serializing_none]
208#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
209#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
210#[serde(rename_all = "camelCase")]
211#[non_exhaustive]
212pub struct PlanItems {
213 pub plan_id: PlanId,
215 #[serde_as(deserialize_as = "VecSkipError<_>")]
220 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
221 pub entries: Vec<PlanEntry>,
222 #[serde_as(deserialize_as = "DefaultOnError")]
228 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
229 #[serde(default)]
230 #[serde(rename = "_meta")]
231 pub meta: Option<Meta>,
232}
233
234impl PlanItems {
235 #[must_use]
237 pub fn new(plan_id: impl Into<PlanId>, entries: Vec<PlanEntry>) -> Self {
238 Self {
239 plan_id: plan_id.into(),
240 entries,
241 meta: None,
242 }
243 }
244
245 #[must_use]
251 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
252 self.meta = meta.into_option();
253 self
254 }
255}
256
257#[serde_as]
259#[skip_serializing_none]
260#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
261#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
262#[serde(rename_all = "camelCase")]
263#[non_exhaustive]
264pub struct PlanMarkdown {
265 pub plan_id: PlanId,
267 pub content: String,
269 #[serde_as(deserialize_as = "DefaultOnError")]
275 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
276 #[serde(default)]
277 pub path: Option<AbsolutePath>,
278 #[serde_as(deserialize_as = "DefaultOnError")]
284 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
285 #[serde(default)]
286 #[serde(rename = "_meta")]
287 pub meta: Option<Meta>,
288}
289
290impl PlanMarkdown {
291 #[must_use]
293 pub fn new(plan_id: impl Into<PlanId>, content: impl Into<String>) -> Self {
294 Self {
295 plan_id: plan_id.into(),
296 content: content.into(),
297 path: None,
298 meta: None,
299 }
300 }
301
302 #[must_use]
306 pub fn path(mut self, path: impl IntoOption<AbsolutePath>) -> Self {
307 self.path = path.into_option();
308 self
309 }
310
311 #[must_use]
317 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
318 self.meta = meta.into_option();
319 self
320 }
321}
322
323#[serde_as]
325#[skip_serializing_none]
326#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
327#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
328#[serde(rename_all = "camelCase")]
329#[non_exhaustive]
330pub struct PlanRemoved {
331 pub plan_id: PlanId,
333 #[serde_as(deserialize_as = "DefaultOnError")]
339 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
340 #[serde(default)]
341 #[serde(rename = "_meta")]
342 pub meta: Option<Meta>,
343}
344
345impl PlanRemoved {
346 #[must_use]
348 pub fn new(plan_id: impl Into<PlanId>) -> Self {
349 Self {
350 plan_id: plan_id.into(),
351 meta: None,
352 }
353 }
354
355 #[must_use]
361 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
362 self.meta = meta.into_option();
363 self
364 }
365}
366
367#[serde_as]
373#[skip_serializing_none]
374#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
375#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
376#[serde(rename_all = "camelCase")]
377#[non_exhaustive]
378pub struct PlanEntry {
379 pub content: String,
382 pub priority: PlanEntryPriority,
385 pub status: PlanEntryStatus,
387 #[serde_as(deserialize_as = "DefaultOnError")]
393 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
394 #[serde(default)]
395 #[serde(rename = "_meta")]
396 pub meta: Option<Meta>,
397}
398
399impl PlanEntry {
400 #[must_use]
402 pub fn new(
403 content: impl Into<String>,
404 priority: PlanEntryPriority,
405 status: PlanEntryStatus,
406 ) -> Self {
407 Self {
408 content: content.into(),
409 priority,
410 status,
411 meta: None,
412 }
413 }
414
415 #[must_use]
421 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
422 self.meta = meta.into_option();
423 self
424 }
425}
426
427#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
433#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
434#[serde(rename_all = "snake_case")]
435#[non_exhaustive]
436pub enum PlanEntryPriority {
437 High,
439 Medium,
441 Low,
443 #[serde(untagged)]
449 Other(String),
450}
451
452#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
457#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
458#[serde(rename_all = "snake_case")]
459#[non_exhaustive]
460pub enum PlanEntryStatus {
461 Pending,
463 InProgress,
465 Completed,
467 Cancelled,
469 #[serde(untagged)]
475 Other(String),
476}
477
478#[cfg(test)]
479mod tests {
480 use super::*;
481
482 #[test]
483 fn plan_entry_priority_preserves_unknown_variant() {
484 let priority: PlanEntryPriority = serde_json::from_str("\"urgent\"").unwrap();
485 assert_eq!(priority, PlanEntryPriority::Other("urgent".to_string()));
486 assert_eq!(serde_json::to_value(&priority).unwrap(), "urgent");
487 }
488
489 #[test]
490 fn plan_entry_status_preserves_unknown_variant() {
491 let status: PlanEntryStatus = serde_json::from_str("\"blocked\"").unwrap();
492 assert_eq!(status, PlanEntryStatus::Other("blocked".to_string()));
493 assert_eq!(serde_json::to_value(&status).unwrap(), "blocked");
494 }
495
496 #[test]
497 fn plan_entry_status_recognizes_cancelled_variant() {
498 let status: PlanEntryStatus = serde_json::from_str("\"cancelled\"").unwrap();
499 assert_eq!(status, PlanEntryStatus::Cancelled);
500 assert_eq!(serde_json::to_value(&status).unwrap(), "cancelled");
501 }
502
503 #[test]
504 fn plan_update_content_preserves_unknown_variant() {
505 let content: PlanUpdateContent = serde_json::from_value(serde_json::json!({
506 "type": "_timeline",
507 "planId": "plan-1",
508 "events": []
509 }))
510 .unwrap();
511
512 let PlanUpdateContent::Other(unknown) = content else {
513 panic!("expected unknown plan update content");
514 };
515
516 assert_eq!(unknown.type_, "_timeline");
517 assert_eq!(unknown.plan_id.to_string(), "plan-1");
518 assert!(!unknown.fields.contains_key("planId"));
519 assert_eq!(
520 serde_json::to_value(PlanUpdateContent::Other(unknown)).unwrap(),
521 serde_json::json!({
522 "type": "_timeline",
523 "planId": "plan-1",
524 "events": []
525 })
526 );
527 }
528
529 #[test]
530 fn plan_update_content_does_not_hide_malformed_known_variant() {
531 for tag in ["items", "markdown"] {
532 let wire = serde_json::json!({
533 "type": tag,
534 "planId": "plan-1"
535 });
536 assert!(serde_json::from_value::<PlanUpdateContent>(wire).is_err());
537 }
538 }
539
540 #[test]
541 fn markdown_plan_path_round_trips() {
542 let wire = serde_json::json!({
543 "type": "markdown",
544 "planId": "plan-1",
545 "content": "# Next steps",
546 "path": "/home/user/project/PLAN.md"
547 });
548 let content: PlanUpdateContent = serde_json::from_value(wire.clone()).unwrap();
549 assert_eq!(
550 content,
551 PlanUpdateContent::Markdown(
552 PlanMarkdown::new("plan-1", "# Next steps").path("/home/user/project/PLAN.md")
553 )
554 );
555 assert_eq!(serde_json::to_value(content).unwrap(), wire);
556 }
557
558 #[test]
559 fn markdown_plan_path_is_optional_and_lenient() {
560 let without_path = PlanUpdateContent::markdown("plan-1", "# Next steps");
561 assert_eq!(
562 serde_json::to_value(&without_path).unwrap(),
563 serde_json::json!({
564 "type": "markdown",
565 "planId": "plan-1",
566 "content": "# Next steps"
567 })
568 );
569 for path in [serde_json::Value::Null, serde_json::json!(42)] {
571 let content: PlanUpdateContent = serde_json::from_value(serde_json::json!({
572 "type": "markdown",
573 "planId": "plan-1",
574 "content": "# Next steps",
575 "path": path
576 }))
577 .unwrap();
578 assert_eq!(content, without_path);
579 }
580 }
581
582 #[test]
583 fn plan_update_content_requires_id_for_unknown_variant() {
584 assert!(
585 serde_json::from_value::<PlanUpdateContent>(serde_json::json!({
586 "type": "_timeline"
587 }))
588 .is_err()
589 );
590 }
591}