Skip to main content

harn_cli/package/
manifest.rs

1use super::errors::PackageError;
2use super::*;
3mod check_config;
4pub use check_config::{CheckConfig, PreflightSeverity};
5pub use harn_modules::personas::{
6    PersonaAutonomyTier, PersonaManifestEntry, PersonaStageDecl, PersonaStageExit,
7    PersonaValidationError, ResolvedPersonaManifest,
8};
9
10#[derive(Debug, Clone, Deserialize)]
11pub struct Manifest {
12    pub package: Option<PackageInfo>,
13    #[serde(default)]
14    pub dependencies: HashMap<String, Dependency>,
15    #[serde(default)]
16    pub mcp: Vec<McpServerConfig>,
17    #[serde(default)]
18    pub check: CheckConfig,
19    #[serde(default)]
20    pub workspace: WorkspaceConfig,
21    /// `[registry]` table — lightweight package discovery index
22    /// configuration. The CLI also honors `HARN_PACKAGE_REGISTRY` and
23    /// `--registry` flags for one-off overrides.
24    #[serde(default)]
25    pub registry: PackageRegistryConfig,
26    /// `[skills]` table — per-project skill discovery configuration
27    /// (paths, lookup_order, disable).
28    #[serde(default)]
29    pub skills: SkillsConfig,
30    /// `[[skill.source]]` array-of-tables — declared skill sources
31    /// (filesystem, git, reserved registry).
32    #[serde(default)]
33    pub skill: SkillTables,
34    /// `[capabilities]` section — per-provider-per-model override of
35    /// the shipped capability matrix (`defer_loading`, `tool_search`,
36    /// `prompt_caching`, etc.). Entries under `[[capabilities.provider.<name>]]`
37    /// are prepended to the built-in rules for the same provider so
38    /// early adopters can flag proxied endpoints as supporting tool
39    /// search without waiting for a Harn release. See
40    /// `harn_vm::llm::capabilities` for the rule schema.
41    #[serde(default)]
42    pub capabilities: Option<harn_vm::llm::capabilities::CapabilitiesFile>,
43    /// Stable exported package modules. Keys are the logical import
44    /// suffixes (e.g. `providers/openai`) and values are package-root-
45    /// relative file paths. Consumers import them via `<package>/<key>`.
46    #[serde(default)]
47    pub exports: HashMap<String, String>,
48    /// `[llm]` section — packaged provider definitions, aliases,
49    /// inference rules, tier rules, and model defaults. Uses the same
50    /// schema as `providers.toml`, but merges into the current run
51    /// instead of replacing the global config file.
52    #[serde(default)]
53    pub llm: harn_vm::llm_config::ProvidersConfig,
54    /// `[[hooks]]` array-of-tables — declarative runtime hooks installed
55    /// once per process/thread before execution starts. Matches the
56    /// manifest-extension ABI shape added by `[exports]` / `[llm]`, but
57    /// the handlers themselves live in Harn modules.
58    #[serde(default)]
59    pub hooks: Vec<HookConfig>,
60    /// `[[triggers]]` array-of-tables — declarative event-driven trigger
61    /// registrations that resolve local handlers and predicates from Harn
62    /// modules at load time and preserve remote URI schemes for later
63    /// dispatcher work.
64    #[serde(default)]
65    pub triggers: Vec<TriggerManifestEntry>,
66    /// `[[handoff_routes]]` array-of-tables — declarative handoff route data.
67    /// Route selection stays in Harn stdlib/persona code; the Rust manifest
68    /// loader makes these tenant routes available to that code.
69    #[serde(default)]
70    pub handoff_routes: Vec<harn_vm::HandoffRouteConfig>,
71    /// `[[providers]]` array-of-tables — provider-specific connector
72    /// overrides used by the orchestrator to load either builtin Rust
73    /// connectors or `.harn` modules as connector implementations.
74    #[serde(default)]
75    pub providers: Vec<ProviderManifestEntry>,
76    /// `[[personas]]` array-of-tables — durable, non-executing agent role
77    /// manifests. Personas bind an entry workflow to tools, capabilities,
78    /// autonomy, budgets, receipts, handoffs, evals, and rollout metadata.
79    #[serde(default)]
80    pub personas: Vec<PersonaManifestEntry>,
81    /// `[connector_contract]` table — deterministic package-local fixtures
82    /// consumed by `harn connector check` for pure-Harn connector packages.
83    #[serde(default, alias = "connector-contract")]
84    pub connector_contract: ConnectorContractConfig,
85    /// `[orchestrator]` table — listener-level controls shared by
86    /// manifest-driven ingress surfaces.
87    #[serde(default)]
88    pub orchestrator: OrchestratorConfig,
89    /// `[rules]` table — `sgconfig`-style structural-rule discovery. Lists the
90    /// directories `harn scan` / `harn codemod` load rules from when no
91    /// explicit `--rule`/`--rule-pack` is given.
92    #[serde(default)]
93    pub rules: RulesConfig,
94    /// `[[contributes]]` array-of-tables — host-surface extension
95    /// contributions (editor languages, preview panes, build profiles,
96    /// commands, themes, …). Harn treats `kind` as a host-owned, namespaced
97    /// string and validates only the envelope plus that each contribution's
98    /// declared `scopes` are covered by `[package].permissions`; the host
99    /// (e.g. a host) interprets the kind-specific payload. New contribution
100    /// kinds therefore need no Harn release. This is the editor-layer twin of
101    /// the agent-layer blocks (`[[providers]]`, `[[personas]]`, `[[hooks]]`):
102    /// one signed package may populate any mix of both.
103    #[serde(default)]
104    pub contributes: Vec<ContributionEntry>,
105}
106
107/// A single `[[contributes]]` host-surface contribution.
108///
109/// ```toml
110/// [[contributes]]
111/// kind = "editor.language"          # host-owned namespaced vocabulary
112/// id = "latex"                      # unique within the package
113/// title = "LaTeX"
114/// when = "*.tex"                    # optional activation predicate (host-interpreted)
115/// scopes = ["workspace:read_text"]  # MUST be a subset of [package].permissions
116/// platforms = ["macos", "linux"]    # optional support/parity matrix; empty = all
117/// # kind-specific keys are captured into `config` and interpreted by the host:
118/// languageId = "latex"
119/// extensions = [".tex", ".sty"]
120/// ```
121#[derive(Debug, Clone, Deserialize, Serialize)]
122pub struct ContributionEntry {
123    /// Host-owned, namespaced contribution kind (e.g. `editor.language`,
124    /// `editor.preview`, `build.profile`, `editor.command`, `editor.theme`).
125    /// Harn does not enumerate kinds — new ones need no release; it only
126    /// requires the value be namespaced (`segment(.segment)+`).
127    pub kind: String,
128    /// Stable identifier, unique across the package's contributions.
129    pub id: String,
130    #[serde(default)]
131    pub title: Option<String>,
132    /// Optional activation predicate the host interprets (a glob, a
133    /// `languageId`, or a host-defined expression). Absent = always available.
134    #[serde(default)]
135    pub when: Option<String>,
136    /// Capability scopes this contribution exercises. Every entry MUST be
137    /// declared in `[package].permissions`; validation fails closed otherwise.
138    #[serde(default)]
139    pub scopes: Vec<String>,
140    /// Optional support/parity matrix — which surfaces/platforms this
141    /// contribution targets (e.g. `macos`, `linux`, `windows`, `ide`, `tui`).
142    /// Empty means "all".
143    #[serde(default)]
144    pub platforms: Vec<String>,
145    /// Kind-specific payload, captured verbatim and interpreted by the host.
146    #[serde(flatten)]
147    pub config: BTreeMap<String, toml::Value>,
148}
149
150impl ContributionEntry {
151    /// `true` when `kind` is a non-empty, dot-namespaced identifier such as
152    /// `editor.language`. Single-segment kinds are rejected so third parties
153    /// cannot squat unprefixed names.
154    pub fn has_namespaced_kind(&self) -> bool {
155        let mut segments = 0usize;
156        for segment in self.kind.split('.') {
157            if segment.is_empty()
158                || !segment
159                    .chars()
160                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
161                || !segment.starts_with(|c: char| c.is_ascii_lowercase())
162            {
163                return false;
164            }
165            segments += 1;
166        }
167        segments >= 2
168    }
169}
170
171/// `[rules]` table — project-local structural-rule discovery (#2843).
172///
173/// ```toml
174/// [rules]
175/// ruleDirs = ["rules", "vendor/rules"]
176/// utilDirs = ["rules/util"]
177/// testConfigs = ["rules/tests"]
178/// nativeRuleDirs = ["target/harn-native-rules"]
179/// ```
180///
181/// Paths are resolved relative to the manifest's directory.
182#[derive(Debug, Clone, Default, Deserialize)]
183pub struct RulesConfig {
184    /// Directories of top-level rule `*.toml` files to load.
185    #[serde(default, alias = "rule-dirs", alias = "ruleDirs")]
186    pub rule_dirs: Vec<String>,
187    /// Directories of utility-rule `*.toml` files (referenced via `matches`).
188    #[serde(default, alias = "util-dirs", alias = "utilDirs")]
189    pub util_dirs: Vec<String>,
190    /// Directories holding rule-test fixtures (for `harn rule test`).
191    #[serde(default, alias = "test-configs", alias = "testConfigs")]
192    pub test_configs: Vec<String>,
193    /// Trusted directories of native lint-rule dynamic libraries.
194    #[serde(
195        default,
196        alias = "native-rule-dirs",
197        alias = "nativeRuleDirs",
198        alias = "native_rule_dirs"
199    )]
200    pub native_rule_dirs: Vec<String>,
201}
202
203#[derive(Debug, Clone, Default, Deserialize)]
204pub struct OrchestratorConfig {
205    #[serde(default, alias = "allowed-origins")]
206    pub allowed_origins: Vec<String>,
207    #[serde(default, alias = "max-body-bytes")]
208    pub max_body_bytes: Option<usize>,
209    #[serde(default)]
210    pub budget: OrchestratorBudgetSpec,
211    #[serde(default)]
212    pub drain: OrchestratorDrainConfig,
213    #[serde(default)]
214    pub pumps: OrchestratorPumpConfig,
215}
216
217#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
218pub struct OrchestratorBudgetSpec {
219    #[serde(default)]
220    pub daily_cost_usd: Option<f64>,
221    #[serde(default)]
222    pub hourly_cost_usd: Option<f64>,
223}
224
225#[derive(Debug, Clone, Deserialize)]
226pub struct OrchestratorDrainConfig {
227    #[serde(default = "default_orchestrator_drain_max_items", alias = "max-items")]
228    pub max_items: usize,
229    #[serde(
230        default = "default_orchestrator_drain_deadline_seconds",
231        alias = "deadline-seconds"
232    )]
233    pub deadline_seconds: u64,
234}
235
236impl Default for OrchestratorDrainConfig {
237    fn default() -> Self {
238        Self {
239            max_items: default_orchestrator_drain_max_items(),
240            deadline_seconds: default_orchestrator_drain_deadline_seconds(),
241        }
242    }
243}
244
245pub(crate) fn default_orchestrator_drain_max_items() -> usize {
246    1024
247}
248
249pub(crate) fn default_orchestrator_drain_deadline_seconds() -> u64 {
250    30
251}
252
253#[derive(Debug, Clone, Deserialize)]
254pub struct OrchestratorPumpConfig {
255    #[serde(
256        default = "default_orchestrator_pump_max_outstanding",
257        alias = "max-outstanding"
258    )]
259    pub max_outstanding: usize,
260}
261
262impl Default for OrchestratorPumpConfig {
263    fn default() -> Self {
264        Self {
265            max_outstanding: default_orchestrator_pump_max_outstanding(),
266        }
267    }
268}
269
270pub(crate) fn default_orchestrator_pump_max_outstanding() -> usize {
271    64
272}
273
274#[derive(Debug, Clone, Deserialize)]
275pub struct HookConfig {
276    pub event: harn_vm::orchestration::HookEvent,
277    #[serde(default = "default_hook_pattern")]
278    pub pattern: String,
279    pub handler: String,
280}
281
282pub(crate) fn default_hook_pattern() -> String {
283    "*".to_string()
284}
285
286#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
287pub struct TriggerManifestEntry {
288    pub id: String,
289    #[serde(default)]
290    pub kind: Option<TriggerKind>,
291    #[serde(default)]
292    pub provider: Option<harn_vm::ProviderId>,
293    #[serde(default, alias = "tier")]
294    pub autonomy_tier: harn_vm::AutonomyTier,
295    #[serde(default, rename = "match")]
296    pub match_: Option<TriggerMatchExpr>,
297    #[serde(default)]
298    pub sources: Vec<TriggerSourceManifestEntry>,
299    #[serde(default)]
300    pub when: Option<String>,
301    #[serde(default)]
302    pub when_budget: Option<TriggerWhenBudgetSpec>,
303    pub handler: String,
304    #[serde(default)]
305    pub dedupe_key: Option<String>,
306    #[serde(default)]
307    pub retry: TriggerRetrySpec,
308    #[serde(default)]
309    pub priority: Option<TriggerPriorityField>,
310    #[serde(default)]
311    pub budget: TriggerBudgetSpec,
312    #[serde(default)]
313    pub concurrency: Option<TriggerConcurrencyManifestSpec>,
314    #[serde(default)]
315    pub throttle: Option<TriggerThrottleManifestSpec>,
316    #[serde(default)]
317    pub rate_limit: Option<TriggerRateLimitManifestSpec>,
318    #[serde(default)]
319    pub debounce: Option<TriggerDebounceManifestSpec>,
320    #[serde(default)]
321    pub singleton: Option<TriggerSingletonManifestSpec>,
322    #[serde(default)]
323    pub batch: Option<TriggerBatchManifestSpec>,
324    #[serde(default)]
325    pub window: Option<TriggerStreamWindowManifestSpec>,
326    #[serde(default, alias = "dlq-alerts")]
327    pub dlq_alerts: Vec<TriggerDlqAlertManifestSpec>,
328    #[serde(default)]
329    pub secrets: BTreeMap<String, String>,
330    #[serde(default)]
331    pub filter: Option<String>,
332    #[serde(flatten, default)]
333    pub kind_specific: BTreeMap<String, toml::Value>,
334}
335
336#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
337pub struct TriggerSourceManifestEntry {
338    #[serde(default)]
339    pub id: Option<String>,
340    pub kind: TriggerKind,
341    pub provider: harn_vm::ProviderId,
342    #[serde(default, rename = "match")]
343    pub match_: Option<TriggerMatchExpr>,
344    #[serde(default)]
345    pub dedupe_key: Option<String>,
346    #[serde(default)]
347    pub retry: Option<TriggerRetrySpec>,
348    #[serde(default)]
349    pub priority: Option<TriggerPriorityField>,
350    #[serde(default)]
351    pub budget: Option<TriggerBudgetSpec>,
352    #[serde(default)]
353    pub concurrency: Option<TriggerConcurrencyManifestSpec>,
354    #[serde(default)]
355    pub throttle: Option<TriggerThrottleManifestSpec>,
356    #[serde(default)]
357    pub rate_limit: Option<TriggerRateLimitManifestSpec>,
358    #[serde(default)]
359    pub debounce: Option<TriggerDebounceManifestSpec>,
360    #[serde(default)]
361    pub singleton: Option<TriggerSingletonManifestSpec>,
362    #[serde(default)]
363    pub batch: Option<TriggerBatchManifestSpec>,
364    #[serde(default)]
365    pub window: Option<TriggerStreamWindowManifestSpec>,
366    #[serde(default)]
367    pub secrets: BTreeMap<String, String>,
368    #[serde(default)]
369    pub filter: Option<String>,
370    #[serde(flatten, default)]
371    pub kind_specific: BTreeMap<String, toml::Value>,
372}
373
374#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
375#[serde(rename_all = "kebab-case")]
376pub enum TriggerKind {
377    Webhook,
378    Cron,
379    Poll,
380    Stream,
381    Predicate,
382    A2aPush,
383}
384
385#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
386pub struct TriggerMatchExpr {
387    #[serde(default)]
388    pub events: Vec<String>,
389    #[serde(flatten, default)]
390    pub extra: BTreeMap<String, toml::Value>,
391}
392
393#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
394pub struct TriggerRetrySpec {
395    #[serde(default)]
396    pub max: u32,
397    #[serde(default)]
398    pub backoff: TriggerRetryBackoff,
399    #[serde(default = "default_trigger_retention_days")]
400    pub retention_days: u32,
401}
402
403#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
404#[serde(rename_all = "kebab-case")]
405pub enum TriggerRetryBackoff {
406    #[default]
407    Immediate,
408    Svix,
409}
410
411pub(crate) fn default_trigger_retention_days() -> u32 {
412    harn_vm::DEFAULT_INBOX_RETENTION_DAYS
413}
414
415impl Default for TriggerRetrySpec {
416    fn default() -> Self {
417        Self {
418            max: 0,
419            backoff: TriggerRetryBackoff::default(),
420            retention_days: default_trigger_retention_days(),
421        }
422    }
423}
424
425#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
426#[serde(rename_all = "lowercase")]
427pub enum TriggerDispatchPriority {
428    High,
429    #[default]
430    Normal,
431    Low,
432}
433
434#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
435#[serde(untagged)]
436pub enum TriggerPriorityField {
437    Dispatch(TriggerDispatchPriority),
438    Flow(TriggerPriorityManifestSpec),
439}
440
441#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
442pub struct TriggerBudgetSpec {
443    #[serde(default)]
444    pub max_cost_usd: Option<f64>,
445    #[serde(default, alias = "tokens_max")]
446    pub max_tokens: Option<u64>,
447    #[serde(default)]
448    pub daily_cost_usd: Option<f64>,
449    #[serde(default)]
450    pub hourly_cost_usd: Option<f64>,
451    #[serde(default)]
452    pub max_autonomous_decisions_per_hour: Option<u64>,
453    #[serde(default)]
454    pub max_autonomous_decisions_per_day: Option<u64>,
455    #[serde(default)]
456    pub max_concurrent: Option<u32>,
457    #[serde(default)]
458    pub on_budget_exhausted: harn_vm::TriggerBudgetExhaustionStrategy,
459}
460
461#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
462pub struct TriggerWhenBudgetSpec {
463    #[serde(default)]
464    pub max_cost_usd: Option<f64>,
465    #[serde(default)]
466    pub tokens_max: Option<u64>,
467    #[serde(default)]
468    pub timeout: Option<String>,
469}
470
471#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
472pub struct TriggerConcurrencyManifestSpec {
473    #[serde(default)]
474    pub key: Option<String>,
475    pub max: u32,
476}
477
478#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
479pub struct TriggerThrottleManifestSpec {
480    #[serde(default)]
481    pub key: Option<String>,
482    pub period: String,
483    pub max: u32,
484}
485
486#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
487pub struct TriggerRateLimitManifestSpec {
488    #[serde(default)]
489    pub key: Option<String>,
490    pub period: String,
491    pub max: u32,
492}
493
494#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
495pub struct TriggerDebounceManifestSpec {
496    pub key: String,
497    pub period: String,
498}
499
500#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
501pub struct TriggerSingletonManifestSpec {
502    #[serde(default)]
503    pub key: Option<String>,
504}
505
506#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
507pub struct TriggerBatchManifestSpec {
508    #[serde(default)]
509    pub key: Option<String>,
510    pub size: u32,
511    pub timeout: String,
512}
513
514#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
515pub struct TriggerPriorityManifestSpec {
516    pub key: String,
517    #[serde(default)]
518    pub order: Vec<String>,
519}
520
521#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
522#[serde(rename_all = "kebab-case")]
523pub enum TriggerStreamWindowMode {
524    Tumbling,
525    Sliding,
526    Session,
527}
528
529#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
530pub struct TriggerStreamWindowManifestSpec {
531    pub mode: TriggerStreamWindowMode,
532    #[serde(default)]
533    pub key: Option<String>,
534    #[serde(default)]
535    pub size: Option<String>,
536    #[serde(default)]
537    pub every: Option<String>,
538    #[serde(default)]
539    pub gap: Option<String>,
540    #[serde(default)]
541    pub max_items: Option<u32>,
542}
543
544#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
545pub struct TriggerDlqAlertManifestSpec {
546    #[serde(default)]
547    pub destinations: Vec<TriggerDlqAlertDestination>,
548    #[serde(default)]
549    pub threshold: TriggerDlqAlertThreshold,
550}
551
552#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
553pub struct TriggerDlqAlertThreshold {
554    #[serde(default, alias = "entries-in-1h")]
555    pub entries_in_1h: Option<u32>,
556    #[serde(default, alias = "percent-of-dispatches")]
557    pub percent_of_dispatches: Option<f64>,
558}
559
560#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
561#[serde(tag = "kind", rename_all = "snake_case")]
562pub enum TriggerDlqAlertDestination {
563    Slack {
564        channel: String,
565        #[serde(default)]
566        webhook_url_env: Option<String>,
567    },
568    Email {
569        address: String,
570    },
571    Webhook {
572        url: String,
573        #[serde(default)]
574        headers: BTreeMap<String, String>,
575    },
576}
577
578impl TriggerDlqAlertDestination {
579    pub fn label(&self) -> String {
580        match self {
581            Self::Slack { channel, .. } => format!("slack:{channel}"),
582            Self::Email { address } => format!("email:{address}"),
583            Self::Webhook { url, .. } => format!("webhook:{url}"),
584        }
585    }
586}
587
588#[derive(Debug, Clone, PartialEq, Eq)]
589pub enum TriggerHandlerUri {
590    Local(TriggerFunctionRef),
591    A2a {
592        target: String,
593        allow_cleartext: bool,
594    },
595    Worker {
596        queue: String,
597    },
598    Persona {
599        name: String,
600    },
601    EvalPack {
602        target: String,
603    },
604}
605
606#[derive(Debug, Clone, PartialEq, Eq)]
607pub struct TriggerFunctionRef {
608    pub raw: String,
609    pub module_name: Option<String>,
610    pub function_name: String,
611}
612
613/// `[skills]` table body.
614#[derive(Debug, Default, Clone, Deserialize)]
615#[allow(dead_code)] // `defaults` is parsed per harn#73; default application remains staged.
616pub struct SkillsConfig {
617    /// Additional filesystem roots to scan. Each entry may be a
618    /// literal directory or a glob (`packages/*/skills`). Resolved
619    /// relative to the directory holding harn.toml.
620    #[serde(default)]
621    pub paths: Vec<String>,
622    /// Override priority order. Values are layer labels —
623    /// `cli`, `env`, `project`, `manifest`, `user`, `package`,
624    /// `system`, `host`. Unlisted layers fall through to default
625    /// priority after listed ones.
626    #[serde(default)]
627    pub lookup_order: Vec<String>,
628    /// Disable entire layers. Same label set as `lookup_order`.
629    #[serde(default)]
630    pub disable: Vec<String>,
631    /// Optional remote registry base URL used to resolve
632    /// `<fingerprint>.pub` when a signer is not installed locally.
633    #[serde(default)]
634    pub signer_registry_url: Option<String>,
635    /// `[skills.defaults]` inline sub-table — applied to every
636    /// discovered skill when the field is unset in its SKILL.md
637    /// frontmatter.
638    #[serde(default)]
639    pub defaults: SkillDefaults,
640}
641
642#[derive(Debug, Default, Clone, Deserialize)]
643#[allow(dead_code)] // Parsed per harn#73; loader default application is still staged.
644pub struct SkillDefaults {
645    #[serde(default)]
646    pub tool_search: Option<String>,
647    #[serde(default)]
648    pub always_loaded: Vec<String>,
649}
650
651/// Container for `[[skill.source]]` array-of-tables.
652#[derive(Debug, Default, Clone, Deserialize)]
653pub struct SkillTables {
654    #[serde(default, rename = "source")]
655    pub sources: Vec<SkillSourceEntry>,
656}
657
658/// One `[[skill.source]]` entry. The `registry` variant is accepted
659/// for forward-compat but inert — see issue #73 and `docs/src/skills.md`
660/// for the marketplace timeline.
661#[derive(Debug, Clone, Deserialize)]
662#[serde(tag = "type", rename_all = "lowercase")]
663#[allow(dead_code)] // Git/registry skill sources are manifest-reserved by harn#73.
664pub enum SkillSourceEntry {
665    Fs {
666        path: String,
667        #[serde(default)]
668        namespace: Option<String>,
669    },
670    Git {
671        url: String,
672        #[serde(default)]
673        tag: Option<String>,
674        #[serde(default)]
675        namespace: Option<String>,
676    },
677    Registry {
678        #[serde(default)]
679        url: Option<String>,
680        #[serde(default)]
681        name: Option<String>,
682    },
683}
684
685#[derive(Debug, Default, Clone, Deserialize)]
686pub struct WorkspaceConfig {
687    /// Directory or file globs (repo-relative) that `harn check --workspace`
688    /// walks to collect the full pipeline tree in one invocation.
689    #[serde(default)]
690    pub pipelines: Vec<String>,
691}
692
693#[derive(Debug, Default, Clone, Deserialize)]
694pub struct PackageRegistryConfig {
695    /// URL or filesystem path to a TOML package index.
696    #[serde(default)]
697    pub url: Option<String>,
698}
699
700#[derive(Debug, Clone, Deserialize)]
701pub struct McpServerConfig {
702    pub name: String,
703    #[serde(default)]
704    pub transport: Option<String>,
705    #[serde(default)]
706    pub command: String,
707    #[serde(default)]
708    pub args: Vec<String>,
709    #[serde(default)]
710    pub env: HashMap<String, String>,
711    #[serde(default)]
712    pub url: String,
713    #[serde(default)]
714    pub auth_token: Option<String>,
715    #[serde(default)]
716    pub token_exchange: Option<harn_vm::mcp_oauth::McpTokenExchangeConfig>,
717    #[serde(default)]
718    pub auth: Option<McpAuthConfig>,
719    #[serde(default)]
720    pub client_id: Option<String>,
721    #[serde(default)]
722    pub client_secret: Option<String>,
723    #[serde(default)]
724    pub scopes: Option<String>,
725    #[serde(default)]
726    pub protocol_version: Option<String>,
727    #[serde(default)]
728    pub proxy_server_name: Option<String>,
729    /// When `true`, the server is NOT booted up-front. It boots on the
730    /// first `mcp_call` or on skill activation that declares it in
731    /// `requires_mcp`. See harn#75.
732    #[serde(default)]
733    pub lazy: bool,
734    /// Optional pointer to a Server Card — either an HTTP(S) URL or a
735    /// local filesystem path. When set, `mcp_server_card("name")` reads
736    /// the card from this source (cached per-process with a TTL).
737    #[serde(default)]
738    pub card: Option<String>,
739    /// How long (milliseconds) to keep a lazy server's process alive
740    /// after its last binder releases. 0 / unset → disconnect
741    /// immediately. Ignored for non-lazy servers.
742    #[serde(default, alias = "keep-alive-ms", alias = "keep_alive")]
743    pub keep_alive_ms: Option<u64>,
744}
745
746#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
747pub struct McpAuthConfig {
748    #[serde(default)]
749    pub mode: Option<harn_vm::mcp_auth::OAuthClientAuthMode>,
750    #[serde(default, alias = "client-id")]
751    pub client_id: Option<String>,
752    #[serde(
753        default,
754        alias = "client_secret_id",
755        alias = "client-secret-id",
756        alias = "client_secret_ref",
757        alias = "client-secret-ref"
758    )]
759    pub client_secret_id: Option<String>,
760    #[serde(
761        default,
762        alias = "secret_id",
763        alias = "secret-id",
764        alias = "token-secret-id"
765    )]
766    pub secret_id: Option<String>,
767    #[serde(default, alias = "scope")]
768    pub scopes: Option<String>,
769    #[serde(default, alias = "token_auth_method", alias = "token-auth-method")]
770    pub token_endpoint_auth_method: Option<String>,
771}
772
773#[derive(Debug, Clone, Deserialize)]
774#[allow(dead_code)] // Package metadata feeds authoring/publish validation tracked in harn#471.
775pub struct PackageInfo {
776    pub name: Option<String>,
777    pub version: Option<String>,
778    #[serde(default)]
779    pub evals: Vec<String>,
780    #[serde(default)]
781    pub description: Option<String>,
782    #[serde(default)]
783    pub license: Option<String>,
784    #[serde(default)]
785    pub repository: Option<String>,
786    #[serde(default, alias = "harn_version", alias = "harn_version_range")]
787    pub harn: Option<String>,
788    #[serde(default)]
789    pub docs_url: Option<String>,
790    #[serde(default)]
791    pub provenance: Option<String>,
792    /// Human-facing publisher / developer name shown in marketplace surfaces.
793    #[serde(default)]
794    pub publisher: Option<String>,
795    /// Publisher contact (email or URL) shown alongside the publisher name.
796    #[serde(default)]
797    pub contact: Option<String>,
798    /// Optional ISO-8601 authoring date. Mutation dates are better derived
799    /// from the registry/VCS, but a declared creation date is allowed.
800    #[serde(default)]
801    pub created: Option<String>,
802    #[serde(default)]
803    pub permissions: Vec<String>,
804    #[serde(default, alias = "host-requirements")]
805    pub host_requirements: Vec<String>,
806    #[serde(default)]
807    pub tools: Vec<PackageToolExport>,
808    #[serde(default)]
809    pub skills: Vec<PackageSkillExport>,
810}
811
812#[derive(Debug, Clone, Deserialize, PartialEq)]
813pub struct PackageToolExport {
814    pub name: String,
815    pub module: String,
816    #[serde(default = "default_package_tool_symbol")]
817    pub symbol: String,
818    #[serde(default)]
819    pub description: Option<String>,
820    #[serde(default)]
821    pub permissions: Vec<String>,
822    #[serde(default, alias = "host-requirements")]
823    pub host_requirements: Vec<String>,
824    #[serde(default, alias = "input-schema")]
825    pub input_schema: Option<toml::Value>,
826    #[serde(default, alias = "output-schema")]
827    pub output_schema: Option<toml::Value>,
828    #[serde(default)]
829    pub annotations: BTreeMap<String, toml::Value>,
830}
831
832pub(crate) fn default_package_tool_symbol() -> String {
833    "tools".to_string()
834}
835
836#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
837pub struct PackageSkillExport {
838    pub name: String,
839    pub path: String,
840    #[serde(default)]
841    pub description: Option<String>,
842    #[serde(default)]
843    pub permissions: Vec<String>,
844    #[serde(default, alias = "host-requirements")]
845    pub host_requirements: Vec<String>,
846}
847
848#[derive(Debug, Clone, Deserialize)]
849#[serde(untagged)]
850pub enum Dependency {
851    Table(Box<DepTable>),
852    Path(String),
853}
854
855#[derive(Debug, Clone, Default, Deserialize)]
856pub struct DepTable {
857    pub git: Option<String>,
858    #[serde(default, alias = "archive-url", alias = "archive_url")]
859    pub archive: Option<String>,
860    pub tag: Option<String>,
861    pub rev: Option<String>,
862    pub branch: Option<String>,
863    pub version: Option<String>,
864    pub path: Option<String>,
865    pub package: Option<String>,
866    #[serde(default)]
867    pub checksum: Option<String>,
868    /// Registry index URL/path the dependency was originally added from.
869    /// Persisted in the manifest so registry provenance survives
870    /// round-trips and the lockfile can compare against the registry's
871    /// latest version.
872    #[serde(default)]
873    pub registry: Option<String>,
874    /// Registry-side package name (e.g. `@burin/notion-sdk`). May differ
875    /// from the alias and from the git URL's repo name.
876    #[serde(default, alias = "registry-name")]
877    pub registry_name: Option<String>,
878    /// Registry version specifier the dependency was added against.
879    #[serde(default, alias = "registry-version")]
880    pub registry_version: Option<String>,
881    /// Immutable commit recorded by registry v2 for a Git-backed version.
882    #[serde(default, alias = "registry-commit")]
883    pub registry_commit: Option<String>,
884    /// Registry-v2 evidence URL for the selected published version.
885    #[serde(default, alias = "registry-provenance")]
886    pub registry_provenance: Option<String>,
887}
888
889impl Dependency {
890    pub(crate) fn git_url(&self) -> Option<&str> {
891        match self {
892            Dependency::Table(t) => t.git.as_deref(),
893            Dependency::Path(_) => None,
894        }
895    }
896
897    pub(crate) fn archive_url(&self) -> Option<&str> {
898        match self {
899            Dependency::Table(t) => t.archive.as_deref(),
900            Dependency::Path(_) => None,
901        }
902    }
903
904    pub(crate) fn rev(&self) -> Option<&str> {
905        match self {
906            Dependency::Table(t) => t.rev.as_deref(),
907            Dependency::Path(_) => None,
908        }
909    }
910
911    pub(crate) fn tag(&self) -> Option<&str> {
912        match self {
913            Dependency::Table(t) => t.tag.as_deref(),
914            Dependency::Path(_) => None,
915        }
916    }
917
918    pub(crate) fn branch(&self) -> Option<&str> {
919        match self {
920            Dependency::Table(t) => t.branch.as_deref(),
921            Dependency::Path(_) => None,
922        }
923    }
924
925    pub(crate) fn version(&self) -> Option<&str> {
926        match self {
927            Dependency::Table(t) => t.version.as_deref(),
928            Dependency::Path(_) => None,
929        }
930    }
931
932    pub(crate) fn requires_git(&self) -> bool {
933        self.git_url().is_some()
934    }
935
936    pub(crate) fn local_path(&self) -> Option<&str> {
937        match self {
938            Dependency::Table(t) => t.path.as_deref(),
939            Dependency::Path(p) => Some(p.as_str()),
940        }
941    }
942}
943
944pub(crate) fn validate_package_alias(alias: &str) -> Result<(), PackageError> {
945    if harn_modules::package_snapshot::is_valid_package_name(alias) {
946        Ok(())
947    } else {
948        Err(PackageError::Validation(format!(
949            "invalid dependency alias {alias:?}; use ASCII letters, numbers, '.', '_' or '-'"
950        )))
951    }
952}
953
954pub(crate) fn toml_string_literal(value: &str) -> Result<String, PackageError> {
955    use std::fmt::Write as _;
956
957    let mut encoded = String::with_capacity(value.len() + 2);
958    encoded.push('"');
959    for ch in value.chars() {
960        match ch {
961            '\u{08}' => encoded.push_str("\\b"),
962            '\t' => encoded.push_str("\\t"),
963            '\n' => encoded.push_str("\\n"),
964            '\u{0C}' => encoded.push_str("\\f"),
965            '\r' => encoded.push_str("\\r"),
966            '"' => encoded.push_str("\\\""),
967            '\\' => encoded.push_str("\\\\"),
968            ch if ch <= '\u{1F}' || ch == '\u{7F}' => {
969                write!(&mut encoded, "\\u{:04X}", ch as u32).map_err(|error| {
970                    PackageError::Manifest(format!("failed to encode TOML string: {error}"))
971                })?;
972            }
973            ch => encoded.push(ch),
974        }
975    }
976    encoded.push('"');
977    Ok(encoded)
978}
979#[derive(Debug, Default, Clone)]
980pub struct RuntimeExtensions {
981    pub root_manifest: Option<Manifest>,
982    pub root_manifest_path: Option<PathBuf>,
983    pub root_manifest_dir: Option<PathBuf>,
984    pub(crate) runtime_personas: Vec<ResolvedRuntimePersona>,
985    pub llm: Option<harn_vm::llm_config::ProvidersConfig>,
986    pub capabilities: Option<harn_vm::llm::capabilities::CapabilitiesFile>,
987    pub hooks: Vec<ResolvedHookConfig>,
988    pub triggers: Vec<ResolvedTriggerConfig>,
989    pub handoff_routes: Vec<harn_vm::HandoffRouteConfig>,
990    pub provider_connectors: Vec<ResolvedProviderConnectorConfig>,
991}
992
993#[derive(Debug, Clone, Deserialize)]
994pub struct ProviderManifestEntry {
995    pub id: harn_vm::ProviderId,
996    pub connector: ProviderConnectorManifest,
997    #[serde(default)]
998    pub oauth: Option<ProviderOAuthManifest>,
999    #[serde(default)]
1000    pub setup: Option<ProviderSetupManifest>,
1001    #[serde(default)]
1002    pub capabilities: ConnectorCapabilities,
1003}
1004
1005#[derive(Debug, Clone, Deserialize)]
1006pub struct ProviderConnectorManifest {
1007    #[serde(default)]
1008    pub harn: Option<String>,
1009    #[serde(default)]
1010    pub rust: Option<String>,
1011}
1012
1013#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
1014pub struct ProviderOAuthManifest {
1015    #[serde(default, alias = "auth_url", alias = "authorization-endpoint")]
1016    pub authorization_endpoint: Option<String>,
1017    #[serde(default, alias = "token_url", alias = "token-endpoint")]
1018    pub token_endpoint: Option<String>,
1019    #[serde(default, alias = "registration_url", alias = "registration-endpoint")]
1020    pub registration_endpoint: Option<String>,
1021    #[serde(default)]
1022    pub resource: Option<String>,
1023    #[serde(default, alias = "scope")]
1024    pub scopes: Option<String>,
1025    #[serde(default, alias = "client-id")]
1026    pub client_id: Option<String>,
1027    #[serde(default, alias = "client-secret")]
1028    pub client_secret: Option<String>,
1029    #[serde(default, alias = "token_auth_method", alias = "token-auth-method")]
1030    pub token_endpoint_auth_method: Option<String>,
1031}
1032
1033#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1034pub struct ProviderSetupManifest {
1035    #[serde(default, alias = "auth-type")]
1036    pub auth_type: Option<String>,
1037    #[serde(default)]
1038    pub flow: Option<String>,
1039    #[serde(default, alias = "required-scopes", alias = "scopes")]
1040    pub required_scopes: Vec<String>,
1041    #[serde(default, alias = "required-secrets")]
1042    pub required_secrets: Vec<String>,
1043    #[serde(default, alias = "setup-command")]
1044    pub setup_command: Vec<String>,
1045    #[serde(default, alias = "validation-command")]
1046    pub validation_command: Vec<String>,
1047    #[serde(default, alias = "health-checks")]
1048    pub health_checks: Vec<ConnectorHealthCheckManifest>,
1049    #[serde(default)]
1050    pub recovery: ConnectorRecoveryCopy,
1051    #[serde(flatten, default)]
1052    pub extra: BTreeMap<String, toml::Value>,
1053}
1054
1055#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1056pub struct ConnectorHealthCheckManifest {
1057    pub id: String,
1058    pub kind: String,
1059    #[serde(default)]
1060    pub command: Vec<String>,
1061    #[serde(default)]
1062    pub secret: Option<String>,
1063    #[serde(default)]
1064    pub url: Option<String>,
1065}
1066
1067#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1068pub struct ConnectorRecoveryCopy {
1069    #[serde(default, alias = "missing-install")]
1070    pub missing_install: Option<String>,
1071    #[serde(default, alias = "missing-auth")]
1072    pub missing_auth: Option<String>,
1073    #[serde(default, alias = "expired-credentials")]
1074    pub expired_credentials: Option<String>,
1075    #[serde(default, alias = "revoked-credentials")]
1076    pub revoked_credentials: Option<String>,
1077    #[serde(default, alias = "missing-scopes")]
1078    pub missing_scopes: Option<String>,
1079    #[serde(default, alias = "inaccessible-resource")]
1080    pub inaccessible_resource: Option<String>,
1081    #[serde(default, alias = "transient-provider-outage")]
1082    pub transient_provider_outage: Option<String>,
1083}
1084
1085#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
1086pub struct ConnectorCapabilities {
1087    pub webhook: bool,
1088    pub oauth: bool,
1089    pub rate_limit: bool,
1090    pub pagination: bool,
1091    pub graphql: bool,
1092    pub streaming: bool,
1093}
1094
1095impl ConnectorCapabilities {
1096    pub const FEATURES: [&'static str; 6] = [
1097        "webhook",
1098        "oauth",
1099        "rate_limit",
1100        "pagination",
1101        "graphql",
1102        "streaming",
1103    ];
1104
1105    fn enable(&mut self, feature: &str) -> Result<(), String> {
1106        match normalize_connector_capability(feature).as_str() {
1107            "webhook" => self.webhook = true,
1108            "oauth" => self.oauth = true,
1109            "rate_limit" => self.rate_limit = true,
1110            "pagination" => self.pagination = true,
1111            "graphql" => self.graphql = true,
1112            "streaming" => self.streaming = true,
1113            other => {
1114                return Err(format!(
1115                    "unknown connector capability '{feature}' (normalized as '{other}')"
1116                ));
1117            }
1118        }
1119        Ok(())
1120    }
1121}
1122
1123#[derive(Debug, Default, Deserialize)]
1124struct ConnectorCapabilitiesTable {
1125    #[serde(default)]
1126    webhook: bool,
1127    #[serde(default)]
1128    oauth: bool,
1129    #[serde(default, alias = "rate-limit")]
1130    rate_limit: bool,
1131    #[serde(default)]
1132    pagination: bool,
1133    #[serde(default)]
1134    graphql: bool,
1135    #[serde(default)]
1136    streaming: bool,
1137}
1138
1139impl From<ConnectorCapabilitiesTable> for ConnectorCapabilities {
1140    fn from(value: ConnectorCapabilitiesTable) -> Self {
1141        Self {
1142            webhook: value.webhook,
1143            oauth: value.oauth,
1144            rate_limit: value.rate_limit,
1145            pagination: value.pagination,
1146            graphql: value.graphql,
1147            streaming: value.streaming,
1148        }
1149    }
1150}
1151
1152impl<'de> Deserialize<'de> for ConnectorCapabilities {
1153    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1154    where
1155        D: serde::Deserializer<'de>,
1156    {
1157        #[derive(Deserialize)]
1158        #[serde(untagged)]
1159        enum RawConnectorCapabilities {
1160            List(Vec<String>),
1161            Table(ConnectorCapabilitiesTable),
1162        }
1163
1164        match RawConnectorCapabilities::deserialize(deserializer)? {
1165            RawConnectorCapabilities::List(features) => {
1166                let mut capabilities = ConnectorCapabilities::default();
1167                for feature in features {
1168                    capabilities
1169                        .enable(&feature)
1170                        .map_err(serde::de::Error::custom)?;
1171                }
1172                Ok(capabilities)
1173            }
1174            RawConnectorCapabilities::Table(table) => Ok(table.into()),
1175        }
1176    }
1177}
1178
1179pub fn normalize_connector_capability(feature: &str) -> String {
1180    feature.trim().to_lowercase().replace('-', "_")
1181}
1182
1183#[derive(Debug, Clone, Default, Deserialize)]
1184pub struct ConnectorContractConfig {
1185    #[serde(default)]
1186    pub version: Option<u32>,
1187    #[serde(default)]
1188    pub fixtures: Vec<ConnectorContractFixture>,
1189}
1190
1191#[derive(Debug, Clone, Deserialize)]
1192pub struct ConnectorContractFixture {
1193    pub provider: harn_vm::ProviderId,
1194    #[serde(default)]
1195    pub name: Option<String>,
1196    #[serde(default)]
1197    pub kind: Option<String>,
1198    #[serde(default)]
1199    pub headers: BTreeMap<String, String>,
1200    #[serde(default)]
1201    pub query: BTreeMap<String, String>,
1202    #[serde(default)]
1203    pub metadata: Option<toml::Value>,
1204    #[serde(default)]
1205    pub body: Option<String>,
1206    #[serde(default)]
1207    pub body_json: Option<toml::Value>,
1208    #[serde(default)]
1209    pub expect_type: Option<String>,
1210    #[serde(default)]
1211    pub expect_kind: Option<String>,
1212    #[serde(default)]
1213    pub expect_dedupe_key: Option<String>,
1214    #[serde(default)]
1215    pub expect_signature_state: Option<String>,
1216    #[serde(default)]
1217    pub expect_payload_contains: Option<toml::Value>,
1218    #[serde(default)]
1219    pub expect_response_status: Option<u16>,
1220    #[serde(default)]
1221    pub expect_response_body: Option<toml::Value>,
1222    #[serde(default)]
1223    pub expect_event_count: Option<usize>,
1224    #[serde(default)]
1225    pub expect_error_contains: Option<String>,
1226}
1227
1228#[derive(Debug, Clone, PartialEq, Eq)]
1229pub enum ResolvedProviderConnectorKind {
1230    Harn { module: String },
1231    RustBuiltin,
1232    Invalid(String),
1233}
1234
1235#[derive(Debug, Clone)]
1236pub struct ResolvedProviderConnectorConfig {
1237    pub id: harn_vm::ProviderId,
1238    pub manifest_dir: PathBuf,
1239    pub connector: ResolvedProviderConnectorKind,
1240    pub oauth: Option<ProviderOAuthManifest>,
1241    pub setup: Option<ProviderSetupManifest>,
1242}
1243
1244#[derive(Debug, Clone)]
1245pub struct ResolvedHookConfig {
1246    pub event: harn_vm::orchestration::HookEvent,
1247    pub pattern: String,
1248    pub handler: String,
1249    pub manifest_dir: PathBuf,
1250    pub package_name: Option<String>,
1251    pub exports: HashMap<String, String>,
1252}
1253
1254#[derive(Debug, Clone)]
1255pub struct ResolvedTriggerConfig {
1256    pub id: String,
1257    pub kind: TriggerKind,
1258    pub provider: harn_vm::ProviderId,
1259    pub autonomy_tier: harn_vm::AutonomyTier,
1260    pub match_: TriggerMatchExpr,
1261    pub when: Option<String>,
1262    pub when_budget: Option<TriggerWhenBudgetSpec>,
1263    pub handler: String,
1264    pub dedupe_key: Option<String>,
1265    pub retry: TriggerRetrySpec,
1266    pub dispatch_priority: TriggerDispatchPriority,
1267    pub budget: TriggerBudgetSpec,
1268    pub concurrency: Option<TriggerConcurrencyManifestSpec>,
1269    pub throttle: Option<TriggerThrottleManifestSpec>,
1270    pub rate_limit: Option<TriggerRateLimitManifestSpec>,
1271    pub debounce: Option<TriggerDebounceManifestSpec>,
1272    pub singleton: Option<TriggerSingletonManifestSpec>,
1273    pub batch: Option<TriggerBatchManifestSpec>,
1274    pub window: Option<TriggerStreamWindowManifestSpec>,
1275    pub priority_flow: Option<TriggerPriorityManifestSpec>,
1276    pub secrets: BTreeMap<String, String>,
1277    pub filter: Option<String>,
1278    pub kind_specific: BTreeMap<String, toml::Value>,
1279    pub manifest_dir: PathBuf,
1280    pub manifest_path: PathBuf,
1281    pub package_name: Option<String>,
1282    pub exports: HashMap<String, String>,
1283    pub execution_guard: Option<Arc<harn_modules::package_execution::PackageExecutionGuard>>,
1284    pub table_index: usize,
1285    pub shape_error: Option<String>,
1286}
1287
1288#[derive(Debug, Clone)]
1289#[allow(dead_code)] // Collected bindings are validated now and consumed by harn#159 dispatcher work.
1290pub struct CollectedManifestTrigger {
1291    pub config: ResolvedTriggerConfig,
1292    pub handler: CollectedTriggerHandler,
1293    pub when: Option<CollectedTriggerPredicate>,
1294    pub flow_control: harn_vm::TriggerFlowControlConfig,
1295}
1296
1297#[derive(Debug, Clone)]
1298#[allow(dead_code)] // Remote targets and closures are retained for harn#159 trigger execution.
1299pub enum CollectedTriggerHandler {
1300    Local {
1301        reference: TriggerFunctionRef,
1302        callable: harn_vm::VmCallable,
1303    },
1304    A2a {
1305        target: String,
1306        allow_cleartext: bool,
1307    },
1308    Worker {
1309        queue: String,
1310    },
1311    Persona {
1312        binding: harn_vm::PersonaRuntimeBinding,
1313        callable: harn_vm::VmCallable,
1314    },
1315    EvalPack {
1316        target: String,
1317        manifest: Box<harn_vm::orchestration::EvalPackManifest>,
1318        ledger_options: Option<serde_json::Value>,
1319    },
1320}
1321#[derive(Debug, Clone)]
1322#[allow(dead_code)] // Predicate callables are validated now and reused by harn#161 dispatch gating.
1323pub struct CollectedTriggerPredicate {
1324    pub reference: TriggerFunctionRef,
1325    pub callable: harn_vm::VmCallable,
1326}
1327
1328pub(crate) type ManifestModuleCacheKey = (PathBuf, Option<String>, Option<String>);
1329pub(crate) type ManifestModuleExports = BTreeMap<String, Arc<harn_vm::VmClosure>>;
1330
1331static MANIFEST_PROVIDER_SCHEMA_LOCK: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
1332
1333pub(crate) async fn lock_manifest_provider_schemas() -> tokio::sync::MutexGuard<'static, ()> {
1334    MANIFEST_PROVIDER_SCHEMA_LOCK
1335        .get_or_init(|| tokio::sync::Mutex::new(()))
1336        .lock()
1337        .await
1338}
1339
1340fn llm_manifest_diagnostics(content: &str) -> Vec<harn_vm::llm_config::ProviderConfigDiagnostic> {
1341    let Ok(value) = toml::from_str::<toml::Value>(content) else {
1342        return Vec::new();
1343    };
1344    let Some(llm) = value.get("llm") else {
1345        return Vec::new();
1346    };
1347    let Ok(llm_src) = toml::to_string(llm) else {
1348        return Vec::new();
1349    };
1350    let Ok(parsed) = harn_vm::llm_config::parse_config_toml_with_diagnostics(&llm_src) else {
1351        return Vec::new();
1352    };
1353    parsed
1354        .diagnostics
1355        .into_iter()
1356        .map(|mut diagnostic| {
1357            if !diagnostic.path.is_empty() {
1358                diagnostic.path = format!("llm.{}", diagnostic.path);
1359            }
1360            diagnostic
1361        })
1362        .collect()
1363}
1364
1365pub(crate) fn read_manifest_from_path(path: &Path) -> Result<Manifest, PackageError> {
1366    let content = fs::read_to_string(path).map_err(|error| {
1367        if error.kind() == std::io::ErrorKind::NotFound {
1368            PackageError::Manifest(format!(
1369                "No {} found in {}.",
1370                MANIFEST,
1371                path.parent().unwrap_or_else(|| Path::new(".")).display()
1372            ))
1373        } else {
1374            PackageError::Manifest(format!("failed to read {}: {error}", path.display()))
1375        }
1376    })?;
1377    let manifest = toml::from_str::<Manifest>(&content).map_err(|error| {
1378        PackageError::Manifest(format!("failed to parse {}: {error}", path.display()))
1379    })?;
1380    for diagnostic in llm_manifest_diagnostics(&content) {
1381        eprintln!("[llm_config] warning in {}: {diagnostic}", path.display());
1382    }
1383    Ok(manifest)
1384}
1385
1386pub(crate) fn absolutize_check_config_paths(
1387    mut config: CheckConfig,
1388    manifest_dir: &Path,
1389) -> CheckConfig {
1390    if let Some(path) = config.host_capabilities_path.clone() {
1391        let candidate = PathBuf::from(&path);
1392        if !candidate.is_absolute() {
1393            config.host_capabilities_path =
1394                Some(manifest_dir.join(candidate).display().to_string());
1395        }
1396    }
1397    if let Some(path) = config.bundle_root.clone() {
1398        let candidate = PathBuf::from(&path);
1399        if !candidate.is_absolute() {
1400            config.bundle_root = Some(manifest_dir.join(candidate).display().to_string());
1401        }
1402    }
1403    config
1404}
1405
1406/// Load the `[check]` config from the nearest `harn.toml`.
1407/// Walks up from the given file (or from cwd if no file is given),
1408/// stopping at a `.git` boundary.
1409pub fn load_check_config(harn_file: Option<&std::path::Path>) -> CheckConfig {
1410    let anchor = harn_file
1411        .map(Path::to_path_buf)
1412        .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
1413    if let Some((manifest, dir)) = nearest_manifest_or_warn(&anchor) {
1414        return absolutize_check_config_paths(manifest.check, &dir);
1415    }
1416    CheckConfig::default()
1417}
1418
1419/// Load the `[workspace]` config and the directory of the `harn.toml`
1420/// it came from. Paths in the returned config are left as-is (callers
1421/// resolve them against the returned `manifest_dir`).
1422pub fn load_workspace_config(anchor: Option<&Path>) -> Option<(WorkspaceConfig, PathBuf)> {
1423    let anchor = anchor
1424        .map(Path::to_path_buf)
1425        .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
1426    let (manifest, dir) = nearest_manifest_or_warn(&anchor)?;
1427    Some((manifest.workspace, dir))
1428}
1429
1430pub fn load_package_eval_pack_paths(anchor: Option<&Path>) -> Result<Vec<PathBuf>, PackageError> {
1431    let anchor = anchor
1432        .map(Path::to_path_buf)
1433        .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
1434    let Some((manifest, dir)) = load_nearest_manifest(&anchor).into_result()? else {
1435        return Err(PackageError::Manifest(
1436            "no harn.toml found for package eval discovery".to_string(),
1437        ));
1438    };
1439
1440    let ctx = ManifestContext { manifest, dir };
1441    let mut paths = eval_pack_paths_from_manifest(&ctx.manifest, &ctx.dir)?;
1442    paths.extend(installed_package_eval_pack_paths(&ctx)?);
1443    paths.sort();
1444    paths.dedup();
1445    if paths.is_empty() {
1446        return Err(PackageError::Manifest(
1447            "package declares no eval packs; add [package].evals, harn.eval.toml, or install a dependency that ships eval packs".to_string(),
1448        ));
1449    }
1450    for path in &paths {
1451        if !path.is_file() {
1452            return Err(PackageError::Manifest(format!(
1453                "eval pack does not exist: {}",
1454                path.display()
1455            )));
1456        }
1457    }
1458    Ok(paths)
1459}
1460
1461fn eval_pack_paths_from_manifest(
1462    manifest: &Manifest,
1463    manifest_dir: &Path,
1464) -> Result<Vec<PathBuf>, PackageError> {
1465    let declared = manifest
1466        .package
1467        .as_ref()
1468        .map(|package| package.evals.clone())
1469        .unwrap_or_default();
1470    let paths = if declared.is_empty() {
1471        let default_pack = manifest_dir.join("harn.eval.toml");
1472        if default_pack.is_file() {
1473            vec![default_pack]
1474        } else {
1475            Vec::new()
1476        }
1477    } else {
1478        declared
1479            .iter()
1480            .map(|entry| {
1481                let path = PathBuf::from(entry);
1482                if path.is_absolute() {
1483                    path
1484                } else {
1485                    manifest_dir.join(path)
1486                }
1487            })
1488            .collect()
1489    };
1490    for path in &paths {
1491        if !path.is_file() {
1492            return Err(PackageError::Manifest(format!(
1493                "eval pack does not exist: {}",
1494                path.display()
1495            )));
1496        }
1497    }
1498    Ok(paths)
1499}
1500
1501fn installed_package_eval_pack_paths(ctx: &ManifestContext) -> Result<Vec<PathBuf>, PackageError> {
1502    let Some(snapshot) = dependency_package_snapshot(&ctx.manifest, &ctx.dir)? else {
1503        return Ok(Vec::new());
1504    };
1505    let lock = LockFile::load(snapshot.lock_path())?.ok_or_else(|| {
1506        PackageError::Lockfile(format!(
1507            "published package generation is missing {}",
1508            snapshot.lock_path().display()
1509        ))
1510    })?;
1511    let mut paths = Vec::new();
1512    let packages_dir = snapshot.packages_root();
1513    for entry in &lock.packages {
1514        validate_package_alias(&entry.name)?;
1515        let package_dir = packages_dir.join(&entry.name);
1516        if package_dir.is_dir() {
1517            if let Some(manifest) = read_package_manifest_from_dir(&package_dir)? {
1518                paths.extend(eval_pack_paths_from_manifest(&manifest, &package_dir)?);
1519            }
1520            continue;
1521        }
1522
1523        let package_file = packages_dir.join(format!("{}.harn", entry.name));
1524        if package_file.is_file() {
1525            continue;
1526        }
1527
1528        return Err(PackageError::Manifest(format!(
1529            "installed package {} is missing under {}; run `harn install`",
1530            entry.name,
1531            packages_dir.display()
1532        )));
1533    }
1534    Ok(paths)
1535}
1536
1537#[derive(Debug, Clone)]
1538pub(crate) struct ManifestContext {
1539    pub(crate) manifest: Manifest,
1540    pub(crate) dir: PathBuf,
1541}
1542
1543impl ManifestContext {
1544    pub(crate) fn manifest_path(&self) -> PathBuf {
1545        self.dir.join(MANIFEST)
1546    }
1547
1548    pub(crate) fn lock_path(&self) -> PathBuf {
1549        self.dir.join(LOCK_FILE)
1550    }
1551}
1552
1553#[cfg(test)]
1554mod tests {
1555    use super::*;
1556    use crate::package::test_support::{current_packages_dir, TestWorkspace};
1557
1558    #[test]
1559    fn rules_table_parses_camel_and_kebab_dir_keys() {
1560        // The documented `ruleDirs` camelCase form and the kebab alias both map
1561        // to `rule_dirs` (#2843).
1562        let camel: Manifest =
1563            toml::from_str("[rules]\nruleDirs = [\"rules\", \"vendor/rules\"]\n").unwrap();
1564        assert_eq!(camel.rules.rule_dirs, vec!["rules", "vendor/rules"]);
1565
1566        let kebab: Manifest = toml::from_str("[rules]\nrule-dirs = [\"r\"]\n").unwrap();
1567        assert_eq!(kebab.rules.rule_dirs, vec!["r"]);
1568
1569        let native: Manifest =
1570            toml::from_str("[rules]\nnativeRuleDirs = [\"native-rules\"]\n").unwrap();
1571        assert_eq!(native.rules.native_rule_dirs, vec!["native-rules"]);
1572
1573        let native_kebab: Manifest =
1574            toml::from_str("[rules]\nnative-rule-dirs = [\"nr\"]\n").unwrap();
1575        assert_eq!(native_kebab.rules.native_rule_dirs, vec!["nr"]);
1576
1577        // No `[rules]` table → empty discovery, never an error.
1578        let none: Manifest = toml::from_str("[package]\nname = \"x\"\n").unwrap();
1579        assert!(none.rules.rule_dirs.is_empty());
1580        assert!(none.rules.native_rule_dirs.is_empty());
1581    }
1582
1583    #[test]
1584    fn llm_manifest_diagnostics_report_unknown_model_fields() {
1585        let diagnostics = llm_manifest_diagnostics(
1586            r#"
1587[llm.models."demo/model"]
1588name = "Demo"
1589provider = "demo"
1590context_window = 4096
1591fast_mode = true
1592"#,
1593        );
1594        let texts: Vec<String> = diagnostics
1595            .into_iter()
1596            .map(|diagnostic| diagnostic.to_string())
1597            .collect();
1598        assert!(
1599            texts.iter().any(
1600                |diagnostic| diagnostic.contains("llm.models.demo/model.fast_mode")
1601                    && diagnostic.contains("serving_tiers")
1602            ),
1603            "expected manifest [llm] unknown-field diagnostic, got {texts:?}"
1604        );
1605    }
1606
1607    #[test]
1608    fn package_eval_pack_paths_use_package_manifest_entries() {
1609        let tmp = tempfile::tempdir().unwrap();
1610        let root = tmp.path();
1611        fs::create_dir_all(root.join(".git")).unwrap();
1612        fs::create_dir_all(root.join("evals")).unwrap();
1613        fs::write(
1614            root.join(MANIFEST),
1615            r#"
1616    [package]
1617    name = "demo"
1618    version = "0.1.0"
1619    evals = ["evals/webhook.toml"]
1620    "#,
1621        )
1622        .unwrap();
1623        fs::write(
1624            root.join("evals/webhook.toml"),
1625            "version = 1\n[[cases]]\nrun = \"run.json\"\n",
1626        )
1627        .unwrap();
1628
1629        let paths = load_package_eval_pack_paths(Some(&root.join("src/main.harn"))).unwrap();
1630
1631        assert_eq!(paths, vec![root.join("evals/webhook.toml")]);
1632        assert!(
1633            !root.join(".harn").exists(),
1634            "loading project eval packs without dependencies must remain read-only"
1635        );
1636    }
1637
1638    #[test]
1639    fn package_eval_pack_paths_include_installed_package_evals() {
1640        let dependency_tmp = tempfile::tempdir().unwrap();
1641        let dependency = dependency_tmp.path().join("coding-pack");
1642        fs::create_dir_all(dependency.join("evals")).unwrap();
1643        fs::write(
1644            dependency.join(MANIFEST),
1645            r#"
1646[package]
1647name = "coding-pack"
1648version = "0.1.0"
1649evals = ["evals/coding.toml"]
1650"#,
1651        )
1652        .unwrap();
1653        fs::write(
1654            dependency.join("evals/run.json"),
1655            serde_json::to_string_pretty(&serde_json::json!({
1656                "_type": "workflow_run",
1657                "id": "run_1",
1658                "workflow_id": "workflow_1",
1659                "status": "completed",
1660                "usage": {
1661                    "total_duration_ms": 12,
1662                    "total_cost": 0.01,
1663                    "input_tokens": 3,
1664                    "output_tokens": 4,
1665                    "call_count": 1,
1666                    "models": ["mock"]
1667                },
1668                "replay_fixture": {
1669                    "_type": "replay_fixture",
1670                    "expected_status": "completed"
1671                }
1672            }))
1673            .unwrap(),
1674        )
1675        .unwrap();
1676        fs::write(
1677            dependency.join("evals/coding.toml"),
1678            r#"
1679version = 1
1680id = "coding-pack"
1681trials = 2
1682
1683[package]
1684name = "coding-pack"
1685version = "0.1.0"
1686source = "path:test"
1687templates = ["templates/rubric.harn.prompt"]
1688
1689[metadata]
1690model = "mock-model"
1691commit = "commit-a"
1692
1693[[cases]]
1694id = "case-a"
1695run = "run.json"
1696rubrics = ["status"]
1697
1698[[rubrics]]
1699id = "status"
1700kind = "deterministic"
1701
1702[[rubrics.assertions]]
1703kind = "run-status"
1704expected = "completed"
1705"#,
1706        )
1707        .unwrap();
1708
1709        let helper = dependency_tmp.path().join("helper-lib");
1710        fs::create_dir_all(&helper).unwrap();
1711        fs::write(
1712            helper.join(MANIFEST),
1713            r#"
1714[package]
1715name = "helper-lib"
1716version = "0.1.0"
1717"#,
1718        )
1719        .unwrap();
1720
1721        let project_tmp = tempfile::tempdir().unwrap();
1722        let root = project_tmp.path();
1723        let workspace = TestWorkspace::new(root);
1724        fs::create_dir_all(root.join(".git")).unwrap();
1725        fs::write(
1726            root.join(MANIFEST),
1727            format!(
1728                r#"
1729[package]
1730name = "workspace"
1731version = "0.1.0"
1732
1733[dependencies]
1734coding-pack = {{ path = {} }}
1735helper-lib = {{ path = {} }}
1736"#,
1737                crate::format::toml_basic_string_literal(&dependency.display().to_string()),
1738                crate::format::toml_basic_string_literal(&helper.display().to_string())
1739            ),
1740        )
1741        .unwrap();
1742
1743        install_packages_in(workspace.env(), false, None, false).unwrap();
1744
1745        let paths = load_package_eval_pack_paths(Some(&root.join("src/main.harn"))).unwrap();
1746        assert_eq!(
1747            paths,
1748            vec![current_packages_dir(root)
1749                .join("coding-pack")
1750                .join("evals/coding.toml")]
1751        );
1752
1753        harn_vm::event_log::reset_active_event_log();
1754        let manifest = harn_vm::orchestration::load_eval_pack_manifest(&paths[0]).unwrap();
1755        let package = manifest.package.as_ref().expect("package descriptor");
1756        assert_eq!(package.name.as_deref(), Some("coding-pack"));
1757        assert_eq!(package.templates, vec!["templates/rubric.harn.prompt"]);
1758
1759        let report = harn_vm::orchestration::evaluate_eval_pack_manifest_resumable(
1760            &manifest,
1761            Some(serde_json::json!({
1762                "namespace": "installed-pack-evals",
1763                "suite": "coding-pack",
1764                "model": "mock-model",
1765                "commit": "commit-a",
1766                "branch": "main"
1767            })),
1768        )
1769        .unwrap();
1770        assert!(report.pass);
1771        assert_eq!(report.trial_count, 2);
1772        assert_eq!(report.run_state.ledger_rows_inserted, 2);
1773        assert_eq!(report.stats_rows.len(), 1);
1774        assert_eq!(report.stats_rows[0].trials, 2);
1775        assert!(!report.stats_rows[0].case_fingerprint.is_empty());
1776        assert_eq!(
1777            report.harness_config_fingerprint,
1778            report.stats_rows[0].harness_config_fingerprint
1779        );
1780
1781        let ledger = harn_vm::orchestration::eval_ledger_read_report(Some(serde_json::json!({
1782            "namespace": "installed-pack-evals",
1783            "suite": "coding-pack",
1784            "model": "mock-model",
1785            "commit": "commit-a"
1786        })))
1787        .unwrap();
1788        assert_eq!(ledger.rows.len(), 2);
1789        harn_vm::event_log::reset_active_event_log();
1790    }
1791    #[test]
1792    fn preflight_severity_parsing_accepts_synonyms() {
1793        assert_eq!(
1794            PreflightSeverity::from_opt(Some("warning")),
1795            PreflightSeverity::Warning
1796        );
1797        assert_eq!(
1798            PreflightSeverity::from_opt(Some("WARN")),
1799            PreflightSeverity::Warning
1800        );
1801        assert_eq!(
1802            PreflightSeverity::from_opt(Some("off")),
1803            PreflightSeverity::Off
1804        );
1805        assert_eq!(
1806            PreflightSeverity::from_opt(Some("allow")),
1807            PreflightSeverity::Off
1808        );
1809        assert_eq!(
1810            PreflightSeverity::from_opt(Some("error")),
1811            PreflightSeverity::Error
1812        );
1813        assert_eq!(PreflightSeverity::from_opt(None), PreflightSeverity::Error);
1814        // Unknown values fall back to the safe default (error).
1815        assert_eq!(
1816            PreflightSeverity::from_opt(Some("bogus")),
1817            PreflightSeverity::Error
1818        );
1819    }
1820
1821    #[test]
1822    fn load_check_config_walks_up_from_nested_file() {
1823        let tmp = tempfile::tempdir().unwrap();
1824        let root = tmp.path();
1825        // Mark root as project boundary so walk-up terminates here.
1826        std::fs::create_dir_all(root.join(".git")).unwrap();
1827        fs::write(
1828            root.join(MANIFEST),
1829            r#"
1830    [check]
1831    preflight_severity = "warning"
1832    preflight_allow = ["custom.scan", "runtime.*"]
1833    host_capabilities_path = "./schemas/host-caps.json"
1834
1835    [workspace]
1836    pipelines = ["pipelines", "scripts"]
1837    "#,
1838        )
1839        .unwrap();
1840        let nested = root.join("src").join("deep");
1841        std::fs::create_dir_all(&nested).unwrap();
1842        let harn_file = nested.join("pipeline.harn");
1843        fs::write(&harn_file, "pipeline main() {}\n").unwrap();
1844
1845        let cfg = load_check_config(Some(&harn_file));
1846        assert_eq!(cfg.preflight_severity.as_deref(), Some("warning"));
1847        assert_eq!(cfg.preflight_allow, vec!["custom.scan", "runtime.*"]);
1848        let caps_path = cfg.host_capabilities_path.expect("host caps path");
1849        assert!(
1850            caps_path.ends_with("schemas/host-caps.json")
1851                || caps_path.ends_with("schemas\\host-caps.json"),
1852            "unexpected absolutized path: {caps_path}"
1853        );
1854
1855        let (workspace, manifest_dir) =
1856            load_workspace_config(Some(&harn_file)).expect("workspace manifest");
1857        assert_eq!(workspace.pipelines, vec!["pipelines", "scripts"]);
1858        // Walk-up lands on the directory containing the harn.toml.
1859        assert_eq!(manifest_dir, root);
1860    }
1861
1862    #[test]
1863    fn toml_string_literal_escapes_all_basic_control_characters() {
1864        let literal = toml_string_literal("a\u{08}\t\n\u{0C}\r\"\\\u{07}z").unwrap();
1865        let parsed: toml::Value = toml::from_str(&format!("value = {literal}\n")).unwrap();
1866        assert_eq!(
1867            parsed.get("value").and_then(toml::Value::as_str),
1868            Some("a\u{08}\t\n\u{0C}\r\"\\\u{07}z")
1869        );
1870    }
1871
1872    #[test]
1873    fn orchestrator_drain_config_parses_defaults_and_overrides() {
1874        let default_manifest: Manifest = toml::from_str(
1875            r#"
1876    [package]
1877    name = "fixture"
1878    "#,
1879        )
1880        .unwrap();
1881        assert_eq!(default_manifest.orchestrator.drain.max_items, 1024);
1882        assert_eq!(default_manifest.orchestrator.drain.deadline_seconds, 30);
1883        assert_eq!(default_manifest.orchestrator.pumps.max_outstanding, 64);
1884
1885        let configured: Manifest = toml::from_str(
1886            r#"
1887    [package]
1888    name = "fixture"
1889
1890    [orchestrator]
1891    drain.max_items = 77
1892    drain.deadline_seconds = 12
1893    pumps.max_outstanding = 3
1894    "#,
1895        )
1896        .unwrap();
1897        assert_eq!(configured.orchestrator.drain.max_items, 77);
1898        assert_eq!(configured.orchestrator.drain.deadline_seconds, 12);
1899        assert_eq!(configured.orchestrator.pumps.max_outstanding, 3);
1900    }
1901
1902    #[test]
1903    fn load_check_config_stops_at_git_boundary() {
1904        let tmp = tempfile::tempdir().unwrap();
1905        // An ancestor harn.toml above .git must NOT be picked up.
1906        fs::write(
1907            tmp.path().join(MANIFEST),
1908            "[check]\npreflight_severity = \"off\"\n",
1909        )
1910        .unwrap();
1911        let project = tmp.path().join("project");
1912        std::fs::create_dir_all(project.join(".git")).unwrap();
1913        let inner = project.join("src");
1914        std::fs::create_dir_all(&inner).unwrap();
1915        let harn_file = inner.join("main.harn");
1916        fs::write(&harn_file, "pipeline main() {}\n").unwrap();
1917        let cfg = load_check_config(Some(&harn_file));
1918        assert!(
1919            cfg.preflight_severity.is_none(),
1920            "must not inherit harn.toml from outside the .git boundary"
1921        );
1922    }
1923}