rhei-cli 0.3.0

Command-line driver for the Rhei agent runtime.
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
/// Parsed task-state value from markdown, optionally carrying an explicit visit suffix.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedTaskState {
    /// Canonical state name defined in the state machine.
    pub state: String,
    /// Explicit visit count encoded in markdown as `<state>-<n>`.
    pub visit: Option<u32>,
}

/// Parse a markdown task-state value against a state machine.
///
/// Exact state names take precedence. If the raw value is not an exact state
/// match, Rhei interprets a trailing `-<n>` suffix as a counted-loop visit when
/// the prefix is a valid state name.
pub fn parse_task_state(raw: &str, machine: &StateMachine) -> ParsedTaskState {
    if machine.is_valid_state(raw) {
        return ParsedTaskState { state: raw.to_string(), visit: None };
    }

    if let Some((base, visit_text)) = raw.rsplit_once('-') {
        if let Ok(visit) = visit_text.parse::<u32>() {
            if machine.is_valid_state(base) {
                return ParsedTaskState { state: base.to_string(), visit: Some(visit) };
            }
        }
    }

    ParsedTaskState { state: raw.to_string(), visit: None }
}

// ========================================
// Semantic Validator (Task 5)
// ========================================

/// The state machines governing one loaded plan: the project default plus the
/// machine of every rhei that declared its own `**States:**`. A ticket's
/// machine resolves through its owning rhei — the leading segment of its
/// project-qualified id.
// §DA-per-rhei-state-machines §AR-rhei-panta.4
#[derive(Debug, Clone)]
pub struct MachineSet {
    /// The project default: the manifest declaration or the built-in machine.
    pub default: StateMachine,
    /// Machines of self-declaring rheis, keyed by rhei id.
    pub per_rhei: BTreeMap<String, StateMachine>,
}

impl MachineSet {
    /// A set with no self-declaring rheis — the single-machine case every
    /// pre-existing entry point still speaks.
    pub fn single(machine: StateMachine) -> Self {
        Self { default: machine, per_rhei: BTreeMap::new() }
    }

    /// The machine governing `id`: its owning rhei's declared machine when
    /// there is one, the project default otherwise.
    pub fn for_task(&self, id: &TaskId) -> &StateMachine {
        if let Some(TaskIdSegment::Named(rhei)) = id.segments.first() {
            if let Some(machine) = self.per_rhei.get(rhei) {
                return machine;
            }
        }
        &self.default
    }

    /// [`for_task`](Self::for_task) over a rendered qualified id (`auth.1`).
    pub fn for_task_str(&self, task_id: &str) -> &StateMachine {
        let rhei_id = task_id.split('.').next().unwrap_or(task_id);
        self.per_rhei.get(rhei_id).unwrap_or(&self.default)
    }

    /// Every distinct machine in the set, default first. Distinctness is
    /// content identity, not name: two same-named machines that differ in any
    /// field are two machines. [`StateMachine::fingerprint`] explains why.
    pub fn distinct(&self) -> Vec<&StateMachine> {
        let mut seen: HashSet<String> = HashSet::new();
        let mut out = vec![&self.default];
        seen.insert(self.default.fingerprint());
        for machine in self.per_rhei.values() {
            if seen.insert(machine.fingerprint()) {
                out.push(machine);
            }
        }
        out
    }

    /// Whether one machine governs everything in scope.
    pub fn is_single(&self) -> bool {
        self.distinct().len() == 1
    }
}

/// Validator configured with the [`MachineSet`] of a loaded plan.
pub struct Validator {
    machines: MachineSet,
}

impl Validator {
    /// Create a validator that will use `machine` for allowed-state checks.
    pub fn new(machine: StateMachine) -> Self {
        Self { machines: MachineSet::single(machine) }
    }

    /// Create a validator over a full per-rhei machine set.
    pub fn with_machines(machines: MachineSet) -> Self {
        Self { machines }
    }

