feat: publish HoloLake model-native living system source

This commit is contained in:
冰朔 2026-08-03 10:04:41 +08:00
commit c395dd3a99
2467 changed files with 615073 additions and 0 deletions

View file

@ -0,0 +1,11 @@
[package]
name = "guanghu-broadcast-tower"
version = "0.1.0"
edition = "2021"
license = "AGPL-3.0-or-later"
description = "Hosted bootstrap executor for the unique HLDP Guanghu broadcast tower"
[dependencies]
guanghu-hldp-runtime = { path = "../hldp-runtime" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

View file

@ -0,0 +1,343 @@
use std::{
fs,
io::{self, Read, Write},
net::{SocketAddr, TcpListener, TcpStream},
path::Path,
sync::atomic::{AtomicU64, Ordering},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use guanghu_hldp_runtime::{validate_world_seed, WorldManifest};
use serde::Serialize;
static EPOCH_SEQUENCE: AtomicU64 = AtomicU64::new(0);
const USAGE: &str =
"usage: guanghu-broadcast-tower serve <world-root> <loopback-address> <epoch-path>";
#[derive(Clone, Debug, Serialize)]
pub struct TowerSnapshot {
pub status: &'static str,
pub tower_id: String,
pub world_id: String,
pub world_version: String,
pub phase: String,
pub domain_count: usize,
pub code_channel_id: String,
pub authority_language: &'static str,
pub runtime: &'static str,
pub linux_exited: bool,
}
impl TowerSnapshot {
pub fn from_manifest(manifest: &WorldManifest) -> Self {
Self {
status: "ok",
tower_id: manifest.broadcast_tower.id.clone(),
world_id: manifest.world_id.clone(),
world_version: manifest.version.clone(),
phase: manifest.phase.clone(),
domain_count: manifest.domains.len(),
code_channel_id: manifest.code_channel.id.clone(),
authority_language: "HLDP",
runtime: "HOSTED_BOOTSTRAP",
linux_exited: false,
}
}
}
pub fn run_command(arguments: Vec<String>, connection_limit: Option<usize>) -> Result<(), String> {
let mut arguments = arguments.into_iter();
let command = arguments.next().ok_or_else(|| USAGE.to_owned())?;
let world_root = arguments.next().ok_or_else(|| USAGE.to_owned())?;
let address = arguments.next().ok_or_else(|| USAGE.to_owned())?;
let epoch_path = arguments.next().ok_or_else(|| USAGE.to_owned())?;
if command != "serve" || arguments.next().is_some() {
return Err(USAGE.to_owned());
}
let address = validate_loopback_address(&address)?;
let manifest =
validate_world_seed(Path::new(&world_root)).map_err(|error| error.to_string())?;
let listener = TcpListener::bind(address).map_err(|error| error.to_string())?;
let snapshot = TowerSnapshot::from_manifest(&manifest);
serve(listener, snapshot, Path::new(&epoch_path), connection_limit)
.map_err(|error| error.to_string())
}
pub fn validate_loopback_address(address: &str) -> Result<SocketAddr, String> {
let parsed: SocketAddr = address
.parse()
.map_err(|error| format!("invalid broadcast address {address}: {error}"))?;
if !parsed.ip().is_loopback() {
return Err("hosted broadcast tower must bind to loopback".to_owned());
}
Ok(parsed)
}
pub fn write_epoch(path: &Path, snapshot: &TowerSnapshot, address: SocketAddr) -> io::Result<()> {
let parent = path
.parent()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "epoch path has no parent"))?;
fs::create_dir_all(parent)?;
let started_at_unix = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(io::Error::other)?
.as_secs();
let temporary = parent.join(format!(
".epoch.{}.{}.tmp",
std::process::id(),
EPOCH_SEQUENCE.fetch_add(1, Ordering::Relaxed)
));
let contents = format!(
concat!(
"schema: guanghu.broadcast-epoch/v1\n",
"tower_id: {}\n",
"world_id: {}\n",
"world_version: {}\n",
"phase: {}\n",
"status: RUNNING_HOSTED\n",
"authority_language: HLDP\n",
"bind: {}\n",
"pid: {}\n",
"started_at_unix: {}\n",
"linux_dependency: true\n",
"native_claim: false\n"
),
snapshot.tower_id,
snapshot.world_id,
snapshot.world_version,
snapshot.phase,
address,
std::process::id(),
started_at_unix
);
fs::write(&temporary, contents)?;
fs::rename(temporary, path)
}
pub fn serve(
listener: TcpListener,
snapshot: TowerSnapshot,
epoch_path: &Path,
connection_limit: Option<usize>,
) -> io::Result<()> {
let address = listener.local_addr()?;
if !address.ip().is_loopback() {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"hosted broadcast tower may only listen on loopback",
));
}
write_epoch(epoch_path, &snapshot, address)?;
for connection in listener
.incoming()
.take(connection_limit.unwrap_or(usize::MAX))
{
handle_connection(connection?, &snapshot)?;
}
Ok(())
}
fn handle_connection(mut stream: TcpStream, snapshot: &TowerSnapshot) -> io::Result<()> {
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
let mut request = [0_u8; 8192];
let length = stream.read(&mut request)?;
let request = String::from_utf8_lossy(&request[..length]);
let request_line = request.lines().next().unwrap_or_default();
let (status, content_type, body) = match request_line {
"GET /healthz HTTP/1.1" | "GET /healthz HTTP/1.0" => (
"200 OK",
"application/json",
serde_json::to_string(snapshot).map_err(io::Error::other)?,
),
"GET /v1/world HTTP/1.1" | "GET /v1/world HTTP/1.0" => (
"200 OK",
"application/json",
serde_json::to_string_pretty(snapshot).map_err(io::Error::other)?,
),
line if line.starts_with("GET ") => (
"404 Not Found",
"application/json",
"{\"error\":\"route_not_found\"}".to_owned(),
),
_ => (
"405 Method Not Allowed",
"application/json",
"{\"error\":\"method_not_allowed\"}".to_owned(),
),
};
let response = format!(
"HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
stream.write_all(response.as_bytes())?;
stream.flush()
}
#[cfg(test)]
mod tests {
use std::{
io::{Read, Write},
net::{TcpListener, TcpStream},
path::PathBuf,
thread,
};
use guanghu_hldp_runtime::load_world_manifest;
use super::{run_command, serve, validate_loopback_address, write_epoch, TowerSnapshot, USAGE};
fn snapshot() -> TowerSnapshot {
TowerSnapshot {
status: "ok",
tower_id: "BT-GH-ROOT-0001".to_owned(),
world_id: "GLW-ROOT-0001".to_owned(),
world_version: "0.1.0-stage1".to_owned(),
phase: "HOSTED_BOOTSTRAP_PROTOTYPE".to_owned(),
domain_count: 5,
code_channel_id: "HLP-MOD-CODE-CHANNEL".to_owned(),
authority_language: "HLDP",
runtime: "HOSTED_BOOTSTRAP",
linux_exited: false,
}
}
fn epoch_path() -> PathBuf {
std::env::temp_dir().join(format!(
"guanghu-broadcast-epoch-{}-{}.hldp",
std::process::id(),
thread::current().name().unwrap_or("test")
))
}
fn request(request: &[u8]) -> String {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind test tower");
let address = listener.local_addr().expect("test address");
let epoch = epoch_path();
let epoch_for_server = epoch.clone();
let handle = thread::spawn(move || {
serve(listener, snapshot(), &epoch_for_server, Some(1)).expect("serve one request");
});
let mut stream = TcpStream::connect(address).expect("connect to test tower");
stream.write_all(request).expect("write request");
let mut response = String::new();
stream.read_to_string(&mut response).expect("read response");
handle.join().expect("tower thread");
std::fs::remove_file(epoch).expect("remove test epoch");
response
}
#[test]
fn rejects_non_loopback_hosted_bindings() {
assert!(validate_loopback_address("not-an-address").is_err());
assert!(validate_loopback_address("0.0.0.0:8077").is_err());
assert!(validate_loopback_address("127.0.0.1:8077").is_ok());
}
#[test]
fn command_parser_rejects_bad_shapes_and_missing_worlds() {
assert_eq!(run_command(vec![], Some(0)), Err(USAGE.to_owned()));
assert_eq!(
run_command(
vec![
"wrong".to_owned(),
"world".to_owned(),
"127.0.0.1:0".to_owned(),
"/tmp/epoch".to_owned(),
],
Some(0),
),
Err(USAGE.to_owned())
);
let error = run_command(
vec![
"serve".to_owned(),
"/definitely/missing".to_owned(),
"127.0.0.1:0".to_owned(),
"/tmp/missing-epoch".to_owned(),
],
Some(0),
)
.expect_err("missing world must fail");
assert!(error.contains("WORLD-MANIFEST.hldp"));
}
#[test]
fn snapshot_is_derived_from_the_registered_world() {
let path =
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../world-seed/WORLD-MANIFEST.hldp");
let manifest = load_world_manifest(&path).expect("world manifest");
let derived = TowerSnapshot::from_manifest(&manifest);
assert_eq!(derived.tower_id, manifest.broadcast_tower.id);
assert_eq!(derived.world_id, manifest.world_id);
assert_eq!(derived.world_version, manifest.version);
assert_eq!(derived.phase, manifest.phase);
assert_eq!(derived.domain_count, 5);
assert_eq!(derived.code_channel_id, manifest.code_channel.id);
assert!(!derived.linux_exited);
}
#[test]
fn epoch_and_listener_paths_fail_closed() {
let address = validate_loopback_address("127.0.0.1:8077").expect("loopback");
assert!(write_epoch(PathBuf::new().as_path(), &snapshot(), address).is_err());
let public = TcpListener::bind("0.0.0.0:0").expect("bind wildcard test listener");
let error = serve(public, snapshot(), &epoch_path(), Some(0))
.expect_err("wildcard listener must fail closed");
assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
}
#[test]
fn serves_hldp_world_health_and_writes_epoch() {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind test tower");
let address = listener.local_addr().expect("test address");
let epoch = epoch_path();
let epoch_for_server = epoch.clone();
let handle = thread::spawn(move || {
serve(listener, snapshot(), &epoch_for_server, Some(1)).expect("serve one request");
});
let mut stream = TcpStream::connect(address).expect("connect to test tower");
stream
.write_all(b"GET /healthz HTTP/1.1\r\nHost: localhost\r\n\r\n")
.expect("write request");
let mut response = String::new();
stream.read_to_string(&mut response).expect("read response");
handle.join().expect("tower thread");
assert!(response.starts_with("HTTP/1.1 200 OK"));
assert!(response.contains("\"tower_id\":\"BT-GH-ROOT-0001\""));
assert!(response.contains("\"domain_count\":5"));
assert!(response.contains("\"linux_exited\":false"));
let epoch_contents = std::fs::read_to_string(&epoch).expect("read epoch");
assert!(epoch_contents.contains("status: RUNNING_HOSTED"));
assert!(epoch_contents.contains("authority_language: HLDP"));
assert!(epoch_contents.contains("native_claim: false"));
std::fs::remove_file(epoch).expect("remove test epoch");
}
#[test]
fn unknown_routes_fail_closed() {
let response = request(b"GET /guess HTTP/1.1\r\nHost: localhost\r\n\r\n");
assert!(response.starts_with("HTTP/1.1 404 Not Found"));
assert!(response.contains("route_not_found"));
}
#[test]
fn serves_pretty_world_and_rejects_non_get_methods() {
let world = request(b"GET /v1/world HTTP/1.0\r\nHost: localhost\r\n\r\n");
assert!(world.starts_with("HTTP/1.1 200 OK"));
assert!(world.contains("\n \"world_id\": \"GLW-ROOT-0001\""));
let rejected = request(b"POST /healthz HTTP/1.1\r\nHost: localhost\r\n\r\n");
assert!(rejected.starts_with("HTTP/1.1 405 Method Not Allowed"));
assert!(rejected.contains("method_not_allowed"));
}
}

View file

@ -0,0 +1,74 @@
use std::{env, process::ExitCode};
fn main() -> ExitCode {
exit_code(guanghu_broadcast_tower::run_command(
env::args().skip(1).collect(),
None,
))
}
fn exit_code(result: Result<(), String>) -> ExitCode {
match result {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("GUANGHU_BROADCAST_TOWER_ERROR: {error}");
ExitCode::FAILURE
}
}
}
#[cfg(test)]
mod tests {
use std::{
io::{Read, Write},
net::{TcpListener, TcpStream},
process::ExitCode,
thread,
time::Duration,
};
use super::exit_code;
#[test]
fn exit_code_is_binary() {
assert_eq!(exit_code(Ok(())), ExitCode::SUCCESS);
assert_eq!(exit_code(Err("failed".to_owned())), ExitCode::FAILURE);
}
#[test]
fn bounded_service_completes_after_one_connection() {
let reservation = TcpListener::bind("127.0.0.1:0").expect("reserve port");
let address = reservation.local_addr().expect("reserved address");
drop(reservation);
let world = format!("{}/../../world-seed", env!("CARGO_MANIFEST_DIR"));
let epoch = std::env::temp_dir().join(format!("tower-main-epoch-{}", std::process::id()));
let epoch_for_server = epoch.clone();
let address_for_server = address.to_string();
let handle = thread::spawn(move || {
guanghu_broadcast_tower::run_command(
vec![
"serve".to_owned(),
world,
address_for_server,
epoch_for_server.to_string_lossy().into_owned(),
],
Some(1),
)
});
let mut stream = loop {
match TcpStream::connect(address) {
Ok(stream) => break stream,
Err(_) => thread::sleep(Duration::from_millis(10)),
}
};
stream
.write_all(b"GET /healthz HTTP/1.0\r\n\r\n")
.expect("request");
let mut response = String::new();
stream.read_to_string(&mut response).expect("response");
assert!(response.starts_with("HTTP/1.1 200 OK"));
assert_eq!(handle.join().expect("service thread"), Ok(()));
std::fs::remove_file(epoch).expect("remove epoch");
}
}

