Skip to main content

memstead_base/
pipeline.rs

1//! Pipeline primitives — the inline [`Source`] and the migrate-local legacy
2//! shapes.
3//!
4//! A pipeline is **one record**: the versioned [`crate::binding::Binding`]
5//! (v2) under `projections/<mem>/<name>.json`, which alone fully defines the
6//! obligation — intent, inline sources, reference mems, destination, deny
7//! paths, coverage semantics, and operations. [`Source`] is the record's
8//! inline source entry; *medium* and *facet* survive only as the names of a
9//! source description's two halves (where it lives / which part of it),
10//! never as standalone records.
11//!
12//! - The **medium half** of a [`Source`]: `type` / `pointer` /
13//!   `change_detection` — a typed reference to a body of information.
14//! - The **facet half**: `scope` (allow/deny patterns), an optional
15//!   `engagement` contract, and an optional deterministic `preparation` step.
16//!
17//! These are operator-edited configs. The loader's job is load + validate +
18//! expose read-only; nothing here fetches, transforms, or schedules.
19//!
20//! [`Medium`] / [`Facet`] / [`Projection`] are **migrate-local** legacy
21//! shapes: parsed only by `memstead projection migrate`'s conversion legs
22//! (gen-1 root-folder, gen-2 four-primitive, v1 three-file). No live path
23//! constructs or reads them, same as [`crate::pipeline_store::LegacyIngest`].
24
25use serde::{Deserialize, Serialize};
26
27/// What kind of surface a [`Medium`] references. The string forms match the
28/// `type` field of the legacy `scopes/<mem>/<name>.json` records, so
29/// the migration shim maps them without translation. `pdf` (and other
30/// non-text mediums) join this enum with their follow-up plans.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(rename_all = "lowercase")]
33pub enum MediumType {
34    /// A source tree of code.
35    Codebase,
36    /// A directory of files (non-code).
37    Filesystem,
38    /// Another mem's graph (reachable as the reserved id `graph` for "home").
39    Graph,
40    /// A git history.
41    Git,
42    /// Web sources.
43    Web,
44}
45
46/// One inline **source** of a v2 [`crate::binding::Binding`] — the full
47/// description of a body of information the pipeline reads, carrying both
48/// halves the retired standalone records used to split: the *medium* half
49/// (where it lives — `type` / `pointer` / `change_detection`) and the
50/// *facet* half (which part of it — `scope` / `engagement` / `preparation`).
51///
52/// `name` is required and unique within the record: it keys per-source
53/// sync/verify state (`<mem>/<binding>/<source>#synced`) exactly as facet
54/// names did before the consolidation, which is why migration preserves
55/// facet names as source names byte-verbatim.
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct Source {
58    /// Stable name — keys per-source sync/verify state.
59    pub name: String,
60    /// What kind of surface this source references (the medium half).
61    #[serde(rename = "type")]
62    pub medium_type: MediumType,
63    /// Where the body of information lives — a path, URL, or mem id,
64    /// interpreted per [`Self::medium_type`]. Opaque to this layer.
65    pub pointer: String,
66    /// Optional declared change-detection strategy — `none` / `git` /
67    /// `mtime` / `auto`. Unset (the common case) means `auto`: the ingest
68    /// resolver probes for a git work tree over [`Self::pointer`] and picks
69    /// `git` or `mtime`. A graph-typed source ignores this and always uses
70    /// the graph snapshot signal.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub change_detection: Option<String>,
73    /// Allow/deny selection over the source (the facet half). A source with
74    /// **no allow patterns is *unscoped*** — a typed refusal at run time (no
75    /// strategy diffs or enumerates the whole territory; the brief reports
76    /// it as unmonitored), not "everything". A source that truly wants
77    /// everything writes `**/*`.
78    #[serde(default)]
79    pub scope: Vec<PatternEntry>,
80    /// Engagement contract — verbs, tools, terminology, discipline.
81    /// Free-form because the shape differs by medium type; the engine does
82    /// not interpret it.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub engagement: Option<serde_json::Value>,
85    /// Optional deterministic preparation step (string identifier, e.g.
86    /// `pdf-to-markdown`). Unset for every text source today. A source that
87    /// names a preparation the engine has no implementation for is refused
88    /// at validation time — no silent skip, no crash.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub preparation: Option<String>,
91}
92
93/// Legacy **Medium** (migrate-local) — the standalone territory record of the
94/// retired three-file store. Parsed only by the migration legs; the live
95/// model carries this content inline as a [`Source`]'s medium half.
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
97pub struct Medium {
98    /// Stable name — facets and projections reference a medium by this.
99    pub name: String,
100    /// What kind of surface this is.
101    #[serde(rename = "type")]
102    pub medium_type: MediumType,
103    /// Where the body of information lives — a path, URL, or mem id,
104    /// interpreted per [`Self::medium_type`]. Opaque to this layer.
105    pub pointer: String,
106    /// An optional declared change-detection strategy for sources reading
107    /// this medium — `none` / `git` / `mtime` / `auto`. Unset (the common
108    /// case) means `auto`: the ingest resolver probes for a git work tree
109    /// over [`Self::pointer`] and picks `git` or `mtime`. A graph-typed
110    /// medium ignores this and always uses the graph snapshot signal.
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub change_detection: Option<String>,
113}
114
115/// Whether a [`PatternEntry`] admits or excludes the matched paths.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "lowercase")]
118pub enum PatternMode {
119    /// Paths matching this pattern are in reach.
120    Allow,
121    /// Paths matching this pattern are excluded.
122    Deny,
123}
124
125/// One allow/deny glob in a [`Facet`]'s selection over its medium. Mirrors the
126/// `{ path, mode }` entries of the legacy scope `tree`.
127#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128pub struct PatternEntry {
129    /// Glob pattern, interpreted relative to the referenced medium's pointer.
130    pub path: String,
131    /// Whether the pattern admits or excludes.
132    pub mode: PatternMode,
133}
134
135/// Legacy **Facet** (migrate-local) — the standalone engagement record of
136/// the retired three-file store. Parsed only by the migration legs; the live
137/// model carries this content inline as a [`Source`]'s facet half.
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139pub struct Facet {
140    /// Stable name — projections reference a facet by this.
141    pub name: String,
142    /// The [`Medium`] (by name) this facet is a perspective on. A facet
143    /// always references exactly one medium.
144    pub medium: String,
145    /// Allow/deny selection over the referenced medium. A facet with **no
146    /// allow patterns is *unscoped*** — a typed refusal at run time (no
147    /// strategy diffs or enumerates the whole medium; the brief reports it as
148    /// unmonitored), not "whole medium". A facet that truly wants everything
149    /// writes `**/*`.
150    #[serde(default)]
151    pub scope: Vec<PatternEntry>,
152    /// Engagement contract — verbs, tools, terminology, discipline. Free-form
153    /// because the shape differs by medium type and by source/destination
154    /// side; the engine does not interpret it.
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub engagement: Option<serde_json::Value>,
157    /// Optional deterministic preparation step (string identifier, e.g.
158    /// `pdf-to-markdown`). Unset for every text medium today. A facet that
159    /// names a preparation the engine has no implementation for is accepted at
160    /// rest but reported unsupported at run time — no silent skip, no crash.
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub preparation: Option<String>,
163}
164
165/// Legacy **Projection** (migrate-local) — the gen-2 obligation record that
166/// referenced facets by name. Parsed only by the migration legs; the live
167/// obligation is the v2 [`crate::binding::Binding`] with inline sources.
168#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
169pub struct Projection {
170    /// What the projection is trying to accomplish — prose for the agent.
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub intent: Option<String>,
173    /// Source facets (by name) the projection consumes.
174    #[serde(default)]
175    pub source_facets: Vec<String>,
176    /// Read-only reference mems that supply cross-mem context.
177    #[serde(default)]
178    pub reference_mems: Vec<String>,
179    /// The mem this projection writes into.
180    pub destination_mem: String,
181    /// Free-form projection rules (e.g. a one-shot lens `routing` string).
182    /// Opaque to the engine — consumed only by the one-shot brief renderer.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub rules: Option<serde_json::Value>,
185}
186
187/// What sets a binding's operation running — the `trigger` of a
188/// [`crate::binding::BuildOperation`] / `SyncOperation` / `VerifyOperation`.
189#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
190#[serde(rename_all = "kebab-case")]
191pub enum IngestTrigger {
192    /// Repeated runs (the ingest skill loops it).
193    Loop,
194    /// Operator-initiated.
195    Manual,
196    /// Fired by an external event.
197    OnEvent,
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    /// A v2 inline source round-trips: the medium half (`type` lowercase on
205    /// the wire, unset `change_detection` omitted) and the facet half
206    /// (`scope` present, unset `engagement`/`preparation` omitted) in one
207    /// record — the plan's wire example shape.
208    #[test]
209    fn source_round_trips_with_both_halves() {
210        let s = Source {
211            name: "source-tree".to_string(),
212            medium_type: MediumType::Codebase,
213            pointer: "../public".to_string(),
214            change_detection: None,
215            scope: vec![
216                PatternEntry {
217                    path: "../public/**/*.rs".to_string(),
218                    mode: PatternMode::Allow,
219                },
220                PatternEntry {
221                    path: "../public/target/**".to_string(),
222                    mode: PatternMode::Deny,
223                },
224            ],
225            engagement: None,
226            preparation: None,
227        };
228        let json = serde_json::to_string(&s).unwrap();
229        assert!(json.contains(r#""type":"codebase""#), "got {json}");
230        assert!(json.contains(r#""mode":"deny""#), "got {json}");
231        for absent in ["change_detection", "engagement", "preparation"] {
232            assert!(!json.contains(absent), "unset {absent} omitted: {json}");
233        }
234        let back: Source = serde_json::from_str(&json).unwrap();
235        assert_eq!(back, s);
236    }
237
238    /// A source declaring the optional slots round-trips them.
239    #[test]
240    fn source_optional_slots_round_trip_when_set() {
241        let s = Source {
242            name: "manual-pages".to_string(),
243            medium_type: MediumType::Filesystem,
244            pointer: "../docs".to_string(),
245            change_detection: Some("mtime".to_string()),
246            scope: Vec::new(),
247            engagement: Some(serde_json::json!({ "readVerb": "Read PDF" })),
248            preparation: Some("pdf-to-markdown".to_string()),
249        };
250        let json = serde_json::to_string(&s).unwrap();
251        assert!(json.contains(r#""change_detection":"mtime""#), "got {json}");
252        let back: Source = serde_json::from_str(&json).unwrap();
253        assert_eq!(back, s);
254    }
255
256    /// A medium round-trips and its `type` serialises to the lowercase form
257    /// the legacy scope JSON used.
258    #[test]
259    fn medium_round_trips_with_lowercase_type() {
260        let m = Medium {
261            name: "source-tree".to_string(),
262            medium_type: MediumType::Codebase,
263            pointer: "../macos".to_string(),
264            change_detection: None,
265        };
266        let json = serde_json::to_string(&m).unwrap();
267        assert!(
268            !json.contains("change_detection"),
269            "unset change_detection is omitted on the wire: {json}"
270        );
271        assert!(json.contains(r#""type":"codebase""#), "got {json}");
272        let back: Medium = serde_json::from_str(&json).unwrap();
273        assert_eq!(back, m);
274    }
275
276    /// A medium declaring a `change_detection` strategy round-trips with the
277    /// value present; the field is the optional slot the ingest resolver
278    /// reads to pick a source's change-detection strategy.
279    #[test]
280    fn medium_change_detection_round_trips_when_set() {
281        let m = Medium {
282            name: "manuals".to_string(),
283            medium_type: MediumType::Filesystem,
284            pointer: "../docs".to_string(),
285            change_detection: Some("mtime".to_string()),
286        };
287        let json = serde_json::to_string(&m).unwrap();
288        assert!(json.contains(r#""change_detection":"mtime""#), "got {json}");
289        let back: Medium = serde_json::from_str(&json).unwrap();
290        assert_eq!(back.change_detection.as_deref(), Some("mtime"));
291        assert_eq!(back, m);
292    }
293
294    /// A source facet with allow/deny scope and no preparation round-trips,
295    /// and the unset `preparation`/`engagement` keys are omitted on the wire.
296    #[test]
297    fn facet_round_trips_and_omits_unset_optional_fields() {
298        let f = Facet {
299            name: "source-files".to_string(),
300            medium: "source-tree".to_string(),
301            scope: vec![
302                PatternEntry {
303                    path: "../macos/**/*.swift".to_string(),
304                    mode: PatternMode::Allow,
305                },
306                PatternEntry {
307                    path: "../macos/specs/**".to_string(),
308                    mode: PatternMode::Deny,
309                },
310            ],
311            engagement: None,
312            preparation: None,
313        };
314        let json = serde_json::to_string(&f).unwrap();
315        assert!(
316            !json.contains("preparation"),
317            "unset preparation omitted: {json}"
318        );
319        assert!(
320            !json.contains("engagement"),
321            "unset engagement omitted: {json}"
322        );
323        assert!(json.contains(r#""mode":"deny""#), "got {json}");
324        let back: Facet = serde_json::from_str(&json).unwrap();
325        assert_eq!(back, f);
326        assert_eq!(back.preparation, None);
327    }
328
329    /// A facet declaring a preparation identifier round-trips with the value
330    /// present — the slot is reserved even though no implementation exists.
331    #[test]
332    fn facet_preparation_slot_round_trips_when_set() {
333        let f = Facet {
334            name: "manual-pages".to_string(),
335            medium: "manuals".to_string(),
336            scope: Vec::new(),
337            engagement: Some(serde_json::json!({ "readVerb": "Read PDF" })),
338            preparation: Some("pdf-to-markdown".to_string()),
339        };
340        let json = serde_json::to_string(&f).unwrap();
341        let back: Facet = serde_json::from_str(&json).unwrap();
342        assert_eq!(back.preparation.as_deref(), Some("pdf-to-markdown"));
343        assert_eq!(back, f);
344    }
345
346    /// A projection maps source facets + reference mems to one destination.
347    #[test]
348    fn projection_round_trips() {
349        let p = Projection {
350            intent: Some("Swift macOS app source.".to_string()),
351            source_facets: vec!["source-files".to_string()],
352            reference_mems: vec!["engine".to_string()],
353            destination_mem: "macos".to_string(),
354            rules: None,
355        };
356        let json = serde_json::to_string(&p).unwrap();
357        let back: Projection = serde_json::from_str(&json).unwrap();
358        assert_eq!(back, p);
359        assert_eq!(back.destination_mem, "macos");
360    }
361
362    /// `IngestTrigger`'s kebab-case variants serialise as the doc names
363    /// (`on-event`) — the wire forms a binding's operation `trigger` uses.
364    #[test]
365    fn ingest_trigger_uses_kebab_wire_forms() {
366        let on_event = serde_json::to_string(&IngestTrigger::OnEvent).unwrap();
367        assert_eq!(on_event, r#""on-event""#);
368        let loop_ = serde_json::to_string(&IngestTrigger::Loop).unwrap();
369        assert_eq!(loop_, r#""loop""#);
370    }
371}