| 744 | } |
| 745 | |
| 746 | pub(crate) fn guard_agent_boundary( |
| 747 | repository_root: &std::path::Path, |
| 748 | managed: &mut Option<super::lifecycle::ManagedLifecycle>, |
| 749 | session_id: &str, |
| 750 | hook_type: HookType, |
| 751 | ) -> CliResult<AgentBoundary> { |
| 752 | let operation = match hook_type { |
| 753 | HookType::TurnEnd => GuardOperation::AgentTurnEnd, |
| 754 | HookType::SessionEnd => GuardOperation::AgentSessionEnd, |
| 755 | _ => return Ok(AgentBoundary::Ready), |
| 756 | }; |
| 757 | |
| 758 | // A managed run is terminal after its first refusal. Reuse that exact |
| 759 | // recovery object rather than reclassifying a filesystem that may already |
| 760 | // be under remediation. |
| 761 | if let Some(existing) = managed |
| 762 | .as_ref() |
| 763 | .and_then(|lifecycle| lifecycle.refusal.as_ref()) |
| 764 | { |
| 765 | return Ok(AgentBoundary::Refused(existing.outcome.clone())); |
| 766 | } |
| 767 | |
| 768 | // A transient writer (stop checkpoint publication, recording) must not |
| 769 | // fail the guard: wait for it inside the opener so the stop hook can |
| 770 | // acquire its publication coordination first (dev-sync behavior). |
| 771 | let mut repository = Repository::open_for_workspace_transaction_wait( |
| 772 | repository_root, |
| 773 | std::time::Duration::from_secs(10), |
| 774 | ) |
| 775 | .map_err(|error| CliError::StaleBaseline { |
| 776 | report: format!( |
| 777 | "Unsafe operation: {operation}\nGuard failed before agent boundary: {error}" |
| 778 | ), |
| 779 | })?; |
| 780 | let boundary_start = repository |
| 781 | .begin_workspace_txn(WorkspaceTxnMode::Reconcile) |
| 782 | .map_err(|error| CliError::StaleBaseline { |
| 783 | report: format!( |
| 784 | "Unsafe operation: {operation}\nGuard failed before agent boundary: {error}" |
| 785 | ), |
| 786 | })?; |
| 787 | |
| 788 | match boundary_start { |
| 789 | WorkspaceTxnStart::Ready(_workspace) => { |
| 790 | // Safe baseline: the turn proceeds to the orchestrator. |
| 791 | // |
| 792 | // A session ending for a session Atomic never saw is the last |
| 793 | // chance to preserve pending tracked work: no session-start ever |
| 794 | // ran, so no pre-session capture exists and the ending must not |
| 795 | // quietly discard unattributed bytes. Preservation failure is |
| 796 | // never an empty successful turn — it persists a durable |
| 797 | // incomplete reason and ends non-zero. Successful preservation of |
| 798 | // pending work is evidence-only: nothing was imported, projected, |
| 799 | // or recorded, so the ending reports incomplete rather than |
| 800 | // claiming success. |
| 801 | if hook_type == HookType::SessionEnd |
| 802 | && !agent_session_exists(repository_root, session_id)? |
| 803 | { |