sergio/takana
> Una distribución Linux construida con un laboratorio funcional y hermético en el > sótano, y una terminal mutable, clásica y anárquica en el piso de arriba — diseñada > desde el suelo para que una IA programadora entienda, modifique y co…
⎇ f769d9173c036c3d9dc035bf1c7040d189f1b7c1
crates/hammer-agent/src/orchestrator.rs
History
Who touched what
raw
Fase 6 — bucle de auto-reparación (cliente reacciona a Crashed)
1//! El bucle agéntico. Ver `docs/08-ai-integration.md` §2.
2//!
3//! `Orchestrator::run(intent)` ejecuta:
4//!
5//! ```text
6//! plan → translator.translate(intent, ctx) → Swm
7//! schema → swm.verify_schema()
8//! base → swm.verify_base(local) → debe ser Ok
9//! build → para cada source_patch: AgentClient.compile() vía el bus (o saltar si --no-bus)
10//! try → hammer_overlay::try_overlay() (o usar --prefix)
11//! apply → hammer-core::apply para config_edit/file_drop + hydrate para source_patch
12//! verify → spot-checks post-condición sobre disco
13//! propose → devuelve Proposal con overlay_id + log de checks
14//! ```
15//!
16//! La IA NUNCA ejecuta `hammer commit`. El humano lo hace tras revisar el `Proposal`.
17
18use std::path::{Path, PathBuf};
19use std::time::Duration;
20
21use hammer_core::apply::{apply_config_edit, apply_file_drop, rebase_path};
22use hammer_core::proto::RecipeInline;
23use hammer_core::swm::{Mutation, Swm};
24use hammer_core::BaseRef;
25use hammer_overlay::OverlayId;
26
27use crate::client::AgentClient;
28use crate::translator::{IntentTranslator, SystemContext};
29use crate::{Error, Result};
30
31/// Cómo aplica el orquestador las mutaciones al sistema.
32#[derive(Debug, Clone)]
33pub enum ApplyTarget {
34 /// Abre un overlay sobre los targets por defecto del FHS (requiere root). Las
35 /// mutaciones caen sobre las rutas absolutas del `.swm`.
36 Overlay { state_root: PathBuf },
37 /// Re-rootea cada path bajo `prefix`. No abre overlay — útil para tests offline y
38 /// para staging en otro filesystem.
39 Prefix { prefix: PathBuf },
40}
41
42/// Cómo se construyen las `source_patch`. `ViaBus` requiere un `hammerd` corriendo;
43/// `Skip` ignora las source_patch (apropiado para escenarios sin lab).
44#[derive(Debug, Clone)]
45pub enum CompileMode {
46 /// Llama a `Compile` por el bus y espera `BuildReady`. Hidrata localmente desde el
47 /// store si está configurado.
48 ViaBus {
49 sock: PathBuf,
50 store: PathBuf,
51 timeout: Duration,
52 },
53 /// Salta cualquier `source_patch`. Se anota en `Proposal.skipped_source_patches`.
54 Skip,
55}
56
57pub struct Orchestrator<T: IntentTranslator> {
58 translator: T,
59 base: BaseRef,
60 apply: ApplyTarget,
61 compile: CompileMode,
62}
63
64impl<T: IntentTranslator> Orchestrator<T> {
65 pub fn new(translator: T, base: BaseRef, apply: ApplyTarget, compile: CompileMode) -> Self {
66 Self { translator, base, apply, compile }
67 }
68
69 pub fn run(&self, intent: &str) -> Result<Proposal> {
70 // 1. PLAN
71 let ctx = SystemContext {
72 base: self.base.clone(),
73 extras: serde_json::Value::Null,
74 };
75 let swm = self.translator.translate(intent, &ctx)?;
76
77 // 2. SCHEMA
78 swm.verify_schema()?;
79
80 // 3. BASE
81 match swm.verify_base(&self.base) {
82 hammer_core::BaseCompat::Ok => {}
83 other => {
84 return Err(Error::Orchestrate(format!(
85 "base incompatible: {other:?}"
86 )));
87 }
88 }
89
90 // 4. TRY (overlay) — recolectamos el id si lo abrimos; en modo Prefix no hay id.
91 let (overlay_id, prefix): (Option<OverlayId>, Option<PathBuf>) = match &self.apply {
92 ApplyTarget::Overlay { state_root } => {
93 std::fs::create_dir_all(state_root)?;
94 let id = hammer_overlay::try_overlay(&[], state_root)?;
95 (Some(id), None)
96 }
97 ApplyTarget::Prefix { prefix } => {
98 std::fs::create_dir_all(prefix)?;
99 (None, Some(prefix.clone()))
100 }
101 };
102
103 // 5. APPLY — recorremos las mutaciones en orden. En source_patch, dispatch al bus
104 // o skip; en config_edit/file_drop, primitivas de hammer-core::apply.
105 let mut applied = AppliedCounts::default();
106 let mut checks: Vec<VerifyCheck> = Vec::new();
107 let mut skipped_source_patches = 0usize;
108
109 let mut maybe_client: Option<AgentClient> = None;
110 if matches!(self.compile, CompileMode::ViaBus { .. })
111 && swm.mutations.iter().any(|m| matches!(m, Mutation::SourcePatch { .. }))
112 {
113 if let CompileMode::ViaBus { sock, .. } = &self.compile {
114 maybe_client = Some(AgentClient::connect(sock).map_err(Error::Client)?);
115 }
116 }
117
118 for m in &swm.mutations {
119 match m {
120 Mutation::ConfigEdit { file, inline_diff } => {
121 let target = rebase_path(file, prefix.as_deref());
122 apply_config_edit(&target, inline_diff)?;
123 applied.config_edit += 1;
124 checks.push(VerifyCheck::pass(format!(
125 "config_edit aplicado a {}",
126 target.display()
127 )));
128 }
129 Mutation::FileDrop { path, content_hash, content_b64, content_url } => {
130 if let Some(_url) = content_url {
131 return Err(Error::Orchestrate(format!(
132 "file_drop con content_url no soportado en Fase 6: {path}"
133 )));
134 }
135 let b64 = content_b64.as_deref().ok_or_else(|| {
136 Error::Orchestrate(format!(
137 "file_drop {path} no trae content_b64 (verify_schema falló)"
138 ))
139 })?;
140 let target = rebase_path(path, prefix.as_deref());
141 apply_file_drop(&target, b64, content_hash)?;
142 applied.file_drop += 1;
143 checks.push(VerifyCheck::pass(format!(
144 "file_drop escrito en {} (hash verificado)",
145 target.display()
146 )));
147 }
148 Mutation::InitRule { action, service, .. } => {
149 applied.init_rule += 1;
150 checks.push(VerifyCheck::warn(format!(
151 "init_rule '{action} {service}' anotada — pendiente Fase 5+ (supervisor)"
152 )));
153 }
154 Mutation::SourcePatch {
155 repo,
156 commit,
157 patch,
158 patch_url: _,
159 build,
160 target_bin,
161 expected_hash,
162 } => {
163 let CompileMode::ViaBus { store, timeout, .. } = &self.compile else {
164 skipped_source_patches += 1;
165 checks.push(VerifyCheck::warn(format!(
166 "source_patch {target_bin} omitido (CompileMode::Skip)"
167 )));
168 continue;
169 };
170 let name = Path::new(target_bin)
171 .file_name()
172 .and_then(|s| s.to_str())
173 .unwrap_or("swm-bin")
174 .to_string();
175 let recipe = RecipeInline {
176 name: name.clone(),
177 repo: repo.clone(),
178 commit: commit.clone(),
179 patch: patch.clone(),
180 compiler: build.compiler.clone(),
181 target: build.target.clone(),
182 link: build.link.clone(),
183 flags: build.flags.clone(),
184 };
185 let client = maybe_client.as_mut().expect("client conectado arriba");
186 let artifact = client
187 .compile(recipe, *timeout)
188 .map_err(Error::Client)?;
189 if let Some(expected) = expected_hash {
190 let want = expected.strip_prefix("b3:").unwrap_or(expected);
191 let got = artifact.strip_prefix("b3:").unwrap_or(&artifact);
192 if want != got {
193 return Err(Error::Orchestrate(format!(
194 "source_patch {target_bin}: expected_hash no coincide \
195 (declarado=b3:{want}, build=b3:{got})"
196 )));
197 }
198 }
199 // Hidratamos localmente desde el store (sin pasar por el bus, evita un
200 // segundo Inject que duplicaría trabajo).
201 let store = hammer_core::Store::open(store)?;
202 let artifact_dir = store
203 .find_by_hash(&artifact)
204 .map_err(|e| Error::Orchestrate(format!("find_by_hash: {e}")))?;
205 let into = rebase_path("/", prefix.as_deref());
206 let report = hammer_build_run_hydrate(&artifact_dir, &into)?;
207 let abs = rebase_path(target_bin, prefix.as_deref());
208 if !abs.exists() {
209 return Err(Error::Orchestrate(format!(
210 "source_patch declara target_bin={target_bin} pero no quedó en {}",
211 abs.display()
212 )));
213 }
214 applied.source_patch += 1;
215 checks.push(VerifyCheck::pass(format!(
216 "source_patch {target_bin}: build {artifact}, {} archivo(s) hidratado(s)",
217 report
218 )));
219 }
220 }
221 }
222
223 Ok(Proposal {
224 intent: intent.to_string(),
225 swm,
226 overlay_id: overlay_id.map(|o| o.as_str().to_string()),
227 prefix: prefix.clone(),
228 applied,
229 skipped_source_patches,
230 checks,
231 repair_chain: Vec::new(),
232 })
233 }
234
235 /// Variante con auto-reparación. Tras cada aplicación, si la política trae un
236 /// `event_sock`, abre un cliente del bus y espera `crash_window` para ver si
237 /// llega un `Crashed`. Si llega, traduce `(service, code)` a una nueva intención
238 /// con `policy.format_intent` y vuelve a entrar al bucle, hasta `max_attempts`.
239 ///
240 /// El `Proposal` devuelto siempre lleva la cadena completa de intentos en
241 /// `repair_chain`. Si el último intento se estabilizó (sin crash dentro de la
242 /// ventana), su `triggered_crash` es `None`. Si se agotaron los intentos con un
243 /// crash todavía pendiente, la última entrada lo refleja — el humano lee la cadena
244 /// y decide si commit, discard o seguir manualmente.
245 pub fn run_with_repair(&self, intent: &str, policy: &RepairPolicy) -> Result<Proposal> {
246 let max = policy.max_attempts.max(1);
247 let mut chain: Vec<RepairAttempt> = Vec::new();
248 let mut current = intent.to_string();
249 let mut last: Option<Proposal> = None;
250
251 for attempt in 0..max {
252 let p = self.run(¤t)?;
253 let overlay_id = p.overlay_id.clone();
254
255 let crash = wait_for_crash(policy);
256 chain.push(RepairAttempt {
257 attempt,
258 intent: current.clone(),
259 overlay_id,
260 triggered_crash: crash.clone(),
261 });
262 last = Some(p);
263
264 match crash {
265 None => break, // estabilizado
266 Some(c) => {
267 current = (policy.format_intent)(&c.service, c.code);
268 }
269 }
270 }
271
272 let mut p = last.expect("max_attempts >= 1, así que hubo al menos un run");
273 p.repair_chain = chain;
274 Ok(p)
275 }
276}
277
278/// Conecta al bus y drena eventos hasta encontrar un `Crashed` dentro de `crash_window`.
279/// Devuelve `None` si:
280/// - la política no tiene socket;
281/// - la conexión falla (caso "no hay bus") — el bucle decide entonces "estabilizado";
282/// - expira la ventana sin recibir Crashed.
283fn wait_for_crash(policy: &RepairPolicy) -> Option<CrashInfo> {
284 let Some(sock) = &policy.event_sock else { return None };
285 let client = match AgentClient::connect(sock) {
286 Ok(c) => c,
287 Err(e) => {
288 tracing::debug!(error = %e, "auto-repair: no pude conectar al bus, ignoro");
289 return None;
290 }
291 };
292 let deadline = std::time::Instant::now() + policy.crash_window;
293 // Drenamos primero la cola asíncrona ya acumulada (eventos llegados durante el `run`).
294 for ev in client.drain_async() {
295 if let hammer_core::proto::Event::Crashed { service, code } = ev {
296 return Some(CrashInfo { service, code });
297 }
298 }
299 while let Some(remaining) = deadline.checked_duration_since(std::time::Instant::now()) {
300 match client.next_async(remaining) {
301 Ok(hammer_core::proto::Event::Crashed { service, code }) => {
302 return Some(CrashInfo { service, code });
303 }
304 Ok(_other) => continue,
305 Err(_) => break, // timeout o cierre
306 }
307 }
308 None
309}
310
311/// Stub: `hammer-build` no es dependencia directa de `hammer-agent` para no arrastrar el
312/// lab a clientes que sólo quieran hablar con el bus. Implementamos la hidratación local
313/// con `std::fs::hard_link` directamente porque es trivial. Si el árbol del artefacto crece
314/// (symlinks, perms más finos), promovemos a `hammer-build::run_hydrate` añadiendo la dep
315/// de manera condicional.
316fn hammer_build_run_hydrate(artifact_dir: &Path, target_fhs: &Path) -> Result<usize> {
317 let mut files = 0usize;
318 walk(artifact_dir, &mut |rel, kind| {
319 let dst = target_fhs.join(rel);
320 match kind {
321 EntryKind::Dir => {
322 std::fs::create_dir_all(&dst)?;
323 }
324 EntryKind::Symlink(target) => {
325 if let Some(parent) = dst.parent() {
326 std::fs::create_dir_all(parent)?;
327 }
328 let _ = std::fs::remove_file(&dst);
329 std::os::unix::fs::symlink(&target, &dst)?;
330 files += 1;
331 }
332 EntryKind::File(src) => {
333 if let Some(parent) = dst.parent() {
334 std::fs::create_dir_all(parent)?;
335 }
336 let _ = std::fs::remove_file(&dst);
337 std::fs::hard_link(&src, &dst).or_else(|_| {
338 // Cross-fs ⇒ caemos a copia. No optimizamos: hammer-agent espera
339 // mismo FS; sólo damos el fallback como cinturón de seguridad.
340 std::fs::copy(&src, &dst).map(|_| ())
341 })?;
342 files += 1;
343 }
344 }
345 Ok::<(), std::io::Error>(())
346 })?;
347 Ok(files)
348}
349
350enum EntryKind {
351 Dir,
352 Symlink(PathBuf),
353 File(PathBuf),
354}
355
356fn walk<F>(root: &Path, f: &mut F) -> std::io::Result<()>
357where
358 F: FnMut(&Path, EntryKind) -> std::io::Result<()>,
359{
360 fn inner<F>(root: &Path, cur: &Path, f: &mut F) -> std::io::Result<()>
361 where
362 F: FnMut(&Path, EntryKind) -> std::io::Result<()>,
363 {
364 for entry in std::fs::read_dir(cur)? {
365 let entry = entry?;
366 let src = entry.path();
367 let rel = src.strip_prefix(root).unwrap();
368 let ft = entry.file_type()?;
369 if ft.is_symlink() {
370 let target = std::fs::read_link(&src)?;
371 f(rel, EntryKind::Symlink(target))?;
372 } else if ft.is_dir() {
373 f(rel, EntryKind::Dir)?;
374 inner(root, &src, f)?;
375 } else if ft.is_file() {
376 f(rel, EntryKind::File(src.clone()))?;
377 }
378 }
379 Ok(())
380 }
381 if !root.is_dir() {
382 return Err(std::io::Error::new(
383 std::io::ErrorKind::NotFound,
384 format!("artifact_dir no existe: {}", root.display()),
385 ));
386 }
387 inner(root, root, f)
388}
389
390#[derive(Debug, Default, Clone, serde::Serialize)]
391pub struct AppliedCounts {
392 pub source_patch: usize,
393 pub config_edit: usize,
394 pub init_rule: usize,
395 pub file_drop: usize,
396}
397
398#[derive(Debug, Clone, serde::Serialize)]
399pub struct VerifyCheck {
400 pub level: CheckLevel,
401 pub msg: String,
402}
403
404#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
405#[serde(rename_all = "kebab-case")]
406pub enum CheckLevel {
407 Pass,
408 Warn,
409 Fail,
410}
411
412impl VerifyCheck {
413 pub fn pass(msg: impl Into<String>) -> Self {
414 Self { level: CheckLevel::Pass, msg: msg.into() }
415 }
416 pub fn warn(msg: impl Into<String>) -> Self {
417 Self { level: CheckLevel::Warn, msg: msg.into() }
418 }
419}
420
421/// El resultado del bucle. El humano lo lee para decidir `hammer commit <overlay_id>` (si
422/// está en modo Overlay) o `hammer discard`.
423#[derive(Debug, Clone, serde::Serialize)]
424pub struct Proposal {
425 pub intent: String,
426 pub swm: Swm,
427 /// `Some` si abrimos un overlay. En modo Prefix, `None`.
428 pub overlay_id: Option<String>,
429 pub prefix: Option<PathBuf>,
430 pub applied: AppliedCounts,
431 pub skipped_source_patches: usize,
432 pub checks: Vec<VerifyCheck>,
433 /// Si la propuesta provino del bucle de auto-reparación, la cadena completa de
434 /// intentos. La última entrada corresponde a este `Proposal`. Para corridas sin
435 /// auto-reparación queda vacío.
436 #[serde(default, skip_serializing_if = "Vec::is_empty")]
437 pub repair_chain: Vec<RepairAttempt>,
438}
439
440/// Un intento dentro del bucle de auto-reparación. Sirve para que el humano vea
441/// cómo evolucionó la intención: original → reparación A → reparación B …
442#[derive(Debug, Clone, serde::Serialize)]
443pub struct RepairAttempt {
444 pub attempt: u32,
445 pub intent: String,
446 /// `Some` cuando el ciclo abrió un overlay; preservado para que el humano pueda hacer
447 /// `hammer discard <id>` sobre intentos intermedios si lo desea.
448 pub overlay_id: Option<String>,
449 /// Si tras este intento llegó un `Crashed`, el servicio y código. `None` ⇒ estabilizado.
450 pub triggered_crash: Option<CrashInfo>,
451}
452
453#[derive(Debug, Clone, serde::Serialize)]
454pub struct CrashInfo {
455 pub service: String,
456 pub code: i32,
457}
458
459/// Política del bucle de auto-reparación. La IA NUNCA decide por sí sola seguir
460/// reintentando: la política la fija el llamador (CLI o cliente) y acota el blast-radius.
461#[derive(Clone)]
462pub struct RepairPolicy {
463 /// Máximo de intentos en total (incluyendo el primero). Mínimo efectivo: 1.
464 pub max_attempts: u32,
465 /// Ventana de espera tras aplicar para detectar un `Crashed` por el bus.
466 pub crash_window: Duration,
467 /// Socket del bus de eventos. Si `None`, el orquestador no escucha y devuelve
468 /// el `Proposal` tras la primera aplicación (equivalente a `run`).
469 pub event_sock: Option<PathBuf>,
470 /// Convierte un crash `(service, code)` en la próxima intención. Por defecto:
471 /// `"repair service <s> crashed code <c>"`.
472 pub format_intent: fn(&str, i32) -> String,
473}
474
475impl std::fmt::Debug for RepairPolicy {
476 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
477 f.debug_struct("RepairPolicy")
478 .field("max_attempts", &self.max_attempts)
479 .field("crash_window", &self.crash_window)
480 .field("event_sock", &self.event_sock)
481 .field("format_intent", &"fn(&str, i32) -> String")
482 .finish()
483 }
484}
485
486pub fn default_crash_intent(service: &str, code: i32) -> String {
487 format!("repair service {service} crashed code {code}")
488}
489
490impl Default for RepairPolicy {
491 fn default() -> Self {
492 Self {
493 max_attempts: 3,
494 crash_window: Duration::from_secs(5),
495 event_sock: None,
496 format_intent: default_crash_intent,
497 }
498 }
499}
500
501#[cfg(test)]
502mod tests {
503 use super::*;
504 use crate::translator::MockTranslator;
505 use hammer_core::swm::{Base, Mutation};
506 use std::collections::BTreeMap;
507
508 fn baseref() -> BaseRef {
509 BaseRef { distro_version: "2026-06-06".into(), pins: BTreeMap::new() }
510 }
511
512 fn swm_config_only() -> Swm {
513 Swm {
514 swm_version: 1,
515 base: Base { distro_version: "2026-06-06".into(), pins: BTreeMap::new() },
516 mutations: vec![Mutation::ConfigEdit {
517 file: "/etc/network.conf".into(),
518 inline_diff: "- DHCP=yes\n+ STATIC=1\n".into(),
519 }],
520 signature: None,
521 }
522 }
523
524 #[test]
525 fn orchestrator_applies_config_edit_to_prefix() {
526 let d = tempfile::tempdir().unwrap();
527 let prefix = d.path().join("prefix");
528 std::fs::create_dir_all(prefix.join("etc")).unwrap();
529 std::fs::write(prefix.join("etc/network.conf"), "DHCP=yes\nMTU=1500\n").unwrap();
530
531 let t = MockTranslator::empty().with_intent("set static ip", swm_config_only());
532 let o = Orchestrator::new(
533 t,
534 baseref(),
535 ApplyTarget::Prefix { prefix: prefix.clone() },
536 CompileMode::Skip,
537 );
538 let p = o.run("set static ip").unwrap();
539 assert_eq!(p.applied.config_edit, 1);
540 assert!(p.overlay_id.is_none());
541 assert_eq!(p.checks.len(), 1);
542 assert_eq!(p.checks[0].level, CheckLevel::Pass);
543
544 let got = std::fs::read_to_string(prefix.join("etc/network.conf")).unwrap();
545 assert_eq!(got, "STATIC=1\nMTU=1500\n");
546 }
547
548 #[test]
549 fn orchestrator_rejects_base_mismatch() {
550 let mut swm = swm_config_only();
551 swm.base.distro_version = "2027-01-01".into();
552 let t = MockTranslator::empty().with_intent("x", swm);
553 let d = tempfile::tempdir().unwrap();
554 let o = Orchestrator::new(
555 t,
556 baseref(),
557 ApplyTarget::Prefix { prefix: d.path().to_path_buf() },
558 CompileMode::Skip,
559 );
560 let err = o.run("x").unwrap_err().to_string();
561 assert!(err.contains("base incompatible"), "{err}");
562 }
563
564 #[test]
565 fn orchestrator_skips_source_patch_with_warn() {
566 let swm = Swm {
567 swm_version: 1,
568 base: Base { distro_version: "2026-06-06".into(), pins: BTreeMap::new() },
569 mutations: vec![Mutation::SourcePatch {
570 repo: "git://x".into(),
571 commit: "abc".into(),
572 patch: None,
573 patch_url: None,
574 build: hammer_core::swm::SwmBuild {
575 compiler: "zig-cc".into(),
576 target: "x86_64-linux-musl".into(),
577 link: "static".into(),
578 flags: vec![],
579 },
580 target_bin: "/bin/x".into(),
581 expected_hash: None,
582 }],
583 signature: None,
584 };
585 let t = MockTranslator::empty().with_intent("compile x", swm);
586 let d = tempfile::tempdir().unwrap();
587 let o = Orchestrator::new(
588 t,
589 baseref(),
590 ApplyTarget::Prefix { prefix: d.path().to_path_buf() },
591 CompileMode::Skip,
592 );
593 let p = o.run("compile x").unwrap();
594 assert_eq!(p.skipped_source_patches, 1);
595 assert_eq!(p.checks[0].level, CheckLevel::Warn);
596 }
597
598 #[test]
599 fn orchestrator_translates_unknown_intent_errors() {
600 let t = MockTranslator::empty();
601 let d = tempfile::tempdir().unwrap();
602 let o = Orchestrator::new(
603 t,
604 baseref(),
605 ApplyTarget::Prefix { prefix: d.path().to_path_buf() },
606 CompileMode::Skip,
607 );
608 let err = o.run("haz lo que tú quieras").unwrap_err().to_string();
609 assert!(err.contains("no reconocida"), "{err}");
610 }
611}