Skip to main content

lean_ctx/core/workflow/
gate.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The workflow tool gate: the one decision both call paths apply — the
3//! direct call (`server/call_tool/policy.rs::guard_workflow`) and the inner
4//! tool of `ctx_call` (`server/dispatch/mod.rs`). They pass the active run and
5//! the tool name and act on the answer; neither decides anything itself.
6
7use super::store::{is_run_stale, is_withheld_sentinel};
8use super::types::WorkflowRun;
9
10/// The workflow control tool. It is never gated: it is how a run is seen,
11/// advanced and ended.
12const CONTROL_TOOL: &str = "ctx_workflow";
13
14/// The `ctx_call` wrapper. Under the stand-in for a withheld workflow the
15/// wrapper name itself passes, because on a surface that exposes only the
16/// wrapper it is the one way to reach [`CONTROL_TOOL`]. The tool it invokes
17/// is gated by its own name at both call paths, so this opens nothing else.
18const WRAPPER_TOOL: &str = "ctx_call";
19
20/// What the gate answers for one tool call under an active run.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum ToolGate {
23    /// The run is finished or stale: the caller clears it (memory and store)
24    /// and the call proceeds ungated.
25    Expired,
26    /// The call proceeds.
27    Pass,
28    /// The call is refused with this message.
29    Refuse(String),
30}
31
32/// Decide `tool` under `run`. `passthrough` is the server's list of tools a
33/// real run never blocks.
34///
35/// - The stand-in for a withheld workflow is CLOSED: only the control tool
36///   (and the wrapper that reaches it) passes. The pass-through list does not
37///   apply, and the stand-in never expires — an expiry would clear it into
38///   "no workflow", which gates nothing, and delete the stored workflow it
39///   stands for. The refusal names no workflow, state or file.
40/// - A real run: finished or stale → [`ToolGate::Expired`]; otherwise the
41///   control tool and the pass-through tools pass, and any other tool must be
42///   in the allowed list of the current state, when that state has one.
43#[must_use]
44pub fn tool_gate(run: &WorkflowRun, tool: &str, passthrough: &[&str]) -> ToolGate {
45    if is_withheld_sentinel(run) {
46        // `ctx` is the meta name; a call through it reaches the gate under
47        // the name of the tool it resolves to, so it opens nothing either.
48        return if matches!(tool, CONTROL_TOOL | WRAPPER_TOOL | "ctx") {
49            ToolGate::Pass
50        } else {
51            ToolGate::Refuse(format!(
52                "Tool '{tool}' blocked: the stored workflow is withheld by the context gateway. \
53                 Use ctx_workflow(action=\"status\") to check it again, or \
54                 ctx_workflow(action=\"stop\") to discard it."
55            ))
56        };
57    }
58    if tool == CONTROL_TOOL {
59        return ToolGate::Pass;
60    }
61    if run.current == "done" || is_run_stale(run) {
62        return ToolGate::Expired;
63    }
64    if passthrough.contains(&tool) {
65        return ToolGate::Pass;
66    }
67    let Some(allowed) = run
68        .spec
69        .state(&run.current)
70        .and_then(|state| state.allowed_tools.as_ref())
71    else {
72        return ToolGate::Pass;
73    };
74    if allowed.iter().any(|permitted| permitted == tool) {
75        return ToolGate::Pass;
76    }
77    let mut shown = allowed.clone();
78    shown.sort();
79    shown.truncate(30);
80    ToolGate::Refuse(format!(
81        "Tool '{tool}' blocked by workflow '{}' (state: {}). Allowed: {}. Use ctx_workflow(action=\"stop\") to exit.",
82        run.spec.name,
83        run.current,
84        shown.join(", ")
85    ))
86}
87
88#[cfg(test)]
89pub(crate) mod tests {
90    use super::{ToolGate, tool_gate};
91    use crate::core::context_admission::stored::lineage_support::{governed, project, scoped};
92    use crate::core::policy::runtime::TestPolicyOverride;
93    use crate::core::workflow::store::{
94        is_run_stale, is_withheld_sentinel, load_active, save_active,
95    };
96    use crate::core::workflow::types::{StateSpec, WorkflowRun, WorkflowSpec};
97
98    /// The server's list, as `server::WORKFLOW_PASSTHROUGH_TOOLS` has it.
99    const PASSTHROUGH: &[&str] = crate::server::WORKFLOW_PASSTHROUGH_TOOLS;
100
101    /// A real run whose only state allows `ctx_overview`. Shared with the
102    /// tests of the two server gates.
103    pub(crate) fn review() -> WorkflowRun {
104        let now = chrono::Utc::now();
105        WorkflowRun {
106            spec: WorkflowSpec {
107                name: "review".to_string(),
108                description: Some("Check the parser change".to_string()),
109                initial: "planning".to_string(),
110                states: vec![StateSpec {
111                    name: "planning".to_string(),
112                    description: None,
113                    allowed_tools: Some(vec!["ctx_overview".to_string()]),
114                    requires_evidence: None,
115                }],
116                transitions: Vec::new(),
117            },
118            current: "planning".to_string(),
119            started_at: now,
120            updated_at: now,
121            transitions: Vec::new(),
122            evidence: Vec::new(),
123        }
124    }
125
126    /// Where the store keeps the active workflow.
127    pub(crate) fn workflow_file() -> std::path::PathBuf {
128        crate::core::data_dir::lean_ctx_data_dir()
129            .expect("data dir")
130            .join("workflows")
131            .join("active.json")
132    }
133
134    /// The stand-in is closed and stays closed: neither the pass-through list
135    /// nor its age opens it, the stored workflow it stands for is untouched,
136    /// and it is gone once the workflow may be read again.
137    #[test]
138    fn the_withheld_stand_in_is_closed_and_never_expires() {
139        let _data = governed();
140        let _community = TestPolicyOverride::set(None);
141        let (_directory, root) = project();
142        let (_other_directory, other) = project();
143        scoped(&root, || save_active(&review())).expect("saved in its project");
144        let stored = std::fs::read(workflow_file()).expect("stored workflow");
145
146        let mut closed = scoped(&other, load_active)
147            .expect("load")
148            .expect("a withheld workflow is still a workflow");
149        assert!(is_withheld_sentinel(&closed));
150        // Older than the stale threshold: still not stale, still closed.
151        closed.updated_at = chrono::Utc::now() - chrono::Duration::minutes(45);
152        assert!(!is_run_stale(&closed));
153        for tool in [
154            "ctx_read",
155            "ctx_session",
156            "ctx_ledger",
157            "ctx_search",
158            "ctx_overview",
159        ] {
160            let ToolGate::Refuse(reason) = tool_gate(&closed, tool, PASSTHROUGH) else {
161                panic!("{tool} must be refused under the stand-in");
162            };
163            assert!(
164                reason.contains("withheld by the context gateway"),
165                "{reason}"
166            );
167            assert!(!reason.contains("review"), "no workflow name: {reason}");
168            assert!(!reason.contains("planning"), "no state name: {reason}");
169            assert!(!reason.contains("active.json"), "no file name: {reason}");
170        }
171        assert_eq!(
172            tool_gate(&closed, "ctx_workflow", PASSTHROUGH),
173            ToolGate::Pass
174        );
175        assert_eq!(tool_gate(&closed, "ctx_call", PASSTHROUGH), ToolGate::Pass);
176        assert_eq!(
177            std::fs::read(workflow_file()).expect("stored workflow"),
178            stored,
179            "the withheld workflow is byte-identical on disk"
180        );
181
182        // The authority holds again: the real workflow loads.
183        let real = scoped(&root, load_active).expect("load").expect("active");
184        assert!(!is_withheld_sentinel(&real));
185        assert_eq!(real.spec.name, "review");
186        assert_eq!(
187            tool_gate(&real, "ctx_overview", PASSTHROUGH),
188            ToolGate::Pass
189        );
190    }
191
192    /// A withheld workflow whose own run is older than the stale threshold is
193    /// kept and loads closed; once it may be read, the normal stale rule
194    /// applies to it.
195    #[test]
196    fn a_withheld_workflow_is_not_deleted_for_its_age() {
197        let _data = governed();
198        let _community = TestPolicyOverride::set(None);
199        let (_directory, root) = project();
200        let (_other_directory, other) = project();
201        let mut old = review();
202        old.updated_at = chrono::Utc::now() - chrono::Duration::minutes(45);
203        scoped(&root, || save_active(&old)).expect("saved in its project");
204        let stored = std::fs::read(workflow_file()).expect("stored workflow");
205
206        let closed = scoped(&other, load_active).expect("load").expect("closed");
207        assert!(is_withheld_sentinel(&closed));
208        assert_eq!(std::fs::read(workflow_file()).expect("kept"), stored);
209
210        assert!(scoped(&root, load_active).expect("load").is_none());
211        assert!(
212            !workflow_file().exists(),
213            "a served stale run is cleared as before"
214        );
215    }
216
217    /// Control: a real run is gated exactly as before.
218    #[test]
219    fn a_real_run_goes_stale_and_keeps_its_pass_through_tools() {
220        let _data = crate::core::data_dir::isolated_data_dir();
221        let _community = TestPolicyOverride::set(None);
222        let mut run = review();
223        assert_eq!(tool_gate(&run, "ctx_read", PASSTHROUGH), ToolGate::Pass);
224        assert_eq!(tool_gate(&run, "ctx_session", PASSTHROUGH), ToolGate::Pass);
225        assert_eq!(tool_gate(&run, "ctx_overview", PASSTHROUGH), ToolGate::Pass);
226        assert_eq!(tool_gate(&run, "ctx_workflow", PASSTHROUGH), ToolGate::Pass);
227        assert_eq!(
228            tool_gate(&run, "ctx_shell", PASSTHROUGH),
229            ToolGate::Refuse(
230                "Tool 'ctx_shell' blocked by workflow 'review' (state: planning). Allowed: ctx_overview. Use ctx_workflow(action=\"stop\") to exit."
231                    .to_string()
232            )
233        );
234
235        run.updated_at = chrono::Utc::now() - chrono::Duration::minutes(31);
236        assert!(is_run_stale(&run));
237        assert_eq!(tool_gate(&run, "ctx_shell", PASSTHROUGH), ToolGate::Expired);
238        assert_eq!(tool_gate(&run, "ctx_read", PASSTHROUGH), ToolGate::Expired);
239        assert_eq!(tool_gate(&run, "ctx_workflow", PASSTHROUGH), ToolGate::Pass);
240
241        run.updated_at = chrono::Utc::now();
242        run.current = "done".to_string();
243        assert_eq!(tool_gate(&run, "ctx_shell", PASSTHROUGH), ToolGate::Expired);
244    }
245}