orion-server 1.5.1

Turn business logic into live REST/Kafka services, declared as JSON
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
//! Rules whose finding is "this workflow cannot behave as written".
//!
//! Each one names its proof and its exclusions in `explain()`, which is the
//! text `--explain` prints and the contract the rule's `quiet` fixture
//! writes down.

use std::collections::BTreeSet;

use serde_json::Value;

use super::{list_ids, walk_values};
use crate::definitions::analysis::dataflow::{overlaps, reads};
use crate::definitions::analysis::{Analysis, StepKind, selection_context};
use crate::definitions::clippy::{Diagnostic, Group, Level, Rule, Scope};

// ============================================================
// correctness.workflow_never_matches
// ============================================================

pub struct WorkflowNeverMatches;

impl Rule for WorkflowNeverMatches {
    fn id(&self) -> &'static str {
        "correctness.workflow_never_matches"
    }
    fn group(&self) -> Group {
        Group::Correctness
    }
    fn level(&self) -> Level {
        Level::Deny
    }
    fn scope(&self) -> Scope {
        Scope::Workflow
    }
    fn summary(&self) -> &'static str {
        "the workflow-level condition is false for every request, so the workflow never runs"
    }
    fn explain(&self) -> &'static str {
        "A workflow's `condition` decides whether the workflow matches a request. It is \
         evaluated before any task runs, against a context in which `data` and `temp_data` \
         are empty objects — the request body is the *payload*, which only `parse_json` \
         brings into `data`. A condition that reads only `data`/`temp_data` therefore has \
         one possible result, and this rule asks the engine for it.\n\n\
         Proof: either the datalogic compiler folded the condition to a constant `false`/\
         `null` (`Logic::is_constant`), or every read is a literal path under `data` or \
         `temp_data` and the engine's own evaluator, run on exactly the selection-time \
         context, returns `false` or `null`.\n\n\
         Silent when: the condition reads `metadata` (populated at ingress, unknown \
         offline); it has a computed `val` or a read inside an element-scoped operator; \
         it uses `now`, `random` or `secret`; it reads the loop counter (written before \
         the first sweep); it evaluates to anything but exactly `false` or `null`.\n\n\
         Before:  \"condition\": { \"==\": [{ \"var\": \"data.type\" }, \"order\"] }\n\
         After:   \"condition\": true, and a task condition on `data.type` after `parse_json`."
    }

    fn check(&self, cx: &Analysis<'_>, out: &mut Vec<Diagnostic>) {
        for wf in &cx.workflows {
            let c = &wf.condition;
            if !c.compiles {
                continue;
            }
            let verdict = if let Some(constant) = &c.constant {
                if c.is_constant_falsy() {
                    Some(format!("`condition` is constant {constant}"))
                } else {
                    None
                }
            } else {
                if c.reads.uncertain() || c.nondeterministic() {
                    continue;
                }
                let only_empty_roots = c.reads.paths.iter().all(|p| {
                    (p == "data"
                        || p.starts_with("data.")
                        || p == "temp_data"
                        || p.starts_with("temp_data."))
                        && wf
                            .loop_counter
                            .as_deref()
                            .is_none_or(|counter| !overlaps(p, counter))
                });
                if !only_empty_roots {
                    continue;
                }
                match cx.evaluator.evaluate(&c.value, &selection_context()) {
                    Some(v @ (Value::Bool(false) | Value::Null)) => Some(format!(
                        "`condition` reads only `data`/`temp_data`, which are empty when the engine \
                         selects a workflow, and evaluates to {v} there"
                    )),
                    _ => None,
                }
            };
            if let Some(why) = verdict {
                out.push(
                    Diagnostic::on_workflow(
                        self,
                        cx,
                        wf,
                        Some("condition"),
                        format!("{why}; the workflow never matches a request"),
                    )
                    .with_remedy(
                        "a workflow condition can only branch on `metadata`; parse the payload in a \
                         task and put the test on a task or group condition",
                    ),
                );
            }
        }
    }
}

