canic-cli 0.112.0

Operator CLI for Canic fleet setup, builds, evidence, catalog, backup, and restore workflows
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
// Ensure status defaults to the local environment and ordinary `icp` binary.

use super::*;
use crate::test_support::{TempDir, temp_dir};
use canic_contracts::{
    dto::fleet_registry::FleetRegistry,
    ids::{
        AppId, CanonicalNetworkId, FleetAdmissionPolicy, FleetBinding, FleetCoordinatorBinding,
        FleetId, FleetKey, FleetRegistryAuthority, SubnetId,
    },
};
use canic_host::fleet_ensure::{
    CurrentFleetInventoryError,
    model::{
        CycleConservation, FLEET_ENSURE_SCHEMA_VERSION, FleetEnsureCompletion,
        FleetEnsureJournalRecord, FleetEnsurePlan, FleetEnsurePlanScope, FleetEnsureStateRecord,
        FleetEnsureTopologyRecord,
    },
    ops::{
        EnsurePaths, EnsureStateError, read_journal, read_state, write_journal, write_plan,
        write_state,
    },
    resolve_current_fleet,
};
use ic_platform::principal::ExternalPrincipal as Principal;
use std::{collections::BTreeMap, fs};

#[test]
fn parses_status_options() {
    let default_options = StatusOptions::parse([]).expect("parse default options");
    assert_eq!(default_options.environment, "local");
    assert_eq!(default_options.icp, "icp");

    let options = StatusOptions::parse([
        OsString::from(crate::cli::globals::INTERNAL_ENVIRONMENT_OPTION),
        OsString::from("ic"),
        OsString::from(crate::cli::globals::INTERNAL_ICP_OPTION),
        OsString::from("/tmp/icp"),
    ])
    .expect("parse explicit options");
    assert_eq!(options.environment, "ic");
    assert_eq!(options.icp, "/tmp/icp");
}

// Ensure App configs and current Fleets render as independent inventories.
#[test]
fn renders_status_report() {
    let report = StatusReport {
        environment: "local".to_string(),
        replica: ReplicaStatus::Running,
        replica_port: "8000".to_string(),
        icp_cli: "icp 0.2.5".to_string(),
        icp_config: "ok (icp.yaml)".to_string(),
        canonical_network_id: "network-1".to_string(),
        apps: vec![
            StatusAppRow {
                app: "shop".to_string(),
                config: "apps/demo/canic.toml".to_string(),
                canisters: "4".to_string(),
            },
            StatusAppRow {
                app: "test".to_string(),
                config: "apps/test/canic.toml".to_string(),
                canisters: "7".to_string(),
            },
        ],
        fleets: vec![StatusFleetRow {
            fleet: "staging".to_string(),
            app: "shop".to_string(),
            network: "network-1".to_string(),
            deployed: "yes".to_string(),
            coordinator: "aaaaa-aa".to_string(),
        }],
    };

    let rendered = render_status_report(&report);

    assert!(rendered.contains("Apps: 2 configured"));
    assert!(rendered.contains("Fleets: 1/1 deployed (environment local, network network-1)"));
    assert!(rendered.contains("APP    CONFIG                 CANISTERS"));
    assert!(rendered.contains("shop   apps/demo/canic.toml   4"));
    assert!(rendered.contains("FLEET     APP    NETWORK     DEPLOYED   COORDINATOR"));
    assert!(rendered.contains("staging   shop   network-1   yes        aaaaa-aa"));
    assert!(!rendered.contains("DEPLOYMENT"));
}

// Ensure workspaces without App configs still render a useful quick status.
#[test]
fn renders_empty_status_report() {
    let report = StatusReport {
        environment: "local".to_string(),
        replica: ReplicaStatus::Stopped,
        replica_port: "8001".to_string(),
        icp_cli: "icp 0.2.5".to_string(),
        icp_config: "not checked (no Canic App configs)".to_string(),
        canonical_network_id: "network-1".to_string(),
        apps: Vec::new(),
        fleets: Vec::new(),
    };

    assert_eq!(
        render_status_report(&report),
        "Replica: stopped (local, port 8001)\nICP CLI: icp 0.2.5\nICP config: not checked (no Canic App configs)\nApps: 0 configured\nFleets: 0/0 deployed (environment local, network network-1)"
    );
}

