intentional-cli 0.5.1

Polyglot intent-driven release CLI
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
// ---
// relationships:
//   implements: intent-driven-polyglot-release
// ---

use anyhow::{bail, Context, Result};
use clap::{Args, Parser, Subcommand};
use intentional_core::{
    check_workspace, initialize_with, ApplyResult, Bump, BumpTranslation, Config, InitOptions,
    InitState, IntentDraft, ReleasePlan, Severity, StampResult, TagPhase, TagResult,
    WorkspaceStatus, CONFIG_PATH, MISSING_BASELINE_CODE, MISSING_BASELINE_NEXT_ACTION,
};
use semver::Version;
use std::collections::{BTreeMap, BTreeSet};
use std::io::{self, Write};
use std::path::PathBuf;

const SKILL_DOCUMENT: &str = include_str!("../skills/intentional/SKILL.md");

#[derive(Debug, Parser)]
#[command(
    name = "intentional",
    version,
    about = "Intent-driven polyglot releases"
)]
struct Cli {
    /// Workspace directory.
    #[arg(short = 'C', long, default_value = ".", global = true)]
    directory: PathBuf,

    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Scan supported manifests and create the release-unit inventory.
    Init(InitArgs),
    /// Write the template-facing Release Model.
    Model(ModelArgs),
    /// Author a pending change intent.
    Add(AddArgs),
    /// Show pending intents and computed release-unit versions.
    Status {
        /// Emit machine-readable workspace status.
        #[arg(long)]
        json: bool,
    },
    /// Emit canonical digest-bound release-plan JSON.
    Plan(ChannelArgs),
    /// Materialize versions, changelogs, dependencies, and intent consumption.
    Apply(ChannelDryRunArgs),
    /// Write computed versions into injected projections only.
    Stamp(StampArgs),
    /// Create annotated tag records or establish baseline tags.
    Tag(TagArgs),
    /// Validate config, intents, and deterministic planning for CI.
    Check,
    /// Verify one established Release or baseline from its annotated tag.
    Verify(VerifyArgs),
    /// Print the agent-facing Intentional workflow skill.
    Skill,
}

#[derive(Debug, Args)]
struct DryRun {
    /// Print mutations without changing the workspace.
    #[arg(long)]
    dry_run: bool,
}

#[derive(Debug, Args)]
struct InitArgs {
    /// Perform the explicit authority handoff from a ready Changesets plan.
    #[arg(long)]
    take_over: bool,

    /// How pending component-style bumps translate: `parity` keeps the next
    /// versions, `significance` keeps the bump names.
    #[arg(long, value_name = "parity|significance")]
    bump_translation: Option<BumpTranslation>,

    /// Emit stable structured JSON.
    #[arg(long)]
    json: bool,

    /// Print mutations without changing the workspace.
    #[arg(long)]
    dry_run: bool,
}

#[derive(Debug, Args)]
struct ModelArgs {
    /// Report the operation without writing.
    #[arg(long)]
    dry_run: bool,
    /// Print canonical model JSON without changing the tree.
    #[arg(long)]
    stdout: bool,
    /// Emit structured operation results.
    #[arg(long, conflicts_with = "stdout")]
    json: bool,
}

#[derive(Debug, Args)]
struct AddArgs {
    /// Release-unit bump as `id:major|minor|patch`; repeat for multiple release units.
    #[arg(long = "release-unit")]
    release_units: Vec<String>,

    /// Graduate this release unit from `0.x` to `1.0.0`; requires its bump to be major.
    #[arg(long = "graduate", value_name = "ID")]
    graduates: Vec<String>,

    /// Changelog prose.
    #[arg(long)]
    message: Option<String>,

    /// Print mutations without changing the workspace.
    #[arg(long)]
    dry_run: bool,
}

#[derive(Debug, Args)]
struct ChannelArgs {
    /// Release channel, such as beta.
    #[arg(long)]
    channel: Option<String>,
}

#[derive(Debug, Args)]
struct ChannelDryRunArgs {
    /// Release channel, such as beta.
    #[arg(long)]
    channel: Option<String>,

    /// Print mutations without changing the workspace.
    #[arg(long)]
    dry_run: bool,
}

#[derive(Debug, Args)]
struct TagArgs {
    /// Release channel, such as beta.
    #[arg(long)]
    channel: Option<String>,

    /// Establish initial annotated tag authority from projections.
    #[arg(long)]
    baseline: bool,