// ============================================================
// correctness.task_never_runs
// ============================================================

pub struct TaskNeverRuns;

impl Rule for TaskNeverRuns {
    fn id(&self) -> &'static str {
        "correctness.task_never_runs"
    }
    fn group(&self) -> Group {
        Group::Correctness
    }
    fn level(&self) -> Level {
        Level::Warn
    }
    fn scope(&self) -> Scope {
        Scope::Workflow
    }
    fn summary(&self) -> &'static str {
        "a step's condition folds to a constant false, so the step never runs"
    }
    fn explain(&self) -> &'static str {
        "A step whose `condition` the compiler folds to `false` or `null` is skipped on \
         every request.\n\n\
         Proof: `Logic::is_constant` — the datalogic compiler's own verdict that the \
         expression has no data dependency and what it folded to.\n\n\
         Silent when: the condition depends on any read at all, or folds to anything but \
         exactly `false` or `null`. A warning rather than an error: `\"condition\": false` is \
         a way to switch a step off deliberately."
    }

    fn check(&self, cx: &Analysis<'_>, out: &mut Vec<Diagnostic>) {
        for wf in &cx.workflows {
            for step in &wf.steps {
                if let Some(c) = &step.condition
                    && c.compiles
                    && c.is_constant_falsy()
                {
                    let constant = c.constant.as_ref().expect("constant");
                    out.push(
                        Diagnostic::on_workflow(
                            self,
                            cx,
                            wf,
                            Some(&format!("{}.condition", step.path)),
                            format!(
                                "`{}` has a condition that is constant {constant}, so it never runs",
                                step.id
                            ),
                        )
                        .with_remedy("remove the step, or the condition if it is meant to run"),
                    );
                }
            }
        }
    }
}

// ============================================================
// correctness.unreachable_step
// ============================================================

pub struct UnreachableStep;

impl Rule for UnreachableStep {
    fn id(&self) -> &'static str {
        "correctness.unreachable_step"
    }
    fn group(&self) -> Group {
        Group::Correctness
    }
    fn level(&self) -> Level {
        Level::Deny
    }
    fn scope(&self) -> Scope {
        Scope::Workflow
    }
    fn summary(&self) -> &'static str {
        "steps after an unconditional terminal step can never run"
    }
    fn explain(&self) -> &'static str {
        "A `terminal: true` step ends the workflow. When that step is certain to be reached \
         — no condition on it or on any enclosing group — everything after it in document \
         order is dead.\n\n\
         Proof: read from the dataflow-rs executor. A terminal *task* halts after it has \
         run, so it must be unconditional to be certain; a terminal *group* halts when its \
         span closes even if no member ran, so an unconditional group is certain whatever \
         its members do. A halt ends the whole workflow.\n\n\
         Silent when: the terminal step, or any group enclosing it, has a condition that \
         does not fold to `true`."
    }

    fn check(&self, cx: &Analysis<'_>, out: &mut Vec<Diagnostic>) {
        for wf in &cx.workflows {
            let Some(halt) = wf.steps.iter().position(|s| s.terminal && s.certain) else {
                continue;
            };
            let descends_from = |mut i: usize| {
                while let Some(p) = wf.steps[i].parent {
                    if p == halt {
                        return true;
                    }
                    i = p;
                }
                false
            };
            let unreachable: Vec<usize> = (halt + 1..wf.steps.len())
                .filter(|&i| !descends_from(i))
                // Report the outermost steps only; their members are implied.
                .filter(|&i| wf.steps[i].parent.is_none_or(|p| p <= halt))
                .collect();
            let Some(&first) = unreachable.first() else {
                continue;
            };
            let halting = &wf.steps[halt];
            let ids: Vec<&str> = unreachable
                .iter()
                .map(|&i| wf.steps[i].id.as_str())
                .collect();
            out.push(
                Diagnostic::on_workflow(
                    self,
                    cx,
                    wf,
                    Some(&wf.steps[first].path),
                    format!(
                        "`{}` ({}) is unconditional and terminal, so the workflow always ends there; \
                         {} can never run",
                        halting.id,
                        halting.path,
                        list_ids(&ids)
                    ),
                )
                .with_remedy("move the terminal step after them, give it a condition, or delete them"),
            );
        }
    }
}