#[test]
fn status_headers_escape_external_text_before_joining_tables() {
    let injected = "value\nforged\x1b]52;c;dGVzdA==\x07\u{202e}";
    let report = StatusReport {
        environment: injected.into(),
        replica: ReplicaStatus::Error(injected.into()),
        replica_port: injected.into(),
        icp_cli: injected.into(),
        icp_config: injected.into(),
        canonical_network_id: injected.into(),
        apps: vec![StatusAppRow {
            app: "界".into(),
            config: "apps/demo/canic.toml".into(),
            canisters: "1".into(),
        }],
        fleets: Vec::new(),
    };
    let rendered = render_status_report(&report);
    assert_eq!(rendered.lines().count(), 9);
    assert!(!rendered.contains(['\x1b', '\x07', '\u{202e}']));
    assert!(rendered.contains(r"value\nforged\u{1b}]52;c;dGVzdA==\u{7}\u{202e}"));
    assert!(rendered.lines().any(|line| line.starts_with("界")));
}

// Ensure foreground/untracked replicas are visible instead of being silently
// collapsed into ordinary ICP CLI-managed status.
#[test]
fn renders_http_fallback_replica_status() {
    let report = StatusReport {
        environment: "local".to_string(),
        replica: ReplicaStatus::RunningHttpFallback,
        replica_port: "8000".to_string(),
        icp_cli: "icp 0.2.6".to_string(),
        icp_config: "ok (icp.yaml)".to_string(),
        canonical_network_id: "network-1".to_string(),
        apps: Vec::new(),
        fleets: Vec::new(),
    };

    assert_eq!(
        render_status_report(&report),
        "Replica: running (local, port 8000, HTTP reachable; ICP CLI status stopped)\nICP CLI: icp 0.2.6\nICP config: ok (icp.yaml)\nApps: 0 configured\nFleets: 0/0 deployed (environment local, network network-1)"
    );
}

// Ensure status renders config paths relative to the resolved Canic workspace root.
#[test]
fn status_app_inventory_uses_workspace_root_for_config_paths() {
    let root = temp_dir("canic-status-workspace-root");
    let config = root.join("apps/toko/canic.toml");
    fs::create_dir_all(config.parent().expect("config parent")).expect("create config parent");
    fs::write(
        &config,
        r#"
[app]
name = "toko"

[roles.root]
kind = "root"

[roles.app]
kind = "canister"
package = "app"

[auth.delegated_tokens]
enabled = false


[component_specs.app]
component_role = "app"
maximum_instances = 1
"#,
    )
    .expect("write config");

    let inventory = load_status_apps(&root, std::slice::from_ref(&config));
    let row = inventory.first().expect("status App row");

    fs::remove_dir_all(root).expect("remove temp root");
    assert_eq!(row.app, "toko");
    assert_eq!(row.config, "apps/toko/canic.toml");
    assert_eq!(row.canisters, "2");
}

#[test]
fn fleet_status_uses_terminal_registry_app_binding() {
    let fleet = current_fleet_summary();
    let row = status_fleet_row(&fleet);

    assert_eq!(row.fleet, "demo");
    assert_eq!(row.app, "shop");
    assert_ne!(row.fleet, row.app);
    assert_eq!(row.network, fleet.canonical_network_id.to_string());
    assert_eq!(row.deployed, "yes");
    assert_eq!(row.coordinator, fleet.coordinator);
}

