hyprstream_core/services/namespace_builder.rs
1//! Shared "standard namespace" composition for VFS consumers.
2//!
3//! Prior to #634, `cli::shell_handlers::handle_shell_tui` and
4//! `tui::vfs::build_chat_vfs_namespace` each hand-rolled the same
5//! `Namespace::new()` + `bind_mount(...)` recipe: `/srv/model`,
6//! `/srv/registry` (+ `/worktree` alias), `/bin` (static command listing +
7//! discovered `.tcl` tool scripts), `/env` (session variables), and
8//! `/lang/tcl` (the Tcl shell mount, whose driver gets a `fork()` snapshot of
9//! the namespace taken *before* `/lang/tcl` itself is mounted so it never
10//! observes itself). The two copies had already drifted — the TUI builder
11//! was missing `/srv/registry` — so this module is now the single place that
12//! recipe is defined. Callers add only what's genuinely consumer-specific
13//! (e.g. `/lang/python`, tracked separately in #632) around a call to
14//! [`build_standard_namespace`].
15//!
16//! This is a pure assembly layer: it does not change any Subject/MAC
17//! scoping semantics of the individual mounts (`RemoteModelMount`,
18//! `RemoteRegistryMount`, `TclMount`) it wires together.
19//!
20//! Per epic #809's mount-point convention ("a mount point is a per-namespace
21//! binding decision... the server never dictates the path"), this builder
22//! does not itself choose where anything lands in the tree — every mount
23//! path below is a required field on [`StandardNamespaceConfig`] that the
24//! caller must supply. The CLI shell and TUI ChatApp callers both currently
25//! pass the same literal paths (`/srv/model`, `/srv/registry`, `/worktree`,
26//! `/bin`, `/env`, `/lang/tcl`), but that's a coincidence of current
27//! behavior, not something this module bakes in.
28
29use std::collections::HashMap;
30use std::sync::Arc;
31
32use hyprstream_rpc::Subject;
33use hyprstream_vfs::Namespace;
34
35use super::fs::{SyntheticNode, SyntheticTree};
36use super::remote_mount::RemoteModelMount;
37use super::remote_registry_mount::RemoteRegistryMount;
38use hyprstream_rpc_std::model_client::ModelClient;
39use hyprstream_rpc_std::registry_client::RegistryClient;
40
41/// Inputs that legitimately differ between the CLI shell and TUI ChatApp
42/// call sites. Everything else about the recipe is fixed by
43/// [`build_standard_namespace`].
44///
45/// The mount-point paths are required fields, not defaults this builder
46/// invents (epic #809) — every caller states its own paths explicitly, even
47/// when they happen to match another caller's.
48pub struct StandardNamespaceConfig {
49 /// Subject the `/lang/tcl` driver operates as (the caller separately
50 /// keeps its own copy of the `Subject` for VFS proxy / RPC use — this
51 /// builder only consumes it for `TclMount::spawn`).
52 pub subject: Subject,
53 /// Already-constructed model service RPC client.
54 pub model_client: ModelClient,
55 /// Registry service RPC client. When `Some`, mounts `registry_path`
56 /// (+ a `worktree_path` alias, `BindFlag::After`, same backing mount).
57 /// The CLI shell always has a registry client available; the TUI
58 /// ChatApp namespace builder currently does not obtain one and passes
59 /// `None` — this was already the pre-#634 behavior of each builder, now
60 /// made an explicit parameter rather than silently unified.
61 pub registry: Option<RegistryClient>,
62 /// Production direct-VFS PEP. Callers must construct this with the signed
63 /// audit WAL; `None` is reserved for non-production embeddings.
64 pub pep: Option<Arc<hyprstream_vfs::NamespacePep>>,
65 /// Path at which `model_client`'s 9P filesystem is mounted (caller
66 /// convention today: `/srv/model`).
67 pub model_path: String,
68 /// Path at which `registry`'s worktree filesystem is mounted, when
69 /// `registry` is `Some` (caller convention today: `/srv/registry`).
70 pub registry_path: String,
71 /// Alias path bound (`BindFlag::After`) to the same backing mount as
72 /// `registry_path`, when `registry` is `Some` (caller convention today:
73 /// `/worktree`).
74 pub worktree_path: String,
75 /// Path for the static `/bin`-style command listing + discovered `.tcl`
76 /// tool scripts (caller convention today: `/bin`).
77 pub bin_path: String,
78 /// Path for the session-variable file tree (caller convention today:
79 /// `/env`).
80 pub env_path: String,
81 /// Path at which the Tcl shell driver is mounted (caller convention
82 /// today: `/lang/tcl`).
83 pub tcl_path: String,
84}
85
86/// Compose the standard VFS namespace shared by the CLI shell and TUI
87/// ChatApp namespace builders.
88///
89/// Returns the un-wrapped `Namespace`; callers `Arc::new` it themselves
90/// (some need to add consumer-specific mounts, e.g. `/lang/python`, before
91/// sharing it).
92pub fn build_standard_namespace(cfg: StandardNamespaceConfig) -> Namespace {
93 let StandardNamespaceConfig {
94 subject,
95 model_client,
96 registry,
97 pep,
98 model_path,
99 registry_path,
100 worktree_path,
101 bin_path,
102 env_path,
103 tcl_path,
104 } = cfg;
105
106 let mut ns = Namespace::new();
107
108 // Mount the model service's 9P filesystem via RPC proxy.
109 // RemoteModelMount translates sync Mount trait calls to async ModelClient
110 // RPC requests, so `{model_path}/{model_ref}/status` etc. are served by
111 // the model service's SyntheticTree on the other end of the RPC channel.
112 let remote_model_mount = RemoteModelMount::new(model_client);
113 let _ = ns.mount(&model_path, Arc::new(remote_model_mount));
114
115 // Mount the registry service's worktree filesystem via RPC proxy, when a
116 // registry client is available. RemoteRegistryMount is the registry
117 // analogue of RemoteModelMount: it proxies 9P operations to the registry
118 // service's `WorktreeClient` (real qids, real filesystem). 2-level scope:
119 // {registry_path}/{repo_name}/{worktree_name}/<...rest...>
120 // Per #389 + #391 (Option 1, shared content model): the namespace mirrors
121 // the browser namespace's `/srv/registry` mount, both backed at the
122 // hyprstream spine. See `STANDARD_NAMESPACE_PATHS` in hyprstream-vfs for
123 // the convergence contract.
124 if let Some(registry) = registry {
125 let remote_registry_mount = RemoteRegistryMount::new(registry);
126 let registry_mount: Arc<RemoteRegistryMount> = Arc::new(remote_registry_mount);
127 let _ = ns.mount(®istry_path, registry_mount.clone());
128 // `worktree_path` is an alias for `registry_path` — same backing
129 // mount, exposed under a separate path for ergonomic worktree
130 // access. Both resolve to the same worktree content.
131 let _ = ns.bind_mount(
132 &worktree_path,
133 registry_mount,
134 hyprstream_vfs::BindFlag::After,
135 );
136 }
137
138 // /bin/ — static directory entries for listing purposes.
139 // Actual command execution goes through TclShell builtins via VFS proxy,
140 // not through these nodes. These exist so `ls /bin` shows available commands.
141 let bin_tree = {
142 let mut children = HashMap::new();
143
144 children.insert(
145 "cat".to_owned(),
146 SyntheticNode::ReadFile(Box::new(|| b"usage: cat <path> [path ...]".to_vec())),
147 );
148 children.insert(
149 "ls".to_owned(),
150 SyntheticNode::ReadFile(Box::new(|| b"usage: ls [path]".to_vec())),
151 );
152 children.insert(
153 "help".to_owned(),
154 SyntheticNode::ReadFile(Box::new(|| {
155 let mut out = String::from("VFS commands:\n");
156 out.push_str(" cat <path> read file contents\n");
157 out.push_str(" ls [path] list directory\n");
158 out.push_str(" write <path> <data> write to file\n");
159 out.push_str(" ctl <path> <cmd> control file (write+read)\n");
160 out.push_str(" json parse <str> convert JSON to Tcl dict\n");
161 out.push_str(" mount [prefix] list mount points\n");
162 out.push_str(" help this message\n");
163 out.into_bytes()
164 })),
165 );
166 children.insert(
167 "mount".to_owned(),
168 SyntheticNode::ReadFile(Box::new(|| b"usage: mount".to_vec())),
169 );
170 children.insert(
171 "write".to_owned(),
172 SyntheticNode::ReadFile(Box::new(|| b"usage: write <path> <data>".to_vec())),
173 );
174
175 SyntheticTree::new(SyntheticNode::Dir { children })
176 };
177 let _ = ns.mount(&bin_path, Arc::new(bin_tree));
178
179 // Discover .tcl tool scripts and bind them into bin_path (After = fallback).
180 let tools_dir = std::env::var("XDG_CONFIG_HOME")
181 .map(std::path::PathBuf::from)
182 .unwrap_or_else(|_| dirs::home_dir().unwrap_or_default().join(".config"))
183 .join("hyprstream/tools");
184 let tools = discover_tools(&tools_dir);
185 if !tools.is_empty() {
186 let tools_tree = SyntheticTree::new(SyntheticNode::Dir { children: tools });
187 let _ = ns.bind_mount(
188 &bin_path,
189 Arc::new(tools_tree),
190 hyprstream_vfs::BindFlag::After,
191 );
192 }
193
194 // /env/ — session variables as files (Plan9 per-process /env/).
195 let env_store: Arc<parking_lot::RwLock<HashMap<String, String>>> =
196 Arc::new(parking_lot::RwLock::new(HashMap::new()));
197
198 let env_tree = {
199 let store_list = env_store.clone();
200 let store_resolve = env_store.clone();
201
202 SyntheticTree::new(SyntheticNode::DynamicDir {
203 list: Box::new(move || {
204 store_list
205 .read()
206 .keys()
207 .map(|k| hyprstream_vfs::DirEntry {
208 name: k.clone(),
209 is_dir: false,
210 size: 0,
211 stat: None,
212 })
213 .collect()
214 }),
215 resolve: Box::new(move |name| {
216 let store = store_resolve.clone();
217 let key = name.to_owned();
218 Some(SyntheticNode::ReadFile(Box::new(move || {
219 store
220 .read()
221 .get(&key)
222 .cloned()
223 .unwrap_or_default()
224 .into_bytes()
225 })))
226 }),
227 })
228 };
229 let _ = ns.mount(&env_path, Arc::new(env_tree));
230
231 // tcl_path — the driver gets a fork() snapshot of the namespace (taken
232 // before tcl_path is mounted, so it never observes itself) for
233 // `{bin_path}/{cmd}` fallback resolution inside `{tcl_path}/eval`.
234 let mut driver_ns = ns.fork();
235 if let Some(pep) = pep.as_ref() {
236 driver_ns.set_pep(Arc::clone(pep));
237 }
238 let driver_ns = Arc::new(driver_ns);
239 let tcl_mount = Arc::new(hyprstream_workers_tcl::TclMount::spawn(subject, driver_ns));
240 let _ = ns.mount(&tcl_path, tcl_mount);
241
242 // /lang/python needs a wasm Sandbox this builder does not hold; wiring it
243 // is tracked in #632.
244
245 if let Some(pep) = pep {
246 ns.set_pep(pep);
247 }
248 ns
249}
250
251/// Discover `.tcl` tool scripts in `dir` and turn each into a `SyntheticNode`
252/// keyed by file stem, for binding into `/bin` (After = fallback).
253pub(crate) fn discover_tools(dir: &std::path::Path) -> HashMap<String, SyntheticNode> {
254 let mut tools = HashMap::new();
255 let entries = match std::fs::read_dir(dir) {
256 Ok(e) => e,
257 Err(_) => return tools,
258 };
259
260 for entry in entries.flatten() {
261 let path = entry.path();
262 if path.extension().and_then(|e| e.to_str()) != Some("tcl") {
263 continue;
264 }
265 let name = match path.file_stem().and_then(|s| s.to_str()) {
266 Some(n) => n.to_owned(),
267 None => continue,
268 };
269 // Reject names with path separators or dots (safety).
270 if name.contains('/') || name.contains("..") || name.is_empty() {
271 continue;
272 }
273
274 let script_path = path.clone();
275 tools.insert(
276 name,
277 SyntheticNode::ReadFile(Box::new(move || {
278 // Read script from disk at access time so edits take effect immediately.
279 std::fs::read_to_string(&script_path)
280 .unwrap_or_else(|e| format!("# error reading tool script: {e}"))
281 .into_bytes()
282 })),
283 );
284 }
285
286 tools
287}