promptforge-core 0.1.0

PromptForge runtime core: prompt parser, HTTP client, section execution
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! `{{ }}` prose substitution.
//!
//! After a section's Lua prologue runs, the harness resolves `{{ path }}`
//! placeholders in the prose before the model sees it. Lua source in the
//! prologue and epilog is never substituted. Five namespaces are available:
//! `args` (the single raw input string), `reply` (the previous section's model
//! reply, nil in section 1), `item` (the current fanout arm's item text, nil
//! outside arms), `var` (values the prologue wrote), and `sys`
//! (runtime-provided metadata). Resolution is a single pass with no recursion:
//! scalars render as strings, tables/arrays as JSON, and a missing path is a
//! hard error. `{{ reply }}` when nil is a hard error. `{{ item }}` outside a
//! fanout arm is a hard error. Substitution does no arithmetic - compute in
//! Lua and reference the result.
//!
//! # Escape grammar
//!
//! A backslash escapes the following character when it is `{`, `}`, or `\\`:
//! the backslash is consumed and the next character is emitted literally.
//! Everywhere else a backslash is an ordinary literal. This lets prose carry a
//! literal opening delimiter (`\{{` emits `{{`), a literal closing delimiter
//! (`\}}` emits `}}`), and a literal backslash (`\\` emits `\`). Escapes
//! compose, so adjacent escaped delimiters resolve independently.
//!
//! Substitution is a single left-to-right pass over the *input* prose only:
//! resolved output is appended to a separate buffer and never rescanned, so a
//! replacement that itself contains `{{ ... }}` is emitted verbatim and never
//! triggers a second round of substitution.

use serde_json::Value;

use crate::Result;

/// A stable classification of a [`SubstitutionError`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SubstErrorKind {
    /// A `{{` was opened but never closed with `}}`.
    Unclosed,
    /// A bare namespace with no `.key` suffix where one is required.
    BadPath,
    /// A path segment was empty or whitespace-padded (`var.`, `var..x`).
    EmptySegment,
    /// The leading namespace is not one of the five known roots.
    UnknownNamespace,
    /// A scalar namespace (`args`/`reply`/`item`) was indexed like a table.
    NotATable,
    /// A `var`/`sys` lookup found no value at the requested key.
    MissingKey,
    /// The resolved value was JSON null.
    NullValue,
    /// `{{ reply }}` was used before any prior section reply existed.
    NilReply,
    /// `{{ item }}` was used outside a fanout arm.
    NilItem,
    /// A table/array value failed to serialize to JSON.
    Serialize,
}

/// A typed substitution failure.
///
/// Carries a stable [`kind`](SubstitutionError::kind), the byte
/// [`offset`](SubstitutionError::offset) of the offending placeholder within
/// the prose, a `message` that embeds a bounded, control-escaped preview of the
/// placeholder path, and - for the serialization case - the preserved
/// underlying error as its [`source`](std::error::Error::source).
#[derive(Debug)]
pub(crate) struct SubstitutionError {
    kind: SubstErrorKind,
    offset: usize,
    message: String,
    source: Option<Box<dyn std::error::Error + Send + Sync>>,
}

impl SubstitutionError {
    fn new(kind: SubstErrorKind, offset: usize, message: String) -> Self {
        SubstitutionError {
            kind,
            offset,
            message,
            source: None,
        }
    }

    fn with_source(
        kind: SubstErrorKind,
        offset: usize,
        message: String,
        source: Box<dyn std::error::Error + Send + Sync>,
    ) -> Self {
        SubstitutionError {
            kind,
            offset,
            message,
            source: Some(source),
        }
    }
}

impl std::fmt::Display for SubstitutionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} [{:?} at byte {}]",
            self.message, self.kind, self.offset
        )
    }
}

impl std::error::Error for SubstitutionError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source
            .as_deref()
            .map(|s| s as &(dyn std::error::Error + 'static))
    }
}

type SubstResult<T> = std::result::Result<T, SubstitutionError>;

/// Resolve every `{{ path }}` in `prose` against `args`, `reply`, `item`,
/// `var`, and `sys`.
///
/// `var` and `sys` are JSON objects (`var` read back from the Lua prologue,
/// `sys` built by the runtime). `reply` is the previous section's model
/// reply text, or `None` in the first section. `item` is the current fanout
/// arm's item text, or `None` outside arms. This function receives prose
/// only and does not transform either compiled Lua phase.
///
/// # Errors
/// Returns [`Error::Substitution`](crate::Error::Substitution) for an unclosed
/// `{{`, an unknown namespace, an empty or whitespace path segment, a missing
/// key, a null value, `{{ reply }}` when `reply` is `None`, or `{{ item }}`
/// when `item` is `None`.
pub(crate) fn substitute(
    prose: &str,
    args: &str,
    reply: Option<&str>,
    item: Option<&str>,
    var: &Value,
    sys: &Value,
) -> Result<String> {
    Ok(substitute_inner(prose, args, reply, item, var, sys)?)
}

