cdk-rsx-cli 0.1.1

Build and test Internet Computer canisters with CDK RSX
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
use crate::cargo::{self, Compiler};
use crate::project::{self, Agent};
use anyhow::{Context, Result, bail, ensure};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet};
use std::ffi::CString;
use std::fs::{self, File, OpenOptions};
use std::io::{self, ErrorKind};
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

const FACADE: &str = "cdk-rsx";
const MARKER: &str = ".cdk-rsx-skill.json";
const PROFILE: &str = "cdk-rsx-profile";
const CORE: &[&str] = &[
    "cdk-rsx-app-build",
    "cdk-rsx-app-create",
    "cdk-rsx-app-deploy",
    "cdk-rsx-app-evolution",
    "cdk-rsx-app-test",
];
const OPTIONAL: &[(&str, &str)] = &[
    ("cdk-rsx-ashroot", "cdk-rsx-ashroot-evolution"),
    ("cdk-rsx-rechain", "cdk-rsx-rechain-evolution"),
    ("cdk-rsx-takt", "cdk-rsx-takt-evolution"),
];

#[derive(Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct Installed {
    format: u8,
    package: String,
    version: String,
    sha256: String,
}

impl Installed {
    fn from_package(package: &Value, sha256: String) -> Result<Self> {
        Ok(Self {
            format: 1,
            package: package["name"]
                .as_str()
                .context("missing Cargo package name")?
                .into(),
            version: package["version"]
                .as_str()
                .context("missing Cargo package version")?
                .into(),
            sha256,
        })
    }
}

fn find_skill(package: &Value, name: &str) -> Result<Option<PathBuf>> {
    if let Some(registry) = package["source"].as_str() {
        ensure!(
            matches!(
                registry,
                "registry+https://github.com/rust-lang/crates.io-index"
                    | "sparse+https://index.crates.io/"
            ) && package["repository"] == "https://github.com/3V-Interactive/cdk-rsx",
            "{} is not an official crates.io CDK RSX skill source",
            package["name"]
        );
    }
    let root = project::package_directory(package)?;
    let path = root.join("skills").join(name);
    let source = match path.canonicalize() {
        Ok(source) => source,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(None),
        Err(error) => return Err(error).with_context(|| format!("open {}", path.display())),
    };
    ensure!(
        source == path && source.starts_with(&root),
        "skill path requires a directory inside the resolved package: {}",
        path.display()
    );
    ensure!(
        source
            .join("SKILL.md")
            .symlink_metadata()?
            .file_type()
            .is_file(),
        "skill {name} has no regular SKILL.md"
    );
    ensure!(
        source
            .join(MARKER)
            .symlink_metadata()
            .is_err_and(|error| error.kind() == ErrorKind::NotFound),
        "package skill {name} contains a reserved receipt path"
    );
    Ok(Some(source))
}

fn tree_hash(root: &Path) -> Result<String> {
    ensure!(
        root.symlink_metadata()?.file_type().is_dir(),
        "{} must be a regular directory",
        root.display()
    );
    let mut hash = Sha256::new();
    for entry in WalkDir::new(root).min_depth(1).sort_by_file_name() {
        let entry = entry?;
        let relative = entry.path().strip_prefix(root)?;
        if relative == Path::new(MARKER) {
            ensure!(entry.file_type().is_file(), "invalid skill receipt entry");
            continue;
        }
        ensure!(
            entry.file_type().is_file() || entry.file_type().is_dir(),
            "skill entry must be a regular file or directory: {}",
            entry.path().display()
        );
        let name = relative.as_os_str().as_encoded_bytes();
        hash.update((name.len() as u64).to_le_bytes());
        hash.update(name);
        hash.update([u8::from(entry.file_type().is_file())]);
        if entry.file_type().is_file() {
            let permissions = entry.metadata()?.permissions().mode() & 0o777;
            hash.update(permissions.to_le_bytes());
            let contents = fs::read(entry.path())?;
            hash.update((contents.len() as u64).to_le_bytes());
            hash.update(contents);
        }
    }
    Ok(format!("{:x}", hash.finalize()))
}

