dalo 1.11.1

Your team's agent skills, versioned like code. Review, pin, and sync skills, instructions, and hooks into every agent.
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
//! Aggregated, read-only-first review of portable plugin trust boundaries.

use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::path::Path;

use serde::Serialize;
use sha2::{Digest, Sha256};

use crate::audit::{self, AuditOptions};
use crate::error::{DaloError, DaloResult};
use crate::hook::HookTrustState;
use crate::plan::{InstallationPlan, PlanCompatibility, TargetComponentState};
use crate::plugin::{MemberRequirement, PluginComponentState, PluginDependencyState, PluginState};
use crate::store::{self, ApprovalRecord, StorePaths};
use crate::tool::ToolState;

/// Current machine-readable aggregated-review schema.
pub const PLUGIN_REVIEW_SCHEMA_VERSION: u32 = 2;

/// Whether this invocation can collect the displayed approval decisions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum InteractiveApprovals {
    /// Interactive mode will prompt for individual decisions and a final commit.
    Available,
    /// JSON mode returns the review snapshot without prompting or granting approvals.
    SkippedInJsonMode,
}

/// One complete, inert review snapshot.
#[derive(Debug, Clone, Serialize)]
pub struct PluginReviewReport {
    /// Explicit review schema version.
    pub schema_version: u32,
    /// Canonical root selected by the user.
    pub root_plugin: String,
    /// Exact selected dependency closure, in canonical order.
    pub plugin_closure: Vec<ReviewPlugin>,
    /// The same typed target and projection facts exposed by `dalo plan`.
    pub installation_plan: InstallationPlan,
    /// Separately scoped trust decisions in deterministic display order.
    pub decisions: Vec<ReviewDecision>,
    /// Hash binding the displayed closure, contracts, and target mappings.
    pub review_token: String,
    /// Whether this invocation can collect the displayed approval decisions.
    pub interactive_approvals: InteractiveApprovals,
    /// Aggregated review never executes active components or mutates targets.
    pub read_only: bool,
}

/// Package provenance retained in the reviewed dependency closure.
#[derive(Debug, Clone, Serialize)]
pub struct ReviewPlugin {
    /// Canonical plugin identity.
    pub source_ref: String,
    /// Complete authored package hash.
    pub package_hash: String,
    /// Effective passive closure hash.
    pub closure_hash: String,
    /// Current canonical state.
    pub state: PluginState,
    /// Deterministic blocking explanations.
    pub blocking_reasons: Vec<String>,
}

/// Stable trust-boundary vocabulary.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ReviewDecisionKind {
    /// Passive skill content, with a deterministic content audit.
    SkillContent,
    /// Independently activated canonical agent package.
    AgentActivation,
    /// Independently managed instruction recommendation; never approved here.
    InstructionRecommendation,
    /// Exact executable tool contract.
    ToolExecution,
    /// Exact hook event/effect contract.
    HookBinding,
}

impl std::fmt::Display for ReviewDecisionKind {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::SkillContent => "skill_content",
            Self::AgentActivation => "agent_activation",
            Self::InstructionRecommendation => "instruction_recommendation",
            Self::ToolExecution => "tool_execution",
            Self::HookBinding => "hook_binding",
        })
    }
}

/// State of one exact component boundary at snapshot time.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ReviewDecisionState {
    /// Exact existing approval remains valid and is reused.
    Reused,
    /// Exact displayed approval can be selected in this session.
    Pending,
    /// A prior identity approval exists but its hash-bound contract changed.
    Invalidated,
    /// Safety, audit, dependency, or availability prevents approval.
    Blocked,
    /// Target adapters cannot represent the component safely.
    Unsupported,
    /// Component is visible but intentionally not activated by plugin review.
    Inactive,
}

impl std::fmt::Display for ReviewDecisionState {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::Reused => "reused",
            Self::Pending => "pending",
            Self::Invalidated => "invalidated",
            Self::Blocked => "blocked",
            Self::Unsupported => "unsupported",
            Self::Inactive => "inactive",
        })
    }
}

