Skip to main content

harn_vm/orchestration/
mod.rs

1use std::path::PathBuf;
2use std::{cell::RefCell, thread_local};
3
4use serde::{Deserialize, Serialize};
5
6use crate::llm::vm_value_to_json;
7use crate::value::{VmError, VmValue};
8
9pub(crate) fn now_rfc3339() -> String {
10    use std::time::{SystemTime, UNIX_EPOCH};
11    let ts = SystemTime::now()
12        .duration_since(UNIX_EPOCH)
13        .unwrap_or_default()
14        .as_secs();
15    format!("{ts}")
16}
17
18pub(crate) fn new_id(prefix: &str) -> String {
19    format!("{prefix}_{}", uuid::Uuid::now_v7())
20}
21
22pub(crate) fn default_run_dir() -> PathBuf {
23    let base = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
24    crate::runtime_paths::run_root(&base)
25}
26
27mod hooks;
28pub use hooks::*;
29
30mod compaction;
31pub use compaction::*;
32
33mod artifacts;
34pub use artifacts::*;
35
36mod assemble;
37pub use assemble::*;
38
39mod handoffs;
40pub use handoffs::*;
41
42mod friction;
43pub use friction::*;
44
45mod policy;
46pub use policy::*;
47
48mod workflow;
49pub use workflow::*;
50
51mod records;
52pub use records::*;
53
54thread_local! {
55    static CURRENT_MUTATION_SESSION: RefCell<Option<MutationSessionRecord>> = const { RefCell::new(None) };
56    /// Workflow-level skill context, installed by `workflow_execute` so
57    /// every per-node agent loop constructed inside `execute_stage_node`
58    /// can pick up the same `skills:` / `skill_match:` registry without
59    /// threading a new parameter through every helper. Cleared on
60    /// workflow exit (success or error) by `WorkflowSkillContextGuard`.
61    static CURRENT_WORKFLOW_SKILL_CONTEXT: RefCell<Option<WorkflowSkillContext>> = const { RefCell::new(None) };
62}
63
64/// Skill wiring threaded from `workflow_execute` into the per-stage
65/// agent loops via thread-local context. `VmValue` wraps `Rc` and is
66/// not `Send`, so we store it in a thread-local rather than a mutex —
67/// the workflow runner pins itself to one task via `LocalSet`, so
68/// every stage observes the same context.
69#[derive(Clone, Default)]
70pub struct WorkflowSkillContext {
71    pub registry: Option<VmValue>,
72    pub match_config: Option<VmValue>,
73}
74
75pub fn install_workflow_skill_context(context: Option<WorkflowSkillContext>) {
76    CURRENT_WORKFLOW_SKILL_CONTEXT.with(|slot| {
77        *slot.borrow_mut() = context;
78    });
79}
80
81pub fn current_workflow_skill_context() -> Option<WorkflowSkillContext> {
82    CURRENT_WORKFLOW_SKILL_CONTEXT.with(|slot| slot.borrow().clone())
83}
84
85/// RAII guard that clears the workflow skill context on drop. Paired
86/// with `install_workflow_skill_context` at the top of `execute_workflow`
87/// so the context never leaks past a workflow's scope.
88pub struct WorkflowSkillContextGuard;
89
90impl Drop for WorkflowSkillContextGuard {
91    fn drop(&mut self) {
92        install_workflow_skill_context(None);
93    }
94}
95
96#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
97#[serde(default)]
98pub struct MutationSessionRecord {
99    pub session_id: String,
100    pub parent_session_id: Option<String>,
101    pub run_id: Option<String>,
102    pub worker_id: Option<String>,
103    pub execution_kind: Option<String>,
104    pub mutation_scope: String,
105    /// Declarative per-tool approval policy for this session. When `None`,
106    /// no policy-driven approval is requested; the session update stream
107    /// remains the only host-observable surface for tool dispatch.
108    pub approval_policy: Option<ToolApprovalPolicy>,
109}
110
111impl MutationSessionRecord {
112    pub fn normalize(mut self) -> Self {
113        if self.session_id.is_empty() {
114            self.session_id = new_id("session");
115        }
116        if self.mutation_scope.is_empty() {
117            self.mutation_scope = "read_only".to_string();
118        }
119        self
120    }
121}
122
123pub fn install_current_mutation_session(session: Option<MutationSessionRecord>) {
124    CURRENT_MUTATION_SESSION.with(|slot| {
125        *slot.borrow_mut() = session.map(MutationSessionRecord::normalize);
126    });
127}
128
129pub fn current_mutation_session() -> Option<MutationSessionRecord> {
130    CURRENT_MUTATION_SESSION.with(|slot| slot.borrow().clone())
131}
132pub(crate) fn parse_json_payload<T: for<'de> Deserialize<'de>>(
133    json: serde_json::Value,
134    label: &str,
135) -> Result<T, VmError> {
136    let payload = json.to_string();
137    let mut deserializer = serde_json::Deserializer::from_str(&payload);
138    let mut tracker = serde_path_to_error::Track::new();
139    let path_deserializer = serde_path_to_error::Deserializer::new(&mut deserializer, &mut tracker);
140    T::deserialize(path_deserializer).map_err(|error| {
141        let snippet = if payload.len() > 600 {
142            format!("{}...", &payload[..600])
143        } else {
144            payload.clone()
145        };
146        VmError::Runtime(format!(
147            "{label} parse error at {}: {} | payload={}",
148            tracker.path(),
149            error,
150            snippet
151        ))
152    })
153}
154
155pub(crate) fn parse_json_value<T: for<'de> Deserialize<'de>>(
156    value: &VmValue,
157) -> Result<T, VmError> {
158    parse_json_payload(vm_value_to_json(value), "orchestration")
159}
160
161#[cfg(test)]
162mod tests;