fn write_skill(source: &Path, destination: &Path, stamp: &Installed) -> Result<()> {
    for entry in WalkDir::new(source).min_depth(1) {
        let entry = entry?;
        let relative = entry.path().strip_prefix(source)?;
        ensure!(
            relative != Path::new(MARKER),
            "package skill contains a reserved receipt path"
        );
        let target = destination.join(relative);
        if entry.file_type().is_dir() {
            fs::create_dir(&target)?;
        } else if entry.file_type().is_file() {
            fs::copy(entry.path(), &target)?;
        } else {
            bail!(
                "skill entry must be a regular file or directory: {}",
                entry.path().display()
            );
        }
    }
    ensure!(
        tree_hash(destination)? == stamp.sha256,
        "package skill changed while copying"
    );
    let mut json = serde_json::to_string_pretty(stamp)?;
    json.push('\n');
    fs::write(destination.join(MARKER), json)?;
    Ok(())
}

fn project_directory(parent: &Path, name: &str) -> Result<PathBuf> {
    let directory = parent.join(name);
    match fs::create_dir(&directory) {
        Ok(()) => {}
        Err(error) if error.kind() == ErrorKind::AlreadyExists => ensure!(
            directory.symlink_metadata()?.file_type().is_dir(),
            "{} must be a project-owned directory",
            directory.display()
        ),
        Err(error) => return Err(error).with_context(|| format!("create {}", directory.display())),
    }
    Ok(directory)
}

fn skill_directory(app: &Path, agent: Agent) -> Result<(PathBuf, File)> {
    let app = app.canonicalize()?;
    let agent = project_directory(&app, agent.project_directory())?;
    let skills = project_directory(&agent, "skills")?;
    let lock = OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .custom_flags(libc::O_NOFOLLOW)
        .open(agent.join(".cdk-rsx-skills.lock"))?;
    lock.lock()?;
    Ok((skills, lock))
}

pub(crate) fn install_skill(
    metadata: &Value,
    app: &Path,
    name: &str,
    agent: Agent,
) -> Result<PathBuf> {
    ensure!(
        !name.is_empty()
            && name
                .bytes()
                .all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == b'-'),
        "skill name must use lowercase letters, digits, and hyphens"
    );
    let owner = OPTIONAL
        .iter()
        .find_map(|(crate_name, skill)| (*skill == name).then_some(*crate_name))
        .unwrap_or(FACADE);
    let package = project::resolved_package(metadata, owner)?;
    let (source, package) = if let Some(source) = find_skill(package, name)? {
        (source, package)
    } else {
        // The first published SDK shipped these specialized skills in its facade.
        let version = package["version"]
            .as_str()
            .context("missing Cargo package version")?;
        let facade = project::resolved_package(metadata, &format!("{FACADE}@{version}"))?;
        (
            find_skill(facade, name)?
                .with_context(|| format!("{owner} {version} does not ship skill {name}"))?,
            facade,
        )
    };
    let stamp = Installed::from_package(package, tree_hash(&source)?)?;
    let (skills, _lock) = skill_directory(app, agent)?;
    let destination = skills.join(name);
    project::populate_directory(&destination, |staging| {
        write_skill(&source, staging, &stamp)
    })
    .with_context(|| format!("install CDK RSX skill {name}"))?;
    Ok(destination)
}

pub(crate) fn sync(
    manifest: &Path,
    package: Option<&str>,
    features: &[String],
    target: &str,
    agent: Agent,
) -> Result<()> {
    let manifest = manifest
        .canonicalize()
        .with_context(|| format!("open {}", manifest.display()))?;
    let compiler = Compiler::select(false)?;
    compiler.prepare_lock(&manifest, false, false)?;
    let workspace = compiler.workspace_metadata(&manifest)?;
    let (app, _) = cargo::app_library(&workspace, &manifest, package)?;
    let manifest = Path::new(
        app["manifest_path"]
            .as_str()
            .context("missing app Cargo.toml path")?,
    );
    let name = app["name"].as_str().context("missing app package name")?;
    let metadata = compiler.metadata(manifest, features, None, false)?;
    let graph: Value = serde_json::from_slice(
        &cargo::checked(
            compiler
                .for_manifest(manifest, "build")
                .args([
                    "--package",
                    name,
                    "--lib",
                    "--target",
                    target,
                    "--locked",
                    "--offline",
                    "-Z",
                    "unstable-options",
                    "--unit-graph",
                ])
                .args(features),
            &[],
        )
        .context("resolve the canister's active build graph")?,
    )?;
    let active = graph["units"]
        .as_array()
        .context("Cargo did not return build units")?
        .iter()
        .filter_map(|unit| unit["pkg_id"].as_str())
        .collect();
    let app = manifest
        .parent()
        .context("app manifest has no parent directory")?;
    sync_active(&metadata, &active, app, agent)
}

