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
//! The SM decision protocol — structured-text (ReAct-style) action blocks (§3.4).
//!
//! Why: the SM's [`LlmProvider`](crate::core::sm::providers::LlmProvider) surface
//! is non-streaming `complete()` returning TEXT only — it has NO tool/function
//! calling (the provider trait deliberately omits the tool-call shape, see
//! `providers/mod.rs::ChatMessage`). So the §3.4 delegation loop cannot rely on
//! native tool calls; instead the SM emits a STRUCTURED-TEXT decision — a single
//! JSON action block — which the delegation engine ([`super`]) parses and
//! EXECUTES against the session-control + goal surfaces. This is the
//! deterministic, provider-agnostic decision protocol the spec's "verbs the SM
//! calls" (§4.2/SM_TOOLS) maps onto when the provider is text-only. Parsing is
//! lenient (the model may wrap the JSON in prose or a ```json fence) but the
//! resulting action is a strict, typed enum so the engine never interprets free
//! text as an instruction.
//! What: [`SmDecision`] — the closed set of actions the SM may emit at the
//! DECOMPOSE step (`delegate` to launch session-sized tasks, `respond` to talk
//! to the operator, or `do_work` — a PROHIBITION-violating direct-work attempt
//! the engine refuses and redirects, §3.2 SP1–SP5); [`TaskSpec`] — one
//! session-sized task; and [`parse_decision`] — the lenient JSON extractor.
//! Test: `decision_tests.rs` covers fenced/bare/prose-wrapped JSON, each action
//! variant, the empty-tasks guard, and the malformed-input fallback.
use ;
/// One session-sized task the SM decomposed a goal into (§3.4 DECOMPOSE).
///
/// Why: DECOMPOSE splits a goal into one-or-many tasks, each of which becomes
/// exactly ONE launched session (§3.4: "one task → one launched session"). A task
/// carries everything LAUNCH needs: the working directory/repo, the prompt the
/// session executes, and an optional model/runtime selector.
/// What: `workdir` (required — the repo/dir the session runs against, mapped to
/// the launch `workdir`), `prompt` (required — the task the session performs,
/// DELIVERED to the session per #1299), and an optional `model` selector.
/// Test: `decision_tests.rs::parse_delegate_with_tasks`.
/// The closed set of decisions the SM may emit at the DECOMPOSE step (§3.4).
///
/// Why: the engine must NEVER interpret free model text as an instruction — that
/// is how a prohibition (SP5: "answer a work question from your own knowledge")
/// sneaks in. Constraining the SM's decision to this typed enum means the only
/// thing it can ask the engine to do is delegate (launch sessions), talk to the
/// operator, or — explicitly — attempt direct work, which the engine REFUSES and
/// redirects (§3.2). Anything unparseable degrades to [`SmDecision::Respond`]
/// (talk to the operator) — never to silently doing work.
/// What: `Delegate { tasks }` launches one session per [`TaskSpec`];
/// `Respond { message }` is an Allowlist-1 operator-facing reply (triage/status/
/// clarification); `DoWork { summary }` is a flagged direct-work attempt the
/// engine converts into a delegation refusal (the SP guard).
/// Test: `decision_tests.rs` — every variant + the lenient/fallback parses.
/// The opening fence/marker the SM may wrap its decision JSON in.
const JSON_FENCE: &str = "```json";
/// A generic code fence the SM may use instead of the `json`-tagged one.
const BARE_FENCE: &str = "```";
/// Parse the SM's reply text into a typed [`SmDecision`] (lenient extraction).
///
/// Why: the model returns TEXT (no tool calls), and may wrap its JSON action
/// block in a ```json fence or surround it with prose. The engine must extract
/// the action robustly but NEVER guess: if no valid action object is found, the
/// safe fallback is to treat the whole reply as an operator-facing message
/// ([`SmDecision::Respond`]) — the SM is talking, not delegating — rather than
/// inventing a delegation or (worse) doing work. This keeps an unparseable reply
/// on the always-safe Allowlist-1 path.
/// What: (1) if a ```json / ``` fenced block is present, extracts its inner
/// content (matching opening→closing fence); (2) otherwise (or if the fenced inner
/// is not an object) runs a BALANCED-BRACE scan from the first `{` that respects
/// JSON string literals, yielding the first complete top-level object regardless of
/// surrounding/trailing prose braces; (3) attempts to deserialize that candidate as
/// [`SmDecision`]; (4) on any failure returns `Respond { message: <trimmed original> }`.
/// Test: `decision_tests.rs::parse_fenced_json`, `parse_bare_json`,
/// `parse_prose_wrapped_json`, `parse_garbage_is_respond`, `parse_do_work_action`,
/// `parse_both_json_and_bare_fence`, `parse_prose_brace_after_json`,
/// `parse_prose_brace_before_json`, `parse_brace_inside_string_value`.
/// Collect candidate JSON-object spans from the SM's reply, best-first.
///
/// Why: the prior extractor was fragile in two ways the review flagged: (1) the
/// `[JSON_FENCE, BARE_FENCE]` ordering made `BARE_FENCE` re-match a ```json
/// opening as a bare fence and mishandled a reply with BOTH a ```json block AND a
/// later ``` block; and (2) the `first '{' ..= last '}'` span grabbed a WRONG span
/// whenever prose braces surrounded the JSON (e.g. `{...} see {docs}` →
/// `rfind('}')` captured the prose brace → truncated JSON → a spurious `Respond`
/// fallback that silently dropped an intended `Delegate`). Both are now robust.
/// What: returns, in priority order, (1) the first balanced object found INSIDE a
/// ```json (or bare ```) fenced block — the `json` tag is consumed as part of the
/// opening fence so it is never re-read as a bare fence; then (2) successive
/// complete top-level `{ … }` objects scanned over the whole text, each found by a
/// BALANCED-BRACE walk that RESPECTS JSON string literals + escapes (so braces
/// inside strings and prose braces before/after the object do not corrupt the
/// span). The caller deserializes each in turn and keeps the first valid action.
/// Test: exercised via `parse_decision` in `decision_tests.rs`
/// (`parse_both_json_and_bare_fence`, `parse_prose_brace_after_json`,
/// `parse_prose_brace_before_json`, `parse_brace_inside_string_value`, plus the
/// existing fenced/bare/prose/garbage cases).
/// Return the inner content of the first fenced code block, if any.
///
/// Why: isolates fence handling so [`candidate_objects`] stays readable, and so
/// a ```json opening is matched exactly once (the `json` tag is part of the
/// opening, never re-read as a separate bare fence).
/// What: finds a ```json opening if present (else a bare ```), skips to the end of
/// that line (so the opening fence + optional language tag is fully consumed), then
/// returns the substring up to the next ``` closing fence (or end of text if the
/// block is unterminated). Returns `None` when there is no opening fence.
/// Test: exercised via `parse_decision` (`parse_fenced_json`, `parse_bare_json`,
/// `parse_both_json_and_bare_fence`).
/// Return the first COMPLETE top-level JSON object in `text` (balanced scan).
///
/// Why: convenience wrapper for callers (the fenced-inner path) that only need the
/// first object and not the continuation offset.
/// What: returns the object span from [`next_balanced_object`] starting at 0.
/// Test: exercised via `parse_decision` (`parse_fenced_json`, `parse_bare_json`).
/// Find the next COMPLETE top-level `{ … }` object at or after `from`.
///
/// Why: a naive `first '{' ..= last '}'` span breaks when prose braces appear
/// before or after the JSON object, or when braces appear inside a JSON string
/// value. A depth-tracking scan that honours JSON string literals + escapes finds
/// each well-formed top-level object in turn, so the caller can try successive
/// candidates (skipping a leading prose `{…}` that is not a valid action).
/// What: from the first `{` at/after `from`, increments depth on `{` and
/// decrements on `}`, but ONLY when NOT inside a string literal (a `"` toggles
/// string mode; a `\` inside a string escapes the next char so an escaped quote
/// does not end the string). Returns `(object_span, end_offset)` the moment depth
/// returns to zero, where `end_offset` is the absolute index just past the closing
/// `}` (so a follow-up call can resume there). Returns `None` if there is no `{`
/// at/after `from` or the object never closes.
/// Test: `parse_prose_brace_after_json`, `parse_prose_brace_before_json`,
/// `parse_brace_inside_string_value`, `parse_escaped_quote_in_string`.