#[test]
fn terminal_ensure_is_the_status_fleet_source() {
    let root = temp_dir("canic-status-terminal-ensure-reproduction");
    fs::create_dir_all(&root).expect("create workspace root");
    fs::write(
        root.join("icp.yaml"),
        "environments:\n  - name: staging\n    network: ic\n  - name: production\n    network: ic\n",
    )
    .expect("write ICP config");
    retain_terminal_fleet(&root, "staging", "demo");
    retain_terminal_fleet(&root, "staging", "pending");
    let pending_paths = EnsurePaths::under(&root, "staging", "pending");
    let mut pending = read_journal(&pending_paths)
        .expect("read pending journal")
        .expect("pending journal");
    pending.completion = FleetEnsureCompletion::InProgress;
    write_journal(&pending_paths, &pending).expect("retain pending journal");

    resolve_current_fleet(&root, "staging", "demo").expect("terminal Fleet authority");
    let discovery = discover_current_fleets(&root, "staging").expect("status Fleet source");
    let production = discover_current_fleets(&root, "production").expect("production status");
    let rows = discovery
        .fleets
        .iter()
        .map(status_fleet_row)
        .collect::<Vec<_>>();

    assert_eq!(discovery.environment, "staging");
    assert!(production.fleets.is_empty());
    assert_eq!(
        discovery.canonical_network_id,
        CanonicalNetworkId::ic_mainnet()
    );
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].fleet, "demo");
    assert_eq!(rows[0].app, "shop");
    assert_eq!(
        rows[0].network,
        CanonicalNetworkId::ic_mainnet().to_string()
    );
    assert_eq!(rows[0].deployed, "yes");
    assert_eq!(rows[0].coordinator, "rrkah-fqaaa-aaaaa-aaaaq-cai");

    retain_terminal_fleet(&root, "staging", "duplicate");
    assert!(matches!(
        discover_current_fleets(&root, "staging"),
        Err(CurrentFleetInventoryError::DuplicateDiscoveryAuthority {
            field: "Fleet ID",
            ..
        })
    ));

    fs::remove_dir_all(root).expect("remove fixture");
}

#[test]
fn status_discovers_fleets_with_null_and_omitted_release_without_writes() {
    let root = TempDir::new("canic-status-optional-release");
    fs::create_dir_all(&root).unwrap();
    fs::write(
        root.join("icp.yaml"),
        "environments:\n  - name: staging\n    network: ic\n",
    )
    .unwrap();
    retain_terminal_fleet(&root, "staging", "demo");
    retain_terminal_fleet(&root, "staging", "other");
    let paths = EnsurePaths::under(&root, "staging", "other");
    let coordinator = Principal::from_text("aaaaa-aa").unwrap();
    let mut state = read_state(&paths, "other").unwrap();
    let registry = state.active_registry.as_mut().unwrap();
    let fleet_id = FleetId::from_generated_bytes([8; 32]);
    registry.authority.binding.fleet.fleet.fleet_id = fleet_id;
    registry.authority.binding.coordinator = coordinator;
    registry.admission.fleet.fleet.fleet_id = fleet_id;
    state
        .principals
        .insert("coordinator".into(), coordinator.to_text());
    write_state(&paths, &state).unwrap();
    let mut journal: serde_json::Value =
        serde_json::from_slice(&fs::read(&paths.journal).unwrap()).unwrap();
    journal.as_object_mut().unwrap().remove("release");
    fs::write(&paths.journal, serde_json::to_vec(&journal).unwrap()).unwrap();
    let original = [EnsurePaths::under(&root, "staging", "demo"), paths]
        .into_iter()
        .flat_map(|paths| [paths.journal, paths.plan, paths.state])
        .map(|path| {
            let bytes = fs::read(&path).unwrap();
            (path, bytes)
        })
        .collect::<Vec<_>>();
    let discovery = discover_current_fleets(&root, "staging").unwrap();
    let rows = discovery
        .fleets
        .iter()
        .map(status_fleet_row)
        .collect::<Vec<_>>();
    assert_eq!(
        rows.iter()
            .map(|row| row.fleet.as_str())
            .collect::<Vec<_>>(),
        ["demo", "other"]
    );
    assert_eq!(rows[0].coordinator, "rrkah-fqaaa-aaaaa-aaaaq-cai");
    assert_eq!(rows[1].coordinator, coordinator.to_text());
    assert!(
        rows.iter()
            .all(|row| row.deployed == "yes" && row.app == "shop")
    );
    for (path, bytes) in original {
        assert_eq!(fs::read(path).unwrap(), bytes);
    }
}

