memstead_base/binding_run.rs
1//! Binding-run resolution — turning a declared binding into the resolved
2//! form a run works from (sources with their bases and change strategies,
3//! the process mem a binding writes into), with the typed refusals a
4//! malformed declaration earns.
5//!
6//! Kernel, not loop: the health surface resolves the process mem for its
7//! projection axis and the read surface resolves a binding run before it
8//! reports findings, so the resolution lives beside the binding store it
9//! reads. Moved here from `ingest::resolve` on 2026-09-10; the loop and
10//! every consumer path reach it through `ingest::resolve`.
11
12use std::path::{Path, PathBuf};
13
14use crate::binding::{Binding, BuildMode, medium_capabilities};
15pub use crate::pipeline::Source;
16use crate::pipeline::{IngestTrigger, MediumType};
17
18/// A binding source resolved to what the run needs: a **primary** inline
19/// source (the territory to read and write back), or a read-only
20/// **reference** mem supplying cross-mem context.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum ResolvedSource {
23 /// An inline primary source (both halves: where it lives / which part).
24 Primary(Source),
25 /// A read-only reference mem (cross-mem context, never written).
26 Reference {
27 /// The reference mem's id.
28 mem: String,
29 },
30}
31
32/// A v2 binding unpacked into the runtime shape the orchestration stages
33/// (cursor, brief, selection) consume.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct ResolvedIngest {
36 /// The run's identity — the canonical binding id `<mem>/<stem>`, the
37 /// string every downstream key (sync_state, selection cache, brief header)
38 /// derives from.
39 pub name: String,
40 /// The build mode — discovery / one-shot (`refinement` is deleted).
41 /// Defaults to discovery when the binding declares no `build` block.
42 pub mode: BuildMode,
43 /// Loop / manual / on-event.
44 pub trigger: IngestTrigger,
45 /// How many artifacts a single run processes.
46 pub batch_size: u32,
47 /// Paths excluded for this binding's runs, on top of source scope.
48 pub deny_paths: Vec<String>,
49 /// The binding id verbatim (`"<mem>/<name>"`).
50 pub projection_ref: String,
51 /// The binding's owning mem (the part before the `/`).
52 pub projection_mem: String,
53 /// The binding's name (the part after the `/`).
54 pub projection_name: String,
55 /// The binding's intent — prose for the agent (the brief's "about
56 /// the source" block).
57 pub intent: Option<String>,
58 /// The resolved sources, in declaration order: inline primaries first,
59 /// then reference mems.
60 pub sources: Vec<ResolvedSource>,
61 /// The single mem this binding writes into.
62 pub destination_mem: String,
63 /// Free-form binding rules (e.g. one-shot lens `routing`).
64 pub rules: Option<serde_json::Value>,
65 /// Free-form post-run actions (e.g. one-shot `archive_source`).
66 pub post_actions: Option<serde_json::Value>,
67}
68
69/// Why a binding could not be resolved. With inline sources the only
70/// structural failures left are identity-level: an unknown binding id, or a
71/// malformed one.
72#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
73pub enum ResolveError {
74 /// No binding with the given id in the store.
75 #[error("binding '{name}' not found; available: {}", fmt_list(available))]
76 BindingNotFound {
77 /// The requested binding id.
78 name: String,
79 /// The binding ids that do exist.
80 available: Vec<String>,
81 },
82 /// The binding id is not the required `"<mem>/<name>"`.
83 #[error("malformed binding id '{projection}'; expected \"<mem>/<name>\"")]
84 MalformedProjectionRef {
85 /// The binding whose id is malformed.
86 ingest: String,
87 /// The malformed value.
88 projection: String,
89 },
90 /// A source's scope carries a pattern its medium's namespace cannot
91 /// express, so the declared selection reaches nothing. Refused when the
92 /// binding is resolved for a run, not only when it is edited: a scope
93 /// nothing interprets is decorative wherever it came from, and
94 /// hand-editing the record is a route the CLI's own refusal text
95 /// recommends.
96 #[error("binding '{binding}' cannot run: {reason}")]
97 UninterpretableScope {
98 /// The binding whose scope cannot be interpreted.
99 binding: String,
100 /// What is wrong and how to fix it.
101 reason: String,
102 },
103}
104
105impl ResolveError {
106 /// The wire code: one per state, whichever command resolves the binding.
107 pub fn code(&self) -> &'static str {
108 match self {
109 ResolveError::BindingNotFound { .. } => "PROJECTION_NOT_FOUND",
110 ResolveError::MalformedProjectionRef { .. } => "PROJECTION_INVALID_NAME",
111 ResolveError::UninterpretableScope { .. } => "PROJECTION_SCOPE_UNINTERPRETABLE",
112 }
113 }
114
115 /// The recovery payload, with the binding the call named.
116 pub fn details(&self, binding: &str) -> serde_json::Value {
117 match self {
118 ResolveError::BindingNotFound { available, .. } => serde_json::json!({
119 "binding": binding,
120 "available": available,
121 }),
122 ResolveError::UninterpretableScope { reason, .. } => serde_json::json!({
123 "binding": binding,
124 "reason": reason,
125 }),
126 ResolveError::MalformedProjectionRef { .. } => {
127 serde_json::json!({ "binding": binding })
128 }
129 }
130 }
131}
132
133/// Render a name list for an error message: `a, b, c` or `(none)`.
134fn fmt_list(names: &[String]) -> String {
135 if names.is_empty() {
136 "(none)".to_string()
137 } else {
138 names.join(", ")
139 }
140}
141
142/// Unpack a **v2 binding** (by canonical id) into the runtime
143/// [`ResolvedIngest`] shape the orchestration stages (cursor, brief,
144/// selection) consume.
145///
146/// The binding *is* the whole declaration: its inline sources become the
147/// primary [`ResolvedSource`]s verbatim, its `operations.build` supplies the
148/// run mode / trigger / batch / post-actions, and `deny_paths` / `intent` /
149/// `rules` come straight off the record. `binding_id` is the canonical
150/// `<mem>/<stem>`, which becomes the resolved ingest's `name` and
151/// `projection_ref` — every downstream key (sync_state, selection cache,
152/// brief header) is derived from it. A malformed `binding_id` is
153/// [`ResolveError::MalformedProjectionRef`]. Pure — no I/O.
154pub fn resolve_binding_run(
155 binding_id: &str,
156 binding: &Binding,
157) -> Result<ResolvedIngest, ResolveError> {
158 let (mem, name) = crate::pipeline_store::parse_binding_id(binding_id).ok_or_else(|| {
159 ResolveError::MalformedProjectionRef {
160 ingest: binding_id.to_string(),
161 projection: binding_id.to_string(),
162 }
163 })?;
164 let mem = mem.to_string();
165 let name = name.to_string();
166
167 // A scope rule nothing interprets is refused HERE, on the run path, and
168 // not only on the edit paths that call `validate_binding`. Scaffolding the
169 // right shape only protects bindings this engine wrote: every graph
170 // binding scaffolded before the entity vocabulary existed carries the path
171 // glob `**/*`, and a hand-edited record is a route the CLI's own
172 // name-collision refusal points people at. Left unguarded, such a binding
173 // ran clean over an S(D) of zero and recorded a `#verified` baseline for a
174 // measurement that never happened.
175 for source in &binding.sources {
176 match source.medium_type {
177 crate::pipeline::MediumType::Graph => {
178 for rule in &source.scope {
179 if crate::source_scope::parse_entity_selector(&rule.path).is_none() {
180 return Err(ResolveError::UninterpretableScope {
181 binding: binding_id.to_string(),
182 reason: format!(
183 "source '{}' is a graph medium, but its scope pattern '{}' is \
184 not an entity selector — a graph source selects entities, not \
185 paths. Write '*' for the whole mem, 'type:<entity_type>', or \
186 'id:<glob>'",
187 source.name, rule.path
188 ),
189 });
190 }
191 }
192 }
193 // A web source has no scope vocabulary at all, so any rule on it
194 // is uninterpretable — the same class, and gating the run-path
195 // refusal on graph alone is how it survived the declaration gate
196 // being graph-only.
197 crate::pipeline::MediumType::Web => {
198 if let Some(rule) = source.scope.first() {
199 return Err(ResolveError::UninterpretableScope {
200 binding: binding_id.to_string(),
201 reason: format!(
202 "source '{}' is a web medium, which has no scope vocabulary — its \
203 scope pattern '{}' would select nothing while looking like \
204 selection. Remove the scope rule",
205 source.name, rule.path
206 ),
207 });
208 }
209 }
210 crate::pipeline::MediumType::Codebase
211 | crate::pipeline::MediumType::Filesystem
212 | crate::pipeline::MediumType::Git => {}
213 }
214 }
215
216 let mut sources = Vec::with_capacity(binding.sources.len() + binding.reference_mems.len());
217 for source in &binding.sources {
218 sources.push(ResolvedSource::Primary(source.clone()));
219 }
220 for reference_mem in &binding.reference_mems {
221 sources.push(ResolvedSource::Reference {
222 mem: reference_mem.clone(),
223 });
224 }
225
226 // The build op supplies mode / trigger / batch / post-actions. An absent
227 // build block (a not-yet-built obligation) resolves to sane defaults — the
228 // build-path refusal is enforced at the brief entry point, not here, so
229 // read-only callers (status) keep working.
230 let build = binding.operations.build.as_ref();
231 let mode = build.map_or(BuildMode::Discovery, |b| b.mode);
232 let trigger = build.map_or(IngestTrigger::Loop, |b| b.trigger);
233 let batch_size = build.map_or(20, |b| b.batch_size);
234 let post_actions = build.and_then(|b| b.post_actions.clone());
235
236 Ok(ResolvedIngest {
237 name: binding_id.to_string(),
238 mode,
239 trigger,
240 batch_size,
241 deny_paths: binding.deny_paths.clone(),
242 projection_ref: binding_id.to_string(),
243 projection_mem: mem,
244 projection_name: name,
245 intent: binding.intent.clone(),
246 sources,
247 destination_mem: binding.destination_mem.clone(),
248 rules: binding.rules.clone(),
249 post_actions,
250 })
251}
252
253/// A primary source's resolved change-detection strategy — how "what
254/// changed since the last synced pass" is computed for it.
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub enum ChangeStrategy {
257 /// No change detection — the source is re-roamed whole (inert signal).
258 None,
259 /// Git-commit diff between the baseline commit and current `HEAD`.
260 Git,
261 /// Filesystem `(mtime, size)` stat-map digest + diff.
262 Mtime,
263 /// Graph snapshot diff (the source mem's snapshot token).
264 Graph,
265}
266
267/// Resolve a primary source's [`ChangeStrategy`]. A graph-typed source
268/// always uses [`Graph`] (its signal is the source mem's snapshot token,
269/// which the engine provides). Otherwise the source's declared strategy wins
270/// (`none`/`git`/`mtime`); `auto` — the default when unset, and any
271/// unrecognized value — probes for a git work tree over the source pointer
272/// (resolved against `workspace_root`): present → [`Git`], absent →
273/// [`Mtime`].
274///
275/// [`Graph`]: ChangeStrategy::Graph
276/// [`Git`]: ChangeStrategy::Git
277/// [`Mtime`]: ChangeStrategy::Mtime
278pub fn resolve_change_strategy(source: &Source, workspace_root: &Path) -> ChangeStrategy {
279 if source.medium_type == MediumType::Graph {
280 return ChangeStrategy::Graph;
281 }
282 // A detection-less medium (per the capability matrix: `web`)
283 // has no change signal: it resolves to the visible NoSignal (`none`), never
284 // a fabricated `mtime`/`git` token. This mirrors the graph special case
285 // above — the medium type overrides any declared value.
286 if !medium_capabilities(source.medium_type).change_signal {
287 return ChangeStrategy::None;
288 }
289 match source.change_detection.as_deref() {
290 Some("none") => ChangeStrategy::None,
291 // A declared strategy is NOT second-guessed here: this resolver maps
292 // the declaration, and an author who writes `git` means git. Whether
293 // the checkout can actually deliver that signal is a question about
294 // this pass, not about the binding — a `git archive` or Docker `COPY`
295 // has the sources and no `.git`, and the honest place to say so is the
296 // freshness row, which reports what the run observed. See
297 // `FacetFreshness::change_detectable`.
298 Some("git") => ChangeStrategy::Git,
299 Some("mtime") => ChangeStrategy::Mtime,
300 // `auto`, unset, or any unrecognized value: probe the filesystem.
301 _ => {
302 if find_git_root(&source_base_path(source, workspace_root)).is_some() {
303 ChangeStrategy::Git
304 } else {
305 ChangeStrategy::Mtime
306 }
307 }
308 }
309}
310
311/// The on-disk base directory a path-based primary source resolves to: the
312/// source pointer joined onto the workspace root (`Path::join` yields the
313/// pointer verbatim when it is absolute), or the workspace root itself for
314/// an empty pointer. Only meaningful for path-namespaced mediums
315/// (codebase / filesystem / git) — a graph pointer is a mem id and a web
316/// pointer a URL.
317pub fn source_base_path(source: &Source, workspace_root: &Path) -> PathBuf {
318 if source.pointer.is_empty() {
319 workspace_root.to_path_buf()
320 } else {
321 workspace_root.join(&source.pointer)
322 }
323}
324
325/// Walk up from `start` looking for a `.git` entry (a directory *or* a file
326/// — a submodule/worktree gitlink is a file), returning the directory that
327/// contains it (the git work-tree root), or `None`. Bounded to 64 ancestors.
328/// Pure filesystem, no subprocess — deterministic for tests.
329pub fn find_git_root(start: &Path) -> Option<PathBuf> {
330 let mut dir = start.to_path_buf();
331 for _ in 0..64 {
332 if dir.join(".git").exists() {
333 return Some(dir);
334 }
335 match dir.parent() {
336 Some(parent) => dir = parent.to_path_buf(),
337 None => break,
338 }
339 }
340 None
341}
342
343#[cfg(test)]
344mod tests {
345 use super::*;
346 use crate::binding::{BINDING_VERSION, BuildOperation, Operations};
347 use crate::pipeline::{PatternEntry, PatternMode};
348
349 fn source(
350 name: &str,
351 medium_type: MediumType,
352 pointer: &str,
353 declared: Option<&str>,
354 ) -> Source {
355 Source {
356 name: name.to_string(),
357 medium_type,
358 pointer: pointer.to_string(),
359 change_detection: declared.map(str::to_string),
360 scope: vec![],
361 engagement: None,
362 preparation: None,
363 }
364 }
365
366 fn allow(path: &str) -> PatternEntry {
367 PatternEntry {
368 path: path.to_string(),
369 mode: PatternMode::Allow,
370 }
371 }
372
373 fn v2_binding(dest: &str, sources: Vec<Source>) -> Binding {
374 Binding {
375 version: BINDING_VERSION,
376 intent: Some("prose".to_string()),
377 sources,
378 reference_mems: vec![],
379 destination_mem: dest.to_string(),
380 deny_paths: vec![],
381 coverage_semantics: None,
382 rules: None,
383 prune: None,
384 operations: Operations {
385 build: Some(BuildOperation {
386 mode: BuildMode::Discovery,
387 trigger: IngestTrigger::Loop,
388 batch_size: 20,
389 post_actions: None,
390 }),
391 sync: None,
392 verify: None,
393 },
394 }
395 }
396
397 /// `resolve_binding_run` produces the runtime shape from a v2 binding
398 /// without any join: the id becomes `name`/`projection_ref`, `build.mode`
399 /// maps to the run mode, deny_paths / trigger / batch / post_actions come
400 /// off the build op, and each inline source carries over verbatim;
401 /// reference mems follow the primaries.
402 #[test]
403 fn resolve_binding_run_produces_runtime_shape() {
404 let mut swift_source = source("source-tree", MediumType::Codebase, "../app", None);
405 swift_source.scope = vec![allow("../app/**/*.swift")];
406 let mut binding = v2_binding("app", vec![swift_source.clone()]);
407 binding.intent = Some("swift".to_string());
408 binding.reference_mems = vec!["engine".to_string()];
409 binding.deny_paths = vec!["**/VISION.md".to_string()];
410 binding.operations.build.as_mut().unwrap().post_actions =
411 Some(serde_json::json!({ "archive_source": true }));
412
413 let r = resolve_binding_run("app/graph", &binding).unwrap();
414 assert_eq!(r.name, "app/graph");
415 assert_eq!(r.projection_ref, "app/graph");
416 assert_eq!(r.projection_mem, "app");
417 assert_eq!(r.projection_name, "graph");
418 assert_eq!(r.mode, BuildMode::Discovery);
419 assert_eq!(r.batch_size, 20);
420 assert_eq!(r.deny_paths, ["**/VISION.md"]);
421 assert_eq!(r.destination_mem, "app");
422 assert_eq!(r.intent.as_deref(), Some("swift"));
423 assert_eq!(
424 r.post_actions,
425 Some(serde_json::json!({ "archive_source": true }))
426 );
427 assert_eq!(r.sources.len(), 2);
428 assert_eq!(r.sources[0], ResolvedSource::Primary(swift_source));
429 assert_eq!(
430 r.sources[1],
431 ResolvedSource::Reference {
432 mem: "engine".to_string()
433 }
434 );
435 }
436
437 /// A one-shot binding maps to the one-shot run mode.
438 #[test]
439 fn resolve_binding_run_maps_one_shot() {
440 let mut binding = v2_binding("m", vec![]);
441 let build = binding.operations.build.as_mut().unwrap();
442 build.mode = BuildMode::OneShot;
443 build.trigger = IngestTrigger::Manual;
444 build.batch_size = 5;
445 let r = resolve_binding_run("m/lens", &binding).unwrap();
446 assert_eq!(r.mode, BuildMode::OneShot);
447 assert_eq!(r.batch_size, 5);
448 }
449
450 /// A malformed binding id (no `/`) is a located error.
451 #[test]
452 fn resolve_binding_run_malformed_id_errors() {
453 let binding = v2_binding("m", vec![]);
454 let err = resolve_binding_run("noslash", &binding).unwrap_err();
455 assert!(matches!(err, ResolveError::MalformedProjectionRef { .. }));
456 }
457
458 /// The convention-derived process mem: the binding id itself for a
459 /// single-component destination (unchanged), the last separator
460 /// hyphenated for a nested one, so a git-branch workspace can hold
461 /// the derived name beside the destination's own branch.
462 #[test]
463 fn derived_process_mem_name_keeps_flat_ids_and_hyphenates_nested_ones() {
464 assert_eq!(derived_process_mem_name("engine/graph"), "engine/graph");
465 assert_eq!(
466 derived_process_mem_name("library/sample/notes"),
467 "library/sample-notes"
468 );
469 assert_eq!(
470 derived_process_mem_name("planning/plan-first-sample/notes"),
471 "planning/plan-first-sample-notes"
472 );
473 assert_eq!(derived_process_mem_name("a/b/c/d"), "a/b/c-d");
474 // A malformed id passes through: nothing to derive from.
475 assert_eq!(derived_process_mem_name("noslash"), "noslash");
476 assert_eq!(derived_process_mem_name(""), "");
477 }
478
479 /// An absent build block resolves to sane defaults (read-only callers
480 /// keep working; the mutating-op refusal is enforced at the brief entry).
481 #[test]
482 fn absent_build_resolves_to_defaults() {
483 let mut binding = v2_binding("m", vec![]);
484 binding.operations.build = None;
485 let r = resolve_binding_run("m/p", &binding).unwrap();
486 assert_eq!(r.mode, BuildMode::Discovery);
487 assert_eq!(r.trigger, IngestTrigger::Loop);
488 assert_eq!(r.batch_size, 20);
489 assert_eq!(r.post_actions, None);
490 }
491
492 /// A graph-typed source always resolves to the graph strategy,
493 /// regardless of any declared value.
494 #[test]
495 fn graph_source_always_uses_graph_strategy() {
496 let root = Path::new("/nonexistent");
497 assert_eq!(
498 resolve_change_strategy(&source("f", MediumType::Graph, "", None), root),
499 ChangeStrategy::Graph
500 );
501 // Even a declared override does not change a graph source.
502 assert_eq!(
503 resolve_change_strategy(&source("f", MediumType::Graph, "", Some("mtime")), root),
504 ChangeStrategy::Graph
505 );
506 }
507
508 /// A `web` source (detection-less per the capability matrix) resolves to
509 /// the visible NoSignal `None` regardless of any declared value —
510 /// `status` renders `signal: none`, never a fabricated `mtime`/`git`
511 /// token.
512 #[test]
513 fn web_source_resolves_to_none_signal() {
514 let root = Path::new("/nonexistent");
515 assert_eq!(
516 resolve_change_strategy(
517 &source("w", MediumType::Web, "https://example.com", None),
518 root
519 ),
520 ChangeStrategy::None
521 );
522 // Even a declared override does not fabricate a signal for web.
523 assert_eq!(
524 resolve_change_strategy(
525 &source("w", MediumType::Web, "https://example.com", Some("mtime")),
526 root
527 ),
528 ChangeStrategy::None
529 );
530 }
531
532 /// A declared `none`/`git`/`mtime` wins for a non-graph source.
533 #[test]
534 fn declared_strategy_wins_for_non_graph() {
535 let root = Path::new("/nonexistent");
536 for (declared, expected) in [
537 ("none", ChangeStrategy::None),
538 ("git", ChangeStrategy::Git),
539 ("mtime", ChangeStrategy::Mtime),
540 ] {
541 assert_eq!(
542 resolve_change_strategy(
543 &source("f", MediumType::Codebase, "x", Some(declared)),
544 root
545 ),
546 expected,
547 "declared '{declared}'"
548 );
549 }
550 }
551
552 /// `auto` (unset, or an unrecognized value) probes the filesystem: a
553 /// pointer under a git work tree → git, otherwise → mtime.
554 #[test]
555 fn auto_probes_for_a_git_work_tree() {
556 let git = tempfile::tempdir().unwrap();
557 std::fs::create_dir(git.path().join(".git")).unwrap();
558 std::fs::create_dir(git.path().join("sub")).unwrap();
559 let plain = tempfile::tempdir().unwrap();
560
561 // Unset → auto → probe. Pointer resolves under the git root → Git.
562 assert_eq!(
563 resolve_change_strategy(&source("f", MediumType::Codebase, "sub", None), git.path()),
564 ChangeStrategy::Git
565 );
566 // An unrecognized declared value also falls through to the probe.
567 assert_eq!(
568 resolve_change_strategy(
569 &source("f", MediumType::Codebase, "sub", Some("weird")),
570 git.path()
571 ),
572 ChangeStrategy::Git
573 );
574 // No git work tree over the pointer → Mtime.
575 assert_eq!(
576 resolve_change_strategy(
577 &source("f", MediumType::Filesystem, ".", None),
578 plain.path()
579 ),
580 ChangeStrategy::Mtime
581 );
582 }
583
584 /// `find_git_root` returns the containing directory of a `.git` entry,
585 /// walking up from a nested start, and `None` when there is none.
586 #[test]
587 fn find_git_root_walks_up() {
588 let root = tempfile::tempdir().unwrap();
589 std::fs::create_dir(root.path().join(".git")).unwrap();
590 let nested = root.path().join("a/b/c");
591 std::fs::create_dir_all(&nested).unwrap();
592
593 assert_eq!(
594 find_git_root(&nested).as_deref(),
595 Some(root.path()),
596 "walks up to the work-tree root"
597 );
598
599 let plain = tempfile::tempdir().unwrap();
600 assert_eq!(find_git_root(plain.path()), None, "no .git anywhere above");
601 }
602}
603
604/// How a destination mem's process mem was resolved: by explicit declaration (`MemConfig.process_mem` on the
605/// destination — wins where present) or by the binding-name
606/// convention (the fallback, byte-identical to the pre-declaration
607/// behaviour). One resolution function for every consumer — the
608/// brief renderer and the open-questions health axis read this and
609/// nothing else, so pairing can never drift between surfaces.
610#[derive(Debug, Clone, PartialEq, Eq)]
611pub struct ProcessMemResolution {
612 /// The resolved process-mem name.
613 pub mem: String,
614 /// Whether that mem is actually mounted.
615 pub mounted: bool,
616 /// True when the name came from the destination's declaration
617 /// rather than the naming convention. A declared-but-unmounted
618 /// resolution is a typed finding for the caller to surface —
619 /// never a silent fallback to derivation.
620 pub declared: bool,
621}
622
623/// The schema family every process mem pins: a declared process mem
624/// must carry an `ingest@*` pin, whatever its version.
625pub const PROCESS_MEM_SCHEMA_NAME: &str = "ingest";
626
627/// The convention-derived process mem name for a binding, the fallback
628/// where the destination declares none. For a single-component
629/// destination it is the binding id itself (`engine/graph`), unchanged
630/// since the convention was set. For a nested destination
631/// (`library/sample`) the id's last separator becomes a hyphen
632/// (`library/sample-notes`): a sibling of the destination in the
633/// same namespace directory, because git keeps refs as files in
634/// directories and cannot hold `library/sample/notes` beside the
635/// branch `library/sample`. The one derivation every consumer uses
636/// (the brief renderer, the open-questions health axis), so the two
637/// cannot pair differently. A malformed id passes through unchanged.
638pub fn derived_process_mem_name(binding_id: &str) -> String {
639 match crate::pipeline_store::parse_binding_id(binding_id) {
640 Some((mem, stem)) if mem.contains('/') => format!("{mem}-{stem}"),
641 _ => binding_id.to_string(),
642 }
643}
644
645/// Resolve the process mem for `destination_mem`. `derived_name` is
646/// the convention-derived candidate ([`derived_process_mem_name`] of
647/// the binding id); pass it even when a declaration might exist — the
648/// declaration wins, the derivation remains the fallback.
649pub fn resolve_process_mem(
650 engine: &crate::Engine,
651 destination_mem: &str,
652 derived_name: &str,
653) -> ProcessMemResolution {
654 let mounted_names = engine.mem_names();
655 if let Some(declared) = engine
656 .mem_config_for(destination_mem)
657 .and_then(|c| c.process_mem.clone())
658 {
659 let mounted = mounted_names.iter().any(|m| *m == declared);
660 return ProcessMemResolution {
661 mem: declared,
662 mounted,
663 declared: true,
664 };
665 }
666 let mounted = mounted_names.contains(&derived_name);
667 ProcessMemResolution {
668 mem: derived_name.to_string(),
669 mounted,
670 declared: false,
671 }
672}