apoc 0.9.1

Agentic process control for LLMs
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
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
//! One shape for everything apoc is about to do to the machine.
//!
//! A command, a Code Mode call into apoc, a call into a discovered MCP server,
//! and a process signal arrive in different forms. Before any of them acts, it
//! is stated as an [`Intent`]: what will happen, to what, on whose behalf. A
//! decider registered outside apoc may rule on it; apoc itself ships no rules.
//!
//! Two limits are part of the shape, not footnotes:
//!
//! - apoc names a [`Target`] only when it already resolved that thing for its
//!   own reasons. It never parses argv for paths, expands variables, or reads a
//!   shell string. `rm -rf $TMPDIR/x` has one target, the `rm` executable.
//! - [`Intent::analysable`] means apoc did not have to give up on the request's
//!   form. It does not mean apoc understood the request's effect.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};

/// One action apoc is about to take, stated before it happens.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Intent {
    /// Identifier, also used to answer a pending ruling.
    pub id: String,
    /// When the intent was stated, in Unix milliseconds.
    pub at: u64,
    /// The canonical dotted operation, such as `execution.command`,
    /// `process.signal`, `apoc.execution_start`, or `connector.github.create_issue`.
    pub verb: String,
    /// Which surface the request came through.
    pub origin: IntentOrigin,
    /// Exactly what will be done, in the request's own terms.
    pub body: IntentBody,
    /// Digest of [`Intent::body`]; the identity a declaration and a ruling
    /// refer to.
    pub body_digest: String,
    /// What apoc resolved this action to act on. Never inferred.
    pub targets: Vec<Target>,
    /// Whether apoc could state the request's form at all. A shell string is
    /// not analysable. See the module note: this is not a claim of coverage.
    pub analysable: bool,
    /// Why the request is not analysable, when it is not.
    pub opacity: Option<Opacity>,
    /// Whether the targets describe the action's effect, or only name the verb.
    pub coverage: Coverage,
    /// The tool's own claims about itself, carried verbatim; apoc does not act
    /// on them.
    pub annotations: IntentAnnotations,
    /// Whether the action can be undone. `Unknown` unless apoc has a real way
    /// to undo it.
    pub reversibility: Reversibility,
    /// The one-line purpose the caller gave.
    pub purpose: Option<String>,
    /// Who and what this action belongs to.
    pub lineage: Lineage,
}

/// The surface a request arrived through.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum IntentOrigin {
    Cli,
    Mcp,
    Code,
    Poll,
    Hook,
    Recipe,
    /// apoc stopping its own children. Never waits on a decider.
    Supervisor,
}

/// What will be done, in the request's own terms.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum IntentBody {
    /// A process launch.
    Argv {
        argv: Vec<String>,
        shell: bool,
        cwd: Option<String>,
        /// Names of environment variables set for the launch; values are never
        /// recorded.
        env_keys: Vec<String>,
    },
    /// A signal to already-resolved processes.
    Signal { name: String },
    /// A call into a connector: a discovered MCP server, an OpenAPI provider.
    ToolCall {
        connector: String,
        method: String,
        arguments: Value,
    },
    /// A call into apoc's own typed command graph.
    TypedCall { command_path: String, input: Value },
}

impl IntentBody {
    /// A stable digest of this body: the same request always produces the same
    /// digest, whatever order its JSON fields were written in.
    pub fn digest(&self) -> String {
        let canonical = canonical_json(&serde_json::to_value(self).unwrap_or(Value::Null));
        format!("{:x}", Sha256::digest(canonical.as_bytes()))
    }
}

/// Something apoc resolved an action to act on.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)]
pub struct Target {
    pub kind: TargetKind,
    /// A stable key: `exec:/abs/path`, `process:<boot>/<pid>/<start_ns>`,
    /// `port:tcp/5173`, `path:/abs/path`, `tool:<connector>/<method>`,
    /// `url:https://host/path`, `apoc:<command_path>`, or `opaque:`.
    pub key: String,
}

impl Target {
    pub fn executable(path: &str) -> Self {
        Self {
            kind: TargetKind::Executable,
            key: format!("exec:{path}"),
        }
    }

