zebflow 0.10.4

Reactive web automation platform — pipelines, templates, and real-time collaboration in a single binary.
Documentation
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use std::fs;
use std::path::Path;

fn main() {
    generate_version();
    generate_platform_template_assets();
    generate_source_library_assets();
    generate_skill_assets();
    generate_skill_extra_assets();
    generate_node_bundle_assets();
    generate_help_index();
}

fn generate_version() {
    let cargo_version = std::env::var("CARGO_PKG_VERSION").unwrap_or_else(|_| "0.0.0".to_string());

    // Rerun if CI passes a new BUILD_VERSION.
    println!("cargo:rerun-if-env-changed=BUILD_VERSION");

    // Use BUILD_VERSION from CI (passed as Docker build-arg) so the binary version
    // matches the Docker Hub tag. Fall back to a local timestamp when building outside CI.
    let app_version = match std::env::var("BUILD_VERSION") {
        Ok(v) if !v.trim().is_empty() => v.trim().to_string(),
        _ => {
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();
            format!("{cargo_version}.{}", format_build_timestamp(now))
        }
    };

    // The sekejap engine this binary links, read from Cargo.lock: the help and
    // the skills name it and link its grammar at that tag, so an agent never
    // reads a newer engine's grammar than the one it is talking to.
    let sekejap_version = fs::read_to_string("Cargo.lock")
        .ok()
        .and_then(|lock| {
            let at = lock.find("name = \"sekejap\"\nversion = \"")?;
            let rest = &lock[at + "name = \"sekejap\"\nversion = \"".len()..];
            Some(rest[..rest.find('"')?].to_string())
        })
        .unwrap_or_else(|| "unknown".to_string());
    println!("cargo:rerun-if-changed=Cargo.lock");

    let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR not set");
    let dest = std::path::Path::new(&out_dir).join("version_gen.rs");
    fs::write(
        &dest,
        format!(
            "pub const APP_VERSION: &str = \"{app_version}\";\npub const SEKEJAP_ENGINE_VERSION: &str = \"{sekejap_version}\";\n"
        ),
    )
    .expect("failed writing version_gen.rs");

    println!("cargo:warning=🔖 Build version: {app_version}");
    println!("cargo:rerun-if-changed=Cargo.toml");
}

/// Format unix timestamp as YYYYMMDDHHmm (UTC, no external deps).
fn format_build_timestamp(secs: u64) -> String {
    // Days since Unix epoch
    let mut days = secs / 86400;
    let time_of_day = secs % 86400;
    let hour = time_of_day / 3600;
    let minute = (time_of_day % 3600) / 60;

    // Gregorian calendar calculation
    let mut year = 1970u64;
    loop {
        let leap = is_leap(year);
        let days_in_year = if leap { 366 } else { 365 };
        if days < days_in_year {
            break;
        }
        days -= days_in_year;
        year += 1;
    }
    let leap = is_leap(year);
    let month_days: [u64; 12] = [
        31,
        if leap { 29 } else { 28 },
        31,
        30,
        31,
        30,
        31,
        31,
        30,
        31,
        30,
        31,
    ];
    let mut month = 1u64;
    for &md in &month_days {
        if days < md {
            break;
        }
        days -= md;
        month += 1;
    }
    let day = days + 1;
    format!("{year}{month:02}{day:02}{hour:02}{minute:02}")
}