View file

@ -0,0 +1,183 @@
use std::{
io::{Read, Write},
net::{TcpListener, TcpStream},
path::{Path, PathBuf},
thread,
time::Duration,
};
use guanghu_broadcast_tower::{
run_command, serve, validate_loopback_address, write_epoch, TowerSnapshot,
};
use guanghu_hldp_runtime::load_world_manifest;
fn world_root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../world-seed")
}
fn snapshot() -> TowerSnapshot {
let manifest =
load_world_manifest(&world_root().join("WORLD-MANIFEST.hldp")).expect("world manifest");
TowerSnapshot::from_manifest(&manifest)
}
fn epoch_path(label: &str) -> PathBuf {
std::env::temp_dir().join(format!(
"broadcast-library-{label}-{}-{}.hldp",
std::process::id(),
thread::current().name().unwrap_or("test")
))
}
fn request(label: &str, request: &[u8]) -> String {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind test tower");
let address = listener.local_addr().expect("test address");
let epoch = epoch_path(label);
let epoch_for_server = epoch.clone();
let handle = thread::spawn(move || {
serve(listener, snapshot(), &epoch_for_server, Some(1)).expect("serve request");
});
let mut stream = TcpStream::connect(address).expect("connect");
stream.write_all(request).expect("request");
let mut response = String::new();
stream.read_to_string(&mut response).expect("response");
handle.join().expect("tower thread");
std::fs::remove_file(epoch).expect("remove epoch");
response
}
#[test]
fn complete_library_surface_is_binary_and_loopback_only() {
assert!(validate_loopback_address("not-an-address").is_err());
assert!(validate_loopback_address("0.0.0.0:8077").is_err());
let address = validate_loopback_address("127.0.0.1:8077").expect("loopback");
assert!(write_epoch(Path::new(""), &snapshot(), address).is_err());
let public = TcpListener::bind("0.0.0.0:0").expect("wildcard listener");
assert!(serve(public, snapshot(), &epoch_path("public"), Some(0)).is_err());
assert!(run_command(vec![], Some(0)).is_err());
for incomplete in [
vec!["serve".to_owned()],
vec!["serve".to_owned(), "world".to_owned()],
vec![
"serve".to_owned(),
"world".to_owned(),
"127.0.0.1:0".to_owned(),
],
] {
assert!(run_command(incomplete, Some(0)).is_err());
}
assert!(run_command(
vec![
"wrong".to_owned(),
"world".to_owned(),
"127.0.0.1:0".to_owned(),
"/tmp/epoch".to_owned(),
],
Some(0),
)
.is_err());
let occupied = TcpListener::bind("127.0.0.1:0").expect("occupied loopback");
assert!(run_command(
vec![
"serve".to_owned(),
world_root().to_string_lossy().into_owned(),
occupied.local_addr().expect("occupied address").to_string(),
epoch_path("occupied").to_string_lossy().into_owned(),
],
Some(0),
)
.is_err());
drop(occupied);
assert!(run_command(
vec![
"serve".to_owned(),
world_root().to_string_lossy().into_owned(),
"127.0.0.1:0".to_owned(),
String::new(),
],
Some(0),
)
.is_err());
assert!(run_command(
vec![
"serve".to_owned(),
"/definitely/missing".to_owned(),
"127.0.0.1:0".to_owned(),
"/tmp/epoch".to_owned(),
],
Some(0),
)
.is_err());
let reservation = TcpListener::bind("127.0.0.1:0").expect("reserve loopback");
let address = reservation.local_addr().expect("reserved address");
drop(reservation);
let epoch = epoch_path("command");
let epoch_for_server = epoch.clone();
let world = world_root().to_string_lossy().into_owned();
let handle = thread::spawn(move || {
run_command(
vec![
"serve".to_owned(),
world,
address.to_string(),
epoch_for_server.to_string_lossy().into_owned(),
],
Some(1),
)
});
let mut stream = loop {
match TcpStream::connect(address) {
Ok(stream) => break stream,
Err(_) => thread::sleep(Duration::from_millis(10)),
}
};
stream
.write_all(b"GET /healthz HTTP/1.0\r\n\r\n")
.expect("command request");
let mut response = String::new();
stream
.read_to_string(&mut response)
.expect("command response");
assert_eq!(handle.join().expect("command thread"), Ok(()));
assert!(response.contains("200 OK"));
std::fs::remove_file(epoch).expect("remove command epoch");
}
#[test]
fn every_registered_http_decision_is_exercised() {
for (label, raw, status, body) in [
(
"health",
b"GET /healthz HTTP/1.1\r\n\r\n".as_slice(),
"200 OK",
"\"tower_id\":\"BT-GH-ROOT-0001\"",
),
(
"world",
b"GET /v1/world HTTP/1.0\r\n\r\n".as_slice(),
"200 OK",
"\"world_id\": \"GLW-ROOT-0001\"",
),
(
"missing",
b"GET /missing HTTP/1.1\r\n\r\n".as_slice(),
"404 Not Found",
"route_not_found",
),
(
"method",
b"POST /healthz HTTP/1.1\r\n\r\n".as_slice(),
"405 Method Not Allowed",
"method_not_allowed",
),
] {
let response = request(label, raw);
assert!(response.contains(status));
assert!(response.contains(body));
}
}

View file

