arcature-cli 2026.1.1

Developer lifecycle CLI for Arcature applications.
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
//! The publish executor (RV2.9).
//!
//! Executes a validated Release Plan in topological order. The engine is
//! idempotent and resumable: an already-published target version is
//! verified and skipped; a partial run resumes from the first missing
//! crate; 429 (rate-limited) is retried with bounded backoff; 401/403/
//! build errors fail fast (ADR-0005 invariant 11).
//!
//! Crate version tags are created only after publish success (ADR-0005
//! invariant 19). They are **outputs**, never the selection source.
//!
//! The executor is driven by two boundary traits:
//! - [`RegistryInspector`] — check whether a version already exists.
//! - [`Publisher`] — perform the actual publish (returns a status code).
//! - [`TagCreator`] — create a git tag after publish success.
//!
//! In production these are the real implementations (cargo publish, git
//! tag). In tests they are fakes. This separation keeps the engine pure
//! and testable without a network (ADR-0005 invariant 15).

use std::collections::BTreeMap;

use crate::release::publish::plan::LoadedPlan;
use crate::release::publish::registry::{RegistryInspector, RegistryStatus};
use crate::release::publish::report::{CrateResult, PublishReport};
use crate::release::publish::retry::{PublishOutcome, classify_status, decide_retry};
use crate::release::publish::tag::CrateTag;
use crate::release::version::Ybf;

/// The boundary that performs a single crate publish. Returns the HTTP
/// status code of the registry response (or a synthetic code for build
/// failures).
#[allow(dead_code)]
pub(crate) trait Publisher {
    /// Publish `crate_name` at `version`. Returns an HTTP-like status
    /// code: 200/201 success, 409 already exists, 429 rate limited,
    /// 401/403 auth failed, 400 build error.
    fn publish_crate(&mut self, crate_name: &str, version: &Ybf) -> u16;
}

/// The boundary that creates a git tag after publish success.
#[allow(dead_code)]
pub(crate) trait TagCreator {
    /// Create a tag `tag` pointing at the current HEAD. Returns `Ok(())`
    /// on success, or an error message on failure.
    fn create_tag(&mut self, tag: &str) -> Result<(), String>;
}