/// One exact, separately approvable (or explicitly non-approvable) boundary.
#[derive(Debug, Clone, Serialize)]
pub struct ReviewDecision {
    /// Stable session identity, also used by interactive prompts.
    pub id: String,
    /// Plugin that declares this component.
    pub plugin: String,
    /// Trust boundary.
    pub kind: ReviewDecisionKind,
    /// Required, optional, or recommended membership when applicable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub requirement: Option<MemberRequirement>,
    /// Source-qualified component identity.
    pub component: String,
    /// Exact content or contract hash, when available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_hash: Option<String>,
    /// Existing approval scope; never source, author, organization, or wildcard.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub approval_scope: Option<String>,
    /// Exact existing approval value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub approval_value: Option<String>,
    /// Whether the exact current record already exists.
    pub approval_reused: bool,
    /// Current review state.
    pub state: ReviewDecisionState,
    /// Stable explanation, including invalidation causes.
    pub diagnostic: String,
    /// Component-specific security and behavior facts.
    pub facts: Vec<ReviewFact>,
    /// Per-target mappings and compatibility.
    pub targets: Vec<ReviewTargetFact>,
}

/// One stable label/value fact shown before a decision.
#[derive(Debug, Clone, Serialize)]
pub struct ReviewFact {
    /// Stable fact label.
    pub label: String,
    /// Human- and machine-readable value.
    pub value: String,
}

/// Target-specific component mapping retained from the installation plan.
#[derive(Debug, Clone, Serialize)]
pub struct ReviewTargetFact {
    /// Logical target ID.
    pub target: String,
    /// Effective target component state.
    pub state: TargetComponentState,
    /// Adapter compatibility result.
    pub compatibility: PlanCompatibility,
    /// Proposed native or portable representation.
    pub mapping: String,
    /// Selected authored fallback, when any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fallback: Option<String>,
}

/// Result of the explicit final transaction.
#[derive(Debug, Clone, Serialize)]
pub struct PluginReviewCommit {
    /// Root plugin whose snapshot was committed.
    pub root_plugin: String,
    /// Token verified immediately before the write.
    pub review_token: String,
    /// Exact separately scoped values added to the approval ledger.
    pub granted: Vec<ApprovalRecord>,
    /// Displayed pending decisions the user declined or skipped.
    pub declined: Vec<String>,
    /// Whether the approval ledger changed.
    pub changed: bool,
}

/// Build one deterministic review without executing tools, hooks, generators,
/// semantic reviewers, or provider mutations.
pub fn build(store_root: &Path, plugin_ref: &str) -> DaloResult<PluginReviewReport> {
    let paths = StorePaths::new(store_root.to_path_buf());
    let config = store::read_config(&paths)?;
    let approvals = store::read_approvals(&paths)?;
    let live = crate::resolver::resolve_from_config(&config, approvals.approvals.clone());
    let inventories = live
        .scans
        .iter()
        .filter_map(|scan| scan.inventory.clone())
        .collect::<Vec<_>>();
    let canonical = crate::plugin::normalize_plugin_reference(&config, &inventories, plugin_ref)
        .map_err(|reason| DaloError::StateError { reason })?;
    if !live
        .plugins
        .plugins
        .iter()
        .any(|plugin| plugin.source_ref == canonical)
    {
        return Err(DaloError::InvalidArgument {
            reason: format!(
                "plugin `{canonical}` is not selected; run `dalo plugin select {canonical}` first"
            ),
        });
    }
    let closure = dependency_closure(&live.plugins, &canonical);
    let mut plan = crate::plan::build_installation_plan(store_root, None)?;
    filter_plan(&mut plan, &closure);

    let plugin_closure = plan
        .canonical_plugins
        .plugins
        .iter()
        .map(|plugin| ReviewPlugin {
            source_ref: plugin.source_ref.clone(),
            package_hash: plugin.package_hash.clone(),
            closure_hash: plugin.closure_hash.clone(),
            state: plugin.state,
            blocking_reasons: plugin.blocking_reasons.clone(),
        })
        .collect::<Vec<_>>();
    let mut decisions = Vec::new();
    for plugin in &plan.canonical_plugins.plugins {
        for member in &plugin.members {
            decisions.push(member_decision(
                &paths,
                &plan,
                &inventories,
                &approvals.approvals,
                &plugin.source_ref,
                member,
            ));
        }
    }
    for status in &plan.tools {
        decisions.push(tool_decision(&plan, &approvals.approvals, status));
    }
    for status in &plan.hooks {
        decisions.push(hook_decision(&plan, &approvals.approvals, status));
    }
    decisions.sort_by(|left, right| {
        left.plugin
            .cmp(&right.plugin)
            .then(left.kind.cmp(&right.kind))
            .then(left.component.cmp(&right.component))
    });
    let review_token = review_token(&canonical, &plugin_closure, &decisions, &plan)?;
    Ok(PluginReviewReport {
        schema_version: PLUGIN_REVIEW_SCHEMA_VERSION,
        root_plugin: canonical,
        plugin_closure,
        installation_plan: plan,
        decisions,
        review_token,
        interactive_approvals: InteractiveApprovals::Available,
        read_only: true,
    })
}

