vela-cli 0.940.9

The vela command-line tool: build, check, sign, replay, and publish scientific frontier state.
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
//! Private producer work for current repository epochs.
//!
//! A current Attempt is ignored authoring state. It binds one exact Target
//! Offer and repository read set, but creates no canonical lease, Event,
//! authority record, or scientific standing.

use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};

use chrono::{Duration, SecondsFormat, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::cli::safe_text;

const ATTEMPT_SCHEMA: &str = "vela.attempt.v2";
const TASK_CONTRACT_SCHEMA: &str = "vela.task-contract.internal.v2";
const ATTEMPT_MAX_BYTES: usize = 2 * 1024 * 1024;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct CurrentTaskContract {
    schema: String,
    objective: String,
    completion_condition: String,
    allowed_actions: Vec<String>,
    forbidden_actions: Vec<String>,
    required_outputs: Vec<String>,
    required_checks: Vec<String>,
    escalation_path: String,
    authority_ceiling: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct CurrentAttempt {
    pub(crate) schema: String,
    pub(crate) attempt_id: String,
    pub(crate) frontier_id: String,
    pub(crate) target: String,
    pub(crate) actor: String,
    pub(crate) created_at: String,
    pub(crate) expires_at: String,
    task_contract: CurrentTaskContract,
    pub(crate) task_contract_root: String,
    pub(crate) target_task_binding: vela_edge::target_index::TargetTaskBindingV2,
    briefing: Value,
}

pub(crate) struct CurrentSubmissionAttempt {
    pub(crate) attempt: CurrentAttempt,
    pub(crate) path: PathBuf,
    _lock: AttemptLock,
}

fn canonical_root(value: &impl Serialize) -> Result<String, String> {
    Ok(format!(
        "sha256:{}",
        vela_protocol::canonical::sha256_canonical(value)?
    ))
}

fn contract(
    packet: &Value,
    target: &vela_edge::target_index::TargetIndexEntryV2,
) -> CurrentTaskContract {
    let objective = packet
        .get("statement")
        .and_then(Value::as_str)
        .map(|statement| format!("Produce decision-relevant evidence for: {statement}"))
        .or_else(|| {
            packet
                .get("objective")
                .and_then(Value::as_str)
                .map(ToString::to_string)
        })
        .unwrap_or_else(|| target.objective.clone());
    let mut required_outputs = packet
        .get("allowed_outputs")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(|output| output.get("type").and_then(Value::as_str))
        .map(ToString::to_string)
        .collect::<Vec<_>>();
    if required_outputs.is_empty() {
        required_outputs.push(
            "one evidence artifact or one deliberately informative negative result".to_string(),
        );
    }
    required_outputs.sort();
    required_outputs.dedup();
    CurrentTaskContract {
        schema: TASK_CONTRACT_SCHEMA.to_string(),
        objective,
        completion_condition:
            "Create one valid Submission whose evidence and caveats address this exact target."
                .to_string(),
        allowed_actions: vec![
            "inspect the pinned repository, packet, and task contract".to_string(),
            "run frozen verifiers and private search or experiment loops".to_string(),
            "create bounded evidence artifacts and one Submission".to_string(),
        ],
        forbidden_actions: vec![
            "accept, reject, apply, finalize, or sign a truth-bearing proposal".to_string(),
            "read or use a human or repository-authority signing key".to_string(),
            "hand-edit current repository records or derived views".to_string(),
            "treat producer output as verification or scientific acceptance".to_string(),
        ],
        required_outputs,
        required_checks: vec![
            "run every producer-side check claimed by the Submission".to_string(),
            "state at least one scope limit or explicit no-known-limit caveat".to_string(),
            "keep artifacts repository-relative, bounded, and content-addressed".to_string(),
        ],
        escalation_path:
            "Submit for independent Verification and an authorized terminal decision.".to_string(),
        authority_ceiling:
            "Private producer evidence only; this Attempt grants no repository or scientific authority."
                .to_string(),
    }
}

fn attempt_id(
    frontier_id: &str,
    target: &str,
    actor: &str,
    task_contract_root: &str,
    binding_root: &str,
) -> Result<String, String> {
    let preimage = json!({
        "schema": ATTEMPT_SCHEMA,
        "frontier_id": frontier_id,
        "target": target,
        "actor": actor,
        "task_contract_root": task_contract_root,
        "target_task_binding_root": binding_root,
    });
    Ok(format!(
        "vat_{}",
        vela_protocol::canonical::sha256_canonical(&preimage)?
    ))
}

fn safe_session_dir(frontier: &Path, target: &str) -> PathBuf {
    crate::workflow::session_dir(frontier, target)
}

fn attempt_path(frontier: &Path, target: &str) -> PathBuf {
    safe_session_dir(frontier, target).join("attempt.json")
}

fn validate(attempt: &CurrentAttempt) -> Result<(), String> {
    if attempt.schema != ATTEMPT_SCHEMA {
        return Err(format!(
            "unsupported current Attempt schema {}",
            attempt.schema
        ));
    }
    if attempt.task_contract.schema != TASK_CONTRACT_SCHEMA
        || canonical_root(&attempt.task_contract)? != attempt.task_contract_root
    {
        return Err("current Attempt task contract does not match its root".to_string());
    }
    attempt.target_task_binding.validate()?;
    if attempt.frontier_id != attempt.target_task_binding.frontier_id
        || attempt.target != attempt.target_task_binding.target_id
    {
        return Err("current Attempt does not match its target binding".to_string());
    }
    let expected = attempt_id(
        &attempt.frontier_id,
        &attempt.target,
        &attempt.actor,
        &attempt.task_contract_root,
        &attempt.target_task_binding.binding_root,
    )?;
    if attempt.attempt_id != expected {
        return Err("current Attempt identity does not match its closed preimage".to_string());
    }
    chrono::DateTime::parse_from_rfc3339(&attempt.created_at)
        .map_err(|error| format!("current Attempt created_at: {error}"))?;
    chrono::DateTime::parse_from_rfc3339(&attempt.expires_at)
        .map_err(|error| format!("current Attempt expires_at: {error}"))?;
    Ok(())
}

fn encode(attempt: &CurrentAttempt) -> Result<Vec<u8>, String> {
    validate(attempt)?;
    let mut bytes =
        serde_json::to_vec_pretty(attempt).map_err(|error| format!("encode Attempt: {error}"))?;
    bytes.push(b'\n');
    if bytes.len() > ATTEMPT_MAX_BYTES {
        return Err(format!(
            "current Attempt is {} bytes; limit is {ATTEMPT_MAX_BYTES}",
            bytes.len()
        ));
    }
    Ok(bytes)
}

fn read(path: &Path) -> Result<CurrentAttempt, String> {
    let metadata = fs::symlink_metadata(path)
        .map_err(|error| format!("inspect current Attempt {}: {error}", path.display()))?;
    if metadata.file_type().is_symlink()
        || !metadata.is_file()
        || metadata.len() > ATTEMPT_MAX_BYTES as u64
    {
        return Err(format!(
            "current Attempt must be a bounded regular non-symlink file: {}",
            path.display()
        ));
    }
    let bytes = fs::read(path)
        .map_err(|error| format!("read current Attempt {}: {error}", path.display()))?;
    let attempt: CurrentAttempt = serde_json::from_slice(&bytes)
        .map_err(|error| format!("parse current Attempt {}: {error}", path.display()))?;
    validate(&attempt)?;
    Ok(attempt)
}

pub(crate) fn resolve_submission_attempt(
    frontier: &Path,
    actor: &str,
    requested_attempt: Option<&str>,
) -> Result<Option<CurrentSubmissionAttempt>, String> {
    let Some(requested_attempt) = requested_attempt else {
        return Ok(None);
    };
    let work = frontier.join(".vela/work");
    let mut matches = fs::read_dir(&work)
        .map_err(|error| format!("read current Attempt root {}: {error}", work.display()))?
        .filter_map(Result::ok)
        .map(|entry| entry.path().join("attempt.json"))
        .filter(|path| path.is_file())
        .map(|path| read(&path).map(|attempt| (path, attempt)))
        .collect::<Result<Vec<_>, String>>()?
        .into_iter()
        .filter(|(_, attempt)| attempt.attempt_id == requested_attempt)
        .collect::<Vec<_>>();
    let [(path, attempt)] = matches.as_mut_slice() else {
        return Err(format!(
            "current Attempt {requested_attempt:?} must resolve to exactly one private record; found {}",
            matches.len()
        ));
    };
    if attempt.actor != actor {
        return Err(format!(
            "current Attempt {requested_attempt} belongs to {}, not {actor}",
            attempt.actor
        ));
    }
    let expires_at = chrono::DateTime::parse_from_rfc3339(&attempt.expires_at)
        .map_err(|error| format!("current Attempt expires_at: {error}"))?;
    if expires_at <= Utc::now() {
        return Err(format!("current Attempt {requested_attempt} has expired"));
    }
    vela_edge::target_index::revalidate_current_target_task_binding(
        frontier,
        &attempt.target_task_binding,
    )?;
    let lock = lock_attempt(frontier, &attempt.target)?;
    Ok(Some(CurrentSubmissionAttempt {
        attempt: attempt.clone(),
        path: path.clone(),
        _lock: lock,
    }))
}

pub(crate) fn close_submission_attempt(
    resolved: Option<CurrentSubmissionAttempt>,
) -> Result<(), String> {
    let Some(resolved) = resolved else {
        return Ok(());
    };
    match fs::remove_file(&resolved.path) {
        Ok(()) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => {
            return Err(format!(
                "Submission registered but Attempt cleanup failed at {}: {error}",
                resolved.path.display()
            ));
        }
    }
    if let Some(directory) = resolved.path.parent() {
        let _ = fs::remove_dir(directory);
    }
    Ok(())
}

fn ensure_private_directory(path: &Path, label: &str) -> Result<(), String> {
    match fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_dir() => Err(format!(
            "{label} must be a real directory: {}",
            path.display()
        )),
        Ok(_) => Ok(()),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => fs::create_dir(path)
            .map_err(|error| format!("create {label} {}: {error}", path.display())),
        Err(error) => Err(format!("inspect {label} {}: {error}", path.display())),
    }
}

struct AttemptLock {
    _file: fs::File,
}

fn lock_attempt(frontier: &Path, target: &str) -> Result<AttemptLock, String> {
    let vela = frontier.join(".vela");
    ensure_private_directory(&vela, "Frontier private directory")?;
    let work = vela.join("work");
    ensure_private_directory(&work, "Attempt root")?;
    let directory = safe_session_dir(frontier, target);
    ensure_private_directory(&directory, "Attempt directory")?;
    let path = directory.join(".lock");
    if let Ok(metadata) = fs::symlink_metadata(&path)
        && (metadata.file_type().is_symlink() || !metadata.is_file())
    {
        return Err(format!(
            "Attempt lock must be a regular non-symlink file: {}",
            path.display()
        ));
    }
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&path)
        .map_err(|error| format!("open Attempt lock {}: {error}", path.display()))?;
    if !file
        .metadata()
        .map_err(|error| format!("inspect Attempt lock {}: {error}", path.display()))?
        .is_file()
    {
        return Err(format!("Attempt lock is not a file: {}", path.display()));
    }
    match file.try_lock() {
        Ok(()) => Ok(AttemptLock { _file: file }),
        Err(std::fs::TryLockError::WouldBlock) => {
            Err(format!("another command is changing target {target}"))
        }
        Err(std::fs::TryLockError::Error(error)) => {
            Err(format!("lock Attempt {}: {error}", path.display()))
        }
    }
}

