Skip to main content

node_app_manifest/
manifest.rs

1//! App manifest domain entity — unified v1/v2 schema.
2//!
3//! This module defines the canonical `AppManifest` used by the Node daemon to
4//! discover, load, and validate mini apps. It is a backward-compatible superset
5//! of the existing `PerAppManifest` (now promoted from `apps/server`).
6//!
7//! # Schema version detection
8//!
9//! - **v1** (legacy): no `manifest_version` field → `manifest_version = 1`.
10//!   All v2-only fields default to their v1-equivalent values. Zero existing
11//!   app manifests are invalidated.
12//! - **v2** (extended): `manifest_version = 2`. Adds `abi`, `entrypoint`,
13//!   `hot_reload`, and the typed `capabilities` block. Requires `abi` to be
14//!   present when `manifest_version == 2`.
15//!
16//! # Path-safety (SEC-H3)
17//!
18//! `entrypoint` and `ui_path` are validated at parse time:
19//! 1. Matches regex `^[a-zA-Z0-9_][a-zA-Z0-9_./-]*$`
20//! 2. Contains no `..` segment
21//! 3. Does not begin with `/`
22//!
23//! The canonicalize-inside-install-dir check (step 4) is performed by
24//! `tier_validator.rs` at load time because the install directory is not known
25//! until the daemon resolves the path.
26
27use serde::{Deserialize, Serialize};
28use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
29
30// ── Enums ────────────────────────────────────────────────────────────────────
31
32/// App execution model — determines how the daemon loads and isolates the app.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35pub enum AppType {
36    /// In-process cdylib loaded via dlopen. First-party path only (SEC-H1).
37    Native,
38    /// Isolated subprocess managed by the Bun runtime.
39    Bun,
40    /// Independent systemd-managed service that owns its own Unix domain socket.
41    /// The daemon does not start or supervise the process; it only routes
42    /// capability invocations to the app's socket as JSON-RPC 2.0.
43    /// Requires a `standalone.socket_path` when the manifest declares any
44    /// `provides` / `capabilities.provides` entries.
45    Standalone,
46    /// Packaging-only runtime dependency (for example the shared Bun runtime).
47    /// It is installed and versioned like an app package but is never loaded,
48    /// registered as a capability provider, or hot-reloaded as an app.
49    #[serde(rename = "platform-runtime")]
50    PlatformRuntime,
51    /// Verified executable generated by LLMC and launched through the
52    /// versioned managed-v1 stdio protocol.
53    #[serde(rename = "managed-v1")]
54    ManagedV1,
55    /// ES module bundle hosted by the Burger (QuickJS) runtime host,
56    /// `node-app-burger host` (Burger Plan 02, Contract C7).
57    Burger,
58    /// A stage-only app: a `ui` block of kind `stage` and no backend at all
59    /// (burger-07, Plans 07a/07b Contracts F5). Never loaded, spawned or
60    /// woken; node-server only lists and serves its UI bundle. Derived by
61    /// [`AppManifest::from_json`] for a manifest with a `ui` object and neither
62    /// `app_type` nor `entrypoint`. The string `"ui-only"` is also accepted,
63    /// so a serialised manifest round-trips.
64    #[serde(rename = "ui-only")]
65    UiOnly,
66}
67
68impl AppType {
69    pub fn as_str(self) -> &'static str {
70        match self {
71            AppType::Native => "native",
72            AppType::Bun => "bun",
73            AppType::Standalone => "standalone",
74            AppType::PlatformRuntime => "platform-runtime",
75            AppType::ManagedV1 => "managed-v1",
76            AppType::Burger => "burger",
77            AppType::UiOnly => "ui-only",
78        }
79    }
80}
81
82impl std::fmt::Display for AppType {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        write!(f, "{}", self.as_str())
85    }
86}
87
88/// Trust/distribution tier — derived at load time from the install path
89/// AND (per FR-028 cycle 4) the manifest sidecar's GPG signature.
90///
91/// This is **not** stored in the manifest; it is computed by `tier_validator`.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
93#[serde(rename_all = "snake_case")]
94pub enum AppTier {
95    /// App installed at the bundled path (`/usr/share/node/builtin-apps/`)
96    /// OR at the apt path with a manifest sidecar signed by a node project key.
97    /// May be `Native` or `Bun`. Highest trust.
98    FirstParty,
99    /// App installed at the optional apt path (`/usr/lib/node/apps/`) with
100    /// no/invalid project signature. MUST be `Bun`; `Native` at this tier
101    /// triggers `TierError` (FR-028).
102    Optional,
103    /// App loaded from a developer's local dev directory (`NODE_DEV_APPS_DIR`),
104    /// via `node-app-build dev` or manual sideload. Bypasses signature checks
105    /// because the dev directory is owned by the developer (security gate is
106    /// the file-system path: only the dev user can write to it). Permitted
107    /// for `Native` apps so cdylib developers can iterate without per-build
108    /// GPG signing.
109    ///
110    /// Daemon logs every Development-tier load at `info!` so operators of a
111    /// real node can see when a non-prod app is active. UI badges this tier
112    /// distinctly (amber/red, never green).
113    Development,
114}
115
116impl AppTier {
117    pub fn as_str(self) -> &'static str {
118        match self {
119            AppTier::FirstParty => "first_party",
120            AppTier::Optional => "optional",
121            AppTier::Development => "development",
122        }
123    }
124}
125
126impl std::fmt::Display for AppTier {
127    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128        write!(f, "{}", self.as_str())
129    }
130}
131
132/// Host ABI compatibility version declared by the app.
133///
134/// The runtime's currently supported set is `[V1]`. Apps declaring an
135/// unsupported version are rejected with `AbiIncompatible` (FR-018).
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(rename_all = "lowercase")]
138pub enum AbiVersion {
139    V1,
140}
141
142impl AbiVersion {
143    pub fn as_str(&self) -> &'static str {
144        match self {
145            AbiVersion::V1 => "v1",
146        }
147    }
148
149    /// Returns true if this ABI version is supported by the current runtime.
150    pub fn is_supported(&self) -> bool {
151        matches!(self, AbiVersion::V1)
152    }
153}
154
155impl std::fmt::Display for AbiVersion {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        write!(f, "{}", self.as_str())
158    }
159}
160
161/// How in-process (native) app reload is expected to behave.
162///
163/// Per research.md §R10, native hot-reload is inherently unreliable due to
164/// `dlclose` semantics. The manifest field sets correct user expectations.
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
166#[serde(rename_all = "snake_case")]
167pub enum HotReloadKind {
168    /// Reload is reliable (Bun subprocess restart). Default for `Bun` apps.
169    Supported,
170    /// Reload is attempted but its result depends on whether the on-disk
171    /// library image actually changed. When the daemon has this app's OLD
172    /// image mapped (Linux's `dlopen` returns the cached handle for an
173    /// already-`dlopen`'d path, so a package upgrade landing new bytes at
174    /// the same path goes undetected without an explicit staleness check),
175    /// `app.reload` succeeds and reports `status: "restart_required"`; the
176    /// process keeps serving the OLD mapped image (with its last known-good
177    /// `provides`) until the node actually restarts, at which point the new
178    /// version activates. Default for `Native` apps (FR-024).
179    Experimental,
180    /// App must be restarted to pick up changes.
181    Unsupported,
182}
183
184impl HotReloadKind {
185    pub fn default_for(app_type: AppType) -> Self {
186        match app_type {
187            AppType::Native => HotReloadKind::Experimental,
188            AppType::Bun => HotReloadKind::Supported,
189            // Standalone apps are restarted by systemd, not the daemon —
190            // from the daemon's perspective they are never hot-reloaded.
191            AppType::Standalone => HotReloadKind::Unsupported,
192            AppType::PlatformRuntime => HotReloadKind::Unsupported,
193            AppType::ManagedV1 => HotReloadKind::Supported,
194            AppType::Burger => HotReloadKind::Supported,
195            // A stage bundle reloads with the page; there is no process to reload.
196            AppType::UiOnly => HotReloadKind::Unsupported,
197        }
198    }
199}
200
201// ── Sub-types ─────────────────────────────────────────────────────────────────
202
203/// Capability declarations from the v2 manifest `capabilities` block.
204///
205/// Semantic equivalent of the existing `permissions` + `provides` fields;
206/// v2 manifests may use either or both (backward compat preserved).
207#[derive(Debug, Clone, Default, Serialize, Deserialize)]
208pub struct ManifestCapabilities {
209    /// Capabilities this app requests from the host or other apps.
210    /// Format: `"core.lightning.payment.send:max=1000sat/day"` (see §1.2).
211    #[serde(default)]
212    pub requires: Vec<String>,
213
214    /// Capabilities this app provides to other apps.
215    /// Format: `"core.cron.register"`.
216    #[serde(default)]
217    pub provides: Vec<String>,
218}
219
220/// A single scope provided by an app (existing v1 model, preserved verbatim).
221#[derive(Debug, Clone, Serialize, Deserialize, Default)]
222pub struct ProvidedScope {
223    pub scope: String,
224    pub description: String,
225    pub resource_pattern: String,
226}
227
228/// Declarative per-endpoint access policy (existing v1 model, preserved verbatim).
229#[derive(Debug, Clone, Serialize, Deserialize)]
230pub struct EndpointPolicy {
231    pub method: String,
232    pub path: String,
233    pub required_permissions: Vec<String>,
234}
235
236/// Capability provider declaration (existing v1 model, preserved verbatim).
237#[derive(Debug, Clone, Serialize, Deserialize)]
238pub struct ProvidedCapability {
239    #[serde(default)]
240    pub description: String,
241    #[serde(default)]
242    pub schema: Option<serde_json::Value>,
243}
244
245/// Configuration for `AppType::Standalone` apps.
246///
247/// Carried only by manifests whose `app_type == "standalone"`. The daemon uses
248/// `socket_path` to route capability invocations as line-delimited JSON-RPC 2.0
249/// over the standalone daemon's own Unix domain socket.
250///
251/// Path-safety rules (validated by `AppManifest::validate`):
252/// - Absolute path.
253/// - Lives under `/run/`.
254/// - No `..` segments.
255#[derive(Debug, Clone, Serialize, Deserialize)]
256pub struct StandaloneConfig {
257    pub socket_path: std::path::PathBuf,
258}
259
260/// Browser UI unit shipped by an app package.
261#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
262#[serde(rename_all = "snake_case")]
263pub enum AppUiKind {
264    Stage,
265    Widget,
266}
267
268fn default_app_ui_kind() -> AppUiKind {
269    AppUiKind::Stage
270}
271
272fn default_nav_section() -> String {
273    "default".to_string()
274}
275
276/// Shell-owned navigation metadata for a top-level stage.
277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
278pub struct AppUiNav {
279    #[serde(default = "default_nav_section")]
280    pub section: String,
281    #[serde(default)]
282    pub order: i32,
283}
284
285/// Shell-chrome regions an app may contribute a surface to.
286///
287/// The shell owns this vocabulary; an app requests a region by name. Keep this
288/// list to slots that have a real occupant — a speculative slot is a contract
289/// nobody has had to honour yet.
290///
291/// Checked in TWO places on purpose. `node-app package` rejects an unknown slot
292/// so an author sees a typo while they can still fix it; the shell ALSO ignores
293/// surfaces whose slot it does not recognise, because an app packaged against a
294/// newer SDK can be installed on an older shell, and that shell must degrade by
295/// dropping the surface rather than failing the app.
296pub const KNOWN_SURFACE_SLOTS: &[&str] = &["status-rail"];
297
298/// A UI unit an app contributes to a named region of the shell's own chrome.
299///
300/// Not a route: it has no nav entry, and it is mounted by the shell rather than
301/// by any stage. `requires` is the surface's OWN authorization scope — the
302/// primary containment control, since a surface otherwise receives the same
303/// `StageContext` a stage receives. A wallet chip declares `wallet.balance.get`
304/// and is refused `wallet.payment.send` even though the app provides it.
305#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
306pub struct AppUiSurface {
307    pub id: String,
308    pub slot: String,
309    pub entry: String,
310    pub title: String,
311    #[serde(default)]
312    pub order: i32,
313    #[serde(default)]
314    pub requires: AppUiRequirements,
315}
316
317/// How the client shell may behave when the home node is unavailable.
318#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
319#[serde(rename_all = "kebab-case")]
320pub enum AppDataOfflinePolicy {
321    /// A stage may render the last verified cached projection with stale/offline labeling.
322    LastKnown,
323    /// A stage must fail clearly when the home node is unavailable.
324    OnlineOnly,
325}
326
327/// Generic query declaration shape for app-owned cached projections.
328#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
329#[serde(rename_all = "kebab-case")]
330pub enum AppDataQueryKind {
331    Collection,
332    Detail,
333    Snapshot,
334}
335
336/// Generic stream declaration shape for app-owned invalidation/cursor feeds.
337#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
338#[serde(rename_all = "kebab-case")]
339pub enum AppDataStreamKind {
340    Changes,
341    Events,
342}
343
344/// How the client shell refreshes app-owned data.
345#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
346#[serde(rename_all = "kebab-case")]
347pub enum AppDataSyncKind {
348    Cursor,
349    Snapshot,
350}
351
352/// Bounded synchronization policy for generic app data.
353#[derive(Debug, Clone, PartialEq, Eq)]
354pub struct AppDataSyncPolicy {
355    pub kind: AppDataSyncKind,
356    pub cursor_ttl_secs: Option<u32>,
357    pub full_refresh_interval_secs: Option<u32>,
358    pub retention_secs: Option<u32>,
359}
360
361impl Serialize for AppDataSyncPolicy {
362    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
363    where
364        S: serde::Serializer,
365    {
366        use serde::ser::SerializeStruct;
367
368        if self.cursor_ttl_secs.is_none()
369            && self.full_refresh_interval_secs.is_none()
370            && self.retention_secs.is_none()
371        {
372            return self.kind.serialize(serializer);
373        }
374
375        let mut state = serializer.serialize_struct("AppDataSyncPolicy", 4)?;
376        state.serialize_field("kind", &self.kind)?;
377        if let Some(cursor_ttl_secs) = self.cursor_ttl_secs {
378            state.serialize_field("cursor_ttl_secs", &cursor_ttl_secs)?;
379        }
380        if let Some(full_refresh_interval_secs) = self.full_refresh_interval_secs {
381            state.serialize_field("full_refresh_interval_secs", &full_refresh_interval_secs)?;
382        }
383        if let Some(retention_secs) = self.retention_secs {
384            state.serialize_field("retention_secs", &retention_secs)?;
385        }
386        state.end()
387    }
388}
389
390impl<'de> Deserialize<'de> for AppDataSyncPolicy {
391    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
392    where
393        D: serde::Deserializer<'de>,
394    {
395        #[derive(Deserialize)]
396        #[serde(deny_unknown_fields)]
397        struct ObjectPolicy {
398            kind: AppDataSyncKind,
399            #[serde(default)]
400            cursor_ttl_secs: Option<u32>,
401            #[serde(default)]
402            full_refresh_interval_secs: Option<u32>,
403            #[serde(default)]
404            retention_secs: Option<u32>,
405        }
406
407        #[derive(Deserialize)]
408        #[serde(untagged)]
409        enum WirePolicy {
410            Kind(AppDataSyncKind),
411            Object(ObjectPolicy),
412        }
413
414        match WirePolicy::deserialize(deserializer)? {
415            WirePolicy::Kind(kind) => Ok(Self {
416                kind,
417                cursor_ttl_secs: None,
418                full_refresh_interval_secs: None,
419                retention_secs: None,
420            }),
421            WirePolicy::Object(policy) => Ok(Self {
422                kind: policy.kind,
423                cursor_ttl_secs: policy.cursor_ttl_secs,
424                full_refresh_interval_secs: policy.full_refresh_interval_secs,
425                retention_secs: policy.retention_secs,
426            }),
427        }
428    }
429}
430
431/// A namespaced app-owned query exposed through the generic stage data plane.
432#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
433#[serde(deny_unknown_fields)]
434pub struct AppDataQueryDeclaration {
435    pub name: String,
436    pub capability: String,
437    pub kind: AppDataQueryKind,
438}
439
440/// A namespaced app-owned stream exposed through the generic stage data plane.
441#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
442#[serde(deny_unknown_fields)]
443pub struct AppDataStreamDeclaration {
444    pub name: String,
445    pub kind: AppDataStreamKind,
446}
447
448/// Generic, app-owned data contract declared by a stage manifest.
449#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
450#[serde(deny_unknown_fields)]
451pub struct AppDataManifest {
452    pub namespace: String,
453    pub offline: AppDataOfflinePolicy,
454    pub sync: AppDataSyncPolicy,
455    #[serde(default)]
456    pub queries: Vec<AppDataQueryDeclaration>,
457    #[serde(default)]
458    pub streams: Vec<AppDataStreamDeclaration>,
459}
460
461/// Capability, query, and stream contracts exposed to an app-delivered UI
462/// stage. This is intentionally separate from the app's backend dependency
463/// declaration (`requires` / `capabilities.requires`): backend providers may
464/// need capabilities that must never be delegated to browser UI code.
465#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
466#[serde(deny_unknown_fields)]
467pub struct AppUiRequirements {
468    #[serde(default)]
469    pub capabilities: Vec<String>,
470    #[serde(default)]
471    pub queries: Vec<String>,
472    #[serde(default)]
473    pub streams: Vec<String>,
474}
475
476impl AppUiRequirements {
477    /// Return the UI's complete declared contract in stable, de-duplicated
478    /// order. Query and stream names are included because they are separately
479    /// authorized stage declarations at the client RPC boundary.
480    pub fn resolved(&self) -> Result<Vec<String>, String> {
481        let mut resolved = Vec::new();
482        let mut seen = HashSet::new();
483        for (values, allow_wildcard) in [
484            (&self.capabilities, true),
485            (&self.queries, false),
486            (&self.streams, false),
487        ] {
488            for value in values {
489                let requirement = value.trim();
490                if requirement.is_empty() {
491                    return Err("ui.requires entries must not be blank".to_string());
492                }
493                validate_ui_requirement_name(requirement, allow_wildcard).map_err(|error| {
494                    format!("ui.requires entry '{requirement}' invalid: {error}")
495                })?;
496                if seen.insert(requirement.to_string()) {
497                    resolved.push(requirement.to_string());
498                }
499            }
500        }
501        Ok(resolved)
502    }
503}
504
505/// Optional stage metadata carried by the canonical app manifest.
506#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
507pub struct AppUiManifest {
508    #[serde(default = "default_app_ui_kind")]
509    pub kind: AppUiKind,
510    pub entry: String,
511    pub title: String,
512    #[serde(default)]
513    pub icon: Option<String>,
514    #[serde(default)]
515    pub nav: Option<AppUiNav>,
516    #[serde(default)]
517    pub composes: Vec<String>,
518    /// Shell-chrome contributions. Empty for the overwhelming majority of apps.
519    #[serde(default)]
520    pub surfaces: Vec<AppUiSurface>,
521    pub ui_api: u8,
522    #[serde(default)]
523    pub integrity: BTreeMap<String, String>,
524    /// Stage-specific description that overrides the app-level
525    /// `AppManifest::description` when the stage's UI purpose differs from the
526    /// app's. Optional; when absent the app-level description is used.
527    #[serde(default)]
528    pub description: Option<String>,
529    /// Author-supplied synonyms for this stage (search/intent phrasings).
530    /// Optional; defaults to empty.
531    #[serde(default)]
532    pub keywords: Vec<String>,
533    /// The browser stage contract. Do not populate this from the app's
534    /// backend `requires` declaration.
535    #[serde(default)]
536    pub requires: AppUiRequirements,
537    #[serde(default, skip_serializing_if = "Option::is_none")]
538    pub data: Option<AppDataManifest>,
539}
540
541// ── Path-safety helpers ───────────────────────────────────────────────────────
542
543/// Validate a relative file path declared in a manifest (`entrypoint`, `ui_path`).
544///
545/// Rules (SEC-H3):
546/// 1. Matches `^[a-zA-Z0-9_][a-zA-Z0-9_./-]*$` — rejects shell metacharacters,
547///    leading `.`, leading `/`, etc.
548/// 2. No `..` segment anywhere.
549/// 3. Does not begin with `/` (absolute paths).
550///
551/// Returns `Ok(())` if valid, `Err(reason)` describing the violation.
552pub fn validate_manifest_path(path: &str) -> Result<(), String> {
553    if path.is_empty() {
554        return Err("path must not be empty".to_string());
555    }
556
557    // Rule 3: no absolute paths
558    if path.starts_with('/') {
559        return Err(format!(
560            "path '{}' must not be absolute (starts with /)",
561            path
562        ));
563    }
564
565    // Rule 1: allowed character set
566    // ^[a-zA-Z0-9_][a-zA-Z0-9_./-]*$
567    let first = path.chars().next().unwrap();
568    if !first.is_ascii_alphanumeric() && first != '_' {
569        return Err(format!(
570            "path '{}' must begin with an alphanumeric character or underscore",
571            path
572        ));
573    }
574    for ch in path.chars().skip(1) {
575        if !ch.is_ascii_alphanumeric() && !matches!(ch, '_' | '.' | '/' | '-') {
576            return Err(format!(
577                "path '{}' contains disallowed character '{}'",
578                path, ch
579            ));
580        }
581    }
582
583    // Rule 2: no `..` segment
584    for segment in path.split('/') {
585        if segment == ".." {
586            return Err(format!(
587                "path '{}' contains a '..' segment (path traversal rejected)",
588                path
589            ));
590        }
591    }
592
593    Ok(())
594}
595
596// ── AppManifest ───────────────────────────────────────────────────────────────
597
598/// Canonical manifest entity — unified v1/v2 format.
599///
600/// Deserializes both old (v1, no `manifest_version`) and new (v2) manifests.
601/// All v2-only fields use `#[serde(default)]` so that v1 manifests parse
602/// correctly without any field changes.
603#[derive(Debug, Clone, Serialize, Deserialize)]
604pub struct AppManifest {
605    /// Schema version. Absent or 1 = legacy v1; 2 = extended v2.
606    #[serde(default = "default_manifest_version", rename = "manifest_version")]
607    pub manifest_version: u8,
608
609    pub name: String,
610    pub version: String,
611
612    #[serde(default = "default_app_type_native")]
613    pub app_type: AppType,
614
615    #[serde(default)]
616    pub description: String,
617
618    // ── v2-only additions (all optional, v1-compatible defaults) ─────────────
619    /// Host ABI compatibility version. Required when `manifest_version == 2`.
620    pub abi: Option<AbiVersion>,
621
622    /// Payload entry point relative to the app directory.
623    /// Default: `app.so` for Native, `dist/index.js` for Bun.
624    pub entrypoint: Option<String>,
625
626    /// Hot-reload behaviour classification.
627    /// Default: `experimental` for Native, `supported` for Bun.
628    pub hot_reload: Option<HotReloadKind>,
629
630    // ── Existing v1 fields (preserved verbatim — DO NOT RENAME) ──────────────
631    #[serde(default)]
632    pub critical: bool,
633
634    #[serde(
635        default = "default_auto_start",
636        deserialize_with = "deserialize_auto_start"
637    )]
638    pub auto_start: bool,
639
640    #[serde(default)]
641    pub has_ui: bool,
642
643    #[serde(default = "default_ui_path")]
644    pub ui_path: String,
645
646    #[serde(default)]
647    pub permissions: Vec<String>,
648
649    /// Capability requirements in the v2 top-level vocabulary. This is an
650    /// alias for `capabilities.requires`, not a second permission system.
651    #[serde(default)]
652    pub requires: Vec<String>,
653
654    #[serde(default)]
655    pub optional_permissions: Vec<String>,
656
657    #[serde(default)]
658    pub provides_scopes: Vec<ProvidedScope>,
659
660    #[serde(default)]
661    pub endpoint_policies: Vec<EndpointPolicy>,
662
663    #[serde(default)]
664    pub capability_scopes: HashMap<String, String>,
665
666    #[serde(default)]
667    pub provides: HashMap<String, ProvidedCapability>,
668
669    // ── v2 capabilities block (semantic alias for permissions + provides) ─────
670    #[serde(default)]
671    pub capabilities: ManifestCapabilities,
672
673    /// App-delivered browser UI metadata. Legacy `has_ui`/`ui_path` remains
674    /// readable but does not synthesize this block.
675    #[serde(default, skip_serializing_if = "Option::is_none")]
676    pub ui: Option<AppUiManifest>,
677
678    // ── Optional metadata fields ──────────────────────────────────────────────
679    #[serde(default)]
680    pub author: Option<String>,
681
682    #[serde(default)]
683    pub homepage: Option<String>,
684
685    #[serde(default)]
686    pub depends_on: Option<Vec<String>>,
687
688    #[serde(default)]
689    pub boot_priority: Option<u32>,
690
691    /// App-governor idle-termination policy (issue #811 SP1). Absent means
692    /// the app is subject to the default eligibility rules with no explicit
693    /// opt-out and no minimum-idle override.
694    #[serde(default)]
695    pub governor: Option<GovernorManifest>,
696
697    /// Event-bus topics this app listens for while lazily started. Only
698    /// meaningful for apps holding the `EVENT_LISTENER` capability — a
699    /// listener with no declared `subscribes` topics is exempt from idle
700    /// termination because the governor cannot know what would need to wake
701    /// it back up (see `node-app-host::governor_eligibility`).
702    #[serde(default)]
703    pub subscribes: Vec<String>,
704
705    /// Required when `app_type == "standalone"` and the manifest declares any
706    /// `provides` / `capabilities.provides` entries. Carries the Unix domain
707    /// socket path the daemon dispatches capability calls to.
708    #[serde(default)]
709    pub standalone: Option<StandaloneConfig>,
710
711    /// Optional TCP-binding block — feature 470 (port registry).
712    /// Absence means the app does not bind a TCP port the registry manages.
713    #[serde(default, skip_serializing_if = "Option::is_none")]
714    pub tcp: Option<TcpManifest>,
715
716    /// Runtime resource requests (Burger Plan 02, Contracts C2/C7). Absence means
717    /// runtime defaults (Burger: 32 MB QuickJS memory limit, 5000 ms callback deadline).
718    #[serde(default, skip_serializing_if = "Option::is_none")]
719    pub resources: Option<ResourcesManifest>,
720}
721
722/// Upper bound for `resources.callback_deadline_ms` (10 minutes).
723pub const MAX_CALLBACK_DEADLINE_MS: u32 = 600_000;
724
725/// Runtime resource requests (Contract C2). `memory_mb` becomes the Burger
726/// host's per-app QuickJS memory limit (`load_app.memory_limit_mb`);
727/// `callback_deadline_ms` becomes its per-callback CPU watchdog
728/// (`load_app.callback_deadline_ms`). Both are omitted from `load_app` when
729/// absent so the Burger host applies its own defaults (32 MB, 5000 ms).
730#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
731pub struct ResourcesManifest {
732    #[serde(default, skip_serializing_if = "Option::is_none")]
733    pub memory_mb: Option<u32>,
734    #[serde(default, skip_serializing_if = "Option::is_none")]
735    pub callback_deadline_ms: Option<u32>,
736}
737
738/// Declared responsiveness expectation for an app's lease engine decisions
739/// (app lease engine design §8, Task 1). `None` on [`GovernorManifest`] means
740/// the app has not declared a preference — the lease engine (Task 5) then
741/// falls back to its own default rather than treating an unset field as
742/// either variant.
743#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
744#[serde(rename_all = "lowercase")]
745pub enum LatencyClass {
746    /// The app serves latency-sensitive, user-facing requests — the lease
747    /// engine should prefer to keep it warm.
748    Interactive,
749    /// The app only does deferred/background work — the lease engine may
750    /// treat it as a lower priority to keep resident.
751    Background,
752}
753
754impl LatencyClass {
755    pub fn as_str(&self) -> &'static str {
756        match self {
757            LatencyClass::Interactive => "interactive",
758            LatencyClass::Background => "background",
759        }
760    }
761
762    #[allow(clippy::should_implement_trait)]
763    pub fn from_str(s: &str) -> Result<Self, String> {
764        match s {
765            "interactive" => Ok(LatencyClass::Interactive),
766            "background" => Ok(LatencyClass::Background),
767            _ => Err(format!("Invalid LatencyClass: {}", s)),
768        }
769    }
770}
771
772impl std::fmt::Display for LatencyClass {
773    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
774        write!(f, "{}", self.as_str())
775    }
776}
777
778/// Idle-termination policy for a lazily-started app (issue #811 SP1 — the
779/// app governor). Nested under `AppManifest::governor`.
780#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
781pub struct GovernorManifest {
782    /// Explicit opt-out. `Some(false)` exempts the app from idle termination
783    /// regardless of any other eligibility rule. `None`/`Some(true)` defers
784    /// to the other eligibility rules.
785    #[serde(default)]
786    pub terminable: Option<bool>,
787
788    /// Minimum idle duration, in seconds, before the governor may terminate
789    /// this app — overrides the governor's default sweep threshold. `None`
790    /// defers to the default.
791    #[serde(default)]
792    pub min_idle_secs: Option<u64>,
793
794    /// Memory budget in KB. When the app's measured footprint — on the basis
795    /// selected by its measurement attribution, see
796    /// `node_app_host::app_memory::budget` — exceeds this, the owner is warned
797    /// in the shell.
798    ///
799    /// # What `None` defers to
800    ///
801    /// NOT one number. The default is chosen PER BASIS
802    /// (`node_app_host::app_memory::budget::default_budget_kb`), because the
803    /// bases are not comparable quantities:
804    ///
805    /// | basis                | default   | why                                     |
806    /// |----------------------|-----------|-----------------------------------------|
807    /// | `heap_used`, `pss`   | 10,240 KB | the app and nothing else                |
808    /// | `rss`                | 61,440 KB | the whole OS process, runtime included  |
809    /// | `not_attributable`   | 10,240 KB | never `over`; carried only for the wire |
810    ///
811    /// A shared-runtime Bun worker is compared on `heap_used`; a dedicated
812    /// process or cgroup-scoped standalone on `rss`, which charges it for a
813    /// JavaScript engine it did not choose and cannot shed.
814    ///
815    /// On top of that, a host-side runtime-critical entry
816    /// (`RUNTIME_CRITICAL_BUDGETS`) acts as a FLOOR, never a ceiling: it can
817    /// only raise an app above the per-basis default, never pull it below one.
818    ///
819    /// A value declared HERE is the one thing that overrides both, in either
820    /// direction — it is a deliberate choice by the app author, not a fallback,
821    /// so it is honoured unchanged even when it is lower than the default.
822    ///
823    /// Apps that legitimately need more than their basis default MUST declare a
824    /// realistic budget here; otherwise the warning is permanently lit and
825    /// stops meaning anything.
826    #[serde(default)]
827    pub memory_budget_kb: Option<u64>,
828
829    /// Declared responsiveness expectation (app lease engine design §8,
830    /// Task 1). `None` when the app declares no preference — see
831    /// [`LatencyClass`] for what each variant means and what `None` defers
832    /// to.
833    #[serde(default)]
834    pub latency_class: Option<LatencyClass>,
835}
836
837/// TCP port preferences for standalone apps that bind their own port.
838/// Consumed by the port registry (`system/server/src/services/port_registry/`)
839/// at install time.
840#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
841pub struct TcpManifest {
842    /// The TCP port the app would like to bind. Honored when free;
843    /// otherwise the registry assigns the next free port from the pool
844    /// (default 7000–7099). Absent → registry picks any free pool slot.
845    #[serde(default, skip_serializing_if = "Option::is_none")]
846    pub preferred_port: Option<u16>,
847
848    /// When `true`, the platform UI shell builds iframe URLs as direct LAN
849    /// connections to the assigned port rather than routing via the
850    /// `/api/v2/node-apps/{name}/ui/` reverse-proxy. Intended only for apps
851    /// that must outlive a platform restart (e.g. OTA self-upgrade). Remote
852    /// users may see a degraded experience — owned by the consuming app's UI,
853    /// not this spec (see `specs/470-port-registry/spec.md` Clarifications Q5b).
854    #[serde(default, skip_serializing_if = "Option::is_none")]
855    pub direct_bind: Option<bool>,
856}
857
858fn default_manifest_version() -> u8 {
859    1
860}
861
862fn default_auto_start() -> bool {
863    true
864}
865
866/// Deserialize `auto_start` from either a bool (manifest v1) or a load-mode
867/// string (v2, e.g. `"lazy"`/`"eager"`/`"active"`). Eager-start modes map to
868/// `true`; `"lazy"` and other on-demand/inactive states map to `false` (the app
869/// is started on first capability use, not at boot). This keeps both manifest
870/// schema generations parseable by `AppManifest::from_json`.
871fn deserialize_auto_start<'de, D>(deserializer: D) -> Result<bool, D::Error>
872where
873    D: serde::Deserializer<'de>,
874{
875    #[derive(Deserialize)]
876    #[serde(untagged)]
877    enum BoolOrStr {
878        Bool(bool),
879        Str(String),
880    }
881    Ok(match BoolOrStr::deserialize(deserializer)? {
882        BoolOrStr::Bool(b) => b,
883        BoolOrStr::Str(s) => matches!(
884            s.trim().to_ascii_lowercase().as_str(),
885            "true" | "eager" | "active" | "auto" | "on" | "1"
886        ),
887    })
888}
889
890fn default_ui_path() -> String {
891    "dist".to_string()
892}
893
894fn default_app_type_native() -> AppType {
895    AppType::Native
896}
897
898impl AppManifest {
899    /// Resolve top-level `requires` and `capabilities.requires` into one
900    /// canonical declaration list. Equal aliases are accepted regardless of
901    /// order or duplicates; differing aliases are rejected.
902    pub fn resolved_requires(&self) -> Result<Vec<String>, String> {
903        let top = normalized_requirements(&self.requires)?;
904        let nested = normalized_requirements(&self.capabilities.requires)?;
905        if !top.is_empty()
906            && !nested.is_empty()
907            && top.iter().cloned().collect::<BTreeSet<_>>()
908                != nested.iter().cloned().collect::<BTreeSet<_>>()
909        {
910            return Err("top-level 'requires' conflicts with 'capabilities.requires'".to_string());
911        }
912        Ok(if !top.is_empty() { top } else { nested })
913    }
914
915    /// Returns the effective `HotReloadKind` — explicit field or the default
916    /// for the app type.
917    pub fn effective_hot_reload(&self) -> HotReloadKind {
918        self.hot_reload
919            .unwrap_or_else(|| HotReloadKind::default_for(self.app_type))
920    }
921
922    /// Returns the effective entrypoint — explicit field or the type-specific default.
923    ///
924    /// Standalone and UI-only apps have no daemon-managed entrypoint (systemd
925    /// owns a standalone's lifecycle; a UI-only stage has no process); the
926    /// empty string signals "not applicable".
927    pub fn effective_entrypoint(&self) -> &str {
928        if let Some(ref ep) = self.entrypoint {
929            ep.as_str()
930        } else {
931            match self.app_type {
932                AppType::Native => "app.so",
933                AppType::Bun => "dist/index.js",
934                AppType::Standalone => "",
935                AppType::PlatformRuntime => "bun",
936                AppType::ManagedV1 => "llmc-generated-app",
937                AppType::Burger => "dist/index.js",
938                AppType::UiOnly => "",
939            }
940        }
941    }
942
943    /// True iff this manifest declares at least one capability provider
944    /// (via either the v1 `provides` map or the v2 `capabilities.provides` list).
945    pub fn has_capability_providers(&self) -> bool {
946        !self.provides.is_empty() || !self.capabilities.provides.is_empty()
947    }
948
949    /// Merges the v1 `provides` map and the v2 `capabilities.provides` name
950    /// list into a single capability→declaration map (composition-root
951    /// cleanup Round 4 T28 — extracted from
952    /// `control_ipc::handlers::handle_app_register_standalone`, which uses
953    /// this to shape a standalone app's declared providers for capability
954    /// registration).
955    ///
956    /// - v1 entries (the `provides` map) carry their real
957    ///   description/schema and always win on a name conflict.
958    /// - v2-only names (declared only via `capabilities.provides`, format
959    ///   `"name"` or `"name:extra"` — only the part before the first `:` is
960    ///   used) get a blank declaration, inserted only if the name is not
961    ///   already present from v1. Blank/whitespace-only names are skipped.
962    pub fn resolved_capability_provides(&self) -> HashMap<String, ProvidedCapability> {
963        let mut out: HashMap<String, ProvidedCapability> = self.provides.clone();
964        for raw in &self.capabilities.provides {
965            let name = raw.split(':').next().unwrap_or(raw).trim().to_string();
966            if name.is_empty() {
967                continue;
968            }
969            out.entry(name).or_insert(ProvidedCapability {
970                description: String::new(),
971                schema: None,
972            });
973        }
974        out
975    }
976
977    /// Validate the manifest for structural correctness.
978    ///
979    /// Returns `Ok(())` on success, or a human-readable error string.
980    /// Called by the manifest parser after deserialization.
981    pub fn validate(&self) -> Result<(), String> {
982        self.validate_with_socket_path_policy(false)
983    }
984
985    /// Validate this manifest with an explicit standalone socket-path policy.
986    ///
987    /// Runtime adapters may opt into non-`/run` paths for development without
988    /// making the domain model read process configuration.
989    pub fn validate_with_socket_path_policy(&self, allow_non_run: bool) -> Result<(), String> {
990        // v2 requires abi field
991        if self.manifest_version == 2 && self.abi.is_none() {
992            return Err("manifest_version 2 requires an 'abi' field".to_string());
993        }
994
995        // Name validation: ^[a-z][a-z0-9-]*(/([a-z][a-z0-9-]*))?$
996        // (publisher/name form accepted but not yet semantically used — FR-019)
997        validate_app_name(&self.name)?;
998        self.resolved_requires()?;
999
1000        // Path-safety on entrypoint and ui_path
1001        if let Some(ref ep) = self.entrypoint {
1002            validate_manifest_path(ep).map_err(|e| format!("entrypoint invalid: {}", e))?;
1003        }
1004        // ui_path is only meaningful when has_ui is true, but validate always
1005        if !self.ui_path.is_empty() && self.ui_path != "dist" {
1006            validate_manifest_path(&self.ui_path).map_err(|e| format!("ui_path invalid: {}", e))?;
1007        }
1008
1009        if let Some(ui) = &self.ui {
1010            validate_app_ui(&self.name, ui)?;
1011        }
1012
1013        // Homepage scheme validation (if present)
1014        if let Some(ref hp) = self.homepage {
1015            if !hp.starts_with("https://") && !hp.starts_with("http://") {
1016                return Err(format!(
1017                    "homepage '{}' must use https:// or http:// scheme",
1018                    hp
1019                ));
1020            }
1021        }
1022
1023        // Standalone-app rules:
1024        // - When `app_type == "standalone"` AND the manifest declares any
1025        //   capability providers, `standalone.socket_path` is required and
1026        //   must be an absolute path under `/run/` with no `..` segments.
1027        // - Non-standalone manifests MUST NOT carry a `standalone` block
1028        //   (rejected to surface accidental schema misuse).
1029        match self.app_type {
1030            AppType::Standalone => {
1031                if self.has_capability_providers() {
1032                    let cfg = self.standalone.as_ref().ok_or_else(|| {
1033                        "standalone apps that declare 'provides' require a \
1034                         'standalone.socket_path' field"
1035                            .to_string()
1036                    })?;
1037                    validate_standalone_socket_path_with_policy(&cfg.socket_path, allow_non_run)?;
1038                }
1039            }
1040            AppType::Native
1041            | AppType::Bun
1042            | AppType::PlatformRuntime
1043            | AppType::ManagedV1
1044            | AppType::Burger
1045            | AppType::UiOnly => {
1046                if self.standalone.is_some() {
1047                    return Err(format!(
1048                        "'standalone' block is only valid when app_type == 'standalone' \
1049                         (found app_type='{}')",
1050                        self.app_type
1051                    ));
1052                }
1053            }
1054        }
1055
1056        if self.app_type == AppType::UiOnly {
1057            validate_ui_only(self)?;
1058        }
1059
1060        if let Some(resources) = &self.resources {
1061            if resources.memory_mb == Some(0) {
1062                return Err("resources.memory_mb must be at least 1".to_string());
1063            }
1064            if let Some(deadline) = resources.callback_deadline_ms {
1065                if !(1..=MAX_CALLBACK_DEADLINE_MS).contains(&deadline) {
1066                    return Err(format!(
1067                        "resources.callback_deadline_ms must be between 1 and {MAX_CALLBACK_DEADLINE_MS} (found {deadline})"
1068                    ));
1069                }
1070            }
1071        }
1072
1073        if self.app_type == AppType::PlatformRuntime
1074            && !self.resolved_capability_provides().is_empty()
1075        {
1076            return Err(
1077                "platform-runtime packages cannot provide runtime capabilities".to_string(),
1078            );
1079        }
1080
1081        Ok(())
1082    }
1083
1084    /// Parse from a JSON string, validate, and return the manifest.
1085    pub fn from_json(json: &str) -> Result<Self, String> {
1086        Self::from_json_with_socket_path_policy(json, false)
1087    }
1088
1089    /// Parse and validate with an explicit standalone socket-path policy.
1090    pub fn from_json_with_socket_path_policy(
1091        json: &str,
1092        allow_non_run: bool,
1093    ) -> Result<Self, String> {
1094        let mut manifest: Self =
1095            serde_json::from_str(json).map_err(|e| format!("manifest JSON parse error: {}", e))?;
1096        if serde_json::from_str::<serde_json::Value>(json).is_ok_and(|raw| declares_ui_only(&raw)) {
1097            manifest.app_type = AppType::UiOnly;
1098        }
1099        if manifest.ui.is_some() {
1100            manifest.has_ui = true;
1101        }
1102        manifest.validate_with_socket_path_policy(allow_non_run)?;
1103        Ok(manifest)
1104    }
1105}
1106
1107fn normalized_requirements(values: &[String]) -> Result<Vec<String>, String> {
1108    let mut seen = HashSet::new();
1109    let mut resolved = Vec::new();
1110    for value in values {
1111        let requirement = value.trim();
1112        if requirement.is_empty() {
1113            return Err("capability requirements must not be blank".to_string());
1114        }
1115        if seen.insert(requirement.to_string()) {
1116            resolved.push(requirement.to_string());
1117        }
1118    }
1119    Ok(resolved)
1120}
1121
1122/// Contracts F5: a UI-only app declares a stage and nothing that implies a process.
1123fn validate_ui_only(manifest: &AppManifest) -> Result<(), String> {
1124    match &manifest.ui {
1125        Some(ui) if ui.kind == AppUiKind::Stage => {}
1126        _ => return Err("ui-only apps must declare a ui block of kind \"stage\"".to_string()),
1127    }
1128    match ui_only_process_declaration(manifest) {
1129        Some(what) => Err(format!(
1130            "ui-only apps have no backend process and must not declare {what}"
1131        )),
1132        None => Ok(()),
1133    }
1134}
1135
1136/// Contracts F5: the first thing `manifest` declares that implies a backend
1137/// process, which a UI-only app cannot have. A UI-only app is never started,
1138/// so it can neither receive events nor wait on dependencies. Shared by
1139/// [`AppManifest::validate`] and `node-app audit`.
1140pub fn ui_only_process_declaration(manifest: &AppManifest) -> Option<&'static str> {
1141    if manifest.entrypoint.is_some() {
1142        Some("'entrypoint'")
1143    } else if manifest.has_capability_providers() {
1144        Some("capability providers ('provides' / 'capabilities.provides')")
1145    } else if manifest.tcp.is_some() {
1146        Some("a 'tcp' block")
1147    } else if manifest.resources.is_some() {
1148        Some("a 'resources' block")
1149    } else if manifest.standalone.is_some() {
1150        Some("a 'standalone' block")
1151    } else if !manifest.subscribes.is_empty() {
1152        Some("event subscriptions ('subscribes')")
1153    } else if manifest
1154        .depends_on
1155        .as_ref()
1156        .is_some_and(|deps| !deps.is_empty())
1157    {
1158        Some("dependencies ('depends_on')")
1159    } else {
1160        None
1161    }
1162}
1163
1164/// Contracts F5: whether a raw manifest is UI-only — a `ui` object with
1165/// neither `app_type` nor `entrypoint`, or an explicit `"app_type":
1166/// "ui-only"`. Read off the raw JSON, because serde's `app_type` default
1167/// (`native`) hides whether the key was there. The one definition shared by
1168/// [`AppManifest::from_json`], `node-app audit` and `node-app package`.
1169///
1170/// Precedence: an explicit `app_type` other than `"ui-only"` always wins
1171/// over the derived form. A manifest with `"app_type": "bun"`, a `ui` block
1172/// and no `entrypoint` is a Bun app, not UI-only — the derived branch's
1173/// `!object.contains_key("app_type")` check is false, so it never fires, and
1174/// [`validate_ui_only`] is skipped for it. The derived form only applies
1175/// when `app_type` is absent entirely.
1176pub fn declares_ui_only(manifest: &serde_json::Value) -> bool {
1177    manifest.as_object().is_some_and(|object| {
1178        let derived = object.get("ui").is_some_and(serde_json::Value::is_object)
1179            && !object.contains_key("app_type")
1180            && !object.contains_key("entrypoint");
1181        derived || object.get("app_type").and_then(serde_json::Value::as_str) == Some("ui-only")
1182    })
1183}
1184
1185fn validate_app_ui(app_name: &str, ui: &AppUiManifest) -> Result<(), String> {
1186    if ui.ui_api != 1 && ui.ui_api != 2 {
1187        return Err(format!(
1188            "ui.ui_api {} is unsupported; only versions 1 and 2 are supported",
1189            ui.ui_api
1190        ));
1191    }
1192    if ui.title.trim().is_empty() {
1193        return Err("ui.title must not be blank".to_string());
1194    }
1195    ui.requires.resolved()?;
1196    validate_manifest_path(&ui.entry).map_err(|error| format!("ui.entry invalid: {error}"))?;
1197    if let Some(icon) = &ui.icon {
1198        validate_manifest_path(icon).map_err(|error| format!("ui.icon invalid: {error}"))?;
1199    }
1200    if let Some(nav) = &ui.nav {
1201        if ui.kind == AppUiKind::Widget {
1202            return Err("widget ui must omit nav metadata".to_string());
1203        }
1204        if nav.section.trim().is_empty() {
1205            return Err("ui.nav.section must not be blank".to_string());
1206        }
1207    }
1208    if let Some(data) = &ui.data {
1209        if ui.kind != AppUiKind::Stage {
1210            return Err("widget ui must omit app data declarations".to_string());
1211        }
1212        validate_app_data(data, &ui.requires.resolved()?)?;
1213    }
1214
1215    let mut composed = HashSet::new();
1216    for name in &ui.composes {
1217        validate_app_name(name).map_err(|error| format!("ui.composes entry invalid: {error}"))?;
1218        if name == app_name {
1219            return Err("ui.composes must not contain the app itself".to_string());
1220        }
1221        if !composed.insert(name) {
1222            return Err(format!("ui.composes contains duplicate app '{name}'"));
1223        }
1224    }
1225
1226    let mut surface_ids = HashSet::new();
1227    for surface in &ui.surfaces {
1228        let id = surface.id.trim();
1229        if id.is_empty() {
1230            return Err("ui.surfaces entry id must not be blank".to_string());
1231        }
1232        if !surface_ids.insert(id.to_string()) {
1233            return Err(format!("ui.surfaces contains duplicate id '{id}'"));
1234        }
1235        if !KNOWN_SURFACE_SLOTS.contains(&surface.slot.as_str()) {
1236            return Err(format!(
1237                "ui.surfaces entry '{id}' requests unknown slot '{}'; known slots: {}",
1238                surface.slot,
1239                KNOWN_SURFACE_SLOTS.join(", ")
1240            ));
1241        }
1242        if surface.title.trim().is_empty() {
1243            return Err(format!("ui.surfaces entry '{id}' title must not be blank"));
1244        }
1245        validate_manifest_path(&surface.entry)
1246            .map_err(|error| format!("ui.surfaces entry '{id}' entry invalid: {error}"))?;
1247        // Same rule `ui.entry` and `ui.icon` get below, and for a sharper reason: the client
1248        // kernel's `ensureIntegrityForUi` (`client/kernel/src/stages/stage-registry-service.js`)
1249        // REQUIRES a digest for every surface entry, and the throw there propagates out of
1250        // `parseCatalogEntry` through `parseCatalogResponse`'s `value.map(...)` — failing the
1251        // whole catalog snapshot, every stage on the node, and looping on retry. Without this
1252        // check a typo, or an entry emitted outside `ui_path` (which is the only tree
1253        // `generate_staged_integrity` stamps), packages cleanly, installs cleanly, and then
1254        // bricks every client's stage list. Refuse it here, where the author can still fix it.
1255        if !ui.integrity.contains_key(&surface.entry) {
1256            return Err(format!("ui.integrity must include surface '{id}' entry"));
1257        }
1258        surface
1259            .requires
1260            .resolved()
1261            .map_err(|error| format!("ui.surfaces entry '{id}' requires invalid: {error}"))?;
1262    }
1263
1264    for (path, digest) in &ui.integrity {
1265        validate_manifest_path(path)
1266            .map_err(|error| format!("ui.integrity path invalid: {error}"))?;
1267        if !is_lowercase_sha256(digest) {
1268            return Err(format!(
1269                "ui.integrity digest for '{path}' must be a lowercase 64-character SHA-256"
1270            ));
1271        }
1272    }
1273    if !ui.integrity.contains_key(&ui.entry) {
1274        return Err("ui.integrity must include the declared entry".to_string());
1275    }
1276    if let Some(icon) = &ui.icon {
1277        if !ui.integrity.contains_key(icon) {
1278            return Err("ui.integrity must include the declared icon".to_string());
1279        }
1280    }
1281    Ok(())
1282}
1283
1284fn validate_app_data(data: &AppDataManifest, resolved_requires: &[String]) -> Result<(), String> {
1285    validate_app_data_namespace(&data.namespace)?;
1286    validate_app_data_sync_policy(&data.sync)?;
1287    if data.queries.is_empty() {
1288        return Err("ui.data.queries must declare at least one query".to_string());
1289    }
1290
1291    let requires: BTreeSet<&str> = resolved_requires.iter().map(String::as_str).collect();
1292    let mut names = BTreeSet::new();
1293    for query in &data.queries {
1294        validate_namespaced_data_name(&query.name, &data.namespace)
1295            .map_err(|error| format!("ui.data query '{}' invalid: {error}", query.name))?;
1296        validate_capability_name(&query.capability).map_err(|error| {
1297            format!(
1298                "ui.data query '{}' capability '{}' invalid: {error}",
1299                query.name, query.capability
1300            )
1301        })?;
1302        if !requires.contains(query.capability.as_str()) {
1303            return Err(format!(
1304                "ui.data query '{}' capability '{}' must be declared in requires",
1305                query.name, query.capability
1306            ));
1307        }
1308        if !names.insert(query.name.as_str()) {
1309            return Err(format!("ui.data contains duplicate query '{}'", query.name));
1310        }
1311    }
1312
1313    for stream in &data.streams {
1314        validate_namespaced_data_name(&stream.name, &data.namespace)
1315            .map_err(|error| format!("ui.data stream '{}' invalid: {error}", stream.name))?;
1316        if !names.insert(stream.name.as_str()) {
1317            return Err(format!(
1318                "ui.data contains duplicate declaration '{}'",
1319                stream.name
1320            ));
1321        }
1322    }
1323
1324    Ok(())
1325}
1326
1327fn validate_app_data_namespace(namespace: &str) -> Result<(), String> {
1328    if !is_safe_name_segment(namespace) {
1329        return Err(format!(
1330            "ui.data namespace '{}' must match [a-z][a-z0-9-]*",
1331            namespace
1332        ));
1333    }
1334    if matches!(
1335        namespace,
1336        "core" | "internal" | "node" | "platform" | "system"
1337    ) {
1338        return Err(format!("ui.data namespace '{namespace}' is reserved"));
1339    }
1340    Ok(())
1341}
1342
1343fn validate_app_data_sync_policy(sync: &AppDataSyncPolicy) -> Result<(), String> {
1344    validate_optional_range("cursor_ttl_secs", sync.cursor_ttl_secs, 60, 86_400)?;
1345    validate_optional_range(
1346        "full_refresh_interval_secs",
1347        sync.full_refresh_interval_secs,
1348        60,
1349        604_800,
1350    )?;
1351    validate_optional_range("retention_secs", sync.retention_secs, 300, 31_536_000)?;
1352    if sync.kind == AppDataSyncKind::Snapshot && sync.cursor_ttl_secs.is_some() {
1353        return Err("ui.data.sync cursor_ttl_secs is only valid for cursor sync".to_string());
1354    }
1355    Ok(())
1356}
1357
1358fn validate_optional_range(
1359    field: &str,
1360    value: Option<u32>,
1361    min: u32,
1362    max: u32,
1363) -> Result<(), String> {
1364    if let Some(value) = value {
1365        if value < min || value > max {
1366            return Err(format!(
1367                "ui.data.sync {field} must be between {min} and {max} seconds"
1368            ));
1369        }
1370    }
1371    Ok(())
1372}
1373
1374fn validate_namespaced_data_name(name: &str, namespace: &str) -> Result<(), String> {
1375    validate_capability_name(name)?;
1376    let Some(rest) = name
1377        .strip_prefix(namespace)
1378        .and_then(|suffix| suffix.strip_prefix('.'))
1379    else {
1380        return Err(format!("name must use namespace '{namespace}'"));
1381    };
1382    if rest.is_empty() {
1383        return Err("name must include a value after its namespace".to_string());
1384    }
1385    if !has_version_suffix(name) {
1386        return Err("name must end with a .vN version suffix".to_string());
1387    }
1388    Ok(())
1389}
1390
1391fn validate_capability_name(name: &str) -> Result<(), String> {
1392    if name.is_empty() {
1393        return Err("name must not be empty".to_string());
1394    }
1395    if name.contains('/') || name.contains("..") {
1396        return Err("name must not contain path separators or traversal".to_string());
1397    }
1398    if !name.split('.').all(is_safe_declaration_segment) {
1399        return Err("name must contain only lowercase dot-separated segments".to_string());
1400    }
1401    Ok(())
1402}
1403
1404fn validate_ui_requirement_name(name: &str, allow_wildcard: bool) -> Result<(), String> {
1405    if allow_wildcard && name.ends_with(".*") {
1406        return validate_capability_name(&name[..name.len() - 2]);
1407    }
1408    validate_capability_name(name)
1409}
1410
1411fn has_version_suffix(name: &str) -> bool {
1412    let Some(version) = name.rsplit('.').next() else {
1413        return false;
1414    };
1415    let Some(digits) = version.strip_prefix('v') else {
1416        return false;
1417    };
1418    !digits.is_empty()
1419        && !digits.starts_with('0')
1420        && digits.bytes().all(|byte| byte.is_ascii_digit())
1421}
1422
1423fn is_safe_name_segment(segment: &str) -> bool {
1424    if segment.is_empty() {
1425        return false;
1426    }
1427    let mut chars = segment.chars();
1428    let Some(first) = chars.next() else {
1429        return false;
1430    };
1431    first.is_ascii_lowercase()
1432        && chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-')
1433}
1434
1435/// A segment of a capability, query, or stream name.
1436///
1437/// Deliberately looser than [`is_safe_name_segment`] by exactly one character:
1438/// `_`. Capability actions in this codebase are snake_case almost without
1439/// exception (`core.lightning.create_invoice`, `core.did.current_did`,
1440/// `contest.world.studio_state`), and app-event resources are too
1441/// (`app.agent_session` — `APP_EVENT_RESOURCE_PATTERN` in `@econ-v1/domain`
1442/// admits `_` for precisely these). Rejecting `_` here did not make a stage
1443/// safer, it made `ui.requires` unusable: a stage that declared any real
1444/// capability failed `resolved()`, and `build_ui_stage_catalog` then dropped
1445/// that stage from the shell entirely. The characters that actually matter —
1446/// path separators, traversal, uppercase, leading digits — are still refused.
1447fn is_safe_declaration_segment(segment: &str) -> bool {
1448    let mut chars = segment.chars();
1449    let Some(first) = chars.next() else {
1450        return false;
1451    };
1452    first.is_ascii_lowercase()
1453        && chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-' || ch == '_')
1454}
1455
1456fn is_lowercase_sha256(value: &str) -> bool {
1457    value.len() == 64
1458        && value
1459            .bytes()
1460            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1461}
1462
1463/// Validate a `StandaloneConfig::socket_path`.
1464///
1465/// Rules:
1466/// 1. Absolute path (starts with `/`).
1467/// 2. Lives under `/run/` (rejects `/etc/...`, `/tmp/...`, etc. — pins the
1468///    socket to a tmpfs path predictably writable by the standalone daemon).
1469///    Runtime adapters can explicitly bypass this restriction for development.
1470/// 3. No `..` segments anywhere in the path.
1471pub fn validate_standalone_socket_path(path: &std::path::Path) -> Result<(), String> {
1472    validate_standalone_socket_path_with_policy(path, false)
1473}
1474
1475/// Validate a standalone socket path with an explicit runtime policy.
1476pub fn validate_standalone_socket_path_with_policy(
1477    path: &std::path::Path,
1478    allow_non_run: bool,
1479) -> Result<(), String> {
1480    if !path.is_absolute() {
1481        return Err(format!(
1482            "standalone.socket_path '{}' must be absolute",
1483            path.display()
1484        ));
1485    }
1486    if !allow_non_run && !path.starts_with("/run/") {
1487        return Err(format!(
1488            "standalone.socket_path '{}' must live under /run/",
1489            path.display()
1490        ));
1491    }
1492    if path
1493        .components()
1494        .any(|c| matches!(c, std::path::Component::ParentDir))
1495    {
1496        return Err(format!(
1497            "standalone.socket_path '{}' must not contain '..' segments",
1498            path.display()
1499        ));
1500    }
1501    Ok(())
1502}
1503
1504/// Validate an app name string.
1505///
1506/// Accepts `app-name` (simple) and `publisher/app-name` (publisher-prefixed, FR-019).
1507fn validate_app_name(name: &str) -> Result<(), String> {
1508    let (publisher, app) = if let Some(slash) = name.find('/') {
1509        let (p, rest) = name.split_at(slash);
1510        (Some(p), &rest[1..])
1511    } else {
1512        (None, name)
1513    };
1514
1515    let valid_segment = |s: &str| -> bool {
1516        if s.is_empty() {
1517            return false;
1518        }
1519        let mut chars = s.chars();
1520        let first = chars.next().unwrap();
1521        if !first.is_ascii_lowercase() {
1522            return false;
1523        }
1524        chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
1525    };
1526
1527    if let Some(pub_name) = publisher {
1528        if !valid_segment(pub_name) {
1529            return Err(format!(
1530                "publisher segment '{}' must match [a-z][a-z0-9-]*",
1531                pub_name
1532            ));
1533        }
1534    }
1535
1536    if !valid_segment(app) {
1537        return Err(format!(
1538            "app name segment '{}' must match [a-z][a-z0-9-]*",
1539            app
1540        ));
1541    }
1542
1543    Ok(())
1544}
1545
1546// ── Tests ─────────────────────────────────────────────────────────────────────
1547
1548#[cfg(test)]
1549mod tests {
1550    use super::*;
1551
1552    fn parse_ok(json: &str) -> AppManifest {
1553        AppManifest::from_json(json).expect("should parse")
1554    }
1555
1556    fn parse_err(json: &str) -> String {
1557        AppManifest::from_json(json).expect_err("should fail")
1558    }
1559
1560    // ── v1 manifests ──────────────────────────────────────────────────────────
1561
1562    #[test]
1563    fn v1_minimal_native() {
1564        let m = parse_ok(r#"{"name":"cron","version":"1.0.0","app_type":"native"}"#);
1565        assert_eq!(m.manifest_version, 1);
1566        assert_eq!(m.app_type, AppType::Native);
1567        assert!(m.abi.is_none());
1568    }
1569
1570    #[test]
1571    fn v1_minimal_bun() {
1572        let m = parse_ok(r#"{"name":"my-app","version":"0.1.0","app_type":"bun"}"#);
1573        assert_eq!(m.app_type, AppType::Bun);
1574        assert_eq!(m.effective_entrypoint(), "dist/index.js");
1575    }
1576
1577    #[test]
1578    fn v1_no_manifest_version_field_defaults_to_1() {
1579        let m = parse_ok(r#"{"name":"example","version":"1.0.0","app_type":"bun"}"#);
1580        assert_eq!(m.manifest_version, 1);
1581    }
1582
1583    #[test]
1584    fn v1_all_optional_fields_missing() {
1585        let m = parse_ok(r#"{"name":"example","version":"1.0.0","app_type":"bun"}"#);
1586        assert!(!m.critical);
1587        assert!(m.auto_start);
1588        assert!(!m.has_ui);
1589        assert_eq!(m.ui_path, "dist");
1590        assert!(m.permissions.is_empty());
1591        assert!(m.optional_permissions.is_empty());
1592        // #1556: governor/subscribes absent → today's implicit behavior
1593        // (no opt-out, no min-idle override, no declared subscriptions).
1594        assert!(m.governor.is_none());
1595        assert!(m.subscribes.is_empty());
1596    }
1597
1598    #[test]
1599    fn v1_with_permissions_and_provides() {
1600        let json = r#"{
1601            "name": "example",
1602            "version": "1.0.0",
1603            "app_type": "bun",
1604            "permissions": ["core.storage.kv"],
1605            "optional_permissions": ["core.notifications.create"],
1606            "provides": {
1607                "core.example.run": { "description": "Run example job" }
1608            }
1609        }"#;
1610        let m = parse_ok(json);
1611        assert_eq!(m.permissions, vec!["core.storage.kv"]);
1612        assert_eq!(m.optional_permissions, vec!["core.notifications.create"]);
1613        assert!(m.provides.contains_key("core.example.run"));
1614    }
1615
1616    // ── v2 manifests ──────────────────────────────────────────────────────────
1617
1618    #[test]
1619    fn v2_minimal_native() {
1620        let json = r#"{
1621            "manifest_version": 2,
1622            "name": "cron",
1623            "version": "1.0.0",
1624            "app_type": "native",
1625            "abi": "v1",
1626            "entrypoint": "app.so",
1627            "hot_reload": "experimental"
1628        }"#;
1629        let m = parse_ok(json);
1630        assert_eq!(m.manifest_version, 2);
1631        assert_eq!(m.abi, Some(AbiVersion::V1));
1632        assert_eq!(m.entrypoint.as_deref(), Some("app.so"));
1633        assert_eq!(m.hot_reload, Some(HotReloadKind::Experimental));
1634    }
1635
1636    #[test]
1637    fn v2_minimal_bun_with_capabilities() {
1638        let json = r#"{
1639            "manifest_version": 2,
1640            "name": "example-fullstack",
1641            "version": "1.0.0",
1642            "app_type": "bun",
1643            "abi": "v1",
1644            "entrypoint": "dist/index.js",
1645            "hot_reload": "supported",
1646            "has_ui": true,
1647            "ui_path": "ui/dist",
1648            "capabilities": {
1649                "requires": ["core.storage.kv", "core.lightning.payment.send:max=500sat/day"],
1650                "provides": []
1651            },
1652            "governor": { "terminable": false, "min_idle_secs": 300 },
1653            "subscribes": ["core.chat.message.received"]
1654        }"#;
1655        let m = parse_ok(json);
1656        assert_eq!(m.manifest_version, 2);
1657        assert_eq!(m.capabilities.requires.len(), 2);
1658        // #1556: governor/subscribes present → parsed through verbatim.
1659        let governor = m.governor.expect("governor block should parse");
1660        assert_eq!(governor.terminable, Some(false));
1661        assert_eq!(governor.min_idle_secs, Some(300));
1662        assert_eq!(m.subscribes, vec!["core.chat.message.received"]);
1663    }
1664
1665    #[test]
1666    fn stage_contract_fixture_parses_with_normalized_requirements() {
1667        let json = include_str!(
1668            "../../../specs/456-node-app-distribution-infrastructure/contracts/fixtures/stage-manifest-v2.json"
1669        );
1670        let m = parse_ok(json);
1671        assert!(m.has_ui);
1672        assert_eq!(m.resolved_requires().unwrap(), vec!["core.metrics.latest"]);
1673        let ui = m.ui.expect("fixture should declare ui");
1674        assert_eq!(ui.kind, AppUiKind::Stage);
1675        assert_eq!(ui.entry, "ui/main.js");
1676        assert_eq!(ui.nav.unwrap().order, 10);
1677    }
1678
1679    #[test]
1680    fn omitted_ui_keeps_legacy_flags_without_fabricating_a_stage() {
1681        let m = parse_ok(
1682            r#"{"name":"legacy","version":"1.0.0","app_type":"bun","has_ui":true,"ui_path":"ui/dist"}"#,
1683        );
1684        assert!(m.has_ui);
1685        assert_eq!(m.ui_path, "ui/dist");
1686        assert!(m.ui.is_none());
1687    }
1688
1689    #[test]
1690    fn ui_requirements_are_typed_serialized_and_separate_from_backend_requires() {
1691        let manifest = parse_ok(
1692            r#"{
1693                "name":"ui-contract","version":"1.0.0","app_type":"bun",
1694                "requires":["core.cron.register"],
1695                "ui":{
1696                    "kind":"stage","entry":"ui/main.js","title":"UI contract","ui_api":1,
1697                    "requires":{
1698                        "capabilities":["ui.snapshot.v1"],
1699                        "queries":["ui.query.v1"],
1700                        "streams":["ui.event.v1"]
1701                    },
1702                    "integrity":{"ui/main.js":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}
1703                }
1704            }"#,
1705        );
1706
1707        assert_eq!(
1708            manifest.resolved_requires().unwrap(),
1709            vec!["core.cron.register"]
1710        );
1711        let ui = manifest.ui.as_ref().expect("ui requirements should parse");
1712        assert_eq!(ui.requires.capabilities, vec!["ui.snapshot.v1"]);
1713        assert_eq!(ui.requires.queries, vec!["ui.query.v1"]);
1714        assert_eq!(ui.requires.streams, vec!["ui.event.v1"]);
1715        assert_eq!(
1716            ui.requires.resolved().unwrap(),
1717            vec!["ui.snapshot.v1", "ui.query.v1", "ui.event.v1"]
1718        );
1719        let serialized = serde_json::to_value(ui).unwrap();
1720        assert_eq!(
1721            serialized["requires"]["queries"],
1722            serde_json::json!(["ui.query.v1"])
1723        );
1724    }
1725
1726    #[test]
1727    fn ui_requirements_reject_blank_entries() {
1728        let error = parse_err(
1729            r#"{
1730                "name":"ui-contract","version":"1.0.0","app_type":"bun",
1731                "ui":{
1732                    "kind":"stage","entry":"ui/main.js","title":"UI contract","ui_api":1,
1733                    "requires":{"capabilities":[""],"queries":[],"streams":[]},
1734                    "integrity":{"ui/main.js":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}
1735                }
1736            }"#,
1737        );
1738        assert!(error.contains("ui.requires entries must not be blank"));
1739    }
1740
1741    #[test]
1742    fn ui_data_namespace_stays_hyphen_only_when_declarations_allow_underscore() {
1743        // `is_safe_declaration_segment` deliberately admits `_` so `ui.requires`
1744        // can name real capabilities. `ui.data.namespace` is a different thing —
1745        // a storage key, contract `[a-z][a-z0-9-]*` — and keeps the stricter
1746        // `is_safe_name_segment`. Nothing else pins that separation, so a future
1747        // refactor collapsing the two predicates back together would silently
1748        // widen the namespace rule. This is the tripwire for that.
1749        assert!(validate_app_data_namespace("obs-viewer").is_ok());
1750
1751        let error = validate_app_data_namespace("obs_viewer")
1752            .expect_err("underscore must not be admitted into a storage namespace");
1753        assert!(
1754            error.contains("must match [a-z][a-z0-9-]*"),
1755            "unexpected error: {error}"
1756        );
1757    }
1758
1759    #[test]
1760    fn ui_data_query_capability_does_not_fall_back_to_backend_requires() {
1761        let error = parse_err(
1762            r#"{
1763                "name":"ui-data","version":"1.0.0","app_type":"bun",
1764                "requires":["ui.snapshot.v1"],
1765                "ui":{
1766                    "kind":"stage","entry":"ui/main.js","title":"UI data","ui_api":1,
1767                    "requires":{"capabilities":[],"queries":[],"streams":[]},
1768                    "integrity":{"ui/main.js":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
1769                    "data":{
1770                        "namespace":"ui-data","offline":"last-known","sync":{"kind":"cursor"},
1771                        "queries":[{"name":"ui-data.snapshot.v1","capability":"ui.snapshot.v1","kind":"snapshot"}],
1772                        "streams":[]
1773                    }
1774                }
1775            }"#,
1776        );
1777        assert!(error.contains("must be declared in requires"));
1778    }
1779
1780    #[test]
1781    fn top_level_and_nested_requires_must_resolve_to_the_same_set() {
1782        let accepted = parse_ok(
1783            r#"{
1784                "name":"aliases","version":"1.0.0","app_type":"bun",
1785                "requires":["core.chat.read","core.chat.read","core.chat.send"],
1786                "capabilities":{"requires":["core.chat.send","core.chat.read"]}
1787            }"#,
1788        );
1789        assert_eq!(
1790            accepted.resolved_requires().unwrap(),
1791            vec!["core.chat.read", "core.chat.send"]
1792        );
1793
1794        let err = parse_err(
1795            r#"{
1796                "name":"aliases","version":"1.0.0","app_type":"bun",
1797                "requires":["core.chat.read"],
1798                "capabilities":{"requires":["core.wallet.pay"]}
1799            }"#,
1800        );
1801        assert!(err.contains("conflicts"), "unexpected error: {err}");
1802    }
1803
1804    #[test]
1805    fn stage_and_widget_ui_kinds_have_distinct_navigation_rules() {
1806        let base = |ui: &str| {
1807            format!(r#"{{"name":"stage","version":"1.0.0","app_type":"bun","ui":{ui}}}"#)
1808        };
1809        let widget = base(
1810            r#"{"kind":"widget","entry":"ui/main.js","title":"Stage","ui_api":1,"integrity":{"ui/main.js":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}"#,
1811        );
1812        assert_eq!(
1813            parse_ok(&widget).ui.expect("widget ui").kind,
1814            AppUiKind::Widget
1815        );
1816        let widget_nav = base(
1817            r#"{"kind":"widget","entry":"ui/main.js","title":"Widget","nav":{"section":"default","order":1},"ui_api":1,"integrity":{"ui/main.js":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}"#,
1818        );
1819        assert!(parse_err(&widget_nav).contains("must omit nav"));
1820        let api = base(
1821            r#"{"kind":"stage","entry":"ui/main.js","title":"Stage","ui_api":2,"integrity":{"ui/main.js":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}"#,
1822        );
1823        assert_eq!(parse_ok(&api).ui.expect("v2 stage ui").ui_api, 2);
1824        let unsupported_api = base(
1825            r#"{"kind":"stage","entry":"ui/main.js","title":"Stage","ui_api":3,"integrity":{"ui/main.js":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}"#,
1826        );
1827        assert!(parse_err(&unsupported_api).contains("ui_api"));
1828        let path = base(
1829            r#"{"kind":"stage","entry":"../main.js","title":"Stage","ui_api":1,"integrity":{"../main.js":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}"#,
1830        );
1831        assert!(parse_err(&path).contains("entry"));
1832    }
1833
1834    #[test]
1835    fn stage_requires_integrity_for_entry_and_icon() {
1836        let missing_entry = r#"{
1837            "name":"stage","version":"1.0.0","app_type":"bun",
1838            "ui":{"entry":"ui/main.js","title":"Stage","ui_api":1,"integrity":{}}
1839        }"#;
1840        assert!(parse_err(missing_entry).contains("entry"));
1841        let missing_icon = r#"{
1842            "name":"stage","version":"1.0.0","app_type":"bun",
1843            "ui":{"entry":"ui/main.js","icon":"ui/icon.svg","title":"Stage","ui_api":1,
1844            "integrity":{"ui/main.js":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}
1845        }"#;
1846        assert!(parse_err(missing_icon).contains("icon"));
1847        let uppercase = r#"{
1848            "name":"stage","version":"1.0.0","app_type":"bun",
1849            "ui":{"entry":"ui/main.js","title":"Stage","ui_api":1,
1850            "integrity":{"ui/main.js":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}}
1851        }"#;
1852        assert!(parse_err(uppercase).contains("lowercase"));
1853    }
1854
1855    #[test]
1856    fn stage_composes_rejects_self_duplicate_and_unsafe_names() {
1857        let manifest = |composes: &str| {
1858            format!(
1859                r#"{{
1860                    "name":"stage","version":"1.0.0","app_type":"bun",
1861                    "ui":{{"entry":"ui/main.js","title":"Stage","ui_api":1,
1862                    "composes":{composes},
1863                    "integrity":{{"ui/main.js":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}}}
1864                }}"#
1865            )
1866        };
1867        assert!(parse_err(&manifest(r#"["stage"]"#)).contains("itself"));
1868        assert!(parse_err(&manifest(r#"["chat","chat"]"#)).contains("duplicate"));
1869        assert!(parse_err(&manifest(r#"["../chat"]"#)).contains("invalid"));
1870    }
1871
1872    // ── ui.surfaces[] ────────────────────────────────────────────────────────
1873
1874    /// A minimal valid manifest with a `ui` block, for tests that only care
1875    /// about `ui.surfaces`. Mirrors the fixture used by
1876    /// `stage_requires_integrity_for_entry_and_icon` above.
1877    ///
1878    /// The integrity map covers `surface()`'s entry as well as `ui.entry`, because a surface
1879    /// entry must be integrity-pinned exactly like the stage entry and the icon — see
1880    /// `surface_entry_missing_from_integrity_is_rejected`. Before that rule existed this fixture
1881    /// declared a surface no digest covered, which is precisely the manifest the client kernel
1882    /// refuses.
1883    fn manifest_with_ui() -> AppManifest {
1884        parse_ok(
1885            r#"{
1886                "name":"stage","version":"1.0.0","app_type":"bun",
1887                "ui":{"entry":"ui/main.js","title":"Stage","ui_api":1,
1888                "integrity":{"ui/main.js":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1889                "ui/dist/surfaces/chip.js":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}}
1890            }"#,
1891        )
1892    }
1893
1894    fn surface(id: &str, slot: &str) -> AppUiSurface {
1895        AppUiSurface {
1896            id: id.to_string(),
1897            slot: slot.to_string(),
1898            entry: "ui/dist/surfaces/chip.js".to_string(),
1899            title: "Chip".to_string(),
1900            order: 10,
1901            requires: AppUiRequirements {
1902                capabilities: vec!["wallet.balance.get".to_string()],
1903                ..Default::default()
1904            },
1905        }
1906    }
1907
1908    #[test]
1909    fn manifest_without_surfaces_still_parses() {
1910        let manifest = manifest_with_ui();
1911        assert!(manifest.ui.as_ref().unwrap().surfaces.is_empty());
1912        assert!(manifest.validate().is_ok());
1913    }
1914
1915    #[test]
1916    fn surface_in_a_known_slot_is_accepted() {
1917        let mut manifest = manifest_with_ui();
1918        manifest.ui.as_mut().unwrap().surfaces = vec![surface("balance-chip", "status-rail")];
1919        assert!(manifest.validate().is_ok());
1920    }
1921
1922    #[test]
1923    fn surface_in_an_unknown_slot_is_rejected() {
1924        let mut manifest = manifest_with_ui();
1925        manifest.ui.as_mut().unwrap().surfaces = vec![surface("balance-chip", "menu-bar")];
1926        let error = manifest.validate().unwrap_err();
1927        assert!(error.contains("menu-bar"), "unexpected error: {error}");
1928    }
1929
1930    #[test]
1931    fn duplicate_surface_ids_are_rejected() {
1932        let mut manifest = manifest_with_ui();
1933        manifest.ui.as_mut().unwrap().surfaces = vec![
1934            surface("chip", "status-rail"),
1935            surface("chip", "status-rail"),
1936        ];
1937        let error = manifest.validate().unwrap_err();
1938        assert!(error.contains("duplicate"), "unexpected error: {error}");
1939    }
1940
1941    #[test]
1942    fn surface_with_a_blank_id_is_rejected() {
1943        let mut manifest = manifest_with_ui();
1944        manifest.ui.as_mut().unwrap().surfaces = vec![surface("  ", "status-rail")];
1945        assert!(manifest.validate().is_err());
1946    }
1947
1948    #[test]
1949    fn surface_with_an_unsafe_entry_path_is_rejected() {
1950        let mut manifest = manifest_with_ui();
1951        let mut bad = surface("chip", "status-rail");
1952        bad.entry = "../../etc/passwd".to_string();
1953        manifest.ui.as_mut().unwrap().surfaces = vec![bad];
1954        assert!(manifest.validate().is_err());
1955    }
1956
1957    #[test]
1958    fn surface_entry_missing_from_integrity_is_rejected() {
1959        // The client kernel requires a digest for every surface entry and fails the WHOLE
1960        // catalog snapshot when one is missing, so a manifest that packages without one bricks
1961        // every installing node's stage list. Catch it at package time instead.
1962        let mut manifest = manifest_with_ui();
1963        let mut unpinned = surface("chip", "status-rail");
1964        unpinned.entry = "ui/dist/surfaces/typo.js".to_string();
1965        manifest.ui.as_mut().unwrap().surfaces = vec![unpinned];
1966        let error = manifest.validate().unwrap_err();
1967        assert!(
1968            error.contains("ui.integrity must include surface 'chip' entry"),
1969            "unexpected error: {error}"
1970        );
1971    }
1972
1973    #[test]
1974    fn surface_with_a_blank_required_capability_is_rejected() {
1975        let mut manifest = manifest_with_ui();
1976        let mut bad = surface("chip", "status-rail");
1977        bad.requires.capabilities = vec!["   ".to_string()];
1978        manifest.ui.as_mut().unwrap().surfaces = vec![bad];
1979        assert!(manifest.validate().is_err());
1980    }
1981
1982    #[test]
1983    fn v2_missing_abi_is_error() {
1984        let json = r#"{
1985            "manifest_version": 2,
1986            "name": "example",
1987            "version": "1.0.0",
1988            "app_type": "bun"
1989        }"#;
1990        let err = parse_err(json);
1991        assert!(err.contains("abi"), "expected abi error, got: {}", err);
1992    }
1993
1994    // ── Publisher-prefixed name (FR-019) ──────────────────────────────────────
1995
1996    #[test]
1997    fn publisher_prefixed_name_accepted() {
1998        let m = parse_ok(r#"{"name":"alice/weather","version":"1.0.0","app_type":"bun"}"#);
1999        assert_eq!(m.name, "alice/weather");
2000    }
2001
2002    #[test]
2003    fn double_slash_name_rejected() {
2004        let err = parse_err(r#"{"name":"a/b/c","version":"1.0.0","app_type":"bun"}"#);
2005        assert!(!err.is_empty());
2006    }
2007
2008    // ── Malformed names ───────────────────────────────────────────────────────
2009
2010    #[test]
2011    fn name_starting_with_digit_rejected() {
2012        let err = parse_err(r#"{"name":"1bad","version":"1.0.0","app_type":"bun"}"#);
2013        assert!(!err.is_empty());
2014    }
2015
2016    #[test]
2017    fn name_with_uppercase_rejected() {
2018        let err = parse_err(r#"{"name":"MyApp","version":"1.0.0","app_type":"bun"}"#);
2019        assert!(!err.is_empty());
2020    }
2021
2022    #[test]
2023    fn empty_name_rejected() {
2024        let err = parse_err(r#"{"name":"","version":"1.0.0","app_type":"bun"}"#);
2025        assert!(!err.is_empty());
2026    }
2027
2028    // ── Path-safety (SEC-H3) ─────────────────────────────────────────────────
2029
2030    #[test]
2031    fn path_traversal_double_dot_rejected() {
2032        let json = r#"{
2033            "manifest_version": 2, "name": "evil", "version": "1.0.0",
2034            "app_type": "bun", "abi": "v1",
2035            "entrypoint": "../etc/passwd"
2036        }"#;
2037        let err = parse_err(json);
2038        assert!(err.contains(".."), "expected traversal error, got: {}", err);
2039    }
2040
2041    #[test]
2042    fn path_traversal_encoded_dot_not_decoded() {
2043        // The regex rejects '%' so encoded traversal fails at char check
2044        let json = r#"{
2045            "manifest_version": 2, "name": "evil", "version": "1.0.0",
2046            "app_type": "bun", "abi": "v1",
2047            "entrypoint": "foo/../bar"
2048        }"#;
2049        let err = parse_err(json);
2050        assert!(!err.is_empty(), "should have failed: {}", err);
2051    }
2052
2053    #[test]
2054    fn absolute_path_rejected() {
2055        let json = r#"{
2056            "manifest_version": 2, "name": "evil", "version": "1.0.0",
2057            "app_type": "bun", "abi": "v1",
2058            "entrypoint": "/usr/bin/sh"
2059        }"#;
2060        let err = parse_err(json);
2061        assert!(
2062            err.contains("absolute"),
2063            "expected absolute error, got: {}",
2064            err
2065        );
2066    }
2067
2068    #[test]
2069    fn shell_metachar_in_path_rejected() {
2070        let json = r#"{
2071            "manifest_version": 2, "name": "evil", "version": "1.0.0",
2072            "app_type": "bun", "abi": "v1",
2073            "entrypoint": "dist/index.js;rm -rf /"
2074        }"#;
2075        let err = parse_err(json);
2076        assert!(!err.is_empty());
2077    }
2078
2079    #[test]
2080    fn valid_nested_path_accepted() {
2081        let json = r#"{
2082            "manifest_version": 2, "name": "my-app", "version": "1.0.0",
2083            "app_type": "bun", "abi": "v1",
2084            "entrypoint": "dist/index.js",
2085            "ui_path": "ui/dist"
2086        }"#;
2087        parse_ok(json);
2088    }
2089
2090    // ── Homepage scheme ───────────────────────────────────────────────────────
2091
2092    #[test]
2093    fn homepage_https_accepted() {
2094        let json = r#"{
2095            "name": "my-app", "version": "1.0.0", "app_type": "bun",
2096            "homepage": "https://example.com"
2097        }"#;
2098        parse_ok(json);
2099    }
2100
2101    #[test]
2102    fn homepage_javascript_scheme_rejected() {
2103        let json = r#"{
2104            "name": "my-app", "version": "1.0.0", "app_type": "bun",
2105            "homepage": "javascript:alert(1)"
2106        }"#;
2107        let err = parse_err(json);
2108        assert!(
2109            err.contains("scheme"),
2110            "expected scheme error, got: {}",
2111            err
2112        );
2113    }
2114
2115    #[test]
2116    fn homepage_file_scheme_rejected() {
2117        let json = r#"{
2118            "name": "my-app", "version": "1.0.0", "app_type": "bun",
2119            "homepage": "file:///etc/passwd"
2120        }"#;
2121        let err = parse_err(json);
2122        assert!(!err.is_empty());
2123    }
2124
2125    // ── Effective defaults ────────────────────────────────────────────────────
2126
2127    #[test]
2128    fn effective_entrypoint_native_default() {
2129        let m = parse_ok(r#"{"name":"cron","version":"1.0.0","app_type":"native"}"#);
2130        assert_eq!(m.effective_entrypoint(), "app.so");
2131    }
2132
2133    #[test]
2134    fn effective_entrypoint_bun_default() {
2135        let m = parse_ok(r#"{"name":"myapp","version":"1.0.0","app_type":"bun"}"#);
2136        assert_eq!(m.effective_entrypoint(), "dist/index.js");
2137    }
2138
2139    #[test]
2140    fn effective_hot_reload_native_default_is_experimental() {
2141        let m = parse_ok(r#"{"name":"cron","version":"1.0.0","app_type":"native"}"#);
2142        assert_eq!(m.effective_hot_reload(), HotReloadKind::Experimental);
2143    }
2144
2145    #[test]
2146    fn effective_hot_reload_bun_default_is_supported() {
2147        let m = parse_ok(r#"{"name":"myapp","version":"1.0.0","app_type":"bun"}"#);
2148        assert_eq!(m.effective_hot_reload(), HotReloadKind::Supported);
2149    }
2150
2151    #[test]
2152    fn hot_reload_unsupported_explicit() {
2153        let json = r#"{
2154            "manifest_version": 2, "name": "myapp", "version": "1.0.0",
2155            "app_type": "bun", "abi": "v1", "hot_reload": "unsupported"
2156        }"#;
2157        let m = parse_ok(json);
2158        assert_eq!(m.effective_hot_reload(), HotReloadKind::Unsupported);
2159    }
2160
2161    // ── validate_manifest_path unit tests ─────────────────────────────────────
2162
2163    #[test]
2164    fn validate_path_simple_valid() {
2165        assert!(validate_manifest_path("dist/index.js").is_ok());
2166        assert!(validate_manifest_path("app.so").is_ok());
2167        assert!(validate_manifest_path("ui/dist/bundle.js").is_ok());
2168        assert!(validate_manifest_path("build_output/main").is_ok());
2169    }
2170
2171    #[test]
2172    fn validate_path_empty_rejected() {
2173        assert!(validate_manifest_path("").is_err());
2174    }
2175
2176    #[test]
2177    fn validate_path_absolute_rejected() {
2178        assert!(validate_manifest_path("/usr/bin/sh").is_err());
2179    }
2180
2181    #[test]
2182    fn validate_path_double_dot_segment_rejected() {
2183        assert!(validate_manifest_path("foo/../bar").is_err());
2184        assert!(validate_manifest_path("../etc/passwd").is_err());
2185    }
2186
2187    #[test]
2188    fn validate_path_leading_dot_rejected() {
2189        assert!(validate_manifest_path(".hidden").is_err());
2190    }
2191
2192    #[test]
2193    fn validate_path_null_byte_rejected() {
2194        // null byte is non-ASCII, rejected by char check
2195        let path = "foo\0bar";
2196        assert!(validate_manifest_path(path).is_err());
2197    }
2198
2199    #[test]
2200    fn standalone_socket_path_development_override_is_explicit_and_pure() {
2201        let path = std::path::Path::new("/tmp/node-app/example.sock");
2202        assert!(validate_standalone_socket_path(path).is_err());
2203        assert!(validate_standalone_socket_path_with_policy(path, true).is_ok());
2204        assert!(validate_standalone_socket_path_with_policy(
2205            std::path::Path::new("/tmp/node-app/../escape.sock"),
2206            true,
2207        )
2208        .is_err());
2209    }
2210
2211    // ── ManifestCapabilities defaults ─────────────────────────────────────────
2212
2213    #[test]
2214    fn manifest_capabilities_defaults_to_empty() {
2215        let m = parse_ok(r#"{"name":"myapp","version":"1.0.0","app_type":"bun"}"#);
2216        assert!(m.capabilities.requires.is_empty());
2217        assert!(m.capabilities.provides.is_empty());
2218    }
2219
2220    // ── resolved_capability_provides (T28 standalone-registration shaping) ────
2221
2222    #[test]
2223    fn resolved_capability_provides_v1_only() {
2224        let json = r#"{
2225            "name": "example", "version": "1.0.0", "app_type": "bun",
2226            "provides": { "core.example.run": { "description": "Run example job" } }
2227        }"#;
2228        let m = parse_ok(json);
2229        let out = m.resolved_capability_provides();
2230        assert_eq!(out.len(), 1);
2231        assert_eq!(
2232            out.get("core.example.run").unwrap().description,
2233            "Run example job"
2234        );
2235    }
2236
2237    #[test]
2238    fn resolved_capability_provides_v2_names_get_blank_declaration() {
2239        let json = r#"{
2240            "manifest_version": 2, "name": "example", "version": "1.0.0",
2241            "app_type": "bun", "abi": "v1",
2242            "capabilities": { "requires": [], "provides": ["core.example.run", "core.example.other:extra"] }
2243        }"#;
2244        let m = parse_ok(json);
2245        let out = m.resolved_capability_provides();
2246        assert_eq!(out.len(), 2);
2247        assert_eq!(out.get("core.example.run").unwrap().description, "");
2248        assert!(out.get("core.example.run").unwrap().schema.is_none());
2249        // Only the part before the first ':' is used as the name.
2250        assert!(out.contains_key("core.example.other"));
2251        assert!(!out.contains_key("core.example.other:extra"));
2252    }
2253
2254    #[test]
2255    fn resolved_capability_provides_v1_wins_on_conflict() {
2256        let json = r#"{
2257            "manifest_version": 2, "name": "example", "version": "1.0.0",
2258            "app_type": "bun", "abi": "v1",
2259            "provides": { "core.example.run": { "description": "v1 wins" } },
2260            "capabilities": { "requires": [], "provides": ["core.example.run"] }
2261        }"#;
2262        let m = parse_ok(json);
2263        let out = m.resolved_capability_provides();
2264        assert_eq!(out.len(), 1);
2265        assert_eq!(out.get("core.example.run").unwrap().description, "v1 wins");
2266    }
2267
2268    #[test]
2269    fn resolved_capability_provides_blank_v2_name_skipped() {
2270        let json = r#"{
2271            "manifest_version": 2, "name": "example", "version": "1.0.0",
2272            "app_type": "bun", "abi": "v1",
2273            "capabilities": { "requires": [], "provides": ["  ", "core.example.run"] }
2274        }"#;
2275        let m = parse_ok(json);
2276        let out = m.resolved_capability_provides();
2277        assert_eq!(out.len(), 1);
2278        assert!(out.contains_key("core.example.run"));
2279    }
2280
2281    #[test]
2282    fn resolved_capability_provides_empty_manifest_yields_empty_map() {
2283        let m = parse_ok(r#"{"name":"myapp","version":"1.0.0","app_type":"bun"}"#);
2284        assert!(m.resolved_capability_provides().is_empty());
2285    }
2286
2287    // ── ABI version ───────────────────────────────────────────────────────────
2288
2289    #[test]
2290    fn abi_v1_is_supported() {
2291        assert!(AbiVersion::V1.is_supported());
2292    }
2293
2294    // ── AppTier display ───────────────────────────────────────────────────────
2295
2296    #[test]
2297    fn app_tier_display() {
2298        assert_eq!(AppTier::FirstParty.to_string(), "first_party");
2299        assert_eq!(AppTier::Optional.to_string(), "optional");
2300        assert_eq!(AppTier::Development.to_string(), "development");
2301    }
2302
2303    #[test]
2304    fn app_tier_serde_roundtrip() {
2305        // Wire format must stay snake_case for the existing API contract.
2306        for tier in [AppTier::FirstParty, AppTier::Optional, AppTier::Development] {
2307            let json = serde_json::to_string(&tier).unwrap();
2308            let back: AppTier = serde_json::from_str(&json).unwrap();
2309            assert_eq!(
2310                tier, back,
2311                "roundtrip failed for {:?}: serialized as {}",
2312                tier, json
2313            );
2314        }
2315        assert_eq!(
2316            serde_json::to_string(&AppTier::Development).unwrap(),
2317            "\"development\""
2318        );
2319    }
2320
2321    // ── AppType display ───────────────────────────────────────────────────────
2322
2323    #[test]
2324    fn app_type_display() {
2325        assert_eq!(AppType::Native.to_string(), "native");
2326        assert_eq!(AppType::Bun.to_string(), "bun");
2327        assert_eq!(AppType::PlatformRuntime.to_string(), "platform-runtime");
2328    }
2329
2330    #[test]
2331    fn platform_runtime_is_a_supported_packaging_type() {
2332        let manifest: AppManifest = serde_json::from_value(serde_json::json!({
2333            "manifest_version": 2,
2334            "abi": "v1",
2335            "name": "bun-runtime",
2336            "version": "1.0.0",
2337            "app_type": "platform-runtime",
2338            "entrypoint": "bun"
2339        }))
2340        .expect("platform runtime manifest should parse");
2341
2342        assert_eq!(manifest.app_type, AppType::PlatformRuntime);
2343        assert_eq!(manifest.effective_hot_reload(), HotReloadKind::Unsupported);
2344    }
2345
2346    // ── GovernorManifest memory budget ──────────────────────────────────────────
2347
2348    #[test]
2349    fn governor_manifest_memory_budget_defaults_to_none() {
2350        let parsed: GovernorManifest = serde_json::from_str(r#"{"terminable": true}"#).unwrap();
2351        assert_eq!(parsed.memory_budget_kb, None);
2352    }
2353
2354    #[test]
2355    fn governor_manifest_parses_declared_memory_budget() {
2356        let parsed: GovernorManifest =
2357            serde_json::from_str(r#"{"memory_budget_kb": 40960}"#).unwrap();
2358        assert_eq!(parsed.memory_budget_kb, Some(40_960));
2359    }
2360
2361    // ── GovernorManifest latency_class (app lease engine §8, Task 1) ────────────
2362
2363    #[test]
2364    fn latency_class_parses_and_defaults_none() {
2365        let parsed: GovernorManifest = serde_json::from_str(r#"{"terminable": true}"#).unwrap();
2366        assert_eq!(parsed.latency_class, None);
2367    }
2368
2369    #[test]
2370    fn latency_class_parses_declared_interactive() {
2371        let json = r#"{
2372            "name": "example",
2373            "version": "1.0.0",
2374            "app_type": "bun",
2375            "governor": {"latency_class": "interactive"}
2376        }"#;
2377        let m = parse_ok(json);
2378        let governor = m.governor.expect("governor block should parse");
2379        assert_eq!(governor.latency_class, Some(LatencyClass::Interactive));
2380    }
2381
2382    #[test]
2383    fn latency_class_parses_declared_background() {
2384        let parsed: GovernorManifest =
2385            serde_json::from_str(r#"{"latency_class": "background"}"#).unwrap();
2386        assert_eq!(parsed.latency_class, Some(LatencyClass::Background));
2387    }
2388
2389    #[test]
2390    fn latency_class_invalid_value_is_parse_error() {
2391        let result: Result<GovernorManifest, _> =
2392            serde_json::from_str(r#"{"latency_class": "urgent"}"#);
2393        assert!(result.is_err(), "unknown latency_class value must fail to parse");
2394    }
2395
2396    #[test]
2397    fn latency_class_as_str_and_from_str_roundtrip() {
2398        for class in [LatencyClass::Interactive, LatencyClass::Background] {
2399            let s = class.as_str();
2400            assert_eq!(LatencyClass::from_str(s), Ok(class));
2401        }
2402        assert!(LatencyClass::from_str("urgent").is_err());
2403    }
2404
2405    // ── UI-only stage apps (burger-07, Plans 07a/07b Contracts F5) ───────────
2406
2407    fn ui_only_manifest() -> serde_json::Value {
2408        serde_json::json!({
2409            "manifest_version": 2, "abi": "v1", "name": "burger-runtime", "version": "1.0.0",
2410            "auto_start": false, "has_ui": true, "ui_path": "ui/dist",
2411            "ui": {
2412                "kind": "stage", "entry": "ui/dist/main.js", "title": "Burger", "icon": "ui/dist/icon.svg",
2413                "nav": { "section": "system", "order": 90 }, "ui_api": 1,
2414                "requires": {
2415                    "capabilities": ["core.runtime.burger_snapshot", "core.runtime.burger_logs"],
2416                    "queries": [], "streams": ["app.burger_metrics"]
2417                },
2418                "data": {
2419                    "namespace": "burger", "offline": "online-only", "sync": "snapshot",
2420                    "queries": [{ "name": "burger.snapshot.v1", "capability": "core.runtime.burger_snapshot", "kind": "snapshot" }],
2421                    "streams": [{ "name": "burger.metrics.v1", "kind": "events" }]
2422                },
2423                "integrity": { "ui/dist/main.js": "a".repeat(64), "ui/dist/icon.svg": "b".repeat(64) }
2424            }
2425        })
2426    }
2427
2428    fn ui_only_with(key: &str, value: serde_json::Value) -> String {
2429        let mut manifest = ui_only_manifest();
2430        manifest[key] = value;
2431        manifest.to_string()
2432    }
2433
2434    #[test]
2435    fn a_stage_manifest_without_app_type_or_entrypoint_is_ui_only() {
2436        let m = parse_ok(&ui_only_manifest().to_string());
2437        assert_eq!(m.app_type, AppType::UiOnly);
2438        assert_eq!(m.app_type.as_str(), "ui-only");
2439        assert_eq!(m.effective_entrypoint(), "", "no backend, no entrypoint");
2440        assert_eq!(m.effective_hot_reload(), HotReloadKind::Unsupported);
2441        assert!(m.has_ui);
2442        let ui = m.ui.as_ref().expect("a ui block");
2443        assert_eq!(ui.kind, AppUiKind::Stage);
2444        let data = ui.data.as_ref().expect("the F5 ui.data block validates");
2445        assert_eq!(data.namespace, "burger");
2446        assert_eq!(data.offline, AppDataOfflinePolicy::OnlineOnly);
2447        assert_eq!(data.queries[0].capability, "core.runtime.burger_snapshot");
2448        assert_eq!(data.streams[0].name, "burger.metrics.v1");
2449    }
2450
2451    #[test]
2452    fn a_ui_only_manifest_round_trips_through_its_serialized_form() {
2453        let m = parse_ok(&ui_only_manifest().to_string());
2454        let wire = serde_json::to_string(&m).unwrap();
2455        assert!(wire.contains(r#""app_type":"ui-only""#), "{wire}");
2456        assert_eq!(parse_ok(&wire).app_type, AppType::UiOnly);
2457    }
2458
2459    #[test]
2460    fn a_ui_only_manifest_refuses_everything_that_implies_a_process() {
2461        for (key, value) in [
2462            (
2463                "provides",
2464                serde_json::json!({ "burger.runtime.peek": { "description": "x" } }),
2465            ),
2466            (
2467                "capabilities",
2468                serde_json::json!({ "provides": ["burger.runtime.peek"] }),
2469            ),
2470            ("tcp", serde_json::json!({ "preferred_port": 7010 })),
2471            ("resources", serde_json::json!({ "memory_mb": 16 })),
2472            (
2473                "standalone",
2474                serde_json::json!({ "socket_path": "/run/node/x.sock" }),
2475            ),
2476            ("subscribes", serde_json::json!(["system.network.changed"])),
2477            ("depends_on", serde_json::json!(["cron"])),
2478        ] {
2479            let err = parse_err(&ui_only_with(key, value));
2480            assert!(err.contains("ui-only"), "{key}: {err}");
2481        }
2482        let mut explicit_with_entry = ui_only_manifest();
2483        explicit_with_entry["app_type"] = serde_json::json!("ui-only");
2484        explicit_with_entry["entrypoint"] = serde_json::json!("dist/index.js");
2485        assert!(parse_err(&explicit_with_entry.to_string()).contains("'entrypoint'"));
2486    }
2487
2488    #[test]
2489    fn a_ui_only_manifest_must_declare_a_stage() {
2490        let mut widget = ui_only_manifest();
2491        widget["ui"]["kind"] = serde_json::json!("widget");
2492        let widget_ui = widget["ui"].as_object_mut().unwrap();
2493        widget_ui.remove("nav");
2494        // A widget may not declare app data at all; drop it so the refusal is
2495        // the UI-only rule, not validate_app_ui's widget rule.
2496        widget_ui.remove("data");
2497        assert!(parse_err(&widget.to_string()).contains(r#"kind "stage""#));
2498        let no_ui = r#"{"manifest_version":2,"abi":"v1","name":"x","version":"1.0.0","app_type":"ui-only"}"#;
2499        assert!(parse_err(no_ui).contains(r#"kind "stage""#));
2500    }
2501
2502    #[test]
2503    fn declaring_app_type_or_entrypoint_keeps_the_existing_defaults() {
2504        assert_eq!(
2505            parse_ok(r#"{"name":"cron","version":"1.0.0"}"#).app_type,
2506            AppType::Native
2507        );
2508        let mut with_entry = ui_only_manifest();
2509        with_entry["entrypoint"] = serde_json::json!("app.so");
2510        assert_eq!(parse_ok(&with_entry.to_string()).app_type, AppType::Native);
2511        let mut bun = ui_only_manifest();
2512        bun["app_type"] = serde_json::json!("bun");
2513        assert_eq!(parse_ok(&bun.to_string()).app_type, AppType::Bun);
2514    }
2515
2516    #[test]
2517    fn declares_ui_only_accepts_the_derived_and_the_explicit_form_only() {
2518        assert!(declares_ui_only(&ui_only_manifest()));
2519        assert!(declares_ui_only(
2520            &serde_json::json!({ "app_type": "ui-only" })
2521        ));
2522        assert!(!declares_ui_only(
2523            &serde_json::json!({ "app_type": "bun", "ui": {} })
2524        ));
2525        assert!(!declares_ui_only(
2526            &serde_json::json!({ "entrypoint": "app.so", "ui": {} })
2527        ));
2528        assert!(!declares_ui_only(&serde_json::json!({ "name": "cron" })));
2529        assert!(!declares_ui_only(&serde_json::json!("ui-only")));
2530    }
2531}
2532
2533#[cfg(test)]
2534mod shared_app_data_corpus_tests {
2535    use super::*;
2536
2537    /// The SAME corpus the kernel validator runs
2538    /// (`client/kernel/src/stages/stage-registry-contract.test.js`). Two independent
2539    /// implementations of one contract, with nothing but this comparing them —
2540    /// whichever side drifts fails here.
2541    #[test]
2542    fn shared_app_data_corpus_matches_the_host_validator() {
2543        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/app-data");
2544        let mut checked = 0;
2545        for entry in std::fs::read_dir(&dir).expect("fixture directory must exist") {
2546            let path = entry.expect("readable entry").path();
2547            if path.extension().and_then(|e| e.to_str()) != Some("json") {
2548                continue;
2549            }
2550            let fixture: serde_json::Value =
2551                serde_json::from_str(&std::fs::read_to_string(&path).expect("readable fixture"))
2552                    .expect("valid fixture json");
2553            let name = path
2554                .file_name()
2555                .and_then(|n| n.to_str())
2556                .unwrap_or("?")
2557                .to_string();
2558            let manifest = serde_json::json!({
2559                "manifest_version": 2, "abi": "v1", "name": "fixture", "version": "0.1.0",
2560                "app_type": "bun", "entrypoint": "dist/index.js",
2561                "ui": fixture["ui"],
2562            });
2563            let result = AppManifest::from_json(&manifest.to_string()).and_then(|m| m.validate());
2564            match fixture["expect"].as_str().expect("expect field") {
2565                "accept" => assert!(result.is_ok(), "{name} should be accepted: {result:?}"),
2566                "reject" => {
2567                    let error = result.expect_err(&format!("{name} should be rejected"));
2568                    let reason = fixture["reason"]
2569                        .as_str()
2570                        .expect("reject fixtures need a reason");
2571                    assert!(
2572                        error.contains(reason),
2573                        "{name}: {error:?} should mention {reason:?}"
2574                    );
2575                }
2576                other => panic!("{name}: unknown expect {other:?}"),
2577            }
2578            checked += 1;
2579        }
2580        // Guards against a silently empty or mis-globbed corpus reporting success.
2581        assert!(checked >= 10, "expected the full corpus, walked {checked}");
2582    }
2583}
2584
2585#[cfg(test)]
2586mod burger_manifest_tests {
2587    use super::*;
2588
2589    #[test]
2590    fn burger_app_type_parses_with_bundle_entrypoint_default() {
2591        let m = AppManifest::from_json(r#"{"name":"did","version":"2.0.0","app_type":"burger"}"#)
2592            .expect("burger manifest parses");
2593        assert_eq!(m.app_type, AppType::Burger);
2594        assert_eq!(m.app_type.as_str(), "burger");
2595        assert_eq!(m.effective_entrypoint(), "dist/index.js");
2596        assert_eq!(m.effective_hot_reload(), HotReloadKind::Supported);
2597        assert!(m.resources.is_none());
2598    }
2599
2600    #[test]
2601    fn resources_memory_mb_is_carried() {
2602        let m = AppManifest::from_json(
2603            r#"{"name":"did","version":"2.0.0","app_type":"burger","resources":{"memory_mb":48}}"#,
2604        )
2605        .expect("resources block parses");
2606        assert_eq!(
2607            m.resources,
2608            Some(ResourcesManifest { memory_mb: Some(48), callback_deadline_ms: None })
2609        );
2610    }
2611
2612    #[test]
2613    fn resources_callback_deadline_ms_is_carried() {
2614        let m = AppManifest::from_json(
2615            r#"{"name":"did","version":"2.0.0","app_type":"burger","resources":{"callback_deadline_ms":750}}"#,
2616        )
2617        .expect("callback deadline parses");
2618        assert_eq!(
2619            m.resources,
2620            Some(ResourcesManifest { memory_mb: None, callback_deadline_ms: Some(750) })
2621        );
2622        let max = AppManifest::from_json(
2623            r#"{"name":"did","version":"2.0.0","app_type":"burger","resources":{"callback_deadline_ms":600000}}"#,
2624        )
2625        .expect("the maximum is inclusive");
2626        assert_eq!(
2627            max.resources.and_then(|r| r.callback_deadline_ms),
2628            Some(MAX_CALLBACK_DEADLINE_MS)
2629        );
2630    }
2631
2632    #[test]
2633    fn resources_callback_deadline_ms_out_of_range_is_rejected() {
2634        for bad in ["0", "600001"] {
2635            let json = format!(
2636                r#"{{"name":"did","version":"2.0.0","app_type":"burger","resources":{{"callback_deadline_ms":{bad}}}}}"#
2637            );
2638            let err = AppManifest::from_json(&json).expect_err("out-of-range callback deadline");
2639            assert!(err.contains("resources.callback_deadline_ms"), "{bad}: {err}");
2640        }
2641    }
2642
2643    #[test]
2644    fn resources_callback_deadline_ms_must_be_a_positive_integer() {
2645        for bad in ["-1", "1.5", "\"5000\""] {
2646            let json = format!(
2647                r#"{{"name":"did","version":"2.0.0","app_type":"burger","resources":{{"callback_deadline_ms":{bad}}}}}"#
2648            );
2649            assert!(
2650                AppManifest::from_json(&json).is_err(),
2651                "callback_deadline_ms={bad} must be rejected"
2652            );
2653        }
2654    }
2655
2656    #[test]
2657    fn resources_memory_mb_zero_is_rejected() {
2658        let err = AppManifest::from_json(
2659            r#"{"name":"did","version":"2.0.0","app_type":"burger","resources":{"memory_mb":0}}"#,
2660        )
2661        .expect_err("a zero memory limit is invalid");
2662        assert!(err.contains("resources.memory_mb"), "{err}");
2663    }
2664
2665    #[test]
2666    fn burger_manifest_rejects_a_standalone_block() {
2667        let err = AppManifest::from_json(
2668            r#"{"name":"did","version":"2.0.0","app_type":"burger","standalone":{"socket_path":"/run/node-app-did.sock"}}"#,
2669        )
2670        .expect_err("standalone block is only valid for standalone apps");
2671        assert!(err.contains("only valid when app_type == 'standalone'"), "{err}");
2672    }
2673}