    pub fn process(boot_id: &str, pid: u32, started_at_ns: u128) -> Self {
        Self {
            kind: TargetKind::Process,
            key: format!("process:{boot_id}/{pid}/{started_at_ns}"),
        }
    }

    pub fn path(path: &str) -> Self {
        Self {
            kind: TargetKind::Path,
            key: format!("path:{path}"),
        }
    }

    pub fn tool(connector: &str, method: &str) -> Self {
        Self {
            kind: TargetKind::Tool,
            key: format!("tool:{connector}/{method}"),
        }
    }

    pub fn apoc(command_path: &str) -> Self {
        Self {
            kind: TargetKind::Apoc,
            key: format!("apoc:{command_path}"),
        }
    }

    pub fn opaque() -> Self {
        Self {
            kind: TargetKind::Opaque,
            key: "opaque:".to_string(),
        }
    }
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum TargetKind {
    Executable,
    Process,
    Port,
    Path,
    Tool,
    Endpoint,
    Apoc,
    Opaque,
}

/// Why a request's form could not be stated.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Opacity {
    /// A string handed whole to a shell.
    Shell,
    /// Code evaluated inside another runtime: a debuggee, a browser page.
    ForeignRuntime,
}

/// Whether an intent's targets describe the action's effect.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Coverage {
    /// The targets are what the action acts on.
    Precise,
    /// Only the verb is known; the effect happens somewhere apoc cannot see,
    /// such as inside a debugger or a browser.
    VerbOnly,
}

/// A tool's claims about itself, and who made them.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct IntentAnnotations {
    pub read_only: Option<bool>,
    pub destructive: Option<bool>,
    pub idempotent: Option<bool>,
    pub open_world: Option<bool>,
    /// `local` for apoc's own graph; `remote_mcp` or `openapi` when a server
    /// made the claim about itself.
    pub source: String,
}

/// Whether an action can be undone.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Reversibility {
    NoEffect,
    /// apoc holds a real way to undo it.
    Compensable,
    Irreversible,
    Unknown,
}

/// Who and what an action belongs to.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Lineage {
    pub actor: Option<String>,
    pub invocation_id: Option<String>,
    pub execution_id: Option<String>,
    pub code_execution_id: Option<String>,
    pub code_seq: Option<u64>,
    pub session_id: Option<String>,
    pub cwd: Option<String>,
    pub declaration_id: Option<String>,
}

/// What a caller promises its work will stay within.
///
/// A declaration is the caller's own promise. Enforcing it is not apoc shipping
/// a rule: the caller wrote the rule about itself.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Declaration {
    /// Exact canonical verbs the work may use.
    pub verbs: Vec<String>,
    /// Targets the work may act on. Empty means any target the verbs reach.
    #[serde(default)]
    pub targets: Vec<TargetPattern>,
    /// Whether the work may run requests apoc cannot analyse, such as shell
    /// strings.
    #[serde(default)]
    pub allow_opaque: bool,
    /// Whether the work may call tools that reach outside this machine.
    #[serde(default)]
    pub allow_open_world: bool,
    /// The most intents the whole plan may state.
    #[serde(default)]
    pub max_intents: Option<u32>,
}

/// A target a declaration permits.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "match", content = "key", rename_all = "snake_case")]
pub enum TargetPattern {
    /// Exactly this target key.
    Exact(String),
    /// Any `path:` target at or beneath this absolute path.
    Beneath(String),
}

impl TargetPattern {
    fn permits(&self, target: &Target) -> bool {
        match self {
            TargetPattern::Exact(key) => &target.key == key,
            TargetPattern::Beneath(root) => {
                let Some(path) = target.key.strip_prefix("path:") else {
                    return false;
                };
                let root = root.trim_end_matches('/');
                path == root || path.starts_with(&format!("{root}/"))
            }
        }
    }
}

/// How an intent broke a declaration.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "breach", rename_all = "snake_case")]
pub enum Breach {
    VerbNotDeclared { verb: String },
    TargetNotDeclared { target: String },
    OpaqueNotDeclared,
    OpenWorldNotDeclared,
    TooManyIntents { limit: u32 },
}