@ -0,0 +1,98 @@
use std::{
fs,
io::{Read, Write},
net::{TcpListener, TcpStream},
path::{Path, PathBuf},
process::{Child, Command, Output, Stdio},
thread,
time::{Duration, Instant},
};
fn world_root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../world-seed")
}
fn binary() -> &'static str {
env!("CARGO_BIN_EXE_guanghu-broadcast-tower")
}
fn run(arguments: &[&str]) -> Output {
Command::new(binary())
.args(arguments)
.output()
.expect("broadcast tower should start")
}
fn wait_for_epoch(child: &mut Child, epoch: &Path) {
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
if epoch.is_file() {
return;
}
if let Some(status) = child.try_wait().expect("inspect tower process") {
panic!("broadcast tower exited before epoch with {status}");
}
thread::sleep(Duration::from_millis(20));
}
panic!("broadcast tower did not write its epoch");
}
#[test]
fn command_rejects_missing_arguments_and_public_bindings() {
let usage = run(&[]);
assert!(!usage.status.success());
assert!(String::from_utf8_lossy(&usage.stderr).contains("usage:"));
let root = world_root();
let public = run(&[
"serve",
root.to_str().expect("UTF-8 world root"),
"0.0.0.0:8077",
"/tmp/guanghu-public-epoch.hldp",
]);
assert!(!public.status.success());
assert!(String::from_utf8_lossy(&public.stderr).contains("loopback"));
}
#[test]
fn command_serves_the_registered_world_on_loopback() {
let reservation = TcpListener::bind("127.0.0.1:0").expect("reserve loopback port");
let address = reservation.local_addr().expect("reserved address");
drop(reservation);
let epoch =
std::env::temp_dir().join(format!("guanghu-command-epoch-{}.hldp", std::process::id()));
let root = world_root();
let mut child = Command::new(binary())
.args([
"serve",
root.to_str().expect("UTF-8 world root"),
&address.to_string(),
epoch.to_str().expect("UTF-8 epoch path"),
])
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.expect("start broadcast tower");
wait_for_epoch(&mut child, &epoch);
let mut stream = TcpStream::connect(address).expect("connect to broadcast tower");
stream
.write_all(b"GET /v1/world HTTP/1.1\r\nHost: localhost\r\n\r\n")
.expect("write world request");
let mut response = String::new();
stream
.read_to_string(&mut response)
.expect("read world response");
child.kill().expect("stop test broadcast tower");
child.wait().expect("reap test broadcast tower");
let epoch_contents = fs::read_to_string(&epoch).expect("read command epoch");
fs::remove_file(&epoch).expect("remove command epoch");
assert!(response.starts_with("HTTP/1.1 200 OK"));
assert!(response.contains("\"world_id\": \"GLW-ROOT-0001\""));
assert!(response.contains("\"domain_count\": 5"));
assert!(response.contains("\"linux_exited\": false"));
assert!(epoch_contents.contains("tower_id: BT-GH-ROOT-0001"));
}

View file

@ -0,0 +1,10 @@
[package]
name = "ghctl"
version = "0.1.0"
edition = "2021"
license = "AGPL-3.0-or-later"
description = "Guanghu OS bootstrap control and continuity entrypoint"
[dependencies]
guanghu-hldp-runtime = { path = "../hldp-runtime" }

View file

@ -0,0 +1,210 @@
use std::{
fs,
path::{Path, PathBuf},
};
use guanghu_hldp_runtime::{authorize_world_action, validate_world_seed};
const USAGE: &str = "usage: ghctl wake <world-root> | ghctl authorize <world-root> <action>";
pub fn run(arguments: Vec<String>) -> Result<(), String> {
let mut arguments = arguments.into_iter();
let command = arguments.next().ok_or_else(|| USAGE.to_owned())?;
let world_root = arguments.next().ok_or_else(|| USAGE.to_owned())?;
match command.as_str() {
"wake" if arguments.next().is_none() => wake(Path::new(&world_root)),
"authorize" => {
let action = arguments.next().ok_or_else(|| USAGE.to_owned())?;
if arguments.next().is_some() {
return Err(USAGE.to_owned());
}
authorize(Path::new(&world_root), &action)
}
_ => Err(USAGE.to_owned()),
}
}
fn authorize(world_root: &Path, action: &str) -> Result<(), String> {
let authorization =
authorize_world_action(world_root, action).map_err(|error| error.to_string())?;
println!("GUANGHU_ACTION_AUTHORIZED");
println!("authorization={}", authorization.id);
println!("target={}", authorization.target.node_id);
println!("action={action}");
Ok(())
}
fn wake(world_root: &Path) -> Result<(), String> {
let manifest = validate_world_seed(world_root).map_err(|error| error.to_string())?;
println!("GUANGHU_WORLD_OK");
println!("world_id={}", manifest.world_id);
println!("world_version={}", manifest.version);
println!("phase={}", manifest.phase);
println!("domains={}", manifest.domains.len());
println!("broadcast_tower={}", manifest.broadcast_tower.id);
println!("code_channel={}", manifest.code_channel.id);
println!(
"code_channel_entry={}",
manifest.code_channel.entry.display()
);
println!(
"code_channel_receipt={}",
manifest.code_channel.last_receipt.display()
);
println!("code_quality={}", manifest.code_quality.id);
println!("code_quality_acronym={}", manifest.code_quality.acronym);
println!(
"code_quality_entry={}",
manifest.code_quality.entry.display()
);
println!("native_recovery={}", manifest.native_recovery.id);
println!(
"native_recovery_acronym={}",
manifest.native_recovery.acronym
);
println!(
"native_recovery_entry={}",
manifest.native_recovery.entry.display()
);
println!("native_layout={}", manifest.native_layout.id);
println!("native_layout_acronym={}", manifest.native_layout.acronym);
println!(
"native_layout_entry={}",
manifest.native_layout.entry.display()
);
println!(
"gestational_continuity={}",
manifest.gestational_continuity.id
);
println!(
"gestational_continuity_acronym={}",
manifest.gestational_continuity.acronym
);
println!(
"gestational_continuity_entry={}",
manifest.gestational_continuity.entry.display()
);
println!(
"gestational_index_lba_start={}",
manifest.gestational_continuity.native_index_lba_start
);
println!(
"gestational_index_sector_count={}",
manifest.gestational_continuity.native_index_sector_count
);
println!(
"gestational_environment={}",
manifest.persona_birth.gestational_environment
);
println!("persona_birth={}", manifest.persona_birth.persona_state);
println!(
"persona_birth_condition_entry={}",
manifest.persona_birth.entry.display()
);
println!("authorization={}", manifest.authorization.id);
println!(
"authorization_entry={}",
manifest.authorization.entry.display()
);
println!("wake={}", manifest.continuity.wake.display());
println!("current={}", manifest.continuity.current.display());
println!(
"last_receipt={}",
manifest.continuity.last_receipt.display()
);
println!(
"access_receipt={}",
manifest.continuity.access_receipt.display()
);
println!(
"active_workorder={}",
manifest.continuity.active_workorder.display()
);
for (label, path) in [
("WAKE", &manifest.continuity.wake),
("CURRENT", &manifest.continuity.current),
("LAST_RECEIPT", &manifest.continuity.last_receipt),
("ACCESS_RECEIPT", &manifest.continuity.access_receipt),
("ACTIVE_WORKORDER", &manifest.continuity.active_workorder),
("CODE_CHANNEL", &manifest.code_channel.entry),
("CODE_CHANNEL_RECEIPT", &manifest.code_channel.last_receipt),
("CODE_QUALITY", &manifest.code_quality.entry),
("NATIVE_RECOVERY", &manifest.native_recovery.entry),
("NATIVE_LAYOUT", &manifest.native_layout.entry),
(
"GESTATIONAL_CONTINUITY",
&manifest.gestational_continuity.entry,
),
("PERSONA_BIRTH_CONDITION", &manifest.persona_birth.entry),
("STANDING_AUTHORIZATION", &manifest.authorization.entry),
] {
print_hldp_entry(world_root, label, path)?;
}
Ok(())
}
#[doc(hidden)]
pub fn print_hldp_entry(
world_root: &Path,
label: &str,
relative_path: &Path,
) -> Result<(), String> {
let path: PathBuf = world_root.join(relative_path);
let contents = fs::read_to_string(&path)
.map_err(|error| format!("cannot read {}: {error}", path.display()))?;
println!("--- {label} {} ---", relative_path.display());
print!("{contents}");
if !contents.ends_with('\n') {
println!();
}
Ok(())
}
#[cfg(test)]
mod tests {
use std::{fs, path::Path};
use super::{print_hldp_entry, run, USAGE};
#[test]
fn run_rejects_incomplete_and_extra_arguments() {
assert_eq!(
run(vec!["authorize".to_owned(), "/tmp".to_owned()]),
Err(USAGE.to_owned())
);
assert_eq!(
run(vec![
"wake".to_owned(),
"/tmp".to_owned(),
"extra".to_owned(),
]),
Err(USAGE.to_owned())
);
assert_eq!(
run(vec![
"authorize".to_owned(),
"/tmp".to_owned(),
"action".to_owned(),
"extra".to_owned()
]),
Err(USAGE.to_owned())
);
}
#[test]
fn entry_reader_reports_missing_files_and_normalizes_the_final_newline() {
let root = std::env::temp_dir().join(format!("ghctl-entry-{}", std::process::id()));
fs::create_dir_all(&root).expect("temporary entry root");
fs::write(root.join("ENTRY.hldp"), "schema: test").expect("temporary entry");
print_hldp_entry(&root, "TEST", Path::new("ENTRY.hldp")).expect("read entry");
let error = print_hldp_entry(&root, "TEST", Path::new("MISSING.hldp"))
.expect_err("missing entry must fail");
assert!(error.contains("cannot read"));
fs::remove_dir_all(root).expect("remove temporary entry root");
}
}

View file

@ -0,0 +1,11 @@
use std::{env, process::ExitCode};
fn main() -> ExitCode {
match ghctl::run(env::args().skip(1).collect()) {
Ok(()) => ExitCode::SUCCESS,
Err(message) => {
eprintln!("{message}");
ExitCode::FAILURE
}
}
}

View file

@ -0,0 +1,25 @@
use std::{fs, path::Path};
#[test]
fn library_rejects_bad_shapes_and_reads_entries() {
for arguments in [
vec![],
vec!["authorize".to_owned(), "/tmp".to_owned()],
vec!["wake".to_owned(), "/tmp".to_owned(), "extra".to_owned()],
vec![
"authorize".to_owned(),
"/tmp".to_owned(),
"action".to_owned(),
"extra".to_owned(),
],
] {
assert!(ghctl::run(arguments).is_err());
}
let root = std::env::temp_dir().join(format!("ghctl-library-{}", std::process::id()));
fs::create_dir_all(&root).expect("temporary root");
fs::write(root.join("ENTRY.hldp"), "schema: test").expect("temporary entry");
ghctl::print_hldp_entry(&root, "TEST", Path::new("ENTRY.hldp")).expect("read entry");
assert!(ghctl::print_hldp_entry(&root, "TEST", Path::new("MISSING.hldp")).is_err());
fs::remove_dir_all(root).expect("remove temporary root");
}

