1use std::{collections::BTreeMap, sync::Arc};
9
10use derive_more::{Display, From};
11#[cfg(feature = "schemars")]
12use schemars::Schema;
13use serde::{Deserialize, Serialize};
14use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none};
15
16#[cfg(feature = "unstable_plan_operations")]
17use super::AbsolutePath;
18use super::Meta;
19use crate::IntoOption;
20
21#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
23#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
24#[serde(transparent)]
25#[from(forward)]
26#[non_exhaustive]
27pub struct PlanId(pub Arc<str>);
28
29impl PlanId {
30 #[must_use]
32 pub fn new(id: impl Into<Self>) -> Self {
33 id.into()
34 }
35}
36
37#[serde_as]
39#[skip_serializing_none]
40#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
41#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
42#[serde(rename_all = "camelCase")]
43#[non_exhaustive]
44pub struct PlanUpdate {
45 pub plan: PlanUpdateContent,
47 #[serde_as(deserialize_as = "DefaultOnError")]
53 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
54 #[serde(default)]
55 #[serde(rename = "_meta")]
56 pub meta: Option<Meta>,
57}
58
59impl PlanUpdate {
60 #[must_use]
62 pub fn new(plan: PlanUpdateContent) -> Self {
63 Self { plan, meta: None }
64 }
65
66 #[must_use]
72 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
73 self.meta = meta.into_option();
74 self
75 }
76}
77
78#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
80#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
81#[serde(tag = "type", rename_all = "snake_case")]
82#[non_exhaustive]
83pub enum PlanUpdateContent {
84 Items(PlanItems),
86 #[cfg(feature = "unstable_plan_operations")]
92 Markdown(PlanMarkdown),
93 #[serde(untagged)]
104 Other(OtherPlanUpdateContent),
105}
106
107#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
109#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
110#[cfg_attr(feature = "schemars", schemars(inline))]
111#[cfg_attr(feature = "schemars", schemars(transform = other_plan_update_content_schema))]
112#[serde(rename_all = "camelCase")]
113#[non_exhaustive]
114pub struct OtherPlanUpdateContent {
115 #[serde(rename = "type")]
121 pub type_: String,
122 pub plan_id: PlanId,
124 #[serde(flatten)]
126 pub fields: BTreeMap<String, serde_json::Value>,
127}
128
129impl OtherPlanUpdateContent {
130 #[must_use]
132 pub fn new(
133 type_: impl Into<String>,
134 plan_id: impl Into<PlanId>,
135 mut fields: BTreeMap<String, serde_json::Value>,
136 ) -> Self {
137 fields.remove("type");
138 fields.remove("planId");
139 Self {
140 type_: type_.into(),
141 plan_id: plan_id.into(),
142 fields,
143 }
144 }
145}
146
147impl<'de> Deserialize<'de> for OtherPlanUpdateContent {
148 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
149 where
150 D: serde::Deserializer<'de>,
151 {
152 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
153 let type_ = fields
154 .remove("type")
155 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
156 let serde_json::Value::String(type_) = type_ else {
157 return Err(serde::de::Error::custom("`type` must be a string"));
158 };
159 let plan_id = fields
160 .remove("planId")
161 .ok_or_else(|| serde::de::Error::missing_field("planId"))?;
162 let serde_json::Value::String(plan_id) = plan_id else {
163 return Err(serde::de::Error::custom("`planId` must be a string"));
164 };
165
166 if is_known_plan_update_content_type(&type_) {
167 return Err(serde::de::Error::custom(format!(
168 "known plan update content `{type_}` did not match its schema"
169 )));
170 }
171
172 Ok(Self {
173 type_,
174 plan_id: PlanId::new(plan_id),
175 fields,
176 })
177 }
178}
179
180fn is_known_plan_update_content_type(type_: &str) -> bool {
181 KNOWN_PLAN_UPDATE_CONTENT_TYPES.contains(&type_)
182}
183
184#[cfg(feature = "schemars")]
185fn other_plan_update_content_schema(schema: &mut Schema) {
186 super::schema_util::reject_known_string_discriminators(
187 schema,
188 "type",
189 KNOWN_PLAN_UPDATE_CONTENT_TYPES,
190 );
191}
192
193const KNOWN_PLAN_UPDATE_CONTENT_TYPES: &[&str] = &[
194 "items",
195 #[cfg(feature = "unstable_plan_operations")]
196 "markdown",
197];
198
199impl PlanUpdateContent {
200 #[must_use]
202 pub fn items(plan_id: impl Into<PlanId>, entries: Vec<PlanEntry>) -> Self {
203 Self::Items(PlanItems::new(plan_id, entries))
204 }
205
206 #[cfg(feature = "unstable_plan_operations")]
211 #[must_use]
212 pub fn markdown(plan_id: impl Into<PlanId>, content: impl Into<String>) -> Self {
213 Self::Markdown(PlanMarkdown::new(plan_id, content))
214 }
215}
216
217#[serde_as]
219#[skip_serializing_none]
220#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
221#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
222#[serde(rename_all = "camelCase")]
223#[non_exhaustive]
224pub struct PlanItems {
225 pub plan_id: PlanId,
227 #[serde_as(deserialize_as = "VecSkipError<_>")]
232 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
233 pub entries: Vec<PlanEntry>,
234 #[serde_as(deserialize_as = "DefaultOnError")]
240 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
241 #[serde(default)]
242 #[serde(rename = "_meta")]
243 pub meta: Option<Meta>,
244}
245
246impl PlanItems {
247 #[must_use]
249 pub fn new(plan_id: impl Into<PlanId>, entries: Vec<PlanEntry>) -> Self {
250 Self {
251 plan_id: plan_id.into(),
252 entries,
253 meta: None,
254 }
255 }
256
257 #[must_use]
263 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
264 self.meta = meta.into_option();
265 self
266 }
267}
268
269#[cfg(feature = "unstable_plan_operations")]
275#[serde_as]
276#[skip_serializing_none]
277#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
278#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
279#[serde(rename_all = "camelCase")]
280#[non_exhaustive]
281pub struct PlanMarkdown {
282 pub plan_id: PlanId,
284 pub content: String,
286 #[serde_as(deserialize_as = "DefaultOnError")]
291 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
292 #[serde(default)]
293 pub path: Option<AbsolutePath>,
294 #[serde_as(deserialize_as = "DefaultOnError")]
300 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
301 #[serde(default)]
302 #[serde(rename = "_meta")]
303 pub meta: Option<Meta>,
304}
305
306#[cfg(feature = "unstable_plan_operations")]
307impl PlanMarkdown {
308 #[must_use]
310 pub fn new(plan_id: impl Into<PlanId>, content: impl Into<String>) -> Self {
311 Self {
312 plan_id: plan_id.into(),
313 content: content.into(),
314 path: None,
315 meta: None,
316 }
317 }
318
319 #[must_use]
323 pub fn path(mut self, path: impl IntoOption<AbsolutePath>) -> Self {
324 self.path = path.into_option();
325 self
326 }
327
328 #[must_use]
334 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
335 self.meta = meta.into_option();
336 self
337 }
338}
339
340#[cfg(feature = "unstable_plan_operations")]
346#[serde_as]
347#[skip_serializing_none]
348#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
349#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
350#[serde(rename_all = "camelCase")]
351#[non_exhaustive]
352pub struct PlanRemoved {
353 pub plan_id: PlanId,
355 #[serde_as(deserialize_as = "DefaultOnError")]
361 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
362 #[serde(default)]
363 #[serde(rename = "_meta")]
364 pub meta: Option<Meta>,
365}
366
367#[cfg(feature = "unstable_plan_operations")]
368impl PlanRemoved {
369 #[must_use]
371 pub fn new(plan_id: impl Into<PlanId>) -> Self {
372 Self {
373 plan_id: plan_id.into(),
374 meta: None,
375 }
376 }
377
378 #[must_use]
384 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
385 self.meta = meta.into_option();
386 self
387 }
388}
389
390#[serde_as]
396#[skip_serializing_none]
397#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
398#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
399#[serde(rename_all = "camelCase")]
400#[non_exhaustive]
401pub struct PlanEntry {
402 pub content: String,
404 pub priority: PlanEntryPriority,
407 pub status: PlanEntryStatus,
409 #[serde_as(deserialize_as = "DefaultOnError")]
415 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
416 #[serde(default)]
417 #[serde(rename = "_meta")]
418 pub meta: Option<Meta>,
419}
420
421impl PlanEntry {
422 #[must_use]
424 pub fn new(
425 content: impl Into<String>,
426 priority: PlanEntryPriority,
427 status: PlanEntryStatus,
428 ) -> Self {
429 Self {
430 content: content.into(),
431 priority,
432 status,
433 meta: None,
434 }
435 }
436
437 #[must_use]
443 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
444 self.meta = meta.into_option();
445 self
446 }
447}
448
449#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
455#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
456#[serde(rename_all = "snake_case")]
457#[non_exhaustive]
458pub enum PlanEntryPriority {
459 High,
461 Medium,
463 Low,
465 #[serde(untagged)]
471 Other(String),
472}
473
474#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
479#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
480#[serde(rename_all = "snake_case")]
481#[non_exhaustive]
482pub enum PlanEntryStatus {
483 Pending,
485 InProgress,
487 Completed,
489 Cancelled,
491 #[serde(untagged)]
497 Other(String),
498}
499
500#[cfg(test)]
501mod tests {
502 use super::*;
503
504 #[test]
505 fn plan_entry_priority_preserves_unknown_variant() {
506 let priority: PlanEntryPriority = serde_json::from_str("\"urgent\"").unwrap();
507 assert_eq!(priority, PlanEntryPriority::Other("urgent".to_string()));
508 assert_eq!(serde_json::to_value(&priority).unwrap(), "urgent");
509 }
510
511 #[test]
512 fn plan_entry_status_preserves_unknown_variant() {
513 let status: PlanEntryStatus = serde_json::from_str("\"blocked\"").unwrap();
514 assert_eq!(status, PlanEntryStatus::Other("blocked".to_string()));
515 assert_eq!(serde_json::to_value(&status).unwrap(), "blocked");
516 }
517
518 #[test]
519 fn plan_entry_status_recognizes_cancelled_variant() {
520 let status: PlanEntryStatus = serde_json::from_str("\"cancelled\"").unwrap();
521 assert_eq!(status, PlanEntryStatus::Cancelled);
522 assert_eq!(serde_json::to_value(&status).unwrap(), "cancelled");
523 }
524
525 #[test]
526 fn plan_update_content_preserves_unknown_variant() {
527 let content: PlanUpdateContent = serde_json::from_value(serde_json::json!({
528 "type": "_timeline",
529 "planId": "plan-1",
530 "events": []
531 }))
532 .unwrap();
533
534 let PlanUpdateContent::Other(unknown) = content else {
535 panic!("expected unknown plan update content");
536 };
537
538 assert_eq!(unknown.type_, "_timeline");
539 assert_eq!(unknown.plan_id.to_string(), "plan-1");
540 assert!(!unknown.fields.contains_key("planId"));
541 assert_eq!(
542 serde_json::to_value(PlanUpdateContent::Other(unknown)).unwrap(),
543 serde_json::json!({
544 "type": "_timeline",
545 "planId": "plan-1",
546 "events": []
547 })
548 );
549 }
550
551 #[test]
552 fn plan_update_content_does_not_hide_malformed_known_variant() {
553 assert!(
554 serde_json::from_value::<PlanUpdateContent>(serde_json::json!({
555 "type": "items"
556 }))
557 .is_err()
558 );
559 }
560
561 #[cfg(feature = "unstable_plan_operations")]
562 #[test]
563 fn plan_update_content_does_not_hide_malformed_known_experimental_variant() {
564 assert!(
565 serde_json::from_value::<PlanUpdateContent>(serde_json::json!({
566 "type": "markdown",
567 "planId": "plan-1"
568 }))
569 .is_err()
570 );
571 }
572
573 #[cfg(feature = "unstable_plan_operations")]
574 #[test]
575 fn markdown_plan_path_round_trips() {
576 let wire = serde_json::json!({
577 "type": "markdown",
578 "planId": "plan-1",
579 "content": "# Next steps",
580 "path": "/home/user/project/PLAN.md"
581 });
582 let content: PlanUpdateContent = serde_json::from_value(wire.clone()).unwrap();
583 assert_eq!(
584 content,
585 PlanUpdateContent::Markdown(
586 PlanMarkdown::new("plan-1", "# Next steps").path("/home/user/project/PLAN.md")
587 )
588 );
589 assert_eq!(serde_json::to_value(content).unwrap(), wire);
590 }
591
592 #[cfg(feature = "unstable_plan_operations")]
593 #[test]
594 fn markdown_plan_path_is_optional_and_lenient() {
595 let without_path = PlanUpdateContent::markdown("plan-1", "# Next steps");
596 assert_eq!(
597 serde_json::to_value(&without_path).unwrap(),
598 serde_json::json!({
599 "type": "markdown",
600 "planId": "plan-1",
601 "content": "# Next steps"
602 })
603 );
604 for path in [serde_json::Value::Null, serde_json::json!(42)] {
606 let content: PlanUpdateContent = serde_json::from_value(serde_json::json!({
607 "type": "markdown",
608 "planId": "plan-1",
609 "content": "# Next steps",
610 "path": path
611 }))
612 .unwrap();
613 assert_eq!(content, without_path);
614 }
615 }
616
617 #[test]
618 fn plan_update_content_requires_id_for_unknown_variant() {
619 assert!(
620 serde_json::from_value::<PlanUpdateContent>(serde_json::json!({
621 "type": "_timeline"
622 }))
623 .is_err()
624 );
625 }
626}