Skip to main content

harn_cli/package/
package_ops.rs

1use super::errors::PackageError;
2use super::*;
3use base64::Engine as _;
4
5#[derive(Debug, Clone, Serialize)]
6pub struct PackageCheckReport {
7    pub package_dir: String,
8    pub manifest_path: String,
9    pub name: Option<String>,
10    pub version: Option<String>,
11    pub errors: Vec<PackageCheckDiagnostic>,
12    pub warnings: Vec<PackageCheckDiagnostic>,
13    pub exports: Vec<PackageExportReport>,
14    pub tools: Vec<PackageToolExportReport>,
15    pub skills: Vec<PackageSkillExportReport>,
16}
17
18#[derive(Debug, Clone, Serialize)]
19pub struct PackageCheckDiagnostic {
20    pub field: String,
21    pub message: String,
22}
23
24#[derive(Debug, Clone, Serialize)]
25pub struct PackageExportReport {
26    pub name: String,
27    pub path: String,
28    pub symbols: Vec<PackageApiSymbol>,
29}
30
31#[derive(Debug, Clone, Serialize)]
32pub struct PackageToolExportReport {
33    pub name: String,
34    pub module: String,
35    pub symbol: String,
36    pub permissions: Vec<String>,
37    pub host_requirements: Vec<String>,
38}
39
40#[derive(Debug, Clone, Serialize)]
41pub struct PackageSkillExportReport {
42    pub name: String,
43    pub path: String,
44    pub permissions: Vec<String>,
45    pub host_requirements: Vec<String>,
46}
47
48#[derive(Debug, Clone, Serialize)]
49pub struct PackageApiSymbol {
50    pub kind: String,
51    pub name: String,
52    pub signature: String,
53    pub docs: Option<String>,
54}
55
56#[derive(Debug, Clone, Serialize)]
57pub struct PackagePackReport {
58    pub package_dir: String,
59    pub artifact_dir: String,
60    pub dry_run: bool,
61    pub files: Vec<String>,
62    pub check: PackageCheckReport,
63}
64
65#[derive(Debug, Clone, Serialize)]
66pub struct PackagePublishReport {
67    pub dry_run: bool,
68    pub registry: String,
69    pub artifact_dir: String,
70    pub files: Vec<String>,
71    pub tag: String,
72    pub sha: String,
73    pub remote: String,
74    pub index_repo: String,
75    pub index_path: String,
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub index_pr_url: Option<String>,
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub tag_command: Option<String>,
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub index_diff: Option<String>,
82    pub check: PackageCheckReport,
83}
84
85#[derive(Debug, Clone)]
86pub(crate) struct PackagePublishOptions<'a> {
87    pub(crate) dry_run: bool,
88    pub(crate) remote: &'a str,
89    pub(crate) index_repo: &'a str,
90    pub(crate) index_path: &'a Path,
91    pub(crate) registry_name: Option<&'a str>,
92    pub(crate) skip_index_pr: bool,
93    pub(crate) registry: Option<&'a str>,
94}
95
96#[derive(Debug, Clone)]
97struct PackagePublishPlan {
98    repo_root: PathBuf,
99    package_name: String,
100    registry_name: String,
101    version: String,
102    tag: String,
103    sha: String,
104    git: String,
105    remote: String,
106    index_repo: String,
107    index_path: PathBuf,
108    updated_index_content: String,
109    index_diff: String,
110    tag_command: String,
111    pack: PackagePackReport,
112}
113
114#[derive(Debug, Clone, Serialize)]
115pub struct PackageListReport {
116    pub manifest_path: String,
117    pub lock_path: String,
118    pub lock_present: bool,
119    pub dependency_count: usize,
120    pub packages: Vec<PackageListEntry>,
121}
122
123#[derive(Debug, Clone, Serialize)]
124pub struct PackageListEntry {
125    pub name: String,
126    pub source: String,
127    pub package_version: Option<String>,
128    pub harn_compat: Option<String>,
129    pub provenance: Option<String>,
130    pub materialized: bool,
131    pub integrity: String,
132    pub exports: PackageLockExports,
133    pub permissions: Vec<String>,
134    pub host_requirements: Vec<String>,
135}
136
137#[derive(Debug, Clone, Serialize)]
138pub struct PackageDoctorReport {
139    pub ok: bool,
140    pub manifest_path: String,
141    pub lock_path: String,
142    pub diagnostics: Vec<PackageDoctorDiagnostic>,
143    pub packages: Vec<PackageListEntry>,
144}
145
146#[derive(Debug, Clone, Serialize)]
147pub struct PackageDoctorDiagnostic {
148    pub severity: String,
149    pub code: String,
150    pub message: String,
151    #[serde(skip_serializing_if = "Option::is_none")]
152    pub help: Option<String>,
153}
154
155pub fn check_package(anchor: Option<&Path>, json: bool) {
156    match check_package_impl(anchor) {
157        Ok(report) => {
158            if json {
159                println!(
160                    "{}",
161                    serde_json::to_string_pretty(&report)
162                        .unwrap_or_else(|error| format!(r#"{{"error":"{error}"}}"#))
163                );
164            } else {
165                print_package_check_report(&report);
166            }
167            if !report.errors.is_empty() {
168                process::exit(1);
169            }
170        }
171        Err(error) => {
172            eprintln!("error: {error}");
173            process::exit(1);
174        }
175    }
176}
177
178pub fn pack_package(anchor: Option<&Path>, output: Option<&Path>, dry_run: bool, json: bool) {
179    match pack_package_impl(anchor, output, dry_run) {
180        Ok(report) => {
181            if json {
182                println!(
183                    "{}",
184                    serde_json::to_string_pretty(&report)
185                        .unwrap_or_else(|error| format!(r#"{{"error":"{error}"}}"#))
186                );
187            } else {
188                print_package_pack_report(&report);
189            }
190        }
191        Err(error) => {
192            eprintln!("error: {error}");
193            process::exit(1);
194        }
195    }
196}
197
198pub fn generate_package_docs(anchor: Option<&Path>, output: Option<&Path>, check: bool) {
199    match generate_package_docs_impl(anchor, output, check) {
200        Ok(path) if check => println!("{} is up to date.", path.display()),
201        Ok(path) => println!("Wrote {}.", path.display()),
202        Err(error) => {
203            eprintln!("error: {error}");
204            process::exit(1);
205        }
206    }
207}
208
209#[allow(clippy::too_many_arguments)]
210pub fn publish_package(
211    anchor: Option<&Path>,
212    dry_run: bool,
213    remote: &str,
214    index_repo: &str,
215    index_path: &Path,
216    registry_name: Option<&str>,
217    skip_index_pr: bool,
218    registry: Option<&str>,
219    json: bool,
220) {
221    let options = PackagePublishOptions {
222        dry_run,
223        remote,
224        index_repo,
225        index_path,
226        registry_name,
227        skip_index_pr,
228        registry,
229    };
230
231    match publish_package_impl(anchor, &options) {
232        Ok(report) => {
233            if json {
234                println!(
235                    "{}",
236                    serde_json::to_string_pretty(&report)
237                        .unwrap_or_else(|error| format!(r#"{{"error":"{error}"}}"#))
238                );
239            } else {
240                if report.dry_run {
241                    println!("Publish dry run to {} succeeded.", report.registry);
242                } else {
243                    println!("Published {}.", report.tag);
244                }
245                println!("tag: {}", report.tag);
246                println!("sha: {}", report.sha);
247                if let Some(command) = report.tag_command.as_deref() {
248                    println!("tag command: {command}");
249                }
250                if let Some(diff) = report.index_diff.as_deref() {
251                    println!("\nindex diff:\n{diff}");
252                }
253                if let Some(url) = report.index_pr_url.as_deref() {
254                    println!("index PR: {url}");
255                }
256                println!("artifact: {}", report.artifact_dir);
257                println!("files: {}", report.files.len());
258            }
259        }
260        Err(error) => {
261            eprintln!("error: {error}");
262            process::exit(1);
263        }
264    }
265}
266
267pub fn list_packages(json: bool) {
268    match list_packages_impl() {
269        Ok(report) if json => {
270            println!(
271                "{}",
272                serde_json::to_string_pretty(&report)
273                    .unwrap_or_else(|error| format!(r#"{{"error":"{error}"}}"#))
274            );
275        }
276        Ok(report) => print_package_list_report(&report),
277        Err(error) => {
278            eprintln!("error: {error}");
279            process::exit(1);
280        }
281    }
282}
283
284pub fn doctor_packages(json: bool) {
285    match doctor_packages_impl() {
286        Ok(report) if json => {
287            println!(
288                "{}",
289                serde_json::to_string_pretty(&report)
290                    .unwrap_or_else(|error| format!(r#"{{"error":"{error}"}}"#))
291            );
292            if !report.ok {
293                process::exit(1);
294            }
295        }
296        Ok(report) => {
297            print_package_doctor_report(&report);
298            if !report.ok {
299                process::exit(1);
300            }
301        }
302        Err(error) => {
303            eprintln!("error: {error}");
304            process::exit(1);
305        }
306    }
307}
308
309pub(crate) fn check_package_impl(
310    anchor: Option<&Path>,
311) -> Result<PackageCheckReport, PackageError> {
312    let ctx = load_manifest_context_for_anchor(anchor)?;
313    let manifest_path = ctx.manifest_path();
314    let mut errors = Vec::new();
315    let mut warnings = Vec::new();
316
317    let package = ctx.manifest.package.as_ref();
318    let name = package.and_then(|package| package.name.clone());
319    let version = package.and_then(|package| package.version.clone());
320    let package_name = required_package_string(
321        package.and_then(|package| package.name.as_deref()),
322        "[package].name",
323        &mut errors,
324    );
325    if let Some(name) = package_name {
326        if let Err(message) = validate_package_alias(name) {
327            push_error(&mut errors, "[package].name", message);
328        }
329    }
330    required_package_string(
331        package.and_then(|package| package.version.as_deref()),
332        "[package].version",
333        &mut errors,
334    );
335    required_package_string(
336        package.and_then(|package| package.description.as_deref()),
337        "[package].description",
338        &mut errors,
339    );
340    required_package_string(
341        package.and_then(|package| package.license.as_deref()),
342        "[package].license",
343        &mut errors,
344    );
345    if !ctx.dir.join("README.md").is_file() {
346        push_error(&mut errors, "README.md", "package README.md is required");
347    }
348    if !ctx.dir.join("LICENSE").is_file() && package.and_then(|p| p.license.as_deref()).is_none() {
349        push_error(
350            &mut errors,
351            "[package].license",
352            "publishable packages require a license field or LICENSE file",
353        );
354    }
355
356    validate_optional_url(
357        package.and_then(|package| package.repository.as_deref()),
358        "[package].repository",
359        &mut errors,
360    );
361    validate_docs_url(
362        &ctx.dir,
363        package.and_then(|package| package.docs_url.as_deref()),
364        &mut errors,
365        &mut warnings,
366    );
367    match package.and_then(|package| package.harn.as_deref()) {
368        Some(range) if supports_current_harn(range) => {}
369        Some(range) => push_error(
370            &mut errors,
371            "[package].harn",
372            format!(
373                "unsupported Harn version range '{range}'; include the current {} line, for example {}",
374                current_harn_line_label(),
375                current_harn_range_example()
376            ),
377        ),
378        None => push_error(
379            &mut errors,
380            "[package].harn",
381            format!(
382                "missing Harn compatibility metadata; add harn = \"{}\"",
383                current_harn_range_example()
384            ),
385        ),
386    }
387
388    validate_dependencies_for_publish(&ctx, &mut errors, &mut warnings);
389    if let Err(error) = validate_handoff_routes(&ctx.manifest.handoff_routes, &ctx.manifest) {
390        push_error(&mut errors, "handoff_routes", error.to_string());
391    }
392    let exports = validate_exports_for_publish(&ctx, &mut errors, &mut warnings);
393    let (tools, skills) = validate_package_interface_exports(&ctx, &mut errors, &mut warnings);
394
395    Ok(PackageCheckReport {
396        package_dir: ctx.dir.display().to_string(),
397        manifest_path: manifest_path.display().to_string(),
398        name,
399        version,
400        errors,
401        warnings,
402        exports,
403        tools,
404        skills,
405    })
406}
407
408pub(crate) fn list_packages_impl() -> Result<PackageListReport, PackageError> {
409    let workspace = PackageWorkspace::from_current_dir()?;
410    list_packages_in(&workspace)
411}
412
413fn list_packages_in(workspace: &PackageWorkspace) -> Result<PackageListReport, PackageError> {
414    let ctx = workspace.load_manifest_context()?;
415    let lock_path = ctx.lock_path();
416    let lock = LockFile::load(&lock_path)?;
417    let packages = lock
418        .as_ref()
419        .map(|lock| package_list_entries(&ctx, lock))
420        .unwrap_or_default();
421    Ok(PackageListReport {
422        manifest_path: ctx.manifest_path().display().to_string(),
423        lock_path: lock_path.display().to_string(),
424        lock_present: lock.is_some(),
425        dependency_count: ctx.manifest.dependencies.len(),
426        packages,
427    })
428}
429
430pub(crate) fn doctor_packages_impl() -> Result<PackageDoctorReport, PackageError> {
431    let workspace = PackageWorkspace::from_current_dir()?;
432    doctor_packages_in(&workspace)
433}
434
435fn doctor_packages_in(workspace: &PackageWorkspace) -> Result<PackageDoctorReport, PackageError> {
436    let ctx = workspace.load_manifest_context()?;
437    let lock_path = ctx.lock_path();
438    let mut diagnostics = Vec::new();
439
440    let mut root_errors = Vec::new();
441    let mut root_warnings = Vec::new();
442    if let Some(package) = ctx.manifest.package.as_ref() {
443        if let Some(name) = package.name.as_ref() {
444            if let Err(message) = validate_package_alias(name) {
445                push_error(&mut root_errors, "[package].name", message);
446            }
447        }
448    }
449    validate_package_interface_exports(&ctx, &mut root_errors, &mut root_warnings);
450    for diagnostic in root_errors {
451        diagnostics.push(package_doctor_diagnostic(
452            "error",
453            "root-package-contract",
454            format!("{}: {}", diagnostic.field, diagnostic.message),
455            Some("fix install-facing package metadata in harn.toml"),
456        ));
457    }
458    for diagnostic in root_warnings {
459        diagnostics.push(package_doctor_diagnostic(
460            "warning",
461            "root-package-contract",
462            format!("{}: {}", diagnostic.field, diagnostic.message),
463            None::<String>,
464        ));
465    }
466
467    let lock = LockFile::load(&lock_path)?;
468    if ctx.manifest.dependencies.is_empty() {
469        diagnostics.push(package_doctor_diagnostic(
470            "info",
471            "no-dependencies",
472            "manifest has no package dependencies",
473            None::<String>,
474        ));
475    } else if lock.is_none() {
476        diagnostics.push(package_doctor_diagnostic(
477            "error",
478            "missing-lockfile",
479            format!("{} is missing", lock_path.display()),
480            Some("run `harn install` to resolve dependencies and write harn.lock"),
481        ));
482    }
483
484    if let Some(lock) = lock.as_ref() {
485        if let Err(error) = validate_lock_matches_manifest(workspace, &ctx, lock) {
486            diagnostics.push(package_doctor_diagnostic(
487                "error",
488                "stale-lockfile",
489                error.to_string(),
490                Some("run `harn install` to refresh harn.lock"),
491            ));
492        }
493        for entry in &lock.packages {
494            validate_installed_package_entry(&ctx, entry, &mut diagnostics);
495        }
496    }
497
498    let packages = lock
499        .as_ref()
500        .map(|lock| package_list_entries(&ctx, lock))
501        .unwrap_or_default();
502    let ok = diagnostics
503        .iter()
504        .all(|diagnostic| diagnostic.severity != "error");
505    Ok(PackageDoctorReport {
506        ok,
507        manifest_path: ctx.manifest_path().display().to_string(),
508        lock_path: lock_path.display().to_string(),
509        diagnostics,
510        packages,
511    })
512}
513
514fn package_list_entries(ctx: &ManifestContext, lock: &LockFile) -> Vec<PackageListEntry> {
515    lock.packages
516        .iter()
517        .map(|entry| {
518            let materialized = materialized_package_exists(ctx, entry);
519            PackageListEntry {
520                name: entry.name.clone(),
521                source: entry.source.clone(),
522                package_version: entry.package_version.clone(),
523                harn_compat: entry.harn_compat.clone(),
524                provenance: entry.provenance.clone(),
525                materialized,
526                integrity: package_integrity_status(ctx, entry),
527                exports: entry.exports.clone(),
528                permissions: entry.permissions.clone(),
529                host_requirements: entry.host_requirements.clone(),
530            }
531        })
532        .collect()
533}
534
535fn materialized_package_path(ctx: &ManifestContext, entry: &LockEntry) -> PathBuf {
536    let packages_dir = ctx.packages_dir();
537    let dir = packages_dir.join(&entry.name);
538    if dir.exists() {
539        return dir;
540    }
541    packages_dir.join(format!("{}.harn", entry.name))
542}
543
544fn materialized_package_exists(ctx: &ManifestContext, entry: &LockEntry) -> bool {
545    materialized_package_path(ctx, entry).exists()
546}
547
548fn package_integrity_status(ctx: &ManifestContext, entry: &LockEntry) -> String {
549    if !materialized_package_exists(ctx, entry) {
550        return "missing".to_string();
551    }
552    let Some(expected) = entry.content_hash.as_deref() else {
553        return "not_checked".to_string();
554    };
555    let path = materialized_package_path(ctx, entry);
556    if path.is_dir() && materialized_hash_matches(&path, expected) {
557        "ok".to_string()
558    } else {
559        "mismatch".to_string()
560    }
561}
562
563fn validate_installed_package_entry(
564    ctx: &ManifestContext,
565    entry: &LockEntry,
566    diagnostics: &mut Vec<PackageDoctorDiagnostic>,
567) {
568    let materialized_path = materialized_package_path(ctx, entry);
569    if !materialized_path.exists() {
570        diagnostics.push(package_doctor_diagnostic(
571            "error",
572            "package-not-materialized",
573            format!(
574                "package {} is locked but missing from {}",
575                entry.name,
576                ctx.packages_dir().display()
577            ),
578            Some("run `harn install` to materialize locked packages"),
579        ));
580        return;
581    }
582
583    if package_integrity_status(ctx, entry) == "mismatch" {
584        diagnostics.push(package_doctor_diagnostic(
585            "error",
586            "content-hash-mismatch",
587            format!(
588                "package {} does not match its locked content hash",
589                entry.name
590            ),
591            Some(
592                "run `harn install --refetch {alias}` or inspect local tampering"
593                    .replace("{alias}", &entry.name),
594            ),
595        ));
596    }
597
598    for requirement in &entry.host_requirements {
599        if !host_requirement_satisfied(&ctx.manifest.check, requirement) {
600            diagnostics.push(package_doctor_diagnostic(
601                "error",
602                "missing-host-capability",
603                format!(
604                    "package {} requires host capability {requirement}, but harn.toml does not declare it",
605                    entry.name
606                ),
607                Some("add the capability under [check.host_capabilities] or preflight_allow after the host implements it"),
608            ));
609        }
610    }
611
612    if materialized_path.is_dir() {
613        match read_package_manifest_from_dir(&materialized_path) {
614            Ok(Some(manifest)) => {
615                let installed_ctx = ManifestContext {
616                    manifest,
617                    dir: materialized_path,
618                };
619                let mut errors = Vec::new();
620                let mut warnings = Vec::new();
621                validate_package_interface_exports(&installed_ctx, &mut errors, &mut warnings);
622                for diagnostic in errors {
623                    diagnostics.push(package_doctor_diagnostic(
624                        "error",
625                        "installed-package-export",
626                        format!("{}: {}", diagnostic.field, diagnostic.message),
627                        Some(format!("fix package {} and reinstall it", entry.name)),
628                    ));
629                }
630                for diagnostic in warnings {
631                    diagnostics.push(package_doctor_diagnostic(
632                        "warning",
633                        "installed-package-export-warning",
634                        format!("{}: {}", diagnostic.field, diagnostic.message),
635                        None::<String>,
636                    ));
637                }
638            }
639            Ok(None) => {}
640            Err(error) => diagnostics.push(package_doctor_diagnostic(
641                "error",
642                "installed-manifest-unreadable",
643                format!("failed to read package {} manifest: {error}", entry.name),
644                Some("repair the package source and run `harn install`"),
645            )),
646        }
647    }
648}
649
650fn host_requirement_satisfied(check: &CheckConfig, requirement: &str) -> bool {
651    if check.preflight_allow.iter().any(|allow| {
652        allow == "*"
653            || allow == requirement
654            || requirement
655                .strip_prefix(allow.trim_end_matches(".*"))
656                .is_some_and(|rest| allow.ends_with(".*") && rest.starts_with('.'))
657            || requirement
658                .split_once('.')
659                .is_some_and(|(capability, _)| allow == capability)
660    }) {
661        return true;
662    }
663    let Some((capability, operation)) = requirement.split_once('.') else {
664        return false;
665    };
666    check
667        .host_capabilities
668        .get(capability)
669        .is_some_and(|ops| ops.iter().any(|op| op == "*" || op == operation))
670}
671
672fn package_doctor_diagnostic(
673    severity: impl Into<String>,
674    code: impl Into<String>,
675    message: impl Into<String>,
676    help: Option<impl Into<String>>,
677) -> PackageDoctorDiagnostic {
678    PackageDoctorDiagnostic {
679        severity: severity.into(),
680        code: code.into(),
681        message: message.into(),
682        help: help.map(Into::into),
683    }
684}
685
686pub(crate) fn pack_package_impl(
687    anchor: Option<&Path>,
688    output: Option<&Path>,
689    dry_run: bool,
690) -> Result<PackagePackReport, PackageError> {
691    let report = check_package_impl(anchor)?;
692    fail_if_package_errors(&report)?;
693    let ctx = load_manifest_context_for_anchor(anchor)?;
694    let files = collect_package_files(&ctx.dir)?;
695    let artifact_dir = output
696        .map(Path::to_path_buf)
697        .unwrap_or_else(|| default_artifact_dir(&ctx, &report));
698
699    if !dry_run {
700        if artifact_dir.exists() {
701            return Err(
702                format!("artifact output {} already exists", artifact_dir.display()).into(),
703            );
704        }
705        fs::create_dir_all(&artifact_dir)
706            .map_err(|error| format!("failed to create {}: {error}", artifact_dir.display()))?;
707        for rel in &files {
708            let src = ctx.dir.join(rel);
709            let dst = artifact_dir.join(rel);
710            if let Some(parent) = dst.parent() {
711                fs::create_dir_all(parent)
712                    .map_err(|error| format!("failed to create {}: {error}", parent.display()))?;
713            }
714            fs::copy(&src, &dst)
715                .map_err(|error| format!("failed to copy {}: {error}", src.display()))?;
716        }
717        let manifest_path = artifact_dir.join(".harn-package-manifest.json");
718        let manifest_body = serde_json::to_string_pretty(&report)
719            .map_err(|error| format!("failed to render package manifest: {error}"))?
720            + "\n";
721        harn_vm::atomic_io::atomic_write(&manifest_path, manifest_body.as_bytes())
722            .map_err(|error| format!("failed to write {}: {error}", manifest_path.display()))?;
723    }
724
725    Ok(PackagePackReport {
726        package_dir: ctx.dir.display().to_string(),
727        artifact_dir: artifact_dir.display().to_string(),
728        dry_run,
729        files,
730        check: report,
731    })
732}
733
734pub(crate) fn generate_package_docs_impl(
735    anchor: Option<&Path>,
736    output: Option<&Path>,
737    check: bool,
738) -> Result<PathBuf, PackageError> {
739    let report = check_package_impl(anchor)?;
740    let ctx = load_manifest_context_for_anchor(anchor)?;
741    let output_path = output
742        .map(Path::to_path_buf)
743        .unwrap_or_else(|| ctx.dir.join("docs").join("api.md"));
744    let rendered = render_package_api_docs(&report);
745    if check {
746        let existing = fs::read_to_string(&output_path)
747            .map_err(|error| format!("failed to read {}: {error}", output_path.display()))?;
748        if normalize_newlines(&existing) != normalize_newlines(&rendered) {
749            return Err(format!(
750                "{} is stale; run `harn package docs`",
751                output_path.display()
752            )
753            .into());
754        }
755        return Ok(output_path);
756    }
757    harn_vm::atomic_io::atomic_write(&output_path, rendered.as_bytes())
758        .map_err(|error| format!("failed to write {}: {error}", output_path.display()))?;
759    Ok(output_path)
760}
761
762pub(crate) fn publish_package_impl(
763    anchor: Option<&Path>,
764    options: &PackagePublishOptions<'_>,
765) -> Result<PackagePublishReport, PackageError> {
766    let registry = options
767        .registry
768        .map(str::trim)
769        .filter(|value| !value.is_empty())
770        .map(ToOwned::to_owned)
771        .unwrap_or_else(|| {
772            format!(
773                "{}/{}",
774                options.index_repo.trim(),
775                normalized_relative_path(options.index_path)
776            )
777        });
778    let index_content = if options.skip_index_pr {
779        String::new()
780    } else {
781        fetch_package_index_from_github(options.index_repo, options.index_path)?
782    };
783    let mut plan = prepare_publish_plan(anchor, options, index_content, &registry)?;
784    if !options.dry_run && !options.skip_index_pr {
785        ensure_github_repo_writeable(options.index_repo)?;
786    }
787    let index_pr_url = if options.dry_run {
788        None
789    } else {
790        execute_publish_plan(&mut plan, options.skip_index_pr)?
791    };
792
793    Ok(PackagePublishReport {
794        dry_run: options.dry_run,
795        registry,
796        artifact_dir: plan.pack.artifact_dir,
797        files: plan.pack.files,
798        tag: plan.tag,
799        sha: plan.sha,
800        remote: plan.remote,
801        index_repo: plan.index_repo,
802        index_path: normalized_relative_path(&plan.index_path),
803        index_pr_url,
804        tag_command: Some(plan.tag_command),
805        index_diff: if options.skip_index_pr {
806            None
807        } else {
808            Some(plan.index_diff)
809        },
810        check: plan.pack.check,
811    })
812}
813
814fn prepare_publish_plan(
815    anchor: Option<&Path>,
816    options: &PackagePublishOptions<'_>,
817    index_content: String,
818    registry: &str,
819) -> Result<PackagePublishPlan, PackageError> {
820    let pack = pack_package_impl(anchor, None, true)?;
821    let ctx = load_manifest_context_for_anchor(anchor)?;
822    let package_info = ctx
823        .manifest
824        .package
825        .as_ref()
826        .ok_or_else(|| PackageError::Ops("[package] metadata is required".to_string()))?;
827    let package_name = pack
828        .check
829        .name
830        .clone()
831        .ok_or_else(|| PackageError::Ops("[package].name is required".to_string()))?;
832    let version = pack
833        .check
834        .version
835        .clone()
836        .ok_or_else(|| PackageError::Ops("[package].version is required".to_string()))?;
837    let registry_name = options
838        .registry_name
839        .map(str::trim)
840        .filter(|name| !name.is_empty())
841        .unwrap_or(&package_name)
842        .to_string();
843    if !is_valid_registry_package_name(&registry_name) {
844        return Err(PackageError::Validation(format!(
845            "invalid registry package name '{registry_name}'; use names like @burin/notion-sdk or acme-lib"
846        )));
847    }
848
849    let repo_root = git_output(&ctx.dir, ["rev-parse", "--show-toplevel"])?;
850    let repo_root = PathBuf::from(repo_root.trim());
851    ensure_git_worktree_clean(&repo_root)?;
852    let sha = git_output(&repo_root, ["rev-parse", "HEAD"])?
853        .trim()
854        .to_string();
855    let remote = options.remote.trim();
856    if remote.is_empty() {
857        return Err(PackageError::Ops("--remote cannot be empty".to_string()));
858    }
859    let remote_url = git_output(&repo_root, ["remote", "get-url", remote])?
860        .trim()
861        .to_string();
862    let git = normalize_git_url(&remote_url)?;
863    let tag = format!("v{version}");
864    ensure_tag_available(&repo_root, remote, &tag)?;
865    ensure_changelog_entry(&ctx.dir.join("CHANGELOG.md"), &version)?;
866
867    let (updated_index_content, index_diff) = if options.skip_index_pr {
868        (index_content, String::new())
869    } else {
870        let entry = render_registry_version_entry(&version, &git, &tag, &sha, &package_name)?;
871        let updated = add_registry_version_entry(
872            &index_content,
873            package_info,
874            &pack.check,
875            &registry_name,
876            &entry,
877            &version,
878            &git,
879        )?;
880        parse_package_registry_index(registry, &updated)?;
881        let diff = render_unified_diff(
882            &index_content,
883            &updated,
884            &normalized_relative_path(options.index_path),
885        )?;
886        (updated, diff)
887    };
888
889    Ok(PackagePublishPlan {
890        repo_root: repo_root.clone(),
891        package_name,
892        registry_name,
893        version,
894        tag: tag.clone(),
895        sha,
896        git,
897        remote: remote.to_string(),
898        index_repo: options.index_repo.trim().to_string(),
899        index_path: options.index_path.to_path_buf(),
900        updated_index_content,
901        index_diff,
902        tag_command: format!(
903            "git -C {} tag {tag} && git -C {} push {remote} refs/tags/{tag}",
904            shell_quote_path(&repo_root),
905            shell_quote_path(&repo_root)
906        ),
907        pack,
908    })
909}
910
911fn execute_publish_plan(
912    plan: &mut PackagePublishPlan,
913    skip_index_pr: bool,
914) -> Result<Option<String>, PackageError> {
915    run_git_checked(&plan.repo_root, ["tag", plan.tag.as_str()])?;
916    run_git_checked(
917        &plan.repo_root,
918        [
919            "push",
920            plan.remote.as_str(),
921            &format!("refs/tags/{}", plan.tag),
922        ],
923    )?;
924    if skip_index_pr {
925        return Ok(None);
926    }
927    create_index_pull_request(plan).map(Some)
928}
929
930fn create_index_pull_request(plan: &PackagePublishPlan) -> Result<String, PackageError> {
931    let temp = tempfile::tempdir()
932        .map_err(|error| PackageError::Ops(format!("failed to create temp dir: {error}")))?;
933    let checkout = temp.path().join("index");
934    let base_branch = github_default_branch(&plan.index_repo)?;
935    run_command_checked(
936        Path::new("."),
937        "gh",
938        [
939            "repo",
940            "clone",
941            plan.index_repo.as_str(),
942            checkout.to_string_lossy().as_ref(),
943            "--",
944            "--depth",
945            "1",
946            "--branch",
947            base_branch.as_str(),
948        ],
949    )?;
950    let branch = format!(
951        "harn-publish/{}-{}",
952        sanitize_branch_segment(&plan.package_name),
953        sanitize_branch_segment(&plan.version)
954    );
955    run_git_checked(&checkout, ["switch", "-c", branch.as_str()])?;
956    let index_path = checkout.join(&plan.index_path);
957    if let Some(parent) = index_path.parent() {
958        fs::create_dir_all(parent)
959            .map_err(|error| format!("failed to create {}: {error}", parent.display()))?;
960    }
961    fs::write(&index_path, &plan.updated_index_content)
962        .map_err(|error| format!("failed to write {}: {error}", index_path.display()))?;
963    run_git_checked(
964        &checkout,
965        ["add", normalized_relative_path(&plan.index_path).as_str()],
966    )?;
967    run_git_checked(
968        &checkout,
969        [
970            "commit",
971            "-m",
972            &format!(
973                "Add {} {} to package index",
974                plan.registry_name, plan.version
975            ),
976        ],
977    )?;
978    run_git_checked(&checkout, ["push", "-u", "origin", branch.as_str()])?;
979    let body = format!(
980        "Adds `{}` version `{}` to the Harn package index.\n\nSource tag: `{}`\nSource SHA: `{}`\nSource git: `{}`\n",
981        plan.registry_name, plan.version, plan.tag, plan.sha, plan.git
982    );
983    let body_path = temp.path().join("pr-body.md");
984    fs::write(&body_path, body)
985        .map_err(|error| format!("failed to write {}: {error}", body_path.display()))?;
986    let output = run_command_output(
987        Path::new("."),
988        "gh",
989        [
990            "pr",
991            "create",
992            "--repo",
993            plan.index_repo.as_str(),
994            "--base",
995            base_branch.as_str(),
996            "--head",
997            branch.as_str(),
998            "--title",
999            &format!(
1000                "Add {} {} to package index",
1001                plan.registry_name, plan.version
1002            ),
1003            "--body-file",
1004            body_path.to_string_lossy().as_ref(),
1005        ],
1006    )?;
1007    Ok(output.trim().to_string())
1008}
1009
1010fn github_default_branch(index_repo: &str) -> Result<String, PackageError> {
1011    let branch = run_command_output(
1012        Path::new("."),
1013        "gh",
1014        [
1015            "repo",
1016            "view",
1017            index_repo.trim(),
1018            "--json",
1019            "defaultBranchRef",
1020            "--jq",
1021            ".defaultBranchRef.name",
1022        ],
1023    )?;
1024    let branch = branch.trim();
1025    if branch.is_empty() {
1026        Err(PackageError::Registry(format!(
1027            "failed to resolve default branch for {index_repo}"
1028        )))
1029    } else {
1030        Ok(branch.to_string())
1031    }
1032}
1033
1034fn fetch_package_index_from_github(
1035    index_repo: &str,
1036    index_path: &Path,
1037) -> Result<String, PackageError> {
1038    ensure_gh_available()?;
1039    let api_path = format!(
1040        "repos/{}/contents/{}",
1041        index_repo.trim(),
1042        normalized_relative_path(index_path)
1043    );
1044    let content = run_command_output(
1045        Path::new("."),
1046        "gh",
1047        ["api", api_path.as_str(), "--jq", ".content"],
1048    )?;
1049    let encoded = content.replace(['\n', '\r'], "");
1050    let bytes = base64::engine::general_purpose::STANDARD
1051        .decode(encoded.as_bytes())
1052        .map_err(|error| {
1053            PackageError::Registry(format!(
1054                "failed to decode package index from {index_repo}: {}: {error}",
1055                index_path.display()
1056            ))
1057        })?;
1058    String::from_utf8(bytes).map_err(|error| {
1059        PackageError::Registry(format!(
1060            "package index {} in {index_repo} is not UTF-8: {error}",
1061            index_path.display()
1062        ))
1063    })
1064}
1065
1066fn ensure_gh_available() -> Result<(), PackageError> {
1067    which::which("gh").map(|_| ()).map_err(|_| {
1068        PackageError::Registry(
1069            "gh is required to read or update the package index but was not found in PATH"
1070                .to_string(),
1071        )
1072    })
1073}
1074
1075fn ensure_github_repo_writeable(index_repo: &str) -> Result<(), PackageError> {
1076    let permission = run_command_output(
1077        Path::new("."),
1078        "gh",
1079        [
1080            "repo",
1081            "view",
1082            index_repo.trim(),
1083            "--json",
1084            "viewerPermission",
1085            "--jq",
1086            ".viewerPermission",
1087        ],
1088    )?;
1089    let permission = permission.trim();
1090    if matches!(permission, "ADMIN" | "MAINTAIN" | "WRITE") {
1091        Ok(())
1092    } else {
1093        Err(PackageError::Registry(format!(
1094            "current gh auth has {permission} permission on {index_repo}; WRITE, MAINTAIN, or ADMIN is required to open the package-index PR"
1095        )))
1096    }
1097}
1098
1099fn ensure_git_worktree_clean(repo: &Path) -> Result<(), PackageError> {
1100    let status = git_output(repo, ["status", "--porcelain"])?;
1101    if status.trim().is_empty() {
1102        Ok(())
1103    } else {
1104        Err(PackageError::Ops(format!(
1105            "working tree must be clean before publishing:\n{}",
1106            status.trim_end()
1107        )))
1108    }
1109}
1110
1111fn ensure_tag_available(repo: &Path, remote: &str, tag: &str) -> Result<(), PackageError> {
1112    if git_status(
1113        repo,
1114        [
1115            "rev-parse",
1116            "--verify",
1117            "--quiet",
1118            &format!("refs/tags/{tag}"),
1119        ],
1120    )?
1121    .success()
1122    {
1123        return Err(PackageError::Ops(format!(
1124            "git tag {tag} already exists locally"
1125        )));
1126    }
1127    let status = git_status(
1128        repo,
1129        [
1130            "ls-remote",
1131            "--exit-code",
1132            "--tags",
1133            remote,
1134            &format!("refs/tags/{tag}"),
1135        ],
1136    )?;
1137    if status.success() {
1138        return Err(PackageError::Ops(format!(
1139            "git tag {tag} already exists on remote {remote}"
1140        )));
1141    }
1142    if status.code() == Some(2) {
1143        return Ok(());
1144    }
1145    Err(PackageError::Ops(format!(
1146        "failed to check whether tag {tag} exists on remote {remote}"
1147    )))
1148}
1149
1150fn ensure_changelog_entry(path: &Path, version: &str) -> Result<(), PackageError> {
1151    let content = fs::read_to_string(path)
1152        .map_err(|error| format!("failed to read {}: {error}", path.display()))?;
1153    if changelog_has_nonempty_entry(&content, version) {
1154        Ok(())
1155    } else {
1156        Err(PackageError::Validation(format!(
1157            "{} must contain a non-empty entry for version {version}",
1158            path.display()
1159        )))
1160    }
1161}
1162
1163fn changelog_has_nonempty_entry(content: &str, version: &str) -> bool {
1164    let escaped = regex::escape(version);
1165    let heading = Regex::new(&format!(
1166        r"(?m)^#{{1,6}}\s+(?:\[?v?{escaped}\]?)(?:\s|$|[-(])"
1167    ))
1168    .expect("valid changelog heading regex");
1169    let Some(found) = heading.find(content) else {
1170        return false;
1171    };
1172    let rest = &content[found.end()..];
1173    let entry = rest
1174        .lines()
1175        .take_while(|line| !line.trim_start().starts_with('#'))
1176        .map(str::trim)
1177        .filter(|line| !line.is_empty() && !line.starts_with("<!--"))
1178        .collect::<Vec<_>>();
1179    !entry.is_empty()
1180}
1181
1182fn add_registry_version_entry(
1183    content: &str,
1184    package_info: &PackageInfo,
1185    report: &PackageCheckReport,
1186    registry_name: &str,
1187    version_entry: &str,
1188    version: &str,
1189    git: &str,
1190) -> Result<String, PackageError> {
1191    let snapshot = parse_publish_index_snapshot(content)?;
1192    if let Some(package) = snapshot
1193        .packages
1194        .iter()
1195        .find(|package| package.name == registry_name)
1196    {
1197        if package
1198            .versions
1199            .iter()
1200            .any(|entry| entry.version == version)
1201        {
1202            return Err(PackageError::Registry(format!(
1203                "package index already contains {registry_name}@{version}"
1204            )));
1205        }
1206        return insert_version_entry(content, registry_name, version_entry);
1207    }
1208
1209    let mut updated = content.trim_end().to_string();
1210    updated.push_str("\n\n");
1211    updated.push_str(&render_registry_package_block(
1212        package_info,
1213        report,
1214        registry_name,
1215        git,
1216        version_entry,
1217    )?);
1218    Ok(updated)
1219}
1220
1221fn insert_version_entry(
1222    content: &str,
1223    registry_name: &str,
1224    version_entry: &str,
1225) -> Result<String, PackageError> {
1226    let starts = package_block_offsets(content);
1227    for (idx, start) in starts.iter().enumerate() {
1228        let end = starts.get(idx + 1).copied().unwrap_or(content.len());
1229        let block = &content[*start..end];
1230        if block_has_registry_name(block, registry_name) {
1231            let mut updated = String::with_capacity(content.len() + version_entry.len() + 2);
1232            updated.push_str(content[..end].trim_end());
1233            updated.push_str("\n\n");
1234            updated.push_str(version_entry.trim_end());
1235            updated.push('\n');
1236            updated.push_str(&content[end..]);
1237            return Ok(updated);
1238        }
1239    }
1240    Err(PackageError::Registry(format!(
1241        "failed to locate package index block for {registry_name}"
1242    )))
1243}
1244
1245fn package_block_offsets(content: &str) -> Vec<usize> {
1246    let mut offsets = Vec::new();
1247    let mut cursor = 0;
1248    for line in content.split_inclusive('\n') {
1249        if line.trim() == "[[package]]" {
1250            offsets.push(cursor);
1251        }
1252        cursor += line.len();
1253    }
1254    if cursor < content.len() && content[cursor..].trim() == "[[package]]" {
1255        offsets.push(cursor);
1256    }
1257    offsets
1258}
1259
1260fn block_has_registry_name(block: &str, registry_name: &str) -> bool {
1261    let literal = match toml_string_literal(registry_name) {
1262        Ok(literal) => literal,
1263        Err(_) => return false,
1264    };
1265    block.lines().any(|line| {
1266        let line = line.trim();
1267        line.strip_prefix("name")
1268            .and_then(|rest| rest.trim_start().strip_prefix('='))
1269            .is_some_and(|value| value.trim() == literal)
1270    })
1271}
1272
1273#[derive(Debug, Deserialize)]
1274struct PublishIndexSnapshot {
1275    #[serde(default, rename = "package")]
1276    packages: Vec<PublishIndexPackageSnapshot>,
1277}
1278
1279#[derive(Debug, Deserialize)]
1280struct PublishIndexPackageSnapshot {
1281    name: String,
1282    #[serde(default, rename = "version")]
1283    versions: Vec<PublishIndexVersionSnapshot>,
1284}
1285
1286#[derive(Debug, Deserialize)]
1287struct PublishIndexVersionSnapshot {
1288    version: String,
1289}
1290
1291fn parse_publish_index_snapshot(content: &str) -> Result<PublishIndexSnapshot, PackageError> {
1292    toml::from_str(content)
1293        .map_err(|error| PackageError::Registry(format!("failed to parse package index: {error}")))
1294}
1295
1296fn render_registry_package_block(
1297    package_info: &PackageInfo,
1298    report: &PackageCheckReport,
1299    registry_name: &str,
1300    git: &str,
1301    version_entry: &str,
1302) -> Result<String, PackageError> {
1303    let mut out = String::new();
1304    out.push_str("[[package]]\n");
1305    push_toml_string_field(&mut out, "name", registry_name)?;
1306    if let Some(description) = package_info.description.as_deref() {
1307        push_toml_string_field(&mut out, "description", description)?;
1308    }
1309    push_toml_string_field(
1310        &mut out,
1311        "repository",
1312        package_info.repository.as_deref().unwrap_or(git),
1313    )?;
1314    if let Some(license) = package_info.license.as_deref() {
1315        push_toml_string_field(&mut out, "license", license)?;
1316    }
1317    if let Some(harn) = package_info.harn.as_deref() {
1318        push_toml_string_field(&mut out, "harn", harn)?;
1319    }
1320    if !report.exports.is_empty() {
1321        let exports = report
1322            .exports
1323            .iter()
1324            .map(|export| toml_string_literal(&export.name))
1325            .collect::<Result<Vec<_>, _>>()?
1326            .join(", ");
1327        out.push_str(&format!("exports = [{exports}]\n"));
1328    }
1329    if let Some(docs_url) = package_info.docs_url.as_deref() {
1330        push_toml_string_field(&mut out, "docs_url", docs_url)?;
1331    }
1332    push_toml_string_field(&mut out, "provenance", git)?;
1333    out.push('\n');
1334    out.push_str(version_entry.trim_end());
1335    out.push('\n');
1336    Ok(out)
1337}
1338
1339fn render_registry_version_entry(
1340    version: &str,
1341    git: &str,
1342    tag: &str,
1343    sha: &str,
1344    package_name: &str,
1345) -> Result<String, PackageError> {
1346    let provenance =
1347        github_tag_url(git, tag).unwrap_or_else(|| format!("{git}/releases/tag/{tag}"));
1348    let mut out = String::new();
1349    out.push_str("[[package.version]]\n");
1350    push_toml_string_field(&mut out, "version", version)?;
1351    push_toml_string_field(&mut out, "git", git)?;
1352    push_toml_string_field(&mut out, "rev", sha)?;
1353    push_toml_string_field(&mut out, "tag", tag)?;
1354    push_toml_string_field(&mut out, "sha", sha)?;
1355    push_toml_string_field(&mut out, "package", package_name)?;
1356    push_toml_string_field(&mut out, "provenance", &provenance)?;
1357    Ok(out)
1358}
1359
1360fn github_tag_url(git: &str, tag: &str) -> Option<String> {
1361    let url = Url::parse(git).ok()?;
1362    let host = url.host_str()?;
1363    if host != "github.com" {
1364        return None;
1365    }
1366    let path = url.path().trim_matches('/');
1367    let mut segments = path.split('/');
1368    let owner = segments.next()?;
1369    let repo = segments.next()?;
1370    Some(format!(
1371        "https://github.com/{owner}/{repo}/releases/tag/{tag}"
1372    ))
1373}
1374
1375fn push_toml_string_field(out: &mut String, key: &str, value: &str) -> Result<(), PackageError> {
1376    out.push_str(key);
1377    out.push_str(" = ");
1378    out.push_str(&toml_string_literal(value)?);
1379    out.push('\n');
1380    Ok(())
1381}
1382
1383fn render_unified_diff(old: &str, new: &str, label: &str) -> Result<String, PackageError> {
1384    let temp = tempfile::tempdir()
1385        .map_err(|error| PackageError::Ops(format!("failed to create temp dir: {error}")))?;
1386    let old_path = temp.path().join("old");
1387    let new_path = temp.path().join("new");
1388    fs::write(&old_path, old).map_err(|error| format!("failed to write diff input: {error}"))?;
1389    fs::write(&new_path, new).map_err(|error| format!("failed to write diff input: {error}"))?;
1390    let output = process::Command::new("git")
1391        .args(["diff", "--no-index", "--"])
1392        .arg(&old_path)
1393        .arg(&new_path)
1394        .output()
1395        .map_err(|error| {
1396            PackageError::Ops(format!("failed to render package-index diff: {error}"))
1397        })?;
1398    if !output.status.success() && output.status.code() != Some(1) {
1399        return Err(PackageError::Ops(format!(
1400            "failed to render package-index diff: {}",
1401            String::from_utf8_lossy(&output.stderr)
1402        )));
1403    }
1404    let mut diff = String::from_utf8_lossy(&output.stdout).into_owned();
1405    let old_display = old_path.display().to_string();
1406    let new_display = new_path.display().to_string();
1407    diff = diff.replace(&format!("--- {old_display}"), &format!("--- a/{label}"));
1408    diff = diff.replace(&format!("+++ {new_display}"), &format!("+++ b/{label}"));
1409    Ok(diff)
1410}
1411
1412fn git_output<const N: usize>(repo: &Path, args: [&str; N]) -> Result<String, PackageError> {
1413    run_command_output(repo, "git", args)
1414}
1415
1416fn git_status<const N: usize>(
1417    repo: &Path,
1418    args: [&str; N],
1419) -> Result<process::ExitStatus, PackageError> {
1420    process::Command::new("git")
1421        .current_dir(repo)
1422        .args(args)
1423        .env_remove("GIT_DIR")
1424        .env_remove("GIT_WORK_TREE")
1425        .env_remove("GIT_INDEX_FILE")
1426        .output()
1427        .map(|output| output.status)
1428        .map_err(|error| PackageError::Ops(format!("failed to run git: {error}")))
1429}
1430
1431fn run_git_checked<const N: usize>(repo: &Path, args: [&str; N]) -> Result<(), PackageError> {
1432    run_command_checked(repo, "git", args)
1433}
1434
1435fn run_command_checked<const N: usize>(
1436    cwd: &Path,
1437    program: &str,
1438    args: [&str; N],
1439) -> Result<(), PackageError> {
1440    run_command_output(cwd, program, args).map(|_| ())
1441}
1442
1443fn run_command_output<const N: usize>(
1444    cwd: &Path,
1445    program: &str,
1446    args: [&str; N],
1447) -> Result<String, PackageError> {
1448    let output = process::Command::new(program)
1449        .current_dir(cwd)
1450        .args(args)
1451        .env_remove("GIT_DIR")
1452        .env_remove("GIT_WORK_TREE")
1453        .env_remove("GIT_INDEX_FILE")
1454        .output()
1455        .map_err(|error| PackageError::Ops(format!("failed to run {program}: {error}")))?;
1456    if !output.status.success() {
1457        return Err(PackageError::Ops(format!(
1458            "{} failed: {}",
1459            program,
1460            String::from_utf8_lossy(&output.stderr).trim_end()
1461        )));
1462    }
1463    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
1464}
1465
1466fn sanitize_branch_segment(value: &str) -> String {
1467    value
1468        .chars()
1469        .map(|ch| {
1470            if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.') {
1471                ch
1472            } else {
1473                '-'
1474            }
1475        })
1476        .collect()
1477}
1478
1479fn shell_quote_path(path: &Path) -> String {
1480    let raw = path.display().to_string();
1481    if raw
1482        .bytes()
1483        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'.' | b'-' | b'_'))
1484    {
1485        raw
1486    } else {
1487        format!("'{}'", raw.replace('\'', "'\\''"))
1488    }
1489}
1490
1491pub(crate) fn load_manifest_context_for_anchor(
1492    anchor: Option<&Path>,
1493) -> Result<ManifestContext, PackageError> {
1494    let anchor = anchor
1495        .map(Path::to_path_buf)
1496        .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
1497    let manifest_path = if anchor.is_dir() {
1498        anchor.join(MANIFEST)
1499    } else if anchor.file_name() == Some(OsStr::new(MANIFEST)) {
1500        anchor
1501    } else {
1502        let (_, dir) = find_nearest_manifest(&anchor)
1503            .ok_or_else(|| format!("no {MANIFEST} found from {}", anchor.display()))?;
1504        dir.join(MANIFEST)
1505    };
1506    let manifest = read_manifest_from_path(&manifest_path)?;
1507    let dir = manifest_path
1508        .parent()
1509        .map(Path::to_path_buf)
1510        .unwrap_or_else(|| PathBuf::from("."));
1511    Ok(ManifestContext { manifest, dir })
1512}
1513
1514pub(crate) fn required_package_string<'a>(
1515    value: Option<&'a str>,
1516    field: &str,
1517    errors: &mut Vec<PackageCheckDiagnostic>,
1518) -> Option<&'a str> {
1519    match value.map(str::trim).filter(|value| !value.is_empty()) {
1520        Some(value) => Some(value),
1521        None => {
1522            push_error(errors, field, format!("missing required {field}"));
1523            None
1524        }
1525    }
1526}
1527
1528pub(crate) fn push_error(
1529    diagnostics: &mut Vec<PackageCheckDiagnostic>,
1530    field: impl Into<String>,
1531    message: impl Into<String>,
1532) {
1533    diagnostics.push(PackageCheckDiagnostic {
1534        field: field.into(),
1535        message: message.into(),
1536    });
1537}
1538
1539pub(crate) fn push_warning(
1540    diagnostics: &mut Vec<PackageCheckDiagnostic>,
1541    field: impl Into<String>,
1542    message: impl Into<String>,
1543) {
1544    push_error(diagnostics, field, message);
1545}
1546
1547pub(crate) fn validate_optional_url(
1548    value: Option<&str>,
1549    field: &str,
1550    errors: &mut Vec<PackageCheckDiagnostic>,
1551) {
1552    let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
1553        push_error(errors, field, format!("missing required {field}"));
1554        return;
1555    };
1556    if Url::parse(value).is_err() {
1557        push_error(errors, field, format!("{field} must be an absolute URL"));
1558    }
1559}
1560
1561pub(crate) fn validate_docs_url(
1562    root: &Path,
1563    value: Option<&str>,
1564    errors: &mut Vec<PackageCheckDiagnostic>,
1565    warnings: &mut Vec<PackageCheckDiagnostic>,
1566) {
1567    let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
1568        push_warning(
1569            warnings,
1570            "[package].docs_url",
1571            "missing docs_url; `harn package docs` defaults to docs/api.md",
1572        );
1573        return;
1574    };
1575    if Url::parse(value).is_ok() {
1576        return;
1577    }
1578    let path = PathBuf::from(value);
1579    let path = if path.is_absolute() {
1580        path
1581    } else {
1582        root.join(path)
1583    };
1584    if !path.exists() {
1585        push_error(
1586            errors,
1587            "[package].docs_url",
1588            format!("docs_url path {} does not exist", path.display()),
1589        );
1590    }
1591}
1592
1593pub(crate) fn validate_dependencies_for_publish(
1594    ctx: &ManifestContext,
1595    errors: &mut Vec<PackageCheckDiagnostic>,
1596    warnings: &mut Vec<PackageCheckDiagnostic>,
1597) {
1598    let mut aliases = BTreeSet::new();
1599    for (alias, dependency) in &ctx.manifest.dependencies {
1600        let field = format!("[dependencies].{alias}");
1601        if let Err(message) = validate_package_alias(alias) {
1602            push_error(errors, &field, message);
1603        }
1604        if !aliases.insert(alias) {
1605            push_error(errors, &field, "duplicate dependency alias");
1606        }
1607        match dependency {
1608            Dependency::Path(path) => push_error(
1609                errors,
1610                &field,
1611                format!("path-only dependency '{path}' is not publishable; pin a git tag, git rev, or registry version"),
1612            ),
1613            Dependency::Table(table) => {
1614                if table.version.is_some()
1615                    && (table.git.is_some()
1616                        || table.path.is_some()
1617                        || table.rev.is_some()
1618                        || table.tag.is_some()
1619                        || table.branch.is_some())
1620                {
1621                    push_error(
1622                        errors,
1623                        &field,
1624                        "version dependencies resolve through the registry; do not combine version with git, path, tag, rev, or branch",
1625                    );
1626                }
1627                if table.path.is_some() {
1628                    push_error(
1629                        errors,
1630                        &field,
1631                        "path dependencies are not publishable; pin a git tag, git rev, or registry version",
1632                    );
1633                }
1634                if table.git.is_none() && table.path.is_none() && table.version.is_none() {
1635                    push_error(
1636                        errors,
1637                        &field,
1638                        "dependency must specify git, registry version, or path",
1639                    );
1640                }
1641                let git_ref_count = usize::from(table.rev.is_some())
1642                    + usize::from(table.tag.is_some())
1643                    + usize::from(table.branch.is_some());
1644                if table.git.is_some() && git_ref_count > 1 {
1645                    push_error(errors, &field, "dependency cannot specify more than one of tag, rev, or branch");
1646                }
1647                if table.git.is_some() && git_ref_count == 0 {
1648                    push_error(errors, &field, "git dependency must specify tag, rev, or branch");
1649                }
1650                if table.branch.is_some() {
1651                    push_warning(
1652                        warnings,
1653                        &field,
1654                        "branch dependencies are non-reproducible for publishing; prefer tag, rev, or registry version",
1655                    );
1656                }
1657                if let Some(version) = table.version.as_deref() {
1658                    if let Err(error) = parse_registry_version_req(version) {
1659                        push_error(errors, &field, error.to_string());
1660                    }
1661                }
1662                if let Some(git) = table.git.as_deref() {
1663                    if normalize_git_url(git).is_err() {
1664                        push_error(errors, &field, format!("invalid git source '{git}'"));
1665                    }
1666                }
1667            }
1668        }
1669    }
1670}
1671
1672pub(crate) fn validate_exports_for_publish(
1673    ctx: &ManifestContext,
1674    errors: &mut Vec<PackageCheckDiagnostic>,
1675    warnings: &mut Vec<PackageCheckDiagnostic>,
1676) -> Vec<PackageExportReport> {
1677    if ctx.manifest.exports.is_empty() {
1678        push_error(
1679            errors,
1680            "[exports]",
1681            "publishable packages require at least one stable export",
1682        );
1683        return Vec::new();
1684    }
1685
1686    let mut exports = Vec::new();
1687    for (name, rel_path) in &ctx.manifest.exports {
1688        let field = format!("[exports].{name}");
1689        if let Err(message) = validate_package_alias(name) {
1690            push_error(errors, &field, message);
1691        }
1692        let Ok(path) = safe_package_relative_path(&ctx.dir, rel_path) else {
1693            push_error(
1694                errors,
1695                &field,
1696                "export path must stay inside the package directory",
1697            );
1698            continue;
1699        };
1700        if path.extension() != Some(OsStr::new("harn")) {
1701            push_error(errors, &field, "export path must point at a .harn file");
1702            continue;
1703        }
1704        let content = match fs::read_to_string(&path) {
1705            Ok(content) => content,
1706            Err(error) => {
1707                push_error(
1708                    errors,
1709                    &field,
1710                    format!("failed to read export {}: {error}", path.display()),
1711                );
1712                continue;
1713            }
1714        };
1715        if let Err(error) = parse_harn_source(&content) {
1716            push_error(errors, &field, format!("failed to parse export: {error}"));
1717        }
1718        let symbols = extract_api_symbols(&content);
1719        if symbols.is_empty() {
1720            push_warning(
1721                warnings,
1722                &field,
1723                "exported module has no public symbols to document",
1724            );
1725        }
1726        for symbol in &symbols {
1727            if symbol.docs.is_none() {
1728                push_warning(
1729                    warnings,
1730                    &field,
1731                    format!(
1732                        "public {} '{}' has no doc comment",
1733                        symbol.kind, symbol.name
1734                    ),
1735                );
1736            }
1737        }
1738        exports.push(PackageExportReport {
1739            name: name.clone(),
1740            path: rel_path.clone(),
1741            symbols,
1742        });
1743    }
1744    exports.sort_by(|left, right| left.name.cmp(&right.name));
1745    exports
1746}
1747
1748pub(crate) fn validate_package_interface_exports(
1749    ctx: &ManifestContext,
1750    errors: &mut Vec<PackageCheckDiagnostic>,
1751    warnings: &mut Vec<PackageCheckDiagnostic>,
1752) -> (Vec<PackageToolExportReport>, Vec<PackageSkillExportReport>) {
1753    let Some(package) = ctx.manifest.package.as_ref() else {
1754        return (Vec::new(), Vec::new());
1755    };
1756
1757    validate_permission_tokens(
1758        &package.permissions,
1759        "[package].permissions",
1760        errors,
1761        warnings,
1762    );
1763    validate_host_requirements(
1764        &package.host_requirements,
1765        "[package].host_requirements",
1766        errors,
1767    );
1768
1769    let mut tools = Vec::new();
1770    for (index, tool) in package.tools.iter().enumerate() {
1771        let field = format!("[[package.tools]] #{}", index + 1);
1772        if let Err(message) = validate_package_alias(&tool.name) {
1773            push_error(errors, format!("{field}.name"), message.to_string());
1774        }
1775        validate_required_manifest_string(&tool.module, &format!("{field}.module"), errors);
1776        validate_required_manifest_string(&tool.symbol, &format!("{field}.symbol"), errors);
1777        validate_package_module_path(ctx, &tool.module, &format!("{field}.module"), errors);
1778        validate_permission_tokens(
1779            &tool.permissions,
1780            &format!("{field}.permissions"),
1781            errors,
1782            warnings,
1783        );
1784        validate_host_requirements(
1785            &tool.host_requirements,
1786            &format!("{field}.host_requirements"),
1787            errors,
1788        );
1789        validate_schema_value(
1790            tool.input_schema.as_ref(),
1791            &format!("{field}.input_schema"),
1792            errors,
1793        );
1794        validate_schema_value(
1795            tool.output_schema.as_ref(),
1796            &format!("{field}.output_schema"),
1797            errors,
1798        );
1799        validate_tool_annotations(&tool.annotations, &format!("{field}.annotations"), errors);
1800        if tool.annotations.is_empty() {
1801            push_warning(
1802                warnings,
1803                format!("{field}.annotations"),
1804                "tool export has no annotations; policy evaluation will treat it conservatively",
1805            );
1806        }
1807        tools.push(PackageToolExportReport {
1808            name: tool.name.clone(),
1809            module: tool.module.clone(),
1810            symbol: tool.symbol.clone(),
1811            permissions: merge_package_requirements(&package.permissions, &tool.permissions),
1812            host_requirements: merge_package_requirements(
1813                &package.host_requirements,
1814                &tool.host_requirements,
1815            ),
1816        });
1817    }
1818    tools.sort_by(|left, right| left.name.cmp(&right.name));
1819
1820    let mut skills = Vec::new();
1821    for (index, skill) in package.skills.iter().enumerate() {
1822        let field = format!("[[package.skills]] #{}", index + 1);
1823        if let Err(message) = validate_package_alias(&skill.name) {
1824            push_error(errors, format!("{field}.name"), message.to_string());
1825        }
1826        validate_required_manifest_string(&skill.path, &format!("{field}.path"), errors);
1827        validate_package_skill_path(ctx, &skill.path, &format!("{field}.path"), errors);
1828        validate_permission_tokens(
1829            &skill.permissions,
1830            &format!("{field}.permissions"),
1831            errors,
1832            warnings,
1833        );
1834        validate_host_requirements(
1835            &skill.host_requirements,
1836            &format!("{field}.host_requirements"),
1837            errors,
1838        );
1839        skills.push(PackageSkillExportReport {
1840            name: skill.name.clone(),
1841            path: skill.path.clone(),
1842            permissions: merge_package_requirements(&package.permissions, &skill.permissions),
1843            host_requirements: merge_package_requirements(
1844                &package.host_requirements,
1845                &skill.host_requirements,
1846            ),
1847        });
1848    }
1849    skills.sort_by(|left, right| left.name.cmp(&right.name));
1850
1851    (tools, skills)
1852}
1853
1854pub(crate) fn merge_package_requirements(base: &[String], item: &[String]) -> Vec<String> {
1855    let mut merged = BTreeSet::new();
1856    merged.extend(
1857        base.iter()
1858            .filter_map(|value| normalized_requirement(value)),
1859    );
1860    merged.extend(
1861        item.iter()
1862            .filter_map(|value| normalized_requirement(value)),
1863    );
1864    merged.into_iter().collect()
1865}
1866
1867fn normalized_requirement(value: &str) -> Option<String> {
1868    let trimmed = value.trim();
1869    (!trimmed.is_empty()).then(|| trimmed.to_string())
1870}
1871
1872fn validate_required_manifest_string(
1873    value: &str,
1874    field: &str,
1875    errors: &mut Vec<PackageCheckDiagnostic>,
1876) {
1877    if value.trim().is_empty() {
1878        push_error(errors, field, format!("missing required {field}"));
1879    }
1880}
1881
1882fn validate_permission_tokens(
1883    permissions: &[String],
1884    field: &str,
1885    errors: &mut Vec<PackageCheckDiagnostic>,
1886    warnings: &mut Vec<PackageCheckDiagnostic>,
1887) {
1888    let mut seen = BTreeSet::new();
1889    for permission in permissions {
1890        let trimmed = permission.trim();
1891        if trimmed.is_empty() {
1892            push_error(errors, field, "permission entries cannot be empty");
1893            continue;
1894        }
1895        if trimmed.chars().any(char::is_whitespace) {
1896            push_error(
1897                errors,
1898                field,
1899                format!("permission {permission:?} cannot contain whitespace"),
1900            );
1901        }
1902        if !trimmed.contains(':') && !trimmed.contains('.') {
1903            push_warning(
1904                warnings,
1905                field,
1906                format!("permission {permission:?} should use a namespaced token"),
1907            );
1908        }
1909        if !seen.insert(trimmed.to_string()) {
1910            push_warning(
1911                warnings,
1912                field,
1913                format!("duplicate permission {permission:?}"),
1914            );
1915        }
1916    }
1917}
1918
1919pub(crate) fn validate_host_requirements(
1920    requirements: &[String],
1921    field: &str,
1922    errors: &mut Vec<PackageCheckDiagnostic>,
1923) {
1924    let mut seen = BTreeSet::new();
1925    for requirement in requirements {
1926        let trimmed = requirement.trim();
1927        if trimmed.is_empty() {
1928            push_error(errors, field, "host requirement entries cannot be empty");
1929            continue;
1930        }
1931        let Some((capability, operation)) = trimmed.split_once('.') else {
1932            push_error(
1933                errors,
1934                field,
1935                format!("host requirement {requirement:?} must use capability.operation"),
1936            );
1937            continue;
1938        };
1939        if !valid_identifier(capability)
1940            || !(valid_identifier(operation) || operation == "*")
1941            || trimmed.matches('.').count() != 1
1942        {
1943            push_error(
1944                errors,
1945                field,
1946                format!("host requirement {requirement:?} must use valid capability.operation identifiers"),
1947            );
1948        }
1949        if !seen.insert(trimmed.to_string()) {
1950            push_error(
1951                errors,
1952                field,
1953                format!("duplicate host requirement {requirement:?}"),
1954            );
1955        }
1956    }
1957}
1958
1959fn validate_package_module_path(
1960    ctx: &ManifestContext,
1961    rel_path: &str,
1962    field: &str,
1963    errors: &mut Vec<PackageCheckDiagnostic>,
1964) {
1965    let Ok(path) = safe_package_relative_path(&ctx.dir, rel_path) else {
1966        push_error(errors, field, "module path must stay inside the package");
1967        return;
1968    };
1969    if path.extension() != Some(OsStr::new("harn")) {
1970        push_error(errors, field, "module path must point at a .harn file");
1971        return;
1972    }
1973    match fs::read_to_string(&path) {
1974        Ok(content) => {
1975            if let Err(error) = parse_harn_source(&content) {
1976                push_error(errors, field, format!("failed to parse module: {error}"));
1977            }
1978        }
1979        Err(error) => push_error(
1980            errors,
1981            field,
1982            format!("failed to read module {}: {error}", path.display()),
1983        ),
1984    }
1985}
1986
1987fn validate_package_skill_path(
1988    ctx: &ManifestContext,
1989    rel_path: &str,
1990    field: &str,
1991    errors: &mut Vec<PackageCheckDiagnostic>,
1992) {
1993    let Ok(path) = safe_package_relative_path(&ctx.dir, rel_path) else {
1994        push_error(errors, field, "skill path must stay inside the package");
1995        return;
1996    };
1997    let skill_file = if path.is_dir() {
1998        path.join("SKILL.md")
1999    } else {
2000        path
2001    };
2002    if skill_file.file_name() != Some(OsStr::new("SKILL.md")) {
2003        push_error(
2004            errors,
2005            field,
2006            "skill path must be a SKILL.md file or skill directory",
2007        );
2008        return;
2009    }
2010    match fs::read_to_string(&skill_file) {
2011        Ok(content) => {
2012            let (frontmatter, _) = harn_vm::skills::split_frontmatter(&content);
2013            if let Err(error) = harn_vm::skills::parse_frontmatter(frontmatter) {
2014                push_error(
2015                    errors,
2016                    field,
2017                    format!("invalid SKILL.md frontmatter: {error}"),
2018                );
2019            }
2020        }
2021        Err(error) => push_error(
2022            errors,
2023            field,
2024            format!("failed to read skill {}: {error}", skill_file.display()),
2025        ),
2026    }
2027}
2028
2029fn validate_schema_value(
2030    value: Option<&toml::Value>,
2031    field: &str,
2032    errors: &mut Vec<PackageCheckDiagnostic>,
2033) {
2034    let Some(value) = value else {
2035        return;
2036    };
2037    let json = match toml_value_to_json(value) {
2038        Ok(json) => json,
2039        Err(error) => {
2040            push_error(errors, field, error);
2041            return;
2042        }
2043    };
2044    let Some(object) = json.as_object() else {
2045        push_error(errors, field, "schema must be a table/object");
2046        return;
2047    };
2048    if let Some(schema_type) = object.get("type") {
2049        if !schema_type.is_string() {
2050            push_error(errors, field, "schema `type` must be a string when present");
2051        }
2052    }
2053    if let Some(required) = object.get("required") {
2054        let valid = required
2055            .as_array()
2056            .is_some_and(|items| items.iter().all(|item| item.as_str().is_some()));
2057        if !valid {
2058            push_error(errors, field, "schema `required` must be a list of strings");
2059        }
2060    }
2061}
2062
2063fn validate_tool_annotations(
2064    annotations: &BTreeMap<String, toml::Value>,
2065    field: &str,
2066    errors: &mut Vec<PackageCheckDiagnostic>,
2067) {
2068    if annotations.is_empty() {
2069        return;
2070    }
2071    let json = match toml_value_to_json(&toml::Value::Table(
2072        annotations
2073            .clone()
2074            .into_iter()
2075            .collect::<toml::map::Map<String, toml::Value>>(),
2076    )) {
2077        Ok(json) => json,
2078        Err(error) => {
2079            push_error(errors, field, error);
2080            return;
2081        }
2082    };
2083    if let Err(error) = serde_json::from_value::<harn_vm::tool_annotations::ToolAnnotations>(json) {
2084        push_error(
2085            errors,
2086            field,
2087            format!("annotations do not match ToolAnnotations: {error}"),
2088        );
2089    }
2090}
2091
2092fn toml_value_to_json(value: &toml::Value) -> Result<serde_json::Value, String> {
2093    serde_json::to_value(value).map_err(|error| format!("failed to normalize TOML value: {error}"))
2094}
2095
2096pub(crate) fn parse_harn_source(source: &str) -> Result<(), PackageError> {
2097    let mut lexer = harn_lexer::Lexer::new(source);
2098    let tokens = lexer.tokenize().map_err(|error| error.to_string())?;
2099    let mut parser = harn_parser::Parser::new(tokens);
2100    parser
2101        .parse()
2102        .map(|_| ())
2103        .map_err(|error| PackageError::Ops(error.to_string()))
2104}
2105
2106pub(crate) fn safe_package_relative_path(
2107    root: &Path,
2108    rel_path: &str,
2109) -> Result<PathBuf, PackageError> {
2110    let rel = PathBuf::from(rel_path);
2111    if rel.is_absolute()
2112        || has_windows_rooted_or_drive_relative_prefix(rel_path)
2113        || has_windows_separator_escape(rel_path)
2114        || rel.components().any(|component| {
2115            matches!(
2116                component,
2117                std::path::Component::ParentDir
2118                    | std::path::Component::Prefix(_)
2119                    | std::path::Component::RootDir
2120            )
2121        })
2122    {
2123        return Err(format!("path {rel_path:?} escapes package root").into());
2124    }
2125    Ok(root.join(rel))
2126}
2127
2128fn has_windows_rooted_or_drive_relative_prefix(path: &str) -> bool {
2129    let normalized = path.replace('\\', "/");
2130    let bytes = normalized.as_bytes();
2131    normalized.starts_with('/')
2132        || (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
2133}
2134
2135fn has_windows_separator_escape(path: &str) -> bool {
2136    let normalized = path.replace('\\', "/");
2137    Path::new(&normalized).components().any(|component| {
2138        matches!(
2139            component,
2140            std::path::Component::ParentDir
2141                | std::path::Component::Prefix(_)
2142                | std::path::Component::RootDir
2143        )
2144    })
2145}
2146
2147pub(crate) fn extract_api_symbols(source: &str) -> Vec<PackageApiSymbol> {
2148    static DECL_RE: OnceLock<Regex> = OnceLock::new();
2149    let decl_re = DECL_RE.get_or_init(|| {
2150        Regex::new(r"^\s*pub\s+(fn|pipeline|tool|skill|struct|enum|type|interface)\s+([A-Za-z_][A-Za-z0-9_]*)\b(.*)$")
2151            .expect("valid declaration regex")
2152    });
2153    let mut docs: Vec<String> = Vec::new();
2154    let mut symbols = Vec::new();
2155    let mut in_block_doc = false;
2156    for line in source.lines() {
2157        let trimmed = line.trim();
2158        if in_block_doc {
2159            // Collect content between /** and */, stripping the conventional
2160            // ` * ` continuation marker so docs render the same regardless of
2161            // which form (`///` or `/** */`) authors picked.
2162            let (content, closes) = match trimmed.split_once("*/") {
2163                Some((before, _)) => (before, true),
2164                None => (trimmed, false),
2165            };
2166            let stripped = content
2167                .strip_prefix("* ")
2168                .or_else(|| content.strip_prefix('*'))
2169                .unwrap_or(content)
2170                .trim();
2171            if !stripped.is_empty() {
2172                docs.push(stripped.to_string());
2173            }
2174            if closes {
2175                in_block_doc = false;
2176            }
2177            continue;
2178        }
2179        if let Some(doc) = trimmed.strip_prefix("///") {
2180            docs.push(doc.trim().to_string());
2181            continue;
2182        }
2183        if let Some(rest) = trimmed.strip_prefix("/**") {
2184            // `/** … */` on a single line collapses to one doc line; the
2185            // multi-line opener `/**` (with no `*/` on the same line) flips
2186            // the block-doc flag so subsequent lines are absorbed above.
2187            if let Some((inner, _)) = rest.split_once("*/") {
2188                let stripped = inner.trim();
2189                if !stripped.is_empty() {
2190                    docs.push(stripped.to_string());
2191                }
2192            } else {
2193                let stripped = rest.trim();
2194                if !stripped.is_empty() {
2195                    docs.push(stripped.to_string());
2196                }
2197                in_block_doc = true;
2198            }
2199            continue;
2200        }
2201        if trimmed.is_empty() {
2202            continue;
2203        }
2204        if let Some(captures) = decl_re.captures(line) {
2205            let kind = captures.get(1).expect("kind").as_str().to_string();
2206            let name = captures.get(2).expect("name").as_str().to_string();
2207            let signature = trim_signature(line);
2208            let doc_text = (!docs.is_empty()).then(|| docs.join("\n"));
2209            symbols.push(PackageApiSymbol {
2210                kind,
2211                name,
2212                signature,
2213                docs: doc_text,
2214            });
2215        }
2216        docs.clear();
2217    }
2218    symbols
2219}
2220
2221pub(crate) fn trim_signature(line: &str) -> String {
2222    let mut signature = line.trim().to_string();
2223    if let Some((before, _)) = signature.split_once('{') {
2224        signature = before.trim_end().to_string();
2225    }
2226    signature
2227}
2228
2229pub(crate) fn supports_current_harn(range: &str) -> bool {
2230    let current = env!("CARGO_PKG_VERSION");
2231    let Some((major, minor)) = parse_major_minor(current) else {
2232        return true;
2233    };
2234    let range = range.trim();
2235    if range.is_empty() {
2236        return false;
2237    }
2238    if let Some(rest) = range.strip_prefix('^') {
2239        return parse_major_minor(rest).is_some_and(|(m, n)| m == major && n == minor);
2240    }
2241    if !range.contains([',', '<', '>', '=']) {
2242        return parse_major_minor(range).is_some_and(|(m, n)| m == major && n == minor);
2243    }
2244
2245    let current_value = major * 1000 + minor;
2246    let mut lower_ok = true;
2247    let mut upper_ok = true;
2248    let mut saw_constraint = false;
2249    for raw in range.split(',') {
2250        let part = raw.trim();
2251        if part.is_empty() {
2252            continue;
2253        }
2254        saw_constraint = true;
2255        if let Some(rest) = part.strip_prefix(">=") {
2256            if let Some((m, n)) = parse_major_minor(rest.trim()) {
2257                lower_ok &= current_value >= m * 1000 + n;
2258            } else {
2259                return false;
2260            }
2261        } else if let Some(rest) = part.strip_prefix('>') {
2262            if let Some((m, n)) = parse_major_minor(rest.trim()) {
2263                lower_ok &= current_value > m * 1000 + n;
2264            } else {
2265                return false;
2266            }
2267        } else if let Some(rest) = part.strip_prefix("<=") {
2268            if let Some((m, n)) = parse_major_minor(rest.trim()) {
2269                upper_ok &= current_value <= m * 1000 + n;
2270            } else {
2271                return false;
2272            }
2273        } else if let Some(rest) = part.strip_prefix('<') {
2274            if let Some((m, n)) = parse_major_minor(rest.trim()) {
2275                upper_ok &= current_value < m * 1000 + n;
2276            } else {
2277                return false;
2278            }
2279        } else if let Some(rest) = part.strip_prefix('=') {
2280            if let Some((m, n)) = parse_major_minor(rest.trim()) {
2281                lower_ok &= current_value == m * 1000 + n;
2282                upper_ok &= current_value == m * 1000 + n;
2283            } else {
2284                return false;
2285            }
2286        } else {
2287            return false;
2288        }
2289    }
2290    saw_constraint && lower_ok && upper_ok
2291}
2292
2293pub(crate) fn current_harn_range_example() -> String {
2294    let current = env!("CARGO_PKG_VERSION");
2295    let Some((major, minor)) = parse_major_minor(current) else {
2296        return ">=0.7,<0.8".to_string();
2297    };
2298    format!(">={major}.{minor},<{major}.{}", minor + 1)
2299}
2300
2301pub(crate) fn current_harn_line_label() -> String {
2302    let current = env!("CARGO_PKG_VERSION");
2303    let Some((major, minor)) = parse_major_minor(current) else {
2304        return "0.7".to_string();
2305    };
2306    format!("{major}.{minor}")
2307}
2308
2309pub(crate) fn parse_major_minor(raw: &str) -> Option<(u64, u64)> {
2310    let raw = raw.trim().trim_start_matches('v');
2311    let mut parts = raw.split('.');
2312    let major = parts.next()?.parse().ok()?;
2313    let minor = parts.next()?.trim_end_matches('x').parse().ok()?;
2314    Some((major, minor))
2315}
2316
2317pub(crate) fn collect_package_files(root: &Path) -> Result<Vec<String>, PackageError> {
2318    let mut files = Vec::new();
2319    collect_package_files_inner(root, root, &mut files)?;
2320    files.sort();
2321    Ok(files)
2322}
2323
2324pub(crate) fn collect_package_files_inner(
2325    root: &Path,
2326    dir: &Path,
2327    out: &mut Vec<String>,
2328) -> Result<(), PackageError> {
2329    for entry in
2330        fs::read_dir(dir).map_err(|error| format!("failed to read {}: {error}", dir.display()))?
2331    {
2332        let entry =
2333            entry.map_err(|error| format!("failed to read {} entry: {error}", dir.display()))?;
2334        let path = entry.path();
2335        let file_type = entry
2336            .file_type()
2337            .map_err(|error| format!("failed to inspect {}: {error}", path.display()))?;
2338        if file_type.is_symlink() {
2339            continue;
2340        }
2341        if file_type.is_dir() {
2342            let rel = path
2343                .strip_prefix(root)
2344                .map_err(|error| format!("failed to relativize {}: {error}", path.display()))?;
2345            if should_skip_package_dir(rel) {
2346                continue;
2347            }
2348            collect_package_files_inner(root, &path, out)?;
2349        } else if file_type.is_file() {
2350            let rel = path
2351                .strip_prefix(root)
2352                .map_err(|error| format!("failed to relativize {}: {error}", path.display()))?
2353                .to_string_lossy()
2354                .replace('\\', "/");
2355            out.push(rel);
2356        }
2357    }
2358    Ok(())
2359}
2360
2361pub(crate) fn should_skip_package_dir(rel: &Path) -> bool {
2362    if rel == Path::new("docs").join("dist") {
2363        return true;
2364    }
2365    rel.components().any(|component| {
2366        matches!(
2367            component.as_os_str().to_str(),
2368            Some(".git" | ".harn" | "target" | "node_modules")
2369        )
2370    })
2371}
2372
2373pub(crate) fn default_artifact_dir(ctx: &ManifestContext, report: &PackageCheckReport) -> PathBuf {
2374    let name = report.name.as_deref().unwrap_or("package");
2375    let version = report.version.as_deref().unwrap_or("0.0.0");
2376    ctx.dir
2377        .join(".harn")
2378        .join("dist")
2379        .join(format!("{name}-{version}"))
2380}
2381
2382pub(crate) fn fail_if_package_errors(report: &PackageCheckReport) -> Result<(), PackageError> {
2383    if report.errors.is_empty() {
2384        return Ok(());
2385    }
2386    Err(format!(
2387        "package check failed:\n{}",
2388        report
2389            .errors
2390            .iter()
2391            .map(|diagnostic| format!("- {}: {}", diagnostic.field, diagnostic.message))
2392            .collect::<Vec<_>>()
2393            .join("\n")
2394    )
2395    .into())
2396}
2397
2398pub(crate) fn render_package_api_docs(report: &PackageCheckReport) -> String {
2399    let title = report.name.as_deref().unwrap_or("package");
2400    let mut out = format!("# API Reference: {title}\n\nGenerated by `harn package docs`.\n");
2401    if let Some(version) = report.version.as_deref() {
2402        out.push_str(&format!("\nVersion: `{version}`\n"));
2403    }
2404    for export in &report.exports {
2405        out.push_str(&format!(
2406            "\n## Export `{}`\n\n`{}`\n",
2407            export.name, export.path
2408        ));
2409        for symbol in &export.symbols {
2410            out.push_str(&format!("\n### {} `{}`\n\n", symbol.kind, symbol.name));
2411            if let Some(docs) = symbol.docs.as_deref() {
2412                out.push_str(docs);
2413                out.push_str("\n\n");
2414            }
2415            out.push_str("```harn\n");
2416            out.push_str(&symbol.signature);
2417            out.push_str("\n```\n");
2418        }
2419    }
2420    if !report.tools.is_empty() {
2421        out.push_str("\n## Tool Exports\n");
2422        for tool in &report.tools {
2423            out.push_str(&format!(
2424                "\n### `{}`\n\n- module: `{}`\n- symbol: `{}`\n",
2425                tool.name, tool.module, tool.symbol
2426            ));
2427            if !tool.permissions.is_empty() {
2428                out.push_str(&format!(
2429                    "- permissions: `{}`\n",
2430                    tool.permissions.join("`, `")
2431                ));
2432            }
2433            if !tool.host_requirements.is_empty() {
2434                out.push_str(&format!(
2435                    "- host requirements: `{}`\n",
2436                    tool.host_requirements.join("`, `")
2437                ));
2438            }
2439        }
2440    }
2441    if !report.skills.is_empty() {
2442        out.push_str("\n## Skill Exports\n");
2443        for skill in &report.skills {
2444            out.push_str(&format!("\n### `{}`\n\n`{}`\n", skill.name, skill.path));
2445        }
2446    }
2447    out
2448}
2449
2450pub(crate) fn normalize_newlines(input: &str) -> String {
2451    input.replace("\r\n", "\n")
2452}
2453
2454pub(crate) fn print_package_check_report(report: &PackageCheckReport) {
2455    println!(
2456        "Package {} {}",
2457        report.name.as_deref().unwrap_or("<unnamed>"),
2458        report.version.as_deref().unwrap_or("<unversioned>")
2459    );
2460    println!("manifest: {}", report.manifest_path);
2461    for export in &report.exports {
2462        println!(
2463            "export {} -> {} ({} public symbol(s))",
2464            export.name,
2465            export.path,
2466            export.symbols.len()
2467        );
2468    }
2469    for tool in &report.tools {
2470        println!("tool {} -> {}::{}", tool.name, tool.module, tool.symbol);
2471    }
2472    for skill in &report.skills {
2473        println!("skill {} -> {}", skill.name, skill.path);
2474    }
2475    if !report.warnings.is_empty() {
2476        println!("\nwarnings:");
2477        for warning in &report.warnings {
2478            println!("- {}: {}", warning.field, warning.message);
2479        }
2480    }
2481    if !report.errors.is_empty() {
2482        println!("\nerrors:");
2483        for error in &report.errors {
2484            println!("- {}: {}", error.field, error.message);
2485        }
2486    } else {
2487        println!("\npackage check passed");
2488    }
2489}
2490
2491pub(crate) fn print_package_pack_report(report: &PackagePackReport) {
2492    if report.dry_run {
2493        println!("Package pack dry run succeeded.");
2494    } else {
2495        println!("Packed package artifact.");
2496    }
2497    println!("artifact: {}", report.artifact_dir);
2498    println!("files:");
2499    for file in &report.files {
2500        println!("- {file}");
2501    }
2502}
2503
2504pub(crate) fn print_package_list_report(report: &PackageListReport) {
2505    println!("manifest: {}", report.manifest_path);
2506    println!("lock: {}", report.lock_path);
2507    if !report.lock_present {
2508        println!("lock status: missing");
2509        if report.dependency_count > 0 {
2510            println!(
2511                "run `harn install` to resolve {} dependency(s)",
2512                report.dependency_count
2513            );
2514        }
2515        return;
2516    }
2517    if report.packages.is_empty() {
2518        println!("No packages installed.");
2519        return;
2520    }
2521    println!("Packages ({}):", report.packages.len());
2522    for entry in &report.packages {
2523        let version = entry.package_version.as_deref().unwrap_or("unversioned");
2524        let status = if entry.materialized {
2525            "installed"
2526        } else {
2527            "missing"
2528        };
2529        println!(
2530            "  {}  {}  {}  integrity={}",
2531            entry.name, version, status, entry.integrity
2532        );
2533        if !entry.exports.modules.is_empty() {
2534            let modules: Vec<&str> = entry
2535                .exports
2536                .modules
2537                .iter()
2538                .map(|export| export.name.as_str())
2539                .collect();
2540            println!("    modules: {}", modules.join(", "));
2541        }
2542        if !entry.exports.tools.is_empty() {
2543            let tools: Vec<&str> = entry
2544                .exports
2545                .tools
2546                .iter()
2547                .map(|export| export.name.as_str())
2548                .collect();
2549            println!("    tools: {}", tools.join(", "));
2550        }
2551        if !entry.exports.skills.is_empty() {
2552            let skills: Vec<&str> = entry
2553                .exports
2554                .skills
2555                .iter()
2556                .map(|export| export.name.as_str())
2557                .collect();
2558            println!("    skills: {}", skills.join(", "));
2559        }
2560        if !entry.permissions.is_empty() {
2561            println!("    permissions: {}", entry.permissions.join(", "));
2562        }
2563        if !entry.host_requirements.is_empty() {
2564            println!(
2565                "    host requirements: {}",
2566                entry.host_requirements.join(", ")
2567            );
2568        }
2569    }
2570}
2571
2572pub(crate) fn print_package_doctor_report(report: &PackageDoctorReport) {
2573    println!("Package doctor");
2574    println!("manifest: {}", report.manifest_path);
2575    println!("lock: {}", report.lock_path);
2576    if report.diagnostics.is_empty() {
2577        println!("ok: no package issues found");
2578        return;
2579    }
2580    for diagnostic in &report.diagnostics {
2581        println!(
2582            "{} [{}] {}",
2583            diagnostic.severity, diagnostic.code, diagnostic.message
2584        );
2585        if let Some(help) = diagnostic.help.as_deref() {
2586            println!("  help: {help}");
2587        }
2588    }
2589}
2590
2591#[cfg(test)]
2592mod tests {
2593    use super::*;
2594    use crate::package::test_support::*;
2595
2596    #[test]
2597    fn package_check_accepts_publishable_package() {
2598        let tmp = tempfile::tempdir().unwrap();
2599        write_publishable_package(tmp.path());
2600
2601        let report = check_package_impl(Some(tmp.path())).unwrap();
2602
2603        assert!(report.errors.is_empty(), "{:?}", report.errors);
2604        assert_eq!(report.name.as_deref(), Some("acme-lib"));
2605        assert_eq!(report.exports[0].symbols[0].name, "greet");
2606    }
2607
2608    #[test]
2609    fn package_check_rejects_path_dependencies_and_bad_harn_range() {
2610        let tmp = tempfile::tempdir().unwrap();
2611        write_publishable_package(tmp.path());
2612        fs::write(
2613            tmp.path().join(MANIFEST),
2614            r#"[package]
2615    name = "acme-lib"
2616    version = "0.1.0"
2617    description = "Acme helpers"
2618    license = "MIT"
2619    repository = "https://github.com/acme/acme-lib"
2620    harn = ">=999.0,<999.1"
2621    docs_url = "docs/api.md"
2622
2623    [exports]
2624    lib = "lib/main.harn"
2625
2626    [dependencies]
2627    local = { path = "../local" }
2628    "#,
2629        )
2630        .unwrap();
2631
2632        let report = check_package_impl(Some(tmp.path())).unwrap();
2633        let messages = report
2634            .errors
2635            .iter()
2636            .map(|diagnostic| diagnostic.message.as_str())
2637            .collect::<Vec<_>>()
2638            .join("\n");
2639
2640        assert!(messages.contains("unsupported Harn version range"));
2641        assert!(messages.contains("path dependencies are not publishable"));
2642    }
2643
2644    #[test]
2645    fn package_check_warns_on_branch_dependency() {
2646        let tmp = tempfile::tempdir().unwrap();
2647        write_publishable_package(tmp.path());
2648        fs::write(
2649            tmp.path().join(MANIFEST),
2650            format!(
2651                r#"[package]
2652name = "acme-lib"
2653version = "0.1.0"
2654description = "Acme helpers"
2655license = "MIT"
2656repository = "https://github.com/acme/acme-lib"
2657harn = "{}"
2658docs_url = "docs/api.md"
2659
2660[exports]
2661lib = "lib/main.harn"
2662
2663[dependencies]
2664remote = {{ git = "https://github.com/acme/remote-lib", branch = "main" }}
2665"#,
2666                current_harn_range_example()
2667            ),
2668        )
2669        .unwrap();
2670
2671        let report = check_package_impl(Some(tmp.path())).unwrap();
2672        let warnings = report
2673            .warnings
2674            .iter()
2675            .map(|diagnostic| diagnostic.message.as_str())
2676            .collect::<Vec<_>>()
2677            .join("\n");
2678
2679        assert!(report.errors.is_empty(), "{:?}", report.errors);
2680        assert!(warnings.contains("branch dependencies are non-reproducible"));
2681    }
2682
2683    #[test]
2684    fn extract_api_symbols_recognizes_block_doc_comments() {
2685        // `/** … */` (the canonical HarnDoc form preferred by the linter)
2686        // and `///` lines must produce the same `docs` body so package
2687        // check, package docs, and the missing-doc warning agree on what
2688        // counts as documented.
2689        let single = extract_api_symbols("/** Block doc. */\npub fn one() {}\n");
2690        assert_eq!(single.len(), 1);
2691        assert_eq!(single[0].docs.as_deref(), Some("Block doc."));
2692
2693        let multi =
2694            extract_api_symbols("/**\n * First line.\n * Second line.\n */\npub fn two() {}\n");
2695        assert_eq!(multi.len(), 1);
2696        assert_eq!(multi[0].docs.as_deref(), Some("First line.\nSecond line."));
2697
2698        let triple = extract_api_symbols("/// Slash doc.\npub fn three() {}\n");
2699        assert_eq!(triple.len(), 1);
2700        assert_eq!(triple[0].docs.as_deref(), Some("Slash doc."));
2701
2702        // A non-doc, non-empty intermediate line clears the pending
2703        // doc buffer so an unrelated comment three lines up does not
2704        // accidentally bind to the declaration.
2705        let detached = extract_api_symbols("/** Detached. */\nlet x = 1\npub fn four() {}\n");
2706        assert_eq!(detached.len(), 1);
2707        assert!(detached[0].docs.is_none());
2708    }
2709
2710    #[test]
2711    fn package_docs_and_pack_use_exports() {
2712        let tmp = tempfile::tempdir().unwrap();
2713        write_publishable_package(tmp.path());
2714
2715        let docs_path = generate_package_docs_impl(Some(tmp.path()), None, false).unwrap();
2716        let docs = fs::read_to_string(docs_path).unwrap();
2717        assert!(docs.contains("### fn `greet`"));
2718        assert!(docs.contains("Return a greeting."));
2719
2720        let pack = pack_package_impl(Some(tmp.path()), None, true).unwrap();
2721        assert!(pack.files.contains(&"harn.toml".to_string()));
2722        assert!(pack.files.contains(&"lib/main.harn".to_string()));
2723    }
2724
2725    #[test]
2726    fn package_pack_skips_generated_docs_dist() {
2727        let tmp = tempfile::tempdir().unwrap();
2728        write_publishable_package(tmp.path());
2729        fs::create_dir_all(tmp.path().join("docs/dist")).unwrap();
2730        fs::write(tmp.path().join("docs/dist/index.html"), "<html></html>\n").unwrap();
2731
2732        let pack = pack_package_impl(Some(tmp.path()), None, true).unwrap();
2733
2734        assert!(
2735            !pack.files.iter().any(|path| path.starts_with("docs/dist/")),
2736            "{:?}",
2737            pack.files
2738        );
2739    }
2740
2741    #[test]
2742    fn publish_dry_run_builds_tag_command_and_index_diff() {
2743        let tmp = tempfile::tempdir().unwrap();
2744        write_publishable_package(tmp.path());
2745        write_release_changelog(tmp.path(), "0.1.0");
2746        let _remote = init_publishable_repo(tmp.path());
2747        let index = r#"version = 1
2748
2749[[package]]
2750name = "acme-lib"
2751repository = "https://github.com/acme/acme-lib"
2752
2753[[package.version]]
2754version = "0.0.1"
2755git = "https://github.com/acme/acme-lib"
2756rev = "deadbeef"
2757
2758[[package]]
2759name = "other-lib"
2760repository = "https://github.com/acme/other-lib"
2761
2762[[package.version]]
2763version = "1.0.0"
2764git = "https://github.com/acme/other-lib"
2765rev = "feedface"
2766"#;
2767        let index_path = Path::new("package-index/harn-package-index.toml");
2768        let options = PackagePublishOptions {
2769            dry_run: true,
2770            remote: "origin",
2771            index_repo: "burin-labs/harn-cloud",
2772            index_path,
2773            registry_name: None,
2774            skip_index_pr: false,
2775            registry: None,
2776        };
2777
2778        let plan =
2779            prepare_publish_plan(Some(tmp.path()), &options, index.to_string(), "fixture").unwrap();
2780
2781        assert!(plan.tag_command.contains("git -C"));
2782        assert!(plan.tag_command.contains("tag v0.1.0"));
2783        assert!(plan.index_diff.contains("+version = \"0.1.0\""));
2784        assert!(plan.index_diff.contains("+tag = \"v0.1.0\""));
2785        assert!(plan
2786            .index_diff
2787            .contains(&format!("+rev = \"{}\"", plan.sha)));
2788        assert!(plan
2789            .index_diff
2790            .contains(&format!("+sha = \"{}\"", plan.sha)));
2791        let acme_pos = plan
2792            .updated_index_content
2793            .find("name = \"acme-lib\"")
2794            .unwrap();
2795        let other_pos = plan
2796            .updated_index_content
2797            .find("name = \"other-lib\"")
2798            .unwrap();
2799        let new_version_pos = plan
2800            .updated_index_content
2801            .find("version = \"0.1.0\"")
2802            .unwrap();
2803        assert!(acme_pos < new_version_pos && new_version_pos < other_pos);
2804    }
2805
2806    #[test]
2807    fn publish_preflight_rejects_existing_tag_and_missing_changelog_entry() {
2808        let tmp = tempfile::tempdir().unwrap();
2809        write_publishable_package(tmp.path());
2810        let _remote = init_publishable_repo(tmp.path());
2811        let index_path = Path::new("package-index/harn-package-index.toml");
2812        let options = PackagePublishOptions {
2813            dry_run: true,
2814            remote: "origin",
2815            index_repo: "burin-labs/harn-cloud",
2816            index_path,
2817            registry_name: None,
2818            skip_index_pr: false,
2819            registry: None,
2820        };
2821
2822        let missing_changelog = prepare_publish_plan(
2823            Some(tmp.path()),
2824            &options,
2825            "version = 1\n".to_string(),
2826            "fixture",
2827        )
2828        .unwrap_err()
2829        .to_string();
2830        assert!(missing_changelog.contains("CHANGELOG.md"));
2831
2832        write_release_changelog(tmp.path(), "0.1.0");
2833        run_git(tmp.path(), &["add", "CHANGELOG.md"]);
2834        run_git(tmp.path(), &["commit", "-m", "add changelog"]);
2835        run_git(tmp.path(), &["tag", "v0.1.0"]);
2836
2837        let existing_tag = prepare_publish_plan(
2838            Some(tmp.path()),
2839            &options,
2840            "version = 1\n".to_string(),
2841            "fixture",
2842        )
2843        .unwrap_err()
2844        .to_string();
2845        assert!(existing_tag.contains("already exists locally"));
2846    }
2847
2848    #[test]
2849    fn publish_preflight_rejects_dirty_worktree() {
2850        let tmp = tempfile::tempdir().unwrap();
2851        write_publishable_package(tmp.path());
2852        write_release_changelog(tmp.path(), "0.1.0");
2853        let _remote = init_publishable_repo(tmp.path());
2854        fs::write(tmp.path().join("scratch.txt"), "dirty\n").unwrap();
2855        let index_path = Path::new("package-index/harn-package-index.toml");
2856        let options = PackagePublishOptions {
2857            dry_run: true,
2858            remote: "origin",
2859            index_repo: "burin-labs/harn-cloud",
2860            index_path,
2861            registry_name: None,
2862            skip_index_pr: false,
2863            registry: None,
2864        };
2865
2866        let error = prepare_publish_plan(
2867            Some(tmp.path()),
2868            &options,
2869            "version = 1\n".to_string(),
2870            "fixture",
2871        )
2872        .unwrap_err()
2873        .to_string();
2874
2875        assert!(error.contains("working tree must be clean"));
2876        assert!(error.contains("scratch.txt"));
2877    }
2878
2879    #[cfg(unix)]
2880    #[test]
2881    fn package_pack_does_not_follow_symlinked_files() {
2882        let tmp = tempfile::tempdir().unwrap();
2883        write_publishable_package(tmp.path());
2884        let outside = tempfile::NamedTempFile::new().unwrap();
2885        fs::write(outside.path(), "secret\n").unwrap();
2886        std::os::unix::fs::symlink(outside.path(), tmp.path().join("secret.txt")).unwrap();
2887
2888        let pack = pack_package_impl(Some(tmp.path()), None, true).unwrap();
2889
2890        assert!(
2891            !pack.files.contains(&"secret.txt".to_string()),
2892            "{:?}",
2893            pack.files
2894        );
2895    }
2896
2897    #[test]
2898    fn package_relative_paths_reject_windows_rooted_forms() {
2899        let tmp = tempfile::tempdir().unwrap();
2900        for rel_path in [
2901            "/repo/secret.harn",
2902            r"\repo\secret.harn",
2903            r"C:\repo\secret.harn",
2904            "C:secret.harn",
2905            r"\\server\share\secret.harn",
2906            r"..\secret.harn",
2907            r"lib\..\secret.harn",
2908            r"lib/..\secret.harn",
2909        ] {
2910            assert!(
2911                safe_package_relative_path(tmp.path(), rel_path).is_err(),
2912                "{rel_path:?} must not be accepted as package-relative"
2913            );
2914        }
2915    }
2916
2917    #[test]
2918    fn package_check_validates_tool_and_skill_exports() {
2919        let tmp = tempfile::tempdir().unwrap();
2920        write_publishable_package(tmp.path());
2921        fs::create_dir_all(tmp.path().join("skills/review")).unwrap();
2922        fs::write(
2923            tmp.path().join("harn.toml"),
2924            format!(
2925                r#"[package]
2926name = "acme-lib"
2927version = "0.1.0"
2928description = "Acme helpers"
2929license = "MIT"
2930repository = "https://github.com/acme/acme-lib"
2931harn = "{}"
2932docs_url = "docs/api.md"
2933permissions = ["tool:read_only"]
2934host_requirements = ["workspace.read_text"]
2935
2936[exports]
2937lib = "lib/main.harn"
2938
2939[[package.tools]]
2940name = "read-note"
2941module = "lib/main.harn"
2942symbol = "tools"
2943permissions = ["tool:read_only"]
2944
2945[package.tools.input_schema]
2946type = "object"
2947required = ["path"]
2948
2949[package.tools.annotations]
2950kind = "read"
2951side_effect_level = "read_only"
2952
2953[package.tools.annotations.arg_schema]
2954required = ["path"]
2955
2956[[package.skills]]
2957name = "review"
2958path = "skills/review"
2959permissions = ["skill:prompt"]
2960
2961[dependencies]
2962"#,
2963                current_harn_range_example()
2964            ),
2965        )
2966        .unwrap();
2967        fs::write(
2968            tmp.path().join("skills/review/SKILL.md"),
2969            "---\nname: review\nshort: Review changes\n---\n# Review\n",
2970        )
2971        .unwrap();
2972
2973        let report = check_package_impl(Some(tmp.path())).unwrap();
2974
2975        assert!(report.errors.is_empty(), "{:?}", report.errors);
2976        assert_eq!(report.tools[0].name, "read-note");
2977        assert_eq!(
2978            report.tools[0].host_requirements,
2979            vec!["workspace.read_text"]
2980        );
2981        assert_eq!(report.skills[0].name, "review");
2982    }
2983
2984    #[test]
2985    fn package_check_rejects_invalid_tool_schema_and_host_requirement() {
2986        let tmp = tempfile::tempdir().unwrap();
2987        write_publishable_package(tmp.path());
2988        fs::write(
2989            tmp.path().join(MANIFEST),
2990            format!(
2991                r#"[package]
2992name = "acme-lib"
2993version = "0.1.0"
2994description = "Acme helpers"
2995license = "MIT"
2996repository = "https://github.com/acme/acme-lib"
2997harn = "{}"
2998docs_url = "docs/api.md"
2999
3000[exports]
3001lib = "lib/main.harn"
3002
3003[[package.tools]]
3004name = "broken"
3005module = "lib/main.harn"
3006symbol = "tools"
3007host_requirements = ["workspace"]
3008
3009[package.tools.input_schema]
3010required = [1]
3011
3012[dependencies]
3013"#,
3014                current_harn_range_example()
3015            ),
3016        )
3017        .unwrap();
3018
3019        let report = check_package_impl(Some(tmp.path())).unwrap();
3020        let messages = report
3021            .errors
3022            .iter()
3023            .map(|diagnostic| diagnostic.message.as_str())
3024            .collect::<Vec<_>>()
3025            .join("\n");
3026
3027        assert!(messages.contains("capability.operation"));
3028        assert!(messages.contains("schema `required` must be a list of strings"));
3029    }
3030
3031    #[test]
3032    fn package_doctor_accepts_application_manifests_with_tool_exports() {
3033        let tmp = tempfile::tempdir().unwrap();
3034        fs::write(
3035            tmp.path().join(MANIFEST),
3036            r#"[package]
3037name = "acme-app"
3038
3039[[package.tools]]
3040name = "echo"
3041module = "tools.harn"
3042symbol = "tools"
3043
3044[package.tools.input_schema]
3045type = "object"
3046
3047[package.tools.annotations]
3048kind = "read"
3049side_effect_level = "read_only"
3050"#,
3051        )
3052        .unwrap();
3053        fs::write(tmp.path().join("tools.harn"), "pub fn tools() {}\n").unwrap();
3054        let workspace = TestWorkspace::new(tmp.path());
3055
3056        let report = doctor_packages_in(workspace.env()).unwrap();
3057
3058        assert!(report.ok, "{:?}", report.diagnostics);
3059        assert!(
3060            report
3061                .diagnostics
3062                .iter()
3063                .all(|diagnostic| diagnostic.code != "root-package-check"),
3064            "{:?}",
3065            report.diagnostics
3066        );
3067    }
3068
3069    #[test]
3070    fn package_list_reports_locked_tool_and_skill_exports() {
3071        let tmp = tempfile::tempdir().unwrap();
3072        fs::write(
3073            tmp.path().join(MANIFEST),
3074            r#"[package]
3075name = "consumer"
3076"#,
3077        )
3078        .unwrap();
3079        let lock = LockFile {
3080            packages: vec![LockEntry {
3081                name: "acme-tools".to_string(),
3082                source: "path+../acme-tools".to_string(),
3083                package_version: Some("0.1.0".to_string()),
3084                provenance: Some(
3085                    "https://github.com/acme/acme-tools/releases/tag/v0.1.0".to_string(),
3086                ),
3087                exports: PackageLockExports {
3088                    modules: vec![PackageLockExport {
3089                        name: "tools".to_string(),
3090                        path: Some("lib/tools.harn".to_string()),
3091                        symbol: None,
3092                    }],
3093                    tools: vec![PackageLockExport {
3094                        name: "echo".to_string(),
3095                        path: Some("lib/tools.harn".to_string()),
3096                        symbol: Some("tools".to_string()),
3097                    }],
3098                    skills: vec![PackageLockExport {
3099                        name: "review".to_string(),
3100                        path: Some("skills/review".to_string()),
3101                        symbol: None,
3102                    }],
3103                    personas: Vec::new(),
3104                },
3105                permissions: vec!["tool:read_only".to_string()],
3106                host_requirements: vec!["workspace.read_text".to_string()],
3107                ..LockEntry::default()
3108            }],
3109            ..LockFile::default()
3110        };
3111        let lock_body = toml::to_string_pretty(&lock).unwrap();
3112        fs::write(tmp.path().join(LOCK_FILE), lock_body).unwrap();
3113        let workspace = TestWorkspace::new(tmp.path());
3114
3115        let report = list_packages_in(workspace.env()).unwrap();
3116
3117        assert_eq!(report.packages.len(), 1);
3118        let package = &report.packages[0];
3119        assert_eq!(package.name, "acme-tools");
3120        assert_eq!(
3121            package.provenance.as_deref(),
3122            Some("https://github.com/acme/acme-tools/releases/tag/v0.1.0")
3123        );
3124        assert_eq!(package.exports.tools[0].name, "echo");
3125        assert_eq!(package.exports.skills[0].name, "review");
3126        assert_eq!(package.permissions, vec!["tool:read_only"]);
3127        assert_eq!(package.host_requirements, vec!["workspace.read_text"]);
3128    }
3129
3130    fn write_release_changelog(root: &Path, version: &str) {
3131        fs::write(
3132            root.join("CHANGELOG.md"),
3133            format!("# Changelog\n\n## {version}\n\n- Initial release.\n"),
3134        )
3135        .unwrap();
3136    }
3137
3138    fn init_publishable_repo(root: &Path) -> tempfile::TempDir {
3139        let init = test_git_command(root)
3140            .args(["init", "-b", "main"])
3141            .output()
3142            .unwrap();
3143        if !init.status.success() {
3144            run_git(root, &["init"]);
3145        }
3146        run_git(root, &["config", "user.email", "tests@example.com"]);
3147        run_git(root, &["config", "user.name", "Harn Tests"]);
3148        run_git(root, &["config", "core.hooksPath", "/dev/null"]);
3149        run_git(root, &["add", "."]);
3150        run_git(root, &["commit", "-m", "initial"]);
3151
3152        let remote = tempfile::tempdir().unwrap();
3153        let bare = remote.path().join("origin.git");
3154        let output = test_git_command(root)
3155            .args(["init", "--bare", bare.to_string_lossy().as_ref()])
3156            .output()
3157            .unwrap();
3158        assert!(
3159            output.status.success(),
3160            "git init --bare failed: {}",
3161            String::from_utf8_lossy(&output.stderr)
3162        );
3163        run_git(
3164            root,
3165            &["remote", "add", "origin", bare.to_string_lossy().as_ref()],
3166        );
3167        remote
3168    }
3169}