/// Commit an explicitly selected subset after rebuilding and matching the exact
/// review token. All records are appended with one atomic approval-ledger write.
pub fn commit(
    store_root: &Path,
    plugin_ref: &str,
    expected_token: &str,
    selected: &BTreeSet<String>,
) -> DaloResult<PluginReviewCommit> {
    let paths = StorePaths::new(store_root.to_path_buf());
    let current = build(store_root, plugin_ref)?;
    if current.review_token != expected_token {
        return Err(DaloError::StateError {
            reason: "plugin review changed after display; no approvals were granted—review again"
                .to_owned(),
        });
    }
    let pending = current
        .decisions
        .iter()
        .filter(|decision| {
            matches!(
                decision.state,
                ReviewDecisionState::Pending | ReviewDecisionState::Invalidated
            ) && decision.approval_value.is_some()
        })
        .map(|decision| (decision.id.as_str(), decision))
        .collect::<BTreeMap<_, _>>();
    for id in selected {
        if !pending.contains_key(id.as_str()) {
            return Err(DaloError::InvalidArgument {
                reason: format!("decision `{id}` was not shown as approvable; nothing was written"),
            });
        }
    }

    // Validate every selected boundary before preparing any inert tool bytes.
    for id in selected {
        let decision = pending[id.as_str()];
        if decision.kind == ReviewDecisionKind::SkillContent {
            let report = audit::audit_target(
                &paths,
                &decision.component,
                &AuditOptions {
                    persist: false,
                    ..AuditOptions::default()
                },
            )?;
            if report.is_blocking()
                || decision.content_hash.as_deref() != Some(report.content_hash.as_str())
            {
                return Err(DaloError::AuditBlocked {
                    reason: format!(
                        "skill `{}` no longer matches its displayed non-blocking audit",
                        decision.component
                    ),
                });
            }
        }
        if decision.kind == ReviewDecisionKind::HookBinding {
            let hook = crate::hook::show(&paths, &decision.component)?;
            let tool_id = format!("tool:{}", hook.hook.tool_source_ref);
            if hook.tool_state != ToolState::Ready && !selected.contains(&tool_id) {
                return Err(DaloError::StateError {
                    reason: format!(
                        "hook `{}` requires its separately reviewed tool `{}`",
                        decision.component, hook.hook.tool_source_ref
                    ),
                });
            }
        }
    }
    for id in selected {
        let decision = pending[id.as_str()];
        if decision.kind == ReviewDecisionKind::ToolExecution {
            crate::tool::prepare_approval(
                &paths,
                &decision.component,
                decision
                    .approval_value
                    .as_deref()
                    .expect("pending tool approval value"),
            )?;
        }
    }

    let mut approvals = store::read_approvals(&paths)?;
    let mut granted = Vec::new();
    for id in selected {
        let decision = pending[id.as_str()];
        let record = ApprovalRecord::granted(
            decision
                .approval_scope
                .clone()
                .expect("pending approval scope"),
            decision
                .approval_value
                .clone()
                .expect("pending approval value"),
        );
        if !approvals
            .approvals
            .iter()
            .any(|approval| approval.matches(&record))
        {
            approvals.approvals.push(record.clone());
            granted.push(record);
        }
    }
    approvals.approvals.sort_by(|left, right| {
        left.scope
            .cmp(&right.scope)
            .then(left.value.cmp(&right.value))
    });
    if !granted.is_empty() {
        store::write_approvals(&paths, &approvals)?;
    }
    let declined = pending
        .keys()
        .filter(|id| !selected.contains(**id))
        .map(|id| (*id).to_owned())
        .collect();
    Ok(PluginReviewCommit {
        root_plugin: current.root_plugin,
        review_token: expected_token.to_owned(),
        changed: !granted.is_empty(),
        granted,
        declined,
    })
}