// ============================================================
// correctness.unconditional_call_cycle
// ============================================================

pub struct UnconditionalCallCycle;

impl Rule for UnconditionalCallCycle {
    fn id(&self) -> &'static str {
        "correctness.unconditional_call_cycle"
    }
    fn group(&self) -> Group {
        Group::Correctness
    }
    fn level(&self) -> Level {
        Level::Deny
    }
    fn scope(&self) -> Scope {
        Scope::Set
    }
    fn summary(&self) -> &'static str {
        "channel_call edges that are all unconditional form a cycle, so every request into it fails at the depth limit"
    }
    fn explain(&self) -> &'static str {
        "`channel_call` runs another channel's workflow in-process. If workflow A always \
         calls a channel bound to workflow B, and B always calls back into A, every request \
         that reaches either recurses until `engine.max_channel_call_depth` and fails.\n\n\
         Proof: the static call graph — each `channel_call` with a literal `channel`, joined \
         to the set's channel → `workflow_id` binding — restricted to edges that are certain: \
         the calling task has no condition (or one folded to `true`), sits in no conditional \
         group, and its workflow's condition is absent or `true`. `channel_call.rs` fails the \
         call once the parent depth reaches the limit.\n\n\
         Silent when: any edge on the cycle is conditional (bounded recursion with a base \
         case is a legal pattern — the depth cap exists for it); the target is computed \
         rather than written as a literal channel name, so no edge is known; a target \
         channel or its workflow is not in the set."
    }

    fn check(&self, cx: &Analysis<'_>, out: &mut Vec<Diagnostic>) {
        // edges[a] = (b, calling step path, channel name)
        let mut edges: Vec<Vec<(usize, String, String)>> = vec![Vec::new(); cx.workflows.len()];
        for (a, wf) in cx.workflows.iter().enumerate() {
            if !wf.condition.is_constant_true() {
                continue;
            }
            for step in &wf.steps {
                if step.kind != StepKind::Task
                    || !step.certain
                    || step.function.as_deref() != Some("channel_call")
                {
                    continue;
                }
                let Some(target) = step
                    .node
                    .pointer("/function/input/channel")
                    .and_then(Value::as_str)
                    .filter(|t| !t.is_empty())
                else {
                    continue;
                };
                let Some(id) = cx.channels.get(target) else {
                    continue;
                };
                if let Some(b) = cx
                    .workflows
                    .iter()
                    .position(|w| w.workflow_id.as_deref() == Some(id))
                {
                    edges[a].push((b, step.path.clone(), target.to_string()));
                }
            }
        }

        // A cycle is reported once, from its lowest-indexed workflow.
        for start in 0..cx.workflows.len() {
            if let Some(cycle) = find_cycle(&edges, start) {
                let wf = &cx.workflows[start];
                let chain: Vec<String> = cycle
                    .iter()
                    .map(|(from, channel)| {
                        format!("'{}' calls channel '{channel}'", cx.workflows[*from].name)
                    })
                    .collect();
                let (_, first_path, _) = &edges[start]
                    .iter()
                    .find(|(b, _, _)| *b == cycle[1 % cycle.len()].0 || cycle.len() == 1)
                    .cloned()
                    .unwrap_or_else(|| edges[start][0].clone());
                out.push(
                    Diagnostic::on_workflow(
                        self,
                        cx,
                        wf,
                        Some(first_path),
                        format!(
                            "unconditional channel_call cycle: {} → back to '{}'; every request \
                             recurses until max_channel_call_depth and fails",
                            chain.join(", which "),
                            wf.name
                        ),
                    )
                    .with_remedy("put a condition on one of the calls, or break the cycle"),
                );
            }
        }
    }
}

