interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-cli / src / tool_plan.rs

280 lines · 9650 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! sovereign-core #666: plan a batch of tool calls into ordered segments.
17//!
18//! Mechanism after Hermes Agent (Nous Research, MIT, commit 5480918),
19//! re-implemented; no code copied.
20//!
21//! The model often asks for several tools in one reply. Running them one after
22//! another is always safe; running them together is faster but only safe when
23//! they cannot step on each other. This module decides, without doing any I/O,
24//! which calls may run together:
25//!
26//! - **Readers share, writers exclude.** A reader (view, list, search) and a
27//! writer (write, replace, create) reserve a path. Two calls conflict when
28//! their paths overlap (one is the other or lies inside it) and at least one
29//! of them writes. Readers on the same path never conflict.
30//! - **Everything else is a barrier.** A shell command, a call that would ask
31//! the operator, a call with no path, or a tool this module does not know runs
32//! alone, so it never overlaps anything and approval prompts never interleave.
33//! - **Order is kept.** Segments run in call order. A call joins the current
34//! segment only if it conflicts with nothing in it; otherwise it starts the
35//! next one, so two conflicting calls always run in the order the model asked.
36//! - **Bounded.** At most `max_parallel` calls (8) run at once.
37//!
38//! Paths are compared lexically after making them absolute against the working
39//! directory and removing `.` and `..`. A symlink that gives one file two
40//! different spellings is not detected (known limit).
41
42use serde_json::Value;
43use std::path::{Component, Path, PathBuf};
44
45/// Most calls that run at once (Hermes uses the same bound).
46pub const MAX_PARALLEL: usize = 8;
47
48/// What one call touches.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub enum Access {
51 Read(PathBuf),
52 Write(PathBuf),
53 /// Runs alone: unknown scope, a shell, an operator prompt, any other tool.
54 Barrier,
55}
56
57/// One step of the plan: indices into the batch, in call order. More than one
58/// index means the calls run together.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct Segment {
61 pub calls: Vec<usize>,
62}
63
64/// Lexical normal form: absolute against `cwd`, no `.`, `..` folded.
65pub fn normalize(path: &str, cwd: &Path) -> PathBuf {
66 let p = Path::new(path);
67 let joined = if p.is_absolute() {
68 p.to_path_buf()
69 } else {
70 cwd.join(p)
71 };
72 let mut out = PathBuf::new();
73 for c in joined.components() {
74 match c {
75 Component::CurDir => {}
76 Component::ParentDir => {
77 out.pop();
78 }
79 other => out.push(other.as_os_str()),
80 }
81 }
82 out
83}
84
85fn path_arg(args: &Value) -> Option<&str> {
86 ["path", "Path", "directory", "dir"]
87 .iter()
88 .find_map(|k| args.get(*k).and_then(Value::as_str))
89 .filter(|p| !p.trim().is_empty())
90}
91
92/// What a call touches, from its name and arguments alone.
93pub fn access_of(name: &str, args: &Value, cwd: &Path) -> Access {
94 match name {
95 "view_file" | "list_dir" | "list_directory" => match path_arg(args) {
96 Some(p) => Access::Read(normalize(p, cwd)),
97 None => Access::Barrier,
98 },
99 // A search with no path searches the working directory.
100 "grep_search" | "search_directory" | "find_by_name" | "find_file" => {
101 Access::Read(normalize(path_arg(args).unwrap_or("."), cwd))
102 }
103 "write_to_file" | "create_file" | "replace_file_content" | "edit_file" | "create_dir" => {
104 match path_arg(args) {
105 Some(p) => Access::Write(normalize(p, cwd)),
106 None => Access::Barrier,
107 }
108 }
109 _ => Access::Barrier,
110 }
111}
112
113fn overlaps(a: &Path, b: &Path) -> bool {
114 a.starts_with(b) || b.starts_with(a)
115}
116
117fn conflicts(a: &Access, b: &Access) -> bool {
118 match (a, b) {
119 (Access::Barrier, _) | (_, Access::Barrier) => true,
120 (Access::Read(_), Access::Read(_)) => false,
121 (Access::Read(x) | Access::Write(x), Access::Read(y) | Access::Write(y)) => overlaps(x, y),
122 }
123}
124
125/// Plans the batch. Pure.
126pub fn plan(accesses: &[Access], max_parallel: usize) -> Vec<Segment> {
127 let max_parallel = max_parallel.max(1);
128 let mut segments: Vec<Segment> = Vec::new();
129 for (i, a) in accesses.iter().enumerate() {
130 let joins = match segments.last() {
131 Some(seg) => {
132 !matches!(a, Access::Barrier)
133 && seg.calls.len() < max_parallel
134 && seg.calls.iter().all(|&j| !conflicts(&accesses[j], a))
135 }
136 None => false,
137 };
138 if joins {
139 if let Some(seg) = segments.last_mut() {
140 seg.calls.push(i);
141 }
142 } else {
143 segments.push(Segment { calls: vec![i] });
144 }
145 }
146 segments
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152 use serde_json::json;
153
154 fn cwd() -> PathBuf {
155 PathBuf::from("/w")
156 }
157 fn r(p: &str) -> Access {
158 Access::Read(PathBuf::from(p))
159 }
160 fn w(p: &str) -> Access {
161 Access::Write(PathBuf::from(p))
162 }
163 fn segs(s: &[Segment]) -> Vec<Vec<usize>> {
164 s.iter().map(|x| x.calls.clone()).collect()
165 }
166
167 #[test]
168 fn readers_share_even_on_the_same_path() {
169 let p = plan(&[r("/w/a"), r("/w/a"), r("/w"), r("/w/b/c")], MAX_PARALLEL);
170 assert_eq!(segs(&p), vec![vec![0, 1, 2, 3]]);
171 }
172
173 #[test]
174 fn two_writers_on_one_path_never_share_a_segment() {
175 let p = plan(&[w("/w/a"), w("/w/a")], MAX_PARALLEL);
176 assert_eq!(segs(&p), vec![vec![0], vec![1]]);
177 }
178
179 #[test]
180 fn a_writer_excludes_readers_of_overlapping_paths_but_not_others() {
181 // Reading the folder overlaps writing a file inside it.
182 let p = plan(
183 &[
184 r("/w/src"),
185 w("/w/src/main.rs"),
186 r("/w/docs"),
187 w("/w/out.txt"),
188 ],
189 MAX_PARALLEL,
190 );
191 assert_eq!(segs(&p), vec![vec![0], vec![1, 2, 3]]);
192 // A prefix that is not a path component does not overlap.
193 assert!(!overlaps(Path::new("/w/ab"), Path::new("/w/a")));
194 }
195
196 #[test]
197 fn order_is_kept_across_conflicts() {
198 // write a, read b, read a: the read of a must come after the write.
199 let p = plan(&[w("/w/a"), r("/w/b"), r("/w/a")], MAX_PARALLEL);
200 assert_eq!(segs(&p), vec![vec![0, 1], vec![2]]);
201 }
202
203 #[test]
204 fn barriers_run_alone() {
205 let p = plan(
206 &[r("/w/a"), Access::Barrier, r("/w/b"), r("/w/c")],
207 MAX_PARALLEL,
208 );
209 assert_eq!(segs(&p), vec![vec![0], vec![1], vec![2, 3]]);
210 }
211
212 #[test]
213 fn at_most_max_parallel_run_at_once() {
214 let many: Vec<Access> = (0..20).map(|i| r(&format!("/w/{i}"))).collect();
215 let p = plan(&many, MAX_PARALLEL);
216 assert_eq!(
217 p.iter().map(|s| s.calls.len()).collect::<Vec<_>>(),
218 vec![8, 8, 4]
219 );
220 assert_eq!(p.concat_indices(), (0..20).collect::<Vec<_>>());
221 }
222
223 trait Concat {
224 fn concat_indices(&self) -> Vec<usize>;
225 }
226 impl Concat for Vec<Segment> {
227 fn concat_indices(&self) -> Vec<usize> {
228 self.iter().flat_map(|s| s.calls.clone()).collect()
229 }
230 }
231
232 #[test]
233 fn access_comes_from_the_tool_and_its_path() {
234 let c = cwd();
235 assert_eq!(
236 access_of("view_file", &json!({"path": "src/../a.rs"}), &c),
237 r("/w/a.rs")
238 );
239 assert_eq!(
240 access_of("grep_search", &json!({"query": "x"}), &c),
241 r("/w")
242 );
243 assert_eq!(
244 access_of("write_to_file", &json!({"path": "/w/./o"}), &c),
245 w("/w/o")
246 );
247 assert_eq!(
248 access_of("write_to_file", &json!({"content": "x"}), &c),
249 Access::Barrier
250 );
251 assert_eq!(
252 access_of("run_command", &json!({"command": "ls"}), &c),
253 Access::Barrier
254 );
255 assert_eq!(
256 access_of("brand_new_tool", &json!({"path": "a"}), &c),
257 Access::Barrier
258 );
259 }
260
261 /// The planner runs a call beside others as a reader only when the journal
262 /// says it is read-only, so a new alias in the dispatcher cannot become a
263 /// shared reader by mistake.
264 #[test]
265 fn readers_are_exactly_the_read_only_tools() {
266 use crate::turn_journal::{Effect, TOOL_EFFECTS};
267 let c = cwd();
268 for (name, effect) in TOOL_EFFECTS {
269 let reads = matches!(access_of(name, &json!({"path": "a"}), &c), Access::Read(_));
270 assert_eq!(reads, *effect == Effect::ReadOnly, "{name}");
271 }
272 assert_eq!(
273 access_of("list_directory", &json!({"path": "a"}), &c),
274 r("/w/a")
275 );
276 for name in ["create_file", "edit_file"] {
277 assert_eq!(access_of(name, &json!({"path": "a"}), &c), w("/w/a"));
278 }
279 }
280}