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) ──