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, ®istry)?;
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(®istry_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 ®istry_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 toml_string_literal(value: &str) -> Result<String, PackageError> {
1384 let mut out = String::with_capacity(value.len() + 2);
1385 out.push('"');
1386 for ch in value.chars() {
1387 match ch {
1388 '"' => out.push_str("\\\""),
1389 '\\' => out.push_str("\\\\"),
1390 '\n' => out.push_str("\\n"),
1391 '\r' => out.push_str("\\r"),
1392 '\t' => out.push_str("\\t"),
1393 ch if ch.is_control() => {
1394 out.push_str(&format!("\\u{:04X}", ch as u32));
1395 }
1396 ch => out.push(ch),
1397 }
1398 }
1399 out.push('"');
1400 Ok(out)
1401}
1402
1403fn render_unified_diff(old: &str, new: &str, label: &str) -> Result<String, PackageError> {
1404 let temp = tempfile::tempdir()
1405 .map_err(|error| PackageError::Ops(format!("failed to create temp dir: {error}")))?;
1406 let old_path = temp.path().join("old");
1407 let new_path = temp.path().join("new");
1408 fs::write(&old_path, old).map_err(|error| format!("failed to write diff input: {error}"))?;
1409 fs::write(&new_path, new).map_err(|error| format!("failed to write diff input: {error}"))?;
1410 let output = process::Command::new("git")
1411 .args(["diff", "--no-index", "--"])
1412 .arg(&old_path)
1413 .arg(&new_path)
1414 .output()
1415 .map_err(|error| {
1416 PackageError::Ops(format!("failed to render package-index diff: {error}"))
1417 })?;
1418 if !output.status.success() && output.status.code() != Some(1) {
1419 return Err(PackageError::Ops(format!(
1420 "failed to render package-index diff: {}",
1421 String::from_utf8_lossy(&output.stderr)
1422 )));
1423 }
1424 let mut diff = String::from_utf8_lossy(&output.stdout).into_owned();
1425 let old_display = old_path.display().to_string();
1426 let new_display = new_path.display().to_string();
1427 diff = diff.replace(&format!("--- {old_display}"), &format!("--- a/{label}"));
1428 diff = diff.replace(&format!("+++ {new_display}"), &format!("+++ b/{label}"));
1429 Ok(diff)
1430}
1431
1432fn git_output<const N: usize>(repo: &Path, args: [&str; N]) -> Result<String, PackageError> {
1433 run_command_output(repo, "git", args)
1434}
1435
1436fn git_status<const N: usize>(
1437 repo: &Path,
1438 args: [&str; N],
1439) -> Result<process::ExitStatus, PackageError> {
1440 process::Command::new("git")
1441 .current_dir(repo)
1442 .args(args)
1443 .env_remove("GIT_DIR")
1444 .env_remove("GIT_WORK_TREE")
1445 .env_remove("GIT_INDEX_FILE")
1446 .output()
1447 .map(|output| output.status)
1448 .map_err(|error| PackageError::Ops(format!("failed to run git: {error}")))
1449}
1450
1451fn run_git_checked<const N: usize>(repo: &Path, args: [&str; N]) -> Result<(), PackageError> {
1452 run_command_checked(repo, "git", args)
1453}
1454
1455fn run_command_checked<const N: usize>(
1456 cwd: &Path,
1457 program: &str,
1458 args: [&str; N],
1459) -> Result<(), PackageError> {
1460 run_command_output(cwd, program, args).map(|_| ())
1461}
1462
1463fn run_command_output<const N: usize>(
1464 cwd: &Path,
1465 program: &str,
1466 args: [&str; N],
1467) -> Result<String, PackageError> {
1468 let output = process::Command::new(program)
1469 .current_dir(cwd)
1470 .args(args)
1471 .env_remove("GIT_DIR")
1472 .env_remove("GIT_WORK_TREE")
1473 .env_remove("GIT_INDEX_FILE")
1474 .output()
1475 .map_err(|error| PackageError::Ops(format!("failed to run {program}: {error}")))?;
1476 if !output.status.success() {
1477 return Err(PackageError::Ops(format!(
1478 "{} failed: {}",
1479 program,
1480 String::from_utf8_lossy(&output.stderr).trim_end()
1481 )));
1482 }
1483 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
1484}
1485
1486fn sanitize_branch_segment(value: &str) -> String {
1487 value
1488 .chars()
1489 .map(|ch| {
1490 if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.') {
1491 ch
1492 } else {
1493 '-'
1494 }
1495 })
1496 .collect()
1497}
1498
1499fn shell_quote_path(path: &Path) -> String {
1500 let raw = path.display().to_string();
1501 if raw
1502 .bytes()
1503 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'.' | b'-' | b'_'))
1504 {
1505 raw
1506 } else {
1507 format!("'{}'", raw.replace('\'', "'\\''"))
1508 }
1509}
1510
1511pub(crate) fn load_manifest_context_for_anchor(
1512 anchor: Option<&Path>,
1513) -> Result<ManifestContext, PackageError> {
1514 let anchor = anchor
1515 .map(Path::to_path_buf)
1516 .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
1517 let manifest_path = if anchor.is_dir() {
1518 anchor.join(MANIFEST)
1519 } else if anchor.file_name() == Some(OsStr::new(MANIFEST)) {
1520 anchor
1521 } else {
1522 let (_, dir) = find_nearest_manifest(&anchor)
1523 .ok_or_else(|| format!("no {MANIFEST} found from {}", anchor.display()))?;
1524 dir.join(MANIFEST)
1525 };
1526 let manifest = read_manifest_from_path(&manifest_path)?;
1527 let dir = manifest_path
1528 .parent()
1529 .map(Path::to_path_buf)
1530 .unwrap_or_else(|| PathBuf::from("."));
1531 Ok(ManifestContext { manifest, dir })
1532}
1533
1534pub(crate) fn required_package_string<'a>(
1535 value: Option<&'a str>,
1536 field: &str,
1537 errors: &mut Vec<PackageCheckDiagnostic>,
1538) -> Option<&'a str> {
1539 match value.map(str::trim).filter(|value| !value.is_empty()) {
1540 Some(value) => Some(value),
1541 None => {
1542 push_error(errors, field, format!("missing required {field}"));
1543 None
1544 }
1545 }
1546}
1547
1548pub(crate) fn push_error(
1549 diagnostics: &mut Vec<PackageCheckDiagnostic>,
1550 field: impl Into<String>,
1551 message: impl Into<String>,
1552) {
1553 diagnostics.push(PackageCheckDiagnostic {
1554 field: field.into(),
1555 message: message.into(),
1556 });
1557}
1558
1559pub(crate) fn push_warning(
1560 diagnostics: &mut Vec<PackageCheckDiagnostic>,
1561 field: impl Into<String>,
1562 message: impl Into<String>,
1563) {
1564 push_error(diagnostics, field, message);
1565}
1566
1567pub(crate) fn validate_optional_url(
1568 value: Option<&str>,
1569 field: &str,
1570 errors: &mut Vec<PackageCheckDiagnostic>,
1571) {
1572 let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
1573 push_error(errors, field, format!("missing required {field}"));
1574 return;
1575 };
1576 if Url::parse(value).is_err() {
1577 push_error(errors, field, format!("{field} must be an absolute URL"));
1578 }
1579}
1580
1581pub(crate) fn validate_docs_url(
1582 root: &Path,
1583 value: Option<&str>,
1584 errors: &mut Vec<PackageCheckDiagnostic>,
1585 warnings: &mut Vec<PackageCheckDiagnostic>,
1586) {
1587 let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
1588 push_warning(
1589 warnings,
1590 "[package].docs_url",
1591 "missing docs_url; `harn package docs` defaults to docs/api.md",
1592 );
1593 return;
1594 };
1595 if Url::parse(value).is_ok() {
1596 return;
1597 }
1598 let path = PathBuf::from(value);
1599 let path = if path.is_absolute() {
1600 path
1601 } else {
1602 root.join(path)
1603 };
1604 if !path.exists() {
1605 push_error(
1606 errors,
1607 "[package].docs_url",
1608 format!("docs_url path {} does not exist", path.display()),
1609 );
1610 }
1611}
1612
1613pub(crate) fn validate_dependencies_for_publish(
1614 ctx: &ManifestContext,
1615 errors: &mut Vec<PackageCheckDiagnostic>,
1616 warnings: &mut Vec<PackageCheckDiagnostic>,
1617) {
1618 let mut aliases = BTreeSet::new();
1619 for (alias, dependency) in &ctx.manifest.dependencies {
1620 let field = format!("[dependencies].{alias}");
1621 if let Err(message) = validate_package_alias(alias) {
1622 push_error(errors, &field, message);
1623 }
1624 if !aliases.insert(alias) {
1625 push_error(errors, &field, "duplicate dependency alias");
1626 }
1627 match dependency {
1628 Dependency::Path(path) => push_error(
1629 errors,
1630 &field,
1631 format!("path-only dependency '{path}' is not publishable; pin a git tag, git rev, or registry version"),
1632 ),
1633 Dependency::Table(table) => {
1634 if table.version.is_some()
1635 && (table.git.is_some()
1636 || table.path.is_some()
1637 || table.rev.is_some()
1638 || table.tag.is_some()
1639 || table.branch.is_some())
1640 {
1641 push_error(
1642 errors,
1643 &field,
1644 "version dependencies resolve through the registry; do not combine version with git, path, tag, rev, or branch",
1645 );
1646 }
1647 if table.path.is_some() {
1648 push_error(
1649 errors,
1650 &field,
1651 "path dependencies are not publishable; pin a git tag, git rev, or registry version",
1652 );
1653 }
1654 if table.git.is_none() && table.path.is_none() && table.version.is_none() {
1655 push_error(
1656 errors,
1657 &field,
1658 "dependency must specify git, registry version, or path",
1659 );
1660 }
1661 let git_ref_count = usize::from(table.rev.is_some())
1662 + usize::from(table.tag.is_some())
1663 + usize::from(table.branch.is_some());
1664 if table.git.is_some() && git_ref_count > 1 {
1665 push_error(errors, &field, "dependency cannot specify more than one of tag, rev, or branch");
1666 }
1667 if table.git.is_some() && git_ref_count == 0 {
1668 push_error(errors, &field, "git dependency must specify tag, rev, or branch");
1669 }
1670 if table.branch.is_some() {
1671 push_warning(
1672 warnings,
1673 &field,
1674 "branch dependencies are non-reproducible for publishing; prefer tag, rev, or registry version",
1675 );
1676 }
1677 if let Some(version) = table.version.as_deref() {
1678 if let Err(error) = parse_registry_version_req(version) {
1679 push_error(errors, &field, error.to_string());
1680 }
1681 }
1682 if let Some(git) = table.git.as_deref() {
1683 if normalize_git_url(git).is_err() {
1684 push_error(errors, &field, format!("invalid git source '{git}'"));
1685 }
1686 }
1687 }
1688 }
1689 }
1690}
1691
1692pub(crate) fn validate_exports_for_publish(
1693 ctx: &ManifestContext,
1694 errors: &mut Vec<PackageCheckDiagnostic>,
1695 warnings: &mut Vec<PackageCheckDiagnostic>,
1696) -> Vec<PackageExportReport> {
1697 if ctx.manifest.exports.is_empty() {
1698 push_error(
1699 errors,
1700 "[exports]",
1701 "publishable packages require at least one stable export",
1702 );
1703 return Vec::new();
1704 }
1705
1706 let mut exports = Vec::new();
1707 for (name, rel_path) in &ctx.manifest.exports {
1708 let field = format!("[exports].{name}");
1709 if let Err(message) = validate_package_alias(name) {
1710 push_error(errors, &field, message);
1711 }
1712 let Ok(path) = safe_package_relative_path(&ctx.dir, rel_path) else {
1713 push_error(
1714 errors,
1715 &field,
1716 "export path must stay inside the package directory",
1717 );
1718 continue;
1719 };
1720 if path.extension() != Some(OsStr::new("harn")) {
1721 push_error(errors, &field, "export path must point at a .harn file");
1722 continue;
1723 }
1724 let content = match fs::read_to_string(&path) {
1725 Ok(content) => content,
1726 Err(error) => {
1727 push_error(
1728 errors,
1729 &field,
1730 format!("failed to read export {}: {error}", path.display()),
1731 );
1732 continue;
1733 }
1734 };
1735 if let Err(error) = parse_harn_source(&content) {
1736 push_error(errors, &field, format!("failed to parse export: {error}"));
1737 }
1738 let symbols = extract_api_symbols(&content);
1739 if symbols.is_empty() {
1740 push_warning(
1741 warnings,
1742 &field,
1743 "exported module has no public symbols to document",
1744 );
1745 }
1746 for symbol in &symbols {
1747 if symbol.docs.is_none() {
1748 push_warning(
1749 warnings,
1750 &field,
1751 format!(
1752 "public {} '{}' has no doc comment",
1753 symbol.kind, symbol.name
1754 ),
1755 );
1756 }
1757 }
1758 exports.push(PackageExportReport {
1759 name: name.clone(),
1760 path: rel_path.clone(),
1761 symbols,
1762 });
1763 }
1764 exports.sort_by(|left, right| left.name.cmp(&right.name));
1765 exports
1766}
1767
1768pub(crate) fn validate_package_interface_exports(
1769 ctx: &ManifestContext,
1770 errors: &mut Vec<PackageCheckDiagnostic>,
1771 warnings: &mut Vec<PackageCheckDiagnostic>,
1772) -> (Vec<PackageToolExportReport>, Vec<PackageSkillExportReport>) {
1773 let Some(package) = ctx.manifest.package.as_ref() else {
1774 return (Vec::new(), Vec::new());
1775 };
1776
1777 validate_permission_tokens(
1778 &package.permissions,
1779 "[package].permissions",
1780 errors,
1781 warnings,
1782 );
1783 validate_host_requirements(
1784 &package.host_requirements,
1785 "[package].host_requirements",
1786 errors,
1787 );
1788
1789 let mut tools = Vec::new();
1790 for (index, tool) in package.tools.iter().enumerate() {
1791 let field = format!("[[package.tools]] #{}", index + 1);
1792 if let Err(message) = validate_package_alias(&tool.name) {
1793 push_error(errors, format!("{field}.name"), message.to_string());
1794 }
1795 validate_required_manifest_string(&tool.module, &format!("{field}.module"), errors);
1796 validate_required_manifest_string(&tool.symbol, &format!("{field}.symbol"), errors);
1797 validate_package_module_path(ctx, &tool.module, &format!("{field}.module"), errors);
1798 validate_permission_tokens(
1799 &tool.permissions,
1800 &format!("{field}.permissions"),
1801 errors,
1802 warnings,
1803 );
1804 validate_host_requirements(
1805 &tool.host_requirements,
1806 &format!("{field}.host_requirements"),
1807 errors,
1808 );
1809 validate_schema_value(
1810 tool.input_schema.as_ref(),
1811 &format!("{field}.input_schema"),
1812 errors,
1813 );
1814 validate_schema_value(
1815 tool.output_schema.as_ref(),
1816 &format!("{field}.output_schema"),
1817 errors,
1818 );
1819 validate_tool_annotations(&tool.annotations, &format!("{field}.annotations"), errors);
1820 if tool.annotations.is_empty() {
1821 push_warning(
1822 warnings,
1823 format!("{field}.annotations"),
1824 "tool export has no annotations; policy evaluation will treat it conservatively",
1825 );
1826 }
1827 tools.push(PackageToolExportReport {
1828 name: tool.name.clone(),
1829 module: tool.module.clone(),
1830 symbol: tool.symbol.clone(),
1831 permissions: merge_package_requirements(&package.permissions, &tool.permissions),
1832 host_requirements: merge_package_requirements(
1833 &package.host_requirements,
1834 &tool.host_requirements,
1835 ),
1836 });
1837 }
1838 tools.sort_by(|left, right| left.name.cmp(&right.name));
1839
1840 let mut skills = Vec::new();
1841 for (index, skill) in package.skills.iter().enumerate() {
1842 let field = format!("[[package.skills]] #{}", index + 1);
1843 if let Err(message) = validate_package_alias(&skill.name) {
1844 push_error(errors, format!("{field}.name"), message.to_string());
1845 }
1846 validate_required_manifest_string(&skill.path, &format!("{field}.path"), errors);
1847 validate_package_skill_path(ctx, &skill.path, &format!("{field}.path"), errors);
1848 validate_permission_tokens(
1849 &skill.permissions,
1850 &format!("{field}.permissions"),
1851 errors,
1852 warnings,
1853 );
1854 validate_host_requirements(
1855 &skill.host_requirements,
1856 &format!("{field}.host_requirements"),
1857 errors,
1858 );
1859 skills.push(PackageSkillExportReport {
1860 name: skill.name.clone(),
1861 path: skill.path.clone(),
1862 permissions: merge_package_requirements(&package.permissions, &skill.permissions),
1863 host_requirements: merge_package_requirements(
1864 &package.host_requirements,
1865 &skill.host_requirements,
1866 ),
1867 });
1868 }
1869 skills.sort_by(|left, right| left.name.cmp(&right.name));
1870
1871 (tools, skills)
1872}
1873
1874pub(crate) fn merge_package_requirements(base: &[String], item: &[String]) -> Vec<String> {
1875 let mut merged = BTreeSet::new();
1876 merged.extend(
1877 base.iter()
1878 .filter_map(|value| normalized_requirement(value)),
1879 );
1880 merged.extend(
1881 item.iter()
1882 .filter_map(|value| normalized_requirement(value)),
1883 );
1884 merged.into_iter().collect()
1885}
1886
1887fn normalized_requirement(value: &str) -> Option<String> {
1888 let trimmed = value.trim();
1889 (!trimmed.is_empty()).then(|| trimmed.to_string())
1890}
1891
1892fn validate_required_manifest_string(
1893 value: &str,
1894 field: &str,
1895 errors: &mut Vec<PackageCheckDiagnostic>,
1896) {
1897 if value.trim().is_empty() {
1898 push_error(errors, field, format!("missing required {field}"));
1899 }
1900}
1901
1902fn validate_permission_tokens(
1903 permissions: &[String],
1904 field: &str,
1905 errors: &mut Vec<PackageCheckDiagnostic>,
1906 warnings: &mut Vec<PackageCheckDiagnostic>,
1907) {
1908 let mut seen = BTreeSet::new();
1909 for permission in permissions {
1910 let trimmed = permission.trim();
1911 if trimmed.is_empty() {
1912 push_error(errors, field, "permission entries cannot be empty");
1913 continue;
1914 }
1915 if trimmed.chars().any(char::is_whitespace) {
1916 push_error(
1917 errors,
1918 field,
1919 format!("permission {permission:?} cannot contain whitespace"),
1920 );
1921 }
1922 if !trimmed.contains(':') && !trimmed.contains('.') {
1923 push_warning(
1924 warnings,
1925 field,
1926 format!("permission {permission:?} should use a namespaced token"),
1927 );
1928 }
1929 if !seen.insert(trimmed.to_string()) {
1930 push_warning(
1931 warnings,
1932 field,
1933 format!("duplicate permission {permission:?}"),
1934 );
1935 }
1936 }
1937}
1938
1939pub(crate) fn validate_host_requirements(
1940 requirements: &[String],
1941 field: &str,
1942 errors: &mut Vec<PackageCheckDiagnostic>,
1943) {
1944 let mut seen = BTreeSet::new();
1945 for requirement in requirements {
1946 let trimmed = requirement.trim();
1947 if trimmed.is_empty() {
1948 push_error(errors, field, "host requirement entries cannot be empty");
1949 continue;
1950 }
1951 let Some((capability, operation)) = trimmed.split_once('.') else {
1952 push_error(
1953 errors,
1954 field,
1955 format!("host requirement {requirement:?} must use capability.operation"),
1956 );
1957 continue;
1958 };
1959 if !valid_identifier(capability)
1960 || !(valid_identifier(operation) || operation == "*")
1961 || trimmed.matches('.').count() != 1
1962 {
1963 push_error(
1964 errors,
1965 field,
1966 format!("host requirement {requirement:?} must use valid capability.operation identifiers"),
1967 );
1968 }
1969 if !seen.insert(trimmed.to_string()) {
1970 push_error(
1971 errors,
1972 field,
1973 format!("duplicate host requirement {requirement:?}"),
1974 );
1975 }
1976 }
1977}
1978
1979fn validate_package_module_path(
1980 ctx: &ManifestContext,
1981 rel_path: &str,
1982 field: &str,
1983 errors: &mut Vec<PackageCheckDiagnostic>,
1984) {
1985 let Ok(path) = safe_package_relative_path(&ctx.dir, rel_path) else {
1986 push_error(errors, field, "module path must stay inside the package");
1987 return;
1988 };
1989 if path.extension() != Some(OsStr::new("harn")) {
1990 push_error(errors, field, "module path must point at a .harn file");
1991 return;
1992 }
1993 match fs::read_to_string(&path) {
1994 Ok(content) => {
1995 if let Err(error) = parse_harn_source(&content) {
1996 push_error(errors, field, format!("failed to parse module: {error}"));
1997 }
1998 }
1999 Err(error) => push_error(
2000 errors,
2001 field,
2002 format!("failed to read module {}: {error}", path.display()),
2003 ),
2004 }
2005}
2006
2007fn validate_package_skill_path(
2008 ctx: &ManifestContext,
2009 rel_path: &str,
2010 field: &str,
2011 errors: &mut Vec<PackageCheckDiagnostic>,
2012) {
2013 let Ok(path) = safe_package_relative_path(&ctx.dir, rel_path) else {
2014 push_error(errors, field, "skill path must stay inside the package");
2015 return;
2016 };
2017 let skill_file = if path.is_dir() {
2018 path.join("SKILL.md")
2019 } else {
2020 path
2021 };
2022 if skill_file.file_name() != Some(OsStr::new("SKILL.md")) {
2023 push_error(
2024 errors,
2025 field,
2026 "skill path must be a SKILL.md file or skill directory",
2027 );
2028 return;
2029 }
2030 match fs::read_to_string(&skill_file) {
2031 Ok(content) => {
2032 let (frontmatter, _) = harn_vm::skills::split_frontmatter(&content);
2033 if let Err(error) = harn_vm::skills::parse_frontmatter(frontmatter) {
2034 push_error(
2035 errors,
2036 field,
2037 format!("invalid SKILL.md frontmatter: {error}"),
2038 );
2039 }
2040 }
2041 Err(error) => push_error(
2042 errors,
2043 field,
2044 format!("failed to read skill {}: {error}", skill_file.display()),
2045 ),
2046 }
2047}
2048
2049fn validate_schema_value(
2050 value: Option<&toml::Value>,
2051 field: &str,
2052 errors: &mut Vec<PackageCheckDiagnostic>,
2053) {
2054 let Some(value) = value else {
2055 return;
2056 };
2057 let json = match toml_value_to_json(value) {
2058 Ok(json) => json,
2059 Err(error) => {
2060 push_error(errors, field, error);
2061 return;
2062 }
2063 };
2064 let Some(object) = json.as_object() else {
2065 push_error(errors, field, "schema must be a table/object");
2066 return;
2067 };
2068 if let Some(schema_type) = object.get("type") {
2069 if !schema_type.is_string() {
2070 push_error(errors, field, "schema `type` must be a string when present");
2071 }
2072 }
2073 if let Some(required) = object.get("required") {
2074 let valid = required
2075 .as_array()
2076 .is_some_and(|items| items.iter().all(|item| item.as_str().is_some()));
2077 if !valid {
2078 push_error(errors, field, "schema `required` must be a list of strings");
2079 }
2080 }
2081}
2082
2083fn validate_tool_annotations(
2084 annotations: &BTreeMap<String, toml::Value>,
2085 field: &str,
2086 errors: &mut Vec<PackageCheckDiagnostic>,
2087) {
2088 if annotations.is_empty() {
2089 return;
2090 }
2091 let json = match toml_value_to_json(&toml::Value::Table(
2092 annotations
2093 .clone()
2094 .into_iter()
2095 .collect::<toml::map::Map<String, toml::Value>>(),
2096 )) {
2097 Ok(json) => json,
2098 Err(error) => {
2099 push_error(errors, field, error);
2100 return;
2101 }
2102 };
2103 if let Err(error) = serde_json::from_value::<harn_vm::tool_annotations::ToolAnnotations>(json) {
2104 push_error(
2105 errors,
2106 field,
2107 format!("annotations do not match ToolAnnotations: {error}"),
2108 );
2109 }
2110}
2111
2112fn toml_value_to_json(value: &toml::Value) -> Result<serde_json::Value, String> {
2113 serde_json::to_value(value).map_err(|error| format!("failed to normalize TOML value: {error}"))
2114}
2115
2116pub(crate) fn parse_harn_source(source: &str) -> Result<(), PackageError> {
2117 let mut lexer = harn_lexer::Lexer::new(source);
2118 let tokens = lexer.tokenize().map_err(|error| error.to_string())?;
2119 let mut parser = harn_parser::Parser::new(tokens);
2120 parser
2121 .parse()
2122 .map(|_| ())
2123 .map_err(|error| PackageError::Ops(error.to_string()))
2124}
2125
2126pub(crate) fn safe_package_relative_path(
2127 root: &Path,
2128 rel_path: &str,
2129) -> Result<PathBuf, PackageError> {
2130 let rel = PathBuf::from(rel_path);
2131 if rel.is_absolute()
2132 || has_windows_rooted_or_drive_relative_prefix(rel_path)
2133 || has_windows_separator_escape(rel_path)
2134 || rel.components().any(|component| {
2135 matches!(
2136 component,
2137 std::path::Component::ParentDir
2138 | std::path::Component::Prefix(_)
2139 | std::path::Component::RootDir
2140 )
2141 })
2142 {
2143 return Err(format!("path {rel_path:?} escapes package root").into());
2144 }
2145 Ok(root.join(rel))
2146}
2147
2148fn has_windows_rooted_or_drive_relative_prefix(path: &str) -> bool {
2149 let normalized = path.replace('\\', "/");
2150 let bytes = normalized.as_bytes();
2151 normalized.starts_with('/')
2152 || (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
2153}
2154
2155fn has_windows_separator_escape(path: &str) -> bool {
2156 let normalized = path.replace('\\', "/");
2157 Path::new(&normalized).components().any(|component| {
2158 matches!(
2159 component,
2160 std::path::Component::ParentDir
2161 | std::path::Component::Prefix(_)
2162 | std::path::Component::RootDir
2163 )
2164 })
2165}
2166
2167pub(crate) fn extract_api_symbols(source: &str) -> Vec<PackageApiSymbol> {
2168 static DECL_RE: OnceLock<Regex> = OnceLock::new();
2169 let decl_re = DECL_RE.get_or_init(|| {
2170 Regex::new(r"^\s*pub\s+(fn|pipeline|tool|skill|struct|enum|type|interface)\s+([A-Za-z_][A-Za-z0-9_]*)\b(.*)$")
2171 .expect("valid declaration regex")
2172 });
2173 let mut docs: Vec<String> = Vec::new();
2174 let mut symbols = Vec::new();
2175 let mut in_block_doc = false;
2176 for line in source.lines() {
2177 let trimmed = line.trim();
2178 if in_block_doc {
2179 let (content, closes) = match trimmed.split_once("*/") {
2183 Some((before, _)) => (before, true),
2184 None => (trimmed, false),
2185 };
2186 let stripped = content
2187 .strip_prefix("* ")
2188 .or_else(|| content.strip_prefix('*'))
2189 .unwrap_or(content)
2190 .trim();
2191 if !stripped.is_empty() {
2192 docs.push(stripped.to_string());
2193 }
2194 if closes {
2195 in_block_doc = false;
2196 }
2197 continue;
2198 }
2199 if let Some(doc) = trimmed.strip_prefix("///") {
2200 docs.push(doc.trim().to_string());
2201 continue;
2202 }
2203 if let Some(rest) = trimmed.strip_prefix("/**") {
2204 if let Some((inner, _)) = rest.split_once("*/") {
2208 let stripped = inner.trim();
2209 if !stripped.is_empty() {
2210 docs.push(stripped.to_string());
2211 }
2212 } else {
2213 let stripped = rest.trim();
2214 if !stripped.is_empty() {
2215 docs.push(stripped.to_string());
2216 }
2217 in_block_doc = true;
2218 }
2219 continue;
2220 }
2221 if trimmed.is_empty() {
2222 continue;
2223 }
2224 if let Some(captures) = decl_re.captures(line) {
2225 let kind = captures.get(1).expect("kind").as_str().to_string();
2226 let name = captures.get(2).expect("name").as_str().to_string();
2227 let signature = trim_signature(line);
2228 let doc_text = (!docs.is_empty()).then(|| docs.join("\n"));
2229 symbols.push(PackageApiSymbol {
2230 kind,
2231 name,
2232 signature,
2233 docs: doc_text,
2234 });
2235 }
2236 docs.clear();
2237 }
2238 symbols
2239}
2240
2241pub(crate) fn trim_signature(line: &str) -> String {
2242 let mut signature = line.trim().to_string();
2243 if let Some((before, _)) = signature.split_once('{') {
2244 signature = before.trim_end().to_string();
2245 }
2246 signature
2247}
2248
2249pub(crate) fn supports_current_harn(range: &str) -> bool {
2250 let current = env!("CARGO_PKG_VERSION");
2251 let Some((major, minor)) = parse_major_minor(current) else {
2252 return true;
2253 };
2254 let range = range.trim();
2255 if range.is_empty() {
2256 return false;
2257 }
2258 if let Some(rest) = range.strip_prefix('^') {
2259 return parse_major_minor(rest).is_some_and(|(m, n)| m == major && n == minor);
2260 }
2261 if !range.contains([',', '<', '>', '=']) {
2262 return parse_major_minor(range).is_some_and(|(m, n)| m == major && n == minor);
2263 }
2264
2265 let current_value = major * 1000 + minor;
2266 let mut lower_ok = true;
2267 let mut upper_ok = true;
2268 let mut saw_constraint = false;
2269 for raw in range.split(',') {
2270 let part = raw.trim();
2271 if part.is_empty() {
2272 continue;
2273 }
2274 saw_constraint = true;
2275 if let Some(rest) = part.strip_prefix(">=") {
2276 if let Some((m, n)) = parse_major_minor(rest.trim()) {
2277 lower_ok &= current_value >= m * 1000 + n;
2278 } else {
2279 return false;
2280 }
2281 } else if let Some(rest) = part.strip_prefix('>') {
2282 if let Some((m, n)) = parse_major_minor(rest.trim()) {
2283 lower_ok &= current_value > m * 1000 + n;
2284 } else {
2285 return false;
2286 }
2287 } else if let Some(rest) = part.strip_prefix("<=") {
2288 if let Some((m, n)) = parse_major_minor(rest.trim()) {
2289 upper_ok &= current_value <= m * 1000 + n;
2290 } else {
2291 return false;
2292 }
2293 } else if let Some(rest) = part.strip_prefix('<') {
2294 if let Some((m, n)) = parse_major_minor(rest.trim()) {
2295 upper_ok &= current_value < m * 1000 + n;
2296 } else {
2297 return false;
2298 }
2299 } else if let Some(rest) = part.strip_prefix('=') {
2300 if let Some((m, n)) = parse_major_minor(rest.trim()) {
2301 lower_ok &= current_value == m * 1000 + n;
2302 upper_ok &= current_value == m * 1000 + n;
2303 } else {
2304 return false;
2305 }
2306 } else {
2307 return false;
2308 }
2309 }
2310 saw_constraint && lower_ok && upper_ok
2311}
2312
2313pub(crate) fn current_harn_range_example() -> String {
2314 let current = env!("CARGO_PKG_VERSION");
2315 let Some((major, minor)) = parse_major_minor(current) else {
2316 return ">=0.7,<0.8".to_string();
2317 };
2318 format!(">={major}.{minor},<{major}.{}", minor + 1)
2319}
2320
2321pub(crate) fn current_harn_line_label() -> String {
2322 let current = env!("CARGO_PKG_VERSION");
2323 let Some((major, minor)) = parse_major_minor(current) else {
2324 return "0.7".to_string();
2325 };
2326 format!("{major}.{minor}")
2327}
2328
2329pub(crate) fn parse_major_minor(raw: &str) -> Option<(u64, u64)> {
2330 let raw = raw.trim().trim_start_matches('v');
2331 let mut parts = raw.split('.');
2332 let major = parts.next()?.parse().ok()?;
2333 let minor = parts.next()?.trim_end_matches('x').parse().ok()?;
2334 Some((major, minor))
2335}
2336
2337pub(crate) fn collect_package_files(root: &Path) -> Result<Vec<String>, PackageError> {
2338 let mut files = Vec::new();
2339 collect_package_files_inner(root, root, &mut files)?;
2340 files.sort();
2341 Ok(files)
2342}
2343
2344pub(crate) fn collect_package_files_inner(
2345 root: &Path,
2346 dir: &Path,
2347 out: &mut Vec<String>,
2348) -> Result<(), PackageError> {
2349 for entry in
2350 fs::read_dir(dir).map_err(|error| format!("failed to read {}: {error}", dir.display()))?
2351 {
2352 let entry =
2353 entry.map_err(|error| format!("failed to read {} entry: {error}", dir.display()))?;
2354 let path = entry.path();
2355 let file_type = entry
2356 .file_type()
2357 .map_err(|error| format!("failed to inspect {}: {error}", path.display()))?;
2358 if file_type.is_symlink() {
2359 continue;
2360 }
2361 if file_type.is_dir() {
2362 let rel = path
2363 .strip_prefix(root)
2364 .map_err(|error| format!("failed to relativize {}: {error}", path.display()))?;
2365 if should_skip_package_dir(rel) {
2366 continue;
2367 }
2368 collect_package_files_inner(root, &path, out)?;
2369 } else if file_type.is_file() {
2370 let rel = path
2371 .strip_prefix(root)
2372 .map_err(|error| format!("failed to relativize {}: {error}", path.display()))?
2373 .to_string_lossy()
2374 .replace('\\', "/");
2375 out.push(rel);
2376 }
2377 }
2378 Ok(())
2379}
2380
2381pub(crate) fn should_skip_package_dir(rel: &Path) -> bool {
2382 if rel == Path::new("docs").join("dist") {
2383 return true;
2384 }
2385 rel.components().any(|component| {
2386 matches!(
2387 component.as_os_str().to_str(),
2388 Some(".git" | ".harn" | "target" | "node_modules")
2389 )
2390 })
2391}
2392
2393pub(crate) fn default_artifact_dir(ctx: &ManifestContext, report: &PackageCheckReport) -> PathBuf {
2394 let name = report.name.as_deref().unwrap_or("package");
2395 let version = report.version.as_deref().unwrap_or("0.0.0");
2396 ctx.dir
2397 .join(".harn")
2398 .join("dist")
2399 .join(format!("{name}-{version}"))
2400}
2401
2402pub(crate) fn fail_if_package_errors(report: &PackageCheckReport) -> Result<(), PackageError> {
2403 if report.errors.is_empty() {
2404 return Ok(());
2405 }
2406 Err(format!(
2407 "package check failed:\n{}",
2408 report
2409 .errors
2410 .iter()
2411 .map(|diagnostic| format!("- {}: {}", diagnostic.field, diagnostic.message))
2412 .collect::<Vec<_>>()
2413 .join("\n")
2414 )
2415 .into())
2416}
2417
2418pub(crate) fn render_package_api_docs(report: &PackageCheckReport) -> String {
2419 let title = report.name.as_deref().unwrap_or("package");
2420 let mut out = format!("# API Reference: {title}\n\nGenerated by `harn package docs`.\n");
2421 if let Some(version) = report.version.as_deref() {
2422 out.push_str(&format!("\nVersion: `{version}`\n"));
2423 }
2424 for export in &report.exports {
2425 out.push_str(&format!(
2426 "\n## Export `{}`\n\n`{}`\n",
2427 export.name, export.path
2428 ));
2429 for symbol in &export.symbols {
2430 out.push_str(&format!("\n### {} `{}`\n\n", symbol.kind, symbol.name));
2431 if let Some(docs) = symbol.docs.as_deref() {
2432 out.push_str(docs);
2433 out.push_str("\n\n");
2434 }
2435 out.push_str("```harn\n");
2436 out.push_str(&symbol.signature);
2437 out.push_str("\n```\n");
2438 }
2439 }
2440 if !report.tools.is_empty() {
2441 out.push_str("\n## Tool Exports\n");
2442 for tool in &report.tools {
2443 out.push_str(&format!(
2444 "\n### `{}`\n\n- module: `{}`\n- symbol: `{}`\n",
2445 tool.name, tool.module, tool.symbol
2446 ));
2447 if !tool.permissions.is_empty() {
2448 out.push_str(&format!(
2449 "- permissions: `{}`\n",
2450 tool.permissions.join("`, `")
2451 ));
2452 }
2453 if !tool.host_requirements.is_empty() {
2454 out.push_str(&format!(
2455 "- host requirements: `{}`\n",
2456 tool.host_requirements.join("`, `")
2457 ));
2458 }
2459 }
2460 }
2461 if !report.skills.is_empty() {
2462 out.push_str("\n## Skill Exports\n");
2463 for skill in &report.skills {
2464 out.push_str(&format!("\n### `{}`\n\n`{}`\n", skill.name, skill.path));
2465 }
2466 }
2467 out
2468}
2469
2470pub(crate) fn normalize_newlines(input: &str) -> String {
2471 input.replace("\r\n", "\n")
2472}
2473
2474pub(crate) fn print_package_check_report(report: &PackageCheckReport) {
2475 println!(
2476 "Package {} {}",
2477 report.name.as_deref().unwrap_or("<unnamed>"),
2478 report.version.as_deref().unwrap_or("<unversioned>")
2479 );
2480 println!("manifest: {}", report.manifest_path);
2481 for export in &report.exports {
2482 println!(
2483 "export {} -> {} ({} public symbol(s))",
2484 export.name,
2485 export.path,
2486 export.symbols.len()
2487 );
2488 }
2489 for tool in &report.tools {
2490 println!("tool {} -> {}::{}", tool.name, tool.module, tool.symbol);
2491 }
2492 for skill in &report.skills {
2493 println!("skill {} -> {}", skill.name, skill.path);
2494 }
2495 if !report.warnings.is_empty() {
2496 println!("\nwarnings:");
2497 for warning in &report.warnings {
2498 println!("- {}: {}", warning.field, warning.message);
2499 }
2500 }
2501 if !report.errors.is_empty() {
2502 println!("\nerrors:");
2503 for error in &report.errors {
2504 println!("- {}: {}", error.field, error.message);
2505 }
2506 } else {
2507 println!("\npackage check passed");
2508 }
2509}
2510
2511pub(crate) fn print_package_pack_report(report: &PackagePackReport) {
2512 if report.dry_run {
2513 println!("Package pack dry run succeeded.");
2514 } else {
2515 println!("Packed package artifact.");
2516 }
2517 println!("artifact: {}", report.artifact_dir);
2518 println!("files:");
2519 for file in &report.files {
2520 println!("- {file}");
2521 }
2522}
2523
2524pub(crate) fn print_package_list_report(report: &PackageListReport) {
2525 println!("manifest: {}", report.manifest_path);
2526 println!("lock: {}", report.lock_path);
2527 if !report.lock_present {
2528 println!("lock status: missing");
2529 if report.dependency_count > 0 {
2530 println!(
2531 "run `harn install` to resolve {} dependency(s)",
2532 report.dependency_count
2533 );
2534 }
2535 return;
2536 }
2537 if report.packages.is_empty() {
2538 println!("No packages installed.");
2539 return;
2540 }
2541 println!("Packages ({}):", report.packages.len());
2542 for entry in &report.packages {
2543 let version = entry.package_version.as_deref().unwrap_or("unversioned");
2544 let status = if entry.materialized {
2545 "installed"
2546 } else {
2547 "missing"
2548 };
2549 println!(
2550 " {} {} {} integrity={}",
2551 entry.name, version, status, entry.integrity
2552 );
2553 if !entry.exports.modules.is_empty() {
2554 let modules: Vec<&str> = entry
2555 .exports
2556 .modules
2557 .iter()
2558 .map(|export| export.name.as_str())
2559 .collect();
2560 println!(" modules: {}", modules.join(", "));
2561 }
2562 if !entry.exports.tools.is_empty() {
2563 let tools: Vec<&str> = entry
2564 .exports
2565 .tools
2566 .iter()
2567 .map(|export| export.name.as_str())
2568 .collect();
2569 println!(" tools: {}", tools.join(", "));
2570 }
2571 if !entry.exports.skills.is_empty() {
2572 let skills: Vec<&str> = entry
2573 .exports
2574 .skills
2575 .iter()
2576 .map(|export| export.name.as_str())
2577 .collect();
2578 println!(" skills: {}", skills.join(", "));
2579 }
2580 if !entry.permissions.is_empty() {
2581 println!(" permissions: {}", entry.permissions.join(", "));
2582 }
2583 if !entry.host_requirements.is_empty() {
2584 println!(
2585 " host requirements: {}",
2586 entry.host_requirements.join(", ")
2587 );
2588 }
2589 }
2590}
2591
2592pub(crate) fn print_package_doctor_report(report: &PackageDoctorReport) {
2593 println!("Package doctor");
2594 println!("manifest: {}", report.manifest_path);
2595 println!("lock: {}", report.lock_path);
2596 if report.diagnostics.is_empty() {
2597 println!("ok: no package issues found");
2598 return;
2599 }
2600 for diagnostic in &report.diagnostics {
2601 println!(
2602 "{} [{}] {}",
2603 diagnostic.severity, diagnostic.code, diagnostic.message
2604 );
2605 if let Some(help) = diagnostic.help.as_deref() {
2606 println!(" help: {help}");
2607 }
2608 }
2609}
2610
2611#[cfg(test)]
2612mod tests {
2613 use super::*;
2614 use crate::package::test_support::*;
2615
2616 #[test]
2617 fn package_check_accepts_publishable_package() {
2618 let tmp = tempfile::tempdir().unwrap();
2619 write_publishable_package(tmp.path());
2620
2621 let report = check_package_impl(Some(tmp.path())).unwrap();
2622
2623 assert!(report.errors.is_empty(), "{:?}", report.errors);
2624 assert_eq!(report.name.as_deref(), Some("acme-lib"));
2625 assert_eq!(report.exports[0].symbols[0].name, "greet");
2626 }
2627
2628 #[test]
2629 fn package_check_rejects_path_dependencies_and_bad_harn_range() {
2630 let tmp = tempfile::tempdir().unwrap();
2631 write_publishable_package(tmp.path());
2632 fs::write(
2633 tmp.path().join(MANIFEST),
2634 r#"[package]
2635 name = "acme-lib"
2636 version = "0.1.0"
2637 description = "Acme helpers"
2638 license = "MIT"
2639 repository = "https://github.com/acme/acme-lib"
2640 harn = ">=999.0,<999.1"
2641 docs_url = "docs/api.md"
2642
2643 [exports]
2644 lib = "lib/main.harn"
2645
2646 [dependencies]
2647 local = { path = "../local" }
2648 "#,
2649 )
2650 .unwrap();
2651
2652 let report = check_package_impl(Some(tmp.path())).unwrap();
2653 let messages = report
2654 .errors
2655 .iter()
2656 .map(|diagnostic| diagnostic.message.as_str())
2657 .collect::<Vec<_>>()
2658 .join("\n");
2659
2660 assert!(messages.contains("unsupported Harn version range"));
2661 assert!(messages.contains("path dependencies are not publishable"));
2662 }
2663
2664 #[test]
2665 fn package_check_warns_on_branch_dependency() {
2666 let tmp = tempfile::tempdir().unwrap();
2667 write_publishable_package(tmp.path());
2668 fs::write(
2669 tmp.path().join(MANIFEST),
2670 format!(
2671 r#"[package]
2672name = "acme-lib"
2673version = "0.1.0"
2674description = "Acme helpers"
2675license = "MIT"
2676repository = "https://github.com/acme/acme-lib"
2677harn = "{}"
2678docs_url = "docs/api.md"
2679
2680[exports]
2681lib = "lib/main.harn"
2682
2683[dependencies]
2684remote = {{ git = "https://github.com/acme/remote-lib", branch = "main" }}
2685"#,
2686 current_harn_range_example()
2687 ),
2688 )
2689 .unwrap();
2690
2691 let report = check_package_impl(Some(tmp.path())).unwrap();
2692 let warnings = report
2693 .warnings
2694 .iter()
2695 .map(|diagnostic| diagnostic.message.as_str())
2696 .collect::<Vec<_>>()
2697 .join("\n");
2698
2699 assert!(report.errors.is_empty(), "{:?}", report.errors);
2700 assert!(warnings.contains("branch dependencies are non-reproducible"));
2701 }
2702
2703 #[test]
2704 fn extract_api_symbols_recognizes_block_doc_comments() {
2705 let single = extract_api_symbols("/** Block doc. */\npub fn one() {}\n");
2710 assert_eq!(single.len(), 1);
2711 assert_eq!(single[0].docs.as_deref(), Some("Block doc."));
2712
2713 let multi =
2714 extract_api_symbols("/**\n * First line.\n * Second line.\n */\npub fn two() {}\n");
2715 assert_eq!(multi.len(), 1);
2716 assert_eq!(multi[0].docs.as_deref(), Some("First line.\nSecond line."));
2717
2718 let triple = extract_api_symbols("/// Slash doc.\npub fn three() {}\n");
2719 assert_eq!(triple.len(), 1);
2720 assert_eq!(triple[0].docs.as_deref(), Some("Slash doc."));
2721
2722 let detached = extract_api_symbols("/** Detached. */\nlet x = 1\npub fn four() {}\n");
2726 assert_eq!(detached.len(), 1);
2727 assert!(detached[0].docs.is_none());
2728 }
2729
2730 #[test]
2731 fn package_docs_and_pack_use_exports() {
2732 let tmp = tempfile::tempdir().unwrap();
2733 write_publishable_package(tmp.path());
2734
2735 let docs_path = generate_package_docs_impl(Some(tmp.path()), None, false).unwrap();
2736 let docs = fs::read_to_string(docs_path).unwrap();
2737 assert!(docs.contains("### fn `greet`"));
2738 assert!(docs.contains("Return a greeting."));
2739
2740 let pack = pack_package_impl(Some(tmp.path()), None, true).unwrap();
2741 assert!(pack.files.contains(&"harn.toml".to_string()));
2742 assert!(pack.files.contains(&"lib/main.harn".to_string()));
2743 }
2744
2745 #[test]
2746 fn package_pack_skips_generated_docs_dist() {
2747 let tmp = tempfile::tempdir().unwrap();
2748 write_publishable_package(tmp.path());
2749 fs::create_dir_all(tmp.path().join("docs/dist")).unwrap();
2750 fs::write(tmp.path().join("docs/dist/index.html"), "<html></html>\n").unwrap();
2751
2752 let pack = pack_package_impl(Some(tmp.path()), None, true).unwrap();
2753
2754 assert!(
2755 !pack.files.iter().any(|path| path.starts_with("docs/dist/")),
2756 "{:?}",
2757 pack.files
2758 );
2759 }
2760
2761 #[test]
2762 fn publish_dry_run_builds_tag_command_and_index_diff() {
2763 let tmp = tempfile::tempdir().unwrap();
2764 write_publishable_package(tmp.path());
2765 write_release_changelog(tmp.path(), "0.1.0");
2766 let _remote = init_publishable_repo(tmp.path());
2767 let index = r#"version = 1
2768
2769[[package]]
2770name = "acme-lib"
2771repository = "https://github.com/acme/acme-lib"
2772
2773[[package.version]]
2774version = "0.0.1"
2775git = "https://github.com/acme/acme-lib"
2776rev = "deadbeef"
2777
2778[[package]]
2779name = "other-lib"
2780repository = "https://github.com/acme/other-lib"
2781
2782[[package.version]]
2783version = "1.0.0"
2784git = "https://github.com/acme/other-lib"
2785rev = "feedface"
2786"#;
2787 let index_path = Path::new("package-index/harn-package-index.toml");
2788 let options = PackagePublishOptions {
2789 dry_run: true,
2790 remote: "origin",
2791 index_repo: "burin-labs/harn-cloud",
2792 index_path,
2793 registry_name: None,
2794 skip_index_pr: false,
2795 registry: None,
2796 };
2797
2798 let plan =
2799 prepare_publish_plan(Some(tmp.path()), &options, index.to_string(), "fixture").unwrap();
2800
2801 assert!(plan.tag_command.contains("git -C"));
2802 assert!(plan.tag_command.contains("tag v0.1.0"));
2803 assert!(plan.index_diff.contains("+version = \"0.1.0\""));
2804 assert!(plan.index_diff.contains("+tag = \"v0.1.0\""));
2805 assert!(plan
2806 .index_diff
2807 .contains(&format!("+rev = \"{}\"", plan.sha)));
2808 assert!(plan
2809 .index_diff
2810 .contains(&format!("+sha = \"{}\"", plan.sha)));
2811 let acme_pos = plan
2812 .updated_index_content
2813 .find("name = \"acme-lib\"")
2814 .unwrap();
2815 let other_pos = plan
2816 .updated_index_content
2817 .find("name = \"other-lib\"")
2818 .unwrap();
2819 let new_version_pos = plan
2820 .updated_index_content
2821 .find("version = \"0.1.0\"")
2822 .unwrap();
2823 assert!(acme_pos < new_version_pos && new_version_pos < other_pos);
2824 }
2825
2826 #[test]
2827 fn publish_preflight_rejects_existing_tag_and_missing_changelog_entry() {
2828 let tmp = tempfile::tempdir().unwrap();
2829 write_publishable_package(tmp.path());
2830 let _remote = init_publishable_repo(tmp.path());
2831 let index_path = Path::new("package-index/harn-package-index.toml");
2832 let options = PackagePublishOptions {
2833 dry_run: true,
2834 remote: "origin",
2835 index_repo: "burin-labs/harn-cloud",
2836 index_path,
2837 registry_name: None,
2838 skip_index_pr: false,
2839 registry: None,
2840 };
2841
2842 let missing_changelog = prepare_publish_plan(
2843 Some(tmp.path()),
2844 &options,
2845 "version = 1\n".to_string(),
2846 "fixture",
2847 )
2848 .unwrap_err()
2849 .to_string();
2850 assert!(missing_changelog.contains("CHANGELOG.md"));
2851
2852 write_release_changelog(tmp.path(), "0.1.0");
2853 run_git(tmp.path(), &["add", "CHANGELOG.md"]);
2854 run_git(tmp.path(), &["commit", "-m", "add changelog"]);
2855 run_git(tmp.path(), &["tag", "v0.1.0"]);
2856
2857 let existing_tag = prepare_publish_plan(
2858 Some(tmp.path()),
2859 &options,
2860 "version = 1\n".to_string(),
2861 "fixture",
2862 )
2863 .unwrap_err()
2864 .to_string();
2865 assert!(existing_tag.contains("already exists locally"));
2866 }
2867
2868 #[test]
2869 fn publish_preflight_rejects_dirty_worktree() {
2870 let tmp = tempfile::tempdir().unwrap();
2871 write_publishable_package(tmp.path());
2872 write_release_changelog(tmp.path(), "0.1.0");
2873 let _remote = init_publishable_repo(tmp.path());
2874 fs::write(tmp.path().join("scratch.txt"), "dirty\n").unwrap();
2875 let index_path = Path::new("package-index/harn-package-index.toml");
2876 let options = PackagePublishOptions {
2877 dry_run: true,
2878 remote: "origin",
2879 index_repo: "burin-labs/harn-cloud",
2880 index_path,
2881 registry_name: None,
2882 skip_index_pr: false,
2883 registry: None,
2884 };
2885
2886 let error = prepare_publish_plan(
2887 Some(tmp.path()),
2888 &options,
2889 "version = 1\n".to_string(),
2890 "fixture",
2891 )
2892 .unwrap_err()
2893 .to_string();
2894
2895 assert!(error.contains("working tree must be clean"));
2896 assert!(error.contains("scratch.txt"));
2897 }
2898
2899 #[cfg(unix)]
2900 #[test]
2901 fn package_pack_does_not_follow_symlinked_files() {
2902 let tmp = tempfile::tempdir().unwrap();
2903 write_publishable_package(tmp.path());
2904 let outside = tempfile::NamedTempFile::new().unwrap();
2905 fs::write(outside.path(), "secret\n").unwrap();
2906 std::os::unix::fs::symlink(outside.path(), tmp.path().join("secret.txt")).unwrap();
2907
2908 let pack = pack_package_impl(Some(tmp.path()), None, true).unwrap();
2909
2910 assert!(
2911 !pack.files.contains(&"secret.txt".to_string()),
2912 "{:?}",
2913 pack.files
2914 );
2915 }
2916
2917 #[test]
2918 fn package_relative_paths_reject_windows_rooted_forms() {
2919 let tmp = tempfile::tempdir().unwrap();
2920 for rel_path in [
2921 "/repo/secret.harn",
2922 r"\repo\secret.harn",
2923 r"C:\repo\secret.harn",
2924 "C:secret.harn",
2925 r"\\server\share\secret.harn",
2926 r"..\secret.harn",
2927 r"lib\..\secret.harn",
2928 r"lib/..\secret.harn",
2929 ] {
2930 assert!(
2931 safe_package_relative_path(tmp.path(), rel_path).is_err(),
2932 "{rel_path:?} must not be accepted as package-relative"
2933 );
2934 }
2935 }
2936
2937 #[test]
2938 fn package_check_validates_tool_and_skill_exports() {
2939 let tmp = tempfile::tempdir().unwrap();
2940 write_publishable_package(tmp.path());
2941 fs::create_dir_all(tmp.path().join("skills/review")).unwrap();
2942 fs::write(
2943 tmp.path().join("harn.toml"),
2944 format!(
2945 r#"[package]
2946name = "acme-lib"
2947version = "0.1.0"
2948description = "Acme helpers"
2949license = "MIT"
2950repository = "https://github.com/acme/acme-lib"
2951harn = "{}"
2952docs_url = "docs/api.md"
2953permissions = ["tool:read_only"]
2954host_requirements = ["workspace.read_text"]
2955
2956[exports]
2957lib = "lib/main.harn"
2958
2959[[package.tools]]
2960name = "read-note"
2961module = "lib/main.harn"
2962symbol = "tools"
2963permissions = ["tool:read_only"]
2964
2965[package.tools.input_schema]
2966type = "object"
2967required = ["path"]
2968
2969[package.tools.annotations]
2970kind = "read"
2971side_effect_level = "read_only"
2972
2973[package.tools.annotations.arg_schema]
2974required = ["path"]
2975
2976[[package.skills]]
2977name = "review"
2978path = "skills/review"
2979permissions = ["skill:prompt"]
2980
2981[dependencies]
2982"#,
2983 current_harn_range_example()
2984 ),
2985 )
2986 .unwrap();
2987 fs::write(
2988 tmp.path().join("skills/review/SKILL.md"),
2989 "---\nname: review\nshort: Review changes\n---\n# Review\n",
2990 )
2991 .unwrap();
2992
2993 let report = check_package_impl(Some(tmp.path())).unwrap();
2994
2995 assert!(report.errors.is_empty(), "{:?}", report.errors);
2996 assert_eq!(report.tools[0].name, "read-note");
2997 assert_eq!(
2998 report.tools[0].host_requirements,
2999 vec!["workspace.read_text"]
3000 );
3001 assert_eq!(report.skills[0].name, "review");
3002 }
3003
3004 #[test]
3005 fn package_check_rejects_invalid_tool_schema_and_host_requirement() {
3006 let tmp = tempfile::tempdir().unwrap();
3007 write_publishable_package(tmp.path());
3008 fs::write(
3009 tmp.path().join(MANIFEST),
3010 format!(
3011 r#"[package]
3012name = "acme-lib"
3013version = "0.1.0"
3014description = "Acme helpers"
3015license = "MIT"
3016repository = "https://github.com/acme/acme-lib"
3017harn = "{}"
3018docs_url = "docs/api.md"
3019
3020[exports]
3021lib = "lib/main.harn"
3022
3023[[package.tools]]
3024name = "broken"
3025module = "lib/main.harn"
3026symbol = "tools"
3027host_requirements = ["workspace"]
3028
3029[package.tools.input_schema]
3030required = [1]
3031
3032[dependencies]
3033"#,
3034 current_harn_range_example()
3035 ),
3036 )
3037 .unwrap();
3038
3039 let report = check_package_impl(Some(tmp.path())).unwrap();
3040 let messages = report
3041 .errors
3042 .iter()
3043 .map(|diagnostic| diagnostic.message.as_str())
3044 .collect::<Vec<_>>()
3045 .join("\n");
3046
3047 assert!(messages.contains("capability.operation"));
3048 assert!(messages.contains("schema `required` must be a list of strings"));
3049 }
3050
3051 #[test]
3052 fn package_doctor_accepts_application_manifests_with_tool_exports() {
3053 let tmp = tempfile::tempdir().unwrap();
3054 fs::write(
3055 tmp.path().join(MANIFEST),
3056 r#"[package]
3057name = "acme-app"
3058
3059[[package.tools]]
3060name = "echo"
3061module = "tools.harn"
3062symbol = "tools"
3063
3064[package.tools.input_schema]
3065type = "object"
3066
3067[package.tools.annotations]
3068kind = "read"
3069side_effect_level = "read_only"
3070"#,
3071 )
3072 .unwrap();
3073 fs::write(tmp.path().join("tools.harn"), "pub fn tools() {}\n").unwrap();
3074 let workspace = TestWorkspace::new(tmp.path());
3075
3076 let report = doctor_packages_in(workspace.env()).unwrap();
3077
3078 assert!(report.ok, "{:?}", report.diagnostics);
3079 assert!(
3080 report
3081 .diagnostics
3082 .iter()
3083 .all(|diagnostic| diagnostic.code != "root-package-check"),
3084 "{:?}",
3085 report.diagnostics
3086 );
3087 }
3088
3089 #[test]
3090 fn package_list_reports_locked_tool_and_skill_exports() {
3091 let tmp = tempfile::tempdir().unwrap();
3092 fs::write(
3093 tmp.path().join(MANIFEST),
3094 r#"[package]
3095name = "consumer"
3096"#,
3097 )
3098 .unwrap();
3099 let lock = LockFile {
3100 packages: vec![LockEntry {
3101 name: "acme-tools".to_string(),
3102 source: "path+../acme-tools".to_string(),
3103 package_version: Some("0.1.0".to_string()),
3104 provenance: Some(
3105 "https://github.com/acme/acme-tools/releases/tag/v0.1.0".to_string(),
3106 ),
3107 exports: PackageLockExports {
3108 modules: vec![PackageLockExport {
3109 name: "tools".to_string(),
3110 path: Some("lib/tools.harn".to_string()),
3111 symbol: None,
3112 }],
3113 tools: vec![PackageLockExport {
3114 name: "echo".to_string(),
3115 path: Some("lib/tools.harn".to_string()),
3116 symbol: Some("tools".to_string()),
3117 }],
3118 skills: vec![PackageLockExport {
3119 name: "review".to_string(),
3120 path: Some("skills/review".to_string()),
3121 symbol: None,
3122 }],
3123 personas: Vec::new(),
3124 },
3125 permissions: vec!["tool:read_only".to_string()],
3126 host_requirements: vec!["workspace.read_text".to_string()],
3127 ..LockEntry::default()
3128 }],
3129 ..LockFile::default()
3130 };
3131 let lock_body = toml::to_string_pretty(&lock).unwrap();
3132 fs::write(tmp.path().join(LOCK_FILE), lock_body).unwrap();
3133 let workspace = TestWorkspace::new(tmp.path());
3134
3135 let report = list_packages_in(workspace.env()).unwrap();
3136
3137 assert_eq!(report.packages.len(), 1);
3138 let package = &report.packages[0];
3139 assert_eq!(package.name, "acme-tools");
3140 assert_eq!(
3141 package.provenance.as_deref(),
3142 Some("https://github.com/acme/acme-tools/releases/tag/v0.1.0")
3143 );
3144 assert_eq!(package.exports.tools[0].name, "echo");
3145 assert_eq!(package.exports.skills[0].name, "review");
3146 assert_eq!(package.permissions, vec!["tool:read_only"]);
3147 assert_eq!(package.host_requirements, vec!["workspace.read_text"]);
3148 }
3149
3150 fn write_release_changelog(root: &Path, version: &str) {
3151 fs::write(
3152 root.join("CHANGELOG.md"),
3153 format!("# Changelog\n\n## {version}\n\n- Initial release.\n"),
3154 )
3155 .unwrap();
3156 }
3157
3158 fn init_publishable_repo(root: &Path) -> tempfile::TempDir {
3159 let init = test_git_command(root)
3160 .args(["init", "-b", "main"])
3161 .output()
3162 .unwrap();
3163 if !init.status.success() {
3164 run_git(root, &["init"]);
3165 }
3166 run_git(root, &["config", "user.email", "tests@example.com"]);
3167 run_git(root, &["config", "user.name", "Harn Tests"]);
3168 run_git(root, &["config", "core.hooksPath", "/dev/null"]);
3169 run_git(root, &["add", "."]);
3170 run_git(root, &["commit", "-m", "initial"]);
3171
3172 let remote = tempfile::tempdir().unwrap();
3173 let bare = remote.path().join("origin.git");
3174 let output = test_git_command(root)
3175 .args(["init", "--bare", bare.to_string_lossy().as_ref()])
3176 .output()
3177 .unwrap();
3178 assert!(
3179 output.status.success(),
3180 "git init --bare failed: {}",
3181 String::from_utf8_lossy(&output.stderr)
3182 );
3183 run_git(
3184 root,
3185 &["remote", "add", "origin", bare.to_string_lossy().as_ref()],
3186 );
3187 remote
3188 }
3189}