#[test]
fn omitted_release_keeps_discovery_record_and_plan_authority_checks() {
    let root = TempDir::new("canic-status-optional-release-refusal");
    fs::create_dir_all(&root).unwrap();
    fs::write(
        root.join("icp.yaml"),
        "environments:\n  - name: staging\n    network: ic\n",
    )
    .unwrap();
    retain_terminal_fleet(&root, "staging", "demo");
    let paths = EnsurePaths::under(&root, "staging", "demo");
    let mut journal: serde_json::Value =
        serde_json::from_slice(&fs::read(&paths.journal).unwrap()).unwrap();
    journal.as_object_mut().unwrap().remove("release");
    let mut malformed = journal.clone();
    malformed["release"] = serde_json::json!({"plan_sha256": "22".repeat(32)});
    let mut incomplete = journal.clone();
    incomplete
        .as_object_mut()
        .unwrap()
        .remove("bootstrap_registration_recovery");
    for rejected in [malformed, incomplete] {
        fs::write(&paths.journal, serde_json::to_vec(&rejected).unwrap()).unwrap();
        std::assert_matches!(discover_current_fleets(&root, "staging"),
            Err(CurrentFleetInventoryError::State(EnsureStateError::Decode { source, .. })) if source.is_data());
    }
    journal["plan_sha256"] = serde_json::json!("44".repeat(32));
    fs::write(&paths.journal, serde_json::to_vec(&journal).unwrap()).unwrap();
    std::assert_matches!(discover_current_fleets(&root, "staging"),
        Err(CurrentFleetInventoryError::PlanAuthorityConflict { fleet }) if fleet == "demo");
}

// Ensure Fleet discovery never follows an environment-level directory symlink.
#[cfg(unix)]
#[test]
fn terminal_ensure_discovery_rejects_symlinked_environment_directory() {
    let root = temp_dir("canic-status-terminal-ensure-symlink");
    let target = root.join("terminal-ensure-target");
    let discovery_parent = root.join(".canic/fleet-ensure");
    fs::create_dir_all(&target).expect("create symlink target");
    fs::create_dir_all(&discovery_parent).expect("create discovery parent");
    fs::write(
        root.join("icp.yaml"),
        "environments:\n  - name: staging\n    network: ic\n",
    )
    .expect("write ICP config");
    std::os::unix::fs::symlink(&target, discovery_parent.join("staging"))
        .expect("symlink discovery directory");

    assert!(matches!(
        discover_current_fleets(&root, "staging"),
        Err(CurrentFleetInventoryError::UnsafeDiscoveryPath { .. })
    ));

    fs::remove_dir_all(root).expect("remove fixture");
}

// Ensure status help points to the compact workspace summary command.
#[test]
fn status_usage_lists_options_and_examples() {
    let text = usage();

    assert!(text.contains("Show quick local workspace status"));
    assert!(text.contains("Usage: canic status"));
    assert!(!text.contains("--environment"));
    assert!(!text.contains("--icp"));
    assert!(text.contains("Examples:"));
    assert!(text.contains("validated terminal Fleet Ensure state"));
    assert!(text.contains("does not query live Coordinator"));
}

fn current_fleet_summary() -> CurrentFleetSummary {
    CurrentFleetSummary {
        app: AppId::from("shop"),
        canonical_network_id: canic_contracts::ids::CanonicalNetworkId::ic_mainnet(),
        coordinator: "aaaaa-aa".to_string(),
        fleet: "demo".parse().expect("Fleet name"),
        fleet_id: FleetId::from_generated_bytes([7; 32]),
    }
}

