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