| 547 | } |
| 548 | |
| 549 | pub(crate) fn guard_agent_boundary( |
| 550 | repository_root: &std::path::Path, |
| 551 | managed: &mut Option<super::lifecycle::ManagedLifecycle>, |
| 552 | session_id: &str, |
| 553 | hook_type: HookType, |
| 554 | ) -> CliResult<Option<IncompleteSession>> { |
| 555 | let operation = match hook_type { |
| 556 | HookType::TurnEnd => GuardOperation::AgentTurnEnd, |
| 557 | HookType::SessionEnd => GuardOperation::AgentSessionEnd, |
| 558 | _ => return Ok(None), |
| 559 | }; |
| 560 | |
| 561 | // A managed run is terminal after its first refusal. Reuse that exact |
| 562 | // recovery object rather than reclassifying a filesystem that may already |
| 563 | // be under remediation. |
| 564 | if let Some(existing) = managed |
| 565 | .as_ref() |
| 566 | .and_then(|lifecycle| lifecycle.refusal.as_ref()) |
| 567 | { |
| 568 | return Ok(Some(existing.outcome.clone())); |
| 569 | } |
| 570 | |
| 571 | // A transient writer (stop checkpoint publication, recording) must not |
| 572 | // fail the guard: wait for it inside the opener so the stop hook can |
| 573 | // acquire its publication coordination first (dev-sync behavior). |
| 574 | let mut repository = Repository::open_for_workspace_transaction_wait( |
| 575 | repository_root, |
| 576 | std::time::Duration::from_secs(10), |
| 577 | ) |
| 578 | .map_err(|error| CliError::StaleBaseline { |
| 579 | report: format!( |
| 580 | "Unsafe operation: {operation}\nGuard failed before agent boundary: {error}" |
| 581 | ), |
| 582 | })?; |
| 583 | let boundary_start = repository |
| 584 | .begin_workspace_txn(WorkspaceTxnMode::Reconcile) |
| 585 | .map_err(|error| CliError::StaleBaseline { |
| 586 | report: format!( |
| 587 | "Unsafe operation: {operation}\nGuard failed before agent boundary: {error}" |
| 588 | ), |
| 589 | })?; |
| 590 | |
| 591 | match boundary_start { |
| 592 | WorkspaceTxnStart::Ready(_workspace) => { |
| 593 | // Safe baseline: the turn proceeds to the orchestrator. |
| 594 | // |
| 595 | // A session ending for a session Atomic never saw is the last |
| 596 | // chance to preserve pending tracked work: no session-start ever |
| 597 | // ran, so no pre-session capture exists and the ending must not |
| 598 | // quietly discard unattributed bytes. Preservation failure is |
| 599 | // never an empty successful turn — it persists a durable |
| 600 | // incomplete reason and ends non-zero. Successful preservation of |
| 601 | // pending work is evidence-only: nothing was imported, projected, |
| 602 | // or recorded, so the ending reports incomplete rather than |
| 603 | // claiming success. |
| 604 | if hook_type == HookType::SessionEnd |
| 605 | && !agent_session_exists(repository_root, session_id)? |
| 606 | { |