impl std::fmt::Display for Breach {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Breach::VerbNotDeclared { verb } => {
                write!(formatter, "DECLARATION_BREACH: {verb} was not declared")
            }
            Breach::TargetNotDeclared { target } => {
                write!(formatter, "DECLARATION_BREACH: {target} was not declared")
            }
            Breach::OpaqueNotDeclared => write!(
                formatter,
                "DECLARATION_BREACH: an unanalysable request was not declared"
            ),
            Breach::OpenWorldNotDeclared => write!(
                formatter,
                "DECLARATION_BREACH: an open-world tool was not declared"
            ),
            Breach::TooManyIntents { limit } => write!(
                formatter,
                "DECLARATION_BREACH: more than the declared {limit} intents"
            ),
        }
    }
}

impl Declaration {
    /// Whether one intent stays within this declaration.
    ///
    /// This is the only comparison. Checking a whole plan up front and checking
    /// each action as it happens both call it, so the two cannot disagree.
    pub fn permits(&self, intent: &Intent) -> Result<(), Breach> {
        if !self.verbs.iter().any(|verb| verb == &intent.verb) {
            return Err(Breach::VerbNotDeclared {
                verb: intent.verb.clone(),
            });
        }
        if !intent.analysable && !self.allow_opaque {
            return Err(Breach::OpaqueNotDeclared);
        }
        if intent.annotations.open_world == Some(true) && !self.allow_open_world {
            return Err(Breach::OpenWorldNotDeclared);
        }
        if !self.targets.is_empty() {
            for target in &intent.targets {
                if target.kind == TargetKind::Opaque {
                    continue;
                }
                if !self.targets.iter().any(|pattern| pattern.permits(target)) {
                    return Err(Breach::TargetNotDeclared {
                        target: target.key.clone(),
                    });
                }
            }
        }
        Ok(())
    }

    /// Whether a whole plan stays within this declaration, and if not, the
    /// first intent that breaks it.
    pub fn permits_plan(&self, intents: &[Intent]) -> Result<(), (usize, Breach)> {
        for (index, intent) in intents.iter().enumerate() {
            if let Some(limit) = self.max_intents
                && index as u32 >= limit
            {
                return Err((index, Breach::TooManyIntents { limit }));
            }
            self.permits(intent).map_err(|breach| (index, breach))?;
        }
        Ok(())
    }
}

/// A decider's answer about one intent.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Ruling {
    pub intent_id: String,
    /// Must match the intent's digest; a ruling about a different body is not
    /// a ruling about this one.
    pub body_digest: String,
    pub decision: Decision,
    /// Shown to the caller verbatim.
    pub reason: String,
    pub decider: String,
    pub ruled_at: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Decision {
    Allow,
    Refuse,
    /// Asked, and not yet answered.
    Pending,
}

/// A program registered outside apoc's rules that answers intents.
///
/// apoc ships none. With none registered, nothing is asked and nothing is
/// recorded.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Decider {
    pub name: String,
    /// A Code Mode program. It runs with a frozen `intent` in scope and returns
    /// `{decision: "allow" | "refuse" | "pending", reason}`.
    pub program: String,
    /// Verbs this decider is asked about. Empty means every verb.
    #[serde(default)]
    pub verbs: Vec<String>,
    pub enabled: bool,
    /// How long one answer may take.
    pub timeout_ms: u64,
    /// What happens when this decider cannot answer in time or at all. The
    /// registrant chooses; apoc never guesses.
    pub on_unavailable: OnUnavailable,
    pub created_at: u64,
    pub updated_at: u64,
}

impl Decider {
    /// Whether this decider is asked about `verb`.
    pub fn applies_to(&self, verb: &str) -> bool {
        self.enabled && (self.verbs.is_empty() || self.verbs.iter().any(|name| name == verb))
    }
}

/// What a registrant wants when their decider cannot answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum OnUnavailable {
    Allow,
    Refuse,
}