fn write(frontier: &Path, attempt: &CurrentAttempt) -> Result<PathBuf, String> {
    let bytes = encode(attempt)?;
    let vela = frontier.join(".vela");
    ensure_private_directory(&vela, "Frontier private directory")?;
    let work = vela.join("work");
    ensure_private_directory(&work, "Attempt root")?;
    let directory = safe_session_dir(frontier, &attempt.target);
    ensure_private_directory(&directory, "Attempt directory")?;
    let path = directory.join("attempt.json");
    if let Ok(metadata) = fs::symlink_metadata(&path)
        && (metadata.file_type().is_symlink() || !metadata.is_file())
    {
        return Err(format!(
            "current Attempt must be a regular non-symlink file: {}",
            path.display()
        ));
    }
    let temporary = directory.join(format!(
        ".attempt-{}-{}.tmp",
        std::process::id(),
        &attempt.attempt_id[4..20]
    ));
    let mut options = OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    let result = (|| {
        let mut file = options
            .open(&temporary)
            .map_err(|error| format!("create current Attempt: {error}"))?;
        file.write_all(&bytes)
            .map_err(|error| format!("write current Attempt: {error}"))?;
        file.sync_all()
            .map_err(|error| format!("persist current Attempt: {error}"))?;
        fs::rename(&temporary, &path)
            .map_err(|error| format!("install current Attempt: {error}"))?;
        Ok(path.clone())
    })();
    if result.is_err() {
        let _ = fs::remove_file(&temporary);
    }
    result
}