    /// Explicit baseline as `release-unit=X.Y.Z` or `workspace/tag=X.Y.Z`; repeat as needed.
    #[arg(long = "version")]
    versions: Vec<String>,

    /// Executor phase declaration required by configured release tags.
    #[arg(long)]
    phase: Option<String>,

    /// Digest-sealed release plan to verify before creating release tags.
    #[arg(long, value_name = "PATH")]
    plan: Option<PathBuf>,

    /// Print mutations without changing the workspace.
    #[arg(long)]
    dry_run: bool,
}

#[derive(Debug, Args)]
struct VerifyArgs {
    /// Exact annotated tag that identifies the Release or Release Unit.
    tag: String,

    /// Emit stable structured verification results.
    #[arg(long)]
    json: bool,
}

#[derive(Debug, Args)]
struct StampArgs {
    /// Prerelease identifier composed with first-parent tag height.
    #[arg(long)]
    prerelease: Option<String>,

    /// Print mutations without changing the workspace.
    #[arg(long)]
    dry_run: bool,
}

fn main() -> std::process::ExitCode {
    match run() {
        Ok(code) => std::process::ExitCode::from(code),
        Err(error) => {
            eprintln!("{error:#}");
            std::process::ExitCode::FAILURE
        }
    }
}

fn run() -> Result<u8> {
    let cli = Cli::parse();
    match cli.command {
        Command::Init(args) => return init(&cli.directory, args),
        Command::Verify(args) => return verify(&cli.directory, args),
        Command::Add(args) => add(&cli.directory, args),
        Command::Status { json } => status(&cli.directory, json),
        Command::Model(args) => model(&cli.directory, args),
        Command::Plan(args) => plan(&cli.directory, args.channel.as_deref()),
        Command::Apply(args) => apply(&cli.directory, args.channel.as_deref(), args.dry_run),
        Command::Stamp(args) => stamp(&cli.directory, args.prerelease.as_deref(), args.dry_run),
        Command::Tag(args) => tag(&cli.directory, args),
        Command::Check => check(&cli.directory),
        Command::Skill => skill(),
    }?;
    Ok(0)
}

fn verify(root: &std::path::Path, args: VerifyArgs) -> Result<u8> {
    let verification = intentional_core::verify_release(root, &args.tag)?;
    if args.json {
        println!("{}", verification.to_json()?);
    } else {
        match &verification.target {
            Some(target) if verification.verified => {
                println!("verified {} at {target}", verification.tag)
            }
            _ => println!("verification failed for {}", verification.tag),
        }
        for guarantee in &verification.guarantees {
            println!("guarantee: {guarantee}");
        }
        for tag in &verification.identity_tags {
            println!("identity tag: {tag}");
        }
        for diagnostic in &verification.diagnostics {
            let severity = match diagnostic.severity {
                Severity::Error => "error",
                Severity::Advisory => "advisory",
            };
            println!("{severity} [{}] {}", diagnostic.code, diagnostic.message);
        }
    }
    Ok(if verification.verified { 0 } else { 1 })
}

fn skill() -> Result<()> {
    print!("{SKILL_DOCUMENT}");
    Ok(())
}

fn check(root: &std::path::Path) -> Result<()> {
    check_workspace(root)?;
    println!("check passed");
    Ok(())
}

fn tag(root: &std::path::Path, args: TagArgs) -> Result<()> {
    let phase = args.phase.as_deref().map(parse_phase).transpose()?;
    let mut explicit = BTreeMap::new();
    for value in args.versions {
        let (id, version) = value
            .split_once('=')
            .with_context(|| format!("baseline version must be id=X.Y.Z; got {value}"))?;
        let version = Version::parse(version)?;
        if explicit.insert(id.to_owned(), version).is_some() {
            bail!("baseline version {id} was specified more than once");
        }
    }
    if args.baseline && args.channel.is_some() {
        bail!("--baseline and --channel cannot be combined");
    }
    if args.baseline && args.plan.is_some() {
        bail!("--baseline and --plan cannot be combined");
    }
    if !args.baseline && !explicit.is_empty() {
        bail!("--version is valid only with --baseline");
    }
    let result = if args.baseline {
        TagResult::build_baseline(root, &explicit)?
    } else {
        let plan_path = args.plan.as_ref().map(|path| {
            if path.is_absolute() {
                path.clone()
            } else {
                root.join(path)
            }
        });
        TagResult::build_with_plan(root, args.channel.as_deref(), phase, plan_path.as_deref())?
    };
    for operation in result.operations() {
        println!("{operation}");
    }
    result.apply(root, args.dry_run)?;
    Ok(())
}