fn is_leap(year: u64) -> bool {
    (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}

fn generate_platform_template_assets() {
    let templates_dir = "src/platform/web/templates";
    let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR not set");
    let dest = Path::new(&out_dir).join("platform_templates_gen.rs");
    println!("cargo:rerun-if-changed=build.rs");

    let mut rel_paths: Vec<String> = Vec::new();
    collect_files(Path::new(templates_dir), templates_dir, &mut rel_paths);
    rel_paths.sort();

    let mut code = String::from("pub const PLATFORM_TEMPLATE_ASSETS: &[EmbeddedAsset] = &[\n");
    for rel in &rel_paths {
        code.push_str(&format!(
            "    EmbeddedAsset {{ \
                path: {rel:?}, \
                bytes: include_bytes!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/src/platform/web/templates/{rel}\")) \
            }},\n"
        ));
    }
    code.push_str("];\n");

    fs::write(&dest, code).expect("failed writing platform_templates_gen.rs");

    // Re-run whenever any template file changes.
    println!("cargo:rerun-if-changed={templates_dir}");
}

/// Emits the asset table for source libraries — `zeb/ui` — shipped inside the
/// binary as `.tsx` the RWE compiler inlines into a page. Paths are
/// `zeb/<name>/<version>/src/<file>`; `LibraryService::source_roots` keys on
/// that shape. Drop a component file in and recompile.
fn generate_source_library_assets() {
    let root = "blessed/source-libraries";
    let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR not set");
    let dest = Path::new(&out_dir).join("source_libraries_gen.rs");

    let mut rel_paths: Vec<String> = Vec::new();
    collect_files(Path::new(root), root, &mut rel_paths);
    rel_paths.sort();

    let mut code = String::from("pub const PLATFORM_SOURCE_LIBRARY_ASSETS: &[EmbeddedAsset] = &[\n");
    for rel in &rel_paths {
        if !rel.ends_with(".tsx") && !rel.ends_with(".ts") {
            continue;
        }
        code.push_str(&format!(
            "    EmbeddedAsset {{ \
                path: \"zeb/{rel}\", \
                bytes: include_bytes!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/{root}/{rel}\")) \
            }},\n"
        ));
    }
    code.push_str("];\n");
    fs::write(&dest, code).expect("failed writing source_libraries_gen.rs");
    println!("cargo:rerun-if-changed={root}");
}

/// Emits the asset table for the blessed skills — the `SKILL.md` folders every
/// project's agent sees without cloning anything. Paths are
/// `<skill>/<file>` under `blessed/skills/` — the core set every project
/// lists and none can opt out of; text files only, since a skill
/// is instructions, references and recipes, never a binary. Drop a folder in
/// and recompile.
fn generate_skill_assets() {
    let root = "blessed/skills";
    let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR not set");
    let dest = Path::new(&out_dir).join("skills_gen.rs");

    let mut rel_paths: Vec<String> = Vec::new();
    collect_files(Path::new(root), root, &mut rel_paths);
    rel_paths.sort();
    // A build context that drops markdown (a `.dockerignore` with `**/*.md`)
    // would otherwise compile an empty skill table without a word.
    assert!(
        rel_paths.iter().any(|p| p.ends_with("/SKILL.md")),
        "no SKILL.md under {root} — is the build context excluding markdown?"
    );

    let text = [".md", ".json", ".yaml", ".yml", ".txt", ".ts", ".tsx", ".mjs", ".js", ".py", ".sh", ".sql", ".css"];
    let mut code = String::from("pub const PLATFORM_SKILL_ASSETS: &[EmbeddedAsset] = &[\n");
    for rel in &rel_paths {
        if !text.iter().any(|ext| rel.ends_with(ext)) {
            continue;
        }
        code.push_str(&format!(
            "    EmbeddedAsset {{ \
                path: {rel:?}, \
                bytes: include_bytes!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/{root}/{rel}\")) \
            }},\n"
        ));
    }
    code.push_str("];\n");
    fs::write(&dest, code).expect("failed writing skills_gen.rs");
    println!("cargo:rerun-if-changed={root}");
}

/// The optional skills: `blessed/skill-extras/<name>/`. Not listed by
/// `skill_list` until a project adds one from the hub — the shelf is their
/// only door, so a project chooses them the way it chooses a library. Same
/// file rules as the core set.
fn generate_skill_extra_assets() {
    let root = "blessed/skill-extras";
    let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR not set");
    let dest = Path::new(&out_dir).join("skill_extras_gen.rs");

    let mut rel_paths: Vec<String> = Vec::new();
    collect_files(Path::new(root), root, &mut rel_paths);
    rel_paths.sort();
    // A build context that drops markdown (a `.dockerignore` with `**/*.md`)
    // would otherwise compile an empty skill table without a word.
    assert!(
        rel_paths.iter().any(|p| p.ends_with("/SKILL.md")),
        "no SKILL.md under {root} — is the build context excluding markdown?"
    );

    let text = [".md", ".json", ".yaml", ".yml", ".txt", ".ts", ".tsx", ".mjs", ".js", ".py", ".sh", ".sql", ".css"];
    let mut code = String::from("pub const PLATFORM_SKILL_EXTRA_ASSETS: &[EmbeddedAsset] = &[\n");
    for rel in &rel_paths {
        if !text.iter().any(|ext| rel.ends_with(ext)) {
            continue;
        }
        code.push_str(&format!(
            "    EmbeddedAsset {{ \
                path: {rel:?}, \
                bytes: include_bytes!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/{root}/{rel}\")) \
            }},\n"
        ));
    }
    code.push_str("];\n");
    fs::write(&dest, code).expect("failed writing skill_extras_gen.rs");
    println!("cargo:rerun-if-changed={root}");
}

// ── Bundled node asset generation ────────────────────────────────────────────

/// Emits the asset table for NodeBundles shipped inside the binary.
///
/// These are consumed at build time rather than installed, so every artifact a
/// bundle declares has to be embedded. Generating the table means adding a
/// function pipeline or an icon needs no bookkeeping: drop the file in and
/// recompile.
fn generate_node_bundle_assets() {
    let bundles_dir = "src/pipeline/nodes/bundled";
    let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR not set");
    let dest = Path::new(&out_dir).join("node_bundles_gen.rs");
    println!("cargo:rerun-if-changed=build.rs");

    let mut rel_paths: Vec<String> = Vec::new();
    collect_files(Path::new(bundles_dir), bundles_dir, &mut rel_paths);
    rel_paths.sort();

    let mut code =
        String::from("pub const PLATFORM_COMPOSITE_NODE_ASSETS: &[EmbeddedAsset] = &[\n");
    for rel in &rel_paths {
        code.push_str(&format!(
            "    EmbeddedAsset {{ \
                path: {rel:?}, \
                bytes: include_bytes!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/src/pipeline/nodes/bundled/{rel}\")) \
            }},\n"
        ));
    }
    code.push_str("];\n");

    fs::write(&dest, code).expect("failed writing node_bundles_gen.rs");
    println!("cargo:rerun-if-changed={bundles_dir}");
}

// ── Help index generation ─────────────────────────────────────────────────────

fn generate_help_index() {
    let help_root = "src/platform/help";
    let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR not set");
    let dest = Path::new(&out_dir).join("help_generated.rs");

    // Always rerun when build.rs itself changes (covers cargo-chef stub → real build.rs swap,
    // and ensures a previously-empty cached HELP is regenerated after help files appear).
    println!("cargo:rerun-if-changed=build.rs");

    // Collect all files relative to the manifest root (e.g. "src/platform/help/web/hooks.md")
    let mut all_files: Vec<String> = Vec::new();
    collect_files(Path::new(help_root), help_root, &mut all_files);

    // Only .md files (excludes mod.rs, generated.rs, etc.)
    all_files.retain(|p| p.ends_with(".md"));
    all_files.sort();

    let mut code = String::from(
        "/// Auto-generated help node array. Do not edit — regenerated by build.rs.\n\
         pub static HELP: &[HelpNode] = &[\n",
    );

    for rel_from_help_root in &all_files {
        // Full path relative to manifest root
        let manifest_rel = format!("{}/{}", help_root, rel_from_help_root);

        // Help path: strip .md extension (e.g. "web/hooks")
        let help_path = rel_from_help_root.trim_end_matches(".md");

        // Read content for metadata extraction
        let content = match fs::read_to_string(&manifest_rel) {
            Ok(c) => c,
            Err(e) => {
                eprintln!("cargo:warning=Could not read {}: {}", manifest_rel, e);
                continue;
            }
        };

        let title = parse_title(&content);
        let excerpt = parse_excerpt(&content);
        let last_updated = git_last_updated(&manifest_rel);

        // include_str! path component: absolute via CARGO_MANIFEST_DIR
        let include_path = format!("/{}", manifest_rel);

        code.push_str(&format!(
            "    HelpNode {{\n\
                     path: {help_path:?},\n\
                     title: {title:?},\n\
                     excerpt: {excerpt:?},\n\
                     last_updated: {last_updated:?},\n\
                     content: include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), {include_path:?})),\n\
                 }},\n",
        ));

        // Tell Cargo to rerun if this file changes
        println!("cargo:rerun-if-changed={}", manifest_rel);
    }

    code.push_str("];\n");

    fs::write(&dest, &code).expect("failed writing help_generated.rs");

    // Also rerun if new files are added to the help directory
    println!("cargo:rerun-if-changed={}", help_root);
}

/// Parse the first `# Heading` from markdown content.
fn parse_title(content: &str) -> String {
    for line in content.lines() {
        let trimmed = line.trim();
        if let Some(title) = trimmed.strip_prefix("# ") {
            return title.trim().to_string();
        }
    }
    "Untitled".to_string()
}

/// Parse first non-heading paragraph, ≤150 chars, stripped of inline markdown.
fn parse_excerpt(content: &str) -> String {
    let mut past_title = false;
    let mut paragraph_lines: Vec<&str> = Vec::new();

    for line in content.lines() {
        let trimmed = line.trim();

        if !past_title {
            if trimmed.starts_with("# ") {
                past_title = true;
            }
            continue;
        }

        // End of paragraph
        if trimmed.is_empty() {
            if !paragraph_lines.is_empty() {
                break;
            }
            continue;
        }

        // Skip sub-headings, horizontal rules, code blocks
        if trimmed.starts_with('#') || trimmed == "---" || trimmed.starts_with("```") {
            if !paragraph_lines.is_empty() {
                break;
            }
            continue;
        }

        paragraph_lines.push(trimmed);
    }

    let raw = paragraph_lines.join(" ");
    // Strip inline markdown: bold, italic, backticks
    let cleaned = raw
        .replace("**", "")
        .replace('*', "")
        .replace('`', "")
        .replace("__", "");
    let cleaned = cleaned.trim().to_string();

    // Truncate to 150 chars at word boundary
    if cleaned.len() <= 150 {
        cleaned
    } else {
        let truncated = &cleaned[..150];
        let end = truncated.rfind(' ').unwrap_or(150);
        format!("{}…", cleaned[..end].trim())
    }
}

/// Get last git commit date for a file (YYYY-MM-DD), or "unknown".
fn git_last_updated(manifest_rel: &str) -> String {
    let output = std::process::Command::new("git")
        .args(["log", "--format=%as", "-1", "--", manifest_rel])
        .output();

    match output {
        Ok(out) if out.status.success() => {
            let date = String::from_utf8_lossy(&out.stdout).trim().to_string();
            if date.is_empty() {
                "unknown".to_string()
            } else {
                date
            }
        }
        _ => "unknown".to_string(),
    }
}

fn collect_files(dir: &Path, root: &str, out: &mut Vec<String>) {
    let entries = match fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return,
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            collect_files(&path, root, out);
        } else if let Ok(rel) = path.strip_prefix(root) {
            let rel_str = rel.to_string_lossy().replace('\\', "/");
            out.push(rel_str);
        }
    }
}