fn sync_active(metadata: &Value, active: &BTreeSet<&str>, app: &Path, agent: Agent) -> Result<()> {
    let mut packages = BTreeMap::new();
    for package in metadata["packages"]
        .as_array()
        .context("missing Cargo packages")?
    {
        let Some(name) = package["name"].as_str() else {
            continue;
        };
        if (name == FACADE || OPTIONAL.iter().any(|(owner, _)| *owner == name))
            && package["id"].as_str().is_some_and(|id| active.contains(id))
        {
            ensure!(
                packages.insert(name, package).is_none(),
                "the selected canister uses multiple versions of {name}; select its skill explicitly"
            );
        }
    }
    let facade = *packages
        .get(FACADE)
        .context("the selected canister does not use cdk-rsx")?;
    let (destination, _lock) = skill_directory(app, agent)?;
    let skills = CORE
        .iter()
        .map(|name| (FACADE, *name))
        .chain(OPTIONAL.iter().copied())
        .chain(
            read_stamp(&destination.join(PROFILE))
                .is_ok()
                .then_some((FACADE, PROFILE)),
        );
    for (owner, name) in skills {
        let path = destination.join(name);
        let Some(&package) = packages.get(owner) else {
            if path.join(MARKER).is_file() {
                println!(
                    "kept {} ({owner} is outside the selected canister's build)",
                    path.display()
                );
            }
            continue;
        };
        let source = find_skill(package, name)?;
        let found = match source {
            Some(path) => Some((path, package)),
            None if owner != FACADE && package["version"] == facade["version"] => {
                find_skill(facade, name)?.map(|path| (path, facade))
            }
            None => None,
        };
        if let Some((source, package)) = found {
            let stamp = Installed::from_package(package, tree_hash(&source)?)?;
            let action = sync_skill(&source, &path, &stamp)?;
            println!(
                "{action} {} ({} {})",
                path.display(),
                stamp.package,
                stamp.version
            );
        } else {
            println!(
                "skipped {name} ({owner} {} does not ship it)",
                package["version"]
            );
        }
    }
    Ok(())
}

fn read_stamp(path: &Path) -> Result<Installed> {
    ensure!(
        path.symlink_metadata()?.file_type().is_dir(),
        "not a managed skill directory"
    );
    let stamp = path.join(MARKER);
    ensure!(
        stamp.symlink_metadata()?.file_type().is_file(),
        "not a regular skill receipt"
    );
    let installed: Installed = serde_json::from_slice(&fs::read(&stamp)?)?;
    ensure!(installed.format == 1, "unknown skill receipt format");
    Ok(installed)
}

fn sync_skill(source: &Path, path: &Path, desired: &Installed) -> Result<&'static str> {
    match path.symlink_metadata() {
        Err(error) if error.kind() == ErrorKind::NotFound => {
            project::populate_directory(path, |stage| write_skill(source, stage, desired))?;
            return Ok("installed");
        }
        Err(error) => return Err(error.into()),
        Ok(_) => {}
    }
    let Ok(installed) = read_stamp(path) else {
        return Ok("kept unmanaged");
    };
    if !tree_hash(path).is_ok_and(|hash| hash == installed.sha256) {
        return Ok("kept edited");
    }
    if installed == *desired {
        return Ok("up to date");
    }
    let parent = path
        .parent()
        .context("skill has no destination directory")?;
    let stage = tempfile::Builder::new()
        .prefix(".cdk-rsx-skill-")
        .tempdir_in(parent)?;
    write_skill(source, stage.path(), desired)?;
    if !read_stamp(path).is_ok_and(|now| now == installed)
        || !tree_hash(path).is_ok_and(|hash| hash == installed.sha256)
    {
        return Ok("kept edited");
    }
    exchange(stage.path(), path)
        .with_context(|| format!("replace {} atomically", path.display()))?;
    Ok("updated")
}