fn dependency_closure(plugins: &crate::plugin::PluginResolution, root: &str) -> BTreeSet<String> {
    let mut closure = BTreeSet::new();
    let mut queue = VecDeque::from([root.to_owned()]);
    while let Some(identity) = queue.pop_front() {
        if !closure.insert(identity.clone()) {
            continue;
        }
        if let Some(plugin) = plugins
            .plugins
            .iter()
            .find(|plugin| plugin.source_ref == identity)
        {
            for dependency in &plugin.dependencies {
                if dependency.state == PluginDependencyState::Selected
                    && let Some(resolved) = &dependency.resolved_ref
                {
                    queue.push_back(resolved.clone());
                }
            }
        }
    }
    closure
}

fn filter_plan(plan: &mut InstallationPlan, closure: &BTreeSet<String>) {
    plan.canonical_plugins
        .plugins
        .retain(|plugin| closure.contains(&plugin.source_ref));
    plan.canonical_plugins.diagnostics.retain(|diagnostic| {
        closure.iter().any(|plugin| {
            diagnostic.subject == *plugin || diagnostic.subject.starts_with(&format!("{plugin}#"))
        })
    });
    plan.tools.retain(|status| {
        closure.iter().any(|plugin| {
            status
                .tool
                .source_ref
                .starts_with(&format!("{plugin}#tool:"))
        })
    });
    plan.hooks.retain(|status| {
        closure.iter().any(|plugin| {
            status
                .hook
                .source_ref
                .starts_with(&format!("{plugin}#hook:"))
        })
    });
    plan.native_plugins
        .retain(|report| closure.contains(&report.plugin));
    // A malformed package cannot be part of the resolved selected closure.
    // Keeping global warnings here would leak unrelated source inventory into
    // a root-specific review and make its JSON churn for unrelated plugins.
    plan.inventory_warnings.clear();
    let skill_slots = plan
        .canonical_plugins
        .plugins
        .iter()
        .flat_map(|plugin| &plugin.members)
        .filter(|member| member.reference.starts_with("skill:"))
        .filter_map(|member| member.resolved_ref.as_deref())
        .filter_map(|identity| identity.split_once(':').map(|(_, slot)| slot.to_owned()))
        .collect::<BTreeSet<_>>();
    for destination in &mut plan.destinations {
        let allowed_links = skill_slots
            .iter()
            .map(|slot| destination.path.join(slot))
            .collect::<BTreeSet<_>>();
        destination
            .portable_operations
            .retain(|operation| allowed_links.contains(&operation.link_path));
        for target in &mut destination.logical_targets {
            target
                .plugins
                .retain(|plugin| closure.contains(&plugin.source_ref));
        }
    }
}

