memstead_schema/manifest.rs
1//! Schema manifest (`schema.yaml`) — the outer envelope declaring a schema
2//! package: name, version, type list, relationship vocabulary, community
3//! defaults, and LLM-facing documentation.
4
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
9#[serde(deny_unknown_fields)]
10pub struct SchemaManifest {
11 pub name: String,
12 /// Semver string — parsed into `semver::Version` by the loader.
13 pub version: String,
14 pub description: String,
15 pub when_to_use: String,
16 #[serde(default)]
17 pub system_message: Option<String>,
18 pub types: Vec<String>,
19 pub relationships: RelationshipVocabulary,
20 pub community: CommunityConfig,
21 /// Schema-generic writing guidance — `avoid` and `goal` prose that
22 /// applies to every mem pinned to this schema. The plugin layer
23 /// concatenates these with per-mem `writeGuidance.avoid_additions`
24 /// / `goal_additions` (an opaque pass-through on the engine side —
25 /// see `MemConfig::write_guidance`'s contract).
26 #[serde(default, skip_serializing_if = "Option::is_none")]
27 pub default_writing_guidance: Option<DefaultWritingGuidance>,
28 /// Outbound cross-mem relationship vocabulary, per target schema
29 /// domain. Each entry names a target schema (bare name — never a
30 /// version; eligibility is name-based) and lists rel-types that may
31 /// cross the boundary in that direction. Absent or `[]` means the
32 /// schema declares no outbound cross-mem edges. Source-ownership
33 /// only — third-party bridge schemas are not modelled; each
34 /// direction is owned by exactly one schema.
35 #[serde(default, skip_serializing_if = "Vec::is_empty")]
36 pub cross_mem_relationships: Vec<CrossMemRelationshipEntry>,
37 /// Schema-level pointer naming the rel-type that body wiki-links
38 /// `[[target]]` should auto-emit as engine-synthesised relations.
39 /// `None` (default) means the schema is opt-out of alias synthesis
40 /// — unbacked body wiki-links continue to refuse with
41 /// `WIKILINK_WITHOUT_RELATION`. When set, the named rel-type must
42 /// be declared in `relationships.definitions` or schema load
43 /// fails with `SchemaLoadError::AliasTargetRelTypeNotDeclared`.
44 #[serde(default, skip_serializing_if = "Option::is_none")]
45 pub alias_target_rel_type: Option<String>,
46}
47
48/// One outbound cross-mem declaration — a target schema domain
49/// (named, never versioned) and the rel-types admitted in that
50/// direction.
51///
52/// `target_types` strings within each definition live in the target
53/// schema's namespace by construction — the source schema's loader
54/// accepts them as opaque since the target schema may not be present
55/// at source-schema load time.
56#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
57#[serde(deny_unknown_fields)]
58pub struct CrossMemRelationshipEntry {
59 /// Bare name of the target schema — the domain identity. A version
60 /// suffix (`software@1.0.0`) or range (`software@^1.0`) is rejected
61 /// at schema load: cross-mem eligibility is name-based, so the
62 /// declaration is satisfied by a target mem pinning *any* version
63 /// of the named schema.
64 pub to_schema: String,
65 pub definitions: Vec<RelationshipDef>,
66}
67
68/// Schema-level writing-guidance defaults. Both fields are optional so a
69/// schema can ship `avoid` without a `goal` (or vice versa). The engine
70/// surfaces them via `build_schema_payload` at the top level of the
71/// schema-payload JSON; resolution (concatenation with mem additions)
72/// lives in the plugin layer.
73#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
74#[serde(deny_unknown_fields)]
75pub struct DefaultWritingGuidance {
76 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub avoid: Option<String>,
78 #[serde(default, skip_serializing_if = "Option::is_none")]
79 pub goal: Option<String>,
80}
81
82#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
83#[serde(deny_unknown_fields)]
84pub struct RelationshipVocabulary {
85 pub mode: RelationshipMode,
86 pub definitions: Vec<RelationshipDef>,
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
90#[serde(rename_all = "lowercase")]
91pub enum RelationshipMode {
92 Strict,
93 Open,
94}
95
96#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
97#[serde(deny_unknown_fields)]
98pub struct RelationshipDef {
99 pub name: String,
100 pub description: String,
101 #[serde(default)]
102 pub when_to_use: Option<String>,
103 pub default_weight: f32,
104 /// Per-edge description posture for edges of this rel-type:
105 /// `forbidden` (default) rejects any trailing description text;
106 /// `optional` accepts edges with or without a description;
107 /// `required` rejects edges without a description. The schema
108 /// author opts a catch-all rel-type (e.g. `OTHER`) into
109 /// `required` to force per-edge documentation; most rel-types
110 /// keep the default `forbidden` posture so the rel-type's name
111 /// is the edge's documentation.
112 #[serde(default)]
113 pub per_edge_description: PerEdgeDescription,
114 /// When true, the engine rejects writes that would close a cycle in the
115 /// subgraph restricted to edges of this relationship type. Defaults to
116 /// false so existing user schemas stay opt-in. Semantically meaningless
117 /// on the `_default` sentinel (never a real edge's rel_type).
118 #[serde(default)]
119 pub acyclic: bool,
120 /// Schema-declared types whose entities may be the source of this
121 /// edge. Empty (default) means shape-free — any source type admitted.
122 /// The loader validates every entry against the schema's declared
123 /// types list; unknown names raise `SchemaLoadError::UndeclaredType`.
124 /// At write time, `memstead_relate` rejects shape violations with
125 /// `INVALID_REL_SHAPE`.
126 #[serde(default, skip_serializing_if = "Vec::is_empty")]
127 pub source_types: Vec<String>,
128 /// Same as `source_types` but for the target side. Empty = shape-free.
129 #[serde(default, skip_serializing_if = "Vec::is_empty")]
130 pub target_types: Vec<String>,
131 /// Per-source cardinality hint, parsed and stored on the
132 /// relationship definition. Declarative only — the engine does not
133 /// currently enforce it or warn when a relate pushes the source's
134 /// outgoing count for this rel_type outside the declared range.
135 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub cardinality_per_source: Option<Cardinality>,
137 /// Manual-authoring posture for this rel-type. `allow` (default)
138 /// admits explicit `memstead_relate` calls. `warn` lands the relation
139 /// with a `RELATION_MANUAL_AUTHORING_NOT_RECOMMENDED` warning.
140 /// `forbidden` refuses explicit-author calls with the typed
141 /// `RELATION_MANUAL_AUTHORING_FORBIDDEN` code. The body-link →
142 /// relation alias machinery (`memstead_update` / `memstead_create`'s
143 /// wiki-link parser) is NOT gated — schema-emitted relations like
144 /// REFERENCES synthesise unchanged.
145 #[serde(default)]
146 pub manual_authoring: ManualAuthoring,
147}
148
149/// Per-edge description posture declared on a `RelationshipDef`.
150///
151/// `Forbidden` (the default) rejects any trailing description text on
152/// edges of this rel-type. `Optional` accepts both shapes. `Required`
153/// rejects edges without a description — the schema author opts a
154/// catch-all rel-type into this so every edge carries its own
155/// rationale.
156#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
157#[serde(rename_all = "lowercase")]
158pub enum PerEdgeDescription {
159 #[default]
160 Forbidden,
161 Optional,
162 Required,
163}
164
165/// Manual-authoring posture declared per `RelationshipDef`.
166///
167/// `Allow` (default) is the no-op posture for every rel-type a user
168/// or agent may author explicitly via `memstead_relate`. `Warn` lands the
169/// relation but surfaces a warning so the audit trail records the
170/// drift. `Forbidden` refuses with a typed code — used for rel-types
171/// the engine emits via the body-link → relation alias machinery
172/// (e.g. REFERENCES), where explicit authoring duplicates work and
173/// often masks the author's intent. The schema's `when_to_use` text
174/// rides on the wire as recovery guidance.
175#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
176#[serde(rename_all = "lowercase")]
177pub enum ManualAuthoring {
178 #[default]
179 Allow,
180 Warn,
181 Forbidden,
182}
183
184/// Allowed cardinality ranges for `RelationshipDef::cardinality_per_source`.
185/// Stringly-typed parsing rejected — typos surface at YAML load time via
186/// `serde`, the warning builder gets exhaustive matches, and the wire
187/// payload renders via `Display`.
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
189pub enum Cardinality {
190 #[serde(rename = "1")]
191 One,
192 #[serde(rename = "0..1")]
193 ZeroOrOne,
194 #[serde(rename = "1..N")]
195 OneOrMore,
196 #[serde(rename = "0..N")]
197 ZeroOrMore,
198}
199
200impl std::fmt::Display for Cardinality {
201 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202 let s = match self {
203 Cardinality::One => "1",
204 Cardinality::ZeroOrOne => "0..1",
205 Cardinality::OneOrMore => "1..N",
206 Cardinality::ZeroOrMore => "0..N",
207 };
208 f.write_str(s)
209 }
210}
211
212impl Cardinality {
213 /// Returns `true` iff `count` falls inside the allowed range. Used by
214 /// `memstead_relate` to predict whether a post-mutation outgoing count
215 /// would violate the schema's intent.
216 pub fn admits(&self, count: usize) -> bool {
217 match self {
218 Cardinality::One => count == 1,
219 Cardinality::ZeroOrOne => count <= 1,
220 Cardinality::OneOrMore => count >= 1,
221 Cardinality::ZeroOrMore => true,
222 }
223 }
224}
225
226/// Community-detection (Louvain) defaults — schema-level, not per-type.
227///
228/// Distinct from the legacy `schemas::CommunityConfig` which was attached to
229/// each `TypeDefinition`; the legacy variant has been removed.
230#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
231#[serde(deny_unknown_fields)]
232pub struct CommunityConfig {
233 pub resolution: f64,
234 pub seed: u32,
235}