fn stamp(root: &std::path::Path, prerelease: Option<&str>, dry_run: bool) -> Result<()> {
    let result = StampResult::build(root, prerelease)?;
    for operation in result.operations() {
        println!("{operation}");
    }
    result.apply(root, dry_run)?;
    Ok(())
}

fn apply(root: &std::path::Path, channel: Option<&str>, dry_run: bool) -> Result<()> {
    let result = ApplyResult::build(root, channel)?;
    for operation in result.operations() {
        println!("{operation}");
    }
    result.apply(root, dry_run)?;
    Ok(())
}

fn plan(root: &std::path::Path, channel: Option<&str>) -> Result<()> {
    let plan = ReleasePlan::build(root, channel)?;
    println!("{}", plan.encode()?);
    Ok(())
}

fn init(root: &std::path::Path, args: InitArgs) -> Result<u8> {
    let result = initialize_with(
        root,
        InitOptions {
            take_over: args.take_over,
            bump_translation: args.bump_translation,
        },
    )?;
    if args.json {
        println!("{}", result.to_json()?);
    } else {
        let state = match result.state {
            InitState::NeedsInput => "needs-input",
            InitState::Ready | InitState::Success => "ready",
        };
        println!("initialization state: {state}");
        for operation in &result.operations {
            println!("{operation}");
        }
        let plan = result
            .plan
            .as_ref()
            .filter(|_| result.path == std::path::Path::new(intentional_core::INIT_PLAN_PATH))
            .filter(|_| !args.take_over);
        if let Some(plan) = plan {
            println!("plan: {}", result.path.display());
            if let Some(translation) = plan.bump_translation {
                println!("bump translation: {translation}");
                if plan.source_kind == "contract-1" && plan.parity.status == "blocked" {
                    println!(
                        "bump translation {translation} cannot keep every contract-1 version; see parity in the plan, then run intentional init --bump-translation significance or change the pending intents"
                    );
                } else if plan.source_kind == "contract-1" && result.state == InitState::Ready {
                    println!(
                        "review the bump translation and rewritten intents in the plan, then run intentional init again to upgrade"
                    );
                }
            }
        }
        for action in result.next_actions(root) {
            println!("next: {action}");
        }
    }
    result.apply(root, args.dry_run)?;
    Ok(if result.state == InitState::NeedsInput {
        2
    } else {
        0
    })
}

fn add(root: &std::path::Path, args: AddArgs) -> Result<()> {
    let config = Config::load(root)
        .with_context(|| format!("load {CONFIG_PATH} before adding an intent"))?;
    let release_unit_values = if args.release_units.is_empty() {
        let ids = config.release_units.keys().cloned().collect::<Vec<_>>();
        println!("Release units: {}", ids.join(", "));
        vec![prompt("Release unit (id): ")? + ":" + &prompt("Bump (major|minor|patch): ")?]
    } else {
        args.release_units
    };
    let mut release_units = BTreeMap::new();
    for value in release_unit_values {
        let (id, bump) = value
            .split_once(':')
            .with_context(|| format!("release-unit bump must be id:bump; got {value}"))?;
        let bump = bump.parse::<Bump>().map_err(anyhow::Error::msg)?;
        if release_units.insert(id.to_owned(), bump).is_some() {
            bail!("release unit {id} was specified more than once");
        }
    }
    let mut graduates = BTreeSet::new();
    for id in args.graduates {
        if !graduates.insert(id.clone()) {
            bail!("release unit {id} was given to --graduate more than once");
        }
    }
    let message = match args.message {
        Some(message) => message,
        None => prompt("Changelog message: ")?,
    };
    let write = IntentDraft {
        release_units,
        graduates,
        message,
    }
    .plan(root, &config)?;
    println!("write {}", write.path.display());
    write.apply(root, args.dry_run)?;
    Ok(())
}

