Skip to main content

merry_runtime/plan/
tracker.rs

1//! Pure Plan Mode state machine, multi-plan registry, and dynamic reminders.
2
3use merry_core::{
4    PlanDocument, PlanDocumentStatus, PlanDocumentSummary, PlanId, PlanModeState,
5    PlanReviewDecision, PlanSessionSnapshot,
6};
7use serde::{Deserialize, Serialize};
8use std::collections::BTreeMap;
9use thiserror::Error;
10
11const MAX_PLAN_TITLE_BYTES: usize = 200;
12const MAX_PLAN_CONTENT_BYTES: usize = 256 * 1024;
13const MAX_PLANS_PER_SESSION: usize = 64;
14const MAX_SLUG_LEN: usize = 48;
15
16/// Typed errors returned by Plan Mode state transitions and document authoring.
17#[derive(Debug, Clone, PartialEq, Eq, Error)]
18pub enum PlanError {
19    /// Plan title is blank, too long, or contains control characters.
20    #[error("plan title is invalid: {reason}")]
21    InvalidTitle { reason: &'static str },
22    /// Plan Markdown body exceeds the bounded size limit.
23    #[error("plan content exceeds maximum size of {maximum} bytes (got {actual})")]
24    ContentTooLarge { actual: usize, maximum: usize },
25    /// Plan feedback is blank when requesting revisions.
26    #[error("plan revision feedback must not be blank")]
27    EmptyFeedback,
28    /// Referenced plan id does not exist in this session.
29    #[error("unknown plan id: {plan_id}")]
30    UnknownPlan { plan_id: PlanId },
31    /// Attempted to overwrite a plan that is already approved or abandoned.
32    #[error("plan {plan_id} is {status:?} and cannot be edited; create a new plan instead")]
33    PlanNotEditable {
34        plan_id: PlanId,
35        status: PlanDocumentStatus,
36    },
37    /// Session reached the bounded maximum number of stored plans.
38    #[error("session already has the maximum of {maximum} plans")]
39    TooManyPlans { maximum: usize },
40    /// Sanitized plan file name failed safety validation.
41    #[error("plan file name {file_name:?} is invalid")]
42    InvalidFileName { file_name: String },
43}
44
45/// Durable Plan Mode state persisted in `journal.jsonl`.
46///
47/// Markdown bodies live in `<session_dir>/plans/<file_name>` on disk when a
48/// `FileSessionStore` is attached, and are cached in memory on
49/// [`PlanSessionState`].
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(deny_unknown_fields)]
52pub(crate) struct PersistedPlanModeState {
53    pub(crate) mode: PlanModeState,
54    #[serde(default)]
55    pub(crate) was_previously_active: bool,
56    #[serde(default)]
57    pub(crate) reminder_count: u32,
58    #[serde(default)]
59    pub(crate) pending_exit_reminder: bool,
60    #[serde(default, skip_serializing_if = "Option::is_none")]
61    pub(crate) active_plan_id: Option<PlanId>,
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub(crate) awaiting_approval_plan_id: Option<PlanId>,
64    #[serde(default = "default_next_plan_sequence")]
65    pub(crate) next_plan_sequence: u32,
66    #[serde(default, skip_serializing_if = "Vec::is_empty")]
67    pub(crate) plans: Vec<PlanDocumentSummary>,
68}
69
70const fn default_next_plan_sequence() -> u32 {
71    1
72}
73
74impl Default for PersistedPlanModeState {
75    fn default() -> Self {
76        Self {
77            mode: PlanModeState::Inactive,
78            was_previously_active: false,
79            reminder_count: 0,
80            pending_exit_reminder: false,
81            active_plan_id: None,
82            awaiting_approval_plan_id: None,
83            next_plan_sequence: 1,
84            plans: Vec::new(),
85        }
86    }
87}
88
89impl PersistedPlanModeState {
90    /// Returns whether this state carries any non-default Plan Mode data.
91    #[must_use]
92    pub(crate) fn is_empty(&self) -> bool {
93        self.mode == PlanModeState::Inactive
94            && !self.was_previously_active
95            && self.reminder_count == 0
96            && !self.pending_exit_reminder
97            && self.active_plan_id.is_none()
98            && self.awaiting_approval_plan_id.is_none()
99            && self.plans.is_empty()
100    }
101}
102
103/// Runtime-owned Plan Mode state machine and multi-plan document store for one session.
104#[derive(Debug, Clone, Default)]
105pub(crate) struct PlanSessionState {
106    persisted: PersistedPlanModeState,
107    contents: BTreeMap<PlanId, String>,
108}
109
110impl PlanSessionState {
111    /// Reconstructs Plan Mode state from persisted journal data and on-disk plan bodies.
112    ///
113    /// Transient states (`Pending`, `ExitPending`) collapse cleanly on restart:
114    /// `Pending -> Inactive`, `ExitPending -> Inactive` with a one-shot exit reminder.
115    #[must_use]
116    pub(crate) fn from_persisted(
117        mut persisted: PersistedPlanModeState,
118        contents: BTreeMap<PlanId, String>,
119    ) -> Self {
120        match persisted.mode {
121            PlanModeState::Pending => {
122                persisted.mode = PlanModeState::Inactive;
123            }
124            PlanModeState::ExitPending => {
125                persisted.mode = PlanModeState::Inactive;
126                persisted.pending_exit_reminder = true;
127            }
128            PlanModeState::Inactive | PlanModeState::Active => {}
129        }
130        if persisted.next_plan_sequence == 0 {
131            persisted.next_plan_sequence =
132                u32::try_from(persisted.plans.len()).unwrap_or(u32::MAX - 1) + 1;
133        }
134        Self {
135            persisted,
136            contents,
137        }
138    }
139
140    /// Populates in-memory plan bodies loaded from `<session_dir>/plans/`.
141    pub(crate) fn set_contents(&mut self, contents: BTreeMap<PlanId, String>) {
142        self.contents = contents;
143    }
144
145    /// Returns the serializable persistence snapshot for `journal.jsonl`.
146    #[must_use]
147    pub(crate) fn persisted(&self) -> Option<PersistedPlanModeState> {
148        (!self.persisted.is_empty()).then(|| self.persisted.clone())
149    }
150
151    /// Returns the current Plan Mode state.
152    #[must_use]
153    pub(crate) const fn mode(&self) -> PlanModeState {
154        self.persisted.mode
155    }
156
157    /// Returns whether Plan Mode's read-only edit gate is currently active.
158    #[must_use]
159    pub(crate) const fn is_active(&self) -> bool {
160        self.persisted.mode.is_active()
161    }
162
163    /// Returns the plan id currently parked for user review, if any.
164    #[must_use]
165    pub(crate) fn awaiting_approval_plan_id(&self) -> Option<&PlanId> {
166        self.persisted.awaiting_approval_plan_id.as_ref()
167    }
168
169    /// Returns a compact session snapshot for API/TUI projection.
170    #[must_use]
171    pub(crate) fn snapshot(&self) -> PlanSessionSnapshot {
172        PlanSessionSnapshot {
173            mode: self.persisted.mode,
174            active_plan_id: self.persisted.active_plan_id.clone(),
175            awaiting_approval_plan_id: self.persisted.awaiting_approval_plan_id.clone(),
176            plans: self.persisted.plans.clone(),
177        }
178    }
179
180    /// Returns all persisted plan summaries in chronological order.
181    #[must_use]
182    pub(crate) fn summaries(&self) -> &[PlanDocumentSummary] {
183        &self.persisted.plans
184    }
185
186    /// Returns all plan documents with their cached Markdown bodies.
187    #[must_use]
188    pub(crate) fn documents(&self) -> Vec<PlanDocument> {
189        self.persisted
190            .plans
191            .iter()
192            .map(|summary| PlanDocument {
193                summary: summary.clone(),
194                content: self.contents.get(&summary.id).cloned().unwrap_or_default(),
195            })
196            .collect()
197    }
198
199    /// Looks up one complete plan document by id.
200    #[must_use]
201    pub(crate) fn document(&self, plan_id: &PlanId) -> Option<PlanDocument> {
202        self.persisted
203            .plans
204            .iter()
205            .find(|plan| &plan.id == plan_id)
206            .map(|summary| PlanDocument {
207                summary: summary.clone(),
208                content: self.contents.get(&summary.id).cloned().unwrap_or_default(),
209            })
210    }
211
212    /// Returns the active plan or the most recently created plan.
213    #[must_use]
214    pub(crate) fn active_or_latest_document(&self) -> Option<PlanDocument> {
215        if let Some(id) = self.persisted.active_plan_id.as_ref()
216            && let Some(doc) = self.document(id)
217        {
218            return Some(doc);
219        }
220        self.persisted
221            .plans
222            .last()
223            .and_then(|summary| self.document(&summary.id))
224    }
225
226    /// User-initiated toggle of Plan Mode. Returns `Some(new_mode)` when the state changed.
227    pub(crate) fn set_mode_from_user(
228        &mut self,
229        enabled: bool,
230        turn_in_flight: bool,
231    ) -> Option<PlanModeState> {
232        let next = if enabled {
233            match self.persisted.mode {
234                PlanModeState::Inactive => {
235                    self.persisted.pending_exit_reminder = false;
236                    if turn_in_flight {
237                        self.persisted.was_previously_active = true;
238                        self.persisted.reminder_count = 0;
239                        PlanModeState::Active
240                    } else {
241                        PlanModeState::Pending
242                    }
243                }
244                PlanModeState::ExitPending => {
245                    self.persisted.pending_exit_reminder = false;
246                    PlanModeState::Active
247                }
248                PlanModeState::Pending | PlanModeState::Active => return None,
249            }
250        } else {
251            self.persisted.awaiting_approval_plan_id = None;
252            match self.persisted.mode {
253                PlanModeState::Pending => PlanModeState::Inactive,
254                PlanModeState::Active => {
255                    if turn_in_flight {
256                        PlanModeState::ExitPending
257                    } else {
258                        self.persisted.pending_exit_reminder = true;
259                        PlanModeState::Inactive
260                    }
261                }
262                PlanModeState::Inactive | PlanModeState::ExitPending => return None,
263            }
264        };
265        self.persisted.mode = next;
266        Some(next)
267    }
268
269    /// Activates Plan Mode when the first user prompt arrives in `Pending` state.
270    pub(crate) fn activate_on_user_prompt(&mut self) -> Option<PlanModeState> {
271        if self.persisted.mode != PlanModeState::Pending {
272            return None;
273        }
274        self.persisted.mode = PlanModeState::Active;
275        self.persisted.was_previously_active = true;
276        self.persisted.reminder_count = 0;
277        self.persisted.pending_exit_reminder = false;
278        Some(PlanModeState::Active)
279    }
280
281    /// Completes a deferred `ExitPending -> Inactive` transition when the turn settles.
282    pub(crate) fn complete_deferred_exit(&mut self) -> Option<PlanModeState> {
283        if self.persisted.mode != PlanModeState::ExitPending {
284            return None;
285        }
286        self.persisted.mode = PlanModeState::Inactive;
287        self.persisted.pending_exit_reminder = true;
288        Some(PlanModeState::Inactive)
289    }
290
291    /// Agent-initiated entry via `enter_plan_mode`. Returns `Some(Active)` if state changed.
292    pub(crate) fn activate_from_tool(&mut self) -> Option<PlanModeState> {
293        if self.persisted.mode == PlanModeState::Active {
294            return None;
295        }
296        self.persisted.mode = PlanModeState::Active;
297        self.persisted.was_previously_active = true;
298        self.persisted.reminder_count = 0;
299        self.persisted.pending_exit_reminder = false;
300        Some(PlanModeState::Active)
301    }
302
303    /// Resets reminder alternation after compaction so the model receives the full reminder.
304    pub(crate) fn reset_after_compaction(&mut self) {
305        if self.persisted.mode == PlanModeState::Active {
306            self.persisted.reminder_count = 0;
307        }
308    }
309
310    /// Advances reminder tracking once a model turn consumes the dynamic reminder.
311    pub(crate) fn record_prompt_delivered(&mut self) {
312        if self.persisted.mode == PlanModeState::Active {
313            self.persisted.reminder_count = self.persisted.reminder_count.saturating_add(1);
314        } else if self.persisted.mode == PlanModeState::Inactive
315            && self.persisted.pending_exit_reminder
316        {
317            self.persisted.pending_exit_reminder = false;
318        }
319    }
320
321    /// Creates a new numbered plan or updates an existing editable plan.
322    pub(crate) fn save_plan(
323        &mut self,
324        title: &str,
325        content: &str,
326        requested_plan_id: Option<&PlanId>,
327        create_new: bool,
328        now_ms: u64,
329    ) -> Result<PlanDocument, PlanError> {
330        let title = validate_title(title)?;
331        if content.len() > MAX_PLAN_CONTENT_BYTES {
332            return Err(PlanError::ContentTooLarge {
333                actual: content.len(),
334                maximum: MAX_PLAN_CONTENT_BYTES,
335            });
336        }
337
338        let target_index = if create_new {
339            None
340        } else if let Some(plan_id) = requested_plan_id {
341            let (idx, existing) = self
342                .persisted
343                .plans
344                .iter()
345                .enumerate()
346                .find(|(_, plan)| &plan.id == plan_id)
347                .ok_or_else(|| PlanError::UnknownPlan {
348                    plan_id: plan_id.clone(),
349                })?;
350            if !matches!(
351                existing.status,
352                PlanDocumentStatus::Draft | PlanDocumentStatus::AwaitingApproval
353            ) {
354                return Err(PlanError::PlanNotEditable {
355                    plan_id: existing.id.clone(),
356                    status: existing.status,
357                });
358            }
359            Some(idx)
360        } else {
361            self.persisted
362                .active_plan_id
363                .as_ref()
364                .and_then(|active_id| {
365                    self.persisted.plans.iter().position(|plan| {
366                        &plan.id == active_id
367                            && matches!(
368                                plan.status,
369                                PlanDocumentStatus::Draft | PlanDocumentStatus::AwaitingApproval
370                            )
371                    })
372                })
373        };
374
375        if let Some(summary) = target_index.and_then(|index| self.persisted.plans.get_mut(index)) {
376            summary.title = title;
377            summary.status = PlanDocumentStatus::Draft;
378            summary.revision = summary.revision.saturating_add(1);
379            summary.updated_at_ms = now_ms;
380            let plan_id = summary.id.clone();
381            let summary_clone = summary.clone();
382            self.persisted.active_plan_id = Some(plan_id.clone());
383            self.contents.insert(plan_id, content.to_owned());
384            return Ok(PlanDocument {
385                summary: summary_clone,
386                content: content.to_owned(),
387            });
388        }
389
390        if self.persisted.plans.len() >= MAX_PLANS_PER_SESSION {
391            return Err(PlanError::TooManyPlans {
392                maximum: MAX_PLANS_PER_SESSION,
393            });
394        }
395        let seq = self.persisted.next_plan_sequence;
396        self.persisted.next_plan_sequence = seq.saturating_add(1);
397        // `plan-{u32}` is guaranteed non-blank, ASCII, and within identifier length bounds.
398        let plan_id = PlanId::new(&format!("plan-{seq}")).expect("generated plan id is valid");
399        let file_name = format!("{seq:03}-{}.md", slugify_title(&title));
400        validate_plan_file_name(&file_name)?;
401        let summary = PlanDocumentSummary {
402            id: plan_id.clone(),
403            title,
404            file_name,
405            status: PlanDocumentStatus::Draft,
406            revision: 1,
407            created_at_ms: now_ms,
408            updated_at_ms: now_ms,
409        };
410        self.persisted.plans.push(summary.clone());
411        self.persisted.active_plan_id = Some(plan_id.clone());
412        self.contents.insert(plan_id, content.to_owned());
413        Ok(PlanDocument {
414            summary,
415            content: content.to_owned(),
416        })
417    }
418
419    /// Marks the active or requested plan as awaiting user approval.
420    ///
421    /// If no plan has been authored yet in this cycle, seeds an empty untitled
422    /// plan document so the review UI still opens cleanly with an empty-state notice.
423    pub(crate) fn request_approval(
424        &mut self,
425        requested_plan_id: Option<&PlanId>,
426        now_ms: u64,
427    ) -> Result<PlanDocument, PlanError> {
428        let target_id = if let Some(plan_id) = requested_plan_id {
429            plan_id.clone()
430        } else if let Some(active_id) = self.persisted.active_plan_id.clone() {
431            active_id
432        } else {
433            let seeded = self.save_plan("Untitled Plan", "", None, true, now_ms)?;
434            seeded.summary.id
435        };
436
437        let summary = self
438            .persisted
439            .plans
440            .iter_mut()
441            .find(|plan| plan.id == target_id)
442            .ok_or_else(|| PlanError::UnknownPlan {
443                plan_id: target_id.clone(),
444            })?;
445        summary.status = PlanDocumentStatus::AwaitingApproval;
446        summary.updated_at_ms = now_ms;
447        let summary_clone = summary.clone();
448        self.persisted.active_plan_id = Some(target_id.clone());
449        self.persisted.awaiting_approval_plan_id = Some(target_id.clone());
450        let content = self.contents.get(&target_id).cloned().unwrap_or_default();
451        Ok(PlanDocument {
452            summary: summary_clone,
453            content,
454        })
455    }
456
457    /// Approves a plan, exits Plan Mode, and clears `active_plan_id` so the next
458    /// planning session starts a fresh numbered plan.
459    pub(crate) fn approve_plan(
460        &mut self,
461        plan_id: &PlanId,
462        note: Option<String>,
463        now_ms: u64,
464    ) -> Result<(PlanDocument, PlanReviewDecision), PlanError> {
465        let summary = self
466            .persisted
467            .plans
468            .iter_mut()
469            .find(|plan| &plan.id == plan_id)
470            .ok_or_else(|| PlanError::UnknownPlan {
471                plan_id: plan_id.clone(),
472            })?;
473        summary.status = PlanDocumentStatus::Approved;
474        summary.updated_at_ms = now_ms;
475        let summary_clone = summary.clone();
476        self.persisted.mode = PlanModeState::Inactive;
477        self.persisted.reminder_count = 0;
478        self.persisted.pending_exit_reminder = false;
479        self.persisted.awaiting_approval_plan_id = None;
480        self.persisted.active_plan_id = None;
481        let content = self.contents.get(plan_id).cloned().unwrap_or_default();
482        let note = note.and_then(|value| {
483            let trimmed = value.trim();
484            (!trimmed.is_empty()).then(|| trimmed.to_owned())
485        });
486        Ok((
487            PlanDocument {
488                summary: summary_clone,
489                content,
490            },
491            PlanReviewDecision::Approved { note },
492        ))
493    }
494
495    /// Returns a plan to `Draft`, keeps Plan Mode active, and clears the awaiting gate.
496    pub(crate) fn request_changes(
497        &mut self,
498        plan_id: &PlanId,
499        feedback: String,
500        now_ms: u64,
501    ) -> Result<(PlanDocument, PlanReviewDecision), PlanError> {
502        let feedback = feedback.trim().to_owned();
503        if feedback.is_empty() {
504            return Err(PlanError::EmptyFeedback);
505        }
506        let summary = self
507            .persisted
508            .plans
509            .iter_mut()
510            .find(|plan| &plan.id == plan_id)
511            .ok_or_else(|| PlanError::UnknownPlan {
512                plan_id: plan_id.clone(),
513            })?;
514        summary.status = PlanDocumentStatus::Draft;
515        summary.updated_at_ms = now_ms;
516        let summary_clone = summary.clone();
517        self.persisted.mode = PlanModeState::Active;
518        self.persisted.was_previously_active = true;
519        self.persisted.reminder_count = 0;
520        self.persisted.pending_exit_reminder = false;
521        self.persisted.active_plan_id = Some(plan_id.clone());
522        self.persisted.awaiting_approval_plan_id = None;
523        let content = self.contents.get(plan_id).cloned().unwrap_or_default();
524        Ok((
525            PlanDocument {
526                summary: summary_clone,
527                content,
528            },
529            PlanReviewDecision::ChangesRequested { feedback },
530        ))
531    }
532
533    /// Abandons a plan and exits Plan Mode without starting implementation.
534    pub(crate) fn abandon_plan(
535        &mut self,
536        plan_id: &PlanId,
537        now_ms: u64,
538    ) -> Result<(PlanDocument, PlanReviewDecision), PlanError> {
539        let summary = self
540            .persisted
541            .plans
542            .iter_mut()
543            .find(|plan| &plan.id == plan_id)
544            .ok_or_else(|| PlanError::UnknownPlan {
545                plan_id: plan_id.clone(),
546            })?;
547        summary.status = PlanDocumentStatus::Abandoned;
548        summary.updated_at_ms = now_ms;
549        let summary_clone = summary.clone();
550        self.persisted.mode = PlanModeState::Inactive;
551        self.persisted.reminder_count = 0;
552        self.persisted.pending_exit_reminder = false;
553        self.persisted.awaiting_approval_plan_id = None;
554        self.persisted.active_plan_id = None;
555        let content = self.contents.get(plan_id).cloned().unwrap_or_default();
556        Ok((
557            PlanDocument {
558                summary: summary_clone,
559                content,
560            },
561            PlanReviewDecision::Abandoned,
562        ))
563    }
564
565    /// Renders a compact dynamic reminder for provider requests.
566    ///
567    /// Returns `None` during normal inactive operation so non-plan turns incur
568    /// zero extra tokens and preserve prompt/KV cache stability.
569    #[must_use]
570    pub(crate) fn dynamic_prompt_reminder(&self) -> Option<String> {
571        match self.persisted.mode {
572            PlanModeState::Active => {
573                let full = self.persisted.reminder_count.is_multiple_of(2);
574                if !full {
575                    return Some(
576                        "<plan_mode>\nPlan Mode is still active. Workspace file edits remain blocked; update the plan with `write_plan` and call `exit_plan_mode` when ready for user review.\n</plan_mode>"
577                            .to_owned(),
578                    );
579                }
580                let plan_status = match self.persisted.active_plan_id.as_ref().and_then(|id| {
581                    self.persisted.plans.iter().find(|plan| &plan.id == id)
582                }) {
583                    Some(summary) => format!(
584                        "Active draft: `{}` (\"{}\", file `{}`, r{}). Update it in place with `write_plan`.",
585                        summary.id, summary.title, summary.file_name, summary.revision
586                    ),
587                    None => {
588                        "No draft written for this cycle yet. Author your Markdown plan with `write_plan`."
589                            .to_owned()
590                    }
591                };
592                Some(format!(
593                    "<plan_mode>\nPlan Mode is active (read-only). Do not modify workspace source files; `WorkspaceWrite` tools are blocked until the user approves your plan.\n\
594                     {plan_status}\n\
595                     Explore the repository read-only, write a clear Markdown plan (Context, Recommended Approach, Key Files, Verification) with `write_plan`, and finish your planning turn by calling `exit_plan_mode` (or asking the user clarifying questions).\n\
596                     </plan_mode>"
597                ))
598            }
599            PlanModeState::Inactive if self.persisted.pending_exit_reminder => Some(
600                "<plan_mode_exit>\nYou have exited Plan Mode. Workspace file edits are now enabled.\n</plan_mode_exit>"
601                    .to_owned(),
602            ),
603            PlanModeState::Inactive | PlanModeState::Pending | PlanModeState::ExitPending => None,
604        }
605    }
606}
607
608fn validate_title(title: &str) -> Result<String, PlanError> {
609    let trimmed = title.trim();
610    if trimmed.is_empty() {
611        return Err(PlanError::InvalidTitle {
612            reason: "must not be blank",
613        });
614    }
615    if trimmed.len() > MAX_PLAN_TITLE_BYTES {
616        return Err(PlanError::InvalidTitle {
617            reason: "exceeds maximum length of 200 UTF-8 bytes",
618        });
619    }
620    if trimmed.chars().any(char::is_control) {
621        return Err(PlanError::InvalidTitle {
622            reason: "must not contain control characters",
623        });
624    }
625    Ok(trimmed.to_owned())
626}
627
628/// Validates a plan file name stored directly under `<session_dir>/plans/`.
629pub(crate) fn validate_plan_file_name(file_name: &str) -> Result<(), PlanError> {
630    if file_name.is_empty()
631        || !file_name.ends_with(".md")
632        || file_name.contains('/')
633        || file_name.contains('\\')
634        || file_name.contains("..")
635        || file_name.chars().any(char::is_control)
636    {
637        return Err(PlanError::InvalidFileName {
638            file_name: file_name.to_owned(),
639        });
640    }
641    Ok(())
642}
643
644/// Produces a safe ASCII kebab-case slug from a human-readable plan title.
645fn slugify_title(title: &str) -> String {
646    let mut slug = String::new();
647    let mut prev_dash = false;
648    for ch in title.chars() {
649        if ch.is_ascii_alphanumeric() {
650            slug.push(ch.to_ascii_lowercase());
651            prev_dash = false;
652        } else if !slug.is_empty() && !prev_dash {
653            slug.push('-');
654            prev_dash = true;
655        }
656        if slug.len() >= MAX_SLUG_LEN {
657            break;
658        }
659    }
660    while slug.ends_with('-') {
661        slug.pop();
662    }
663    if slug.is_empty() {
664        "plan".to_owned()
665    } else {
666        slug
667    }
668}
669
670#[cfg(test)]
671mod tests {
672    use super::*;
673
674    #[test]
675    fn user_toggle_and_prompt_lifecycle() {
676        let mut state = PlanSessionState::default();
677        assert_eq!(state.mode(), PlanModeState::Inactive);
678        assert_eq!(state.dynamic_prompt_reminder(), None);
679
680        assert_eq!(
681            state.set_mode_from_user(true, false),
682            Some(PlanModeState::Pending)
683        );
684        assert!(!state.is_active());
685        assert_eq!(state.activate_on_user_prompt(), Some(PlanModeState::Active));
686        assert!(state.is_active());
687        assert!(
688            state
689                .dynamic_prompt_reminder()
690                .expect("full reminder")
691                .contains("write_plan")
692        );
693
694        state.record_prompt_delivered();
695        assert!(
696            state
697                .dynamic_prompt_reminder()
698                .expect("sparse reminder")
699                .contains("still active")
700        );
701
702        assert_eq!(
703            state.set_mode_from_user(false, true),
704            Some(PlanModeState::ExitPending)
705        );
706        assert_eq!(
707            state.complete_deferred_exit(),
708            Some(PlanModeState::Inactive)
709        );
710        assert!(
711            state
712                .dynamic_prompt_reminder()
713                .expect("exit reminder")
714                .contains("exited Plan Mode")
715        );
716        state.record_prompt_delivered();
717        assert_eq!(state.dynamic_prompt_reminder(), None);
718    }
719
720    #[test]
721    fn multiple_named_plans_preserve_history_and_slugs() {
722        let mut state = PlanSessionState::default();
723        state.activate_from_tool();
724
725        let p1 = state
726            .save_plan("Auth Architecture!", "# Plan 1\n", None, false, 100)
727            .expect("plan 1");
728        assert_eq!(p1.summary.id.as_str(), "plan-1");
729        assert_eq!(p1.summary.file_name, "001-auth-architecture.md");
730        assert_eq!(p1.summary.revision, 1);
731
732        let p1_v2 = state
733            .save_plan("Auth Architecture v2", "# Plan 1 v2\n", None, false, 200)
734            .expect("plan 1 update");
735        assert_eq!(p1_v2.summary.id, p1.summary.id);
736        assert_eq!(p1_v2.summary.revision, 2);
737        assert_eq!(p1_v2.summary.file_name, "001-auth-architecture.md");
738
739        let pending = state.request_approval(None, 250).expect("approval");
740        assert_eq!(pending.summary.status, PlanDocumentStatus::AwaitingApproval);
741        let (approved, decision) = state
742            .approve_plan(&p1.summary.id, Some("ship it".to_owned()), 300)
743            .expect("approve");
744        assert_eq!(approved.summary.status, PlanDocumentStatus::Approved);
745        assert!(matches!(
746            decision,
747            PlanReviewDecision::Approved { note: Some(_) }
748        ));
749        assert_eq!(state.mode(), PlanModeState::Inactive);
750
751        // Second plan in the same session gets a fresh numbered file name.
752        state.activate_from_tool();
753        let p2 = state
754            .save_plan("重构计划面板", "# Plan 2\n", None, false, 400)
755            .expect("plan 2");
756        assert_eq!(p2.summary.id.as_str(), "plan-2");
757        assert_eq!(p2.summary.file_name, "002-plan.md");
758        assert_eq!(state.summaries().len(), 2);
759    }
760
761    #[test]
762    fn reload_collapses_transient_states() {
763        let persisted = PersistedPlanModeState {
764            mode: PlanModeState::ExitPending,
765            ..Default::default()
766        };
767        let restored = PlanSessionState::from_persisted(persisted, BTreeMap::new());
768        assert_eq!(restored.mode(), PlanModeState::Inactive);
769        assert!(restored.dynamic_prompt_reminder().is_some());
770    }
771}