fn result(attempt: &CurrentAttempt, path: &Path, idempotent: bool) -> Value {
    let packet = &attempt.target_task_binding.packet;
    json!({
        "schema": ATTEMPT_SCHEMA,
        "ok": true,
        "command": "start",
        "idempotent": idempotent,
        "frontier_id": attempt.frontier_id,
        "target_id": attempt.target,
        "attempt": {
            "id": attempt.attempt_id,
            "path": path.display().to_string(),
            "actor": attempt.actor,
            "expires_at": attempt.expires_at,
        },
        "starting_roots": {
            "epoch": attempt.target_task_binding.repository.epoch_id,
            "repository": attempt.target_task_binding.repository.repository_root,
            "target_index": attempt.target_task_binding.target_index_root,
            "task_contract": attempt.task_contract_root,
            "git_commit": attempt.target_task_binding.claim_read_set.git_commit,
            "git_tree": attempt.target_task_binding.claim_read_set.git_tree,
        },
        "task": {
            "objective": attempt.task_contract.objective,
            "completion_condition": attempt.task_contract.completion_condition,
            "required_outputs": attempt.task_contract.required_outputs,
            "required_checks": attempt.task_contract.required_checks,
            "authority_ceiling": attempt.task_contract.authority_ceiling,
        },
        "packet": packet,
        "briefing": attempt.briefing,
        "canonical_write": false,
        "authority_key_read": false,
        "next_command": format!(
            "vela submit --attempt {} --claim <scoped-result> --type <type> --replayability <class> --artifact <path>:<kind> --caveat <limit> --as {} --json",
            attempt.attempt_id, attempt.actor
        ),
    })
}