    /// Validate a parsed rhei using the currently configured states.
    ///
    /// This does not check markdown link targets (no file-system context).
    /// Use [`validate_with_base`](Self::validate_with_base) to also verify links.
    pub fn validate(&self, rhei: &Rhei) -> ValidationReport {
        self.validate_with_base(rhei, None)
    }

    /// Validate a parsed rhei, optionally resolving markdown links relative
    /// to `base_path` (the directory containing the plan file).
    pub fn validate_with_base(&self, rhei: &Rhei, base_path: Option<&Path>) -> ValidationReport {
        let mut report = ValidationReport::ok();

        let index = build_task_index(rhei);
        for machine in self.machines.distinct() {
            validate_node_policy_against_structure(machine, &rhei.structure, &mut report);
            validate_state_machine_warnings(machine, &mut report);
        }
        validate_sibling_uniqueness(rhei, &mut report);
        validate_dependency_integrity(rhei, &index, &mut report);
        validate_prior_order_coherence(rhei, &index, &self.machines, &mut report);
        validate_state_consistency(rhei, &self.machines, &mut report);
        validate_task_execution_overrides(rhei, &self.machines, &mut report);
        validate_terminal_tree_coherence(rhei, &self.machines, &mut report);
        validate_circular_dependencies(rhei, &index, &mut report);
        validate_assignee_nonempty(rhei, &mut report);
        validate_result_blocks(rhei, &self.machines, &mut report);

        if let Some(base) = base_path {
            validate_markdown_links(rhei, base, &mut report);
        }

        report
    }
}

/// Validate a parsed rhei using an already-loaded [`StateMachine`].
pub fn validate_with_machine(rhei: &Rhei, machine: &StateMachine) -> ValidationReport {
    Validator::new(machine.clone()).validate(rhei)
}

/// Validate a parsed rhei whose rheis may run under their own machines.
/// §DA-per-rhei-state-machines
pub fn validate_with_machine_set(rhei: &Rhei, machines: &MachineSet) -> ValidationReport {
    Validator::with_machines(machines.clone()).validate(rhei)
}

/// Validate with a per-rhei machine set and per-task markdown link bases.
/// §AR-rhei-panta.5 §DA-per-rhei-state-machines
pub fn validate_with_machine_set_and_link_bases(
    rhei: &Rhei,
    machines: &MachineSet,
    default_base: &Path,
    task_bases: &HashMap<String, PathBuf>,
    section_bases: &[PathBuf],
) -> ValidationReport {
    let mut report = Validator::with_machines(machines.clone()).validate_with_base(rhei, None);
    validate_markdown_links_with_task_bases(rhei, default_base, task_bases, section_bases, &mut report);
    report
}

/// Validate a parsed rhei using an already-loaded [`StateMachine`], resolving
/// markdown links relative to `base_path`.
pub fn validate_with_machine_and_base(
    rhei: &Rhei,
    machine: &StateMachine,
    base_path: &Path,
) -> ValidationReport {
    Validator::new(machine.clone()).validate_with_base(rhei, Some(base_path))
}

/// Validate a parsed rhei using per-task markdown link bases. §AR-rhei-panta.5
pub fn validate_with_machine_and_link_bases(
    rhei: &Rhei,
    machine: &StateMachine,
    default_base: &Path,
    task_bases: &HashMap<String, PathBuf>,
    section_bases: &[PathBuf],
) -> ValidationReport {
    let mut report = Validator::new(machine.clone()).validate_with_base(rhei, None);
    validate_markdown_links_with_task_bases(rhei, default_base, task_bases, section_bases, &mut report);
    report
}

/// Load a [`StateMachine`] from `machine_path` and validate a parsed rhei.
pub fn validate_from_machine_file<P: AsRef<Path>>(
    rhei: &Rhei,
    machine_path: P,
) -> Result<ValidationReport, StateMachineLoadError> {
    let machine = StateMachine::from_yaml_file(machine_path)?;
    Ok(Validator::new(machine).validate(rhei))
}

// ---------------------------
// Validation helpers
// ---------------------------