/// One decider's answer, or why it gave none.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DeciderAnswer {
    pub decider: String,
    /// The decision, when the decider gave one.
    pub decision: Option<Decision>,
    pub reason: String,
    /// Why no decision came back: a timeout, a crash, a malformed answer.
    pub unavailable: Option<String>,
    pub elapsed_ms: u64,
}

/// Whether anyone actually ruled on an intent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RulingState {
    /// Every decider asked gave a decision.
    Ruled,
    /// At least one decider could not answer; its registrant's
    /// `on_unavailable` choice stood in for it. Never presented as a ruling.
    Unchecked,
}

/// What happened to one intent, kept for inspection.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct IntentRecord {
    pub intent: Intent,
    /// Whether the action went ahead.
    pub proceeded: bool,
    pub state: RulingState,
    /// The reason shown to the caller, verbatim from a decider where one
    /// refused.
    pub reason: String,
    pub answers: Vec<DeciderAnswer>,
}

/// Combines every decider's answer about one intent.
///
/// Any refusal refuses. A decider that could not answer counts as its
/// registrant's `on_unavailable` choice. A pending answer refuses, and says
/// so, because nothing yet holds an action open until someone answers.
pub fn combine(answers: &[DeciderAnswer], deciders: &[Decider]) -> (bool, RulingState, String) {
    let mut state = RulingState::Ruled;
    let mut refusals = Vec::new();
    for answer in answers {
        match (&answer.decision, &answer.unavailable) {
            (Some(Decision::Refuse), _) => {
                refusals.push(format!("{} refused: {}", answer.decider, answer.reason));
            }
            (Some(Decision::Pending), _) => refusals.push(format!(
                "{} left it pending, and a pending ruling cannot yet hold an action open: {}",
                answer.decider, answer.reason
            )),
            (Some(Decision::Allow), _) => {}
            (None, unavailable) => {
                state = RulingState::Unchecked;
                let refuses = deciders
                    .iter()
                    .find(|decider| decider.name == answer.decider)
                    .is_none_or(|decider| decider.on_unavailable == OnUnavailable::Refuse);
                if refuses {
                    refusals.push(format!(
                        "{} could not answer ({}), and its registrant chose to refuse in that case",
                        answer.decider,
                        unavailable.as_deref().unwrap_or("no answer")
                    ));
                }
            }
        }
    }
    if refusals.is_empty() {
        (true, state, String::new())
    } else {
        (false, state, refusals.join("; "))
    }
}

/// Where an intent is offered before its action runs.
#[async_trait::async_trait]
pub trait IntentGate: Send + Sync {
    /// Whether any decider is registered. When false, callers skip building
    /// the intent entirely: no decider means no question and no record.
    fn active(&self) -> bool;

    /// Offers `intent` to every decider it concerns. `Err` carries the refusal
    /// to show the caller.
    async fn offer(&self, intent: Intent) -> Result<(), String>;
}

/// The gate when no decider can ever be registered.
pub struct Ungated;

#[async_trait::async_trait]
impl IntentGate for Ungated {
    fn active(&self) -> bool {
        false
    }

    async fn offer(&self, _intent: Intent) -> Result<(), String> {
        Ok(())
    }
}

/// The intent for launching one command.
///
/// The only target is the executable, and only when apoc can resolve it the
/// way the launch will: an absolute path, a path relative to `cwd`, or a name
/// found on `path_var`. A shell string has one opaque target and is not
/// analysable.
#[allow(clippy::too_many_arguments)]
pub fn for_command(
    verb: &str,
    argv: &[String],
    shell: bool,
    cwd: Option<&str>,
    env_keys: Vec<String>,
    path_var: Option<&str>,
    purpose: Option<String>,
    lineage: Lineage,
    origin: IntentOrigin,
    at: u64,
) -> Intent {
    let body = IntentBody::Argv {
        argv: argv.to_vec(),
        shell,
        cwd: cwd.map(ToString::to_string),
        env_keys,
    };
    let (targets, analysable, opacity) = if shell {
        (vec![Target::opaque()], false, Some(Opacity::Shell))
    } else {
        let targets = argv
            .first()
            .and_then(|program| resolve_executable(program, cwd, path_var))
            .map(|path| vec![Target::executable(&path)])
            .unwrap_or_default();
        (targets, true, None)
    };
    Intent {
        id: uuid::Uuid::now_v7().to_string(),
        at,
        verb: verb.to_string(),
        origin,
        body_digest: body.digest(),
        body,
        targets,
        analysable,
        opacity,
        coverage: Coverage::Precise,
        annotations: IntentAnnotations {
            source: "local".to_string(),
            ..IntentAnnotations::default()
        },
        reversibility: Reversibility::Unknown,
        purpose,
        lineage,
    }
}