/// A cycle through `start` using only the given edges, as `(workflow,
/// channel called)` pairs in call order, reported only when `start` is the
/// lowest index on it.
fn find_cycle(
    edges: &[Vec<(usize, String, String)>],
    start: usize,
) -> Option<Vec<(usize, String)>> {
    fn dfs(
        edges: &[Vec<(usize, String, String)>],
        start: usize,
        at: usize,
        path: &mut Vec<(usize, String)>,
        seen: &mut BTreeSet<usize>,
    ) -> bool {
        for (next, _, channel) in &edges[at] {
            if *next < start {
                // A cycle through a lower index is that index's to report.
                continue;
            }
            path.push((at, channel.clone()));
            if *next == start {
                return true;
            }
            if seen.insert(*next) && dfs(edges, start, *next, path, seen) {
                return true;
            }
            path.pop();
        }
        false
    }
    let mut path = Vec::new();
    let mut seen = BTreeSet::from([start]);
    dfs(edges, start, start, &mut path, &mut seen).then_some(path)
}

// ============================================================
// correctness.payload_var
// ============================================================

pub struct PayloadVar;

impl Rule for PayloadVar {
    fn id(&self) -> &'static str {
        "correctness.payload_var"
    }
    fn group(&self) -> Group {
        Group::Correctness
    }
    fn level(&self) -> Level {
        Level::Deny
    }
    fn scope(&self) -> Scope {
        Scope::Workflow
    }
    fn summary(&self) -> &'static str {
        "a read of `payload` — which is not in the data context — is always null"
    }
    fn explain(&self) -> &'static str {
        "The raw request payload lives beside the data context, not in it. \
         `{\"var\": \"payload.x\"}` resolves to `null` everywhere an expression is evaluated; \
         only `parse_json`/`parse_xml` with `source: \"payload\"` bring it into `data`.\n\n\
         Proof: the ingress builds the message with the body as the payload \
         (`routes/data`, `channel_call`), and the context the engine evaluates against holds \
         `data`, `metadata` and `temp_data` only.\n\n\
         Silent when: the read sits inside an element-scoped argument of `map`, `filter`, \
         `reduce`, `all`, `some`, `none`, `group_by`, `distinct`, `sort`, `try`, `switch` or \
         `match`, where `payload` may be an element's own field. Only expressions the engine \
         evaluates are examined — conditions, mapping logic, filter and validation rules, \
         `log` fields, `channel_call` logic, and registry fields marked resolvable; a \
         connector payload that merely contains the text is data, not a read."
    }

    fn check(&self, cx: &Analysis<'_>, out: &mut Vec<Diagnostic>) {
        for wf in &cx.workflows {
            let mut exprs: Vec<(String, &crate::definitions::analysis::Expr)> =
                vec![("condition".to_string(), &wf.condition)];
            for step in &wf.steps {
                if let Some(c) = &step.condition {
                    exprs.push((format!("{}.condition", step.path), c));
                }
                for (p, e) in &step.expressions {
                    exprs.push((format!("{}.function.input.{p}", step.path), e));
                }
            }
            for (path, expr) in exprs {
                for read in &expr.reads.paths {
                    if read == "payload" || read.starts_with("payload.") {
                        out.push(
                            Diagnostic::on_workflow(
                                self,
                                cx,
                                wf,
                                Some(&path),
                                format!(
                                    "reads `{read}`, but `payload` is not in the data context — the \
                                     value is always null"
                                ),
                            )
                            .with_remedy(
                                "parse it first: a `parse_json` task with `source: \"payload\"` and \
                                 `target: \"<name>\"`, then read `data.<name>`",
                            ),
                        );
                    }
                }
            }
        }
    }
}