fn substitute_inner(
    prose: &str,
    args: &str,
    reply: Option<&str>,
    item: Option<&str>,
    var: &Value,
    sys: &Value,
) -> SubstResult<String> {
    let mut out = String::with_capacity(prose.len());
    let bytes = prose.as_bytes();
    let mut i = 0;
    while i < prose.len() {
        // Escape grammar: a backslash consumes itself and emits a literal `{`,
        // `}`, or `\` when one immediately follows.
        if bytes[i] == b'\\' && i + 1 < prose.len() {
            let next = bytes[i + 1];
            if matches!(next, b'{' | b'}' | b'\\') {
                out.push(next as char);
                i += 2;
                continue;
            }
        }
        if bytes[i] == b'{' && i + 1 < prose.len() && bytes[i + 1] == b'{' {
            let start = i;
            let after = &prose[i + 2..];
            let end = after.find("}}").ok_or_else(|| {
                SubstitutionError::new(
                    SubstErrorKind::Unclosed,
                    start,
                    "unclosed '{{' in prose".to_string(),
                )
            })?;
            let path = after[..end].trim();
            out.push_str(&resolve(path, start, args, reply, item, var, sys)?);
            i += 2 + end + 2;
            continue;
        }
        let Some(ch) = prose[i..].chars().next() else {
            break;
        };
        out.push(ch);
        i += ch.len_utf8();
    }
    Ok(out)
}

/// Resolve a single `{{ }}` path to its rendered string.
fn resolve(
    path: &str,
    offset: usize,
    args: &str,
    reply: Option<&str>,
    item: Option<&str>,
    var: &Value,
    sys: &Value,
) -> SubstResult<String> {
    if path == "args" {
        return Ok(args.to_string());
    }
    if path == "reply" {
        return reply.map(String::from).ok_or_else(|| {
            SubstitutionError::new(
                SubstErrorKind::NilReply,
                offset,
                "{{ reply }} is nil (no prior section reply)".to_string(),
            )
        });
    }
    if path == "item" {
        return item.map(String::from).ok_or_else(|| {
            SubstitutionError::new(
                SubstErrorKind::NilItem,
                offset,
                "{{ item }} is nil (not inside a fanout arm)".to_string(),
            )
        });
    }

    let Some((namespace, keys)) = path.split_once('.') else {
        return Err(SubstitutionError::new(
            SubstErrorKind::BadPath,
            offset,
            format!("bad path: {{{{ {} }}}}", path_preview(path)),
        ));
    };

    // Validate the complete segment grammar before any lookup: every segment
    // (namespace included) must be nonempty and free of leading or trailing
    // whitespace, so `var.`, `var..x`, and `var. .x` are rejected up front even
    // when a matching JSON key happens to exist.
    for segment in path.split('.') {
        if segment.is_empty() || segment.trim() != segment {
            return Err(SubstitutionError::new(
                SubstErrorKind::EmptySegment,
                offset,
                format!(
                    "empty or padded path segment in {{{{ {} }}}}",
                    path_preview(path)
                ),
            ));
        }
    }

    let root = match namespace {
        "var" => var,
        "sys" => sys,
        "args" | "reply" | "item" => {
            return Err(SubstitutionError::new(
                SubstErrorKind::NotATable,
                offset,
                format!("{namespace} is a string, not a table"),
            ));
        }
        other => {
            return Err(SubstitutionError::new(
                SubstErrorKind::UnknownNamespace,
                offset,
                format!(
                    "unknown namespace '{}' in {{{{ {} }}}}",
                    path_preview(other),
                    path_preview(path)
                ),
            ));
        }
    };

    let mut current = root;
    for key in keys.split('.') {
        current = current.get(key).ok_or_else(|| {
            SubstitutionError::new(
                SubstErrorKind::MissingKey,
                offset,
                format!("missing {{{{ {} }}}}", path_preview(path)),
            )
        })?;
    }
    render(current, path, offset)
}

/// Renders a prompt-controlled placeholder path for a diagnostic.
///
/// Control characters are escaped and the text is truncated to a bounded length
/// so a hostile or malformed placeholder cannot forge multiline log records,
/// leak an oversized span, or smuggle control characters through `Display`.
fn path_preview(path: &str) -> String {
    use std::fmt::Write as _;
    const MAX_PREVIEW_CHARS: usize = 80;
    let mut out = String::with_capacity(path.len().min(MAX_PREVIEW_CHARS));
    for ch in path.chars().take(MAX_PREVIEW_CHARS) {
        match ch {
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if c.is_control() => {
                let _ = write!(out, "\\u{{{:04x}}}", u32::from(c));
            }
            c => out.push(c),
        }
    }
    if path.chars().count() > MAX_PREVIEW_CHARS {
        out.push_str("...");
    }
    out
}

