Skip to main content

pharos_native/binaries/
mod.rs

1#![allow(clippy::result_unit_err)]
2
3/// Public constant `MODULE_STATUS` exposed by this module.
4///
5/// # Examples
6///
7/// ```rust,ignore
8/// let _ = pharos_native::binaries::MODULE_STATUS;
9/// ```
10///
11/// # Related
12///
13/// - [`crate::binaries`] for the surrounding module surface.
14pub const MODULE_STATUS: &str = "PENDING";
15
16#[derive(Debug, Clone, Copy, Eq, PartialEq)]
17/// Public enum `BinaryTarget` used by this module.
18///
19/// # Variants
20///
21/// - `PrimaryRuntime`: Supported `BinaryTarget` variant.
22/// - `StaticServer`: Supported `BinaryTarget` variant.
23/// - `WasiHostBridge`: Supported `BinaryTarget` variant.
24/// - `WasmEntrypoint`: Supported `BinaryTarget` variant.
25/// - `BarcodeReaderCli`: Supported `BinaryTarget` variant.
26///
27/// # Examples
28///
29/// ```rust,ignore
30/// let _ = pharos_native::binaries::BinaryTarget::PrimaryRuntime;
31/// ```
32///
33/// # Related
34///
35/// - [`crate::binaries`] for constructors, helpers, and neighboring runtime types.
36pub enum BinaryTarget {
37    PrimaryRuntime,
38    StaticServer,
39    WasiHostBridge,
40    WasmEntrypoint,
41    BarcodeReaderCli,
42}
43
44/// Public constant `BINARY_TARGETS` exposed by this module.
45///
46/// # Examples
47///
48/// ```rust,ignore
49/// let _ = pharos_native::binaries::BINARY_TARGETS;
50/// ```
51///
52/// # Related
53///
54/// - [`crate::binaries`] for the surrounding module surface.
55pub const BINARY_TARGETS: &[BinaryTarget] = &[
56    BinaryTarget::PrimaryRuntime,
57    BinaryTarget::StaticServer,
58    BinaryTarget::WasiHostBridge,
59    BinaryTarget::WasmEntrypoint,
60    BinaryTarget::BarcodeReaderCli,
61];
62
63/// Returns the declared binary targets owned by this crate.
64///
65/// # Returns
66///
67/// Returns the computed value produced by [`crate::binaries::declared_binary_targets`].
68///
69/// # Examples
70///
71/// ```rust,ignore
72/// let _result = pharos_native::binaries::declared_binary_targets();
73/// ```
74///
75/// # Related
76///
77/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
78pub fn declared_binary_targets() -> &'static [BinaryTarget] {
79    BINARY_TARGETS
80}
81
82use std::env;
83use std::fs;
84use std::io::{Read, Write};
85use std::net::{SocketAddr, TcpListener, TcpStream};
86use std::path::{Path, PathBuf};
87
88use crate::config::{AppRuntime, ServeConfig};
89
90/// Finds the repository root containing the canonical app and script directories.
91///
92/// # Parameters
93///
94/// - `start`: Input consumed by [`crate::binaries::find_repo_root`].
95///
96/// # Returns
97///
98/// Returns [`Some`] when [`crate::binaries::find_repo_root`] can produce a value and [`None`] otherwise.
99///
100/// # Examples
101///
102/// ```rust,ignore
103/// let _result = pharos_native::binaries::find_repo_root(todo!());
104/// ```
105///
106/// # Related
107///
108/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
109pub fn find_repo_root(start: &Path) -> Option<PathBuf> {
110    let mut current = Some(start);
111    while let Some(path) = current {
112        if path.join("apps").is_dir() && path.join("scripts").is_dir() {
113            return Some(path.to_path_buf());
114        }
115        current = path.parent();
116    }
117    None
118}
119
120/// Resolves the directory containing the current Rust launcher binary.
121///
122/// # Returns
123///
124/// Returns [`Some`] when [`crate::binaries::resolve_launcher_binary_dir`] can produce a value and [`None`] otherwise.
125///
126/// # Examples
127///
128/// ```rust,ignore
129/// let _result = pharos_native::binaries::resolve_launcher_binary_dir();
130/// ```
131///
132/// # Related
133///
134/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
135pub fn resolve_launcher_binary_dir() -> Option<PathBuf> {
136    std::env::current_exe()
137        .ok()?
138        .parent()
139        .map(Path::to_path_buf)
140}
141
142/// Resolves the website root below a trusted repository root.
143///
144/// # Parameters
145///
146/// - `repo_root`: Input consumed by [`crate::binaries::resolve_website_root`].
147///
148/// # Returns
149///
150/// Returns [`Some`] when [`crate::binaries::resolve_website_root`] can produce a value and [`None`] otherwise.
151///
152/// # Performance
153///
154/// Performance is proportional to the size of the supplied inputs and any parsed or loaded data consumed by [`crate::binaries::resolve_website_root`].
155///
156/// # Examples
157///
158/// ```rust,ignore
159/// let _result = pharos_native::binaries::resolve_website_root(std::path::Path::new("."));
160/// ```
161///
162/// # Related
163///
164/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
165pub fn resolve_website_root(repo_root: &Path) -> Option<PathBuf> {
166    [repo_root.join("website"), repo_root.join("docs")]
167        .into_iter()
168        .find(|path| path.is_dir())
169}
170
171/// Returns a validated explicit binary-directory override.
172///
173/// # Returns
174///
175/// Returns [`Some`] when [`crate::binaries::explicit_binary_dir_override`] can produce a value and [`None`] otherwise.
176///
177/// # Examples
178///
179/// ```rust,ignore
180/// let _result = pharos_native::binaries::explicit_binary_dir_override();
181/// ```
182///
183/// # Related
184///
185/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
186pub fn explicit_binary_dir_override() -> Option<PathBuf> {
187    let value = env::var_os("PHAROS_BINARY_DIR")?;
188    let path = PathBuf::from(value);
189    path.is_dir().then_some(path)
190}
191
192/// Returns a validated explicit repository-root override.
193///
194/// # Returns
195///
196/// Returns [`Some`] when [`crate::binaries::explicit_repo_root_override`] can produce a value and [`None`] otherwise.
197///
198/// # Examples
199///
200/// ```rust,ignore
201/// let _result = pharos_native::binaries::explicit_repo_root_override();
202/// ```
203///
204/// # Related
205///
206/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
207pub fn explicit_repo_root_override() -> Option<PathBuf> {
208    let value = env::var_os("PHAROS_REPO_ROOT")?;
209    let path = PathBuf::from(value);
210    find_repo_root(&path).filter(|root| root == &path)
211}
212
213/// Reports whether a website identifier is one of the supported declarative roots.
214///
215/// # Parameters
216///
217/// - `website`: Input consumed by [`crate::binaries::known_website_supported`].
218///
219/// # Returns
220///
221/// Returns `true` when the condition checked by [`crate::binaries::known_website_supported`] holds and `false` otherwise.
222///
223/// # Examples
224///
225/// ```rust,ignore
226/// let _result = pharos_native::binaries::known_website_supported(todo!());
227/// ```
228///
229/// # Related
230///
231/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
232pub fn known_website_supported(website: &str) -> bool {
233    matches!(website, "docs" | "reference" | "website")
234}
235
236/// Returns a positive configured size, bounded to the native worker limits.
237///
238/// # Parameters
239///
240/// - `value`: Input consumed by [`crate::binaries::conf_positive_size_value`].
241/// - `default_value`: Input consumed by [`crate::binaries::conf_positive_size_value`].
242///
243/// # Returns
244///
245/// Returns the computed value produced by [`crate::binaries::conf_positive_size_value`].
246///
247/// # Examples
248///
249/// ```rust,ignore
250/// let _result = pharos_native::binaries::conf_positive_size_value("value", todo!());
251/// ```
252///
253/// # Related
254///
255/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
256pub fn conf_positive_size_value(value: Option<&str>, default_value: usize) -> usize {
257    value
258        .and_then(|value| value.parse::<usize>().ok())
259        .filter(|value| *value > 0)
260        .unwrap_or(default_value.max(1))
261        .min(16_384)
262}
263
264/// Returns the default worker count for a runtime configuration.
265///
266/// # Parameters
267///
268/// - `config`: Input consumed by [`crate::binaries::default_worker_count`].
269///
270/// # Returns
271///
272/// Returns the computed value produced by [`crate::binaries::default_worker_count`].
273///
274/// # Examples
275///
276/// ```rust,ignore
277/// let _result = pharos_native::binaries::default_worker_count(todo!());
278/// ```
279///
280/// # Related
281///
282/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
283pub fn default_worker_count(config: &ServeConfig) -> usize {
284    let _ = config;
285    std::thread::available_parallelism()
286        .map(usize::from)
287        .unwrap_or(1)
288        .clamp(1, 128)
289}
290
291/// Returns the default bounded request queue capacity.
292///
293/// # Parameters
294///
295/// - `config`: Input consumed by [`crate::binaries::default_work_queue_capacity`].
296///
297/// # Returns
298///
299/// Returns the computed value produced by [`crate::binaries::default_work_queue_capacity`].
300///
301/// # Examples
302///
303/// ```rust,ignore
304/// let _result = pharos_native::binaries::default_work_queue_capacity(todo!());
305/// ```
306///
307/// # Related
308///
309/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
310pub fn default_work_queue_capacity(config: &ServeConfig) -> usize {
311    let _ = config;
312    256
313}
314
315/// Resolves a configured worker count from the runtime environment.
316///
317/// # Parameters
318///
319/// - `config`: Input consumed by [`crate::binaries::resolved_worker_count`].
320///
321/// # Returns
322///
323/// Returns the computed value produced by [`crate::binaries::resolved_worker_count`].
324///
325/// # Examples
326///
327/// ```rust,ignore
328/// let _result = pharos_native::binaries::resolved_worker_count(todo!());
329/// ```
330///
331/// # Related
332///
333/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
334pub fn resolved_worker_count(config: &ServeConfig) -> usize {
335    conf_positive_size_value(
336        env::var("PHAROS_WORKER_COUNT").ok().as_deref(),
337        default_worker_count(config),
338    )
339    .min(128)
340}
341
342/// Resolves a configured queue capacity from the runtime environment.
343///
344/// # Parameters
345///
346/// - `config`: Input consumed by [`crate::binaries::resolved_work_queue_capacity`].
347///
348/// # Returns
349///
350/// Returns the computed value produced by [`crate::binaries::resolved_work_queue_capacity`].
351///
352/// # Examples
353///
354/// ```rust,ignore
355/// let _result = pharos_native::binaries::resolved_work_queue_capacity(todo!());
356/// ```
357///
358/// # Related
359///
360/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
361pub fn resolved_work_queue_capacity(config: &ServeConfig) -> usize {
362    conf_positive_size_value(
363        env::var("PHAROS_WORK_QUEUE_CAPACITY").ok().as_deref(),
364        default_work_queue_capacity(config),
365    )
366}
367
368/// Returns the current executable directory for an argv0-style input.
369///
370/// # Parameters
371///
372/// - `argv0`: Input consumed by [`crate::binaries::executable_dir_from_argv0`].
373///
374/// # Returns
375///
376/// Returns [`Some`] when [`crate::binaries::executable_dir_from_argv0`] can produce a value and [`None`] otherwise.
377///
378/// # Examples
379///
380/// ```rust,ignore
381/// let _result = pharos_native::binaries::executable_dir_from_argv0(todo!());
382/// ```
383///
384/// # Related
385///
386/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
387pub fn executable_dir_from_argv0(argv0: Option<&Path>) -> Option<PathBuf> {
388    argv0.and_then(Path::parent).map(Path::to_path_buf)
389}
390
391/// Returns whether one argument sequence names a serve handler.
392///
393/// # Parameters
394///
395/// - `arguments`: Input consumed by [`crate::binaries::find_serve_handler`].
396///
397/// # Returns
398///
399/// Returns `true` when the condition checked by [`crate::binaries::find_serve_handler`] holds and `false` otherwise.
400///
401/// # Examples
402///
403/// ```rust,ignore
404/// let _result = pharos_native::binaries::find_serve_handler(todo!());
405/// ```
406///
407/// # Related
408///
409/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
410pub fn find_serve_handler(arguments: &[String]) -> bool {
411    arguments.first().map(String::as_str) == Some("serve")
412}
413
414/// Returns the stable website mode for a supported website verb.
415///
416/// # Parameters
417///
418/// - `verb`: Input consumed by [`crate::binaries::website_verb_mode`].
419///
420/// # Returns
421///
422/// Returns [`Some`] when [`crate::binaries::website_verb_mode`] can produce a value and [`None`] otherwise.
423///
424/// # Examples
425///
426/// ```rust,ignore
427/// let _result = pharos_native::binaries::website_verb_mode(todo!());
428/// ```
429///
430/// # Related
431///
432/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
433pub fn website_verb_mode(verb: &str) -> Option<&'static str> {
434    match verb {
435        "status" => Some("status"),
436        "build" => Some("build"),
437        "serve" => Some("serve"),
438        _ => None,
439    }
440}
441
442/// Returns the stable native help text used by the primary launcher.
443///
444/// # Returns
445///
446/// Returns the computed value produced by [`crate::binaries::print_help`].
447///
448/// # Examples
449///
450/// ```rust,ignore
451/// let _result = pharos_native::binaries::print_help();
452/// ```
453///
454/// # Related
455///
456/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
457pub fn print_help() -> &'static str {
458    "pharos runtime\n\ncommands: build verify status run serve probe smoke doctor barcode json helper noindex\n"
459}
460
461/// Returns the package version exposed by the primary launcher.
462///
463/// # Returns
464///
465/// Returns the computed value produced by [`crate::binaries::print_version`].
466///
467/// # Examples
468///
469/// ```rust,ignore
470/// let _result = pharos_native::binaries::print_version();
471/// ```
472///
473/// # Related
474///
475/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
476pub fn print_version() -> &'static str {
477    env!("CARGO_PKG_VERSION")
478}
479
480/// Returns whether WASI stdio mode has been explicitly enabled.
481///
482/// # Parameters
483///
484/// - `value`: Input consumed by [`crate::binaries::wasi_stdio_mode_enabled`].
485///
486/// # Returns
487///
488/// Returns `true` when the condition checked by [`crate::binaries::wasi_stdio_mode_enabled`] holds and `false` otherwise.
489///
490/// # Examples
491///
492/// ```rust,ignore
493/// let _result = pharos_native::binaries::wasi_stdio_mode_enabled("value");
494/// ```
495///
496/// # Related
497///
498/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
499pub fn wasi_stdio_mode_enabled(value: Option<&str>) -> bool {
500    matches!(value.map(str::trim), Some("1" | "true" | "yes" | "on"))
501}
502
503/// Returns whether the WASI guest should process a single request stream.
504///
505/// # Parameters
506///
507/// - `value`: Input consumed by [`crate::binaries::wasi_single_stream_mode_enabled`].
508///
509/// # Returns
510///
511/// Returns `true` when the condition checked by [`crate::binaries::wasi_single_stream_mode_enabled`] holds and `false` otherwise.
512///
513/// # Examples
514///
515/// ```rust,ignore
516/// let _result = pharos_native::binaries::wasi_single_stream_mode_enabled("value");
517/// ```
518///
519/// # Related
520///
521/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
522pub fn wasi_single_stream_mode_enabled(value: Option<&str>) -> bool {
523    matches!(value.map(str::trim), Some("1" | "true" | "yes" | "on"))
524}
525
526/// Traces argv only when explicitly requested, without interpreting WASI behavior.
527///
528/// # Parameters
529///
530/// - `arguments`: Input consumed by [`crate::binaries::trace_wasm_argv_if_requested`].
531///
532/// # Returns
533///
534/// Returns `true` when the condition checked by [`crate::binaries::trace_wasm_argv_if_requested`] holds and `false` otherwise.
535///
536/// # Examples
537///
538/// ```rust,ignore
539/// let _result = pharos_native::binaries::trace_wasm_argv_if_requested(todo!());
540/// ```
541///
542/// # Related
543///
544/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
545pub fn trace_wasm_argv_if_requested(arguments: &[String]) -> bool {
546    if env::var("PHAROS_TRACE_WASM_ARGV").ok().as_deref() != Some("1") {
547        return false;
548    }
549    let mut stderr = std::io::stderr().lock();
550    let _ = writeln!(stderr, "argv_count={}", arguments.len());
551    true
552}
553
554/// Loads one app runtime from its packaged artifact directory.
555///
556/// # Parameters
557///
558/// - `artifact_dir`: Input consumed by [`crate::binaries::load_app_runtime_for_single_app`].
559///
560/// # Returns
561///
562/// Returns the successful value produced by [`crate::binaries::load_app_runtime_for_single_app`] or an error when the operation fails.
563///
564/// # Errors
565///
566/// Returns an error value when [`crate::binaries::load_app_runtime_for_single_app`] cannot complete successfully.
567///
568/// # Examples
569///
570/// ```rust,ignore
571/// let _result = pharos_native::binaries::load_app_runtime_for_single_app(std::path::Path::new("build/dev_docs"));
572/// ```
573///
574/// # Related
575///
576/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
577pub fn load_app_runtime_for_single_app(artifact_dir: &Path) -> Result<AppRuntime, &'static str> {
578    crate::runtime::load_app_runtime_from_artifact(artifact_dir)
579}
580
581/// Loads the shared runtime stack through the native runtime loader.
582///
583/// # Parameters
584///
585/// - `config`: Input consumed by [`crate::binaries::load_runtime_stack`].
586///
587/// # Returns
588///
589/// Returns the successful value produced by [`crate::binaries::load_runtime_stack`] or an error when the operation fails.
590///
591/// # Errors
592///
593/// Returns an error value when [`crate::binaries::load_runtime_stack`] cannot complete successfully.
594///
595/// # Examples
596///
597/// ```rust,ignore
598/// let _result = pharos_native::binaries::load_runtime_stack(todo!());
599/// ```
600///
601/// # Related
602///
603/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
604pub fn load_runtime_stack(
605    config: &ServeConfig,
606) -> Result<crate::runtime::RuntimeStack, &'static str> {
607    crate::runtime::load_runtime_stack_direct(config)
608}
609
610/// Dispatches a runtime command against the direct Rust runtime implementation.
611///
612/// # Parameters
613///
614/// - `verb`: Input consumed by [`crate::binaries::handle_runtime_command`].
615/// - `config`: Input consumed by [`crate::binaries::handle_runtime_command`].
616/// - `repo_root`: Input consumed by [`crate::binaries::handle_runtime_command`].
617/// - `binary_dir`: Input consumed by [`crate::binaries::handle_runtime_command`].
618///
619/// # Returns
620///
621/// Returns the successful value produced by [`crate::binaries::handle_runtime_command`] or an error when the operation fails.
622///
623/// # Errors
624///
625/// Returns an error value when [`crate::binaries::handle_runtime_command`] cannot complete successfully.
626///
627/// # Examples
628///
629/// ```rust,ignore
630/// let _result = pharos_native::binaries::handle_runtime_command(todo!(), todo!(), std::path::Path::new("."), std::path::Path::new("bin"));
631/// ```
632///
633/// # Related
634///
635/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
636pub fn handle_runtime_command(
637    verb: &str,
638    config: &mut ServeConfig,
639    repo_root: Option<&Path>,
640    binary_dir: Option<&Path>,
641) -> Result<String, &'static str> {
642    crate::runtime::handle_runtime_command_direct(verb, config, repo_root, binary_dir)
643}
644
645/// Dispatches an app-scoped runtime command.
646///
647/// # Parameters
648///
649/// - `verb`: Input consumed by [`crate::binaries::handle_runtime_app_command`].
650/// - `config`: Input consumed by [`crate::binaries::handle_runtime_app_command`].
651/// - `repo_root`: Input consumed by [`crate::binaries::handle_runtime_app_command`].
652/// - `binary_dir`: Input consumed by [`crate::binaries::handle_runtime_app_command`].
653///
654/// # Returns
655///
656/// Returns the successful value produced by [`crate::binaries::handle_runtime_app_command`] or an error when the operation fails.
657///
658/// # Errors
659///
660/// Returns an error value when [`crate::binaries::handle_runtime_app_command`] cannot complete successfully.
661///
662/// # Examples
663///
664/// ```rust,ignore
665/// let _result = pharos_native::binaries::handle_runtime_app_command(todo!(), todo!(), std::path::Path::new("."), std::path::Path::new("bin"));
666/// ```
667///
668/// # Related
669///
670/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
671pub fn handle_runtime_app_command(
672    verb: &str,
673    config: &mut ServeConfig,
674    repo_root: Option<&Path>,
675    binary_dir: Option<&Path>,
676) -> Result<String, &'static str> {
677    if config.kind.as_deref() != Some("app") {
678        return Err("app command requires app target kind");
679    }
680    crate::runtime::handle_runtime_command_direct(verb, config, repo_root, binary_dir)
681}
682
683/// Dispatches the direct serve boundary for app or shared runtime targets.
684///
685/// # Parameters
686///
687/// - `config`: Input consumed by [`crate::binaries::handle_serve`].
688/// - `repo_root`: Input consumed by [`crate::binaries::handle_serve`].
689/// - `binary_dir`: Input consumed by [`crate::binaries::handle_serve`].
690/// - `) -> Result<(`: Input consumed by [`crate::binaries::handle_serve`].
691///
692/// # Returns
693///
694/// Returns the successful value produced by [`crate::binaries::handle_serve`] or an error when the operation fails.
695///
696/// # Errors
697///
698/// Returns an error value when [`crate::binaries::handle_serve`] cannot complete successfully.
699///
700/// # Examples
701///
702/// ```rust,ignore
703/// let _result = pharos_native::binaries::handle_serve(todo!(), std::path::Path::new("."), std::path::Path::new("bin"), todo!());
704/// ```
705///
706/// # Related
707///
708/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
709pub fn handle_serve(
710    config: &ServeConfig,
711    repo_root: Option<&Path>,
712    binary_dir: Option<&Path>,
713) -> Result<(), &'static str> {
714    match config.kind.as_deref() {
715        Some("app") => crate::runtime::serve_single_app(config, repo_root, binary_dir),
716        Some("runtime") => crate::runtime::serve_runtime_stack(config),
717        _ => Err("serve requires app or runtime target kind"),
718    }
719}
720
721/// Handles helper commands without invoking a shell.
722///
723/// # Parameters
724///
725/// - `arguments`: Input consumed by [`crate::binaries::handle_helper_command`].
726///
727/// # Returns
728///
729/// Returns the successful value produced by [`crate::binaries::handle_helper_command`] or an error when the operation fails.
730///
731/// # Errors
732///
733/// Returns an error value when [`crate::binaries::handle_helper_command`] cannot complete successfully.
734///
735/// # Examples
736///
737/// ```rust,ignore
738/// let _result = pharos_native::binaries::handle_helper_command(todo!());
739/// ```
740///
741/// # Related
742///
743/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
744pub fn handle_helper_command(arguments: &[String]) -> Result<String, i32> {
745    match arguments {
746        [command, value] if command == "identifier-safe" => {
747            Ok(crate::runtime::ops_bridge::identifier_safe(value).to_string())
748        }
749        [command, value] if command == "normalize-base-path" => {
750            crate::runtime::ops_bridge::normalize_base_path(value).ok_or(64)
751        }
752        _ => Err(64),
753    }
754}
755
756/// Handles the integrations command family through the persisted state report.
757///
758/// # Parameters
759///
760/// - `root`: Input consumed by [`crate::binaries::handle_integrations_command`].
761///
762/// # Returns
763///
764/// Returns [`Some`] when [`crate::binaries::handle_integrations_command`] can produce a value and [`None`] otherwise.
765///
766/// # Examples
767///
768/// ```rust,ignore
769/// let _result = pharos_native::binaries::handle_integrations_command(std::path::Path::new("."));
770/// ```
771///
772/// # Related
773///
774/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
775pub fn handle_integrations_command(root: &serde_json::Value) -> Option<String> {
776    crate::runtime::business::dynamic_integrations_inspect_report_json(root)
777}
778
779/// Handles the jobs command family through the persisted state report.
780///
781/// # Parameters
782///
783/// - `root`: Input consumed by [`crate::binaries::handle_jobs_command`].
784///
785/// # Returns
786///
787/// Returns [`Some`] when [`crate::binaries::handle_jobs_command`] can produce a value and [`None`] otherwise.
788///
789/// # Examples
790///
791/// ```rust,ignore
792/// let _result = pharos_native::binaries::handle_jobs_command(std::path::Path::new("."));
793/// ```
794///
795/// # Related
796///
797/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
798pub fn handle_jobs_command(root: &serde_json::Value) -> Option<String> {
799    crate::runtime::business::dynamic_jobs_inspect_report_json(root)
800}
801
802/// Handles one job command for a persisted state root.
803///
804/// # Parameters
805///
806/// - `root`: Input consumed by [`crate::binaries::handle_job_command`].
807/// - `job_id`: Input consumed by [`crate::binaries::handle_job_command`].
808///
809/// # Returns
810///
811/// Returns [`Some`] when [`crate::binaries::handle_job_command`] can produce a value and [`None`] otherwise.
812///
813/// # Examples
814///
815/// ```rust,ignore
816/// let _result = pharos_native::binaries::handle_job_command(std::path::Path::new("."), todo!());
817/// ```
818///
819/// # Related
820///
821/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
822pub fn handle_job_command(root: &serde_json::Value, job_id: i64) -> Option<String> {
823    crate::runtime::business::dynamic_job_show_report_json(root, job_id)
824}
825
826/// Handles the migration command using the resolved app configuration.
827///
828/// # Parameters
829///
830/// - `config`: Input consumed by [`crate::binaries::handle_migrate_command`].
831///
832/// # Returns
833///
834/// Returns the successful value produced by [`crate::binaries::handle_migrate_command`] or an error when the operation fails.
835///
836/// # Errors
837///
838/// Returns an error value when [`crate::binaries::handle_migrate_command`] cannot complete successfully.
839///
840/// # Examples
841///
842/// ```rust,ignore
843/// let _result = pharos_native::binaries::handle_migrate_command(todo!());
844/// ```
845///
846/// # Related
847///
848/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
849pub fn handle_migrate_command(config: &ServeConfig) -> Result<String, &'static str> {
850    if config.kind.as_deref() != Some("app") {
851        return Err("migrate requires app target kind");
852    }
853    Err("migration execution requires an explicit app migration contract")
854}
855
856/// Handles operational commands through validated runtime arguments.
857///
858/// # Parameters
859///
860/// - `arguments`: Input consumed by [`crate::binaries::handle_backup_restore_ops_command`].
861///
862/// # Returns
863///
864/// Returns the successful value produced by [`crate::binaries::handle_backup_restore_ops_command`] or an error when the operation fails.
865///
866/// # Errors
867///
868/// Returns an error value when [`crate::binaries::handle_backup_restore_ops_command`] cannot complete successfully.
869///
870/// # Examples
871///
872/// ```rust,ignore
873/// let _result = pharos_native::binaries::handle_backup_restore_ops_command(todo!());
874/// ```
875///
876/// # Related
877///
878/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
879pub fn handle_backup_restore_ops_command(arguments: &[String]) -> Result<String, i32> {
880    if arguments.is_empty() {
881        return Err(64);
882    }
883    Ok(arguments.join(" "))
884}
885
886/// Handles drift check ops command.
887///
888/// # Parameters
889///
890/// - `arguments`: Input consumed by [`crate::binaries::handle_drift_check_ops_command`].
891///
892/// # Returns
893///
894/// Returns the successful value produced by [`crate::binaries::handle_drift_check_ops_command`] or an error when the operation fails.
895///
896/// # Errors
897///
898/// Returns an error value when [`crate::binaries::handle_drift_check_ops_command`] cannot complete successfully.
899///
900/// # Examples
901///
902/// ```rust,ignore
903/// let _result = pharos_native::binaries::handle_drift_check_ops_command(todo!());
904/// ```
905///
906/// # Related
907///
908/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
909pub fn handle_drift_check_ops_command(arguments: &[String]) -> Result<String, i32> {
910    if arguments.is_empty() {
911        return Err(64);
912    }
913    Ok(arguments.join(" "))
914}
915
916/// Handles deploy check ops command.
917///
918/// # Parameters
919///
920/// - `arguments`: Input consumed by [`crate::binaries::handle_deploy_check_ops_command`].
921///
922/// # Returns
923///
924/// Returns the successful value produced by [`crate::binaries::handle_deploy_check_ops_command`] or an error when the operation fails.
925///
926/// # Errors
927///
928/// Returns an error value when [`crate::binaries::handle_deploy_check_ops_command`] cannot complete successfully.
929///
930/// # Examples
931///
932/// ```rust,ignore
933/// let _result = pharos_native::binaries::handle_deploy_check_ops_command(todo!());
934/// ```
935///
936/// # Related
937///
938/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
939pub fn handle_deploy_check_ops_command(arguments: &[String]) -> Result<String, i32> {
940    if arguments.is_empty() {
941        return Err(64);
942    }
943    Ok(arguments.join(" "))
944}
945
946/// Handles ops command.
947///
948/// # Parameters
949///
950/// - `arguments`: Input consumed by [`crate::binaries::handle_ops_command`].
951///
952/// # Returns
953///
954/// Returns the successful value produced by [`crate::binaries::handle_ops_command`] or an error when the operation fails.
955///
956/// # Errors
957///
958/// Returns an error value when [`crate::binaries::handle_ops_command`] cannot complete successfully.
959///
960/// # Examples
961///
962/// ```rust,ignore
963/// let _result = pharos_native::binaries::handle_ops_command(todo!());
964/// ```
965///
966/// # Related
967///
968/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
969pub fn handle_ops_command(arguments: &[String]) -> Result<String, i32> {
970    if arguments.is_empty() {
971        return Err(64);
972    }
973    Ok(arguments.join(" "))
974}
975
976/// Handles noindex marker creation through the native filesystem implementation.
977///
978/// # Parameters
979///
980/// - `root`: Input consumed by [`crate::binaries::handle_noindex_command`].
981///
982/// # Returns
983///
984/// Returns the successful value produced by [`crate::binaries::handle_noindex_command`] or an error when the operation fails.
985///
986/// # Errors
987///
988/// Returns an error value when [`crate::binaries::handle_noindex_command`] cannot complete successfully.
989///
990/// # Examples
991///
992/// ```rust,ignore
993/// let _result = pharos_native::binaries::handle_noindex_command(std::path::Path::new("."));
994/// ```
995///
996/// # Related
997///
998/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
999pub fn handle_noindex_command(root: &Path) -> Result<usize, &'static str> {
1000    crate::runtime::ops_bridge::write_noindex_markers_recursive(root)
1001}
1002
1003/// Performs serve website target.
1004///
1005/// # Parameters
1006///
1007/// - `verb`: Input consumed by [`crate::binaries::serve_website_target`].
1008/// - `website`: Input consumed by [`crate::binaries::serve_website_target`].
1009/// - `root`: Input consumed by [`crate::binaries::serve_website_target`].
1010///
1011/// # Returns
1012///
1013/// Returns the successful value produced by [`crate::binaries::serve_website_target`] or an error when the operation fails.
1014///
1015/// # Errors
1016///
1017/// Returns an error value when [`crate::binaries::serve_website_target`] cannot complete successfully.
1018///
1019/// # Examples
1020///
1021/// ```rust,ignore
1022/// let _result = pharos_native::binaries::serve_website_target(todo!(), todo!(), std::path::Path::new("."));
1023/// ```
1024///
1025/// # Related
1026///
1027/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1028pub fn serve_website_target(
1029    verb: &str,
1030    website: &str,
1031    root: &Path,
1032) -> Result<String, &'static str> {
1033    handle_website_command(verb, website, root)
1034}
1035
1036/// Handles website commands without shell or C fallback behavior.
1037///
1038/// # Parameters
1039///
1040/// - `verb`: Input consumed by [`crate::binaries::handle_website_command`].
1041/// - `website`: Input consumed by [`crate::binaries::handle_website_command`].
1042/// - `root`: Input consumed by [`crate::binaries::handle_website_command`].
1043///
1044/// # Returns
1045///
1046/// Returns the successful value produced by [`crate::binaries::handle_website_command`] or an error when the operation fails.
1047///
1048/// # Errors
1049///
1050/// Returns an error value when [`crate::binaries::handle_website_command`] cannot complete successfully.
1051///
1052/// # Examples
1053///
1054/// ```rust,ignore
1055/// let _result = pharos_native::binaries::handle_website_command(todo!(), todo!(), std::path::Path::new("."));
1056/// ```
1057///
1058/// # Related
1059///
1060/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1061pub fn handle_website_command(
1062    verb: &str,
1063    website: &str,
1064    root: &Path,
1065) -> Result<String, &'static str> {
1066    if !known_website_supported(website) || website_verb_mode(verb).is_none() || !root.is_dir() {
1067        return Err("unsupported website command");
1068    }
1069    Ok(
1070        serde_json::json!({"website": website, "mode": website_verb_mode(verb), "root": root})
1071            .to_string(),
1072    )
1073}
1074
1075/// Builds a migration report from a resolved app runtime.
1076///
1077/// # Parameters
1078///
1079/// - `config`: Input consumed by [`crate::binaries::build_migrate_operation_report_json`].
1080/// - `app`: Input consumed by [`crate::binaries::build_migrate_operation_report_json`].
1081///
1082/// # Returns
1083///
1084/// Returns [`Some`] when [`crate::binaries::build_migrate_operation_report_json`] can produce a value and [`None`] otherwise.
1085///
1086/// # Examples
1087///
1088/// ```rust,ignore
1089/// let _result = pharos_native::binaries::build_migrate_operation_report_json(todo!(), todo!());
1090/// ```
1091///
1092/// # Related
1093///
1094/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1095pub fn build_migrate_operation_report_json(
1096    config: &ServeConfig,
1097    app: &AppRuntime,
1098) -> Option<String> {
1099    Some(
1100        serde_json::json!({
1101            "report_id": "pharos-migrate-operation-v1",
1102            "target_id": config.target_id,
1103            "app_id": app.app_id,
1104            "status": "ready",
1105        })
1106        .to_string(),
1107    )
1108}
1109
1110/// Builds the bounded worker context copied into request workers.
1111///
1112/// # Parameters
1113///
1114/// - `app`: Input consumed by [`crate::binaries::build_worker_context`].
1115///
1116/// # Returns
1117///
1118/// Returns the computed value produced by [`crate::binaries::build_worker_context`].
1119///
1120/// # Examples
1121///
1122/// ```rust,ignore
1123/// let _result = pharos_native::binaries::build_worker_context(todo!());
1124/// ```
1125///
1126/// # Related
1127///
1128/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1129pub fn build_worker_context(app: &AppRuntime) -> AppRuntime {
1130    app.clone()
1131}
1132
1133/// Processes one app request using the direct static artifact server.
1134///
1135/// # Parameters
1136///
1137/// - `stream`: Input consumed by [`crate::binaries::process_single_stream_app_request`].
1138/// - `app`: Input consumed by [`crate::binaries::process_single_stream_app_request`].
1139/// - `) -> Result<(), (`: Input consumed by [`crate::binaries::process_single_stream_app_request`].
1140///
1141/// # Returns
1142///
1143/// Returns the successful value produced by [`crate::binaries::process_single_stream_app_request`] or an error when the operation fails.
1144///
1145/// # Errors
1146///
1147/// Returns an error value when [`crate::binaries::process_single_stream_app_request`] cannot complete successfully.
1148///
1149/// # Performance
1150///
1151/// Performance is proportional to the size of the supplied inputs and any parsed or loaded data consumed by [`crate::binaries::process_single_stream_app_request`].
1152///
1153/// # Examples
1154///
1155/// ```rust,ignore
1156/// let _result = pharos_native::binaries::process_single_stream_app_request(todo!(), todo!(), todo!());
1157/// ```
1158///
1159/// # Related
1160///
1161/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1162pub fn process_single_stream_app_request(
1163    stream: &mut TcpStream,
1164    app: &AppRuntime,
1165) -> Result<(), ()> {
1166    let mut request = [0u8; 16 * 1024];
1167    let read = stream.read(&mut request).map_err(|_| ())?;
1168    let text = std::str::from_utf8(&request[..read]).map_err(|_| ())?;
1169    let line = text.lines().next().ok_or(())?;
1170    let mut fields = line.split_whitespace();
1171    let method = fields.next().ok_or(())?;
1172    let target = fields.next().ok_or(())?;
1173    let response = crate::runtime::app_route_response(app, method, target);
1174    stream.write_all(&response).map_err(|_| ())
1175}
1176
1177/// Processes one shared-runtime request through the selected app stack.
1178///
1179/// # Parameters
1180///
1181/// - `stream`: Input consumed by [`crate::binaries::process_single_stream_runtime_request`].
1182/// - `stack`: Input consumed by [`crate::binaries::process_single_stream_runtime_request`].
1183/// - `) -> Result<(), (`: Input consumed by [`crate::binaries::process_single_stream_runtime_request`].
1184///
1185/// # Returns
1186///
1187/// Returns the successful value produced by [`crate::binaries::process_single_stream_runtime_request`] or an error when the operation fails.
1188///
1189/// # Errors
1190///
1191/// Returns an error value when [`crate::binaries::process_single_stream_runtime_request`] cannot complete successfully.
1192///
1193/// # Performance
1194///
1195/// Performance is proportional to the size of the supplied inputs and any parsed or loaded data consumed by [`crate::binaries::process_single_stream_runtime_request`].
1196///
1197/// # Examples
1198///
1199/// ```rust,ignore
1200/// let _result = pharos_native::binaries::process_single_stream_runtime_request(todo!(), todo!(), todo!());
1201/// ```
1202///
1203/// # Related
1204///
1205/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1206pub fn process_single_stream_runtime_request(
1207    stream: &mut TcpStream,
1208    stack: &crate::runtime::RuntimeStack,
1209) -> Result<(), ()> {
1210    let mut request = [0u8; 16 * 1024];
1211    let read = stream.read(&mut request).map_err(|_| ())?;
1212    let text = std::str::from_utf8(&request[..read]).map_err(|_| ())?;
1213    let line = text.lines().next().ok_or(())?;
1214    let mut fields = line.split_whitespace();
1215    let method = fields.next().ok_or(())?.to_owned();
1216    let target = fields.next().ok_or(())?.to_owned();
1217    let response = if !matches!(method.as_str(), "GET" | "HEAD") {
1218        crate::artifact_server::StaticResponse {
1219            status_code: 405,
1220            status_text: "Method Not Allowed",
1221            content_type: "text/plain; charset=utf-8",
1222            body: b"method not allowed\n".to_vec(),
1223            content_length: 19,
1224        }
1225    } else if let Some(app) = crate::runtime::runtime_match_app(stack, &target) {
1226        crate::artifact_server::serve_app_request(app, &method, &target)
1227    } else {
1228        crate::artifact_server::StaticResponse {
1229            status_code: 404,
1230            status_text: "Not Found",
1231            content_type: "text/plain; charset=utf-8",
1232            body: b"not found\n".to_vec(),
1233            content_length: 10,
1234        }
1235    };
1236    let response_body = if response.status_code >= 400 {
1237        pharos_runtime_core::error::envelope(
1238            pharos_runtime_core::error::ErrorCode::from_http_status(response.status_code),
1239            response.status_text,
1240            None,
1241        )
1242        .to_string()
1243        .into_bytes()
1244    } else {
1245        response.body
1246    };
1247    let content_type = if response.status_code >= 400 {
1248        "application/json; charset=utf-8"
1249    } else {
1250        response.content_type
1251    };
1252    let content_length = response_body.len();
1253    let body = if method == "HEAD" {
1254        Vec::new()
1255    } else {
1256        response_body
1257    };
1258    let encoded = format!(
1259        "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1260        response.status_code,
1261        response.status_text,
1262        content_type,
1263        content_length,
1264        String::from_utf8_lossy(&body)
1265    );
1266    stream.write_all(encoded.as_bytes()).map_err(|_| ())
1267}
1268
1269/// Returns an overload response body without writing unbounded data.
1270///
1271/// # Parameters
1272///
1273/// - `stream`: Input consumed by [`crate::binaries::send_worker_pool_overload_response`].
1274///
1275/// # Returns
1276///
1277/// Returns the successful value produced by [`crate::binaries::send_worker_pool_overload_response`] or an error when the operation fails.
1278///
1279/// # Errors
1280///
1281/// Returns an error value when [`crate::binaries::send_worker_pool_overload_response`] cannot complete successfully.
1282///
1283/// # Examples
1284///
1285/// ```rust,ignore
1286/// let _result = pharos_native::binaries::send_worker_pool_overload_response(todo!());
1287/// ```
1288///
1289/// # Related
1290///
1291/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1292pub fn send_worker_pool_overload_response(stream: &mut TcpStream) -> Result<(), ()> {
1293    let body = pharos_runtime_core::error::envelope(
1294        pharos_runtime_core::error::ErrorCode::CapacityExceeded,
1295        "overloaded worker pool",
1296        None,
1297    )
1298    .to_string();
1299    let response = format!(
1300        "HTTP/1.1 503 Service Unavailable\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
1301        body.len()
1302    );
1303    stream.write_all(response.as_bytes()).map_err(|_| ())
1304}
1305
1306/// Emits a runtime path helper report.
1307///
1308/// # Parameters
1309///
1310/// - `path`: Input consumed by [`crate::binaries::emit_runtime_path_helper_json`].
1311///
1312/// # Returns
1313///
1314/// Returns [`Some`] when [`crate::binaries::emit_runtime_path_helper_json`] can produce a value and [`None`] otherwise.
1315///
1316/// # Examples
1317///
1318/// ```rust,ignore
1319/// let _result = pharos_native::binaries::emit_runtime_path_helper_json(std::path::Path::new("fixture.json"));
1320/// ```
1321///
1322/// # Related
1323///
1324/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1325pub fn emit_runtime_path_helper_json(path: &Path) -> Option<String> {
1326    path.to_str()
1327        .map(|value| serde_json::json!({"path": value}).to_string())
1328}
1329
1330/// Writes a bounded text file to stdout as a string result.
1331///
1332/// # Parameters
1333///
1334/// - `path`: Input consumed by [`crate::binaries::emit_text_file_to_stdout`].
1335///
1336/// # Returns
1337///
1338/// Returns the successful value produced by [`crate::binaries::emit_text_file_to_stdout`] or an error when the operation fails.
1339///
1340/// # Errors
1341///
1342/// Returns an error value when [`crate::binaries::emit_text_file_to_stdout`] cannot complete successfully.
1343///
1344/// # Performance
1345///
1346/// Performance is proportional to the size of the supplied inputs and any parsed or loaded data consumed by [`crate::binaries::emit_text_file_to_stdout`].
1347///
1348/// # Examples
1349///
1350/// ```rust,ignore
1351/// let _result = pharos_native::binaries::emit_text_file_to_stdout(std::path::Path::new("fixture.json"));
1352/// ```
1353///
1354/// # Related
1355///
1356/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1357pub fn emit_text_file_to_stdout(path: &Path) -> Result<String, i32> {
1358    fs::read_to_string(path).map_err(|_| 66)
1359}
1360
1361/// Emits website status as a bounded JSON report.
1362///
1363/// # Parameters
1364///
1365/// - `root`: Input consumed by [`crate::binaries::emit_website_status`].
1366/// - `website`: Input consumed by [`crate::binaries::emit_website_status`].
1367///
1368/// # Returns
1369///
1370/// Returns the successful value produced by [`crate::binaries::emit_website_status`] or an error when the operation fails.
1371///
1372/// # Errors
1373///
1374/// Returns an error value when [`crate::binaries::emit_website_status`] cannot complete successfully.
1375///
1376/// # Examples
1377///
1378/// ```rust,ignore
1379/// let _result = pharos_native::binaries::emit_website_status(std::path::Path::new("."), todo!());
1380/// ```
1381///
1382/// # Related
1383///
1384/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1385pub fn emit_website_status(root: &Path, website: &str) -> Result<String, &'static str> {
1386    if !known_website_supported(website) || !root.is_dir() {
1387        return Err("website root unavailable");
1388    }
1389    Ok(serde_json::json!({"website": website, "root": root, "status": "ready"}).to_string())
1390}
1391
1392/// Exposes the requested runtime verb set for binary dispatch.
1393///
1394/// # Parameters
1395///
1396/// - `verb`: Input consumed by [`crate::binaries::runtime_verb_supported`].
1397///
1398/// # Returns
1399///
1400/// Returns `true` when the condition checked by [`crate::binaries::runtime_verb_supported`] holds and `false` otherwise.
1401///
1402/// # Examples
1403///
1404/// ```rust,ignore
1405/// let _result = pharos_native::binaries::runtime_verb_supported(todo!());
1406/// ```
1407///
1408/// # Related
1409///
1410/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1411pub fn runtime_verb_supported(verb: &str) -> bool {
1412    crate::runtime::runtime_verb_supported(verb)
1413        || matches!(verb, "serve" | "barcode" | "json" | "helper" | "noindex")
1414}
1415
1416/// Serves a static root using the bounded direct listener.
1417///
1418/// # Parameters
1419///
1420/// - `root`: Input consumed by [`crate::binaries::serve_static_root`].
1421/// - `port`: Input consumed by [`crate::binaries::serve_static_root`].
1422/// - `max_requests`: Input consumed by [`crate::binaries::serve_static_root`].
1423///
1424/// # Returns
1425///
1426/// Returns the computed value produced by [`crate::binaries::serve_static_root`].
1427///
1428/// # Examples
1429///
1430/// ```rust,ignore
1431/// let _result = pharos_native::binaries::serve_static_root(std::path::Path::new("."), "8080", todo!());
1432/// ```
1433///
1434/// # Related
1435///
1436/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1437pub fn serve_static_root(root: &Path, port: u16, max_requests: usize) -> i32 {
1438    crate::artifact_server::run(root, port, max_requests)
1439}
1440
1441/// Writes an explicit process-context report without signal-handler side effects.
1442///
1443/// # Parameters
1444///
1445/// - `app`: Input consumed by [`crate::binaries::process_worker_context`].
1446///
1447/// # Returns
1448///
1449/// Returns [`Some`] when [`crate::binaries::process_worker_context`] can produce a value and [`None`] otherwise.
1450///
1451/// # Examples
1452///
1453/// ```rust,ignore
1454/// let _result = pharos_native::binaries::process_worker_context(todo!());
1455/// ```
1456///
1457/// # Related
1458///
1459/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1460pub fn process_worker_context(app: &AppRuntime) -> Option<String> {
1461    serde_json::to_string(&serde_json::json!({
1462        "app_id": app.app_id,
1463        "app_root": app.app_root,
1464        "artifact_dir": app.artifact_dir,
1465        "state_path": app.state_path,
1466        "host_profile": app.host_profile,
1467    }))
1468    .ok()
1469}
1470
1471/// Installs no process-global signal handlers; callers use explicit shutdown tokens.
1472///
1473/// # Parameters
1474///
1475/// - `) -> Result<(`: Input consumed by [`crate::binaries::install_signal_handlers`].
1476///
1477/// # Returns
1478///
1479/// Returns the successful value produced by [`crate::binaries::install_signal_handlers`] or an error when the operation fails.
1480///
1481/// # Errors
1482///
1483/// Returns an error value when [`crate::binaries::install_signal_handlers`] cannot complete successfully.
1484///
1485/// # Examples
1486///
1487/// ```rust,ignore
1488/// let _result = pharos_native::binaries::install_signal_handlers(todo!());
1489/// ```
1490///
1491/// # Related
1492///
1493/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1494pub fn install_signal_handlers() -> Result<(), &'static str> {
1495    Ok(())
1496}
1497
1498/// Returns the path to the launcher binary for a configured executable.
1499///
1500/// # Parameters
1501///
1502/// - `binary_dir`: Input consumed by [`crate::binaries::executable_path`].
1503///
1504/// # Returns
1505///
1506/// Returns [`Some`] when [`crate::binaries::executable_path`] can produce a value and [`None`] otherwise.
1507///
1508/// # Examples
1509///
1510/// ```rust,ignore
1511/// let _result = pharos_native::binaries::executable_path(std::path::Path::new("bin"));
1512/// ```
1513///
1514/// # Related
1515///
1516/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1517pub fn executable_path(binary_dir: Option<&Path>) -> Option<PathBuf> {
1518    binary_dir.map(|dir| dir.join("pharos"))
1519}
1520
1521/// Accepts one bounded TCP connection from a listener.
1522///
1523/// # Parameters
1524///
1525/// - `listener`: Input consumed by [`crate::binaries::accept_http_request`].
1526/// - `SocketAddr`: Input consumed by [`crate::binaries::accept_http_request`].
1527///
1528/// # Returns
1529///
1530/// Returns the successful value produced by [`crate::binaries::accept_http_request`] or an error when the operation fails.
1531///
1532/// # Errors
1533///
1534/// Returns an error value when [`crate::binaries::accept_http_request`] cannot complete successfully.
1535///
1536/// # Examples
1537///
1538/// ```rust,ignore
1539/// let _result = pharos_native::binaries::accept_http_request(todo!(), todo!());
1540/// ```
1541///
1542/// # Related
1543///
1544/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1545pub fn accept_http_request(listener: &TcpListener) -> Result<(TcpStream, SocketAddr), i32> {
1546    listener.accept().map_err(|_| 71)
1547}
1548
1549/// Adds an app to a runtime stack while rejecting duplicate app identifiers.
1550///
1551/// # Parameters
1552///
1553/// - `stack`: Input consumed by [`crate::binaries::add_runtime_app`].
1554/// - `app`: Input consumed by [`crate::binaries::add_runtime_app`].
1555///
1556/// # Returns
1557///
1558/// Returns `true` when the condition checked by [`crate::binaries::add_runtime_app`] holds and `false` otherwise.
1559///
1560/// # Performance
1561///
1562/// Performance is proportional to the size of the supplied inputs and any parsed or loaded data consumed by [`crate::binaries::add_runtime_app`].
1563///
1564/// # Examples
1565///
1566/// ```rust,ignore
1567/// let _result = pharos_native::binaries::add_runtime_app(todo!(), todo!());
1568/// ```
1569///
1570/// # Related
1571///
1572/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1573pub fn add_runtime_app(stack: &mut crate::runtime::RuntimeStack, app: AppRuntime) -> bool {
1574    let Some(app_id) = app.app_id.as_deref().filter(|value| !value.is_empty()) else {
1575        return false;
1576    };
1577    if stack
1578        .apps
1579        .iter()
1580        .any(|existing| existing.app_id.as_deref() == Some(app_id))
1581    {
1582        return false;
1583    }
1584    stack.apps.push(app);
1585    true
1586}
1587
1588/// Resolves the configured app-ops backend without inventing a default.
1589///
1590/// # Parameters
1591///
1592/// - `app_root`: Input consumed by [`crate::binaries::app_ops_backend`].
1593/// - `runtime_conf_path`: Input consumed by [`crate::binaries::app_ops_backend`].
1594///
1595/// # Returns
1596///
1597/// Returns [`Some`] when [`crate::binaries::app_ops_backend`] can produce a value and [`None`] otherwise.
1598///
1599/// # Examples
1600///
1601/// ```rust,ignore
1602/// let _result = pharos_native::binaries::app_ops_backend(std::path::Path::new("apps/dev_docs"), todo!());
1603/// ```
1604///
1605/// # Related
1606///
1607/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1608pub fn app_ops_backend(app_root: &Path, runtime_conf_path: Option<&Path>) -> Option<String> {
1609    crate::runtime::json_commands::dynamic_relational_backend(app_root, runtime_conf_path)
1610}
1611
1612/// Builds a deterministic known-website descriptor.
1613///
1614/// # Parameters
1615///
1616/// - `root`: Input consumed by [`crate::binaries::build_known_website`].
1617/// - `website`: Input consumed by [`crate::binaries::build_known_website`].
1618///
1619/// # Returns
1620///
1621/// Returns [`Some`] when [`crate::binaries::build_known_website`] can produce a value and [`None`] otherwise.
1622///
1623/// # Examples
1624///
1625/// ```rust,ignore
1626/// let _result = pharos_native::binaries::build_known_website(std::path::Path::new("."), todo!());
1627/// ```
1628///
1629/// # Related
1630///
1631/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1632pub fn build_known_website(root: &Path, website: &str) -> Option<String> {
1633    if !known_website_supported(website) || !root.is_dir() {
1634        return None;
1635    }
1636    Some(serde_json::json!({"website": website, "root": root}).to_string())
1637}
1638
1639/// Closes an active listener by consuming its owned handle.
1640///
1641/// # Parameters
1642///
1643/// - `listener`: Input consumed by [`crate::binaries::cleanup_active_listener`].
1644///
1645/// # Returns
1646///
1647/// Returns after [`crate::binaries::cleanup_active_listener`] applies its in-place effect.
1648///
1649/// # Examples
1650///
1651/// ```rust,ignore
1652/// let _result = pharos_native::binaries::cleanup_active_listener(todo!());
1653/// ```
1654///
1655/// # Related
1656///
1657/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1658pub fn cleanup_active_listener(listener: Option<TcpListener>) {
1659    drop(listener);
1660}
1661
1662/// Clears a listener cleanup registration after the listener has been consumed.
1663///
1664/// # Parameters
1665///
1666/// - `registration`: Input consumed by [`crate::binaries::clear_listener_cleanup_registration`].
1667///
1668/// # Returns
1669///
1670/// Returns `true` when the condition checked by [`crate::binaries::clear_listener_cleanup_registration`] holds and `false` otherwise.
1671///
1672/// # Examples
1673///
1674/// ```rust,ignore
1675/// let _result = pharos_native::binaries::clear_listener_cleanup_registration(todo!());
1676/// ```
1677///
1678/// # Related
1679///
1680/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1681pub fn clear_listener_cleanup_registration(registration: &mut Option<SocketAddr>) -> bool {
1682    registration.take().is_some()
1683}
1684
1685/// Encodes one report value as bounded JSON text.
1686///
1687/// # Parameters
1688///
1689/// - `report`: Input consumed by [`crate::binaries::emit_report_json`].
1690///
1691/// # Returns
1692///
1693/// Returns the successful value produced by [`crate::binaries::emit_report_json`] or an error when the operation fails.
1694///
1695/// # Errors
1696///
1697/// Returns an error value when [`crate::binaries::emit_report_json`] cannot complete successfully.
1698///
1699/// # Examples
1700///
1701/// ```rust,ignore
1702/// let _result = pharos_native::binaries::emit_report_json(todo!());
1703/// ```
1704///
1705/// # Related
1706///
1707/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1708pub fn emit_report_json(report: &serde_json::Value) -> Result<String, i32> {
1709    serde_json::to_string(report).map_err(|_| 74)
1710}
1711
1712/// Exports relational state for app operations through the native adapter.
1713///
1714/// # Parameters
1715///
1716/// - `app_root`: Input consumed by [`crate::binaries::export_relational_state_for_app_ops`].
1717/// - `runtime_conf_path`: Input consumed by [`crate::binaries::export_relational_state_for_app_ops`].
1718/// - `app_id`: Input consumed by [`crate::binaries::export_relational_state_for_app_ops`].
1719///
1720/// # Returns
1721///
1722/// Returns [`Some`] when [`crate::binaries::export_relational_state_for_app_ops`] can produce a value and [`None`] otherwise.
1723///
1724/// # Examples
1725///
1726/// ```rust,ignore
1727/// let _result = pharos_native::binaries::export_relational_state_for_app_ops(std::path::Path::new("apps/dev_docs"), todo!(), todo!());
1728/// ```
1729///
1730/// # Related
1731///
1732/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1733pub fn export_relational_state_for_app_ops(
1734    app_root: &Path,
1735    runtime_conf_path: Option<&Path>,
1736    app_id: Option<&str>,
1737) -> Option<String> {
1738    crate::runtime::json_commands::dynamic_runtime_state_export_json_runtime(
1739        app_root,
1740        runtime_conf_path,
1741        app_id,
1742    )
1743}
1744
1745/// Releases an owned worker context.
1746///
1747/// # Parameters
1748///
1749/// - `context`: Input consumed by [`crate::binaries::free_worker_context`].
1750///
1751/// # Returns
1752///
1753/// Returns after [`crate::binaries::free_worker_context`] applies its in-place effect.
1754///
1755/// # Examples
1756///
1757/// ```rust,ignore
1758/// let _result = pharos_native::binaries::free_worker_context(todo!());
1759/// ```
1760///
1761/// # Related
1762///
1763/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1764pub fn free_worker_context(context: Option<AppRuntime>) {
1765    drop(context);
1766}
1767
1768/// Routes one request to a matched app or framework builtin handler.
1769///
1770/// # Parameters
1771///
1772/// - `method`: Input consumed by [`crate::binaries::handle_app_or_runtime_request`].
1773/// - `target`: Input consumed by [`crate::binaries::handle_app_or_runtime_request`].
1774/// - `stack`: Input consumed by [`crate::binaries::handle_app_or_runtime_request`].
1775///
1776/// # Returns
1777///
1778/// Returns [`Some`] when [`crate::binaries::handle_app_or_runtime_request`] can produce a value and [`None`] otherwise.
1779///
1780/// # Examples
1781///
1782/// ```rust,ignore
1783/// let _result = pharos_native::binaries::handle_app_or_runtime_request(todo!(), "/", todo!());
1784/// ```
1785///
1786/// # Related
1787///
1788/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1789pub fn handle_app_or_runtime_request(
1790    method: &str,
1791    target: &str,
1792    stack: &crate::runtime::RuntimeStack,
1793) -> Option<crate::runtime::FrameworkBuiltinResponse> {
1794    let app = crate::runtime::runtime_match_app(stack, target);
1795    crate::runtime::framework_builtin_response(method, target, app, Some(stack))
1796}
1797
1798/// Handles framework-owned health/version endpoints directly.
1799///
1800/// # Parameters
1801///
1802/// - `method`: Input consumed by [`crate::binaries::handle_framework_builtin_request`].
1803/// - `target`: Input consumed by [`crate::binaries::handle_framework_builtin_request`].
1804/// - `app`: Input consumed by [`crate::binaries::handle_framework_builtin_request`].
1805/// - `stack`: Input consumed by [`crate::binaries::handle_framework_builtin_request`].
1806///
1807/// # Returns
1808///
1809/// Returns [`Some`] when [`crate::binaries::handle_framework_builtin_request`] can produce a value and [`None`] otherwise.
1810///
1811/// # Examples
1812///
1813/// ```rust,ignore
1814/// let _result = pharos_native::binaries::handle_framework_builtin_request(todo!(), "/", todo!(), todo!());
1815/// ```
1816///
1817/// # Related
1818///
1819/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1820pub fn handle_framework_builtin_request(
1821    method: &str,
1822    target: &str,
1823    app: Option<&AppRuntime>,
1824    stack: Option<&crate::runtime::RuntimeStack>,
1825) -> Option<crate::runtime::FrameworkBuiltinResponse> {
1826    crate::runtime::framework_builtin_response(method, target, app, stack)
1827}
1828
1829/// Imports relational state for app operations through the native adapter.
1830///
1831/// # Parameters
1832///
1833/// - `app_root`: Input consumed by [`crate::binaries::import_relational_state_for_app_ops`].
1834/// - `runtime_conf_path`: Input consumed by [`crate::binaries::import_relational_state_for_app_ops`].
1835/// - `app_id`: Input consumed by [`crate::binaries::import_relational_state_for_app_ops`].
1836/// - `state_path`: Input consumed by [`crate::binaries::import_relational_state_for_app_ops`].
1837/// - `expected_audit_count`: Input consumed by [`crate::binaries::import_relational_state_for_app_ops`].
1838///
1839/// # Returns
1840///
1841/// Returns the computed value produced by [`crate::binaries::import_relational_state_for_app_ops`].
1842///
1843/// # Examples
1844///
1845/// ```rust,ignore
1846/// let _result = pharos_native::binaries::import_relational_state_for_app_ops(std::path::Path::new("apps/dev_docs"), todo!(), todo!(), todo!(), todo!());
1847/// ```
1848///
1849/// # Related
1850///
1851/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1852pub fn import_relational_state_for_app_ops(
1853    app_root: &Path,
1854    runtime_conf_path: Option<&Path>,
1855    app_id: Option<&str>,
1856    state_path: &Path,
1857    expected_audit_count: Option<&str>,
1858) -> i32 {
1859    crate::runtime::json_commands::dynamic_runtime_state_import_json_runtime(
1860        app_root,
1861        runtime_conf_path,
1862        app_id,
1863        state_path,
1864        expected_audit_count,
1865    )
1866}
1867
1868/// Returns the stable app runtime report identifier.
1869///
1870/// # Parameters
1871///
1872/// - `verb`: Input consumed by [`crate::binaries::app_runtime_report_id`].
1873///
1874/// # Returns
1875///
1876/// Returns the computed value produced by [`crate::binaries::app_runtime_report_id`].
1877///
1878/// # Examples
1879///
1880/// ```rust,ignore
1881/// let _result = pharos_native::binaries::app_runtime_report_id(todo!());
1882/// ```
1883///
1884/// # Related
1885///
1886/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1887pub fn app_runtime_report_id(verb: &str) -> &'static str {
1888    crate::runtime::runtime_report_id_for_verb(verb)
1889}
1890
1891/// Clamps one size to an explicit inclusive range.
1892///
1893/// # Parameters
1894///
1895/// - `value`: Input consumed by [`crate::binaries::clamp_size_value`].
1896/// - `minimum`: Input consumed by [`crate::binaries::clamp_size_value`].
1897/// - `maximum`: Input consumed by [`crate::binaries::clamp_size_value`].
1898///
1899/// # Returns
1900///
1901/// Returns the computed value produced by [`crate::binaries::clamp_size_value`].
1902///
1903/// # Examples
1904///
1905/// ```rust,ignore
1906/// let _result = pharos_native::binaries::clamp_size_value("value", todo!(), todo!());
1907/// ```
1908///
1909/// # Related
1910///
1911/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1912pub fn clamp_size_value(value: usize, minimum: usize, maximum: usize) -> usize {
1913    value.clamp(minimum, maximum.max(minimum))
1914}
1915
1916/// Returns physical memory when an in-process platform provider exposes it.
1917///
1918/// # Returns
1919///
1920/// Returns [`Some`] when [`crate::binaries::detect_physical_memory_bytes`] can produce a value and [`None`] otherwise.
1921///
1922/// # Examples
1923///
1924/// ```rust,ignore
1925/// let _result = pharos_native::binaries::detect_physical_memory_bytes();
1926/// ```
1927///
1928/// # Related
1929///
1930/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1931pub fn detect_physical_memory_bytes() -> Option<u64> {
1932    None
1933}
1934
1935/// Parses a positive size with a safe default and upper bound.
1936///
1937/// # Parameters
1938///
1939/// - `value`: Input consumed by [`crate::binaries::parse_positive_size_value`].
1940/// - `default_value`: Input consumed by [`crate::binaries::parse_positive_size_value`].
1941/// - `maximum`: Input consumed by [`crate::binaries::parse_positive_size_value`].
1942///
1943/// # Returns
1944///
1945/// Returns the computed value produced by [`crate::binaries::parse_positive_size_value`].
1946///
1947/// # Examples
1948///
1949/// ```rust,ignore
1950/// let _result = pharos_native::binaries::parse_positive_size_value("value", todo!(), todo!());
1951/// ```
1952///
1953/// # Related
1954///
1955/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1956pub fn parse_positive_size_value(
1957    value: Option<&str>,
1958    default_value: usize,
1959    maximum: usize,
1960) -> usize {
1961    value
1962        .and_then(|value| value.parse::<usize>().ok())
1963        .filter(|value| *value > 0)
1964        .map(|value| value.min(maximum.max(1)))
1965        .unwrap_or(default_value.max(1).min(maximum.max(1)))
1966}
1967
1968/// Validates app-ops prerequisites without mutating app state.
1969///
1970/// # Parameters
1971///
1972/// - `app`: Input consumed by [`crate::binaries::prepare_app_ops`].
1973///
1974/// # Returns
1975///
1976/// Returns the successful value produced by [`crate::binaries::prepare_app_ops`] or an error when the operation fails.
1977///
1978/// # Errors
1979///
1980/// Returns an error value when [`crate::binaries::prepare_app_ops`] cannot complete successfully.
1981///
1982/// # Examples
1983///
1984/// ```rust,ignore
1985/// let _result = pharos_native::binaries::prepare_app_ops(todo!());
1986/// ```
1987///
1988/// # Related
1989///
1990/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
1991pub fn prepare_app_ops(app: &AppRuntime) -> Result<(), &'static str> {
1992    if app.app_root.as_deref().is_none_or(str::is_empty) {
1993        return Err("app-ops requires an app root");
1994    }
1995    if app.state_path.as_deref().is_none_or(str::is_empty) {
1996        return Err("app-ops requires a state path");
1997    }
1998    Ok(())
1999}
2000
2001/// Registers a listener cleanup token with its bound endpoint.
2002///
2003/// # Parameters
2004///
2005/// - `listener`: Input consumed by [`crate::binaries::register_listener_cleanup`].
2006///
2007/// # Returns
2008///
2009/// Returns [`Some`] when [`crate::binaries::register_listener_cleanup`] can produce a value and [`None`] otherwise.
2010///
2011/// # Examples
2012///
2013/// ```rust,ignore
2014/// let _result = pharos_native::binaries::register_listener_cleanup(todo!());
2015/// ```
2016///
2017/// # Related
2018///
2019/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
2020pub fn register_listener_cleanup(listener: &TcpListener) -> Option<SocketAddr> {
2021    listener.local_addr().ok()
2022}
2023
2024/// Resolves a Unix socket path for a runtime target.
2025///
2026/// # Parameters
2027///
2028/// - `config`: Input consumed by [`crate::binaries::resolve_runtime_socket_path`].
2029/// - `runtime_id`: Input consumed by [`crate::binaries::resolve_runtime_socket_path`].
2030///
2031/// # Returns
2032///
2033/// Returns [`Some`] when [`crate::binaries::resolve_runtime_socket_path`] can produce a value and [`None`] otherwise.
2034///
2035/// # Examples
2036///
2037/// ```rust,ignore
2038/// let _result = pharos_native::binaries::resolve_runtime_socket_path(todo!(), todo!());
2039/// ```
2040///
2041/// # Related
2042///
2043/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
2044pub fn resolve_runtime_socket_path(config: &ServeConfig, runtime_id: &str) -> Option<String> {
2045    if runtime_id.is_empty() {
2046        return None;
2047    }
2048    config
2049        .socket_path
2050        .clone()
2051        .or_else(|| Some(format!("/tmp/pharos-{runtime_id}.sock")))
2052}
2053
2054/// Returns a non-empty runtime value or a supplied default.
2055///
2056/// # Parameters
2057///
2058/// - `value`: Input consumed by [`crate::binaries::resolve_value_or_default`].
2059/// - `default_value`: Input consumed by [`crate::binaries::resolve_value_or_default`].
2060///
2061/// # Returns
2062///
2063/// Returns the computed value produced by [`crate::binaries::resolve_value_or_default`].
2064///
2065/// # Examples
2066///
2067/// ```rust,ignore
2068/// let _result = pharos_native::binaries::resolve_value_or_default("value", todo!());
2069/// ```
2070///
2071/// # Related
2072///
2073/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
2074pub fn resolve_value_or_default(value: Option<&str>, default_value: &str) -> String {
2075    value
2076        .filter(|value| !value.is_empty())
2077        .unwrap_or(default_value)
2078        .to_owned()
2079}
2080
2081/// Confirms that an app directory manifest identifies the expected app.
2082///
2083/// # Parameters
2084///
2085/// - `app_root`: Input consumed by [`crate::binaries::runtime_app_directory_matches_id`].
2086/// - `app_id`: Input consumed by [`crate::binaries::runtime_app_directory_matches_id`].
2087///
2088/// # Returns
2089///
2090/// Returns `true` when the condition checked by [`crate::binaries::runtime_app_directory_matches_id`] holds and `false` otherwise.
2091///
2092/// # Examples
2093///
2094/// ```rust,ignore
2095/// let _result = pharos_native::binaries::runtime_app_directory_matches_id(std::path::Path::new("apps/dev_docs"), todo!());
2096/// ```
2097///
2098/// # Related
2099///
2100/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
2101pub fn runtime_app_directory_matches_id(app_root: &Path, app_id: &str) -> bool {
2102    if app_id.is_empty() || !app_root.is_dir() {
2103        return false;
2104    }
2105    crate::config::match_app_root_in_directory(app_root, app_id).is_some()
2106}
2107
2108/// Confirms that a finalized artifact manifest exists below an app root.
2109///
2110/// # Parameters
2111///
2112/// - `app_root`: Input consumed by [`crate::binaries::app_root_has_finalized_artifact`].
2113///
2114/// # Returns
2115///
2116/// Returns `true` when the condition checked by [`crate::binaries::app_root_has_finalized_artifact`] holds and `false` otherwise.
2117///
2118/// # Examples
2119///
2120/// ```rust,ignore
2121/// let _result = pharos_native::binaries::app_root_has_finalized_artifact(std::path::Path::new("apps/dev_docs"));
2122/// ```
2123///
2124/// # Related
2125///
2126/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
2127pub fn app_root_has_finalized_artifact(app_root: &Path) -> bool {
2128    app_root.join("pharos.app.json").is_file() && app_root.join("runtime-route-map.tsv").is_file()
2129}
2130
2131/// Confirms that the app runtime configuration contract is present.
2132///
2133/// # Parameters
2134///
2135/// - `app_root`: Input consumed by [`crate::binaries::app_runtime_conf_required_present`].
2136///
2137/// # Returns
2138///
2139/// Returns `true` when the condition checked by [`crate::binaries::app_runtime_conf_required_present`] holds and `false` otherwise.
2140///
2141/// # Examples
2142///
2143/// ```rust,ignore
2144/// let _result = pharos_native::binaries::app_runtime_conf_required_present(std::path::Path::new("apps/dev_docs"));
2145/// ```
2146///
2147/// # Related
2148///
2149/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
2150pub fn app_runtime_conf_required_present(app_root: &Path) -> bool {
2151    app_root.join("app.conf").is_file() || app_root.join("pharos.app.json").is_file()
2152}
2153
2154/// Seeds a missing state file only when the caller explicitly requests seeding.
2155///
2156/// # Parameters
2157///
2158/// - `app`: Input consumed by [`crate::binaries::maybe_seed_app_state`].
2159///
2160/// # Returns
2161///
2162/// Returns the successful value produced by [`crate::binaries::maybe_seed_app_state`] or an error when the operation fails.
2163///
2164/// # Errors
2165///
2166/// Returns an error value when [`crate::binaries::maybe_seed_app_state`] cannot complete successfully.
2167///
2168/// # Examples
2169///
2170/// ```rust,ignore
2171/// let _result = pharos_native::binaries::maybe_seed_app_state(todo!());
2172/// ```
2173///
2174/// # Related
2175///
2176/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
2177pub fn maybe_seed_app_state(app: &AppRuntime) -> Result<bool, i32> {
2178    let path = Path::new(app.state_path.as_deref().ok_or(64)?);
2179    if path.is_file() {
2180        return Ok(false);
2181    }
2182    if let Some(parent) = path.parent() {
2183        fs::create_dir_all(parent).map_err(|_| 73)?;
2184    }
2185    pharos_runtime_core::fs::write_binary_file(path, b"{}\n", 0o640).map_err(|_| 73)?;
2186    Ok(true)
2187}
2188
2189/// Extracts a bounded HTTP error body from a response document.
2190///
2191/// # Parameters
2192///
2193/// - `response`: Input consumed by [`crate::binaries::http_parse_error_body`].
2194///
2195/// # Returns
2196///
2197/// Returns [`Some`] when [`crate::binaries::http_parse_error_body`] can produce a value and [`None`] otherwise.
2198///
2199/// # Examples
2200///
2201/// ```rust,ignore
2202/// let _result = pharos_native::binaries::http_parse_error_body(todo!());
2203/// ```
2204///
2205/// # Related
2206///
2207/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
2208pub fn http_parse_error_body(response: &str) -> Option<String> {
2209    let body = response
2210        .split_once("\r\n\r\n")
2211        .map(|(_, body)| body)
2212        .or_else(|| response.split_once("\n\n").map(|(_, body)| body))?;
2213    (!body.is_empty() && body.len() <= 1024 * 1024).then(|| body.to_owned())
2214}
2215
2216/// Returns a stable HTTP reason phrase for a status code.
2217///
2218/// # Parameters
2219///
2220/// - `status_code`: Input consumed by [`crate::binaries::http_parse_reason_phrase`].
2221///
2222/// # Returns
2223///
2224/// Returns the computed value produced by [`crate::binaries::http_parse_reason_phrase`].
2225///
2226/// # Examples
2227///
2228/// ```rust,ignore
2229/// let _result = pharos_native::binaries::http_parse_reason_phrase(400);
2230/// ```
2231///
2232/// # Related
2233///
2234/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
2235pub fn http_parse_reason_phrase(status_code: u16) -> &'static str {
2236    match status_code {
2237        200 => "OK",
2238        201 => "Created",
2239        204 => "No Content",
2240        400 => "Bad Request",
2241        401 => "Unauthorized",
2242        403 => "Forbidden",
2243        404 => "Not Found",
2244        405 => "Method Not Allowed",
2245        409 => "Conflict",
2246        413 => "Payload Too Large",
2247        429 => "Too Many Requests",
2248        500 => "Internal Server Error",
2249        503 => "Service Unavailable",
2250        _ => "Unknown",
2251    }
2252}
2253
2254/// Returns one exact command-line option value.
2255///
2256/// # Parameters
2257///
2258/// - `arguments`: Input consumed by [`crate::binaries::option_value`].
2259/// - `name`: Input consumed by [`crate::binaries::option_value`].
2260///
2261/// # Returns
2262///
2263/// Returns [`Some`] when [`crate::binaries::option_value`] can produce a value and [`None`] otherwise.
2264///
2265/// # Performance
2266///
2267/// Performance is proportional to the size of the supplied inputs and any parsed or loaded data consumed by [`crate::binaries::option_value`].
2268///
2269/// # Examples
2270///
2271/// ```rust,ignore
2272/// let _result = pharos_native::binaries::option_value(todo!(), "name");
2273/// ```
2274///
2275/// # Related
2276///
2277/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
2278pub fn option_value(arguments: &[String], name: &str) -> Option<String> {
2279    arguments
2280        .windows(2)
2281        .find(|pair| pair[0] == name)
2282        .map(|pair| pair[1].clone())
2283}
2284
2285/// Parses an app-ops JSON configuration document.
2286///
2287/// # Parameters
2288///
2289/// - `text`: Input consumed by [`crate::binaries::parse_app_ops_config`].
2290///
2291/// # Returns
2292///
2293/// Returns the successful value produced by [`crate::binaries::parse_app_ops_config`] or an error when the operation fails.
2294///
2295/// # Errors
2296///
2297/// Returns an error value when [`crate::binaries::parse_app_ops_config`] cannot complete successfully.
2298///
2299/// # Performance
2300///
2301/// Performance is proportional to the size of the supplied inputs and any parsed or loaded data consumed by [`crate::binaries::parse_app_ops_config`].
2302///
2303/// # Examples
2304///
2305/// ```rust,ignore
2306/// let _result = pharos_native::binaries::parse_app_ops_config("{}");
2307/// ```
2308///
2309/// # Related
2310///
2311/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
2312pub fn parse_app_ops_config(text: &str) -> Result<serde_json::Value, i32> {
2313    let value: serde_json::Value = serde_json::from_str(text).map_err(|_| 65)?;
2314    value.is_object().then_some(value).ok_or(65)
2315}
2316
2317/// Prepares a finalized app runtime from a resolved app directory and config.
2318///
2319/// # Parameters
2320///
2321/// - `app_root`: Input consumed by [`crate::binaries::prepare_finalized_app_from_config`].
2322///
2323/// # Returns
2324///
2325/// Returns the successful value produced by [`crate::binaries::prepare_finalized_app_from_config`] or an error when the operation fails.
2326///
2327/// # Errors
2328///
2329/// Returns an error value when [`crate::binaries::prepare_finalized_app_from_config`] cannot complete successfully.
2330///
2331/// # Examples
2332///
2333/// ```rust,ignore
2334/// let _result = pharos_native::binaries::prepare_finalized_app_from_config(std::path::Path::new("apps/dev_docs"));
2335/// ```
2336///
2337/// # Related
2338///
2339/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
2340pub fn prepare_finalized_app_from_config(app_root: &Path) -> Result<AppRuntime, &'static str> {
2341    if !app_root_has_finalized_artifact(app_root) {
2342        return Err("finalized app artifact is incomplete");
2343    }
2344    let artifact_dir = app_root.to_path_buf();
2345    crate::runtime::load_app_runtime_from_artifact(&artifact_dir)
2346}
2347
2348/// Returns whether the shared runtime stack has enough state for readiness.
2349///
2350/// # Parameters
2351///
2352/// - `stack`: Input consumed by [`crate::binaries::runtime_stack_probe_ready`].
2353///
2354/// # Returns
2355///
2356/// Returns `true` when the condition checked by [`crate::binaries::runtime_stack_probe_ready`] holds and `false` otherwise.
2357///
2358/// # Performance
2359///
2360/// Performance is proportional to the size of the supplied inputs and any parsed or loaded data consumed by [`crate::binaries::runtime_stack_probe_ready`].
2361///
2362/// # Examples
2363///
2364/// ```rust,ignore
2365/// let _result = pharos_native::binaries::runtime_stack_probe_ready(todo!());
2366/// ```
2367///
2368/// # Related
2369///
2370/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
2371pub fn runtime_stack_probe_ready(stack: &crate::runtime::RuntimeStack) -> bool {
2372    !stack.apps.is_empty()
2373        && stack.apps.iter().all(|app| {
2374            app.artifact_dir
2375                .as_deref()
2376                .is_some_and(|path| Path::new(path).is_dir())
2377        })
2378}
2379
2380/// Serves one validated static request from a packaged artifact root.
2381///
2382/// # Parameters
2383///
2384/// - `root`: Input consumed by [`crate::binaries::serve_static_file`].
2385/// - `method`: Input consumed by [`crate::binaries::serve_static_file`].
2386/// - `target`: Input consumed by [`crate::binaries::serve_static_file`].
2387///
2388/// # Returns
2389///
2390/// Returns the computed value produced by [`crate::binaries::serve_static_file`].
2391///
2392/// # Examples
2393///
2394/// ```rust,ignore
2395/// let _result = pharos_native::binaries::serve_static_file(std::path::Path::new("."), todo!(), "/");
2396/// ```
2397///
2398/// # Related
2399///
2400/// - [`crate::binaries`] for adjacent helpers that share the same runtime surface.
2401pub fn serve_static_file(
2402    root: &Path,
2403    method: &str,
2404    target: &str,
2405) -> crate::artifact_server::StaticResponse {
2406    let app = AppRuntime {
2407        artifact_dir: Some(root.to_string_lossy().into_owned()),
2408        ..AppRuntime::default()
2409    };
2410    crate::artifact_server::serve_app_request(&app, method, target)
2411}