fn open(frontier: &Path, target_id: &str, actor: &str, ttl_seconds: u64) -> Result<Value, String> {
    if ttl_seconds == 0 || ttl_seconds > vela_protocol::events::MAX_ATTEMPT_LEASE_TTL_SECONDS {
        return Err(format!(
            "private Attempt TTL must be between 1 and {} seconds",
            vela_protocol::events::MAX_ATTEMPT_LEASE_TTL_SECONDS
        ));
    }
    let repository = crate::current_repository::verify_current_repository_at(frontier, true)?;
    let repository_root = repository.canonical_root()?;
    let assessment = vela_edge::target_index::assess_current_target_index(
        frontier,
        &repository.frontier_id,
        &repository.epoch_id,
        &repository_root,
    )?
    .ok_or_else(|| "current repository has no Target Index".to_string())?;
    let target = assessment
        .index
        .targets
        .iter()
        .find(|target| target.id == target_id)
        .cloned()
        .ok_or_else(|| format!("current Target Index has no target {target_id:?}"))?;
    let binding = vela_edge::target_index::build_current_target_task_binding(
        frontier,
        &assessment,
        &repository.frontier_id,
        &repository.epoch_id,
        &repository_root,
        target_id,
    )?;
    let _lock = lock_attempt(frontier, target_id)?;
    let path = attempt_path(frontier, target_id);
    if path.is_file() {
        let existing = read(&path)?;
        if existing.actor != actor {
            return Err(format!(
                "target {target_id} already has a private Attempt owned by {}",
                existing.actor
            ));
        }
        vela_edge::target_index::revalidate_current_target_task_binding(
            frontier,
            &existing.target_task_binding,
        )?;
        let expires_at = chrono::DateTime::parse_from_rfc3339(&existing.expires_at)
            .map_err(|error| format!("current Attempt expires_at: {error}"))?;
        if expires_at <= Utc::now() {
            return Err(format!(
                "target {target_id} has an expired private Attempt; remove it with `vela start {target_id} --drop --as {actor} --reason <reason>`"
            ));
        }
        return Ok(result(&existing, &path, true));
    }
    let packet = assessment
        .packet_value(target_id)
        .cloned()
        .ok_or_else(|| format!("current target {target_id:?} has no verified packet"))?;
    let task_contract = contract(&packet, &target);
    let task_contract_root = canonical_root(&task_contract)?;
    let attempt_id = attempt_id(
        &repository.frontier_id,
        target_id,
        actor,
        &task_contract_root,
        &binding.binding_root,
    )?;
    let created_at = Utc::now();
    let ttl = i64::try_from(ttl_seconds)
        .map_err(|_| "private Attempt TTL exceeds the supported range".to_string())?;
    let expires_at = created_at
        .checked_add_signed(Duration::seconds(ttl))
        .ok_or_else(|| "private Attempt expiry overflowed".to_string())?;
    let attempt = CurrentAttempt {
        schema: ATTEMPT_SCHEMA.to_string(),
        attempt_id,
        frontier_id: repository.frontier_id,
        target: target_id.to_string(),
        actor: actor.to_string(),
        created_at: created_at.to_rfc3339_opts(SecondsFormat::Secs, true),
        expires_at: expires_at.to_rfc3339_opts(SecondsFormat::Secs, true),
        task_contract,
        task_contract_root,
        target_task_binding: binding,
        briefing: json!({
            "schema": "vela.work-briefing.v2",
            "target": target,
            "packet": packet,
        }),
    };
    let path = write(frontier, &attempt)?;
    Ok(result(&attempt, &path, false))
}

