ready-set 0.1.0-alpha.1

ready, set, go: capability lifecycle orchestration for projects.
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
//! Core capability registry and readiness matrix renderers.

use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::Path;

use ready_set_sdk::config::{Config, load_config};
use ready_set_sdk::describe::Platform;
use ready_set_sdk::manifest::Manifest;
use ready_set_sdk::{
    CapabilityDescriptor, CapabilityId, CapabilityRelevance, CapabilityReport, CapabilityState,
    CapabilityVerb, ProviderId, Result,
};

use crate::cache::PluginCache;
use crate::discovery::list_all;
use crate::metadata::resolve_metadata;

/// One effective capability row after applying project configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegisteredCapability {
    /// Stable capability id.
    pub id: CapabilityId,
    /// Human label for matrix and help output.
    pub title: String,
    /// Effective provider id.
    pub provider: ProviderId,
    /// Supported lifecycle verbs.
    pub verbs: Vec<CapabilityVerb>,
    /// Effective product relevance.
    pub relevance: CapabilityRelevance,
}

impl RegisteredCapability {
    fn from_descriptor(descriptor: CapabilityDescriptor, config: Option<&Config>) -> Self {
        let capability_config = config.and_then(|cfg| cfg.capabilities.get(descriptor.id.as_str()));
        let relevance = capability_config
            .and_then(|cfg| cfg.relevance)
            .unwrap_or(descriptor.default_relevance);
        let provider = capability_config
            .and_then(|cfg| cfg.provider.clone())
            .unwrap_or(descriptor.provider);

        Self {
            id: descriptor.id,
            title: descriptor.title,
            provider,
            verbs: descriptor.verbs,
            relevance,
        }
    }
}

/// Sorted collection of registered capabilities.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CapabilityRegistry {
    capabilities: Vec<RegisteredCapability>,
}

impl CapabilityRegistry {
    /// Build a registry from optional config and already-resolved plugin
    /// manifests.
    ///
    /// Plugin capabilities with duplicate ids keep the first discovered
    /// descriptor unless `.ready-set.toml` selects a later provider.
    pub fn from_parts(
        config: Option<&Config>,
        plugin_manifests: impl IntoIterator<Item = Manifest>,
    ) -> Self {
        let mut descriptors: BTreeMap<String, CapabilityDescriptor> = BTreeMap::new();

        for manifest in plugin_manifests {
            for descriptor in manifest.capabilities {
                let id = descriptor.id.as_str().to_owned();
                match descriptors.entry(id) {
                    std::collections::btree_map::Entry::Vacant(entry) => {
                        entry.insert(descriptor);
                    },
                    std::collections::btree_map::Entry::Occupied(mut entry) => {
                        let selected = provider_override(config, entry.key())
                            .is_some_and(|provider| provider == &descriptor.provider);
                        if selected {
                            entry.insert(descriptor);
                        }
                    },
                }
            }
        }

        let capabilities = descriptors
            .into_values()
            .map(|descriptor| RegisteredCapability::from_descriptor(descriptor, config))
            .collect();

        Self { capabilities }
    }

    /// Discover project config and installed plugins, then build a registry.
    ///
    /// # Errors
    ///
    /// Returns config loading errors from `.ready-set.toml` parsing or I/O.
    pub fn discover(cwd: &Path) -> Result<Self> {
        let config = load_config(cwd)?;
        let mut cache = PluginCache::default_path()
            .as_deref()
            .map_or_else(PluginCache::default, PluginCache::load);
        let current_platform = Platform::current();
        let mut manifests = Vec::new();

        for entry in list_all() {
            let Some(manifest) = resolve_metadata(&entry, &mut cache) else {
                continue;
            };
            if current_platform.is_some_and(|platform| !manifest.platforms.contains(&platform)) {
                continue;
            }
            manifests.push(manifest);
        }

        Ok(Self::from_parts(config.as_ref(), manifests))
    }

    /// Borrow the sorted registered capabilities.
    #[must_use]
    pub fn capabilities(&self) -> &[RegisteredCapability] {
        &self.capabilities
    }

    /// Render unevaluated placeholder reports for every registered capability.
    #[must_use]
    pub fn reports_unevaluated(&self) -> Vec<CapabilityReport> {
        self.capabilities
            .iter()
            .map(|capability| {
                let (state, summary) = match capability.relevance {
                    CapabilityRelevance::NotNeeded => {
                        (CapabilityState::NotNeeded, "capability marked not needed")
                    },
                    CapabilityRelevance::Required | CapabilityRelevance::Optional => {
                        (CapabilityState::Blocked, "readiness not evaluated yet")
                    },
                };
                CapabilityReport {
                    id: capability.id.clone(),
                    title: capability.title.clone(),
                    provider: capability.provider.clone(),
                    state,
                    relevance: capability.relevance,
                    summary: summary.into(),
                    next_action: None,
                }
            })
            .collect()
    }
}