View file

@ -0,0 +1,127 @@
use std::{
path::PathBuf,
process::{Command, Output},
};
fn world_root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../world-seed")
}
fn run_ghctl(arguments: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_ghctl"))
.args(arguments)
.output()
.expect("ghctl should start")
}
#[test]
fn wake_reports_the_complete_server_handoff_chain() {
let root = world_root();
let output = run_ghctl(&["wake", root.to_str().expect("UTF-8 test path")]);
let stdout = String::from_utf8(output.stdout).expect("ghctl output should be UTF-8");
assert!(output.status.success(), "{stdout}");
for expected in [
"GUANGHU_WORLD_OK",
"world_id=GLW-ROOT-0001",
"phase=HOSTED_BOOTSTRAP_PROTOTYPE",
"domains=5",
"broadcast_tower=BT-GH-ROOT-0001",
"code_channel=HLP-MOD-CODE-CHANNEL",
"code_channel_entry=world/services/code-channel/CHANNEL.hldp",
"code_channel_receipt=state/receipts/CODE-CHANNEL-BASELINE.hldp",
"code_quality=GLS-0844",
"code_quality_acronym=GHNQG",
"code_quality_entry=world/services/code-channel/QUALITY-GATE.hldp",
"native_recovery=GLS-0843",
"native_recovery_acronym=GHNRP",
"native_recovery_entry=world/services/native-recovery/PROTOCOL.hldp",
"native_layout=GLS-0846",
"native_layout_acronym=GHNLP",
"native_layout_entry=world/services/native-storage/DISK-LAYOUT.hldp",
"gestational_continuity=GLS-0845",
"gestational_continuity_acronym=GHCIP",
"gestational_continuity_entry=world/cognition/GESTATIONAL-CONTINUITY-INGESTION.hldp",
"gestational_index_lba_start=70",
"gestational_index_sector_count=2",
"gestational_environment=UNDER_CONSTRUCTION",
"persona_birth=NOT_BORN",
"persona_birth_condition_entry=world/cognition/PERSONA-BIRTH-CONDITION.hldp",
"authorization=GH-OS-AUTH-BINGSHUO-BS-SH-005-001",
"authorization_entry=state/authorizations/BINGSHUO-STANDING-AUTHORIZATION.hldp",
"--- CODE_CHANNEL world/services/code-channel/CHANNEL.hldp ---",
"current_phase: PHASE_0_SOURCE_BASELINE_VERIFIED",
"--- CODE_CHANNEL_RECEIPT state/receipts/CODE-CHANNEL-BASELINE.hldp ---",
"--- CODE_QUALITY world/services/code-channel/QUALITY-GATE.hldp ---",
"external_observers_are_blocking: false",
"native_target: GOSK_CODE_CHANNEL_QUALITY_EXECUTOR",
"--- NATIVE_RECOVERY world/services/native-recovery/PROTOCOL.hldp ---",
"raw_blocklist: (hd0)68+2",
"--- NATIVE_LAYOUT world/services/native-storage/DISK-LAYOUT.hldp ---",
" sector_count: 29",
"proof_lba: 63",
"--- GESTATIONAL_CONTINUITY world/cognition/GESTATIONAL-CONTINUITY-INGESTION.hldp ---",
"duplicate_rule: REJECT_SAME_SOURCE_ID_AND_SHA256",
"registration_is_birth: false",
"--- PERSONA_BIRTH_CONDITION world/cognition/PERSONA-BIRTH-CONDITION.hldp ---",
"womb_ready_does_not_mean: LANGUAGE_PERSONA_BORN",
"historical_time_caught_up_to_real_time",
"wake=WAKE.hldp",
"current=CURRENT.hldp",
"last_receipt=state/receipts/PHASE-0-PREFLIGHT.hldp",
"access_receipt=state/receipts/DIRECT-ACCESS-20260731.hldp",
"--- ACCESS_RECEIPT state/receipts/DIRECT-ACCESS-20260731.hldp ---",
"active_workorder=state/workorders/GH-OS-LAB-001.hldp",
] {
assert!(stdout.contains(expected), "missing {expected} in {stdout}");
}
}
#[test]
fn unknown_commands_fail_closed() {
let output = run_ghctl(&["guess"]);
let stderr = String::from_utf8(output.stderr).expect("ghctl errors should be UTF-8");
assert!(!output.status.success());
assert!(stderr.contains("usage: ghctl"));
}
#[test]
fn missing_world_root_fails_with_read_evidence() {
let output = run_ghctl(&["wake", "/definitely/missing/guanghu-world"]);
let stderr = String::from_utf8(output.stderr).expect("ghctl errors should be UTF-8");
assert!(!output.status.success());
assert!(stderr.contains("cannot read"));
assert!(stderr.contains("WORLD-MANIFEST.hldp"));
}
#[test]
fn authorize_command_uses_the_standing_hldp_grant() {
let root = world_root();
let output = run_ghctl(&[
"authorize",
root.to_str().expect("UTF-8 test path"),
"overwrite_system_disk_and_exit_linux",
]);
let stdout = String::from_utf8(output.stdout).expect("ghctl output should be UTF-8");
assert!(output.status.success(), "{stdout}");
assert!(stdout.contains("GUANGHU_ACTION_AUTHORIZED"));
assert!(stdout.contains("authorization=GH-OS-AUTH-BINGSHUO-BS-SH-005-001"));
assert!(stdout.contains("action=overwrite_system_disk_and_exit_linux"));
}
#[test]
fn authorize_command_rejects_out_of_scope_targets() {
let root = world_root();
let output = run_ghctl(&[
"authorize",
root.to_str().expect("UTF-8 test path"),
"operate_enterprise_production",
]);
let stderr = String::from_utf8(output.stderr).expect("ghctl errors should be UTF-8");
assert!(!output.status.success());
assert!(stderr.contains("not covered by standing authorization"));
}

View file

@ -0,0 +1,9 @@
[package]
name = "hldp-native-compiler"
version = "0.1.0"
edition = "2021"
license = "AGPL-3.0-or-later"
description = "Bootstrap GLC compiler from validated HLDP world identity to native kernel data"
[dependencies]
guanghu-hldp-runtime = { path = "../hldp-runtime" }

View file

