Skip to main content

memstead_base/
pipeline.rs

1//! Pipeline primitives — the inline [`Source`] of a binding and its parts.
2//!
3//! A pipeline is **one record**: the versioned [`crate::binding::Binding`]
4//! (v2) under `projections/<mem>/<name>.json`, which alone fully defines the
5//! obligation — intent, inline sources, reference mems, destination, deny
6//! paths, coverage semantics, and operations. [`Source`] is the record's
7//! inline source entry; *medium* and *facet* survive only as the names of a
8//! source description's two halves (where it lives / which part of it),
9//! never as standalone records.
10//!
11//! - The **medium half** of a [`Source`]: `type` / `pointer` /
12//!   `change_detection` — a typed reference to a body of information.
13//! - The **facet half**: `scope` (allow/deny patterns), an optional
14//!   `engagement` contract, and an optional deterministic `preparation` step.
15//!
16//! These are operator-edited configs. The loader's job is load + validate +
17//! expose read-only; nothing here fetches, transforms, or schedules.
18
19use serde::{Deserialize, Serialize};
20
21/// What kind of surface a [`Source`] references (its `type` field, lowercase
22/// on the wire). `pdf` (and other non-text mediums) join this enum with
23/// their follow-up plans.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "lowercase")]
26pub enum MediumType {
27    /// A source tree of code.
28    Codebase,
29    /// A directory of files (non-code).
30    Filesystem,
31    /// Another mem's graph (reachable as the reserved id `graph` for "home").
32    Graph,
33    /// A git history.
34    Git,
35    /// Web sources.
36    Web,
37}
38
39/// One inline **source** of a v2 [`crate::binding::Binding`] — the full
40/// description of a body of information the pipeline reads, carrying both
41/// halves the retired standalone records used to split: the *medium* half
42/// (where it lives — `type` / `pointer` / `change_detection`) and the
43/// *facet* half (which part of it — `scope` / `engagement` / `preparation`).
44///
45/// `name` is required and unique within the record: it keys per-source
46/// sync/verify state (`<mem>/<binding>/<source>#synced`) exactly as facet
47/// names did before the consolidation.
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49pub struct Source {
50    /// Stable name — keys per-source sync/verify state.
51    pub name: String,
52    /// What kind of surface this source references (the medium half).
53    #[serde(rename = "type")]
54    pub medium_type: MediumType,
55    /// Where the body of information lives — a path, URL, or mem id,
56    /// interpreted per [`Self::medium_type`]. Opaque to this layer.
57    pub pointer: String,
58    /// Optional declared change-detection strategy — `none` / `git` /
59    /// `mtime` / `auto`. Unset (the common case) means `auto`: the ingest
60    /// resolver probes for a git work tree over [`Self::pointer`] and picks
61    /// `git` or `mtime`. A graph-typed source ignores this and always uses
62    /// the graph snapshot signal.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub change_detection: Option<String>,
65    /// Allow/deny selection over the source (the facet half). A source with
66    /// **no allow patterns is *unscoped*** — a typed refusal at run time (no
67    /// strategy diffs or enumerates the whole territory; the brief reports
68    /// it as unmonitored), not "everything". A source that truly wants
69    /// everything writes `**/*`.
70    #[serde(default)]
71    pub scope: Vec<PatternEntry>,
72    /// Engagement contract — verbs, tools, terminology, discipline.
73    /// Free-form because the shape differs by medium type; the engine does
74    /// not interpret it.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub engagement: Option<serde_json::Value>,
77    /// Optional deterministic preparation — the identifier of a
78    /// preparation registered in the engine's [`crate::preparation`]
79    /// registry (today `entity-load-bearing` on graph sources and
80    /// `dated-entries` on path-shaped ones). At most one per source.
81    /// The edit/validate paths refuse an identifier the registry does not
82    /// know ([`crate::binding::CapabilityError::PreparationUnsupported`]);
83    /// a record that acquired an unknown one by hand is accepted at rest and
84    /// reported unsupported at run time (the brief prints "Skipping." and
85    /// exits 0) — both paths apply the one registry rule.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub preparation: Option<String>,
88}
89
90/// Whether a [`PatternEntry`] admits or excludes the matched paths.
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
92#[serde(rename_all = "lowercase")]
93pub enum PatternMode {
94    /// Paths matching this pattern are in reach.
95    Allow,
96    /// Paths matching this pattern are excluded.
97    Deny,
98}
99
100/// One allow/deny glob in a [`Source`]'s scope over its medium.
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
102pub struct PatternEntry {
103    /// Glob pattern, interpreted relative to the source's pointer.
104    pub path: String,
105    /// Whether the pattern admits or excludes.
106    pub mode: PatternMode,
107}
108
109/// What sets a binding's operation running — the `trigger` of a
110/// [`crate::binding::BuildOperation`] / `SyncOperation` / `VerifyOperation`.
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
112#[serde(rename_all = "kebab-case")]
113pub enum IngestTrigger {
114    /// Repeated runs (the ingest skill loops it).
115    Loop,
116    /// Operator-initiated.
117    Manual,
118    /// Fired by an external event.
119    OnEvent,
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    /// A v2 inline source round-trips: the medium half (`type` lowercase on
127    /// the wire, unset `change_detection` omitted) and the facet half
128    /// (`scope` present, unset `engagement`/`preparation` omitted) in one
129    /// record — the plan's wire example shape.
130    #[test]
131    fn source_round_trips_with_both_halves() {
132        let s = Source {
133            name: "source-tree".to_string(),
134            medium_type: MediumType::Codebase,
135            pointer: "../public".to_string(),
136            change_detection: None,
137            scope: vec![
138                PatternEntry {
139                    path: "../public/**/*.rs".to_string(),
140                    mode: PatternMode::Allow,
141                },
142                PatternEntry {
143                    path: "../public/target/**".to_string(),
144                    mode: PatternMode::Deny,
145                },
146            ],
147            engagement: None,
148            preparation: None,
149        };
150        let json = serde_json::to_string(&s).unwrap();
151        assert!(json.contains(r#""type":"codebase""#), "got {json}");
152        assert!(json.contains(r#""mode":"deny""#), "got {json}");
153        for absent in ["change_detection", "engagement", "preparation"] {
154            assert!(!json.contains(absent), "unset {absent} omitted: {json}");
155        }
156        let back: Source = serde_json::from_str(&json).unwrap();
157        assert_eq!(back, s);
158    }
159
160    /// A source declaring the optional slots round-trips them.
161    #[test]
162    fn source_optional_slots_round_trip_when_set() {
163        let s = Source {
164            name: "manual-pages".to_string(),
165            medium_type: MediumType::Filesystem,
166            pointer: "../docs".to_string(),
167            change_detection: Some("mtime".to_string()),
168            scope: Vec::new(),
169            engagement: Some(serde_json::json!({ "readVerb": "Read PDF" })),
170            preparation: Some("pdf-to-markdown".to_string()),
171        };
172        let json = serde_json::to_string(&s).unwrap();
173        assert!(json.contains(r#""change_detection":"mtime""#), "got {json}");
174        let back: Source = serde_json::from_str(&json).unwrap();
175        assert_eq!(back, s);
176    }
177
178    /// `IngestTrigger`'s kebab-case variants serialise as the doc names
179    /// (`on-event`) — the wire forms a binding's operation `trigger` uses.
180    #[test]
181    fn ingest_trigger_uses_kebab_wire_forms() {
182        let on_event = serde_json::to_string(&IngestTrigger::OnEvent).unwrap();
183        assert_eq!(on_event, r#""on-event""#);
184        let loop_ = serde_json::to_string(&IngestTrigger::Loop).unwrap();
185        assert_eq!(loop_, r#""loop""#);
186    }
187}