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
9/// Current time as a decimal Unix-seconds string.
10///
11/// Renamed from `now_rfc3339`, which it never was: the orchestration records
12/// it stamps (`created_at`, `generated_at`, `selected_at`) carry values like
13/// `"1753000000"`, not RFC3339. Correcting the *format* would change the shape
14/// of already-persisted records, so the name is corrected here instead — both
15/// to stop the next reader assuming RFC3339 and to keep this from being folded
16/// into `harn_clock::system_now_rfc3339` as if it were another copy.
17pub(crate) fn now_unix_seconds_text() -> String {
18    use std::time::{SystemTime, UNIX_EPOCH};
19    let ts = SystemTime::now()
20        .duration_since(UNIX_EPOCH)
21        .unwrap_or_default()
22        .as_secs();
23    format!("{ts}")
24}
25
26pub(crate) fn new_id(prefix: &str) -> String {
27    format!("{prefix}_{}", uuid::Uuid::now_v7())
28}
29
30pub(crate) fn default_run_dir() -> PathBuf {
31    let base = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
32    crate::runtime_paths::run_root(&base)
33}
34
35mod hooks;
36pub use hooks::*;
37#[cfg(test)]
38mod tests_lazy_hooks;
39
40mod pipeline_lifecycle;
41pub use pipeline_lifecycle::*;
42
43mod settlement_agent;
44pub use settlement_agent::*;
45
46mod lifecycle_receipts;
47pub use lifecycle_receipts::*;
48
49mod command_policy;
50pub use command_policy::*;
51
52mod tool_precheck;
53pub use tool_precheck::*;
54
55/// The `AutoReview` answerer for an `Ask` with nobody to ask. Mirrors the
56/// precheck seam above, but fails CLOSED: it can only lift a refusal, so an
57/// ambiguity it cannot read must never become a grant.
58mod approval_reviewer;
59pub use approval_reviewer::*;
60
61mod compaction;
62pub use compaction::*;
63
64mod repair_ledger;
65
66mod compact_lifecycle;
67pub use compact_lifecycle::*;
68
69mod compaction_receipt;
70pub use compaction_receipt::*;
71
72mod compaction_policy_registry;
73pub use compaction_policy_registry::*;
74
75pub mod agent_inbox;
76
77mod artifacts;
78pub use artifacts::*;
79
80mod assemble;
81pub use assemble::*;
82
83mod handoffs;
84pub use handoffs::*;
85
86mod friction;
87pub use friction::*;
88
89mod crystallize;
90pub use crystallize::*;
91
92mod release_fixture;
93pub use release_fixture::*;
94
95mod replay_oracle;
96pub use replay_oracle::*;
97
98mod replay_bench;
99pub use replay_bench::*;
100
101mod policy;
102#[cfg(test)]
103pub(crate) use policy::swap_execution_policy_stack;
104pub use policy::*;
105
106mod ambient_scope;
107pub use ambient_scope::blocking::run_blocking_with_ambient;
108pub(crate) use ambient_scope::{
109    scope_agent_session, scope_ambient, scope_ambient_transaction, scope_approval_policy,
110    scope_autonomy_policy, scope_command_policy, scope_dynamic_permissions, scope_inline_subtask,
111    scope_run_event_sink, scope_spawned_source_dir, AmbientExecutionScope,
112};
113pub use ambient_scope::{
114    scope_execution_policy, scope_fresh_run_runtime, scope_fresh_tracing_runtime,
115    scope_fresh_trigger_registry, scope_llm_runtime_overrides,
116    scope_llm_runtime_overrides_with_provider_endpoints,
117};
118
119mod stage_options;
120pub use stage_options::*;
121
122mod workflow;
123pub use workflow::*;
124
125mod workflow_bundle;
126pub use workflow_bundle::*;
127
128mod workflow_patch;
129pub use workflow_patch::*;
130
131mod safe_function_tools;
132pub use safe_function_tools::*;
133
134mod nested_invocation;
135pub use nested_invocation::*;
136
137#[cfg(test)]
138mod workflow_test_fixtures;
139
140mod records;
141pub use records::*;
142
143mod run_review;
144pub use run_review::*;
145
146mod run_view_fixtures;
147pub use run_view_fixtures::*;
148
149mod training_example;
150pub use training_example::*;
151
152mod context_eval;
153pub use context_eval::*;
154
155mod skill_gate;
156pub use skill_gate::*;
157
158mod merge_captain_audit;
159pub use merge_captain_audit::*;
160
161mod merge_captain_driver;
162pub use merge_captain_driver::*;
163
164mod merge_captain_ladder;
165pub use merge_captain_ladder::*;
166
167mod merge_captain_iteration;
168pub use merge_captain_iteration::*;
169
170pub mod playground;
171
172thread_local! {
173    static CURRENT_MUTATION_SESSION: RefCell<Option<MutationSessionRecord>> = const { RefCell::new(None) };
174    /// Workflow-level skill context, installed by `workflow_execute` so
175    /// every per-node agent loop constructed inside `execute_stage_node`
176    /// can pick up the same `skills:` / `skill_match:` registry without
177    /// threading a new parameter through every helper. Cleared on
178    /// workflow exit (success or error) by `WorkflowSkillContextGuard`.
179    static CURRENT_WORKFLOW_SKILL_CONTEXT: RefCell<Option<WorkflowSkillContext>> = const { RefCell::new(None) };
180}
181
182/// Skill wiring threaded from `workflow_execute` into the per-stage
183/// agent loops via thread-local context. The workflow runner pins itself
184/// to one task via `LocalSet`, so every stage observes the same context
185/// without cross-task synchronization.
186#[derive(Clone, Default)]
187pub struct WorkflowSkillContext {
188    pub registry: Option<VmValue>,
189    pub match_config: Option<VmValue>,
190}
191
192pub fn install_workflow_skill_context(context: Option<WorkflowSkillContext>) {
193    CURRENT_WORKFLOW_SKILL_CONTEXT.with(|slot| {
194        *slot.borrow_mut() = context;
195    });
196}
197
198pub fn current_workflow_skill_context() -> Option<WorkflowSkillContext> {
199    CURRENT_WORKFLOW_SKILL_CONTEXT.with(|slot| slot.borrow().clone())
200}
201
202/// RAII guard that clears the workflow skill context on drop. Paired
203/// with `install_workflow_skill_context` at the top of `execute_workflow`
204/// so the context never leaks past a workflow's scope.
205pub struct WorkflowSkillContextGuard;
206
207impl Drop for WorkflowSkillContextGuard {
208    fn drop(&mut self) {
209        install_workflow_skill_context(None);
210    }
211}
212
213#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
214#[serde(default)]
215pub struct MutationSessionRecord {
216    pub session_id: String,
217    pub parent_session_id: Option<String>,
218    pub run_id: Option<String>,
219    pub worker_id: Option<String>,
220    pub execution_kind: Option<String>,
221    pub mutation_scope: String,
222    /// Declarative per-tool approval policy for this session. When `None`,
223    /// no policy-driven approval is requested; the session update stream
224    /// remains the only host-observable surface for tool dispatch.
225    pub approval_policy: Option<ToolApprovalPolicy>,
226}
227
228impl MutationSessionRecord {
229    pub fn normalize(mut self) -> Self {
230        if self.session_id.is_empty() {
231            self.session_id = new_id("session");
232        }
233        if self.mutation_scope.is_empty() {
234            self.mutation_scope = "read_only".to_string();
235        }
236        self
237    }
238}
239
240pub fn install_current_mutation_session(session: Option<MutationSessionRecord>) {
241    CURRENT_MUTATION_SESSION.with(|slot| {
242        *slot.borrow_mut() = session.map(MutationSessionRecord::normalize);
243    });
244}
245
246pub fn current_mutation_session() -> Option<MutationSessionRecord> {
247    CURRENT_MUTATION_SESSION.with(|slot| slot.borrow().clone())
248}
249
250/// Per-task ambient-scope swap of the current mutation session. See
251/// `orchestration::ambient_scope`: the mutation session attributes audit
252/// records, `run_id`, approval policy, and secret-access scope to the running
253/// task, so a worker holding it across an `.await` must keep its OWN copy rather
254/// than read whatever a cooperatively-scheduled fan-out sibling left behind. The
255/// helper is `pub(crate)` — only the ambient combinator moves whole sessions;
256/// ordinary code uses `install_current_mutation_session`/`current_mutation_session`.
257pub(crate) fn swap_mutation_session(
258    next: Option<MutationSessionRecord>,
259) -> Option<MutationSessionRecord> {
260    CURRENT_MUTATION_SESSION.with(|slot| std::mem::replace(&mut *slot.borrow_mut(), next))
261}
262
263/// How much of the offending payload a deserialization error quotes back.
264const PAYLOAD_SNIPPET_MAX_BYTES: usize = 600;
265
266pub(crate) fn parse_json_payload<T: for<'de> Deserialize<'de>>(
267    json: serde_json::Value,
268    label: &str,
269) -> Result<T, VmError> {
270    let payload = json.to_string();
271    let mut deserializer = serde_json::Deserializer::from_str(&payload);
272    let mut tracker = serde_path_to_error::Track::new();
273    let path_deserializer = serde_path_to_error::Deserializer::new(&mut deserializer, &mut tracker);
274    T::deserialize(path_deserializer).map_err(|error| {
275        let snippet = crate::text::truncate_end_bytes(&payload, PAYLOAD_SNIPPET_MAX_BYTES);
276        VmError::Runtime(format!(
277            "{label} parse error at {}: {} | payload={}",
278            tracker.path(),
279            error,
280            snippet
281        ))
282    })
283}
284
285pub(crate) fn parse_json_value<T: for<'de> Deserialize<'de>>(
286    value: &VmValue,
287) -> Result<T, VmError> {
288    parse_json_payload(vm_value_to_json(value), "orchestration")
289}
290
291#[cfg(test)]
292mod tests;
293
294#[cfg(test)]
295mod policy_restriction_tests;
296
297#[cfg(test)]
298mod typed_options_parity;