// ============================================================
// correctness.mapping_overwritten
// ============================================================

pub struct MappingOverwritten;

impl Rule for MappingOverwritten {
    fn id(&self) -> &'static str {
        "correctness.mapping_overwritten"
    }
    fn group(&self) -> Group {
        Group::Correctness
    }
    fn level(&self) -> Level {
        Level::Warn
    }
    fn scope(&self) -> Scope {
        Scope::Workflow
    }
    fn summary(&self) -> &'static str {
        "two mappings in one map write the same path with nothing reading it in between"
    }
    fn explain(&self) -> &'static str {
        "`map` applies its mappings in order. When two of them write the same `path` and \
         no mapping between them — nor the second one itself — reads that path, the first \
         write is dead: nothing can observe it.\n\n\
         Proof: the documented in-order semantics of `map`; the reads of every intervening \
         mapping and of the overwriting one are literal paths that do not overlap the \
         written path (prefix in either direction).\n\n\
         Silent when: any mapping between them, or the overwriting one, reads the path or \
         anything inside or above it, or has a computed or element-scoped read. \
         `data.x = 1` followed by `data.x = data.x + 1` is a pattern, not a mistake."
    }

    fn check(&self, cx: &Analysis<'_>, out: &mut Vec<Diagnostic>) {
        for wf in &cx.workflows {
            for step in &wf.steps {
                if step.function.as_deref() != Some("map") {
                    continue;
                }
                let Some(mappings) = step
                    .node
                    .pointer("/function/input/mappings")
                    .and_then(Value::as_array)
                else {
                    continue;
                };
                let paths: Vec<Option<&str>> = mappings
                    .iter()
                    .map(|m| m.get("path").and_then(Value::as_str))
                    .collect();
                let logic_reads: Vec<_> = mappings
                    .iter()
                    .map(|m| m.get("logic").map(reads).unwrap_or_default())
                    .collect();
                for i in 0..mappings.len() {
                    let Some(path) = paths[i] else {
                        continue;
                    };
                    let Some(j) = (i + 1..mappings.len()).find(|&j| paths[j] == Some(path)) else {
                        continue;
                    };
                    let observed = (i + 1..=j)
                        .any(|k| logic_reads[k].uncertain() || logic_reads[k].touches(path));
                    if observed {
                        continue;
                    }
                    out.push(
                        Diagnostic::on_workflow(
                            self,
                            cx,
                            wf,
                            Some(&format!("{}.function.input.mappings[{i}]", step.path)),
                            format!(
                                "writes `{path}`, which mappings[{j}] of the same task overwrites \
                                 before anything reads it"
                            ),
                        )
                        .with_remedy("remove the first mapping"),
                    );
                }
            }
        }
    }
}

// ============================================================
// correctness.metadata_var_undeclared  (needs -c)
// ============================================================

pub struct MetadataVarUndeclared;