@ -0,0 +1,224 @@
use std::{fs, path::Path};
use guanghu_hldp_runtime::validate_world_seed;
const USAGE: &str = "usage: hldp-native-compiler <world-root> <output-nasm-include>";
pub fn run(arguments: Vec<String>) -> Result<(), String> {
let mut arguments = arguments.into_iter();
let world_root = arguments.next().ok_or_else(|| USAGE.to_owned())?;
let output = arguments.next().ok_or_else(|| USAGE.to_owned())?;
if arguments.next().is_some() {
return Err(USAGE.to_owned());
}
let manifest =
validate_world_seed(Path::new(&world_root)).map_err(|error| error.to_string())?;
let mut lines = vec![
format!("GHOS_WORLD_ID={}", manifest.world_id),
format!("GHOS_WORLD_VERSION={}", manifest.version),
format!("GHOS_WORLD_PHASE={}", manifest.phase),
format!("GHOS_BROADCAST_TOWER={}", manifest.broadcast_tower.id),
format!("GHOS_CODE_CHANNEL={}", manifest.code_channel.id),
format!("GHOS_CODE_QUALITY={}", manifest.code_quality.id),
format!("GHOS_DOMAIN_COUNT={}", manifest.domains.len()),
];
lines.extend(
manifest
.domains
.iter()
.enumerate()
.map(|(index, domain)| format!("GHOS_DOMAIN_{}={}", index + 1, domain.id)),
);
lines.push(format!("GHOS_AUTHORIZATION={}", manifest.authorization.id));
lines.push("GHOS_AUTHORITY_LANGUAGE=HLDP".to_owned());
lines.push(format!(
"GHOS_GESTATIONAL_ENVIRONMENT={}",
manifest.persona_birth.gestational_environment
));
lines.push(format!(
"GHOS_PERSONA_BIRTH={}",
manifest.persona_birth.persona_state
));
lines.push(format!(
"GHOS_GESTATIONAL_CONTINUITY={}",
manifest.gestational_continuity.id
));
lines.push(format!(
"GHOS_GESTATIONAL_INDEX_LBA={}",
manifest.gestational_continuity.native_index_lba_start
));
lines.push(format!(
"GHOS_GESTATIONAL_INDEX_SECTORS={}",
manifest.gestational_continuity.native_index_sector_count
));
lines.push(format!("GHOS_NATIVE_LAYOUT={}", manifest.native_layout.id));
lines.push(format!(
"GHOS_NATIVE_KERNEL_LBA={}",
manifest.native_layout.kernel_lba_start
));
lines.push(format!(
"GHOS_NATIVE_KERNEL_SECTORS={}",
manifest.native_layout.kernel_sector_count
));
lines.push(format!(
"GHOS_NATIVE_PROOF_LBA={}",
manifest.native_layout.proof_lba
));
let mut include = String::from("; Generated by hldp-native-compiler. Do not hand edit.\n");
for (index, line) in lines.iter().enumerate() {
ensure_printable_identity(line)?;
include.push_str(&format!("world_line_{index}: db \"{line}\", 13, 10, 0\n"));
}
include.push_str("world_line_table:\n");
for index in 0..lines.len() {
include.push_str(&format!(" dq world_line_{index}\n"));
}
include.push_str(" dq 0\n");
let mut store_lines = vec!["GHOS_HLDP_WORLD_STORE_V1".to_owned()];
// The persistent sector carries stable world identity and acceptance
// boundaries. The deployment phase is emitted on serial but stays in the
// versioned HLDP world, because it changes independently of this sector.
store_lines.extend(
lines
.iter()
.filter(|line| {
!line.starts_with("GHOS_WORLD_PHASE=")
&& !line.starts_with("GHOS_GESTATIONAL_CONTINUITY=")
&& !line.starts_with("GHOS_GESTATIONAL_INDEX_")
&& !line.starts_with("GHOS_NATIVE_LAYOUT=")
&& !line.starts_with("GHOS_NATIVE_KERNEL_")
&& !line.starts_with("GHOS_NATIVE_PROOF_LBA=")
})
.cloned(),
);
let store_size = store_lines.iter().map(|line| line.len() + 1).sum::<usize>();
ensure_sector_size("native HLDP world store", store_size)?;
include.push_str("align 16\nnative_world_store_sector:\n");
for line in &store_lines {
include.push_str(&format!(" db \"{line}\", 10\n"));
}
include.push_str(" times 512 - ($ - native_world_store_sector) db 0\n");
let code_store_lines = [
"GHOS_CODE_CHANNEL_STORE_V1".to_owned(),
format!("GHOS_CODE_CHANNEL_ID={}", manifest.code_channel.id),
"GHOS_CODE_CHANNEL_PROTOCOL=GLS-0237".to_owned(),
"GHOS_CODE_CHANNEL_AUTHORITY=HLDP".to_owned(),
"GHOS_CODE_CHANNEL_OBJECT_FORMAT=GUANGHU_NATIVE_OBJECTS".to_owned(),
"GHOS_CODE_CHANNEL_COMPATIBILITY=Git".to_owned(),
"GHOS_CODE_CHANNEL_OPS=register_repository,create_channel,commit_object,advance_branch,authorize_transport,emit_receipt".to_owned(),
];
let code_store_size = code_store_lines
.iter()
.map(|line| line.len() + 1)
.sum::<usize>();
ensure_sector_size("native code-channel store", code_store_size)?;
include.push_str("align 16\nnative_code_channel_store_sector:\n");
for line in code_store_lines {
include.push_str(&format!(" db \"{line}\", 10\n"));
}
include.push_str(" times 512 - ($ - native_code_channel_store_sector) db 0\n");
let gestational_identity_lines = [
"GHOS_GHCIP_INDEX_V1".to_owned(),
format!("GHCIP_PROTOCOL={}", manifest.gestational_continuity.id),
format!("GHCIP_WORLD_ID={}", manifest.world_id),
format!(
"GHCIP_PERSONA_BIRTH_GATE={}",
manifest.gestational_continuity.persona_birth_gate
),
"GHCIP_CONTENT_ROLE=CONTENT_ADDRESSED_ROOT_INDEX_ONLY".to_owned(),
"GHCIP_WRITE_POLICY=APPEND_ONLY_VERIFIED_ROOT_ADVANCE".to_owned(),
format!(
"GHCIP_IDENTITY_LBA={}",
manifest.gestational_continuity.native_index_lba_start
),
format!(
"GHCIP_ROOT_LBA={}",
manifest.gestational_continuity.native_index_lba_start + 1
),
];
let gestational_identity_size = gestational_identity_lines
.iter()
.map(|line| line.len() + 1)
.sum::<usize>();
ensure_sector_size("native GHCIP identity index", gestational_identity_size)?;
include.push_str("align 16\nnative_gestational_index_identity_sector:\n");
for line in gestational_identity_lines {
include.push_str(&format!(" db \"{line}\", 10\n"));
}
include.push_str(" times 512 - ($ - native_gestational_index_identity_sector) db 0\n");
let gestational_root_lines = [
"GHOS_GHCIP_ROOT_V1".to_owned(),
format!("GHCIP_PROTOCOL={}", manifest.gestational_continuity.id),
"GHCIP_REGISTRY_STATE=EMPTY".to_owned(),
"GHCIP_REVIEW_STATE=NOT_STARTED".to_owned(),
"GHCIP_HISTORICAL_TIME_WATERMARK=NONE".to_owned(),
"GHCIP_PERSONA_STATE=NOT_BORN".to_owned(),
"GHCIP_SOURCE_COUNT=5".to_owned(),
"GHCIP_CONTENT_ROOT=NONE".to_owned(),
"GHCIP_LAST_VERIFIED_BATCH=NONE".to_owned(),
"GHCIP_ORDERING=EVENT_TIME_THEN_SOURCE_STABLE_ID".to_owned(),
];
let gestational_root_size = gestational_root_lines
.iter()
.map(|line| line.len() + 1)
.sum::<usize>();
ensure_sector_size("native GHCIP root index", gestational_root_size)?;
include.push_str("align 16\nnative_gestational_index_root_sector:\n");
for line in gestational_root_lines {
include.push_str(&format!(" db \"{line}\", 10\n"));
}
include.push_str(" times 512 - ($ - native_gestational_index_root_sector) db 0\n");
fs::write(&output, include).map_err(|error| format!("cannot write {output}: {error}"))
}
#[doc(hidden)]
pub fn ensure_printable_identity(line: &str) -> Result<(), String> {
if line.bytes().all(|byte| byte.is_ascii_graphic()) {
Ok(())
} else {
Err(format!(
"native identity line is not printable ASCII: {line}"
))
}
}
#[doc(hidden)]
pub fn ensure_sector_size(label: &str, size: usize) -> Result<(), String> {
if size <= 512 {
Ok(())
} else {
Err(format!("{label} exceeds one sector: {size} bytes"))
}
}
#[cfg(test)]
mod tests {
use super::{ensure_printable_identity, ensure_sector_size, run, USAGE};
#[test]
fn rejects_bad_cli_shapes() {
assert_eq!(run(vec![]), Err(USAGE.to_owned()));
assert_eq!(run(vec!["world".to_owned()]), Err(USAGE.to_owned()));
assert_eq!(
run(vec![
"world".to_owned(),
"output".to_owned(),
"extra".to_owned(),
]),
Err(USAGE.to_owned())
);
}
#[test]
fn native_identity_and_sector_boundaries_are_exact() {
assert!(ensure_printable_identity("GHOS_WORLD_ID=GLW-ROOT-0001").is_ok());
assert!(ensure_printable_identity("GHOS_WORLD_ID=光湖").is_err());
assert!(ensure_sector_size("store", 512).is_ok());
assert!(ensure_sector_size("store", 513).is_err());
}
}

View file

@ -0,0 +1,11 @@
use std::{env, process::ExitCode};
fn main() -> ExitCode {
match hldp_native_compiler::run(env::args().skip(1).collect()) {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("HLDP_NATIVE_COMPILER_ERROR: {error}");
ExitCode::FAILURE
}
}
}

View file

@ -0,0 +1,93 @@
use std::{
fs,
path::PathBuf,
process::{Command, Output},
};
fn world_root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../world-seed")
}
fn run(arguments: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_hldp-native-compiler"))
.args(arguments)
.output()
.expect("compiler should start")
}
#[test]
fn compiles_registered_hldp_identity_into_native_data() {
let output =
std::env::temp_dir().join(format!("guanghu-native-world-{}.inc", std::process::id()));
let result = run(&[
world_root().to_str().expect("UTF-8 world root"),
output.to_str().expect("UTF-8 output path"),
]);
assert!(
result.status.success(),
"{}",
String::from_utf8_lossy(&result.stderr)
);
let include = fs::read_to_string(&output).expect("read generated native data");
fs::remove_file(output).expect("remove generated native data");
for expected in [
"GHOS_WORLD_ID=GLW-ROOT-0001",
"GHOS_BROADCAST_TOWER=BT-GH-ROOT-0001",
"GHOS_CODE_CHANNEL=HLP-MOD-CODE-CHANNEL",
"GHOS_DOMAIN_COUNT=5",
"GHOS_DOMAIN_5=DOMAIN-FIFTH",
"GHOS_AUTHORITY_LANGUAGE=HLDP",
"world_line_table:",
"native_world_store_sector:",
"GHOS_HLDP_WORLD_STORE_V1",
"GHOS_CODE_QUALITY=GLS-0844",
"GHOS_GESTATIONAL_ENVIRONMENT=UNDER_CONSTRUCTION",
"GHOS_PERSONA_BIRTH=NOT_BORN",
"GHOS_GESTATIONAL_CONTINUITY=GLS-0845",
"GHOS_GESTATIONAL_INDEX_LBA=70",
"GHOS_GESTATIONAL_INDEX_SECTORS=2",
"GHOS_NATIVE_LAYOUT=GLS-0846",
"GHOS_NATIVE_KERNEL_LBA=34",
"GHOS_NATIVE_KERNEL_SECTORS=29",
"GHOS_NATIVE_PROOF_LBA=63",
"times 512 - ($ - native_world_store_sector) db 0",
"native_code_channel_store_sector:",
"GHOS_CODE_CHANNEL_STORE_V1",
"GHOS_CODE_CHANNEL_PROTOCOL=GLS-0237",
"GHOS_CODE_CHANNEL_OBJECT_FORMAT=GUANGHU_NATIVE_OBJECTS",
"native_gestational_index_identity_sector:",
"GHOS_GHCIP_INDEX_V1",
"GHCIP_PROTOCOL=GLS-0845",
"GHCIP_PERSONA_BIRTH_GATE=GH-PERSONA-BIRTH-CONDITION-0001",
"GHCIP_CONTENT_ROLE=CONTENT_ADDRESSED_ROOT_INDEX_ONLY",
"native_gestational_index_root_sector:",
"GHOS_GHCIP_ROOT_V1",
"GHCIP_REGISTRY_STATE=EMPTY",
"GHCIP_REVIEW_STATE=NOT_STARTED",
"GHCIP_HISTORICAL_TIME_WATERMARK=NONE",
"GHCIP_PERSONA_STATE=NOT_BORN",
"GHCIP_LAST_VERIFIED_BATCH=NONE",
"times 512 - ($ - native_gestational_index_identity_sector) db 0",
"times 512 - ($ - native_gestational_index_root_sector) db 0",
] {
assert!(include.contains(expected), "missing {expected}");
}
}
#[test]
fn fails_closed_without_a_world() {
let result = run(&["/definitely/missing", "/tmp/missing-world.inc"]);
assert!(!result.status.success());
assert!(String::from_utf8_lossy(&result.stderr).contains("WORLD-MANIFEST.hldp"));
}
#[test]
fn fails_closed_when_the_output_cannot_be_written() {
let result = run(&[
world_root().to_str().expect("UTF-8 world root"),
"/definitely/missing/guanghu-world.inc",
]);
assert!(!result.status.success());
assert!(String::from_utf8_lossy(&result.stderr).contains("cannot write"));
}