/// Execute a validated Release Plan. Returns a complete report of what
/// happened to each crate.
///
/// The engine processes crates in topological order (from the plan's
/// `order` field). For each crate:
/// 1. Inspect the registry: if already published, skip (idempotent).
/// 2. If absent, publish with bounded retry on 429.
/// 3. On success, create the crate version tag.
/// 4. On failure (401/403/build error/exhausted retries), fail fast:
///    remaining crates are skipped.
#[allow(dead_code)]
pub(crate) fn execute_plan(
    plan: &LoadedPlan,
    registry: &mut dyn RegistryInspector,
    publisher: &mut dyn Publisher,
    tag_creator: &mut dyn TagCreator,
) -> PublishReport {
    let mut results: BTreeMap<String, CrateResult> = BTreeMap::new();
    let ordered = plan.ordered_entries();
    let mut failed = false;
    let mut failure_reason = String::new();

    for entry in &ordered {
        if failed {
            results.insert(
                entry.crate_name.clone(),
                CrateResult::Skipped {
                    reason: format!("prior failure: {failure_reason}"),
                },
            );
            continue;
        }

        // 1. Idempotent: check if already published.
        match registry.check_version(&entry.crate_name, &entry.version) {
            RegistryStatus::Published => {
                results.insert(entry.crate_name.clone(), CrateResult::AlreadyPublished);
                continue;
            }
            RegistryStatus::Absent => { /* proceed to publish */ }
            RegistryStatus::VersionMismatch { expected, found } => {
                failed = true;
                failure_reason = format!(
                    "version mismatch for {}: expected {expected}, found {found}",
                    entry.crate_name
                );
                results.insert(
                    entry.crate_name.clone(),
                    CrateResult::Failed {
                        reason: failure_reason.clone(),
                    },
                );
                continue;
            }
        }

        // 2. Publish with bounded retry.
        let mut attempt: u32 = 1;
        let outcome = loop {
            let status = publisher.publish_crate(&entry.crate_name, &entry.version);
            let this_outcome = classify_status(status);

            match decide_retry(&this_outcome, attempt) {
                crate::release::publish::retry::RetryDecision::Retry { attempt: next, .. } => {
                    attempt = next;
                    // In a real run, sleep here. The pure engine does not
                    // sleep — the boundary layer handles timing. For
                    // testing, the loop simply retries immediately.
                    continue;
                }
                crate::release::publish::retry::RetryDecision::Fail => {
                    break this_outcome;
                }
            }
        };

        match outcome {
            PublishOutcome::Success => {
                // 3. Create the crate version tag (only after success).
                let tag = CrateTag::render(&entry.crate_name, &entry.version);
                match tag_creator.create_tag(&tag) {
                    Ok(()) => {
                        results.insert(entry.crate_name.clone(), CrateResult::Published { tag });
                    }
                    Err(error) => {
                        failed = true;
                        failure_reason =
                            format!("tag creation failed for {}: {error}", entry.crate_name);
                        results.insert(
                            entry.crate_name.clone(),
                            CrateResult::Failed {
                                reason: failure_reason.clone(),
                            },
                        );
                    }
                }
            }
            PublishOutcome::AlreadyPublished => {
                // The registry confirmed it exists during the publish
                // attempt (409). Treat as idempotent skip.
                results.insert(entry.crate_name.clone(), CrateResult::AlreadyPublished);
            }
            PublishOutcome::RateLimited
            | PublishOutcome::AuthFailed
            | PublishOutcome::BuildFailed
            | PublishOutcome::Failed => {
                failed = true;
                failure_reason = format!(
                    "publish {crate} v{version} failed: {outcome:?}",
                    crate = entry.crate_name,
                    version = entry.version,
                );
                results.insert(
                    entry.crate_name.clone(),
                    CrateResult::Failed {
                        reason: failure_reason.clone(),
                    },
                );
            }
        }
    }

    let all_published = !failed
        && results.values().all(|r| {
            matches!(
                r,
                CrateResult::Published { .. } | CrateResult::AlreadyPublished
            )
        });

    PublishReport {
        transaction_id: plan.transaction_id.clone(),
        commit: plan.commit.clone(),
        results,
        all_published,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::release::publish::plan::{LoadedEntry, LoadedPlan};
    use crate::release::publish::registry::FakeRegistry;
    use crate::release::version::Ybf;
    use std::collections::BTreeMap;

    // --- Test doubles ---

    struct FakePublisher {
        responses: Vec<(String, Ybf, u16)>,
        calls: Vec<(String, Ybf)>,
    }

    impl FakePublisher {
        /// Build a publisher that returns canned status codes based on
        /// the crate name and version. The `responses` list is checked
        /// in order; the first matching response wins.
        fn new(responses: Vec<(&str, &str, u16)>) -> Self {
            Self {
                responses: responses
                    .into_iter()
                    .map(|(c, v, s)| (c.to_string(), Ybf::parse(v).unwrap(), s))
                    .collect(),
                calls: Vec::new(),
            }
        }
    }

    impl Publisher for FakePublisher {
        fn publish_crate(&mut self, crate_name: &str, version: &Ybf) -> u16 {
            self.calls.push((crate_name.to_string(), *version));
            for (name, ver, status) in &self.responses {
                if name == crate_name && *ver == *version {
                    return *status;
                }
            }
            201
        }
    }

    struct FakeTagCreator {
        created: Vec<String>,
        fail: bool,
    }

    impl FakeTagCreator {
        fn new() -> Self {
            Self {
                created: Vec::new(),
                fail: false,
            }
        }

        fn failing() -> Self {
            Self {
                created: Vec::new(),
                fail: true,
            }
        }
    }

    impl TagCreator for FakeTagCreator {
        fn create_tag(&mut self, tag: &str) -> Result<(), String> {
            if self.fail {
                return Err("simulated tag failure".to_string());
            }
            self.created.push(tag.to_string());
            Ok(())
        }
    }

    fn make_plan(entries: Vec<LoadedEntry>) -> LoadedPlan {
        let map: BTreeMap<String, LoadedEntry> = entries
            .into_iter()
            .map(|e| (e.crate_name.clone(), e))
            .collect();
        LoadedPlan {
            transaction_id: "2026-08-15.01".to_string(),
            commit: "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0".to_string(),
            entries: map,
        }
    }

    fn entry(name: &str, version: &str, order: usize) -> LoadedEntry {
        LoadedEntry {
            crate_name: name.to_string(),
            version: Ybf::parse(version).unwrap(),
            order,
        }
    }

    // --- Tests ---

    #[test]
    fn publish_all_success() {
        let plan = make_plan(vec![
            entry("arcature-auth", "2026.1.7", 1),
            entry("arcature-cli", "2026.1.9", 2),
        ]);
        let mut registry = FakeRegistry::default();
        let mut publisher = FakePublisher::new(vec![]);
        let mut tags = FakeTagCreator::new();

        let report = execute_plan(&plan, &mut registry, &mut publisher, &mut tags);

        assert!(report.all_published);
        assert_eq!(report.published_count(), 2);
        assert_eq!(report.failed_count(), 0);
        assert_eq!(
            tags.created,
            vec!["arcature-auth-v2026.1.7", "arcature-cli-v2026.1.9"]
        );
    }

    #[test]
    fn idempotent_skip_already_published() {
        let plan = make_plan(vec![entry("arcature-auth", "2026.1.7", 1)]);
        let mut registry = FakeRegistry::default();
        registry
            .published
            .insert(("arcature-auth".to_string(), "2026.1.7".to_string()), true);
        let mut publisher = FakePublisher::new(vec![]);
        let mut tags = FakeTagCreator::new();

        let report = execute_plan(&plan, &mut registry, &mut publisher, &mut tags);

        assert!(report.all_published);
        assert_eq!(report.published_count(), 0);
        assert_eq!(report.already_published_count(), 1);
        // No tag should be created for already-published crates.
        assert!(tags.created.is_empty());
    }

    #[test]
    fn partial_failure_skips_remaining() {
        let plan = make_plan(vec![
            entry("arcature-auth", "2026.1.7", 1),
            entry("arcature-cli", "2026.1.9", 2),
            entry("arcature-jobs", "2026.1.5", 3),
        ]);
        let mut registry = FakeRegistry::default();
        // auth publishes OK (default 201), cli fails with 403.
        let mut publisher = FakePublisher::new(vec![("arcature-cli", "2026.1.9", 403)]);
        let mut tags = FakeTagCreator::new();

        let report = execute_plan(&plan, &mut registry, &mut publisher, &mut tags);

        assert!(!report.all_published);
        assert_eq!(report.published_count(), 1);
        assert_eq!(report.failed_count(), 1);
        assert_eq!(report.skipped_count(), 1);
        assert!(matches!(
            report.results.get("arcature-auth"),
            Some(CrateResult::Published { .. })
        ));
        assert!(matches!(
            report.results.get("arcature-cli"),
            Some(CrateResult::Failed { .. })
        ));
        assert!(matches!(
            report.results.get("arcature-jobs"),
            Some(CrateResult::Skipped { .. })
        ));
    }

    #[test]
    fn build_error_fails_fast() {
        let plan = make_plan(vec![
            entry("arcature-auth", "2026.1.7", 1),
            entry("arcature-cli", "2026.1.9", 2),
        ]);
        let mut registry = FakeRegistry::default();
        let mut publisher = FakePublisher::new(vec![("arcature-auth", "2026.1.7", 400)]);
        let mut tags = FakeTagCreator::new();

        let report = execute_plan(&plan, &mut registry, &mut publisher, &mut tags);

        assert!(!report.all_published);
        assert_eq!(report.failed_count(), 1);
        assert_eq!(report.skipped_count(), 1);
    }

    #[test]
    fn tag_creation_failure_stops_remaining() {
        let plan = make_plan(vec![
            entry("arcature-auth", "2026.1.7", 1),
            entry("arcature-cli", "2026.1.9", 2),
        ]);
        let mut registry = FakeRegistry::default();
        let mut publisher = FakePublisher::new(vec![]);
        let mut tags = FakeTagCreator::failing();

        let report = execute_plan(&plan, &mut registry, &mut publisher, &mut tags);

        assert!(!report.all_published);
        assert_eq!(report.failed_count(), 1);
        assert_eq!(report.skipped_count(), 1);
        assert!(matches!(
            report.results.get("arcature-auth"),
            Some(CrateResult::Failed { .. })
        ));
    }

    #[test]
    fn empty_plan_succeeds() {
        let plan = make_plan(vec![]);
        let mut registry = FakeRegistry::default();
        let mut publisher = FakePublisher::new(vec![]);
        let mut tags = FakeTagCreator::new();

        let report = execute_plan(&plan, &mut registry, &mut publisher, &mut tags);

        assert!(report.all_published);
        assert_eq!(report.results.len(), 0);
    }

    #[test]
    fn registry_409_treated_as_already_published() {
        let plan = make_plan(vec![entry("arcature-auth", "2026.1.7", 1)]);
        let mut registry = FakeRegistry::default();
        // The registry says absent, but the publisher returns 409
        // (already exists on the registry).
        let mut publisher = FakePublisher::new(vec![("arcature-auth", "2026.1.7", 409)]);
        let mut tags = FakeTagCreator::new();

        let report = execute_plan(&plan, &mut registry, &mut publisher, &mut tags);

        assert!(report.all_published);
        assert_eq!(report.already_published_count(), 1);
        assert_eq!(report.published_count(), 0);
        // No tag created for already-published.
        assert!(tags.created.is_empty());
    }
}