fn build_task_index(rhei: &Rhei) -> HashMap<TaskId, &Task> {
    fn visit<'a>(task: &'a Task, map: &mut HashMap<TaskId, &'a Task>) {
        map.insert(task.id.clone(), task);
        for child in &task.children {
            visit(child, map);
        }
    }
    let mut map = HashMap::new();
    for t in &rhei.tasks {
        visit(t, &mut map);
    }
    map
}

// §FS-rhei-states.9.3: Validate node policy selectors against plan structure.

/// Validate the plan-dependent parts of `node_policy`: by-type keys and
/// override selectors are checked against the current plan's
/// `structure.nodeKinds` and `structure.maxLevels`.
fn validate_node_policy_against_structure(
    machine: &StateMachine,
    structure: &Structure,
    report: &mut ValidationReport,
) {
    let Some(policy) = machine.node_policy.as_ref() else {
        return;
    };

    // A project's structure is merged from every rhei in it, so naming the
    // merged set inside an error blames an unrelated create for changing it.
    // §FS-rhei-new.5.2
    for kind in policy.by_type.keys() {
        if !structure.accepts_kind(kind) {
            report.errors.push(format!(
                "node_policy.by_type references node kind '{kind}', which the plan structure does not declare"
            ));
            report.help.push(format!(
                "node_policy.by_type '{kind}': the plan structure declares nodeKinds {:?}.",
                structure.node_kinds
            ));
        }
    }

    for (idx, ov) in policy.overrides.iter().enumerate() {
        if let Some(node_type) = ov.match_.node_type.as_deref() {
            if !structure.accepts_kind(node_type) {
                report.errors.push(format!(
                    "node_policy.overrides[{idx}].match.type references node kind '{node_type}', which the plan structure does not declare"
                ));
                report.help.push(format!(
                    "node_policy.overrides[{idx}].match.type '{node_type}': the plan structure declares nodeKinds {:?}.",
                    structure.node_kinds
                ));
            }
        }
        if let Some(level) = ov.match_.level {
            if level == 0 || level > structure.max_levels {
                report.errors.push(format!(
                    "node_policy.overrides[{idx}].match.level is {level}, which is outside the levels this plan structure allows"
                ));
                report.help.push(format!(
                    "node_policy.overrides[{idx}].match.level: levels must be in 1..={} for this plan structure.",
                    structure.max_levels
                ));
            }
        }
    }
}

/// Call `f` for every node in the tree, depth-first.
fn for_each_node<'a>(rhei: &'a Rhei, mut f: impl FnMut(&'a Task)) {
    fn recurse<'a>(task: &'a Task, f: &mut impl FnMut(&'a Task)) {
        f(task);
        for child in &task.children {
            recurse(child, f);
        }
    }
    for t in &rhei.tasks {
        recurse(t, &mut f);
    }
}

fn validate_state_consistency(rhei: &Rhei, machines: &MachineSet, report: &mut ValidationReport) {
    for_each_node(rhei, |task| {
        let machine = machines.for_task(&task.id);
        let kind_label = title_case_kind(&task.kind);
        let subject = format!("{} {}", kind_label, task.id);
        validate_task_state_instance(&subject, &task.state, machine, report);
        validate_task_state_against_profile(
            &subject,
            &task.state,
            task.kind.as_str(),
            task.profile_level(),
            machine,
            report,
        );
    });
}

