harn-cli 0.10.22

CLI for the Harn programming language — run, test, REPL, format, and lint
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
use std::fs;
use std::path::{Path, PathBuf};

use include_dir::{include_dir, Dir};

use crate::cli::{PersonaNewArgs, PersonaTemplateKind};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PersonaScaffoldResult {
    pub root: PathBuf,
    pub files: Vec<PathBuf>,
}

static PERSONA_TEMPLATE_ASSETS: Dir<'_> =
    include_dir!("$CARGO_MANIFEST_DIR/assets/persona-templates");

async fn scaffold_persona(args: &PersonaNewArgs) -> Result<PersonaScaffoldResult, String> {
    let name = normalize_name(&args.name)?;
    let target_root = args.output_root.join(&name);
    if target_root.exists() && !args.force {
        return Err(format!(
            "{} already exists; pass --force to replace it after validation",
            target_root.display()
        ));
    }

    let prepared = prepare_persona_package(&args.output_root, &name, args.template)?;
    validate_prepared_persona(&prepared, &name).await?;
    publish_prepared_persona(prepared, target_root, args.force)
}

pub async fn scaffold_persona_package(
    name: &str,
    template: &str,
    output_root: &Path,
    force: bool,
) -> Result<PersonaScaffoldResult, String> {
    let args = PersonaNewArgs {
        name: name.to_string(),
        template: parse_template_kind(template)?,
        output_root: output_root.to_path_buf(),
        force,
    };
    scaffold_persona(&args).await
}

pub(crate) async fn run_new(args: &PersonaNewArgs) -> Result<(), String> {
    let result = scaffold_persona(args).await?;
    println!("created persona package {}", result.root.display());
    for file in &result.files {
        println!("  create {}", file.display());
    }
    println!();
    println!("  harn persona doctor {}", normalize_name(&args.name)?);
    Ok(())
}

fn normalize_name(raw: &str) -> Result<String, String> {
    let name = raw.trim().replace('-', "_");
    if !valid_identifier(&name) {
        return Err(format!(
            "persona name must be an identifier-like token, got {raw:?}"
        ));
    }
    Ok(name)
}

fn valid_identifier(value: &str) -> bool {
    let mut chars = value.chars();
    match chars.next() {
        Some(ch) if ch == '_' || ch.is_ascii_alphabetic() => {}
        _ => return false,
    }
    chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric())
}

fn parse_template_kind(value: &str) -> Result<PersonaTemplateKind, String> {
    match value {
        "deterministic-sweeper" => Ok(PersonaTemplateKind::DeterministicSweeper),
        "hybrid-classify-then-act" => Ok(PersonaTemplateKind::HybridClassifyThenAct),
        "frontier-judgment-loop" => Ok(PersonaTemplateKind::FrontierJudgmentLoop),
        _ => Err(format!("unknown persona template {value:?}")),
    }
}

