-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.rs
More file actions
1925 lines (1766 loc) · 72.7 KB
/
Copy pathcompiler.rs
File metadata and controls
1925 lines (1766 loc) · 72.7 KB
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! [`PlanCompiler`] implementations that back the prose-first
//! `plan_create` / `plan_answer` / `plan_refine` MCP surface.
//!
//! `flowd-mcp` ships three [`PlanCompiler`]s, each with a distinct role:
//!
//! | Type | When to use |
//! |----------------------------|-----------------------------------------------------------------------------|
//! | [`StubPlanCompiler`] | Default. No LLM, no network. Parses structured-markdown prose into a DAG. |
//! | [`LlmPlanCompiler`] | Real LLM-backed compiler. Generic over [`LlmCallback`]; the daemon wires |
//! | | [`crate::llm::OpenAiCompatibleCallback`] for local `mlx_lm.server` traffic. |
//! | [`RejectingPlanCompiler`] | Test double / "prose-first disabled" build flag. Always errors. |
//!
//! ## Trait contract recap
//!
//! Every implementation must honour the [`PlanCompiler`] invariants:
//!
//! * `definition.is_some()` iff `open_questions.is_empty()`.
//! * Every emitted [`OpenQuestion::depends_on_decisions`] entry must
//! reference either a question already answered or one that will appear
//! in this same `CompileOutput`'s `new_decisions`.
//! * Question ids are stable across rounds (the executor uses them as the
//! handle for invalidation).
//!
//! ## Stub-compiler grammar
//!
//! The [`StubPlanCompiler`] is intentionally tiny so that operators can
//! drive the prose-first loop end-to-end without an LLM, as long as their
//! prose is already structured. It recognises:
//!
//! ```text
//! # <plan name> (optional, sets PlanDefinition.name)
//!
//! ## <step-id> [agent: <agent_type>] (depends_on omitted -> no deps)
//! prompt body line 1
//! prompt body line 2
//!
//! ## <step-id> [agent: <agent_type>] depends_on: [a, b]
//! prompt body
//!
//! ## <step-id> [agent: <agent_type>] timeout_secs: 90 depends_on: [a]
//! prompt body (timeout_secs and depends_on may
//! appear in either order)
//! ```
//!
//! Anything that does not match a step heading and follows one is treated
//! as part of the preceding step's prompt. Unrecognised content before the
//! first step heading is silently dropped (the original prose is still
//! preserved verbatim in [`Plan::source_doc`]). Validation done in the
//! parser:
//!
//! * at least one step,
//! * unique step ids,
//! * each `depends_on` id refers to a defined step,
//! * no self-cycle (full cycle detection is left to `validate_plan`).
//!
//! On any parse failure the stub returns one [`OpenQuestion`] with
//! `allow_explain_more = true`, instructing the caller to either restructure
//! the prose (via `plan_refine`) or paste a structured version through
//! `Answer::ExplainMore`.
use std::collections::HashSet;
use std::fmt::Write as _;
use std::future::Future;
use std::sync::Arc;
use flowd_core::error::{FlowdError, Result};
use flowd_core::orchestration::{
Answer, CompileOutput, DecisionRecord, OpenQuestion, PlanCompiler, PlanDefinition,
PlanDraftSnapshot, QuestionOption, StepDefinition,
};
use serde::Deserialize;
// ---------------------------------------------------------------------------
// RejectingPlanCompiler
// ---------------------------------------------------------------------------
/// [`PlanCompiler`] that refuses every call with a clear validation error.
///
/// Useful as a test double when a handler test wants to assert that the
/// prose-first surface is reachable but does not want to script a
/// [`flowd_core::orchestration::MockPlanCompiler`], or as a build-time
/// flag for deployments that want to disable prose-first plans entirely.
#[derive(Debug, Default, Clone, Copy)]
pub struct RejectingPlanCompiler;
impl RejectingPlanCompiler {
/// Construct a new rejecting compiler. Cheap; the type is zero-sized.
#[must_use]
pub const fn new() -> Self {
Self
}
fn unavailable(method: &'static str) -> FlowdError {
FlowdError::PlanValidation(format!(
"prose-first plan creation is disabled in this build (called {method}); \
pass `definition` to plan_create instead, or rebuild with a real PlanCompiler wired in"
))
}
}
impl PlanCompiler for RejectingPlanCompiler {
async fn compile_prose(&self, _prose: String, _project: String) -> Result<CompileOutput> {
Err(Self::unavailable("compile_prose"))
}
async fn apply_answers(
&self,
_snapshot: PlanDraftSnapshot,
_answers: Vec<(String, Answer)>,
_defer_remaining: bool,
) -> Result<CompileOutput> {
Err(Self::unavailable("apply_answers"))
}
async fn refine(
&self,
_snapshot: PlanDraftSnapshot,
_feedback: String,
) -> Result<CompileOutput> {
Err(Self::unavailable("refine"))
}
}
// ---------------------------------------------------------------------------
// StubPlanCompiler
// ---------------------------------------------------------------------------
/// Question id surfaced when the stub cannot parse the prose.
///
/// Stable so callers can match on it and so subsequent rounds keep the
/// same id (the executor uses ids as the invalidation handle).
const STRUCTURE_QUESTION_ID: &str = "stub.structure_required";
/// Deterministic, no-LLM [`PlanCompiler`] that parses structured-markdown
/// prose into a [`PlanDefinition`].
///
/// See the module docs for the grammar.
#[derive(Debug, Default, Clone, Copy)]
pub struct StubPlanCompiler;
impl StubPlanCompiler {
/// Construct a new stub compiler. Cheap; the type is zero-sized.
#[must_use]
pub const fn new() -> Self {
Self
}
}
impl PlanCompiler for StubPlanCompiler {
async fn compile_prose(&self, prose: String, _project: String) -> Result<CompileOutput> {
Ok(parse_or_pending(
&prose, &prose, /* surface_error_in_prompt */ true,
))
}
async fn apply_answers(
&self,
snapshot: PlanDraftSnapshot,
answers: Vec<(String, Answer)>,
defer_remaining: bool,
) -> Result<CompileOutput> {
// The stub cannot interpret `Choose` answers (it has nothing to
// pick between). The only signal it can act on is `ExplainMore`,
// whose `note` field is the natural channel for the user (or a
// helper LLM running outside flowd) to paste a structured version
// of the plan.
let extra: String = answers
.iter()
.filter_map(|(_, a)| match a {
Answer::ExplainMore { note } if !note.trim().is_empty() => Some(note.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join("\n\n");
let base = snapshot.source_doc.unwrap_or_default();
let candidate = if extra.is_empty() {
base.clone()
} else if base.trim().is_empty() {
extra.clone()
} else {
format!("{base}\n\n{extra}")
};
let out = parse_or_pending(&candidate, &candidate, true);
if defer_remaining && out.definition.is_none() {
// The stub has no model, so it cannot invent best-effort
// answers. Surface that explicitly so callers do not loop.
return Err(FlowdError::PlanValidation(
"StubPlanCompiler cannot honour `defer_remaining`: it has no LLM to invent \
answers from. Either restructure the prose via plan_refine, or wire an \
LlmPlanCompiler into the daemon."
.to_string(),
));
}
Ok(out)
}
async fn refine(
&self,
_snapshot: PlanDraftSnapshot,
feedback: String,
) -> Result<CompileOutput> {
// Refinement contract for the stub: `feedback` is the new
// source_doc verbatim. The user is expected to paste a corrected
// structured-markdown plan. This is the documented escape hatch
// for environments without an LLM.
Ok(parse_or_pending(&feedback, &feedback, true))
}
}
/// Parse `prose` and turn the outcome into a [`CompileOutput`].
///
/// `source_doc` is the value the executor will store into
/// [`flowd_core::orchestration::Plan::source_doc`]; in the typical case
/// it is identical to `prose`, but callers that synthesise a candidate
/// (e.g. base + extra in `apply_answers`) can pass the synthesised text.
///
/// When `surface_error_in_prompt` is true and parsing fails, the parse
/// error is included in the open question's prompt so the caller can see
/// exactly what went wrong without re-running the parser. We always set
/// it true today; the parameter exists so future callers (e.g. a
/// silent-mode CLI) can opt out.
fn parse_or_pending(prose: &str, source_doc: &str, surface_error_in_prompt: bool) -> CompileOutput {
match parse_structured(prose) {
Ok(definition) => CompileOutput::ready(source_doc, definition),
Err(err) => CompileOutput::pending(
source_doc,
vec![structure_question(err.as_str(), surface_error_in_prompt)],
),
}
}
/// Build the open question the stub surfaces when parsing fails.
fn structure_question(reason: &str, include_reason: bool) -> OpenQuestion {
let prompt = if include_reason && !reason.is_empty() {
format!(
"Could not parse the prose plan deterministically: {reason}. \
Either restructure your prose so each step looks like \
`## <step-id> [agent: <type>] depends_on: [a, b]` followed by the \
prompt body, or paste a structured version via Answer::ExplainMore."
)
} else {
"Could not parse the prose plan deterministically; \
please structure it or attach an LLM compiler."
.to_string()
};
OpenQuestion {
id: STRUCTURE_QUESTION_ID.to_string(),
prompt,
rationale: "The stub compiler is parser-only and needs each step to be expressed \
in the documented structured-markdown grammar."
.to_string(),
// No options to choose from; the only meaningful response is
// `ExplainMore { note: <restructured prose> }` or a `plan_refine`
// call with the structured prose as feedback.
options: Vec::new(),
allow_explain_more: true,
allow_none: false,
depends_on_decisions: Vec::new(),
}
}
/// Hand-rolled line-based parser for the stub grammar. Returns
/// `Err(reason)` with a human-readable explanation on failure.
fn parse_structured(prose: &str) -> std::result::Result<PlanDefinition, String> {
let mut name: Option<String> = None;
let mut steps: Vec<StepDefinition> = Vec::new();
let mut current_header: Option<StepHeader> = None;
let mut current_body: Vec<&str> = Vec::new();
let flush = |header: StepHeader,
body: &[&str],
acc: &mut Vec<StepDefinition>|
-> std::result::Result<(), String> {
let prompt = body.join("\n").trim().to_string();
if prompt.is_empty() {
return Err(format!("step '{}' has no prompt body", header.id));
}
acc.push(StepDefinition {
id: header.id,
agent_type: header.agent_type,
prompt,
depends_on: header.depends_on,
timeout_secs: header.timeout_secs,
retry_count: 0,
});
Ok(())
};
for line in prose.lines() {
// Optional H1 plan title -- only honoured before the first step
// heading. `# foo` matches; `## foo` does not (different prefix).
if name.is_none()
&& current_header.is_none()
&& steps.is_empty()
&& let Some(rest) = line.strip_prefix("# ")
{
let trimmed = rest.trim();
if !trimmed.is_empty() {
name = Some(trimmed.to_string());
continue;
}
}
if let Some(header) = parse_step_header(line) {
if let Some(prev) = current_header.take() {
flush(prev, ¤t_body, &mut steps)?;
current_body.clear();
}
current_header = Some(header);
} else if current_header.is_some() {
current_body.push(line);
}
// Lines before the first step heading that are not the H1 title
// are deliberately ignored. The original prose is preserved
// verbatim by the executor in `Plan::source_doc`, so nothing is
// lost in the audit trail.
}
if let Some(prev) = current_header.take() {
flush(prev, ¤t_body, &mut steps)?;
}
if steps.is_empty() {
return Err("no `## <id> [agent: <type>]` step headings found".into());
}
// Unique ids.
let mut seen: HashSet<&String> = HashSet::new();
for s in &steps {
if !seen.insert(&s.id) {
return Err(format!("duplicate step id: '{}'", s.id));
}
}
// Dependencies refer to defined ids, no self-cycle. Full multi-step
// cycle detection is left to `validate_plan` downstream so we don't
// duplicate that logic here.
let id_set: HashSet<&String> = steps.iter().map(|s| &s.id).collect();
for s in &steps {
for dep in &s.depends_on {
if dep == &s.id {
return Err(format!("step '{}' depends on itself", s.id));
}
if !id_set.contains(dep) {
return Err(format!(
"step '{}' depends_on '{dep}' which is not defined in this plan",
s.id
));
}
}
}
Ok(PlanDefinition {
name: name.unwrap_or_else(|| "prose-plan".to_string()),
project: None,
project_root: None,
steps,
})
}
#[derive(Debug)]
struct StepHeader {
id: String,
agent_type: String,
depends_on: Vec<String>,
timeout_secs: Option<u64>,
}
/// Parse a single `## <id> [agent: <type>] [depends_on: [...]]` line.
///
/// Returns `None` for any line that does not match the grammar; the
/// caller treats those as either body text (if a step is open) or
/// preamble (if not).
fn parse_step_header(line: &str) -> Option<StepHeader> {
let body = line.strip_prefix("## ")?.trim();
if body.is_empty() {
return None;
}
// <id> is the first whitespace-delimited token.
let id_end = body.find(char::is_whitespace)?;
let id = body[..id_end].trim().to_string();
if id.is_empty() {
return None;
}
let after_id = body[id_end..].trim_start();
// [agent: <type>]
let agent_marker = "[agent:";
let agent_start = after_id.find(agent_marker)?;
let after_agent = &after_id[agent_start + agent_marker.len()..];
let agent_close = after_agent.find(']')?;
let agent_type = after_agent[..agent_close].trim().to_string();
if agent_type.is_empty() {
return None;
}
let after_bracket = after_agent[agent_close + 1..].trim_start();
// Optional `depends_on: [a, b, c]`. Anything else after the agent
// bracket is ignored by the stub (room for future fields without
// breaking existing inputs).
let marker = "depends_on:";
let depends_on = match after_bracket.find(marker) {
Some(idx) => {
let after_marker = after_bracket[idx + marker.len()..].trim_start();
let open = after_marker.find('[')?;
let close = after_marker[open + 1..].find(']')?;
let inner = &after_marker[open + 1..open + 1 + close];
inner
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
}
None => Vec::new(),
};
// Optional `timeout_secs: <N>`. Authors set this so the step keeps
// its bespoke deadline across compile/refine cycles instead of
// silently inheriting the daemon-wide default. May appear before or
// after `depends_on:`; an unparseable value is treated as "field
// omitted" so a typo never blocks the rest of the header.
let timeout_secs = parse_timeout_field(after_bracket);
Some(StepHeader {
id,
agent_type,
depends_on,
timeout_secs,
})
}
/// Extract `timeout_secs: <N>` from the tail of a step header, if present.
fn parse_timeout_field(tail: &str) -> Option<u64> {
let marker = "timeout_secs:";
let idx = tail.find(marker)?;
let after = tail[idx + marker.len()..].trim_start();
// Stop at the next whitespace, comma, or `]` so we don't slurp the
// following `depends_on: [...]` block.
let end = after
.find(|c: char| c.is_whitespace() || c == ',' || c == ']')
.unwrap_or(after.len());
after[..end].parse::<u64>().ok()
}
// ---------------------------------------------------------------------------
// LlmPlanCompiler
// ---------------------------------------------------------------------------
/// Question id surfaced when the LLM repeatedly fails to produce a valid
/// JSON response. Stable across rounds so the executor can match on it
/// for invalidation, and deliberately distinct from
/// [`STRUCTURE_QUESTION_ID`] so callers can tell which compiler bailed.
const LLM_STRUCTURE_QUESTION_ID: &str = "llm.structure_required";
/// Callback shape the [`LlmPlanCompiler`] invokes to talk to a model.
/// Modelled after [`flowd_core::memory::Summarizer`] so that the MCP
/// layer can plug in any transport (HTTP via
/// [`crate::llm::OpenAiCompatibleCallback`], stdio CLI shellouts,
/// `sampling/createMessage` adapter) without changing the compiler's
/// public surface.
pub trait LlmCallback: Send + Sync {
/// Send `prompt` to the underlying model and return the completion.
///
/// The prompt is the full assistant input including any system /
/// schema instructions; the callback is expected to be a pure
/// "string in, string out" transport with no awareness of plan
/// semantics.
///
/// # Errors
/// Implementations should return `FlowdError::Internal` for transport
/// failures and `FlowdError::PlanValidation` for model-rejected
/// prompts (e.g. content-policy rejections).
fn complete(&self, prompt: String) -> impl Future<Output = Result<String>> + Send;
}
/// LLM-backed [`PlanCompiler`].
///
/// Drives the prose-first loop by sending tightly scoped prompts to a
/// model behind an [`LlmCallback`] and parsing the responses into
/// [`CompileOutput`]s. The compiler enforces a strict JSON output shape
/// (see the `LlmCompileResponse` wire type), retries once with a
/// corrective prompt when the first response fails to parse, and falls
/// back to a structured `llm.structure_required` open question rather
/// than bubbling raw model errors to the user.
///
/// ## Determinism
///
/// The compiler is deterministic given a deterministic callback. Tests
/// can therefore use a hand-rolled mock implementing [`LlmCallback`]
/// instead of calling out to the real model. The `--ignored` end-to-end
/// test in `tests/llm_e2e.rs` exercises a live `mlx_lm.server` once
/// per release.
#[derive(Debug, Clone)]
pub struct LlmPlanCompiler<C: LlmCallback> {
callback: Arc<C>,
}
impl<C: LlmCallback> LlmPlanCompiler<C> {
/// Construct a new LLM-backed compiler around `callback`.
#[must_use]
pub fn new(callback: Arc<C>) -> Self {
Self { callback }
}
/// Borrow the callback. Exposed so tests and the daemon's startup
/// banner can observe wiring without taking ownership.
#[must_use]
pub fn callback(&self) -> &Arc<C> {
&self.callback
}
/// Run a prompt through the callback with at most one corrective
/// retry on parse failure, then fall back to a structure-required
/// open question. The fallback path is what keeps the user out of
/// the "model just answered with prose" deadlock.
///
/// Transport errors are propagated as-is (the user can't recover by
/// rephrasing prose if MLX is down); only *parse* failures trigger
/// the retry/fallback path.
async fn invoke(&self, prompt: String, source_doc: &str) -> Result<CompileOutput> {
let raw = self.callback.complete(prompt.clone()).await?;
match parse_llm_response(&raw) {
Ok(out) => Ok(out.into_compile_output(source_doc)),
Err(parse_err) => {
tracing::warn!(
error = %parse_err,
raw_preview = %preview(&raw, 256),
"LlmPlanCompiler: first response did not parse; retrying with corrective prompt"
);
let corrective = corrective_prompt(&prompt, &raw, &parse_err);
let retry_raw = self.callback.complete(corrective).await?;
match parse_llm_response(&retry_raw) {
Ok(out) => Ok(out.into_compile_output(source_doc)),
Err(retry_err) => {
tracing::warn!(
error = %retry_err,
raw_preview = %preview(&retry_raw, 256),
"LlmPlanCompiler: corrective retry still did not parse; falling back to structure-required question"
);
Ok(structure_required_fallback(
source_doc, &parse_err, &retry_err,
))
}
}
}
}
}
}
impl<C: LlmCallback + 'static> PlanCompiler for LlmPlanCompiler<C> {
async fn compile_prose(&self, prose: String, project: String) -> Result<CompileOutput> {
let prompt = build_compile_prose_prompt(&prose, &project);
self.invoke(prompt, &prose).await
}
async fn apply_answers(
&self,
snapshot: PlanDraftSnapshot,
answers: Vec<(String, Answer)>,
defer_remaining: bool,
) -> Result<CompileOutput> {
let source_doc = snapshot.source_doc.clone().unwrap_or_default();
let prompt = build_apply_answers_prompt(&snapshot, &answers, defer_remaining);
self.invoke(prompt, &source_doc).await
}
async fn refine(&self, snapshot: PlanDraftSnapshot, feedback: String) -> Result<CompileOutput> {
let source_doc = snapshot.source_doc.clone().unwrap_or_default();
let prompt = build_refine_prompt(&snapshot, &feedback);
self.invoke(prompt, &source_doc).await
}
}
// ---------------------------------------------------------------------------
// LLM JSON wire types
// ---------------------------------------------------------------------------
/// JSON shape we ask the model to produce. Mirrors [`CompileOutput`] but
/// wire-friendlier:
///
/// * `definition` is `null` when questions remain.
/// * `decisions` (auto-fills) and `open_questions` are always present
/// as empty arrays rather than omitted, so the parser can validate
/// without a `serde(default)` per field.
///
/// The schema is documented inline in [`json_schema_string`] -- that
/// constant is what the prompts hand the model so the wire shape and
/// the parser stay in lockstep.
#[derive(Debug, Deserialize)]
struct LlmCompileResponse {
#[serde(default)]
plan_name: Option<String>,
#[serde(default)]
open_questions: Vec<LlmOpenQuestion>,
#[serde(default)]
decisions: Vec<LlmDecision>,
#[serde(default)]
definition: Option<LlmDefinition>,
}
#[derive(Debug, Deserialize)]
struct LlmOpenQuestion {
id: String,
prompt: String,
#[serde(default)]
rationale: String,
#[serde(default)]
options: Vec<LlmOption>,
#[serde(default)]
allow_explain_more: bool,
#[serde(default)]
allow_none: bool,
#[serde(default)]
depends_on_decisions: Vec<String>,
}
#[derive(Debug, Deserialize)]
struct LlmOption {
id: String,
label: String,
#[serde(default)]
rationale: String,
}
#[derive(Debug, Deserialize)]
struct LlmDecision {
question_id: String,
chosen_option_id: String,
#[serde(default)]
depends_on_decisions: Vec<String>,
/// Defaults to true on the wire because every decision the LLM
/// emits is by definition a compiler-driven fill (the user-driven
/// decisions are recorded by the handler before invocation). We
/// still allow the model to explicitly mark `auto = false` for a
/// caller who wants to record an "I would have picked this even if
/// you'd asked" rationale; the executor doesn't currently
/// distinguish, but the audit trail does.
#[serde(default = "default_auto")]
auto: bool,
}
const fn default_auto() -> bool {
true
}
#[derive(Debug, Deserialize)]
struct LlmDefinition {
#[serde(default)]
name: Option<String>,
steps: Vec<LlmStep>,
}
#[derive(Debug, Deserialize)]
struct LlmStep {
id: String,
#[serde(alias = "agent")]
agent_type: String,
prompt: String,
#[serde(default)]
depends_on: Vec<String>,
#[serde(default)]
timeout_secs: Option<u64>,
#[serde(default)]
retry_count: u32,
}
impl LlmCompileResponse {
/// Project the wire shape into a [`CompileOutput`] using
/// `source_doc` for the source-of-truth prose. Validates the
/// definition / question invariants of [`PlanCompiler`].
///
/// We deliberately only run *local* invariants here -- full DAG
/// validation (`validate_plan`) runs later in the executor when the
/// definition is materialised, so we don't duplicate that logic.
fn into_compile_output(self, source_doc: &str) -> CompileOutput {
// Hard contract per `PlanCompiler`: definition.is_some() iff
// open_questions.is_empty(). If the model produced both, the
// open_questions win -- the user has more clarifications to do
// and the partial definition can't be trusted.
let drop_definition = !self.open_questions.is_empty();
let definition = if drop_definition {
None
} else {
self.definition.map(|d| d.into_definition(self.plan_name))
};
CompileOutput {
source_doc: source_doc.to_string(),
open_questions: self
.open_questions
.into_iter()
.map(LlmOpenQuestion::into_open_question)
.collect(),
new_decisions: self
.decisions
.into_iter()
.map(LlmDecision::into_decision_record)
.collect(),
definition,
}
}
}
impl LlmOpenQuestion {
fn into_open_question(self) -> OpenQuestion {
OpenQuestion {
id: self.id,
prompt: self.prompt,
rationale: self.rationale,
options: self
.options
.into_iter()
.map(|o| QuestionOption {
id: o.id,
label: o.label,
rationale: o.rationale,
})
.collect(),
allow_explain_more: self.allow_explain_more,
allow_none: self.allow_none,
depends_on_decisions: self.depends_on_decisions,
}
}
}
impl LlmDecision {
fn into_decision_record(self) -> DecisionRecord {
// We use `now()` for the timestamp because the wire shape doesn't
// carry one -- the model can't possibly produce a meaningful
// `decided_at`, and the handler/executor isn't in a position to
// override it. This means the audit trail records the "compile
// round when this auto-fill happened", which is exactly what a
// human reviewer wants.
DecisionRecord {
question_id: self.question_id,
chosen_option_id: self.chosen_option_id,
depends_on_decisions: self.depends_on_decisions,
auto: self.auto,
decided_at: chrono::Utc::now(),
}
}
}
impl LlmDefinition {
fn into_definition(self, top_level_name: Option<String>) -> PlanDefinition {
PlanDefinition {
name: self
.name
.or(top_level_name)
.unwrap_or_else(|| "prose-plan".to_string()),
project: None,
project_root: None,
steps: self
.steps
.into_iter()
.map(|s| StepDefinition {
id: s.id,
agent_type: s.agent_type,
prompt: s.prompt,
depends_on: s.depends_on,
timeout_secs: s.timeout_secs,
retry_count: s.retry_count,
})
.collect(),
}
}
}
// ---------------------------------------------------------------------------
// Prompt assembly
// ---------------------------------------------------------------------------
/// Wire-shape JSON the model must emit. Embedded into every prompt.
///
/// We deliberately use a hand-rolled "shape doc" string rather than a
/// machine-readable JSON Schema:
///
/// 1. JSON Schema enforcement isn't available across all backends we
/// plan to target (`mlx_lm.server` in particular).
/// 2. A tightly scoped natural-language schema with a worked example
/// has empirically been the most reliable way to get small/mid
/// models to produce parseable JSON on the first try.
///
/// Keep this string and the `LlmCompileResponse` wire types in lockstep
/// -- the parse-error diagnostics here are the sole runtime check.
fn json_schema_string() -> &'static str {
r#"You must reply with a single JSON object matching this exact shape:
{
"plan_name": "string | null // optional human label, falls back to 'prose-plan'",
"open_questions": [ // empty array when the plan is ready to compile
{
"id": "stable-snake_case-id, used as the invalidation handle across rounds",
"prompt": "the question text shown to the user",
"rationale": "why this question matters; 1-3 sentences",
"options": [
{ "id": "snake_case", "label": "short label", "rationale": "trade-off, 1-2 sentences" }
],
"allow_explain_more": false,
"allow_none": false,
"depends_on_decisions": ["question_id_of_a_resolved_dependency"]
}
],
"decisions": [ // empty array unless you are auto-filling answers
{
"question_id": "matches one of the questions you would have asked",
"chosen_option_id": "matches that question's option id",
"depends_on_decisions": [],
"auto": true
}
],
"definition": null // OR an object when open_questions is empty:
// {
// "name": "optional, overrides plan_name",
// "steps": [
// {
// "id": "snake_case-step-id",
// "agent_type": "rust-engineer | tester | reviewer | ...",
// "prompt": "what this agent should do",
// "depends_on": ["other_step_id"],
// "timeout_secs": null,
// "retry_count": 0
// }
// ]
// }
}
Strict rules:
- Output ONE JSON object, no leading/trailing prose, no markdown fences.
- "definition" must be null whenever "open_questions" is non-empty.
- "definition" must be a valid object whenever "open_questions" is empty.
- Reuse question ids across rounds when refining the same concern.
- Never refer to a step or decision id you didn't declare in this same response.
- Prefer snake_case for ids (`my_step`, `lib_choice`); kebab-case (`my-step`)
is normalised to snake_case server-side for backwards compatibility with
earlier rounds, so do not mix the two within one response."#
}
fn build_compile_prose_prompt(prose: &str, project: &str) -> String {
format!(
"{schema}\n\n\
You are compiling a fresh prose plan into either an executable DAG \
or a list of clarification questions.\n\n\
Project: {project}\n\n\
Prose plan to compile:\n```\n{prose}\n```\n\n\
If the prose is unambiguous, emit a `definition` with no questions. \
If material decisions are missing (library choice, architectural fork, \
scope ambiguity), emit `open_questions` instead. Cap at 5 questions per \
round; surface the highest-impact ones first.",
schema = json_schema_string(),
)
}
fn build_apply_answers_prompt(
snapshot: &PlanDraftSnapshot,
answers: &[(String, Answer)],
defer_remaining: bool,
) -> String {
let source_doc = snapshot.source_doc.as_deref().unwrap_or("");
let answers_block = render_answers_block(answers);
let still_open_block = render_open_questions_block(&snapshot.open_questions);
let prior_decisions_block = render_decisions_block(&snapshot.decisions);
let defer_clause = if defer_remaining {
"The user has asked you to FILL IN best-effort answers for any still-open \
questions rather than asking another round. For every still-open question \
that you do not surface again, append a `decisions` entry with `auto: true` \
and your best-guess option. Avoid emitting open_questions in this mode \
unless a question raises a brand-new concern that the user must see."
} else {
"Surface only follow-up questions that are still material after applying \
these answers. Drop any prior question whose answer is now implied."
};
format!(
"{schema}\n\n\
You are advancing an in-flight plan after the user submitted answers.\n\n\
Project: {project}\n\
Plan name: {plan_name}\n\n\
Original prose:\n```\n{source_doc}\n```\n\n\
Prior decisions (already recorded; do not re-emit):\n{prior_decisions}\n\n\
Still-open questions before this round:\n{still_open}\n\n\
User-submitted answers this round:\n{answers}\n\n\
{defer_clause}",
schema = json_schema_string(),
project = snapshot.project,
plan_name = snapshot.plan_name,
prior_decisions = prior_decisions_block,
still_open = still_open_block,
answers = answers_block,
)
}
fn build_refine_prompt(snapshot: &PlanDraftSnapshot, feedback: &str) -> String {
let source_doc = snapshot.source_doc.as_deref().unwrap_or("");
let still_open_block = render_open_questions_block(&snapshot.open_questions);
let prior_decisions_block = render_decisions_block(&snapshot.decisions);
format!(
"{schema}\n\n\
You are applying a freeform refinement instruction to an in-flight plan.\n\n\
Project: {project}\n\
Plan name: {plan_name}\n\n\
Original prose:\n```\n{source_doc}\n```\n\n\
Prior decisions:\n{prior_decisions}\n\n\
Still-open questions:\n{still_open}\n\n\
Refinement instruction:\n```\n{feedback}\n```\n\n\
If the refinement raises new architectural concerns, you may RE-OPEN \
questions (including ones whose decisions are now stale -- include a \
`decisions` entry referring to the same question_id only if you are \
keeping the prior choice). Otherwise, emit a fresh `definition` \
reflecting the refined intent.",
schema = json_schema_string(),
project = snapshot.project,
plan_name = snapshot.plan_name,
prior_decisions = prior_decisions_block,
still_open = still_open_block,
)
}
fn render_answers_block(answers: &[(String, Answer)]) -> String {
if answers.is_empty() {
return "(none -- the user passed an empty answer list)".into();
}
let mut out = String::new();
for (qid, a) in answers {
// `writeln!` into a String never fails; the `let _ =` discards
// the impossible Err arm without dragging in `unwrap()`.
match a {
Answer::Choose { option_id } => {
let _ = writeln!(out, "- {qid}: choose `{option_id}`");
}
Answer::ExplainMore { note } => {
let _ = writeln!(out, "- {qid}: explain_more (user note: {note:?})");
}
Answer::NoneOfThese => {
let _ = writeln!(out, "- {qid}: none_of_these (propose new options)");
}
}
}
out
}
fn render_open_questions_block(qs: &[OpenQuestion]) -> String {
if qs.is_empty() {
return "(none)".into();
}
let mut out = String::new();
for q in qs {
let _ = writeln!(out, "- {} ({}): {}", q.id, q.prompt, q.rationale);
for opt in &q.options {
let _ = writeln!(out, " * {} -- {} ({})", opt.id, opt.label, opt.rationale);
}
}
out
}
fn render_decisions_block(ds: &[DecisionRecord]) -> String {
if ds.is_empty() {
return "(none)".into();
}
let mut out = String::new();
for d in ds {
let tag = if d.auto { " [auto]" } else { "" };
let _ = writeln!(
out,
"- {}: chose `{}`{tag}",
d.question_id, d.chosen_option_id
);
}
out
}
// ---------------------------------------------------------------------------
// Response parsing + corrective retry
// ---------------------------------------------------------------------------
/// Try hard to parse `raw` as one of our wire shapes.
///
/// Strategy:
/// 1. Strip leading/trailing whitespace.
/// 2. Strip markdown code fences (```json ... ``` and ``` ... ```).
/// 3. Best-effort: locate the first `{` and the matching `}` and try
/// that substring as JSON. This handles the "model added a polite
/// sentence before the JSON" failure mode.
///
/// Returns a structured `LlmCompileResponse` on success, or a
/// human-readable diagnostic string on failure (which the caller embeds
/// in the corrective prompt).
fn parse_llm_response(raw: &str) -> std::result::Result<LlmCompileResponse, String> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err("response was empty".into());
}