fn retain_terminal_fleet(root: &Path, environment: &str, fleet_name: &str) {
    let network = CanonicalNetworkId::ic_mainnet();
    let coordinator =
        Principal::from_text("rrkah-fqaaa-aaaaa-aaaaq-cai").expect("Coordinator Principal");
    let registry = terminal_registry(network, coordinator);
    let operation_id = "11".repeat(32);
    let plan_sha256 = "22".repeat(32);
    let paths = EnsurePaths::under(root, environment, fleet_name);
    write_state(
        &paths,
        &FleetEnsureStateRecord {
            active_registry: Some(registry),
            completed_reinstall_action_sha256: BTreeMap::new(),
            completed_reinstall_operation_id: None,
            completed_reinstalls: BTreeMap::new(),
            fleet: fleet_name.to_string(),
            pending_principals: BTreeMap::new(),
            principals: BTreeMap::from([("coordinator".to_string(), coordinator.to_text())]),
            retained_cycles_by_principal: BTreeMap::new(),
            schema_version: FLEET_ENSURE_SCHEMA_VERSION,
            topology: BTreeMap::from([(
                "coordinator".to_string(),
                FleetEnsureTopologyRecord {
                    kind: canic_host::fleet_ensure::model::DesiredCanisterKind::Coordinator,
                    module_hash: None,
                    parent: None,
                    protocol_binding: None,
                    role: None,
                },
            )]),
        },
    )
    .expect("write terminal state");
    write_plan(
        &paths,
        &FleetEnsurePlan {
            continuation: None,
            canisters: Vec::new(),
            conservation: CycleConservation {
                estate_funding_domains: Vec::new(),
                expected_post_operation_cycles: 0,
                maximum_execution_burn_cycles: 0,
                maximum_new_funding_cycles: 0,
                maximum_operator_debit_cycles: 0,
                maximum_unavoidable_fee_cycles: 0,
                observed_controlled_cycles: 0,
                retained_in_reused_canisters_cycles: 0,
                scheduled_transfer_cycles: 0,
            },
            desired_sha256: "33".repeat(32),
            environment: environment.to_string(),
            fleet: fleet_name.to_string(),
            operation_id: operation_id.clone(),
            plan_sha256: plan_sha256.clone(),
            planned_at_time: 1,
            protocol_actions: Vec::new(),
            recovery_review: None,
            reinstall: None,
            infrastructure_bootstrap: None,
            root_reinstall_bindings: Vec::new(),
            root_start_authority: None,
            reviewed_desired: None,
            schema_version: FLEET_ENSURE_SCHEMA_VERSION,
            scope: FleetEnsurePlanScope::Full,
            terminal_inventory_operation_id: Some(operation_id.clone()),
        },
    )
    .expect("write terminal plan");
    write_journal(
        &paths,
        &FleetEnsureJournalRecord {
            release: None,
            bootstrap_registration_recovery: None,
            funding_observations: BTreeMap::new(),
            funding_reviews: Vec::new(),
            successor_phases: Vec::new(),
            completion: FleetEnsureCompletion::Converged,
            estate_funding_required: None,
            effects: Vec::new(),
            fleet: fleet_name.to_string(),
            initial_controlled_cycles: 0,
            initial_estate_funding_cycles_by_root: BTreeMap::new(),
            initial_operator_cycles: 0,
            operation_id,
            plan_sha256,
            schema_version: FLEET_ENSURE_SCHEMA_VERSION,
            stalled_observations: 0,
        },
    )
    .expect("write terminal journal");
}

fn terminal_registry(network: CanonicalNetworkId, coordinator: Principal) -> FleetRegistry {
    let fleet = FleetBinding {
        fleet: FleetKey {
            canonical_network_id: network,
            fleet_id: FleetId::from_generated_bytes([7; 32]),
        },
        app: AppId::from("shop"),
    };
    FleetRegistry {
        authority: FleetRegistryAuthority {
            binding: FleetCoordinatorBinding {
                fleet: fleet.clone(),
                coordinator_subnet: SubnetId::from_principal(
                    Principal::from_text("rwlgt-iiaaa-aaaaa-aaaaa-cai")
                        .expect("Coordinator Subnet Principal"),
                ),
                coordinator,
                recovery_controllers: Vec::new(),
            },
            epoch: 1,
        },
        revision: 1,
        admission: FleetAdmissionPolicy {
            schema_version: 1,
            fleet,
            generation: 1,
            fleet_principals: Vec::new(),
            rules: Vec::new(),
            policy_digest: [0; 32],
        },
        component_specs: Vec::new(),
        fleet_subnet_roots: Vec::new(),
        services: Vec::new(),
    }
}