fn drop_attempt(frontier: &Path, target: &str, actor: &str, reason: &str) -> Result<Value, String> {
    let reason = reason.trim();
    if reason.is_empty() {
        return Err("start --drop requires a non-empty reason".to_string());
    }
    crate::current_repository::verify_current_repository_at(frontier, true)?;
    let _lock = lock_attempt(frontier, target)?;
    let path = attempt_path(frontier, target);
    let attempt = read(&path)?;
    if attempt.actor != actor {
        return Err(format!(
            "target {target} private Attempt belongs to {}, not {actor}",
            attempt.actor
        ));
    }
    fs::remove_file(&path)
        .map_err(|error| format!("remove private Attempt {}: {error}", path.display()))?;
    let directory = safe_session_dir(frontier, target);
    let _ = fs::remove_dir(&directory);
    Ok(json!({
        "schema": "vela.attempt-drop.v2",
        "ok": true,
        "command": "start.drop",
        "attempt_id": attempt.attempt_id,
        "target_id": target,
        "actor": actor,
        "reason": reason,
        "canonical_write": false,
        "authority_key_read": false,
    }))
}

fn list(frontier: &Path) -> Result<Value, String> {
    crate::current_repository::verify_current_repository_at(frontier, true)?;
    let root = frontier.join(".vela/work");
    let mut attempts = fs::read_dir(&root)
        .into_iter()
        .flatten()
        .filter_map(Result::ok)
        .filter_map(|entry| {
            let path = entry.path().join("attempt.json");
            path.is_file().then_some(path)
        })
        .map(|path| {
            let attempt = read(&path)?;
            Ok(json!({
                "attempt_id": attempt.attempt_id,
                "target_id": attempt.target,
                "actor": attempt.actor,
                "expires_at": attempt.expires_at,
                "path": path.display().to_string(),
            }))
        })
        .collect::<Result<Vec<_>, String>>()?;
    attempts.sort_by(|left, right| left["target_id"].as_str().cmp(&right["target_id"].as_str()));
    Ok(json!({
        "schema": "vela.attempt-list.v2",
        "ok": true,
        "command": "start",
        "attempts": attempts,
    }))
}