fn exchange(from: &Path, to: &Path) -> io::Result<()> {
    let from = CString::new(from.as_os_str().as_encoded_bytes())?;
    let to = CString::new(to.as_os_str().as_encoded_bytes())?;
    // Both paths are existing directories on the same filesystem. The exchange
    // publishes the complete skill and receipt in one operation.
    #[cfg(target_os = "linux")]
    let result = unsafe {
        libc::renameat2(
            libc::AT_FDCWD,
            from.as_ptr(),
            libc::AT_FDCWD,
            to.as_ptr(),
            libc::RENAME_EXCHANGE,
        )
    };
    #[cfg(target_os = "macos")]
    let result = unsafe { libc::renamex_np(from.as_ptr(), to.as_ptr(), libc::RENAME_SWAP) };
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    let result = {
        let _ = (from, to);
        return Err(io::Error::new(
            ErrorKind::Unsupported,
            "atomic skill replacement requires Linux or macOS",
        ));
    };
    if result == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn sync_uses_active_packages_and_updates_only_unedited_managed_skills() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let app = dir.path().join("app");
        fs::create_dir(&app)?;
        let create_package = |id: &str,
                              crate_name: &str,
                              version: &str,
                              names: &[&str]|
         -> Result<Value> {
            let root = dir.path().join(id);
            for name in names {
                let skill = root.join("skills").join(name);
                fs::create_dir_all(&skill)?;
                fs::write(skill.join("SKILL.md"), format!("{name} version {version}"))?;
            }
            Ok(
                json!({"id": id, "name": crate_name, "version": version, "manifest_path": root.join("Cargo.toml")}),
            )
        };
        let old = create_package("sdk1", FACADE, "0.1.0", CORE)?;
        let new = create_package("sdk2", FACADE, "0.2.0", CORE)?;
        let ashroot = create_package(
            "ashroot",
            "cdk-rsx-ashroot",
            "0.2.0",
            &["cdk-rsx-ashroot-evolution"],
        )?;
        let unused = create_package(
            "rechain",
            "cdk-rsx-rechain",
            "0.2.0",
            &["cdk-rsx-rechain-evolution"],
        )?;
        let metadata = json!({"packages": [old, new, ashroot, unused]});
        sync_active(
            &metadata,
            &BTreeSet::from(["sdk1", "ashroot"]),
            &app,
            Agent::Codex,
        )?;
        let skills = app.join(".agents/skills");
        assert!(skills.join("cdk-rsx-ashroot-evolution/SKILL.md").is_file());
        assert!(!skills.join("cdk-rsx-rechain-evolution").exists());
        let build = skills.join("cdk-rsx-app-build/SKILL.md");
        let create = skills.join("cdk-rsx-app-create/SKILL.md");
        fs::write(&create, "my changes")?;
        let deploy = skills.join("cdk-rsx-app-deploy");
        fs::remove_file(deploy.join(MARKER))?;
        fs::write(deploy.join("SKILL.md"), "an unmanaged copy")?;
        sync_active(&metadata, &BTreeSet::from(["sdk2"]), &app, Agent::Codex)?;
        assert_eq!(
            fs::read_to_string(build)?,
            "cdk-rsx-app-build version 0.2.0"
        );
        assert_eq!(fs::read_to_string(create)?, "my changes");
        assert_eq!(
            fs::read_to_string(deploy.join("SKILL.md"))?,
            "an unmanaged copy"
        );
        assert!(skills.join("cdk-rsx-ashroot-evolution/SKILL.md").is_file());
        Ok(())
    }
}