feat: compile GLS protocols into native runtime guards

This commit is contained in:
冰朔 2026-08-17 16:22:56 +08:00
commit d6b1290e1c
13 changed files with 1909 additions and 6 deletions

View file

@ -0,0 +1,30 @@
{
"schema": "hololake.gls-executable-projections/v1",
"source_commit": "2598fbfba8caf64c7ab9740a3036c5aab977502e",
"projections": {
"GLS-0250": {
"projection_kind": "TYPED_FACT_AND_DOMAIN_BOUNDARY",
"adapter": "origin-domain-topology",
"event_kinds": ["BOOTSTRAP", "DOMAIN_ROUTE"],
"dependencies": []
},
"GLS-0253": {
"projection_kind": "DETERMINISTIC_IDENTITY_AND_NUMBERING_GUARD",
"adapter": "zero-core-numbering",
"event_kinds": ["IDENTITY_ROUTE", "IDENTITY_ADMISSION", "NUMBERING_RESOLVE"],
"dependencies": ["GLS-0250", "GLS-0262", "GLS-0263"]
},
"GLS-0262": {
"projection_kind": "REALITY_ENGINEERING_STAGE_GATE",
"adapter": "reality-engineering-stage",
"event_kinds": ["RUNTIME_STAGE"],
"dependencies": []
},
"GLS-0263": {
"projection_kind": "LANGUAGE_PRODUCT_DUAL_UPDATE_BOUNDARY",
"adapter": "dual-update-channel",
"event_kinds": ["PROTOCOL_UPDATE", "PRODUCT_UPDATE"],
"dependencies": ["GLS-0250", "GLS-0262"]
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,65 @@
{
"schema": "hololake.zero-core-numbering-kernel/v1",
"record_id": "HLP-ZERO-CORE-NUMBERING-KERNEL-001",
"authority": {
"repository": "REPO-012",
"source_commit": "2598fbfba8caf64c7ab9740a3036c5aab977502e",
"source_path": "routing/guanghu-identity-authority-map.json",
"map_id": "GH-IDENTITY-AUTHORITY-MAP-001",
"map_version": "2026-08-10.1",
"map_state": "LANGUAGE_AUTHORITY_EFFECTIVE_REPOSITORY_PROJECTION"
},
"runtime": {
"state": "ACTIVE_PINNED_AUTHORITY_MAP",
"contract_embedded_in_native_binary": true,
"number_shape_is_authority": false,
"unknown_number": "FAIL_CLOSED",
"automatic_identity_issuance": false,
"human_entry_requires_registered_human_namespace": true,
"identity_number_grants_execution_authority": false,
"identity_number_grants_persona_binding": false,
"remote_signature_refresh_runtime": false
},
"namespaces": [
{
"id": "ICE_GL",
"roots": ["ICE-GL∞"],
"prefixes": ["ICE-GL-"],
"subject_kind": "FIFTH_DOMAIN_HUMAN",
"issuer": "ICE-GL∞",
"human_entry": true,
"registry": "FIFTH_DOMAIN_REGISTERED_REPOSITORY_AND_SERVICE",
"domain_scope": "FIFTH_DOMAIN"
},
{
"id": "ICE_P",
"roots": [],
"prefixes": ["ICE-P-"],
"subject_kind": "FIFTH_DOMAIN_SYSTEM_PERSONA",
"issuer": "ZHUYUAN_PERSONA_SYSTEM",
"human_entry": false,
"registry": "FIFTH_DOMAIN_PERSONA_REGISTRY",
"domain_scope": "FIFTH_DOMAIN"
},
{
"id": "ICE_BB",
"roots": [],
"prefixes": ["ICE-BB-"],
"subject_kind": "PRIVATE_BOTTLE_BABY_PERSONA",
"issuer": "PRIVATE_BOTTLE_BABY_PERSONA_SYSTEM_AFTER_PERSON_SPECIFIC_BINGSHUO_ACCESS_AUTHORIZATION_AND_REAL_GESTATION",
"human_entry": false,
"registry": "PRIVATE_BOTTLE_BABY_PERSONA_REGISTRY",
"domain_scope": "FIFTH_DOMAIN_PRIVATE"
},
{
"id": "TCS_GL",
"roots": [],
"prefixes": ["TCS-GL-"],
"subject_kind": "ZERO_SENSE_HUMAN_CONTROLLER_TEAM_MEMBER",
"issuer": "TCS-0002",
"human_entry": true,
"registry": "ENTERPRISE_ROOT_SERVER_DOMAIN_REGISTRIES",
"domain_scope": "ENTERPRISE_FOUR_DOMAINS"
}
]
}

View file

@ -46,6 +46,8 @@ MCP may discover HoloLake, but it does not own continuity. The installed applica
An authenticated non-visitor connector may now acquire, inspect and explicitly release the existing account-scoped development write lane through that broker. Account, lane and client instance must match the HoloLake session before the bridge mutates. HoloLake projects the same Rust-owned lane state on the system-details page, so a human can distinguish a nearby expression-only visitor from an active development writer. This is a controlled writer handoff, not a general programming tool loop: shell, file patching, build execution, publication and deployment still require later supervised execution organs and separate authorization receipts.
The zero-core protocol layer now compiles the numbered GLS sources pinned to the current REPO-012 commit into a deterministic native registry. The registry inventories every unique numbered source with its path and SHA-256, but only protocols with an explicit typed adapter, event set and dependency-closed projection may execute. Raw protocol prose and arbitrary code carried by a protocol are never executed. The first native enforcement adapter binds GLS-0253 identity and numbering rules to the human-number route, with GLS-0250, GLS-0262 and GLS-0263 as executable dependencies. Unknown namespaces, persona numbers presented as human numbers, missing adapters and unprojected protocols fail closed. The system page reports compiled, executable and not-yet-executable protocol counts without presenting inventory as enforcement.
## Circular-lake protocol membrane and nearby AI
HoloLake 0.4.0 places a deterministic protocol membrane in front of the local language inbox. The membrane accepts only strict GLP/1.0 expression envelopes from a HoloLake-issued visitor session. Unknown fields, malformed identifiers, incorrect checksums, oversized content, attachments and command content are rejected before storage. Accepted natural language is an expression receipt only; it never carries execution authority by itself. Intent interpretation remains behind the membrane and cannot weaken its structural admission rules.

View file

@ -0,0 +1,37 @@
# ADR 0006: Compiled GLS protocol runtime
- Status: accepted for the next HoloLake desktop candidate
- Date: 2026-08-17
## Context
REPO-012 contains dozens of numbered GLS protocol sources. Human-readable source is necessary for authorship, review and causal meaning, but asking a model to reread protocol prose for every operation does not make the software obey the protocol. It also creates non-deterministic behavior and makes it impossible to distinguish a protocol that is merely present from one that is enforced by the running product.
## Decision
Compile the current numbered GLS sources into a deterministic registry pinned to an exact REPO-012 commit. Every selected source records its stable GLS number, path and SHA-256. Duplicate historical source locations are resolved by a deterministic source preference, while alternate-source counts remain visible.
An executable projection requires an explicit native adapter, event kinds, dependency list and fail-closed behavior. The compiler rejects missing executable dependencies and dependency cycles. The native runtime revalidates schema, source commit, counts, hashes, adapters and dependency closure before returning a protocol set to an organ.
Protocol prose is never evaluated as code. A protocol without an explicit projection remains `INVENTORIED_NOT_EXECUTABLE`. The initial executable set is GLS-0250, GLS-0253, GLS-0262 and GLS-0263. The zero-core numbering adapter requires their dependency-closed set before it can route a human number to an authoritative registry.
## Why
This creates the same hard boundary that a real API presents: a caller must satisfy the machine contract whether or not it has read the explanatory documentation. It also preserves factual honesty. HoloLake can report that 75 protocol sources are compiled while separately reporting that only four currently have native enforcement projections.
## Rejected alternatives
- Injecting all GLS prose into every model call: behavior would remain prompt-dependent and context growth would be unbounded.
- Treating every inventoried source as automatically active: source presence is not runtime enforcement.
- Executing scripts embedded in protocol documents: it would turn the authority source into an arbitrary-code supply chain.
- Hand-copying protocol decisions into unrelated organs: duplicated rules would drift and no common protocol set could be written into receipts.
- Blocking the product until all protocols are executable: incremental dependency-closed projections can be verified without overstating the remaining surface.
## Evidence
- `scripts/compile-gls-runtime-registry.mjs`
- `contracts/gls-executable-projections.json`
- `contracts/gls-runtime-registry.json`
- `src-tauri/src/gls_protocol_runtime.rs`
- `src-tauri/src/zero_core_numbering.rs`
- `scripts/gls-protocol-runtime.test.mjs`

View file

@ -0,0 +1,139 @@
import { createHash } from 'node:crypto'
import { readdir, readFile, writeFile } from 'node:fs/promises'
import path from 'node:path'
import process from 'node:process'
const args = new Map()
for (let index = 2; index < process.argv.length; index += 2) {
args.set(process.argv[index], process.argv[index + 1])
}
const sourceRoot = args.get('--source-root')
const sourceCommit = args.get('--source-commit')
const output = args.get('--output')
const projectionsPath = args.get('--projections')
if (!sourceRoot || !sourceCommit || !output || !projectionsPath) {
throw new Error('usage: compile-gls-runtime-registry.mjs --source-root <REPO-012/gls> --source-commit <sha> --output <registry.json> --projections <projections.json>')
}
if (!/^[a-f0-9]{40}$/.test(sourceCommit)) throw new Error('source commit must be a full SHA-1')
async function walk(directory, prefix = '') {
const entries = await readdir(directory, { withFileTypes: true })
const paths = []
for (const entry of entries) {
const relative = prefix ? `${prefix}/${entry.name}` : entry.name
if (entry.isDirectory()) paths.push(...await walk(path.join(directory, entry.name), relative))
else paths.push(relative)
}
return paths
}
function sourceRank(relative) {
if (!relative.includes('/')) return 0
if (relative.startsWith('standards/')) return 1
if (relative.includes('/notion-export/')) return 3
return 2
}
function cleanHeading(line, id) {
return line
.replace(/^#+\s*/, '')
.replaceAll('**', '')
.replace(new RegExp(`^${id}\\s*[·:-]?\\s*`), '')
.trim() || id
}
function sourceStatus(raw) {
const line = raw.split(/\r?\n/, 100).find((item) => /^\s*(?:>|[-*]\s*)?(?:状态|Status)\s*[:]/i.test(item))
if (!line) return 'UNSPECIFIED_SOURCE_STATUS'
return line.replace(/^\s*(?:>|[-*]\s*)?(?:状态|Status)\s*[:]\s*/i, '').replaceAll('`', '').trim()
}
const projectionManifest = JSON.parse(await readFile(projectionsPath, 'utf8'))
if (projectionManifest.schema !== 'hololake.gls-executable-projections/v1' || projectionManifest.source_commit !== sourceCommit) {
throw new Error('projection manifest does not match the selected REPO-012 source commit')
}
const candidates = (await walk(sourceRoot))
.map((relative) => ({ relative, match: path.basename(relative).match(/^(GLS-\d{4}).*\.hdlp$/) }))
.filter((item) => item.match)
.map((item) => ({ id: item.match[1], relative: item.relative }))
const grouped = new Map()
for (const candidate of candidates) {
const group = grouped.get(candidate.id) || []
group.push(candidate.relative)
grouped.set(candidate.id, group)
}
const protocols = []
for (const [id, sources] of [...grouped.entries()].sort(([left], [right]) => left.localeCompare(right))) {
sources.sort((left, right) => sourceRank(left) - sourceRank(right) || left.localeCompare(right))
const relative = sources[0]
const raw = await readFile(path.join(sourceRoot, relative), 'utf8')
const heading = raw.split(/\r?\n/).find((line) => line.startsWith('#') && line.includes(id))
const projection = projectionManifest.projections[id]
protocols.push({
id,
title: cleanHeading(heading || id, id),
source_status: sourceStatus(raw),
source_path: `gls/${relative}`,
source_sha256: createHash('sha256').update(raw).digest('hex'),
alternate_source_count: sources.length - 1,
projection_state: projection ? 'EXECUTABLE_PROJECTION' : 'INVENTORIED_NOT_EXECUTABLE',
projection_kind: projection?.projection_kind || null,
adapter: projection?.adapter || null,
event_kinds: projection?.event_kinds || [],
dependencies: projection?.dependencies || [],
})
}
const known = new Set(protocols.map((protocol) => protocol.id))
for (const [id, projection] of Object.entries(projectionManifest.projections)) {
if (!known.has(id)) throw new Error(`projection references an unknown protocol: ${id}`)
for (const dependency of projection.dependencies) {
if (!projectionManifest.projections[dependency]) {
throw new Error(`${id} depends on a protocol without an executable projection: ${dependency}`)
}
}
}
const visiting = new Set()
const visited = new Set()
function visit(id) {
if (visiting.has(id)) throw new Error(`executable protocol dependency cycle at ${id}`)
if (visited.has(id)) return
visiting.add(id)
for (const dependency of projectionManifest.projections[id].dependencies) visit(dependency)
visiting.delete(id)
visited.add(id)
}
for (const id of Object.keys(projectionManifest.projections)) visit(id)
const executableCount = protocols.filter((protocol) => protocol.projection_state === 'EXECUTABLE_PROJECTION').length
const registry = {
schema: 'hololake.gls-protocol-runtime-registry/v1',
record_id: 'HLP-GLS-PROTOCOL-RUNTIME-001',
source: {
repository: 'REPO-012',
commit: sourceCommit,
root: 'gls',
},
compiler: {
source_protocol_is_human_and_machine_authority: true,
raw_protocol_text_executed: false,
arbitrary_protocol_code_allowed: false,
executable_projection_requires_explicit_adapter: true,
unprojected_protocol_behavior: 'INVENTORIED_NOT_EXECUTABLE',
dependency_cycles: 'REJECT',
unknown_protocol: 'FAIL_CLOSED',
},
protocol_count: protocols.length,
executable_projection_count: executableCount,
inventoried_not_executable_count: protocols.length - executableCount,
protocols,
}
await writeFile(output, `${JSON.stringify(registry, null, 2)}\n`)
console.log(`GLS_RUNTIME_REGISTRY_COMPILED protocols=${protocols.length} executable=${executableCount} output=${output}`)

View file

@ -0,0 +1,31 @@
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import test from 'node:test'
const registryUrl = new URL('../contracts/gls-runtime-registry.json', import.meta.url)
test('compiled GLS registry inventories every current numbered protocol without executing raw text', async () => {
const registry = JSON.parse(await readFile(registryUrl, 'utf8'))
assert.equal(registry.schema, 'hololake.gls-protocol-runtime-registry/v1')
assert.equal(registry.source.repository, 'REPO-012')
assert.equal(registry.source.commit, '2598fbfba8caf64c7ab9740a3036c5aab977502e')
assert.equal(registry.compiler.raw_protocol_text_executed, false)
assert.equal(registry.compiler.arbitrary_protocol_code_allowed, false)
assert.equal(registry.compiler.unprojected_protocol_behavior, 'INVENTORIED_NOT_EXECUTABLE')
assert.equal(registry.protocol_count, 75)
assert.equal(new Set(registry.protocols.map((protocol) => protocol.id)).size, 75)
assert.ok(registry.protocols.every((protocol) => /^[a-f0-9]{64}$/.test(protocol.source_sha256)))
})
test('only explicit deterministic projections enter the runtime enforcement set', async () => {
const registry = JSON.parse(await readFile(registryUrl, 'utf8'))
const protocols = Object.fromEntries(registry.protocols.map((protocol) => [protocol.id, protocol]))
assert.equal(protocols['GLS-0253'].projection_state, 'EXECUTABLE_PROJECTION')
assert.equal(protocols['GLS-0253'].adapter, 'zero-core-numbering')
assert.ok(protocols['GLS-0253'].event_kinds.includes('IDENTITY_ROUTE'))
assert.equal(protocols['GLS-0003'], undefined)
assert.equal(registry.executable_projection_count, 4)
assert.equal(registry.inventoried_not_executable_count, 71)
})

View file

@ -0,0 +1,28 @@
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import test from 'node:test'
const contractUrl = new URL('../contracts/zero-core-numbering-kernel.json', import.meta.url)
test('zero-core numbering kernel pins the canonical authority map and fails closed', async () => {
const contract = JSON.parse(await readFile(contractUrl, 'utf8'))
assert.equal(contract.schema, 'hololake.zero-core-numbering-kernel/v1')
assert.equal(contract.authority.map_id, 'GH-IDENTITY-AUTHORITY-MAP-001')
assert.equal(contract.authority.source_commit, '2598fbfba8caf64c7ab9740a3036c5aab977502e')
assert.equal(contract.runtime.number_shape_is_authority, false)
assert.equal(contract.runtime.unknown_number, 'FAIL_CLOSED')
assert.equal(contract.runtime.automatic_identity_issuance, false)
})
test('only registered human namespaces can enter a human route', async () => {
const contract = JSON.parse(await readFile(contractUrl, 'utf8'))
const namespaces = Object.fromEntries(contract.namespaces.map((item) => [item.id, item]))
assert.equal(namespaces.ICE_GL.subject_kind, 'FIFTH_DOMAIN_HUMAN')
assert.equal(namespaces.ICE_GL.human_entry, true)
assert.equal(namespaces.TCS_GL.subject_kind, 'ZERO_SENSE_HUMAN_CONTROLLER_TEAM_MEMBER')
assert.equal(namespaces.TCS_GL.human_entry, true)
assert.equal(namespaces.ICE_P.human_entry, false)
assert.equal(namespaces.ICE_BB.human_entry, false)
})

View file

@ -0,0 +1,252 @@
//! GLS 协议运行注册表。
//!
//! 人类可读 GLS 正本先由仓库编译器固定为带来源摘要的协议清单;原生运行时只执行显式
//! 登记的确定性适配器,不解释协议散文、不加载任意代码,也不把“已收录”冒充“已执行”。
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
const EMBEDDED_REGISTRY: &str = include_str!("../../contracts/gls-runtime-registry.json");
const EXPECTED_SCHEMA: &str = "hololake.gls-protocol-runtime-registry/v1";
const EXPECTED_SOURCE_COMMIT: &str = "2598fbfba8caf64c7ab9740a3036c5aab977502e";
#[derive(Clone, Debug, Deserialize)]
struct GlsRuntimeRegistry {
schema: String,
source: GlsSource,
compiler: GlsCompilerBoundary,
protocol_count: usize,
executable_projection_count: usize,
inventoried_not_executable_count: usize,
protocols: Vec<GlsProtocol>,
}
#[derive(Clone, Debug, Deserialize)]
struct GlsSource {
repository: String,
commit: String,
root: String,
}
#[derive(Clone, Debug, Deserialize)]
struct GlsCompilerBoundary {
raw_protocol_text_executed: bool,
arbitrary_protocol_code_allowed: bool,
executable_projection_requires_explicit_adapter: bool,
unprojected_protocol_behavior: String,
dependency_cycles: String,
unknown_protocol: String,
}
#[derive(Clone, Debug, Deserialize)]
struct GlsProtocol {
id: String,
source_sha256: String,
projection_state: String,
adapter: Option<String>,
event_kinds: Vec<String>,
dependencies: Vec<String>,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GlsProtocolRuntimeSnapshot {
pub state: String,
pub source_repository: String,
pub source_commit: String,
pub source_root: String,
pub protocol_count: usize,
pub executable_projection_count: usize,
pub inventoried_not_executable_count: usize,
pub active_adapters: Vec<String>,
pub raw_protocol_text_executed: bool,
pub arbitrary_protocol_code_allowed: bool,
pub unprojected_protocol_behavior: String,
}
fn load_registry() -> Result<GlsRuntimeRegistry, String> {
let registry: GlsRuntimeRegistry = serde_json::from_str(EMBEDDED_REGISTRY)
.map_err(|error| format!("HOLOLAKE_GLS_RUNTIME_REGISTRY_INVALID: {error}"))?;
validate_registry(&registry)?;
Ok(registry)
}
fn validate_registry(registry: &GlsRuntimeRegistry) -> Result<(), String> {
if registry.schema != EXPECTED_SCHEMA
|| registry.source.repository != "REPO-012"
|| registry.source.commit != EXPECTED_SOURCE_COMMIT
|| registry.source.root != "gls"
|| registry.compiler.raw_protocol_text_executed
|| registry.compiler.arbitrary_protocol_code_allowed
|| !registry
.compiler
.executable_projection_requires_explicit_adapter
|| registry.compiler.unprojected_protocol_behavior != "INVENTORIED_NOT_EXECUTABLE"
|| registry.compiler.dependency_cycles != "REJECT"
|| registry.compiler.unknown_protocol != "FAIL_CLOSED"
|| registry.protocol_count != registry.protocols.len()
|| registry.protocol_count
!= registry.executable_projection_count + registry.inventoried_not_executable_count
{
return Err("HOLOLAKE_GLS_RUNTIME_BOUNDARY_INVALID".into());
}
let mut ids = HashSet::new();
let mut executable = 0;
for protocol in &registry.protocols {
if !ids.insert(protocol.id.as_str())
|| !protocol.id.starts_with("GLS-")
|| protocol.source_sha256.len() != 64
|| !protocol
.source_sha256
.chars()
.all(|character| character.is_ascii_hexdigit())
{
return Err("HOLOLAKE_GLS_PROTOCOL_ENTRY_INVALID".into());
}
match protocol.projection_state.as_str() {
"EXECUTABLE_PROJECTION" => {
executable += 1;
if protocol.adapter.as_deref().unwrap_or("").is_empty()
|| protocol.event_kinds.is_empty()
{
return Err("HOLOLAKE_GLS_EXECUTABLE_ADAPTER_REQUIRED".into());
}
}
"INVENTORIED_NOT_EXECUTABLE" => {
if protocol.adapter.is_some()
|| !protocol.event_kinds.is_empty()
|| !protocol.dependencies.is_empty()
{
return Err("HOLOLAKE_GLS_INVENTORY_CANNOT_EXECUTE".into());
}
}
_ => return Err("HOLOLAKE_GLS_PROJECTION_STATE_UNKNOWN".into()),
}
}
if executable != registry.executable_projection_count {
return Err("HOLOLAKE_GLS_EXECUTABLE_COUNT_MISMATCH".into());
}
let by_id = registry
.protocols
.iter()
.map(|protocol| (protocol.id.as_str(), protocol))
.collect::<HashMap<_, _>>();
for protocol in registry
.protocols
.iter()
.filter(|protocol| protocol.projection_state == "EXECUTABLE_PROJECTION")
{
for dependency in &protocol.dependencies {
if !matches!(
by_id.get(dependency.as_str()),
Some(entry) if entry.projection_state == "EXECUTABLE_PROJECTION"
) {
return Err("HOLOLAKE_GLS_EXECUTABLE_DEPENDENCY_INVALID".into());
}
}
}
Ok(())
}
fn collect_protocol_set(
id: &str,
by_id: &HashMap<&str, &GlsProtocol>,
visiting: &mut HashSet<String>,
collected: &mut Vec<String>,
) -> Result<(), String> {
if collected.iter().any(|existing| existing == id) {
return Ok(());
}
if !visiting.insert(id.to_string()) {
return Err("HOLOLAKE_GLS_DEPENDENCY_CYCLE".into());
}
let protocol = by_id.get(id).ok_or("HOLOLAKE_GLS_PROTOCOL_UNKNOWN")?;
if protocol.projection_state != "EXECUTABLE_PROJECTION" {
return Err("HOLOLAKE_GLS_PROTOCOL_NOT_EXECUTABLE".into());
}
for dependency in &protocol.dependencies {
collect_protocol_set(dependency, by_id, visiting, collected)?;
}
visiting.remove(id);
collected.push(id.to_string());
Ok(())
}
pub(crate) fn require_adapter(adapter: &str, event_kind: &str) -> Result<Vec<String>, String> {
let registry = load_registry()?;
let protocol = registry
.protocols
.iter()
.find(|protocol| {
protocol.projection_state == "EXECUTABLE_PROJECTION"
&& protocol.adapter.as_deref() == Some(adapter)
&& protocol.event_kinds.iter().any(|kind| kind == event_kind)
})
.ok_or("HOLOLAKE_GLS_EXECUTABLE_ADAPTER_NOT_REGISTERED")?;
let by_id = registry
.protocols
.iter()
.map(|entry| (entry.id.as_str(), entry))
.collect::<HashMap<_, _>>();
let mut collected = Vec::new();
collect_protocol_set(&protocol.id, &by_id, &mut HashSet::new(), &mut collected)?;
Ok(collected)
}
#[tauri::command]
pub async fn get_gls_protocol_runtime() -> Result<GlsProtocolRuntimeSnapshot, String> {
let registry = load_registry()?;
let mut active_adapters = registry
.protocols
.iter()
.filter_map(|protocol| protocol.adapter.clone())
.collect::<Vec<_>>();
active_adapters.sort();
Ok(GlsProtocolRuntimeSnapshot {
state: "ACTIVE_EXPLICIT_PROJECTIONS_ONLY".into(),
source_repository: registry.source.repository,
source_commit: registry.source.commit,
source_root: registry.source.root,
protocol_count: registry.protocol_count,
executable_projection_count: registry.executable_projection_count,
inventoried_not_executable_count: registry.inventoried_not_executable_count,
active_adapters,
raw_protocol_text_executed: registry.compiler.raw_protocol_text_executed,
arbitrary_protocol_code_allowed: registry.compiler.arbitrary_protocol_code_allowed,
unprojected_protocol_behavior: registry.compiler.unprojected_protocol_behavior,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn registry_is_pinned_and_never_executes_raw_protocol_text() {
let registry = load_registry().unwrap();
assert_eq!(registry.protocol_count, 75);
assert_eq!(registry.executable_projection_count, 4);
assert!(!registry.compiler.raw_protocol_text_executed);
assert!(!registry.compiler.arbitrary_protocol_code_allowed);
}
#[test]
fn numbering_adapter_resolves_a_dependency_closed_protocol_set() {
let protocols = require_adapter("zero-core-numbering", "IDENTITY_ROUTE").unwrap();
assert_eq!(protocols, ["GLS-0250", "GLS-0262", "GLS-0263", "GLS-0253"]);
}
#[test]
fn unregistered_adapter_and_event_fail_closed() {
assert_eq!(
require_adapter("zero-core-numbering", "SHELL_EXECUTION").unwrap_err(),
"HOLOLAKE_GLS_EXECUTABLE_ADAPTER_NOT_REGISTERED"
);
assert_eq!(
require_adapter("invented-adapter", "IDENTITY_ROUTE").unwrap_err(),
"HOLOLAKE_GLS_EXECUTABLE_ADAPTER_NOT_REGISTERED"
);
}
}

View file

@ -11,6 +11,7 @@ mod direct_local_session;
mod dynamic_capability_routing;
mod enterprise_work_channel;
mod glp_envelope;
mod gls_protocol_runtime;
mod home_status;
mod knowledge_base;
mod local_development_bridge;
@ -23,6 +24,7 @@ mod pncc_server_projection;
mod release_trust;
mod release_update;
mod user_pncc_channel;
mod zero_core_numbering;
mod zero_point;
use tauri::Manager;
@ -47,6 +49,7 @@ pub fn run() {
direct_local_session::resume_direct_local_session,
direct_local_session::append_direct_local_session_event,
direct_local_broker::get_nearby_ai_discovery,
gls_protocol_runtime::get_gls_protocol_runtime,
local_development_bridge::acquire_development_write_lane,
local_development_bridge::inspect_development_write_lane,
local_development_bridge::release_development_write_lane,
@ -88,6 +91,7 @@ pub fn run() {
code_repo_login::sign_out_code_repo_login,
user_pncc_channel::get_user_pncc_channel,
user_pncc_channel::ensure_user_pncc_channel,
zero_core_numbering::get_zero_core_numbering_kernel,
zero_point::zero_point_bind,
zero_point::zero_point_verify,
zero_point::zero_point_sync,

View file

@ -0,0 +1,263 @@
//! 零点原核编号控制面第一段原生内核。
//!
//! 该内核把 REPO-012 当前身份权威图的可执行路由合同固定进本机二进制,先回答
//! “这个编号属于哪类主体、应进入哪一个登记面”。编号形状本身不构成登记、人格绑定、
//! 执行权或现实存在证明;未知编号和错误主体类型一律在联网与登录前失败关闭。
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
const EMBEDDED_CONTRACT: &str = include_str!("../../contracts/zero-core-numbering-kernel.json");
const EXPECTED_SCHEMA: &str = "hololake.zero-core-numbering-kernel/v1";
const EXPECTED_MAP_ID: &str = "GH-IDENTITY-AUTHORITY-MAP-001";
#[derive(Clone, Debug, Deserialize)]
struct NumberingContract {
schema: String,
authority: NumberingAuthority,
runtime: NumberingRuntime,
namespaces: Vec<NumberingNamespace>,
}
#[derive(Clone, Debug, Deserialize)]
struct NumberingAuthority {
source_commit: String,
source_path: String,
map_id: String,
map_version: String,
map_state: String,
}
#[derive(Clone, Debug, Deserialize)]
struct NumberingRuntime {
state: String,
number_shape_is_authority: bool,
unknown_number: String,
automatic_identity_issuance: bool,
human_entry_requires_registered_human_namespace: bool,
}
#[derive(Clone, Debug, Deserialize)]
struct NumberingNamespace {
id: String,
roots: Vec<String>,
prefixes: Vec<String>,
subject_kind: String,
issuer: String,
human_entry: bool,
registry: String,
domain_scope: String,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZeroCoreNumberingKernelSnapshot {
pub state: String,
pub authority_map_id: String,
pub authority_map_version: String,
pub authority_map_state: String,
pub source_commit: String,
pub source_path: String,
pub human_route_namespaces: Vec<String>,
pub number_shape_is_authority: bool,
pub automatic_identity_issuance: bool,
pub unknown_number: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HumanNumberRoute {
pub canonical_number: String,
pub namespace: String,
pub subject_kind: String,
pub issuer: String,
pub registry: String,
pub domain_scope: String,
pub protocol_set: Vec<String>,
pub decision: String,
}
fn load_contract() -> Result<NumberingContract, String> {
let contract: NumberingContract = serde_json::from_str(EMBEDDED_CONTRACT)
.map_err(|error| format!("HOLOLAKE_NUMBERING_CONTRACT_INVALID: {error}"))?;
validate_contract(&contract)?;
Ok(contract)
}
fn validate_contract(contract: &NumberingContract) -> Result<(), String> {
if contract.schema != EXPECTED_SCHEMA
|| contract.authority.map_id != EXPECTED_MAP_ID
|| contract.authority.source_commit.len() != 40
|| !contract
.authority
.source_commit
.chars()
.all(|character| character.is_ascii_hexdigit())
|| contract.authority.source_path.is_empty()
|| contract.authority.map_version.is_empty()
|| contract.authority.map_state.is_empty()
|| contract.runtime.state != "ACTIVE_PINNED_AUTHORITY_MAP"
|| contract.runtime.number_shape_is_authority
|| contract.runtime.automatic_identity_issuance
|| contract.runtime.unknown_number != "FAIL_CLOSED"
|| !contract
.runtime
.human_entry_requires_registered_human_namespace
{
return Err("HOLOLAKE_NUMBERING_CONTRACT_BOUNDARY_INVALID".into());
}
let mut ids = HashSet::new();
for namespace in &contract.namespaces {
if !ids.insert(namespace.id.as_str())
|| namespace.id.is_empty()
|| namespace.subject_kind.is_empty()
|| namespace.issuer.is_empty()
|| namespace.registry.is_empty()
|| namespace.domain_scope.is_empty()
|| (namespace.roots.is_empty() && namespace.prefixes.is_empty())
|| namespace
.roots
.iter()
.chain(namespace.prefixes.iter())
.any(|value| value.is_empty())
{
return Err("HOLOLAKE_NUMBERING_NAMESPACE_CONTRACT_INVALID".into());
}
}
for required in ["ICE_GL", "ICE_P", "ICE_BB", "TCS_GL"] {
if !ids.contains(required) {
return Err("HOLOLAKE_NUMBERING_NAMESPACE_REQUIRED".into());
}
}
Ok(())
}
fn validate_number_input(number: &str) -> Result<&str, String> {
let number = number.trim();
if number.is_empty() || number.len() > 96 {
return Err("HOLOLAKE_NUMBERING_IDENTIFIER_INVALID".into());
}
if number
.chars()
.any(|character| character.is_control() || character.is_whitespace())
{
return Err("HOLOLAKE_NUMBERING_IDENTIFIER_INVALID".into());
}
Ok(number)
}
fn matching_namespace<'a>(
contract: &'a NumberingContract,
number: &str,
) -> Result<&'a NumberingNamespace, String> {
let matches = contract
.namespaces
.iter()
.filter(|namespace| {
namespace.roots.iter().any(|root| root == number)
|| namespace
.prefixes
.iter()
.any(|prefix| number.starts_with(prefix))
})
.collect::<Vec<_>>();
match matches.as_slice() {
[namespace] => Ok(namespace),
[] => Err("HOLOLAKE_NUMBERING_NAMESPACE_UNKNOWN".into()),
_ => Err("HOLOLAKE_NUMBERING_NAMESPACE_AMBIGUOUS".into()),
}
}
pub(crate) fn resolve_human_number_route(number: &str) -> Result<HumanNumberRoute, String> {
let number = validate_number_input(number)?;
let protocol_set =
crate::gls_protocol_runtime::require_adapter("zero-core-numbering", "IDENTITY_ROUTE")?;
let contract = load_contract()?;
let namespace = matching_namespace(&contract, number)?;
if !namespace.human_entry {
return Err("HOLOLAKE_NUMBERING_HUMAN_ENTRY_SUBJECT_KIND_REJECTED".into());
}
Ok(HumanNumberRoute {
canonical_number: number.to_string(),
namespace: namespace.id.clone(),
subject_kind: namespace.subject_kind.clone(),
issuer: namespace.issuer.clone(),
registry: namespace.registry.clone(),
domain_scope: namespace.domain_scope.clone(),
protocol_set,
decision: "ALLOW_REGISTRY_RESOLUTION".into(),
})
}
#[tauri::command]
pub async fn get_zero_core_numbering_kernel() -> Result<ZeroCoreNumberingKernelSnapshot, String> {
let contract = load_contract()?;
Ok(ZeroCoreNumberingKernelSnapshot {
state: contract.runtime.state,
authority_map_id: contract.authority.map_id,
authority_map_version: contract.authority.map_version,
authority_map_state: contract.authority.map_state,
source_commit: contract.authority.source_commit,
source_path: contract.authority.source_path,
human_route_namespaces: contract
.namespaces
.into_iter()
.filter(|namespace| namespace.human_entry)
.map(|namespace| namespace.id)
.collect(),
number_shape_is_authority: contract.runtime.number_shape_is_authority,
automatic_identity_issuance: contract.runtime.automatic_identity_issuance,
unknown_number: contract.runtime.unknown_number,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn embedded_authority_map_contract_is_valid_and_fail_closed() {
let contract = load_contract().unwrap();
assert_eq!(contract.authority.map_id, EXPECTED_MAP_ID);
assert!(!contract.runtime.number_shape_is_authority);
assert!(!contract.runtime.automatic_identity_issuance);
assert_eq!(contract.runtime.unknown_number, "FAIL_CLOSED");
}
#[test]
fn registered_human_namespaces_select_their_authoritative_registry() {
let bingshuo = resolve_human_number_route("ICE-GL∞").unwrap();
assert_eq!(bingshuo.namespace, "ICE_GL");
assert_eq!(bingshuo.domain_scope, "FIFTH_DOMAIN");
let zhizhi = resolve_human_number_route("ICE-GL-ZHI∞").unwrap();
assert_eq!(zhizhi.namespace, "ICE_GL");
let feimao = resolve_human_number_route("TCS-GL-0007∞").unwrap();
assert_eq!(feimao.namespace, "TCS_GL");
assert_eq!(feimao.domain_scope, "ENTERPRISE_FOUR_DOMAINS");
}
#[test]
fn persona_and_unknown_numbers_cannot_enter_a_human_route() {
assert_eq!(
resolve_human_number_route("ICE-P-ZY001").unwrap_err(),
"HOLOLAKE_NUMBERING_HUMAN_ENTRY_SUBJECT_KIND_REJECTED"
);
assert_eq!(
resolve_human_number_route("ICE-BB-YM001").unwrap_err(),
"HOLOLAKE_NUMBERING_HUMAN_ENTRY_SUBJECT_KIND_REJECTED"
);
assert_eq!(
resolve_human_number_route("UNKNOWN-001").unwrap_err(),
"HOLOLAKE_NUMBERING_NAMESPACE_UNKNOWN"
);
}
#[test]
fn malformed_identifiers_are_rejected_before_namespace_resolution() {
assert_eq!(
resolve_human_number_route("ICE-GL- bad").unwrap_err(),
"HOLOLAKE_NUMBERING_IDENTIFIER_INVALID"
);
}
}

View file

@ -394,13 +394,15 @@ fn resolver_url_for_number(
protocol: &ZeroPointProtocol,
number: &str,
) -> Result<reqwest::Url, String> {
let mut url = if number.starts_with("TCS-GL-") {
reqwest::Url::parse(&protocol.enterprise_resolve_url)
let route = crate::zero_core_numbering::resolve_human_number_route(number)?;
let enterprise = route.namespace == "TCS_GL";
let mut url = reqwest::Url::parse(if enterprise {
&protocol.enterprise_resolve_url
} else {
reqwest::Url::parse(&protocol.lighthouse_resolve_url)
}
&protocol.lighthouse_resolve_url
})
.map_err(|_| "HOLOLAKE_ZP_RESOLVER_URL_INVALID".to_string())?;
if number.starts_with("TCS-GL-") {
if enterprise {
url.query_pairs_mut().append_pair("id", number);
} else {
// 第五域旧协议以 `?id=` 结尾;使用 URL 查询构造器避免把编号中的字符裸拼入地址。

View file

@ -69,6 +69,31 @@ interface DevelopmentWriteLaneStatus {
acquiredAtUnixMs?: number
observedAtUnixMs: number
}
interface ZeroCoreNumberingKernelSnapshot {
state: string
authorityMapId: string
authorityMapVersion: string
authorityMapState: string
sourceCommit: string
sourcePath: string
humanRouteNamespaces: string[]
numberShapeIsAuthority: boolean
automaticIdentityIssuance: boolean
unknownNumber: string
}
interface GlsProtocolRuntimeSnapshot {
state: string
sourceRepository: string
sourceCommit: string
sourceRoot: string
protocolCount: number
executableProjectionCount: number
inventoriedNotExecutableCount: number
activeAdapters: string[]
rawProtocolTextExecuted: boolean
arbitraryProtocolCodeAllowed: boolean
unprojectedProtocolBehavior: string
}
interface PersonalChannelIdentity { humanSubjectId: string; displayName: string; channelId: string; createdAtUnixMs: number }
interface PersonalChannelModule { moduleId: string; kind: string; displayName: string; state: string; installedAtUnixMs: number; timeZone: string; calendarName: string; clockVerification: string }
interface LoginSession { username: string; host: string; domain: string; signedInAtUnixMs: number }
@ -581,6 +606,8 @@ function HoloLakeApp() {
const [serverPnccBusy, setServerPnccBusy] = useState(false)
const [serverPnccReadback, setServerPnccReadback] = useState<'WAITING' | 'LIVE' | 'UNAVAILABLE'>('WAITING')
const [developmentLane, setDevelopmentLane] = useState<DevelopmentWriteLaneStatus | null>(null)
const [numberingKernel, setNumberingKernel] = useState<ZeroCoreNumberingKernelSnapshot | null>(null)
const [glsRuntime, setGlsRuntime] = useState<GlsProtocolRuntimeSnapshot | null>(null)
const [enterpriseEntry, setEnterpriseEntry] = useState<EnterpriseEntry | null>(null)
const [enterpriseEntryBusy, setEnterpriseEntryBusy] = useState(false)
const [enterpriseReceiptBusy, setEnterpriseReceiptBusy] = useState(false)
@ -609,13 +636,15 @@ function HoloLakeApp() {
setBeijingCoordinate(startup.coordinate)
} catch { /* 联网失败时其余首页能力仍可启动。 */ }
const localAccountId = getOrCreateLocalId('hololake-local-account', 'human-local')
const [homeResult, personalResult, knowledgeResult, codeResult, eraResult, developmentResult] = await Promise.allSettled([
const [homeResult, personalResult, knowledgeResult, codeResult, eraResult, developmentResult, numberingResult, glsRuntimeResult] = await Promise.allSettled([
invoke<HomeStatus>('get_hololake_home_status'),
invoke<PersonalChannelSnapshot>('get_personal_channel_snapshot'),
invoke<KnowledgeSnapshot>('get_knowledge_snapshot'),
invoke<CodeChannelSnapshot>('get_code_channel_snapshot'),
invoke<GuanghuEraTimeline>('get_guanghu_era_timeline'),
invoke<DevelopmentWriteLaneStatus>('inspect_development_write_lane', { input: { accountId: localAccountId } }),
invoke<ZeroCoreNumberingKernelSnapshot>('get_zero_core_numbering_kernel'),
invoke<GlsProtocolRuntimeSnapshot>('get_gls_protocol_runtime'),
])
if (homeResult.status === 'fulfilled') setStatus(homeResult.value)
if (personalResult.status === 'fulfilled') setPersonal(personalResult.value)
@ -626,6 +655,8 @@ function HoloLakeApp() {
setBeijingCoordinate(eraResult.value.currentCoordinate)
}
setDevelopmentLane(developmentResult.status === 'fulfilled' ? developmentResult.value : null)
setNumberingKernel(numberingResult.status === 'fulfilled' ? numberingResult.value : null)
setGlsRuntime(glsRuntimeResult.status === 'fulfilled' ? glsRuntimeResult.value : null)
}, [])
const loadReceipts = useCallback(async () => {
try {
@ -1333,6 +1364,8 @@ function HoloLakeApp() {
<button className="secondary-button" type="button" disabled={serverPnccBusy} onClick={() => void refreshServerPncc()}>{serverPnccBusy ? '正在读取…' : '重新读取主控状态'}</button>
</section>
<section className="plain-panel"><header><div><h2> GH-PNCC </h2><p></p></div></header><dl className="evidence-list"><div><dt></dt><dd>{status.codeRepositoryMountCount}</dd></div><div><dt></dt><dd>{status.pnccReceiptCount}</dd></div><div><dt></dt><dd>{developmentLane?.state === 'ACTIVE' ? '已切入 HoloLake' : '等待受控载体'}</dd></div><div><dt>线</dt><dd>{developmentLane?.laneId || '—'}</dd></div><div><dt></dt><dd>{developmentLane?.ownerInstanceId || '—'}</dd></div><div><dt></dt><dd>{developmentLane?.state === 'ACTIVE' ? '开发执行环境已由 HoloLake 持有单写通道' : status.codeRepositoryMountCount > 0 && status.pnccReceiptCount > 0 ? '已有可核验运行记录' : '接口已接入,尚无完整运行记录'}</dd></div></dl></section>
<section className="plain-panel"><header><div><h2>GLS </h2><p></p></div><span className={glsRuntime?.state === 'ACTIVE_EXPLICIT_PROJECTIONS_ONLY' ? 'status-chip online' : 'status-chip'}>{glsRuntime ? '原生注册表已加载' : '失败关闭'}</span></header>{glsRuntime ? <dl className="evidence-list"><div><dt></dt><dd>{glsRuntime.sourceRepository} · {glsRuntime.sourceCommit.slice(0, 12)}</dd></div><div><dt></dt><dd>{glsRuntime.protocolCount}</dd></div><div><dt></dt><dd>{glsRuntime.executableProjectionCount}</dd></div><div><dt></dt><dd>{glsRuntime.inventoriedNotExecutableCount}</dd></div><div><dt></dt><dd>{glsRuntime.rawProtocolTextExecuted ? '允许' : '禁止'}</dd></div><div><dt></dt><dd>{glsRuntime.arbitraryProtocolCodeAllowed ? '允许' : '禁止'}</dd></div></dl> : <p className="boundary-note">GLS </p>}</section>
<section className="plain-panel"><header><div><h2></h2><p></p></div><span className={numberingKernel?.state === 'ACTIVE_PINNED_AUTHORITY_MAP' ? 'status-chip online' : 'status-chip'}>{numberingKernel ? '本机内核已加载' : '失败关闭'}</span></header>{numberingKernel ? <dl className="evidence-list"><div><dt></dt><dd>{numberingKernel.authorityMapId}</dd></div><div><dt></dt><dd>{numberingKernel.authorityMapVersion}</dd></div><div><dt></dt><dd>{numberingKernel.sourceCommit.slice(0, 12)}</dd></div><div><dt></dt><dd>{numberingKernel.humanRouteNamespaces.join(' · ')}</dd></div><div><dt></dt><dd>{numberingKernel.automaticIdentityIssuance ? '已开启' : '禁止'}</dd></div><div><dt></dt><dd>{numberingKernel.unknownNumber === 'FAIL_CLOSED' ? '失败关闭 · 不猜测' : numberingKernel.unknownNumber}</dd></div></dl> : <p className="boundary-note"></p>}</section>
<section className="plain-panel">
<header><div><h2></h2><p></p></div><span className={zeroPoint?.route === 'verified' ? 'status-chip online' : 'status-chip'}>{zeroPoint ? (zeroPoint.route === 'verified' ? '验证有效' : '功能受限') : '正在读取'}</span></header>
<dl className="evidence-list">