fn member_decision(
    paths: &StorePaths,
    plan: &InstallationPlan,
    inventories: &[crate::inventory::SourceInventory],
    approvals: &[ApprovalRecord],
    plugin: &str,
    member: &crate::plugin::ResolvedPluginMember,
) -> ReviewDecision {
    let component = member
        .resolved_ref
        .clone()
        .unwrap_or_else(|| format!("{plugin}#{}", member.reference));
    let (kind, scope) = if member.reference.starts_with("skill:") {
        (ReviewDecisionKind::SkillContent, Some("skill"))
    } else if member.reference.starts_with("agent:") {
        (ReviewDecisionKind::AgentActivation, Some("agent"))
    } else {
        (ReviewDecisionKind::InstructionRecommendation, None)
    };
    let approval_value = scope.and(member.resolved_ref.clone());
    let approval_reused = scope.is_some_and(|scope| {
        approval_value.as_ref().is_some_and(|value| {
            approvals
                .iter()
                .any(|record| record.scope == scope && record.value == *value)
        })
    });
    let mut content_hash = None;
    let mut facts = Vec::new();
    let mut diagnostic = format!("canonical component is {}", member.state);
    let mut state = match member.state {
        PluginComponentState::Active => ReviewDecisionState::Reused,
        PluginComponentState::PendingApproval => ReviewDecisionState::Pending,
        PluginComponentState::Inactive | PluginComponentState::Available => {
            ReviewDecisionState::Inactive
        }
        PluginComponentState::Shadowed
        | PluginComponentState::Blocked
        | PluginComponentState::Missing
        | PluginComponentState::Ambiguous => ReviewDecisionState::Blocked,
    };
    if kind == ReviewDecisionKind::SkillContent && member.resolved_ref.is_some() {
        match audit::audit_target(
            paths,
            &component,
            &AuditOptions {
                persist: false,
                ..AuditOptions::default()
            },
        ) {
            Ok(audit) => {
                content_hash = Some(audit.content_hash.clone());
                facts.push(fact(
                    "audit_status",
                    format!("{:?}", audit.status).to_ascii_lowercase(),
                ));
                facts.push(fact(
                    "audit_coverage",
                    format!("{:?}", audit.coverage).to_ascii_lowercase(),
                ));
                facts.push(fact("audit_findings", audit.static_findings.len()));
                if audit.is_blocking() {
                    state = ReviewDecisionState::Blocked;
                    diagnostic =
                        "deterministic content audit has unaccepted blocking findings".to_owned();
                }
            }
            Err(error) => {
                state = ReviewDecisionState::Blocked;
                diagnostic = format!("content audit failed: {error}");
            }
        }
        if let Some(compatibility) = inventories
            .iter()
            .flat_map(|inventory| &inventory.skills)
            .find(|skill| skill.source_ref == component)
            .and_then(|skill| skill.compatibility.as_deref())
        {
            facts.push(fact("compatibility", compatibility));
        }
    } else if kind == ReviewDecisionKind::AgentActivation {
        if let Some(agent) = inventories
            .iter()
            .flat_map(|inventory| &inventory.agents)
            .find(|agent| agent.source_ref == component)
        {
            content_hash = Some(agent.content_hash.clone());
            facts.push(fact("description", &agent.description));
            facts.push(fact("required_skills", agent.skills.join(",")));
            facts.push(fact(
                "targets",
                agent
                    .targets
                    .clone()
                    .unwrap_or_else(|| vec!["all".to_owned()])
                    .join(","),
            ));
            facts.push(fact("support_files", agent.has_support_files));
        }
    } else {
        facts.push(fact(
            "activation",
            "recommendation only; plugin review never enables instruction packs",
        ));
        state = ReviewDecisionState::Inactive;
    }
    let targets = target_facts(plan, plugin, &member.reference, &component);
    ReviewDecision {
        id: format!("{}:{component}", kind_id(kind)),
        plugin: plugin.to_owned(),
        kind,
        requirement: Some(member.requirement),
        component,
        content_hash,
        approval_scope: scope.map(str::to_owned),
        approval_value,
        approval_reused,
        state,
        diagnostic,
        facts,
        targets,
    }
}

fn tool_decision(
    plan: &InstallationPlan,
    approvals: &[ApprovalRecord],
    status: &crate::tool::ToolStatusReport,
) -> ReviewDecision {
    let reused = approvals.iter().any(|record| {
        record.scope == crate::tool::APPROVAL_SCOPE && record.value == status.approval_value
    });
    let state = match status.state {
        ToolState::Ready => ReviewDecisionState::Reused,
        ToolState::PendingApproval | ToolState::Revoked => ReviewDecisionState::Pending,
        ToolState::HashDrift => ReviewDecisionState::Invalidated,
        ToolState::PlatformMismatch
        | ToolState::RuntimeMissing
        | ToolState::ApprovedNotStaged
        | ToolState::AuditFailure => ReviewDecisionState::Blocked,
    };
    let plugin = status
        .tool
        .source_ref
        .split_once("#tool:")
        .map_or("", |(plugin, _)| plugin)
        .to_owned();
    ReviewDecision {
        id: format!("tool:{}", status.tool.source_ref),
        plugin: plugin.clone(),
        kind: ReviewDecisionKind::ToolExecution,
        requirement: None,
        component: status.tool.source_ref.clone(),
        content_hash: Some(status.tool.contract_hash.clone()),
        approval_scope: Some(crate::tool::APPROVAL_SCOPE.to_owned()),
        approval_value: Some(status.approval_value.clone()),
        approval_reused: reused,
        state,
        diagnostic: status.diagnostic.clone(),
        facts: vec![
            fact("entry", &status.tool.entry),
            fact(
                "runtime",
                format!("{:?}", status.tool.runtime).to_ascii_lowercase(),
            ),
            fact("capabilities", format!("{:?}", status.tool.capabilities)),
            fact("environment", status.tool.env.join(",")),
            fact("closure_files", status.tool.files.len()),
        ],
        targets: target_facts(
            plan,
            &plugin,
            &status.tool.source_ref,
            &status.tool.source_ref,
        ),
    }
}