impl Rule for MetadataVarUndeclared {
    fn id(&self) -> &'static str {
        "correctness.metadata_var_undeclared"
    }
    fn group(&self) -> Group {
        Group::Correctness
    }
    fn level(&self) -> Level {
        Level::Deny
    }
    fn scope(&self) -> Scope {
        Scope::Workflow
    }
    fn needs_config(&self) -> bool {
        true
    }
    fn summary(&self) -> &'static str {
        "a read of `metadata.vars.<name>` that the config given with -c does not declare"
    }
    fn explain(&self) -> &'static str {
        "`metadata.vars` is the `[vars]` section of the serving instance's config, stamped \
         onto every message at ingress. A caller cannot supply it, and a name the section \
         does not declare is `null` on every request.\n\n\
         Proof: `config/vars.rs` and the ingress routes — `vars` is force-stamped and \
         stripped from caller metadata; the config passed with `-c` is the declaration.\n\n\
         Silent when: no `-c` was given (the rule is skipped with a note); the read is \
         computed or element-scoped; the read is of `metadata.vars` as a whole."
    }

    fn check(&self, cx: &Analysis<'_>, out: &mut Vec<Diagnostic>) {
        let Some(config) = cx.config else {
            return;
        };
        let declared: BTreeSet<&str> = config.vars.0.keys().map(String::as_str).collect();
        for wf in &cx.workflows {
            let mut exprs: Vec<(String, &crate::definitions::analysis::Expr)> =
                vec![("condition".to_string(), &wf.condition)];
            for step in &wf.steps {
                if let Some(c) = &step.condition {
                    exprs.push((format!("{}.condition", step.path), c));
                }
                for (p, e) in &step.expressions {
                    exprs.push((format!("{}.function.input.{p}", step.path), e));
                }
            }
            for (path, expr) in exprs {
                for read in &expr.reads.paths {
                    let Some(rest) = read.strip_prefix("metadata.vars.") else {
                        continue;
                    };
                    let name = rest.split('.').next().unwrap_or(rest);
                    if name.is_empty() || declared.contains(name) {
                        continue;
                    }
                    let why = if declared.is_empty() {
                        "the config declares no [vars] at all, so `metadata.vars` is absent"
                            .to_string()
                    } else {
                        format!("the config's [vars] does not declare `{name}`")
                    };
                    out.push(
                        Diagnostic::on_workflow(
                            self,
                            cx,
                            wf,
                            Some(&path),
                            format!("reads `{read}`, but {why}; the value is always null"),
                        )
                        .with_remedy(format!(
                            "add `{name}` under [vars], or read the name it declares"
                        )),
                    );
                }
            }
        }
    }
}

// ============================================================
// correctness.secret_undeclared  (needs -c)
// ============================================================

pub struct SecretUndeclared;

impl Rule for SecretUndeclared {
    fn id(&self) -> &'static str {
        "correctness.secret_undeclared"
    }
    fn group(&self) -> Group {
        Group::Correctness
    }
    fn level(&self) -> Level {
        Level::Deny
    }
    fn scope(&self) -> Scope {
        Scope::Set
    }
    fn needs_config(&self) -> bool {
        true
    }
    fn summary(&self) -> &'static str {
        "a {\"secret\": name} that the config given with -c does not declare"
    }
    fn explain(&self) -> &'static str {
        "`{\"secret\": \"<name>\"}` reads the engine's secret store, which is the `[secrets]` \
         section of the serving instance's config. The engine refuses to build a workflow \
         that names a secret the store lacks, and Orion quarantines the channel at load.\n\n\
         Proof: the dataflow-rs secret store's build-time check, and the config passed with \
         `-c` as the declaration.\n\n\
         Silent when: no `-c` was given (skipped with a note)."
    }

    fn check(&self, cx: &Analysis<'_>, out: &mut Vec<Diagnostic>) {
        let Some(config) = cx.config else {
            return;
        };
        let declared: BTreeSet<&str> = config.secrets.0.keys().map(String::as_str).collect();
        for def in &cx.compiled.definitions {
            let entity = format!(
                "{} '{}'",
                def.entity.as_str(),
                def.doc
                    .get("name")
                    .and_then(Value::as_str)
                    .unwrap_or(&def.origin)
            );
            let mut hits = Vec::new();
            walk_values(&def.doc, "", &mut |path, value| {
                if let Some(name) = crate::engine::functions::secret_ref::secret_name(value)
                    && !declared.contains(name)
                {
                    hits.push((path.to_string(), name.to_string()));
                }
            });
            for (path, name) in hits {
                out.push(
                    Diagnostic::at(
                        self,
                        cx,
                        entity.clone(),
                        &def.origin,
                        Some(&path),
                        format!(
                            "names secret `{name}`, which the config does not declare under [secrets]; \
                             the engine refuses to build this and the channel is quarantined"
                        ),
                    )
                    .with_remedy(format!("declare `{name}` under [secrets] in the serving config")),
                );
            }
        }
    }
}