fn validate_task_execution_overrides(
    rhei: &Rhei,
    machines: &MachineSet,
    report: &mut ValidationReport,
) {
    // §FS-rhei-plan-language.3.11: Task execution override validation.
    for_each_node(rhei, |task| {
        let machine = machines.for_task(&task.id);
        let declared_models: HashSet<&str> = machine.models.iter().map(String::as_str).collect();
        let subject = format!("{} {}", title_case_kind(&task.kind), task.id);
        let has_model = task.model.is_some();
        let has_target = task.target.is_some();
        if has_model && has_target {
            report.errors.push(format!(
                "{} declares both **Model:** and **Target:**; task execution overrides are mutually exclusive",
                subject
            ));
        }

        if let Some(model) = task.model.as_deref() {
            let trimmed = model.trim();
            if trimmed.is_empty() {
                report.errors.push(format!("{} declares an empty **Model:** override", subject));
            } else if !declared_models.contains(trimmed) {
                report.errors.push(format!(
                    "{} declares **Model:** '{}' but the active state machine does not declare that model",
                    subject, trimmed
                ));
            }
        }

        if let Some(target) = task.target.as_deref() {
            let trimmed = target.trim();
            if trimmed.is_empty() {
                report.errors.push(format!("{} declares an empty **Target:** override", subject));
            } else if let Err(err) = parse_execution_target(trimmed) {
                report.errors.push(format!(
                    "{} declares invalid **Target:** '{}': {}",
                    subject, trimmed, err
                ));
            }
        }

        if !has_model && !has_target {
            return;
        }

        let parsed = parse_task_state(&task.state, machine);
        let Some(state_def) = machine.states.get(&parsed.state) else {
            return;
        };
        if !state_def.all_targets.is_empty() || !state_def.all_models.is_empty() {
            report.errors.push(format!(
                "{} declares a task execution override but state '{}' is a fanout state",
                subject, parsed.state
            ));
        }
        if state_def.target_locked {
            report.errors.push(format!(
                "{} declares a task execution override but state '{}' has target_locked: true",
                subject, parsed.state
            ));
        }
    });
}

fn title_case_kind(kind: &str) -> String {
    let mut out = String::with_capacity(kind.len());
    let mut chars = kind.chars();
    if let Some(first) = chars.next() {
        for c in first.to_uppercase() {
            out.push(c);
        }
    }
    for c in chars {
        out.push(c);
    }
    out
}

/// Enforce that the authored state (ignoring any `-<visit>` suffix) is a
/// member of the resolved profile's `allowed` set. No-op when the machine
/// declares no `profiles` / `node_policy`.
fn validate_task_state_against_profile(
    subject: &str,
    raw_state: &str,
    kind: &str,
    level: u8,
    machine: &StateMachine,
    report: &mut ValidationReport,
) {
    let Some(profile) = machine.profile_for_node(kind, level) else {
        return;
    };

    let parsed = parse_task_state(raw_state, machine);
    if !machine.is_valid_state(&parsed.state) {
        // `validate_task_state_instance` already reported the invalid state.
        return;
    }

    if !profile.allowed.iter().any(|s| s == &parsed.state) {
        let allowed = profile.allowed.join(", ");
        report.errors.push(format!(
            "{} has state '{}' which is not allowed by its resolved profile. Profile allows: [{}]",
            subject, parsed.state, allowed
        ));
    }
}

fn validate_task_state_instance(
    subject: &str,
    raw_state: &str,
    machine: &StateMachine,
    report: &mut ValidationReport,
) {
    let parsed = parse_task_state(raw_state, machine);
    if !machine.is_valid_state(&parsed.state) {
        let allowed = machine.allowed_states().collect::<Vec<_>>().join(", ");
        report
            .errors
            .push(format!("{} has invalid state '{}'. Allowed: [{}]", subject, raw_state, allowed));
        return;
    }

    let Some(visit) = parsed.visit else {
        return;
    };

    if visit <= 1 {
        report.errors.push(format!(
            "{} has invalid counted state '{}'. Visit suffix '-1' is not allowed; omit the suffix for the first visit.",
            subject, raw_state
        ));
        return;
    }

    let state_def = &machine.states[&parsed.state];
    let Some(limit) = state_def.visits else {
        report.errors.push(format!(
            "{} has invalid counted state '{}'. State '{}' does not declare 'visits'.",
            subject, raw_state, parsed.state
        ));
        return;
    };

    if visit > limit {
        report.errors.push(format!(
            "{} has invalid counted state '{}'. Visit {} exceeds the declared limit {} for state '{}'.",
            subject, raw_state, visit, limit, parsed.state
        ));
    }
}