feat(infra): temp IdeA launch-scoped alloué par lancement d'agent, injecté via TMPDIR/TMP/TEMP, writable_roots + release au stop, fail-closed — #200 (QA verte)

This commit is contained in:
2026-08-14 23:55:54 +02:00
parent 1d10a6ee80
commit 1157de1dda
5 changed files with 558 additions and 45 deletions

View File

@ -28,10 +28,11 @@ use domain::sandbox::{compile_sandbox_plan, PathAccess, PathGrant, SandboxContex
use domain::{
bound_handoff_summary, Agent, AgentId, AgentManifest, AgentOrigin, AgentProfile,
ContextInjection, ConversationId, ConversationParty, DomainEvent, EffectivePermissions,
Handoff, HandoffStore, ManifestEntry, MarkdownDoc, MemoryIndexEntry, MemoryType, NetworkPolicy,
NodeId, OrchestrationCapabilitySnapshot, PermissionProjector, ProfileId, Project, ProjectPath,
ProjectedFile, ProjectionContext, ProjectorKey, ProviderSessionStore, PtySize, SessionId,
SessionKind, SessionStatus, SkillKind, TerminalSession, HANDOFF_SUMMARY_MAX_CHARS,
Handoff, HandoffStore, ManagedTempKind, ManifestEntry, MarkdownDoc, MemoryIndexEntry,
MemoryType, NetworkPolicy, NodeId, OrchestrationCapabilitySnapshot, PermissionProjector,
ProfileId, Project, ProjectPath, ProjectedFile, ProjectionContext, ProjectorKey,
ProviderSessionStore, PtySize, SessionId, SessionKind, SessionStatus, SkillKind,
TerminalSession, HANDOFF_SUMMARY_MAX_CHARS,
};
use domain::live_state::WorkStatus;
@ -41,7 +42,10 @@ use crate::codex_permissions::{
};
use crate::error::AppError;
use crate::layout::{persist_doc, resolve_doc};
use crate::managed_temp::{ResolveManagedTemp, ResolveManagedTempInput};
use crate::managed_temp::{
AllocateManagedTemp, AllocateManagedTempInput, ReleaseManagedTemp, ReleaseManagedTempInput,
ResolveManagedTemp, ResolveManagedTempInput,
};
use crate::model_server::{
EnsureLocalModelServer, EnsureLocalModelServerInput, ModelServerUseGuard,
};
@ -1165,6 +1169,12 @@ pub struct ManagedTempExposureRequest {
pub handles: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct LaunchManagedTemp {
handle: String,
path: String,
}
/// OS/runtime facts injected by the composition root (`app-tauri`) to materialise
/// the **real** IdeA MCP server declaration in an agent's `.mcp.json` (cadrage v5
/// §2). Carrying these as **plain data** on [`LaunchAgentInput`] keeps
@ -1398,11 +1408,14 @@ fn enrich_sandbox_plan_with_rw_roots(
}
fn dedupe_paths(paths: impl IntoIterator<Item = LocalPath>) -> Vec<String> {
dedupe_string_paths(paths.into_iter().map(|path| path.as_str().to_owned()))
}
fn dedupe_string_paths(paths: impl IntoIterator<Item = String>) -> Vec<String> {
let mut roots = Vec::new();
for path in paths {
let root = path.as_str().to_owned();
if !roots.iter().any(|existing| existing == &root) {
roots.push(root);
if !roots.iter().any(|existing| existing == &path) {
roots.push(path);
}
}
roots.sort();
@ -1562,6 +1575,11 @@ pub struct LaunchAgent {
/// Resolves opaque managed-temp handles at launch time. A non-empty
/// [`ManagedTempExposureRequest`] fails closed when this dependency is absent.
managed_temp_resolver: Option<Arc<ResolveManagedTemp>>,
/// Allocates the primary launch-scoped managed temp directory.
managed_temp_allocator: Option<Arc<AllocateManagedTemp>>,
/// Releases the primary launch-scoped managed temp directory when launch fails
/// before registration.
managed_temp_releaser: Option<Arc<ReleaseManagedTemp>>,
/// Explicit intent for structured profiles when structured ports are absent.
structured_routing_mode: StructuredRoutingMode,
}
@ -1611,6 +1629,8 @@ impl LaunchAgent {
local_model_server: None,
secret_store: None,
managed_temp_resolver: None,
managed_temp_allocator: None,
managed_temp_releaser: None,
structured_routing_mode: StructuredRoutingMode::HumanPtyFallback,
}
}
@ -1648,6 +1668,18 @@ impl LaunchAgent {
self
}
/// Injects the allocator/releaser for the primary launch-scoped managed temp.
#[must_use]
pub fn with_launch_managed_temp(
mut self,
allocator: Arc<AllocateManagedTemp>,
releaser: Arc<ReleaseManagedTemp>,
) -> Self {
self.managed_temp_allocator = Some(allocator);
self.managed_temp_releaser = Some(releaser);
self
}
/// Branche le provider de **live-state lean (lot LS4)** : au lancement, l'aperçu
/// `# État du projet` (status + intent des autres agents) est injecté dans le
/// convention file. Sans cet appel (cas legacy / tests existants), aucune section
@ -1832,6 +1864,39 @@ impl LaunchAgent {
Ok(dedupe_paths(paths))
}
async fn allocate_launch_managed_temp(
&self,
project: &Project,
agent: &Agent,
) -> Result<Option<LaunchManagedTemp>, AppError> {
let Some(allocator) = self.managed_temp_allocator.as_ref() else {
return Ok(None);
};
let output = allocator
.execute(AllocateManagedTempInput {
owner_project_id: Some(project.id),
kind: ManagedTempKind::Directory,
purpose: format!("agent launch temp {}", agent.id),
ttl_ms: None,
})
.await?;
Ok(Some(LaunchManagedTemp {
handle: output.lease.handle.as_str().to_owned(),
path: output.lease.path.as_str().to_owned(),
}))
}
async fn release_launch_managed_temp_best_effort(&self, temp: Option<&LaunchManagedTemp>) {
let (Some(releaser), Some(temp)) = (self.managed_temp_releaser.as_ref(), temp) else {
return;
};
let _ = releaser
.execute(ReleaseManagedTempInput {
handle: temp.handle.clone(),
})
.await;
}
/// Résout **best-effort** le handoff de reprise de la cellule (lot P7), calqué sur
/// [`Self::resolve_memory`]. L'injection n'a lieu que si :
/// - la cellule porte une `conversation_id` ([`LaunchAgentInput::conversation_id`]),
@ -2266,9 +2331,32 @@ impl LaunchAgent {
// remplir `spec.sandbox`. `eff == None` (rien posé) ⇒ `None` : aucun plan,
// comportement natif conservé (invariant produit). L'enforcer concret
// (Landlock/Noop) est injecté côté PTY au composition root.
let managed_temp_writable_roots = self
.resolve_managed_temp_exposure(&input.managed_temp_exposure)
let launch_managed_temp = self
.allocate_launch_managed_temp(&input.project, &agent)
.await?;
if let Some(temp) = &launch_managed_temp {
upsert_env(&mut spec.env, "TMPDIR", &temp.path);
upsert_env(&mut spec.env, "TMP", &temp.path);
upsert_env(&mut spec.env, "TEMP", &temp.path);
}
let exposed_managed_temp_roots = match self
.resolve_managed_temp_exposure(&input.managed_temp_exposure)
.await
{
Ok(roots) => roots,
Err(err) => {
self.release_launch_managed_temp_best_effort(launch_managed_temp.as_ref())
.await;
return Err(err);
}
};
let managed_temp_writable_roots = dedupe_string_paths(
launch_managed_temp
.as_ref()
.map(|temp| temp.path.clone())
.into_iter()
.chain(exposed_managed_temp_roots.into_iter()),
);
spec.sandbox = compile_sandbox_plan(
effective_permissions.as_ref(),
&SandboxContext {
@ -2353,6 +2441,7 @@ impl LaunchAgent {
&spec.env,
spec.sandbox.as_ref(),
structured_policy.as_ref(),
launch_managed_temp,
local_model_server_guard,
)
.await;
@ -2374,13 +2463,22 @@ impl LaunchAgent {
append_codex_pty_model_overrides(&launch_profile, &mut spec);
// 6. Spawn the PTY at the resolved cwd; adopt its session id everywhere.
let handle = self.pty.spawn(spec.clone(), size).await?;
let handle = match self.pty.spawn(spec.clone(), size).await {
Ok(handle) => handle,
Err(err) => {
self.release_launch_managed_temp_best_effort(launch_managed_temp.as_ref())
.await;
return Err(err.into());
}
};
let session_id = handle.session_id;
// 7. For the Stdin strategy, pipe the context once the PTY is live.
if matches!(spec.context_plan, Some(ContextInjectionPlan::Stdin)) {
if let Err(err) = self.pty.write(&handle, content.as_str().as_bytes()) {
let _ = self.pty.kill(&handle).await;
self.release_launch_managed_temp_best_effort(launch_managed_temp.as_ref())
.await;
return Err(err.into());
}
}
@ -2394,11 +2492,12 @@ impl LaunchAgent {
size,
);
session.status = SessionStatus::Running;
self.sessions.insert_in_project_with_model_server_guard(
self.sessions.insert_in_project_with_runtime_resources(
input.project.id,
handle,
session.clone(),
local_model_server_guard,
launch_managed_temp.map(|temp| temp.handle),
);
self.events.publish(DomainEvent::AgentLaunched {
@ -2445,11 +2544,12 @@ impl LaunchAgent {
env: &[(String, String)],
sandbox: Option<&SandboxPlan>,
structured_policy: Option<&StructuredProviderLaunchPolicy>,
launch_managed_temp: Option<LaunchManagedTemp>,
model_server_guard: Option<ModelServerUseGuard>,
) -> Result<LaunchAgentOutput, AppError> {
// Relaie le plan de sandbox OS (lot LP4-4) à la fabrique : `spec.sandbox`,
// déjà compilé (pur, domaine) en step 5d. `None` ⇒ exécution native inchangée.
let session = factory
let session = match factory
.start(
profile,
prepared,
@ -2461,19 +2561,27 @@ impl LaunchAgent {
structured_policy,
)
.await
.map_err(|e| AppError::Process(e.to_string()))?;
{
Ok(session) => session,
Err(err) => {
self.release_launch_managed_temp_best_effort(launch_managed_temp.as_ref())
.await;
return Err(AppError::Process(err.to_string()));
}
};
let session_id = session.id();
let node_id = node_id.unwrap_or_else(NodeId::new_random);
// Enregistre la session vivante (invariant « 1 session/agent » : déjà gardé en
// amont sur les deux registres).
structured.insert_in_project_with_model_server_guard(
structured.insert_in_project_with_runtime_resources(
project_id,
Arc::clone(&session),
agent.id,
node_id,
model_server_guard,
launch_managed_temp.map(|temp| temp.handle),
);
// ── SÉPARATION DES DEUX CLÉS (ARCHITECTURE §19.7, lot P8a) ──

View File

@ -15,6 +15,22 @@ use domain::{AgentId, IssueRef, NodeId, ProjectId, SessionId, SessionKind, Termi
use crate::model_server::ModelServerUseGuard;
/// Runtime resources attached to a live PTY session and released when it stops.
pub struct RemovedPtySession {
/// Live PTY handle to kill.
pub handle: PtyHandle,
/// Launch-scoped managed-temp handle retained for release.
pub managed_temp_handle: Option<String>,
}
/// Runtime resources attached to a live structured session and released when it stops.
pub struct RemovedStructuredSession {
/// Live structured session to shut down.
pub session: Arc<dyn AgentSession>,
/// Launch-scoped managed-temp handle retained for release.
pub managed_temp_handle: Option<String>,
}
/// Runtime family of a live agent session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LiveSessionKind {
@ -103,6 +119,7 @@ struct Entry {
project_id: ProjectId,
handle: PtyHandle,
session: TerminalSession,
managed_temp_handle: Option<String>,
_model_server_guard: Option<ModelServerUseGuard>,
}
@ -262,6 +279,24 @@ impl TerminalSessions {
handle: PtyHandle,
session: TerminalSession,
model_server_guard: Option<ModelServerUseGuard>,
) {
self.insert_in_project_with_runtime_resources(
project_id,
handle,
session,
model_server_guard,
None,
);
}
/// Inserts a freshly-opened session and retains runtime resources until removal.
pub fn insert_in_project_with_runtime_resources(
&self,
project_id: ProjectId,
handle: PtyHandle,
session: TerminalSession,
model_server_guard: Option<ModelServerUseGuard>,
managed_temp_handle: Option<String>,
) {
if let Ok(mut map) = self.entries.lock() {
map.insert(
@ -270,6 +305,7 @@ impl TerminalSessions {
project_id,
handle,
session,
managed_temp_handle,
_model_server_guard: model_server_guard,
},
);
@ -445,13 +481,20 @@ impl TerminalSessions {
/// Removes a session from the registry, returning its handle if present. Also
/// drops any conversation binding pointing at it (no stale `session_for`).
pub fn remove(&self, id: &SessionId) -> Option<PtyHandle> {
self.remove_runtime(id).map(|removed| removed.handle)
}
/// Removes a session and returns all runtime resources retained for it.
pub fn remove_runtime(&self, id: &SessionId) -> Option<RemovedPtySession> {
if let Ok(mut c) = self.conversations.lock() {
c.retain(|_, sid| sid != id);
}
self.entries
.lock()
.ok()
.and_then(|mut m| m.remove(id).map(|e| e.handle))
self.entries.lock().ok().and_then(|mut m| {
m.remove(id).map(|e| RemovedPtySession {
handle: e.handle,
managed_temp_handle: e.managed_temp_handle,
})
})
}
/// Number of currently-registered sessions.
@ -487,6 +530,8 @@ struct StructuredEntry {
agent_id: AgentId,
/// La cellule (feuille de layout) qui héberge actuellement la vue.
node_id: NodeId,
/// Launch-scoped managed-temp handle retained for release.
managed_temp_handle: Option<String>,
/// Optional local-model-server usage guard retained for the live session.
_model_server_guard: Option<ModelServerUseGuard>,
}
@ -579,6 +624,26 @@ impl StructuredSessions {
agent_id: AgentId,
node_id: NodeId,
model_server_guard: Option<ModelServerUseGuard>,
) {
self.insert_in_project_with_runtime_resources(
project_id,
session,
agent_id,
node_id,
model_server_guard,
None,
);
}
/// Enregistre une session structurée et retient ses ressources runtime.
pub fn insert_in_project_with_runtime_resources(
&self,
project_id: ProjectId,
session: Arc<dyn AgentSession>,
agent_id: AgentId,
node_id: NodeId,
model_server_guard: Option<ModelServerUseGuard>,
managed_temp_handle: Option<String>,
) {
if let Ok(mut map) = self.entries.lock() {
let id = session.id();
@ -589,6 +654,7 @@ impl StructuredSessions {
session,
agent_id,
node_id,
managed_temp_handle,
_model_server_guard: model_server_guard,
},
);
@ -831,17 +897,30 @@ impl StructuredSessions {
/// Retire une session du registre, retournant la session si présente (pour que
/// l'appelant la `shutdown` hors du verrou).
pub fn remove(&self, id: &SessionId) -> Option<Arc<dyn AgentSession>> {
self.remove_runtime(id).map(|removed| removed.session)
}
/// Retire une session du registre, retournant ses ressources runtime.
pub fn remove_runtime(&self, id: &SessionId) -> Option<RemovedStructuredSession> {
self.entries
.lock()
.ok()
.and_then(|mut m| m.remove(id).map(|e| e.session))
.and_then(|mut m| {
m.remove(id).map(|e| RemovedStructuredSession {
session: e.session,
managed_temp_handle: e.managed_temp_handle,
})
})
.or_else(|| {
self.ticket_assistants.lock().ok().and_then(|mut m| {
let issue_ref = m
.iter()
.find(|(_, e)| e.session.id() == *id)
.map(|(issue_ref, _)| *issue_ref)?;
m.remove(&issue_ref).map(|e| e.session)
m.remove(&issue_ref).map(|e| RemovedStructuredSession {
session: e.session,
managed_temp_handle: None,
})
})
})
}

View File

@ -9,6 +9,7 @@ use domain::{
};
use crate::error::AppError;
use crate::managed_temp::{ReleaseManagedTemp, ReleaseManagedTempInput};
use super::registry::{LiveRuntimeState, LiveSessionKind, LiveSessions, TerminalSessions};
@ -202,13 +203,39 @@ pub struct CloseTerminalOutput {
pub struct CloseTerminal {
pty: Arc<dyn PtyPort>,
sessions: Arc<TerminalSessions>,
managed_temp_releaser: Option<Arc<ReleaseManagedTemp>>,
}
impl CloseTerminal {
/// Builds the use case.
#[must_use]
pub fn new(pty: Arc<dyn PtyPort>, sessions: Arc<TerminalSessions>) -> Self {
Self { pty, sessions }
Self {
pty,
sessions,
managed_temp_releaser: None,
}
}
/// Injects the releaser for launch-scoped managed temp roots.
#[must_use]
pub fn with_managed_temp_releaser(mut self, releaser: Arc<ReleaseManagedTemp>) -> Self {
self.managed_temp_releaser = Some(releaser);
self
}
/// Releases a launch-scoped managed temp handle retained by a live session.
pub async fn release_managed_temp_handle(
&self,
handle: Option<String>,
) -> Result<(), AppError> {
let (Some(releaser), Some(handle)) = (&self.managed_temp_releaser, handle) else {
return Ok(());
};
releaser
.execute(ReleaseManagedTempInput { handle })
.await
.map(|_| ())
}
/// Kills the session's PTY and removes it from the registry. Idempotent on
@ -226,7 +253,12 @@ impl CloseTerminal {
.handle(&input.session_id)
.ok_or_else(|| AppError::NotFound(format!("terminal session {}", input.session_id)))?;
let status = self.pty.kill(&handle).await?;
self.sessions.remove(&input.session_id);
let managed_temp_handle = self
.sessions
.remove_runtime(&input.session_id)
.and_then(|removed| removed.managed_temp_handle);
self.release_managed_temp_handle(managed_temp_handle)
.await?;
Ok(CloseTerminalOutput { code: status.code })
}
}
@ -264,11 +296,15 @@ pub async fn stop_live_agent_runtime_in_project(
live.mark_runtime_state(snapshot, LiveRuntimeState::Stopping);
match snapshot.kind {
LiveSessionKind::Structured => {
if let Some(session) = live.structured.remove(&snapshot.session_id) {
session
if let Some(removed) = live.structured.remove_runtime(&snapshot.session_id) {
removed
.session
.shutdown()
.await
.map_err(|e| AppError::Process(e.to_string()))?;
close
.release_managed_temp_handle(removed.managed_temp_handle)
.await?;
}
}
LiveSessionKind::Pty => {