fn status(root: &std::path::Path, json: bool) -> Result<()> {
    let status = WorkspaceStatus::load(root)?;
    if json {
        println!("{}", serde_json::to_string(&status)?);
        return Ok(());
    }
    if status.release_model_stale {
        println!("{}", intentional_core::release_model_stale_message());
    }
    if status.intents.is_empty() {
        println!("Pending intents: none");
    } else {
        println!("Pending intents: {}", status.intents.join(", "));
    }
    if !status.missing_baselines.is_empty() {
        println!(
            "[{MISSING_BASELINE_CODE}] Missing baseline tags: {}; run {MISSING_BASELINE_NEXT_ACTION}",
            status.missing_baselines.join(", "),
        );
    }
    for issue in &status.tag_record_issues {
        println!("Tag record: {issue}");
    }
    for release_unit in status.release_units {
        let graduation = if release_unit.graduates {
            ", graduates to 1.0.0"
        } else {
            ""
        };
        println!(
            "{}: {} -> {} ({}{graduation})",
            release_unit.id, release_unit.current, release_unit.next, release_unit.bump
        );
    }
    if status.drift.is_empty() {
        println!("Drift: none");
    } else {
        println!("Drift:");
        for drift in status.drift {
            println!(
                "  {} {}: manifest {} != tag {}",
                drift.release_unit,
                drift.file.display(),
                drift.actual,
                drift.expected
            );
        }
    }
    Ok(())
}

fn parse_phase(value: &str) -> Result<TagPhase> {
    match value {
        "before-publication" => Ok(TagPhase::BeforePublication),
        "after-publication" => Ok(TagPhase::AfterPublication),
        _ => bail!("phase must be before-publication or after-publication; got {value}"),
    }
}

fn prompt(label: &str) -> Result<String> {
    print!("{label}");
    io::stdout().flush()?;
    let mut value = String::new();
    io::stdin().read_line(&mut value)?;
    Ok(value.trim().to_owned())
}

fn model(root: &std::path::Path, args: ModelArgs) -> Result<()> {
    if args.stdout {
        print!("{}", intentional_core::ReleaseModel::build(root)?.encode()?);
        return Ok(());
    }
    let written = intentional_core::write_release_model(root, args.dry_run)?;
    let operation = if written { "written" } else { "unchanged" };
    if args.json {
        println!(
            "{}",
            format_args!(
                r#"{{"dry_run":{},"operation":"{}","path":"{}"}}"#,
                args.dry_run,
                operation,
                intentional_core::RELEASE_MODEL_PATH
            )
        );
    } else {
        println!(
            "{}{} {}",
            if args.dry_run { "dry-run: " } else { "" },
            operation,
            intentional_core::RELEASE_MODEL_PATH
        );
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::Cli;
    use clap::CommandFactory;
    use std::collections::BTreeSet;

    fn long_flags(command: &clap::Command) -> BTreeSet<String> {
        command
            .get_arguments()
            .filter(|argument| !argument.is_global_set())
            .filter(|argument| !matches!(argument.get_id().as_str(), "help" | "version"))
            .filter_map(|argument| argument.get_long())
            .map(|long| format!("--{long}"))
            .collect()
    }

    fn specified_flags(options: &serde_yaml::Value) -> BTreeSet<String> {
        options
            .as_sequence()
            .map(|options| {
                options
                    .iter()
                    .flat_map(|option| option["flags"].as_sequence().cloned().unwrap_or_default())
                    .filter_map(|flag| flag.as_str().map(str::to_owned))
                    .filter(|flag| flag.starts_with("--"))
                    .collect()
            })
            .unwrap_or_default()
    }

    #[test]
    fn commands_and_flags_match_the_cli_specification() {
        let specification: serde_yaml::Value = serde_yaml::from_str(include_str!(
            "../../../docs/specifications/command-line-interface.spec.yml"
        ))
        .expect("CLI specification parses");
        let cli = Cli::command();
        let shipped = cli
            .get_subcommands()
            .map(|command| command.get_name().to_owned())
            .collect::<BTreeSet<_>>();
        let specified = specification["commands"]
            .as_sequence()
            .expect("commands")
            .iter()
            .filter_map(|command| command["name"].as_str().map(str::to_owned))
            .collect::<BTreeSet<_>>();
        assert_eq!(shipped, specified);
        for command in specification["commands"].as_sequence().expect("commands") {
            let name = command["name"].as_str().expect("command name");
            let Some(subcommand) = cli.find_subcommand(name) else {
                continue;
            };
            assert_eq!(
                long_flags(subcommand),
                specified_flags(&command["options"]),
                "{name}"
            );
        }
        assert_eq!(
            specified_flags(&specification["global-options"]),
            BTreeSet::from(["--directory".to_owned()])
        );
    }
}