/// Render capability reports as a human-readable readiness matrix.
#[must_use]
pub fn render_human_matrix(reports: &[CapabilityReport]) -> String {
    let capability_width = reports
        .iter()
        .map(|report| report.id.as_str().len())
        .max()
        .unwrap_or(0)
        .max("capability".len());
    let state_width = reports
        .iter()
        .map(|report| state_label(report.state).len())
        .max()
        .unwrap_or(0)
        .max("state".len());
    let action_width = reports
        .iter()
        .map(|report| {
            report
                .next_action
                .as_ref()
                .map_or(0, |action| action.command.len())
        })
        .max()
        .unwrap_or(0)
        .max("next action".len());

    let mut out = String::new();
    writeln!(
        &mut out,
        "{:<capability_width$}  {:<state_width$}  {:<action_width$}  summary",
        "capability", "state", "next action"
    )
    .expect("writing to a string cannot fail");
    for report in reports {
        let next_action = report
            .next_action
            .as_ref()
            .map_or("", |action| action.command.as_str());
        writeln!(
            &mut out,
            "{:<capability_width$}  {:<state_width$}  {:<action_width$}  {}",
            report.id.as_str(),
            state_label(report.state),
            next_action,
            report.summary
        )
        .expect("writing to a string cannot fail");
    }
    out
}

/// Render capability reports as JSON using the SDK report shape.
///
/// # Errors
///
/// Returns a JSON serialization error if a report cannot be serialized.
pub fn render_json_matrix(reports: &[CapabilityReport]) -> Result<String> {
    serde_json::to_string(reports).map_err(Into::into)
}

fn provider_override<'a>(config: Option<&'a Config>, id: &str) -> Option<&'a ProviderId> {
    config?
        .capabilities
        .get(id)
        .and_then(|capability| capability.provider.as_ref())
}

