1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
use serde_json::{Value, json};
use crate::AppError;
use crate::workflow::definition::{JsonBoundary, MAX_SOURCE_BYTES};
use crate::workflow::{
GraphComposition, GraphDescription, GraphFormat, NoActions, NoConditions, WorkflowDefinition,
};
impl WorkflowDefinition {
/// Describes authored nodes, ordered edges and declared state access.
///
/// This projection owns metadata only; it never retains executable bindings
/// or lower handles. Callable metadata is resolved when bindings are supplied.
///
/// # Example
///
/// ```
/// use app_kit::workflow::WorkflowDefinition;
///
/// let definition = WorkflowDefinition::parse(r#"{
/// "schema":"app-kit.workflow/v2", "id":"counter", "revision":"r1",
/// "state":{"count":0}, "required":["count"],
/// "reducers":{"count":"reject_concurrent"}, "entry":"increment",
/// "nodes":[{"id":"increment","step":{"kind":"state","mutations":[
/// {"kind":"increment","target":"count","value":{"kind":"literal","value":1}}
/// ]}}], "routes":{}
/// }"#)?;
/// let graph = definition.graph();
/// assert_eq!(graph.nodes[0].id, "increment");
/// assert_eq!(graph.nodes[0].writes, ["count"]);
/// # Ok::<(), app_kit::AppError>(())
/// ```
pub fn graph(&self) -> GraphDescription {
self.compiled.graph::<NoActions, NoConditions>(&[], &[])
}
/// Renders deterministic inspection JSON, DOT or Mermaid without a subprocess.
///
/// Caller text is escaped for the chosen format. This is an inspection
/// document, distinct from [`GraphDescription::tracking_record`].
///
/// # Errors
///
/// Returns `InvalidInput` when the projection exceeds JSON or output-size limits,
/// or `Integration` if graph metadata cannot be encoded.
///
/// # Example
///
/// ```
/// use app_kit::workflow::WorkflowDefinition;
///
/// let definition = WorkflowDefinition::parse(r#"{
/// "schema":"app-kit.workflow/v2", "id":"counter", "revision":"r1",
/// "state":{"count":0}, "required":["count"],
/// "reducers":{"count":"reject_concurrent"}, "entry":"increment",
/// "nodes":[{"id":"increment","step":{"kind":"state","mutations":[
/// {"kind":"increment","target":"count","value":{"kind":"literal","value":1}}
/// ]}}], "routes":{}
/// }"#)?;
/// use app_kit::workflow::GraphFormat;
/// let mermaid = definition.export(GraphFormat::Mermaid)?;
/// assert!(mermaid.starts_with("flowchart TD"));
/// # Ok::<(), app_kit::AppError>(())
/// ```
pub fn export(&self, format: GraphFormat) -> Result<String, AppError> {
format.render(&self.graph())
}
/// Imports graph pieces with explicit node prefixes and appended connections.
///
/// The ordinary compiler checks the assembled definition. Conflicting state,
/// reducers, reused revisions, node names, entrypoints and edges fail before
/// any runtime or lower operation is admitted. Behavior binding keys retain
/// their original meaning; only graph-local node references are prefixed.
///
/// # Errors
///
/// Returns `InvalidInput` for conflicting state/reducers, incompatible revisions,
/// colliding prefixed nodes, invalid connections/entrypoints, graph errors, or
/// exceeded compiler bounds. No runtime or lower operation is admitted.
///
/// # Example
///
/// ```
/// use app_kit::workflow::WorkflowDefinition;
/// const SOURCE: &str = r#"{
/// "schema":"app-kit.workflow/v2", "id":"counter", "revision":"r1",
/// "state":{"count":0}, "required":["count"],
/// "reducers":{"count":"reject_concurrent"}, "entry":"increment",
/// "nodes":[{"id":"increment","step":{"kind":"state","mutations":[
/// {"kind":"increment","target":"count","value":{"kind":"literal","value":1}}
/// ]}}], "routes":{}
/// }"#;
/// let definition = WorkflowDefinition::parse(SOURCE)?;
/// use app_kit::workflow::{GraphComposition, GraphConnection, GraphImport};
/// let composition = GraphComposition {
/// id: "composed".parse()?, revision: "r1".into(), entry: "a_increment".into(),
/// imports: vec![
/// GraphImport { definition, prefix: "a_".into() },
/// GraphImport { definition: WorkflowDefinition::parse(SOURCE)?, prefix: "b_".into() },
/// ],
/// connections: vec![GraphConnection { from: "a_increment".into(), to: "b_increment".into() }],
/// };
/// let composed = WorkflowDefinition::compose(composition)?;
/// assert_eq!(composed.graph().nodes.len(), 2);
/// assert_eq!(composed.graph().entry, "a_increment");
/// # Ok::<(), app_kit::AppError>(())
/// ```
pub fn compose(composition: GraphComposition) -> Result<Self, AppError> {
Ok(Self {
compiled: crate::workflow::definition::CompiledDefinition::compose(composition)?,
})
}
}
impl GraphDescription {
/// Produces the pinned rurr application-graph tracking object.
///
/// Every node must carry actual source metadata. Missing source is an error;
/// no placeholder code is invented. Explicit end edges do not create a
/// synthetic action or transition. The caller owns transport and JSONL framing.
///
/// # Errors
///
/// Returns `InvalidInput` if a node lacks actual source metadata or the tracking
/// record exceeds JSON bounds. Unbound caller actions may have no source metadata;
/// the method does not invent callback source.
///
/// # Example
///
/// ```
/// use app_kit::workflow::WorkflowDefinition;
///
/// let definition = WorkflowDefinition::parse(r#"{
/// "schema":"app-kit.workflow/v2", "id":"counter", "revision":"r1",
/// "state":{"count":0}, "required":["count"],
/// "reducers":{"count":"reject_concurrent"}, "entry":"increment",
/// "nodes":[{"id":"increment","step":{"kind":"state","mutations":[
/// {"kind":"increment","target":"count","value":{"kind":"literal","value":1}}
/// ]}}], "routes":{}
/// }"#)?;
/// let record = definition.graph().tracking_record()?;
/// assert_eq!(record["type"], "application");
/// assert_eq!(record["entrypoint"], "increment");
/// # Ok::<(), app_kit::AppError>(())
/// ```
pub fn tracking_record(&self) -> Result<Value, AppError> {
let mut actions = Vec::with_capacity(self.nodes.len());
for node in &self.nodes {
let source = node.source.as_ref().ok_or_else(|| {
AppError::InvalidInput(format!("graph node '{}' has no source metadata", node.id))
})?;
actions.push(json!({
"type": "action", "name": node.id, "reads": node.reads,
"writes": node.writes, "code": source, "inputs": node.required_inputs,
"optional_inputs": node.optional_inputs,
}));
}
let transitions = self
.edges
.iter()
.filter_map(|edge| {
edge.to.as_ref().map(|target| {
json!({
"type": "transition", "from_": edge.from, "to": target,
"condition": edge.condition.as_deref().unwrap_or("default"),
})
})
})
.collect::<Vec<_>>();
let record = json!({
"type": "application", "entrypoint": self.entry,
"actions": actions, "transitions": transitions,
});
JsonBoundary::validate(&record)?;
Ok(record)
}
}
impl GraphFormat {
fn render(&self, graph: &GraphDescription) -> Result<String, AppError> {
let output = match self {
Self::Json => {
let value = serde_json::to_value(graph).map_err(|_| {
AppError::Integration("graph metadata could not be encoded".to_owned())
})?;
JsonBoundary::validate(&value)?;
serde_json::to_string(&value).map_err(|_| {
AppError::Integration("graph metadata could not be encoded".to_owned())
})?
}
Self::Dot => Self::dot(graph),
Self::Mermaid => Self::mermaid(graph),
};
if output.len() > MAX_SOURCE_BYTES {
return Err(AppError::InvalidInput(
"graph document exceeds the private byte bound".to_owned(),
));
}
Ok(output)
}
fn dot(graph: &GraphDescription) -> String {
let mut output = format!("digraph \"{}\" {{\n", graph.id);
for node in &graph.nodes {
let label = Self::Dot.escape(node.name.as_deref().unwrap_or(&node.id));
output.push_str(&format!(" \"{}\" [label=\"{label}\"];\n", node.id));
}
for edge in &graph.edges {
let Some(target) = &edge.to else { continue };
output.push_str(&format!(" \"{}\" -> \"{target}\"", edge.from));
if let Some(condition) = &edge.condition {
let label = Self::Dot.escape(condition);
output.push_str(&format!(" [label=\"{label}\"]"));
}
output.push_str(";\n");
}
output.push_str("}\n");
output
}
fn mermaid(graph: &GraphDescription) -> String {
let mut output = "flowchart TD\n".to_owned();
for node in &graph.nodes {
let label = Self::Mermaid.escape(node.name.as_deref().unwrap_or(&node.id));
let id = Self::mermaid_id(&node.id);
output.push_str(&format!(" {id}[\"{label}\"]\n"));
}
for edge in &graph.edges {
let Some(target) = &edge.to else { continue };
let from = Self::mermaid_id(&edge.from);
let target = Self::mermaid_id(target);
match &edge.condition {
Some(condition) => {
let label = Self::Mermaid.escape(condition);
output.push_str(&format!(" {from} -->|\"{label}\"| {target}\n"));
}
None => output.push_str(&format!(" {from} --> {target}\n")),
}
}
output
}
fn mermaid_id(id: &str) -> String {
let mut output = String::with_capacity(id.len() + 2);
output.push_str("n_");
for character in id.chars() {
match character {
'-' => output.push_str("_2d"),
'_' => output.push_str("_5f"),
character => output.push(character),
}
}
output
}
fn escape(&self, text: &str) -> String {
let mut output = String::with_capacity(text.len());
for character in text.chars() {
match self {
Self::Dot | Self::Json => match character {
'\\' => output.push_str("\\\\"),
'"' => output.push_str("\\\""),
'\n' => output.push_str("\\n"),
'\r' => output.push_str("\\r"),
'\t' => output.push_str("\\t"),
value if value.is_control() => {
output.push_str(&format!("\\u{:04x}", u32::from(value)))
}
value => output.push(value),
},
Self::Mermaid => match character {
'"' | '&' | '<' | '>' | '[' | ']' | '#' | '|' | '\\' => {
output.push_str(&format!("#{};", u32::from(character)));
}
value if value.is_control() => {
output.push_str(&format!("#{};", u32::from(value)))
}
value => output.push(value),
},
}
}
output
}
}