fn resolve_executable(program: &str, cwd: Option<&str>, path_var: Option<&str>) -> Option<String> {
    let is_file = |path: &std::path::Path| path.is_file();
    if program.starts_with('/') {
        return is_file(std::path::Path::new(program)).then(|| program.to_string());
    }
    if program.contains('/') {
        let joined = std::path::Path::new(cwd?).join(program);
        return is_file(&joined).then(|| joined.to_string_lossy().into_owned());
    }
    path_var?
        .split(':')
        .filter(|directory| !directory.is_empty())
        .map(|directory| std::path::Path::new(directory).join(program))
        .find(|candidate| is_file(candidate))
        .map(|found| found.to_string_lossy().into_owned())
}

/// JSON with object keys sorted at every level, so equal values serialize
/// identically.
fn canonical_json(value: &Value) -> String {
    match value {
        Value::Object(map) => {
            let mut keys = map.keys().collect::<Vec<_>>();
            keys.sort();
            let fields = keys
                .into_iter()
                .map(|key| {
                    format!(
                        "{}:{}",
                        serde_json::to_string(key).unwrap_or_default(),
                        canonical_json(&map[key])
                    )
                })
                .collect::<Vec<_>>();
            format!("{{{}}}", fields.join(","))
        }
        Value::Array(items) => format!(
            "[{}]",
            items
                .iter()
                .map(canonical_json)
                .collect::<Vec<_>>()
                .join(",")
        ),
        other => other.to_string(),
    }
}

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

    fn command(argv: &[&str], targets: Vec<Target>) -> Intent {
        let body = IntentBody::Argv {
            argv: argv.iter().map(|arg| arg.to_string()).collect(),
            shell: false,
            cwd: None,
            env_keys: Vec::new(),
        };
        Intent {
            id: "intent".into(),
            at: 1,
            verb: "execution.command".into(),
            origin: IntentOrigin::Cli,
            body_digest: body.digest(),
            body,
            targets,
            analysable: true,
            opacity: None,
            coverage: Coverage::Precise,
            annotations: IntentAnnotations::default(),
            reversibility: Reversibility::Unknown,
            purpose: None,
            lineage: Lineage::default(),
        }
    }

    fn shell(script: &str) -> Intent {
        let mut intent = command(&[script], vec![Target::opaque()]);
        intent.body = IntentBody::Argv {
            argv: vec![script.into()],
            shell: true,
            cwd: None,
            env_keys: Vec::new(),
        };
        intent.body_digest = intent.body.digest();
        intent.analysable = false;
        intent.opacity = Some(Opacity::Shell);
        intent
    }

    fn decider(name: &str, on_unavailable: OnUnavailable) -> Decider {
        Decider {
            name: name.into(),
            program: "return {decision: 'allow'};".into(),
            verbs: Vec::new(),
            enabled: true,
            timeout_ms: 2_000,
            on_unavailable,
            created_at: 1,
            updated_at: 1,
        }
    }

    fn answer(
        decider: &str,
        decision: Option<Decision>,
        unavailable: Option<&str>,
    ) -> DeciderAnswer {
        DeciderAnswer {
            decider: decider.into(),
            decision,
            reason: "because".into(),
            unavailable: unavailable.map(ToString::to_string),
            elapsed_ms: 1,
        }
    }

    #[test]
    fn one_refusal_refuses_and_names_who_refused() {
        let deciders = [
            decider("a", OnUnavailable::Allow),
            decider("b", OnUnavailable::Allow),
        ];
        let (proceeded, state, reason) = combine(
            &[
                answer("a", Some(Decision::Allow), None),
                answer("b", Some(Decision::Refuse), None),
            ],
            &deciders,
        );
        assert!(!proceeded);
        assert_eq!(state, RulingState::Ruled);
        assert!(reason.starts_with("b refused: because"), "{reason}");
    }

    #[test]
    fn an_unavailable_decider_follows_its_registrants_choice_and_is_never_a_ruling() {
        for (choice, proceeds) in [(OnUnavailable::Allow, true), (OnUnavailable::Refuse, false)] {
            let deciders = [decider("slow", choice)];
            let (proceeded, state, _) = combine(
                &[answer("slow", None, Some("timed out after 2000 ms"))],
                &deciders,
            );
            assert_eq!(proceeded, proceeds, "{choice:?}");
            assert_eq!(state, RulingState::Unchecked, "{choice:?}");
        }
    }

    #[test]
    fn a_pending_answer_refuses_until_actions_can_be_held_open() {
        let (proceeded, _, reason) = combine(
            &[answer("a", Some(Decision::Pending), None)],
            &[decider("a", OnUnavailable::Allow)],
        );
        assert!(!proceeded);
        assert!(reason.contains("pending"), "{reason}");
    }

    #[test]
    fn a_command_names_only_the_executable_it_resolves() {
        let intent = for_command(
            "execution.command",
            &["rm".into(), "-rf".into(), "$TMPDIR/x".into()],
            false,
            Some("/"),
            Vec::new(),
            Some("/nonexistent:/bin"),
            None,
            Lineage::default(),
            IntentOrigin::Cli,
            1,
        );
        assert_eq!(intent.targets, vec![Target::executable("/bin/rm")]);
        assert!(intent.analysable);

        let unresolvable = for_command(
            "execution.command",
            &["no-such-program-anywhere".into()],
            false,
            None,
            Vec::new(),
            Some("/bin"),
            None,
            Lineage::default(),
            IntentOrigin::Cli,
            1,
        );
        assert!(unresolvable.targets.is_empty());

        let shell = for_command(
            "execution.command",
            &["rm -rf $TMPDIR/x".into()],
            true,
            None,
            Vec::new(),
            Some("/bin"),
            None,
            Lineage::default(),
            IntentOrigin::Cli,
            1,
        );
        assert_eq!(shell.targets, vec![Target::opaque()]);
        assert!(!shell.analysable);
        assert_eq!(shell.opacity, Some(Opacity::Shell));
    }

    #[test]
    fn a_body_digest_ignores_field_order_but_not_content() {
        let a = IntentBody::ToolCall {
            connector: "github".into(),
            method: "create_issue".into(),
            arguments: serde_json::json!({"title": "x", "body": "y"}),
        };
        let b = IntentBody::ToolCall {
            connector: "github".into(),
            method: "create_issue".into(),
            arguments: serde_json::json!({"body": "y", "title": "x"}),
        };
        let c = IntentBody::ToolCall {
            connector: "github".into(),
            method: "create_issue".into(),
            arguments: serde_json::json!({"body": "z", "title": "x"}),
        };
        assert_eq!(a.digest(), b.digest());
        assert_ne!(a.digest(), c.digest());
    }

    #[test]
    fn an_undeclared_verb_is_a_breach() {
        let declaration = Declaration {
            verbs: vec!["process.signal".into()],
            ..Declaration::default()
        };
        let intent = command(&["/bin/ls"], vec![Target::executable("/bin/ls")]);
        assert_eq!(
            declaration.permits(&intent),
            Err(Breach::VerbNotDeclared {
                verb: "execution.command".into()
            })
        );
    }

    #[test]
    fn a_shell_string_needs_opacity_declared() {
        let mut declaration = Declaration {
            verbs: vec!["execution.command".into()],
            ..Declaration::default()
        };
        assert_eq!(
            declaration.permits(&shell("rm -rf $TMPDIR/x")),
            Err(Breach::OpaqueNotDeclared)
        );
        declaration.allow_opaque = true;
        assert_eq!(declaration.permits(&shell("rm -rf $TMPDIR/x")), Ok(()));
    }

    #[test]
    fn declared_targets_bound_what_a_command_may_touch() {
        let declaration = Declaration {
            verbs: vec!["execution.command".into()],
            targets: vec![
                TargetPattern::Exact("exec:/bin/echo".into()),
                TargetPattern::Beneath("/work".into()),
            ],
            ..Declaration::default()
        };
        let echo = command(
            &["/bin/echo"],
            vec![Target::executable("/bin/echo"), Target::path("/work/a")],
        );
        assert_eq!(declaration.permits(&echo), Ok(()));
        let ls = command(&["/bin/ls"], vec![Target::executable("/bin/ls")]);
        assert_eq!(
            declaration.permits(&ls),
            Err(Breach::TargetNotDeclared {
                target: "exec:/bin/ls".into()
            })
        );
        // `/workshop` shares a prefix with `/work` but is not beneath it.
        let sibling = command(
            &["/bin/echo"],
            vec![Target::executable("/bin/echo"), Target::path("/workshop")],
        );
        assert_eq!(
            declaration.permits(&sibling),
            Err(Breach::TargetNotDeclared {
                target: "path:/workshop".into()
            })
        );
    }

    #[test]
    fn an_open_world_tool_needs_it_declared() {
        let mut intent = command(&["/bin/echo"], Vec::new());
        intent.annotations.open_world = Some(true);
        let declaration = Declaration {
            verbs: vec!["execution.command".into()],
            ..Declaration::default()
        };
        assert_eq!(
            declaration.permits(&intent),
            Err(Breach::OpenWorldNotDeclared)
        );
    }

    #[test]
    fn a_plan_is_bounded_by_its_declared_size() {
        let declaration = Declaration {
            verbs: vec!["execution.command".into()],
            max_intents: Some(2),
            ..Declaration::default()
        };
        let one = command(&["/bin/echo"], Vec::new());
        assert_eq!(
            declaration.permits_plan(&[one.clone(), one.clone()]),
            Ok(())
        );
        assert_eq!(
            declaration.permits_plan(&[one.clone(), one.clone(), one]),
            Err((2, Breach::TooManyIntents { limit: 2 }))
        );
    }

    /// The whole-plan check and the per-action check must never disagree about
    /// one intent. Exhaustive over a small generated space rather than sampled.
    #[test]
    fn whole_plan_and_per_action_checks_agree_on_every_intent() {
        let verbs = ["execution.command", "process.signal"];
        let target_sets: Vec<Vec<Target>> = vec![
            vec![],
            vec![Target::executable("/bin/echo")],
            vec![Target::executable("/bin/ls")],
            vec![Target::path("/work/a")],
            vec![Target::path("/workshop")],
            vec![Target::opaque()],
        ];
        let declarations = [
            Declaration::default(),
            Declaration {
                verbs: vec!["execution.command".into()],
                ..Declaration::default()
            },
            Declaration {
                verbs: vec!["execution.command".into()],
                targets: vec![
                    TargetPattern::Exact("exec:/bin/echo".into()),
                    TargetPattern::Beneath("/work".into()),
                ],
                allow_opaque: true,
                ..Declaration::default()
            },
            Declaration {
                verbs: verbs.iter().map(|verb| verb.to_string()).collect(),
                allow_open_world: true,
                ..Declaration::default()
            },
        ];
        let mut checked = 0;
        for declaration in &declarations {
            for verb in verbs {
                for targets in &target_sets {
                    for (analysable, open_world) in
                        [(true, None), (false, None), (true, Some(true))]
                    {
                        let mut intent = command(&["/bin/echo"], targets.clone());
                        intent.verb = verb.to_string();
                        intent.analysable = analysable;
                        intent.annotations.open_world = open_world;
                        let per_action = declaration.permits(&intent);
                        let whole_plan = declaration
                            .permits_plan(std::slice::from_ref(&intent))
                            .map_err(|(_, breach)| breach);
                        assert_eq!(per_action, whole_plan, "{declaration:?} {intent:?}");
                        checked += 1;
                    }
                }
            }
        }
        assert_eq!(checked, 4 * 2 * 6 * 3);
    }
}