Bind the currently active turn before recording. Repeating the same declaration is idempotent; replacing it or binding a completed turn fails. `expected_turn` lets integrations reject delayed commands from an old turn.
(
&self,
session_id: &str,
expected_turn: Option<u32>,
intent_uid: &str,
)
| 774 | /// declaration is idempotent; replacing it or binding a completed turn fails. |
| 775 | /// `expected_turn` lets integrations reject delayed commands from an old turn. |
| 776 | pub fn bind_turn_intent( |
| 777 | &self, |
| 778 | session_id: &str, |
| 779 | expected_turn: Option<u32>, |
| 780 | intent_uid: &str, |
| 781 | ) -> AgentResult<TurnIntentBinding> { |
| 782 | use fs2::FileExt; |
| 783 | use std::io::Write; |
| 784 | |
| 785 | validate_session_id(session_id)?; |
| 786 | let failure = |reason: String| AgentError::SessionSaveFailed { |
| 787 | session_id: session_id.to_string(), |
| 788 | reason, |
| 789 | }; |
| 790 | let dir = self.sessions_dir.join(session_id); |
| 791 | std::fs::create_dir_all(&dir)?; |
| 792 | // The recorder holds this lock from session load through publication. |
| 793 | let lock = std::fs::OpenOptions::new() |
| 794 | .create(true) |
| 795 | .write(true) |
| 796 | .truncate(false) |
| 797 | .open(dir.join("turn-end.lock"))?; |
| 798 | lock.try_lock_exclusive().map_err(|error| { |
| 799 | failure(format!( |
| 800 | "cannot bind intent while turn is recording: {error}" |
| 801 | )) |
| 802 | })?; |
| 803 | let session = self |
| 804 | .load(session_id)? |
| 805 | .ok_or_else(|| failure("unknown session".into()))?; |
| 806 | if session.session_id != session_id |
| 807 | || !session.is_turn_active() |
| 808 | || session.is_ended() |
| 809 | || session.incomplete().is_some() |
| 810 | { |
| 811 | return Err(failure( |
| 812 | "intent binding requires an active, complete session turn".into(), |
| 813 | )); |
| 814 | } |
| 815 | let turn_number = session.turn_count.saturating_add(1); |
| 816 | if dir |
| 817 | .join(format!("intent-{turn_number}.frozen")) |
| 818 | .try_exists()? |
| 819 | { |
| 820 | return Err(failure( |
| 821 | "turn recording has already started; governing intent is frozen".into(), |
| 822 | )); |
| 823 | } |
| 824 | if expected_turn.is_some_and(|expected| expected != turn_number) { |
| 825 | return Err(failure(format!( |
| 826 | "stale intent binding: active turn is {turn_number}" |
| 827 | ))); |
| 828 | } |
| 829 | if intent_uid.trim().is_empty() { |
| 830 | return Err(failure("intent UID must not be empty".into())); |
| 831 | } |
| 832 | // Managed work items remain authoritative. Non-UID managed references |
| 833 | // retain their existing checkpoint fallback rather than being replaced. |