fn hook_decision(
    plan: &InstallationPlan,
    approvals: &[ApprovalRecord],
    status: &crate::hook::HookStatusReport,
) -> ReviewDecision {
    let reused = approvals.iter().any(|record| {
        record.scope == crate::hook::APPROVAL_SCOPE && record.value == status.approval_value
    });
    let state = match status.state {
        HookTrustState::Ready => ReviewDecisionState::Reused,
        HookTrustState::PendingApproval => ReviewDecisionState::Pending,
        HookTrustState::HashDrift => ReviewDecisionState::Invalidated,
        // The referenced tool may be approved in the same final transaction.
        HookTrustState::ToolUnavailable if !reused => ReviewDecisionState::Pending,
        HookTrustState::ToolUnavailable => ReviewDecisionState::Blocked,
    };
    let plugin = status
        .hook
        .source_ref
        .split_once("#hook:")
        .map_or("", |(plugin, _)| plugin)
        .to_owned();
    let descriptor = &status.hook.descriptor;
    ReviewDecision {
        id: format!("hook:{}", status.hook.source_ref),
        plugin: plugin.clone(),
        kind: ReviewDecisionKind::HookBinding,
        requirement: Some(match descriptor.requirement {
            crate::hook::HookRequirement::Required => MemberRequirement::Required,
            crate::hook::HookRequirement::Optional => MemberRequirement::Optional,
        }),
        component: status.hook.source_ref.clone(),
        content_hash: Some(status.hook.contract_hash.clone()),
        approval_scope: Some(crate::hook::APPROVAL_SCOPE.to_owned()),
        approval_value: Some(status.approval_value.clone()),
        approval_reused: reused,
        state,
        diagnostic: status.diagnostic.clone(),
        facts: vec![
            fact("tool", &status.hook.tool_source_ref),
            fact(
                "event",
                format!("{:?}/{:?}", descriptor.subject, descriptor.phase),
            ),
            fact(
                "effect",
                format!("{:?}", descriptor.effect).to_ascii_lowercase(),
            ),
            fact("matcher", format!("{:?}", descriptor.matcher.tool_names)),
            fact("timeout_ms", descriptor.timeout_ms),
            fact(
                "failure_policy",
                format!("{:?}", descriptor.failure_policy).to_ascii_lowercase(),
            ),
            fact("bindings", descriptor.bindings.len()),
        ],
        targets: target_facts(
            plan,
            &plugin,
            &status.hook.source_ref,
            &status.hook.source_ref,
        ),
    }
}

pub(crate) fn format_quoted_tokens(values: &[String]) -> String {
    if values.is_empty() {
        return "none".to_owned();
    }
    values
        .iter()
        .map(|value| format!("\"{}\"", escape_display_token(value)))
        .collect::<Vec<_>>()
        .join(" ")
}

fn escape_display_token(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for character in value.chars() {
        match character {
            '\\' => escaped.push_str("\\\\"),
            '"' => escaped.push_str("\\\""),
            character if character.is_control() => {
                escaped.push_str(&format!("\\u{{{:x}}}", character as u32));
            }
            character => escaped.push(character),
        }
    }
    escaped
}

fn target_facts(
    plan: &InstallationPlan,
    plugin: &str,
    authored_reference: &str,
    component: &str,
) -> Vec<ReviewTargetFact> {
    let mut facts = Vec::new();
    for destination in &plan.destinations {
        for target in &destination.logical_targets {
            if let Some(plugin_plan) = target
                .plugins
                .iter()
                .find(|candidate| candidate.source_ref == plugin)
            {
                for candidate in &plugin_plan.components {
                    if candidate.reference == authored_reference || candidate.reference == component
                    {
                        facts.push(ReviewTargetFact {
                            target: target.id.clone(),
                            state: candidate.state,
                            compatibility: candidate.compatibility,
                            mapping: candidate.proposed_artifact.clone(),
                            fallback: candidate.selected_fallback.clone(),
                        });
                    }
                }
            }
        }
    }
    facts.sort_by(|left, right| left.target.cmp(&right.target));
    facts.dedup_by(|left, right| left.target == right.target);
    facts
}