const fn state_label(state: CapabilityState) -> &'static str {
    match state {
        CapabilityState::Ready => "ready",
        CapabilityState::Missing => "missing",
        CapabilityState::Incomplete => "incomplete",
        CapabilityState::Blocked => "blocked",
        CapabilityState::Stale => "stale",
        CapabilityState::Optional => "optional",
        CapabilityState::NotNeeded => "not-needed",
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::path::PathBuf;

    use ready_set_sdk::config::{CapabilityConfig, ProjectMeta};
    use ready_set_sdk::describe::{Platform, Stability};

    use super::*;

    fn config_with(
        overrides: impl IntoIterator<
            Item = (
                &'static str,
                Option<CapabilityRelevance>,
                Option<&'static str>,
            ),
        >,
    ) -> Config {
        let capabilities = overrides
            .into_iter()
            .map(|(id, relevance, provider)| {
                (
                    id.to_string(),
                    CapabilityConfig {
                        relevance,
                        provider: provider.map(ProviderId::from),
                        unknown_keys: Vec::new(),
                    },
                )
            })
            .collect();

        Config {
            path: PathBuf::from(".ready-set.toml"),
            ready_set: ProjectMeta {
                schema_version: 2,
                profile: "rust-workspace".into(),
            },
            capabilities,
            plugins: BTreeMap::new(),
            unknown_keys: Vec::new(),
        }
    }

    fn plugin_manifest(capabilities: Vec<CapabilityDescriptor>) -> Manifest {
        Manifest {
            description: "Plugin".into(),
            version: "0.1.0".parse().unwrap(),
            stability: Stability::Stable,
            min_dispatcher_version: "0.1.0".parse().unwrap(),
            platforms: vec![Platform::Linux, Platform::Macos, Platform::Windows],
            requires_cargo_workspace: false,
            capabilities,
        }
    }

    fn plugin_descriptor(id: &str, title: &str, provider: &str) -> CapabilityDescriptor {
        plugin_descriptor_with_relevance(id, title, provider, CapabilityRelevance::Required)
    }

    fn plugin_descriptor_with_relevance(
        id: &str,
        title: &str,
        provider: &str,
        default_relevance: CapabilityRelevance,
    ) -> CapabilityDescriptor {
        CapabilityDescriptor {
            id: id.into(),
            title: title.into(),
            provider: provider.into(),
            verbs: vec![CapabilityVerb::Ready, CapabilityVerb::Set],
            default_relevance,
        }
    }

    fn ids(registry: &CapabilityRegistry) -> Vec<&str> {
        registry
            .capabilities()
            .iter()
            .map(|capability| capability.id.as_str())
            .collect()
    }

    #[test]
    fn empty_registry_contains_no_core_capabilities() {
        let registry = CapabilityRegistry::from_parts(None, Vec::<Manifest>::new());

        assert!(registry.capabilities().is_empty());
    }

    #[test]
    fn config_only_unknown_capability_ids_are_not_registered() {
        let config = config_with([(
            "unknown",
            Some(CapabilityRelevance::Required),
            Some("missing-provider"),
        )]);
        let registry = CapabilityRegistry::from_parts(Some(&config), Vec::<Manifest>::new());

        assert!(registry.capabilities().is_empty());
    }

    #[test]
    fn registry_output_is_sorted_by_capability_id() {
        let manifest = plugin_manifest(vec![
            plugin_descriptor("zzz", "Zzz", "plugin"),
            plugin_descriptor("aaa", "Aaa", "plugin"),
        ]);
        let registry = CapabilityRegistry::from_parts(None, [manifest]);

        assert_eq!(ids(&registry), vec!["aaa", "zzz"]);
    }

    #[test]
    fn config_relevance_override_changes_effective_relevance() {
        let config = config_with([("linting", Some(CapabilityRelevance::Optional), None)]);
        let manifest = plugin_manifest(vec![plugin_descriptor("linting", "Linting", "rust")]);
        let registry = CapabilityRegistry::from_parts(Some(&config), [manifest]);
        let linting = registry
            .capabilities()
            .iter()
            .find(|capability| capability.id.as_str() == "linting")
            .unwrap();

        assert_eq!(linting.relevance, CapabilityRelevance::Optional);
    }

    #[test]
    fn config_provider_override_changes_effective_provider() {
        let config = config_with([("formatting", None, Some("external-formatting"))]);
        let manifest = plugin_manifest(vec![plugin_descriptor("formatting", "Formatting", "rust")]);
        let registry = CapabilityRegistry::from_parts(Some(&config), [manifest]);
        let formatting = registry
            .capabilities()
            .iter()
            .find(|capability| capability.id.as_str() == "formatting")
            .unwrap();

        assert_eq!(formatting.provider.as_str(), "external-formatting");
    }

    #[test]
    fn unique_plugin_capability_descriptors_are_preserved() {
        let manifest = plugin_manifest(vec![plugin_descriptor_with_relevance(
            "security",
            "Security",
            "scan",
            CapabilityRelevance::Optional,
        )]);
        let registry = CapabilityRegistry::from_parts(None, [manifest]);
        let security = registry
            .capabilities()
            .iter()
            .find(|capability| capability.id.as_str() == "security")
            .unwrap();

        assert_eq!(security.title, "Security");
        assert_eq!(security.provider.as_str(), "scan");
        assert_eq!(security.relevance, CapabilityRelevance::Optional);
    }

    #[test]
    fn duplicate_plugin_capability_keeps_first_without_provider_override() {
        let first = plugin_manifest(vec![plugin_descriptor("linting", "First linting", "first")]);
        let second = plugin_manifest(vec![plugin_descriptor(
            "linting",
            "Second linting",
            "second",
        )]);
        let registry = CapabilityRegistry::from_parts(None, [first, second]);
        let linting = registry
            .capabilities()
            .iter()
            .find(|capability| capability.id.as_str() == "linting")
            .unwrap();

        assert_eq!(linting.title, "First linting");
        assert_eq!(linting.provider.as_str(), "first");
    }

    #[test]
    fn duplicate_plugin_capability_is_used_when_provider_override_selects_it() {
        let config = config_with([("linting", None, Some("second"))]);
        let first = plugin_manifest(vec![plugin_descriptor("linting", "First linting", "first")]);
        let second = plugin_manifest(vec![plugin_descriptor(
            "linting",
            "Second linting",
            "second",
        )]);
        let registry = CapabilityRegistry::from_parts(Some(&config), [first, second]);
        let linting = registry
            .capabilities()
            .iter()
            .find(|capability| capability.id.as_str() == "linting")
            .unwrap();

        assert_eq!(linting.title, "Second linting");
        assert_eq!(linting.provider.as_str(), "second");
    }

    #[test]
    fn json_matrix_round_trips_as_capability_reports() {
        let manifest = plugin_manifest(vec![plugin_descriptor("linting", "Linting", "rust")]);
        let reports = CapabilityRegistry::from_parts(None, [manifest]).reports_unevaluated();
        let json = render_json_matrix(&reports).unwrap();
        let round_tripped: Vec<CapabilityReport> = serde_json::from_str(&json).unwrap();

        assert_eq!(round_tripped, reports);
    }

    #[test]
    fn human_matrix_contains_expected_columns() {
        let manifest = plugin_manifest(vec![plugin_descriptor("linting", "Linting", "rust")]);
        let reports = CapabilityRegistry::from_parts(None, [manifest]).reports_unevaluated();
        let human = render_human_matrix(&reports);

        assert!(human.contains("capability"));
        assert!(human.contains("state"));
        assert!(human.contains("next action"));
        assert!(human.contains("summary"));
    }

    #[test]
    fn not_needed_relevance_produces_not_needed_placeholder_report() {
        let config = config_with([("workspace", Some(CapabilityRelevance::NotNeeded), None)]);
        let manifest = plugin_manifest(vec![plugin_descriptor("workspace", "Workspace", "rust")]);
        let reports =
            CapabilityRegistry::from_parts(Some(&config), [manifest]).reports_unevaluated();
        let workspace = reports
            .iter()
            .find(|report| report.id.as_str() == "workspace")
            .unwrap();

        assert_eq!(workspace.state, CapabilityState::NotNeeded);
        assert_eq!(workspace.summary, "capability marked not needed");
        assert!(workspace.next_action.is_none());
    }
}