pub(crate) fn cmd_start(
    frontier: &Path,
    target: Option<&str>,
    ttl: Option<u64>,
    drop_it: bool,
    reason: Option<&str>,
    actor: &str,
    json_out: bool,
) {
    crate::ui::set_mode("start", json_out);
    let result = match (target, drop_it) {
        (None, false) => list(frontier),
        (None, true) => Err("start --drop requires an exact target".to_string()),
        (Some(target), true) => drop_attempt(
            frontier,
            target,
            actor,
            reason.unwrap_or("producer abandoned the private Attempt"),
        ),
        (Some(_), false) if reason.is_some() => {
            Err("--reason is valid only with start --drop".to_string())
        }
        (Some(target), false) => {
            let ttl = ttl.unwrap_or_else(|| {
                crate::config::settings::try_resolve("work.lease_ttl_seconds", Some(frontier))
                    .unwrap_or_else(|error| crate::cli::fail_return(&error))
                    .0
                    .parse()
                    .unwrap_or_else(|_| {
                        crate::cli::fail_return(
                            "resolved work.lease_ttl_seconds is not a positive integer",
                        )
                    })
            });
            open(frontier, target, actor, ttl)
        }
    }
    .unwrap_or_else(|error| crate::cli::fail_return(&error));
    if json_out {
        crate::cli::print_json(&result);
    } else {
        let command = result["command"].as_str().unwrap_or("start");
        println!(
            "{command} · {}",
            result["target_id"].as_str().unwrap_or("Attempts")
        );
        if let Some(path) = result.pointer("/attempt/path").and_then(Value::as_str) {
            println!("  private {}", safe_text::inline(path));
        }
        if let Some(next) = result["next_command"].as_str() {
            println!("  next    {}", safe_text::inline(next));
        }
    }
}

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

    #[test]
    fn current_attempt_identity_binds_actor_target_contract_and_offer() {
        let first = attempt_id(
            "vfr_1234567890abcdef",
            "erdos:1056",
            "agent:codex",
            &format!("sha256:{}", "1".repeat(64)),
            &format!("sha256:{}", "2".repeat(64)),
        )
        .unwrap();
        let second = attempt_id(
            "vfr_1234567890abcdef",
            "erdos:1056",
            "agent:other",
            &format!("sha256:{}", "1".repeat(64)),
            &format!("sha256:{}", "2".repeat(64)),
        )
        .unwrap();
        assert_ne!(first, second);
        assert!(first.starts_with("vat_"));
    }

    #[test]
    fn current_attempt_round_trips_as_private_state_without_event_fields() {
        let directory = tempfile::tempdir().unwrap();
        fs::create_dir(directory.path().join(".vela")).unwrap();
        let mut binding = vela_edge::target_index::TargetTaskBindingV2 {
            schema: vela_edge::target_index::TARGET_TASK_BINDING_SCHEMA_V2.to_string(),
            frontier_id: "vfr_1234567890abcdef".to_string(),
            target_id: "erdos:1056".to_string(),
            target_index_root: format!("sha256:{}", "1".repeat(64)),
            source: vela_edge::target_index::TargetIndexSourceV2 {
                git_object_format: GitObjectFormat::Sha1,
                git_commit: "2".repeat(40),
                git_tree: "3".repeat(40),
            },
            input_root: format!("sha256:{}", "4".repeat(64)),
            packet: vela_edge::target_index::TargetPacketRefV2 {
                schema: "erdos.problem-work.v1".to_string(),
                path: "packets/1056.json".to_string(),
                size: 42,
                sha256: format!("sha256:{}", "5".repeat(64)),
            },
            repository: vela_edge::target_index::TargetIndexRepositoryV3 {
                epoch_id: "vre_1234567890abcdef".to_string(),
                repository_root: format!("sha256:{}", "6".repeat(64)),
            },
            claim_read_set: vela_edge::target_index::TargetTaskClaimReadSetV2 {
                git_object_format: GitObjectFormat::Sha1,
                git_commit: "7".repeat(40),
                git_tree: "8".repeat(40),
            },
            binding_root: format!("sha256:{}", "0".repeat(64)),
        };
        binding.binding_root = binding.computed_binding_root().unwrap();
        let task_contract = CurrentTaskContract {
            schema: TASK_CONTRACT_SCHEMA.to_string(),
            objective: "Produce one bounded result.".to_string(),
            completion_condition: "Create one Submission.".to_string(),
            allowed_actions: vec!["inspect".to_string()],
            forbidden_actions: vec!["sign".to_string()],
            required_outputs: vec!["artifact".to_string()],
            required_checks: vec!["replay".to_string()],
            escalation_path: "verify".to_string(),
            authority_ceiling: "none".to_string(),
        };
        let task_contract_root = canonical_root(&task_contract).unwrap();
        let attempt = CurrentAttempt {
            schema: ATTEMPT_SCHEMA.to_string(),
            attempt_id: attempt_id(
                &binding.frontier_id,
                &binding.target_id,
                "agent:codex",
                &task_contract_root,
                &binding.binding_root,
            )
            .unwrap(),
            frontier_id: binding.frontier_id.clone(),
            target: binding.target_id.clone(),
            actor: "agent:codex".to_string(),
            created_at: "2026-07-27T00:00:00Z".to_string(),
            expires_at: "2026-07-28T00:00:00Z".to_string(),
            task_contract,
            task_contract_root,
            target_task_binding: binding,
            briefing: json!({"schema": "vela.work-briefing.v2"}),
        };
        let path = write(directory.path(), &attempt).unwrap();
        let decoded = read(&path).unwrap();
        assert_eq!(decoded.attempt_id, attempt.attempt_id);
        let encoded = String::from_utf8(fs::read(path).unwrap()).unwrap();
        assert!(!encoded.contains("event_log_root"));
        assert!(!encoded.contains("claim_event_id"));
        assert!(!encoded.contains("signature"));
    }
}