fn fact(label: &str, value: impl ToString) -> ReviewFact {
    ReviewFact {
        label: label.to_owned(),
        value: value.to_string(),
    }
}

const fn kind_id(kind: ReviewDecisionKind) -> &'static str {
    match kind {
        ReviewDecisionKind::SkillContent => "skill",
        ReviewDecisionKind::AgentActivation => "agent",
        ReviewDecisionKind::InstructionRecommendation => "instruction",
        ReviewDecisionKind::ToolExecution => "tool",
        ReviewDecisionKind::HookBinding => "hook",
    }
}

fn review_token(
    root: &str,
    plugins: &[ReviewPlugin],
    decisions: &[ReviewDecision],
    plan: &InstallationPlan,
) -> DaloResult<String> {
    let decision_facts = decisions
        .iter()
        .map(|decision| {
            let targets = decision
                .targets
                .iter()
                .map(|target| {
                    let mapping = if decision.kind == ReviewDecisionKind::ToolExecution {
                        decision
                            .content_hash
                            .as_ref()
                            .map(|hash| format!("immutable tool root sha256:{hash}"))
                    } else {
                        Some(target.mapping.clone())
                    };
                    serde_json::json!({
                        "target": target.target,
                        "state": target.state,
                        "compatibility": target.compatibility,
                        "mapping": mapping,
                        "fallback": target.fallback,
                    })
                })
                .collect::<Vec<_>>();
            serde_json::json!({
                "id": decision.id,
                "plugin": decision.plugin,
                "kind": decision.kind,
                "requirement": decision.requirement,
                "component": decision.component,
                "content_hash": decision.content_hash,
                "approval_scope": decision.approval_scope,
                "approval_value": decision.approval_value,
                "approval_reused": decision.approval_reused,
                "state": decision.state,
                "facts": decision.facts,
                "targets": targets,
            })
        })
        .collect::<Vec<_>>();
    let target_facts = plan
        .destinations
        .iter()
        .map(|destination| {
            let logical_targets = destination
                .logical_targets
                .iter()
                .map(|target| {
                    let plugins = target
                        .plugins
                        .iter()
                        .map(|plugin| {
                            let components = plugin
                                .components
                                .iter()
                                .map(|component| {
                                    serde_json::json!({
                                        "reference": component.reference,
                                        "requirement": component.requirement,
                                        "canonical_state": component.canonical_state,
                                        "state": component.state,
                                        "compatibility": component.compatibility,
                                        "authored_fallback": component.authored_fallback,
                                        "selected_fallback": component.selected_fallback,
                                        "blocker": component.blocker,
                                    })
                                })
                                .collect::<Vec<_>>();
                            serde_json::json!({
                                "source_ref": plugin.source_ref,
                                "state": plugin.state,
                                "compatibility": plugin.compatibility,
                                "dependencies": plugin.dependencies,
                                "components": components,
                                "blockers": plugin.blockers,
                            })
                        })
                        .collect::<Vec<_>>();
                    serde_json::json!({
                        "id": target.id,
                        "verification_baseline": target.verification_baseline,
                        "plugins": plugins,
                    })
                })
                .collect::<Vec<_>>();
            serde_json::json!({
                "path": destination.path,
                "logical_targets": logical_targets,
            })
        })
        .collect::<Vec<_>>();
    let native_facts = plan
        .native_plugins
        .iter()
        .map(|projection| {
            let components = projection
                .components
                .iter()
                .map(|component| {
                    serde_json::json!({
                        "identity": component.identity,
                        "kind": component.kind,
                        "native_path": component.native_path,
                        "content_hash": component.content_hash,
                    })
                })
                .collect::<Vec<_>>();
            serde_json::json!({
                "target": projection.target,
                "plugin": projection.plugin,
                "native_name": projection.native_name,
                "path": projection.path,
                "adapter_baseline": projection.adapter_baseline,
                "state": projection.state,
                "components": components,
            })
        })
        .collect::<Vec<_>>();
    let bytes = serde_json::to_vec(&(root, plugins, decision_facts, target_facts, native_facts))?;
    let digest = Sha256::digest(bytes);
    Ok(format!(
        "sha256:{}",
        digest
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect::<String>()
    ))
}