fn to_title(name: &str) -> String {
    name.split('_')
        .filter(|part| !part.is_empty())
        .map(|part| {
            let mut chars = part.chars();
            match chars.next() {
                Some(first) => format!("{}{}", first.to_ascii_uppercase(), chars.as_str()),
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

fn to_package_slug(name: &str) -> String {
    name.replace('_', "-")
}

struct TemplateIdentity {
    persona_name: String,
    persona_title: String,
    package_slug: String,
    template_kind: &'static str,
}

struct PreparedPersonaPackage {
    staging: tempfile::TempDir,
    relative_files: Vec<PathBuf>,
}

impl TemplateIdentity {
    fn new(name: &str, kind: PersonaTemplateKind) -> Self {
        Self {
            persona_name: name.to_string(),
            persona_title: to_title(name),
            package_slug: to_package_slug(name),
            template_kind: kind.as_str(),
        }
    }
}

fn prepare_persona_package(
    output_root: &Path,
    name: &str,
    kind: PersonaTemplateKind,
) -> Result<PreparedPersonaPackage, String> {
    fs::create_dir_all(output_root)
        .map_err(|error| format!("failed to create {}: {error}", output_root.display()))?;
    let staging = tempfile::Builder::new()
        .prefix(".harn-persona-stage-")
        .tempdir_in(output_root)
        .map_err(|error| {
            format!(
                "failed to create persona staging directory in {}: {error}",
                output_root.display()
            )
        })?;
    let identity = TemplateIdentity::new(name, kind);
    let template_dir = PERSONA_TEMPLATE_ASSETS
        .get_dir(kind.as_str())
        .ok_or_else(|| format!("canonical persona template {} is missing", kind.as_str()))?;
    let mut relative_files = Vec::new();

    write_embedded_template_dir(
        template_dir,
        Path::new(""),
        staging.path(),
        &identity,
        &mut relative_files,
    )?;
    let readme = PERSONA_TEMPLATE_ASSETS
        .get_file("package-README.md")
        .ok_or_else(|| "canonical persona package README is missing".to_string())?;
    write_embedded_template_file(
        Path::new("README.md"),
        readme
            .contents_utf8()
            .ok_or_else(|| "canonical persona package README is not UTF-8".to_string())?,
        staging.path(),
        &identity,
        &mut relative_files,
    )?;
    relative_files.sort();

    Ok(PreparedPersonaPackage {
        staging,
        relative_files,
    })
}

async fn validate_prepared_persona(
    prepared: &PreparedPersonaPackage,
    name: &str,
) -> Result<(), String> {
    let manifest = prepared.staging.path().join("harn.toml");
    let report = match crate::commands::persona_doctor::doctor_report_for_persona(
        Some(&manifest),
        name,
        10_000,
    )
    .await
    {
        Ok(report) | Err(report) => report,
    };
    let failures = report
        .checks
        .iter()
        .filter(|check| check.status != crate::commands::persona_doctor::DoctorStatus::Green)
        .map(|check| format!("{}: {}", check.name, check.message))
        .collect::<Vec<_>>();
    if !failures.is_empty() {
        return Err(format!(
            "generated persona failed strict validation: {}",
            failures.join("; ")
        ));
    }
    remove_validation_artifacts(prepared.staging.path())?;
    Ok(())
}

fn remove_validation_artifacts(root: &Path) -> Result<(), String> {
    for name in [".harn", ".harn-runs"] {
        let path = root.join(name);
        if !path.exists() {
            continue;
        }
        fs::remove_dir_all(&path).map_err(|error| {
            format!(
                "failed to remove validation artifact {}: {error}",
                path.display()
            )
        })?;
    }
    Ok(())
}

fn publish_prepared_persona(
    prepared: PreparedPersonaPackage,
    target_root: PathBuf,
    force: bool,
) -> Result<PersonaScaffoldResult, String> {
    let PreparedPersonaPackage {
        staging,
        relative_files,
    } = prepared;
    let staged_root = staging.keep();
    if let Err(error) = publish_staged_persona(&staged_root, &target_root, force) {
        let _ = fs::remove_dir_all(&staged_root);
        return Err(error);
    }
    let files = relative_files
        .into_iter()
        .map(|relative| target_root.join(relative))
        .collect();
    Ok(PersonaScaffoldResult {
        root: target_root,
        files,
    })
}

fn publish_staged_persona(staged: &Path, target: &Path, force: bool) -> Result<(), String> {
    publish_staged_persona_with(staged, target, force, |from, to| fs::rename(from, to))
}

fn publish_staged_persona_with(
    staged: &Path,
    target: &Path,
    force: bool,
    mut rename: impl FnMut(&Path, &Path) -> std::io::Result<()>,
) -> Result<(), String> {
    if !target.exists() {
        return rename(staged, target).map_err(|error| {
            format!(
                "failed to publish persona package {}: {error}",
                target.display()
            )
        });
    }
    if !force {
        return Err(format!(
            "{} already exists; pass --force to replace it after validation",
            target.display()
        ));
    }

    let backup = unique_backup_path(target)?;
    rename(target, &backup).map_err(|error| {
        format!(
            "failed to stage existing persona package {} for replacement: {error}",
            target.display()
        )
    })?;
    if let Err(publish_error) = rename(staged, target) {
        return match rename(&backup, target) {
            Ok(()) => Err(format!(
                "failed to publish persona package {}; restored the previous package: {publish_error}",
                target.display()
            )),
            Err(restore_error) => Err(format!(
                "failed to publish persona package {} ({publish_error}) and failed to restore its backup {} ({restore_error})",
                target.display(),
                backup.display()
            )),
        };
    }

    remove_path(&backup).map_err(|error| {
        format!(
            "published persona package {}, but failed to remove backup {}: {error}",
            target.display(),
            backup.display()
        )
    })
}

fn unique_backup_path(target: &Path) -> Result<PathBuf, String> {
    let parent = target
        .parent()
        .ok_or_else(|| format!("{} has no parent directory", target.display()))?;
    let name = target
        .file_name()
        .and_then(|name| name.to_str())
        .ok_or_else(|| format!("{} has no UTF-8 file name", target.display()))?;
    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    loop {
        let counter = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let candidate = parent.join(format!(
            ".{name}.harn-persona-backup-{}-{counter}",
            std::process::id()
        ));
        if !candidate.exists() {
            return Ok(candidate);
        }
    }
}

fn remove_path(path: &Path) -> std::io::Result<()> {
    if path.is_dir() {
        fs::remove_dir_all(path)
    } else {
        fs::remove_file(path)
    }
}

fn render_template_path(template: &Path, identity: &TemplateIdentity) -> Result<PathBuf, String> {
    let template = template.to_str().ok_or_else(|| {
        format!(
            "canonical persona template path is not UTF-8: {}",
            template.display()
        )
    })?;
    Ok(PathBuf::from(
        template.replace("template_persona", &identity.persona_name),
    ))
}

fn write_embedded_template_dir(
    template_dir: &Dir<'_>,
    relative_root: &Path,
    staging_root: &Path,
    identity: &TemplateIdentity,
    relative_files: &mut Vec<PathBuf>,
) -> Result<(), String> {
    for file in template_dir.files() {
        let name = file.path().file_name().ok_or_else(|| {
            format!(
                "canonical persona template file has no name: {}",
                file.path().display()
            )
        })?;
        let relative = relative_root.join(name);
        let content = file.contents_utf8().ok_or_else(|| {
            format!(
                "canonical persona template file is not UTF-8: {}",
                file.path().display()
            )
        })?;
        write_embedded_template_file(&relative, content, staging_root, identity, relative_files)?;
    }
    for directory in template_dir.dirs() {
        let name = directory.path().file_name().ok_or_else(|| {
            format!(
                "canonical persona template directory has no name: {}",
                directory.path().display()
            )
        })?;
        write_embedded_template_dir(
            directory,
            &relative_root.join(name),
            staging_root,
            identity,
            relative_files,
        )?;
    }
    Ok(())
}

fn write_embedded_template_file(
    template_path: &Path,
    template_content: &str,
    staging_root: &Path,
    identity: &TemplateIdentity,
    relative_files: &mut Vec<PathBuf>,
) -> Result<(), String> {
    let relative = render_template_path(template_path, identity)?;
    let path = staging_root.join(&relative);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .map_err(|error| format!("failed to create {}: {error}", parent.display()))?;
    }
    let content = render_template_file(template_path, template_content, identity)?;
    fs::write(&path, content)
        .map_err(|error| format!("failed to write {}: {error}", path.display()))?;
    relative_files.push(relative);
    Ok(())
}

fn render_template_file(
    template_path: &Path,
    template_content: &str,
    identity: &TemplateIdentity,
) -> Result<String, String> {
    if template_path == Path::new("harn.toml") {
        return render_manifest(template_content, identity);
    }
    let mut rendered = template_content
        .replace("template_persona", &identity.persona_name)
        .replace("template-persona", &identity.package_slug);
    if template_path == Path::new("README.md") {
        rendered = rendered
            .replace("{{persona_name}}", &identity.persona_name)
            .replace("{{persona_title}}", &identity.persona_title)
            .replace("{{template_kind}}", identity.template_kind);
    }
    Ok(rendered)
}

fn render_manifest(template: &str, identity: &TemplateIdentity) -> Result<String, String> {
    let mut manifest = toml::from_str::<toml::Value>(template)
        .map_err(|error| format!("canonical persona template manifest is invalid: {error}"))?;
    {
        let package = manifest
            .get_mut("package")
            .and_then(toml::Value::as_table_mut)
            .ok_or_else(|| "canonical persona template is missing [package]".to_string())?;
        package.insert(
            "name".to_string(),
            toml::Value::String(format!("harn-{}-persona", identity.package_slug)),
        );
        package.insert(
            "description".to_string(),
            toml::Value::String(format!(
                "{} persona package generated from the {} template.",
                identity.persona_title, identity.template_kind
            )),
        );
    }
    {
        let persona = manifest
            .get_mut("personas")
            .and_then(toml::Value::as_array_mut)
            .and_then(|personas| personas.first_mut())
            .and_then(toml::Value::as_table_mut)
            .ok_or_else(|| "canonical persona template is missing [[personas]]".to_string())?;
        persona.insert(
            "name".to_string(),
            toml::Value::String(identity.persona_name.clone()),
        );
        persona.insert(
            "description".to_string(),
            toml::Value::String(format!(
                "{} persona generated from the {} template.",
                identity.persona_title, identity.template_kind
            )),
        );
        persona.insert(
            "entry_workflow".to_string(),
            toml::Value::String(format!("src/{}.harn#run", identity.persona_name)),
        );
    }
    toml::to_string_pretty(&manifest)
        .map_err(|error| format!("failed to render persona manifest: {error}"))
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;

    use super::*;

    #[tokio::test(flavor = "current_thread")]
    async fn strict_validation_rejects_a_missing_entry_symbol_before_publish() {
        let temp = tempfile::tempdir().unwrap();
        let output_root = temp.path().join("personas");
        let prepared = prepare_persona_package(
            &output_root,
            "reviewer",
            PersonaTemplateKind::DeterministicSweeper,
        )
        .unwrap();
        let source_path = prepared.staging.path().join("src").join("reviewer.harn");
        let source = fs::read_to_string(&source_path).unwrap();
        fs::write(
            &source_path,
            source.replace("pipeline run(", "pipeline renamed_run("),
        )
        .unwrap();

        let error = validate_prepared_persona(&prepared, "reviewer")
            .await
            .unwrap_err();

        assert!(error.contains("entry-symbol"), "{error}");
        assert!(!output_root.join("reviewer").exists());
    }

    #[test]
    fn failed_forced_publish_restores_the_previous_package() {
        let temp = tempfile::tempdir().unwrap();
        let target = temp.path().join("reviewer");
        let staged = temp.path().join(".staged-reviewer");
        fs::create_dir_all(&target).unwrap();
        fs::create_dir_all(&staged).unwrap();
        fs::write(target.join("user-owned.txt"), "keep me").unwrap();
        fs::write(staged.join("generated.txt"), "new package").unwrap();
        let calls = Cell::new(0);

        let error = publish_staged_persona_with(&staged, &target, true, |from, to| {
            let call = calls.get() + 1;
            calls.set(call);
            if call == 2 {
                Err(std::io::Error::other("injected publish failure"))
            } else {
                fs::rename(from, to)
            }
        })
        .unwrap_err();

        assert!(error.contains("restored the previous package"), "{error}");
        assert_eq!(
            fs::read_to_string(target.join("user-owned.txt")).unwrap(),
            "keep me"
        );
        assert!(staged.join("generated.txt").exists());
        assert!(fs::read_dir(temp.path()).unwrap().all(|entry| {
            !entry
                .unwrap()
                .file_name()
                .to_string_lossy()
                .contains("harn-persona-backup")
        }));
    }
}