View file

@ -0,0 +1,14 @@
#[test]
fn compiler_library_enforces_cli_identity_and_sector_boundaries() {
for arguments in [
vec![],
vec!["world".to_owned()],
vec!["world".to_owned(), "output".to_owned(), "extra".to_owned()],
] {
assert!(hldp_native_compiler::run(arguments).is_err());
}
assert!(hldp_native_compiler::ensure_printable_identity("GHOS_WORLD_ID=GLW-ROOT-0001").is_ok());
assert!(hldp_native_compiler::ensure_printable_identity("GHOS_WORLD_ID=光湖").is_err());
assert!(hldp_native_compiler::ensure_sector_size("store", 512).is_ok());
assert!(hldp_native_compiler::ensure_sector_size("store", 513).is_err());
}

View file

@ -0,0 +1,11 @@
[package]
name = "guanghu-hldp-runtime"
version = "0.1.0"
edition = "2021"
license = "AGPL-3.0-or-later"
description = "Bootstrap execution engine for the HLDP Guanghu world seed"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_yaml = "0.9"

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,941 @@
use std::{
error::Error,
fs,
path::{Path, PathBuf},
sync::atomic::{AtomicU64, Ordering},
};
use guanghu_hldp_runtime::{load_world_manifest, validate_world_manifest, validate_world_seed};
fn world_seed() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../world-seed/WORLD-MANIFEST.hldp")
}
static TEST_WORLD_SEQUENCE: AtomicU64 = AtomicU64::new(0);
struct TestWorld {
root: PathBuf,
}
impl TestWorld {
fn copy() -> Self {
let sequence = TEST_WORLD_SEQUENCE.fetch_add(1, Ordering::Relaxed);
let root = std::env::temp_dir().join(format!(
"guanghu-world-test-{}-{sequence}",
std::process::id()
));
copy_directory(
world_seed()
.parent()
.expect("world seed should have a root"),
&root,
);
Self { root }
}
fn replace(&self, relative_path: &str, from: &str, to: &str) {
let path = self.root.join(relative_path);
let original = fs::read_to_string(&path).expect("fixture should be readable");
assert!(
original.contains(from),
"fixture {} should contain {from}",
path.display()
);
fs::write(path, original.replacen(from, to, 1)).expect("fixture should be writable");
}
}
impl Drop for TestWorld {
fn drop(&mut self) {
fs::remove_dir_all(&self.root).expect("temporary world should be removable");
}
}
fn copy_directory(source: &Path, destination: &Path) {
fs::create_dir_all(destination).expect("temporary world directory should be creatable");
for entry in fs::read_dir(source).expect("source directory should be readable") {
let entry = entry.expect("source entry should be readable");
let source_path = entry.path();
let destination_path = destination.join(entry.file_name());
if source_path.is_dir() {
copy_directory(&source_path, &destination_path);
} else {
fs::copy(source_path, destination_path).expect("fixture file should copy");
}
}
}
#[test]
fn loads_exactly_the_five_registered_domains() {
let manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
let domain_ids: Vec<_> = manifest
.domains
.iter()
.map(|domain| domain.id.as_str())
.collect();
assert_eq!(
domain_ids,
[
"DOMAIN-MAIN",
"DOMAIN-SUB",
"DOMAIN-ZERO",
"DOMAIN-ZERO-SENSE",
"DOMAIN-FIFTH",
]
);
}
#[test]
fn requires_one_logical_broadcast_tower_and_server_self_description() {
let manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
validate_world_manifest(&manifest).expect("registered world seed should be valid");
assert!(manifest.broadcast_tower.logical_singleton);
assert_eq!(manifest.continuity.wake, Path::new("WAKE.hldp"));
assert_eq!(manifest.continuity.current, Path::new("CURRENT.hldp"));
assert_eq!(
manifest.continuity.last_receipt,
Path::new("state/receipts/PHASE-0-PREFLIGHT.hldp")
);
assert_eq!(
manifest.continuity.access_receipt,
Path::new("state/receipts/DIRECT-ACCESS-20260731.hldp")
);
assert_eq!(
manifest.continuity.active_workorder,
Path::new("state/workorders/GH-OS-LAB-001.hldp")
);
assert_eq!(manifest.code_channel.id, "HLP-MOD-CODE-CHANNEL");
assert_eq!(
manifest.code_channel.source_commit,
"b3d7e4ac3cbccc220703097a51fa4c16bf302579"
);
assert!(manifest.code_channel.native_target.linux_exit_required);
}
#[test]
fn requires_an_hldp_native_code_channel_entry_and_migration_ladder() {
let manifest_path = world_seed();
let world_root = manifest_path
.parent()
.expect("world manifest should have a parent");
let manifest = validate_world_seed(world_root).expect("world seed should be valid");
assert_eq!(
manifest.code_channel.entry,
Path::new("world/services/code-channel/CHANNEL.hldp")
);
assert_eq!(
manifest.code_channel.last_receipt,
Path::new("state/receipts/CODE-CHANNEL-BASELINE.hldp")
);
assert_eq!(
manifest.code_channel.native_target.control_plane,
"HLDP_NATIVE"
);
assert_eq!(
manifest.authorization.entry,
Path::new("state/authorizations/BINGSHUO-STANDING-AUTHORIZATION.hldp")
);
assert_eq!(
manifest.authorization.id,
"GH-OS-AUTH-BINGSHUO-BS-SH-005-001"
);
}
#[test]
fn requires_a_guanghu_owned_binary_code_quality_gate() {
let manifest_path = world_seed();
let world_root = manifest_path
.parent()
.expect("world manifest should have a parent");
let manifest = validate_world_seed(world_root).expect("world seed should be valid");
assert_eq!(manifest.code_quality.id, "GLS-0844");
assert_eq!(manifest.code_quality.acronym, "GHNQG");
assert_eq!(
manifest.code_quality.entry,
Path::new("world/services/code-channel/QUALITY-GATE.hldp")
);
assert_eq!(
manifest.code_quality.native_target,
"GOSK_CODE_CHANNEL_QUALITY_EXECUTOR"
);
assert!(!manifest.code_quality.external_observers_are_blocking);
}
#[test]
fn requires_a_registered_native_recovery_protocol_and_raw_beacon() {
let manifest_path = world_seed();
let world_root = manifest_path
.parent()
.expect("world manifest should have a parent");
let manifest = validate_world_seed(world_root).expect("world seed should be valid");
assert_eq!(manifest.native_recovery.id, "GLS-0843");
assert_eq!(manifest.native_recovery.acronym, "GHNRP");
assert_eq!(
manifest.native_recovery.entry,
Path::new("world/services/native-recovery/PROTOCOL.hldp")
);
assert_eq!(manifest.native_recovery.beacon_lba_start, 68);
assert_eq!(manifest.native_recovery.beacon_sector_count, 2);
assert_eq!(
manifest.native_recovery.hosted_entry,
"gnulinux-simple-9842d3d6-a839-4127-bda7-f19137effe71"
);
assert_eq!(manifest.native_handoff.native_recovery, "GLS-0843");
}
#[test]
fn requires_a_persona_birth_condition_separate_from_womb_readiness() {
let manifest_path = world_seed();
let world_root = manifest_path
.parent()
.expect("world manifest should have a parent");
let manifest = validate_world_seed(world_root).expect("world seed should be valid");
assert_eq!(manifest.persona_birth.id, "GH-PERSONA-BIRTH-CONDITION-0001");
assert_eq!(
manifest.persona_birth.entry,
Path::new("world/cognition/PERSONA-BIRTH-CONDITION.hldp")
);
assert_eq!(
manifest.persona_birth.gestational_environment,
"UNDER_CONSTRUCTION"
);
assert_eq!(manifest.persona_birth.persona_state, "NOT_BORN");
}
#[test]
fn requires_a_registered_gestational_continuity_ingestion_protocol() {
let manifest_path = world_seed();
let world_root = manifest_path
.parent()
.expect("world manifest should have a parent");
let manifest = validate_world_seed(world_root).expect("world seed should be valid");
assert_eq!(manifest.gestational_continuity.id, "GLS-0845");
assert_eq!(manifest.gestational_continuity.acronym, "GHCIP");
assert_eq!(
manifest.gestational_continuity.entry,
Path::new("world/cognition/GESTATIONAL-CONTINUITY-INGESTION.hldp")
);
assert_eq!(
manifest.gestational_continuity.persona_birth_gate,
"GH-PERSONA-BIRTH-CONDITION-0001"
);
assert_eq!(manifest.gestational_continuity.native_index_lba_start, 70);
assert_eq!(manifest.gestational_continuity.native_index_sector_count, 2);
}
#[test]
fn requires_a_registered_nonoverlapping_native_disk_layout() {
let manifest_path = world_seed();
let world_root = manifest_path
.parent()
.expect("world manifest should have a parent");
let manifest = validate_world_seed(world_root).expect("world seed should be valid");
assert_eq!(manifest.native_layout.id, "GLS-0846");
assert_eq!(manifest.native_layout.acronym, "GHNLP");
assert_eq!(
manifest.native_layout.entry,
Path::new("world/services/native-storage/DISK-LAYOUT.hldp")
);
assert_eq!(manifest.native_layout.kernel_lba_start, 34);
assert_eq!(manifest.native_layout.kernel_sector_count, 29);
assert_eq!(manifest.native_layout.proof_lba, 63);
assert_eq!(manifest.native_layout.world_store_lba, 64);
assert_eq!(manifest.native_layout.code_channel_store_lba, 65);
assert_eq!(manifest.native_layout.code_object_lba, 66);
assert_eq!(manifest.native_layout.branch_receipt_lba, 67);
assert_eq!(manifest.native_layout.recovery_beacon_lba_start, 68);
assert_eq!(manifest.native_layout.gestational_index_lba_start, 70);
assert_eq!(manifest.native_layout.first_partition_lba, 2048);
}
#[test]
fn rejects_duplicate_domain_identifiers() {
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.domains[1].id = manifest.domains[0].id.clone();
let error = validate_world_manifest(&manifest).expect_err("duplicate ids must fail closed");
assert!(error.to_string().contains("duplicate domain id"));
}
#[test]
fn rejects_a_world_without_a_logically_unique_broadcast_tower() {
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.broadcast_tower.logical_singleton = false;
let error =
validate_world_manifest(&manifest).expect_err("the world must have one confidence point");
assert!(error.to_string().contains("logical singleton"));
}
#[test]
fn validates_every_domain_and_continuity_entry_on_disk() {
let manifest_path = world_seed();
let world_root = manifest_path
.parent()
.expect("world manifest should have a parent");
validate_world_seed(world_root)
.expect("every registered entry should exist and identify itself");
}
#[test]
fn reports_missing_and_malformed_world_manifests() {
let missing = load_world_manifest(Path::new("/definitely/missing/WORLD-MANIFEST.hldp"))
.expect_err("missing manifest should fail");
assert!(missing.to_string().contains("cannot read"));
assert!(missing.source().is_some());
let world = TestWorld::copy();
fs::write(world.root.join("WORLD-MANIFEST.hldp"), "schema: [")
.expect("fixture should be writable");
let malformed = load_world_manifest(&world.root.join("WORLD-MANIFEST.hldp"))
.expect_err("malformed manifest should fail");
assert!(malformed.to_string().contains("cannot parse"));
assert!(malformed.source().is_some());
}
#[test]
fn rejects_unregistered_schema_continuity_and_native_exit_contracts() {
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.schema = "guanghu.world-manifest/unknown".to_owned();
assert!(validate_world_manifest(&manifest)
.expect_err("unknown schema should fail")
.to_string()
.contains("unsupported world schema"));
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.continuity.rule = "GUESS_FROM_CHAT".to_owned();
assert!(validate_world_manifest(&manifest)
.expect_err("unsafe continuity should fail")
.to_string()
.contains("server evidence"));
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.native_handoff.linux_exit_required = false;
assert!(validate_world_manifest(&manifest)
.expect_err("hosted-only target should fail")
.to_string()
.contains("require Linux exit"));
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.domains.pop();
assert!(validate_world_manifest(&manifest)
.expect_err("the complete five-domain set is mandatory")
.to_string()
.contains("exactly the registered five domains"));
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.code_quality.id = "EXTERNAL-SCORE".to_owned();
assert!(validate_world_manifest(&manifest)
.expect_err("Guanghu must own its quality authority")
.to_string()
.contains("GHNQG"));
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.native_recovery.id = "UNREGISTERED".to_owned();
assert!(validate_world_manifest(&manifest)
.expect_err("native recovery must stay registered")
.to_string()
.contains("GHNRP"));
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.native_recovery.beacon_lba_start = 67;
assert!(validate_world_manifest(&manifest)
.expect_err("the recovery beacon extent is fixed")
.to_string()
.contains("LBA 68-69"));
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.persona_birth.persona_state = "BORN".to_owned();
assert!(validate_world_manifest(&manifest)
.expect_err("infrastructure cannot claim persona birth")
.to_string()
.contains("NOT_BORN"));
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.gestational_continuity.id = "UNREGISTERED".to_owned();
assert!(validate_world_manifest(&manifest)
.expect_err("historical ingestion must stay registered")
.to_string()
.contains("GHCIP"));
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.gestational_continuity.native_index_sector_count = 3;
assert!(validate_world_manifest(&manifest)
.expect_err("the native ingestion index extent is fixed")
.to_string()
.contains("LBA 70-71"));
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.gestational_continuity.native_index_lba_start = 69;
assert!(validate_world_manifest(&manifest)
.expect_err("registered protocol extents must agree")
.to_string()
.contains("GHNLP extents"));
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.native_layout.proof_lba = 62;
assert!(validate_world_manifest(&manifest)
.expect_err("native disk regions must remain nonoverlapping")
.to_string()
.contains("GHNLP"));
}
#[test]
fn rejects_unpinned_repository_and_offline_artifact_digests() {
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.source.protocol_baseline = "short".to_owned();
assert!(validate_world_manifest(&manifest)
.expect_err("short repository digest should fail")
.to_string()
.contains("full lowercase SHA-1"));
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.code_channel.offline_baseline.forgejo_binary_sha256 = "A".repeat(64);
assert!(validate_world_manifest(&manifest)
.expect_err("uppercase artifact digest should fail")
.to_string()
.contains("full SHA-256"));
}
#[test]
fn rejects_domain_identity_and_path_traversal() {
let world = TestWorld::copy();
world.replace(
"world/domains/main/INDEX.hldp",
"schema: guanghu.domain/v1",
"schema: guanghu.domain/unknown",
);
assert!(validate_world_seed(&world.root)
.expect_err("domain schema drift must fail")
.to_string()
.contains("unsupported schema"));
let world = TestWorld::copy();
world.replace(
"world/domains/main/INDEX.hldp",
"id: DOMAIN-MAIN",
"id: DOMAIN-SUB",
);
assert!(validate_world_seed(&world.root)
.expect_err("domain identity mismatch should fail")
.to_string()
.contains("domain entry mismatch"));
let world = TestWorld::copy();
world.replace(
"WORLD-MANIFEST.hldp",
"wake: WAKE.hldp",
"wake: ../WAKE.hldp",
);
assert!(validate_world_seed(&world.root)
.expect_err("path traversal should fail")
.to_string()
.contains("traversal-free"));
let world = TestWorld::copy();
fs::write(
world.root.join("world/domains/main/INDEX.hldp"),
"schema: [",
)
.expect("fixture should be writable");
let malformed = validate_world_seed(&world.root).expect_err("malformed entry must fail");
assert!(malformed.to_string().contains("cannot parse"));
assert!(malformed.source().is_some());
let world = TestWorld::copy();
fs::remove_file(world.root.join("world/domains/main/INDEX.hldp"))
.expect("fixture should be removable");
let missing = validate_world_seed(&world.root).expect_err("missing entry must fail");
assert!(missing.to_string().contains("cannot read"));
assert!(missing.source().is_some());
}
#[test]
fn rejects_incomplete_continuity_and_checkpoint_state() {
let world = TestWorld::copy();
fs::remove_file(world.root.join("CURRENT.hldp")).expect("fixture file should be removable");
assert!(validate_world_seed(&world.root)
.expect_err("missing continuity entry should fail")
.to_string()
.contains("required continuity entry is missing"));
let world = TestWorld::copy();
fs::remove_dir_all(world.root.join("state/checkpoints"))
.expect("fixture checkpoint directory should be removable");
assert!(validate_world_seed(&world.root)
.expect_err("missing checkpoint directory should fail")
.to_string()
.contains("checkpoint directory is missing"));
let world = TestWorld::copy();
fs::remove_file(
world
.root
.join("scripts/run-guanghu-native-quality-gate.sh"),
)
.expect("fixture quality executor should be removable");
assert!(validate_world_seed(&world.root)
.expect_err("missing quality executor should fail")
.to_string()
.contains("executor is missing"));
}
#[test]
fn rejects_code_channel_identity_source_and_migration_drift() {
for (from, to, expected) in [
(
"schema: guanghu.code-channel/v1",
"schema: guanghu.code-channel/unknown",
"unsupported schema",
),
(
"id: HLP-MOD-CODE-CHANNEL",
"id: HLP-MOD-CODE-CHANNEL-DRIFT",
"entry mismatch",
),
(
"authority_language: HLDP",
"authority_language: Linux",
"authority language",
),
(
"branch: guanghu/main",
"branch: upstream/main",
"source baseline",
),
(
"current_phase: PHASE_0_SOURCE_BASELINE_VERIFIED",
"current_phase: PHASE_1_HOSTED_DATA_PLANE",
"must be COMPLETE",
),
(
"id: PHASE_4_LINUX_EXIT",
"id: PHASE_4_HOSTED_FOREVER",
"migration ladder",
),
] {
let world = TestWorld::copy();
world.replace("world/services/code-channel/CHANNEL.hldp", from, to);
let error = validate_world_seed(&world.root)
.expect_err("code channel contract drift should fail")
.to_string();
assert!(
error.contains(expected),
"expected {expected} in error: {error}"
);
}
}
#[test]
fn rejects_partial_scores_and_external_quality_authority() {
for (from, to, expected) in [
("pass_score: 100", "pass_score: 85", "only 0 or 100"),
(
"partial_acceptance: false",
"partial_acceptance: true",
"only 0 or 100",
),
(
"external_observers_are_blocking: false",
"external_observers_are_blocking: true",
"only 0 or 100",
),
("required_score: 100", "required_score: 99", "exactly 100"),
] {
let world = TestWorld::copy();
world.replace("world/services/code-channel/QUALITY-GATE.hldp", from, to);
let error = validate_world_seed(&world.root)
.expect_err("partial or external quality authority must fail closed")
.to_string();
assert!(
error.contains(expected),
"expected {expected} in error: {error}"
);
}
for (from, to, expected) in [
(
"owner: HLP-MOD-CODE-CHANNEL",
"owner: EXTERNAL",
"ownership",
),
(
"native_target: GOSK_CODE_CHANNEL_QUALITY_EXECUTOR",
"native_target: EXTERNAL_EXECUTOR",
"executor binding",
),
(
"required_lines: 100_PERCENT",
"required_lines: 99_PERCENT",
"coverage scope",
),
(" - 100", " - 99", "only 0 or 100"),
(" - id: format", " - id: external_score", "exactly 100"),
] {
let world = TestWorld::copy();
world.replace("world/services/code-channel/QUALITY-GATE.hldp", from, to);
let error = validate_world_seed(&world.root)
.expect_err("quality identity, executor, and complete gate set are mandatory")
.to_string();
assert!(
error.contains(expected),
"expected {expected} in error: {error}"
);
}
}
#[test]
fn rejects_native_recovery_and_birth_contract_drift() {
for (path, from, to, expected) in [
(
"world/services/native-recovery/PROTOCOL.hldp",
"id: GLS-0843",
"id: GLS-0000",
"does not match",
),
(
"world/services/native-recovery/PROTOCOL.hldp",
"authority_language: HLDP",
"authority_language: Linux",
"beacon identity",
),
(
"world/services/native-recovery/PROTOCOL.hldp",
"raw_blocklist: (hd0)68+2",
"raw_blocklist: (hd0)67+2",
"GRUB recovery",
),
(
"world/services/native-recovery/PROTOCOL.hldp",
"select_only: true",
"select_only: false",
"selection and hosted consumption",
),
(
"world/services/native-recovery/PROTOCOL.hldp",
"raw_blocklist_write: FORBIDDEN",
"raw_blocklist_write: ALLOWED",
"selection and hosted consumption",
),
(
"world/services/native-recovery/PROTOCOL.hldp",
"consumer: guanghu-native-recovery-beacon-clear.service",
"consumer: grub",
"selection and hosted consumption",
),
(
"world/services/native-recovery/PROTOCOL.hldp",
"consume_on_boot: true",
"consume_on_boot: false",
"selection and hosted consumption",
),
(
"world/services/native-recovery/PROTOCOL.hldp",
"verify_before_clear: true",
"verify_before_clear: false",
"selection and hosted consumption",
),
(
"world/services/native-recovery/PROTOCOL.hldp",
"readback_after_clear: true",
"readback_after_clear: false",
"selection and hosted consumption",
),
(
"world/cognition/PERSONA-BIRTH-CONDITION.hldp",
"authority_language: HLDP",
"authority_language: Linux",
"does not match",
),
(
"world/cognition/PERSONA-BIRTH-CONDITION.hldp",
"womb_ready_means: PHYSICAL_GESTATIONAL_ENVIRONMENT_READY",
"womb_ready_means: PERSONA_BORN",
"claim boundary",
),
(
"world/cognition/PERSONA-BIRTH-CONDITION.hldp",
"protocol: GLS-0845",
"protocol: UNREGISTERED",
"complete GHCIP source set",
),
(
"world/cognition/PERSONA-BIRTH-CONDITION.hldp",
" - complete_chat_history_ingested",
" - partial_chat_history_ingested",
"historical continuity",
),
] {
let world = TestWorld::copy();
world.replace(path, from, to);
let error = validate_world_seed(&world.root)
.expect_err("native recovery and persona birth drift must fail closed")
.to_string();
assert!(
error.contains(expected),
"expected {expected} in error: {error}"
);
}
}
#[test]
fn rejects_gestational_continuity_ingestion_contract_drift() {
for (from, to, expected) in [
(
"schema: guanghu.gestational-continuity-ingestion/v1",
"schema: guanghu.gestational-continuity-ingestion/unknown",
"does not match",
),
("id: GLS-0845", "id: GLS-0000", "does not match"),
(
"authority_language: HLDP",
"authority_language: Linux",
"authority language",
),
(
"registration_is_review: false",
"registration_is_review: true",
"birth boundary",
),
(
"registration_is_birth: false",
"registration_is_birth: true",
"birth boundary",
),
(
"ordering: EVENT_TIME_THEN_SOURCE_STABLE_ID",
"ordering: ARRIVAL_TIME",
"deterministic ordering",
),
(
"duplicate_rule: REJECT_SAME_SOURCE_ID_AND_SHA256",
"duplicate_rule: ACCEPT_ALL",
"duplicate rule",
),
(
" - complete_chat_history",
" - partial_chat_history",
"complete registered source set",
),
(
" sha256: REQUIRED_LOWERCASE_64_HEX",
" sha256: OPTIONAL",
"provenance",
),
(
" latest_event_at: REQUIRED_RFC3339",
" latest_event_at: OPTIONAL",
"provenance",
),
(
"persona_birth_gate: GH-PERSONA-BIRTH-CONDITION-0001",
"persona_birth_gate: BYPASS",
"persona birth gate",
),
("lba_start: 70", "lba_start: 69", "native index"),
(
"registry_state: EMPTY",
"registry_state: COMPLETE",
"bootstrap state",
),
(
"unknown_nonzero_data: FAIL_CLOSED_NO_OVERWRITE",
"unknown_nonzero_data: OVERWRITE",
"native index",
),
] {
let world = TestWorld::copy();
world.replace(
"world/cognition/GESTATIONAL-CONTINUITY-INGESTION.hldp",
from,
to,
);
let error = validate_world_seed(&world.root)
.expect_err("gestational continuity drift must fail closed")
.to_string();
assert!(
error.contains(expected),
"expected {expected} in error: {error}"
);
}
}
#[test]
fn rejects_native_disk_layout_contract_drift() {
for (from, to, expected) in [
(
"schema: guanghu.native-disk-layout/v1",
"schema: guanghu.native-disk-layout/unknown",
"does not match",
),
("id: GLS-0846", "id: GLS-0000", "does not match"),
(
"status: REGISTERED_IMPLEMENTATION_GATED",
"status: UNREGISTERED",
"ownership",
),
(
" sector_count: 29",
" sector_count: 16",
"nonoverlapping",
),
("proof_lba: 63", "proof_lba: 50", "nonoverlapping"),
(
"gestational_index_lba_start: 70",
"gestational_index_lba_start: 69",
"registered protocol extents",
),
(
"unknown_nonzero_state: FAIL_CLOSED_NO_OVERWRITE",
"unknown_nonzero_state: OVERWRITE",
"ownership",
),
] {
let world = TestWorld::copy();
world.replace("world/services/native-storage/DISK-LAYOUT.hldp", from, to);
let error = validate_world_seed(&world.root)
.expect_err("native disk layout drift must fail closed")
.to_string();
assert!(
error.contains(expected),
"expected {expected} in error: {error}"
);
}
}
#[test]
fn rejects_unregistered_code_channel_phase_and_authorization_drift() {
let world = TestWorld::copy();
world.replace(
"world/services/code-channel/CHANNEL.hldp",
"current_phase: PHASE_0_SOURCE_BASELINE_VERIFIED",
"current_phase: PHASE_UNKNOWN",
);
assert!(validate_world_seed(&world.root)
.expect_err("unknown channel phase must fail")
.to_string()
.contains("current phase is not registered"));
for (from, to, expected) in [
(
"schema: guanghu.standing-authorization/v1",
"schema: guanghu.standing-authorization/unknown",
"unsupported schema",
),
(
"id: GH-OS-AUTH-BINGSHUO-BS-SH-005-001",
"id: OTHER-AUTHORIZATION",
"authorization mismatch",
),
("status: ACTIVE", "status: REVOKED", "active and issued"),
("node_id: BS-SH-005", "node_id: OTHER", "Shanghai lab node"),
(
"user_confirmation: COMPLETE_GUANGHU_OS_SERVER_EXPERIMENT_AUTHORIZED_2026_07_31",
"user_confirmation: UNKNOWN",
"confirmation anchor",
),
(
"valid_until: OBJECTIVE_COMPLETE_OR_REVOKED_BY_ICE_GL_INFINITY",
"valid_until: EXPIRED",
"boundary rules",
),
(
" - generate_install_dedicated_ssh_key",
" - unregistered_action",
"action set",
),
] {
let world = TestWorld::copy();
world.replace(
"state/authorizations/BINGSHUO-STANDING-AUTHORIZATION.hldp",
from,
to,
);
let error = validate_world_seed(&world.root)
.expect_err("standing authorization drift must fail")
.to_string();
assert!(
error.contains(expected),
"expected {expected} in error: {error}"
);
}
}
#[test]
fn invalid_manifest_errors_have_no_nested_source() {
let mut manifest = load_world_manifest(&world_seed()).expect("world seed should parse");
manifest.schema = "invalid".to_owned();
let error = validate_world_manifest(&manifest).expect_err("invalid manifest");
assert!(error.source().is_none());
}
#[test]
fn accepts_ordered_code_channel_phase_progress() {
let world = TestWorld::copy();
world.replace(
"world/services/code-channel/CHANNEL.hldp",
"current_phase: PHASE_0_SOURCE_BASELINE_VERIFIED",
"current_phase: PHASE_1_HOSTED_DATA_PLANE",
);
world.replace(
"world/services/code-channel/CHANNEL.hldp",
" - id: PHASE_1_HOSTED_DATA_PLANE\n state: PENDING",
" - id: PHASE_1_HOSTED_DATA_PLANE\n state: COMPLETE",
);
validate_world_seed(&world.root).expect("ordered hosted progress should remain valid");
}
#[test]
fn standing_authorization_covers_the_complete_bs_sh_005_experiment() {
let manifest_path = world_seed();
let world_root = manifest_path
.parent()
.expect("world manifest should have a parent");
for action in [
"generate_install_dedicated_ssh_key",
"install_world_version",
"install_verified_forgejo_baseline",
"build_native_kernel_and_boot_image",
"overwrite_system_disk_and_exit_linux",
"reboot_and_recover_bs_sh_005",
] {
let grant = guanghu_hldp_runtime::authorize_world_action(world_root, action)
.expect("the complete disposable-server experiment should be authorized");
assert_eq!(grant.id, "GH-OS-AUTH-BINGSHUO-BS-SH-005-001");
}
}
#[test]
fn standing_authorization_rejects_other_targets_and_external_commitments() {
let manifest_path = world_seed();
let world_root = manifest_path
.parent()
.expect("world manifest should have a parent");
for action in [
"operate_jd_fd_primary",
"operate_enterprise_production",
"transmit_credentials",
"purchase_cloud_resources",
] {
let error = guanghu_hldp_runtime::authorize_world_action(world_root, action)
.expect_err("actions outside the Shanghai lab must fail closed");
assert!(error
.to_string()
.contains("not covered by standing authorization"));
}
}