/// Render a resolved JSON value as its substituted string.
fn render(value: &Value, path: &str, offset: usize) -> SubstResult<String> {
    match value {
        Value::Null => Err(SubstitutionError::new(
            SubstErrorKind::NullValue,
            offset,
            format!("missing {{{{ {} }}}}", path_preview(path)),
        )),
        Value::String(s) => Ok(s.clone()),
        Value::Bool(b) => Ok(b.to_string()),
        Value::Number(n) => Ok(n.to_string()),
        Value::Array(_) | Value::Object(_) => serde_json::to_string(value).map_err(|error| {
            SubstitutionError::with_source(
                SubstErrorKind::Serialize,
                offset,
                format!("could not serialize {{{{ {} }}}}", path_preview(path)),
                Box::new(error),
            )
        }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn run(prose: &str) -> Result<String> {
        let var = json!({ "kind": "library", "count": 3, "row": { "a": 1 } });
        let sys = json!({ "when": "2026-07-29T00:00:00Z", "id": 1 });
        substitute(prose, "Acme Corp", None, None, &var, &sys)
    }

    fn err_of(prose: &str) -> SubstitutionError {
        let var = json!({ "kind": "library", "row": { "a": 1 }, "arr": [1, 2] });
        let sys = json!({ "id": 1 });
        substitute_inner(prose, "Acme Corp", Some("r"), Some("i"), &var, &sys)
            .expect_err("expected substitution failure")
    }

    #[test]
    fn substitution_diagnostics_escape_and_bound_the_placeholder() {
        let hostile = format!("var.{}", "x".repeat(500));
        let preview = path_preview(&hostile);
        assert!(
            preview.chars().count() <= 83,
            "preview must be bounded, got {} chars",
            preview.chars().count()
        );
        assert!(preview.ends_with("..."), "over-long preview must be elided");

        let with_controls = path_preview("var.a\nb\tc");
        assert!(
            !with_controls.contains('\n') && !with_controls.contains('\t'),
            "control characters must be escaped, got: {with_controls}"
        );
        assert!(with_controls.contains("\\n") && with_controls.contains("\\t"));
    }

    #[test]
    fn resolves_args() {
        assert_eq!(run("hi {{ args }}!").unwrap(), "hi Acme Corp!");
    }

    #[test]
    fn resolves_var_scalar() {
        assert_eq!(run("a {{ var.kind }} paper").unwrap(), "a library paper");
        assert_eq!(run("{{ var.count }}").unwrap(), "3");
    }

    #[test]
    fn resolves_sys() {
        assert_eq!(run("id {{ sys.id }}").unwrap(), "id 1");
        assert_eq!(run("at {{ sys.when }}").unwrap(), "at 2026-07-29T00:00:00Z");
    }

    #[test]
    fn table_renders_as_json() {
        assert_eq!(run("{{ var.row }}").unwrap(), "{\"a\":1}");
    }

    #[test]
    fn missing_key_is_error() {
        assert!(run("{{ var.nope }}").is_err());
        assert!(run("{{ ghost.x }}").is_err());
        let sys_error = run("{{ sys.bogus }}").expect_err("unknown sys field must fail");
        assert!(
            sys_error.to_string().contains("missing {{ sys.bogus }}"),
            "error was {sys_error}"
        );
    }

    #[test]
    fn no_placeholders_passthrough() {
        assert_eq!(run("plain text").unwrap(), "plain text");
    }

    #[test]
    fn unclosed_is_error() {
        assert_eq!(err_of("open {{ args").kind, SubstErrorKind::Unclosed);
    }

    // --- SUBST-003: escape grammar -------------------------------------------

    #[test]
    fn escaped_delimiters_are_literal() {
        assert_eq!(
            run(r"literal \{{ args }} here").unwrap(),
            "literal {{ args }} here"
        );
        assert_eq!(run(r"close \}} brace").unwrap(), "close }} brace");
        assert_eq!(run(r"back \\ slash").unwrap(), r"back \ slash");
    }

    #[test]
    fn escape_then_real_placeholder_adjacent() {
        // First delimiter escaped, second one live and resolved.
        assert_eq!(run(r"\{{x}}{{ args }}").unwrap(), "{{x}}Acme Corp");
    }

    #[test]
    fn lone_backslash_is_literal() {
        assert_eq!(run(r"a\b").unwrap(), r"a\b");
        assert_eq!(run("trailing\\").unwrap(), "trailing\\");
    }

    #[test]
    fn replacement_produced_delimiters_are_not_resubstituted() {
        let var = json!({ "payload": "{{ args }}" });
        let sys = json!({});
        // `var.payload` renders text that looks like a placeholder; it must be
        // emitted verbatim, never resolved against args.
        let out = substitute("value: {{ var.payload }}", "SECRET", None, None, &var, &sys).unwrap();
        assert_eq!(out, "value: {{ args }}");
    }

    // --- SUBST-004: path segment grammar -------------------------------------

    #[test]
    fn empty_or_padded_segments_are_rejected() {
        for bad in ["var.", "var..x", "var. .x", "var.x.", "var. .x .y"] {
            let prose = format!("{{{{ {bad} }}}}");
            let e = err_of(&prose);
            assert_eq!(
                e.kind,
                SubstErrorKind::EmptySegment,
                "path {bad:?} must be an empty-segment error, got {:?}",
                e.kind
            );
        }
    }

    #[test]
    fn valid_nested_segment_still_resolves() {
        assert_eq!(run("{{ var.row.a }}").unwrap(), "1");
    }

    // --- SUBST-005: typed error kind/offset/source ---------------------------

    #[test]
    fn error_carries_kind_and_offset() {
        let e = err_of("prefix {{ ghost.x }}");
        assert_eq!(e.kind, SubstErrorKind::UnknownNamespace);
        assert_eq!(e.offset, 7, "offset must point at the '{{{{'");
        assert!(e.to_string().contains("ghost.x"));
    }

    #[test]
    fn null_value_and_reply_item_kinds() {
        let var = json!({ "n": Value::Null });
        let sys = json!({});
        let e = substitute_inner("{{ var.n }}", "", None, None, &var, &sys).unwrap_err();
        assert_eq!(e.kind, SubstErrorKind::NullValue);

        let e = substitute_inner("{{ reply }}", "", None, None, &var, &sys).unwrap_err();
        assert_eq!(e.kind, SubstErrorKind::NilReply);
        let e = substitute_inner("{{ item }}", "", None, None, &var, &sys).unwrap_err();
        assert_eq!(e.kind, SubstErrorKind::NilItem);
    }

    #[test]
    fn not_a_table_kind() {
        let e = err_of("{{ reply.x }}");
        assert_eq!(e.kind, SubstErrorKind::NotATable);
        assert!(e.to_string().contains("not a table"));
    }

    // --- SUBST-006: null, arrays, trust-neutral passthrough ------------------

    #[test]
    fn array_renders_as_json() {
        let var = json!({ "arr": [1, 2, 3] });
        let sys = json!({});
        let out = substitute("{{ var.arr }}", "", None, None, &var, &sys).unwrap();
        assert_eq!(out, "[1,2,3]");
    }

    #[test]
    fn resolves_reply_when_present() {
        let var = json!({});
        let sys = json!({});
        let out = substitute(
            "prev: {{ reply }}",
            "",
            Some("model output"),
            None,
            &var,
            &sys,
        )
        .unwrap();
        assert_eq!(out, "prev: model output");
    }

    #[test]
    fn reply_nil_is_error() {
        let var = json!({});
        let sys = json!({});
        let err =
            substitute("{{ reply }}", "", None, None, &var, &sys).expect_err("nil reply must fail");
        assert!(
            err.to_string().contains("nil"),
            "error must mention nil: {err}"
        );
    }

    #[test]
    fn reply_dot_path_is_error() {
        let var = json!({});
        let sys = json!({});
        let err = substitute("{{ reply.x }}", "", Some("text"), None, &var, &sys)
            .expect_err("reply is a string, not a table");
        assert!(
            err.to_string().contains("not a table"),
            "error must say not a table: {err}"
        );
    }

    #[test]
    fn resolves_item_when_present() {
        let var = json!({});
        let sys = json!({});
        let out = substitute("topic: {{ item }}", "", None, Some("the angle"), &var, &sys).unwrap();
        assert_eq!(out, "topic: the angle");
    }

    #[test]
    fn item_nil_is_error() {
        let var = json!({});
        let sys = json!({});
        let err =
            substitute("{{ item }}", "", None, None, &var, &sys).expect_err("nil item must fail");
        assert!(
            err.to_string().contains("nil"),
            "error must mention nil: {err}"
        );
    }

    #[test]
    fn item_dot_path_is_error() {
        let var = json!({});
        let sys = json!({});
        let err = substitute("{{ item.x }}", "", None, Some("text"), &var, &sys)
            .expect_err("item is a string, not a table");
        assert!(
            err.to_string().contains("not a table"),
            "error must say not a table: {err}"
        );
    }
}