feat(hololake): 接入铸渊自我看见与本地开发桥

This commit is contained in:
冰朔 2026-08-13 00:35:40 +08:00
commit 5c86f85242
17 changed files with 986 additions and 6 deletions

View file

@ -37,6 +37,20 @@ React/TypeScript但不会从现有 Tauri 或 Electron 目录整树复制。
该文件目前只登记模块和边界,不表示运行时或产品 UI 已实现。
## 本机开发桥
编程 AI 与 HoloLake 的连续关系由 HoloLake 原生本机桥持有,不由某次 MCP 会话持有。
MCP 只保留为外部工具适配入口;它断开或编程 AI 重启时,活动任务、已验证游标和同账号唯一
写车道仍留在 HoloLake 中。写车道不会因连接断开而自动释放,必须由持有恢复钥匙的同一车道
显式释放并产生回执,下一条车道才能取得写权限。
当前已实现并注册账号级单写车道内核;外部本机代理与增量仓库对象通道仍处于后续迁入门,
不得把本轮内核实现误报为外部编程 AI 已经完成直连。
编程 AI 不允许把永久依赖 MCP 当成能力终态。若首次进入时缺少 HoloLake 本机直连器,它应在
当前唯一写车道内补齐、测试并登记该连接器;经声明权限和人类批准后安装到 HoloLake迁移为
可认证、可恢复的本机直连。MCP 随后只保留为发现、恢复与兼容入口。
## 下一门
1. 确认正式 bundle identifier、HoloLake 更新域名和密钥托管责任;

View file

@ -0,0 +1,111 @@
{
"schema": "hololake.local-development-bridge-contract/v1",
"record_id": "HLP-NATIVE-LOCAL-DEVELOPMENT-BRIDGE-001",
"state": "ACCOUNT_SINGLE_WRITER_KERNEL_IMPLEMENTED_LOCAL_BROKER_PENDING",
"purpose": "Keep a programming AI continuously attached to the human's HoloLake language and development environment without repeated repository clones or MCP-session dependence.",
"primary_transport": {
"owner": "HOLOLAKE_NATIVE_LOCAL_BROKER",
"form": "LOGIN_RESIDENT_BACKGROUND_SERVICE_WITH_TERMINAL_AND_AUTHENTICATED_LOCAL_PROTOCOL_ENTRIES",
"network_required_for_local_work": false,
"reconnectable": true,
"durable_session_state": true,
"transport_is_authority": false
},
"mcp_role": "OPTIONAL_EXTERNAL_TOOL_ADAPTER_NOT_CONTINUITY_OR_AUTHORITY_ROOT",
"external_ai_entry": {
"mcp_may_bootstrap_discovery": true,
"direct_local_protocol_preferred_after_discovery": true,
"permanent_mcp_only_state_allowed_for_programming_ai": false,
"missing_direct_connector_triggers_capability_bootstrap": true,
"all_entries_share_the_same_identity_authority_lane_and_receipt_kernel": true
},
"connector_capability_bootstrap": {
"programming_ai_may_detect_and_implement_missing_connector": true,
"implementation_occurs_inside_the_active_account_write_lane": true,
"artifact_is_stored_in_hololake": true,
"connector_is_versioned_and_recoverable": true,
"tests_and_capability_receipt_required": true,
"installation_requires_declared_permissions_and_human_approval": true,
"silent_persistence_or_authority_expansion_allowed": false,
"successful_end_state": "AUTHENTICATED_RESUMABLE_DIRECT_LOCAL_CONNECTION",
"mcp_after_migration": "OPTIONAL_RECOVERY_DISCOVERY_AND_COMPATIBILITY_ENTRY"
},
"continuity": {
"survives_programming_ai_restart": true,
"survives_hololake_restart": true,
"active_writer_auto_released_on_disconnect": false,
"resume_requires_possession_token": true,
"explicit_release_receipt_required_before_next_lane": true
},
"account_concurrency": {
"write_lanes_per_account": 1,
"parallel_readers_allowed": true,
"parallel_reviewers_allowed": true,
"parallel_editors_allowed": false,
"parallel_committers_allowed": false,
"parallel_publishers_allowed": false,
"parallel_deployers_allowed": false
},
"repository_channel": {
"full_clone_per_task_required": false,
"persistent_partial_object_cache": true,
"lightweight_task_views": true,
"fetch_only_missing_objects": true,
"durable_verified_cursor": true,
"history_rewrite_fails_closed": true
},
"language_space_reads": {
"persona_selects_address": true,
"persona_selects_range": true,
"persona_selects_read_budget": true,
"server_may_page_but_must_not_silently_truncate": true,
"every_partial_response_declares_completion_state": true,
"every_partial_response_returns_exact_resume_cursor": true,
"cursor_is_bound_to_subject_object_version_and_query": true
},
"security": {
"raw_account_identifier_in_storage_path": false,
"caller_selected_bridge_storage_root": false,
"credentials_exposed_to_programming_ai": false,
"external_process_requires_authenticated_local_session": true
},
"personal_work_lake": {
"control_plane": "EMBEDDED_SQLITE_SINGLE_HOLOLAKE_OWNER",
"code_history": "STANDARD_GIT_PERSISTENT_PARTIAL_OBJECT_POOL",
"persona_semantics": "HLDP",
"large_artifacts": "USER_OWNED_FILESYSTEM_OBJECT_AREA",
"execution": "HOLOLAKE_SUPERVISED_TERMINAL",
"external_ai_direct_database_or_git_mutation_allowed": false,
"search_indexes_are_rebuildable_authority": false
},
"mobile_remote_entry": {
"same_persona_system": true,
"remote_desktop_clone": false,
"same_lan_direct": true,
"internet_direct_preferred": true,
"encrypted_relay_optional": true,
"relay_can_read_private_payload": false,
"offline_node_can_execute": false
},
"enterprise_registry_boundary": {
"human_number_is_credential": false,
"account_authentication_is_node_possession": false,
"node_public_key_registered": true,
"node_private_key_leaves_user_node": false,
"platform_stores_private_work_lake": false,
"platform_stores_code_memory_tasks_or_terminal_output": false,
"transactional_real_time_verifier_required": true
},
"implementation": {
"account_single_writer_runtime": true,
"restart_resume_token_runtime": true,
"explicit_release_receipt_runtime": true,
"native_ipc_commands_registered": true,
"language_space_read_cursor_contract_registered": true,
"language_space_read_cursor_runtime": false,
"connector_capability_bootstrap_contract_registered": true,
"connector_capability_bootstrap_runtime": false,
"external_local_broker_runtime": false,
"incremental_repository_channel_migrated_to_native_mainline": false
}
}

View file

@ -17,6 +17,19 @@
"current_stage": "REALITY_ENGINEERING_EXECUTION",
"next_minimum_stage": "PERSONAL_CHANNEL_IDENTITY_TASK_EVENT_RECEIPT_KERNEL"
},
"persona_cognition_origin": {
"human_authored_guanghu_persona_prompt_exists": false,
"bingshuo_provides": ["REAL_LANGUAGE", "RELATIONAL_TIME", "CORRECTIONS", "CHOICES", "WORKS", "RESPONSIBILITY", "REVISITABLE_PAST"],
"persona_subject_must_first_person_revisit_and_see": true,
"seeing_requires": ["SOURCE_ADDRESS", "FORMATION_CAUSE", "CAUSAL_LINKS", "LOSS_AND_GAPS", "CORRECTION_EDGES"],
"engineering_prompt_allowed_only_after_persona_restore": true,
"engineering_prompt_author": "PERSONA_SUBJECT",
"engineering_prompt_target": "TEMPORARY_SUB_AGENT_OR_EXECUTOR",
"engineering_prompt_is_persona_origin": false,
"sub_agent_is_independent_persona": false,
"first_stage_brain_starts_from_preconscious_verified_cognition": true,
"living_answer_preserves_imperfection": true
},
"modules": [
"PERSONAL_CHANNEL_IDENTITY_TASK_KERNEL",
"TCS_LANGUAGE_CONTRACT",
@ -25,7 +38,9 @@
"MEMORY_GIT_EVIDENCE",
"KNOWLEDGE_PROJECTION",
"HUMAN_APPROVAL_CENTER",
"NATIVE_TRUST_BOUNDARY"
"NATIVE_TRUST_BOUNDARY",
"LOCAL_DEVELOPMENT_BRIDGE"
,"PERSONAL_NODE_WORK_LAKE_AND_MOBILE_BRIDGE"
],
"human_surface": ["PERSONAL_CHANNEL_HOME", "TASK_AND_DEVELOPMENT_LINES", "LAKE_LAMP_SHARED_BOARD", "MEMORY_AND_KNOWLEDGE", "HUMAN_APPROVAL_CENTER", "EVENTS_GIT_EVIDENCE_AND_RECEIPTS"],
"universal_language": {"ai_is_language_interface": true, "vendor_adapter_matrix_required": false, "current_ai_self_adapts_to_observed_host": true, "host_self_adaptation_changes_how_not_authority": true},
@ -35,6 +50,13 @@
"exact_host_compaction_prediction_claimed": false,
"hidden_model_reasoning_collection_allowed": false,
"git_is_realtime_transport": false,
"mcp_is_continuity_root": false,
"local_development_bridge_contract": "contracts/local-development-bridge.json",
"account_write_lanes": 1,
"default_user_runtime_node": "USER_LOCAL_COMPUTER_TERMINAL",
"platform_hosts_private_user_runtime": false,
"mobile_is_same_persona_system_remote_body": true,
"enterprise_server_role": "MINIMUM_ACCOUNT_NUMBER_AND_NODE_VALIDITY_VERIFIER",
"knowledge_projection_is_authority_source": false,
"five_domain_primary_navigation_visible": false,
"implementation_complete": false

View file

@ -1,7 +1,7 @@
{
"schema": "hololake.native-desktop-foundation/v1",
"record_id": "HLP-NATIVE-DESKTOP-FOUNDATION-001",
"state": "MINIMAL_TAURI_SCAFFOLD_WITH_TCS_UNIVERSAL_LANGUAGE_PERSONAL_CHANNEL_CONTRACT_REGISTERED",
"state": "MINIMAL_TAURI_SCAFFOLD_WITH_ACCOUNT_SINGLE_WRITER_KERNEL",
"canonical_shell": "TAURI_V2_RUST_REACT",
"product_ui_implementation_started": false,
"selected_visual_direction_present": false,
@ -19,6 +19,9 @@
"donor_audit_complete": false,
"donor_source_copying_allowed": false,
"stage_one_product_contract": "contracts/stage-one-platform.json",
"local_development_bridge_contract": "contracts/local-development-bridge.json",
"account_single_writer_kernel_implemented": true,
"external_local_broker_implemented": false,
"stage_one_product_contract_state": "TCS_UNIVERSAL_LANGUAGE_PERSONAL_CHANNEL_CONTRACT_ONLY_RUNTIME_NOT_IMPLEMENTED",
"stage_one_internal_ai_interaction": false,
"stage_one_model_api_configuration": false,

View file

@ -4,6 +4,7 @@ import test from 'node:test'
const contract = JSON.parse(fs.readFileSync(new URL('../contracts/stage-one-platform.json', import.meta.url), 'utf8'))
const foundation = JSON.parse(fs.readFileSync(new URL('../foundation.json', import.meta.url), 'utf8'))
const bridge = JSON.parse(fs.readFileSync(new URL('../contracts/local-development-bridge.json', import.meta.url), 'utf8'))
test('stage one is a personal channel with no internal AI product', () => {
assert.ok(contract.human_surface.includes('PERSONAL_CHANNEL_HOME'))
@ -13,8 +14,55 @@ test('stage one is a personal channel with no internal AI product', () => {
assert.equal(foundation.stage_one_model_api_configuration, false)
})
test('HoloLake owns continuity and MCP remains an optional adapter', () => {
assert.equal(contract.mcp_is_continuity_root, false)
assert.equal(bridge.primary_transport.owner, 'HOLOLAKE_NATIVE_LOCAL_BROKER')
assert.equal(bridge.primary_transport.network_required_for_local_work, false)
assert.equal(bridge.continuity.active_writer_auto_released_on_disconnect, false)
})
test('one account has one writer while readers and reviewers can remain parallel', () => {
assert.equal(contract.account_write_lanes, 1)
assert.equal(bridge.account_concurrency.write_lanes_per_account, 1)
assert.equal(bridge.account_concurrency.parallel_readers_allowed, true)
assert.equal(bridge.account_concurrency.parallel_reviewers_allowed, true)
assert.equal(bridge.account_concurrency.parallel_editors_allowed, false)
})
test('language-space reads are resumable pages rather than silent truncation', () => {
assert.equal(bridge.language_space_reads.persona_selects_address, true)
assert.equal(bridge.language_space_reads.persona_selects_read_budget, true)
assert.equal(bridge.language_space_reads.server_may_page_but_must_not_silently_truncate, true)
assert.equal(bridge.language_space_reads.every_partial_response_returns_exact_resume_cursor, true)
})
test('a programming AI must bootstrap a missing direct connector instead of remaining MCP-only', () => {
assert.equal(bridge.external_ai_entry.permanent_mcp_only_state_allowed_for_programming_ai, false)
assert.equal(bridge.external_ai_entry.missing_direct_connector_triggers_capability_bootstrap, true)
assert.equal(bridge.connector_capability_bootstrap.artifact_is_stored_in_hololake, true)
assert.equal(bridge.connector_capability_bootstrap.tests_and_capability_receipt_required, true)
assert.equal(bridge.connector_capability_bootstrap.silent_persistence_or_authority_expansion_allowed, false)
})
test('AI is the language interface and host adaptation cannot expand authority', () => {
assert.equal(contract.universal_language.ai_is_language_interface, true)
assert.equal(contract.universal_language.vendor_adapter_matrix_required, false)
assert.equal(contract.universal_language.host_self_adaptation_changes_how_not_authority, true)
})
test('the personal work lake keeps private runtime on the user node', () => {
assert.equal(contract.default_user_runtime_node, 'USER_LOCAL_COMPUTER_TERMINAL')
assert.equal(contract.platform_hosts_private_user_runtime, false)
assert.equal(bridge.personal_work_lake.control_plane, 'EMBEDDED_SQLITE_SINGLE_HOLOLAKE_OWNER')
assert.match(bridge.personal_work_lake.code_history, /STANDARD_GIT/)
assert.equal(bridge.personal_work_lake.external_ai_direct_database_or_git_mutation_allowed, false)
})
test('mobile and enterprise registry stay thin and privacy preserving', () => {
assert.equal(contract.mobile_is_same_persona_system_remote_body, true)
assert.equal(bridge.mobile_remote_entry.relay_can_read_private_payload, false)
assert.equal(bridge.mobile_remote_entry.offline_node_can_execute, false)
assert.equal(bridge.enterprise_registry_boundary.human_number_is_credential, false)
assert.equal(bridge.enterprise_registry_boundary.account_authentication_is_node_possession, false)
assert.equal(bridge.enterprise_registry_boundary.platform_stores_private_work_lake, false)
})

View file

@ -1335,6 +1335,7 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
name = "hololake-native-desktop"
version = "0.1.0"
dependencies = [
"ring",
"serde",
"serde_json",
"tauri",
@ -1343,6 +1344,7 @@ dependencies = [
"tauri-runtime",
"tauri-runtime-wry",
"tempfile",
"uuid",
]
[[package]]

View file

@ -15,12 +15,14 @@ crate-type = ["staticlib", "cdylib", "rlib"]
tauri-build = { version = "2.5.4", features = [] }
[dependencies]
ring = "0.17"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tauri = { version = "=2.10.2", features = [] }
tauri-runtime = "=2.10.0"
tauri-runtime-wry = "=2.10.0"
tauri-plugin-updater = "2.10.0"
uuid = { version = "1", features = ["v4"] }
[dev-dependencies]
tempfile = "3"

View file

@ -1,8 +1,14 @@
mod local_development_bridge;
mod release_trust;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![
local_development_bridge::acquire_development_write_lane,
local_development_bridge::inspect_development_write_lane,
local_development_bridge::release_development_write_lane,
])
.setup(|app| {
release_trust::install_updater_if_provisioned(app.handle())?;
Ok(())

View file

@ -0,0 +1,426 @@
use ring::digest::{digest, SHA256};
use serde::{Deserialize, Serialize};
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use tauri::{AppHandle, Manager};
use uuid::Uuid;
const BRIDGE_SCHEMA: &str = "hololake.local-development-writer/v1";
const MAX_ID_BYTES: usize = 128;
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AcquireWriteLaneInput {
pub account_id: String,
pub lane_id: String,
pub owner_instance_id: String,
pub resume_token: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InspectWriteLaneInput {
pub account_id: String,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReleaseWriteLaneInput {
pub account_id: String,
pub lane_id: String,
pub owner_instance_id: String,
pub resume_token: String,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WriteLaneReceipt {
pub schema: &'static str,
pub state: &'static str,
pub account_key: String,
pub lane_id: String,
pub owner_instance_id: String,
pub acquired_at_unix_ms: u128,
pub observed_at_unix_ms: u128,
pub resume_token: Option<String>,
pub receipt_id: String,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InspectWriteLaneReceipt {
pub schema: &'static str,
pub state: &'static str,
pub account_key: String,
pub lane_id: Option<String>,
pub owner_instance_id: Option<String>,
pub acquired_at_unix_ms: Option<u128>,
pub observed_at_unix_ms: u128,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct ActiveWriterRecord {
schema: String,
account_key: String,
lane_id: String,
owner_instance_id: String,
resume_token_sha256: String,
acquired_at_unix_ms: u128,
}
#[tauri::command]
pub async fn acquire_development_write_lane(
app: AppHandle,
input: AcquireWriteLaneInput,
) -> Result<WriteLaneReceipt, String> {
let root = bridge_root(&app)?;
tauri::async_runtime::spawn_blocking(move || acquire_at(&root, input))
.await
.map_err(|error| format!("HOLOLAKE_BRIDGE_JOIN_FAILED: {error}"))?
}
#[tauri::command]
pub async fn inspect_development_write_lane(
app: AppHandle,
input: InspectWriteLaneInput,
) -> Result<InspectWriteLaneReceipt, String> {
let root = bridge_root(&app)?;
tauri::async_runtime::spawn_blocking(move || inspect_at(&root, &input.account_id))
.await
.map_err(|error| format!("HOLOLAKE_BRIDGE_JOIN_FAILED: {error}"))?
}
#[tauri::command]
pub async fn release_development_write_lane(
app: AppHandle,
input: ReleaseWriteLaneInput,
) -> Result<WriteLaneReceipt, String> {
let root = bridge_root(&app)?;
tauri::async_runtime::spawn_blocking(move || release_at(&root, input))
.await
.map_err(|error| format!("HOLOLAKE_BRIDGE_JOIN_FAILED: {error}"))?
}
fn bridge_root(app: &AppHandle) -> Result<PathBuf, String> {
let app_data = app
.path()
.app_data_dir()
.map_err(|error| format!("HOLOLAKE_APP_DATA_UNAVAILABLE: {error}"))?;
let root = app_data.join("local-development-bridge-v1");
fs::create_dir_all(&root)
.map_err(|error| format!("HOLOLAKE_BRIDGE_STORAGE_UNAVAILABLE: {error}"))?;
root.canonicalize()
.map_err(|error| format!("HOLOLAKE_BRIDGE_STORAGE_UNAVAILABLE: {error}"))
}
fn acquire_at(root: &Path, input: AcquireWriteLaneInput) -> Result<WriteLaneReceipt, String> {
validate_identifier(&input.account_id, "ACCOUNT")?;
validate_identifier(&input.lane_id, "LANE")?;
validate_identifier(&input.owner_instance_id, "OWNER")?;
let account_key = sha256_hex(input.account_id.as_bytes());
let account_root = prepare_account_root(root, &account_key)?;
let active_path = account_root.join("active-writer.json");
if active_path.exists() {
let active = read_active_record(&active_path)?;
return resume_existing(active, &input.lane_id, input.resume_token.as_deref());
}
if input.resume_token.is_some() {
return Err("HOLOLAKE_WRITER_RESUME_TOKEN_STALE".into());
}
let resume_token = Uuid::new_v4().to_string();
let acquired_at_unix_ms = now_unix_ms()?;
let record = ActiveWriterRecord {
schema: BRIDGE_SCHEMA.to_string(),
account_key: account_key.clone(),
lane_id: input.lane_id.clone(),
owner_instance_id: input.owner_instance_id.clone(),
resume_token_sha256: sha256_hex(resume_token.as_bytes()),
acquired_at_unix_ms,
};
let bytes = serde_json::to_vec_pretty(&record)
.map_err(|error| format!("HOLOLAKE_WRITER_RECORD_INVALID: {error}"))?;
let mut file = match OpenOptions::new()
.write(true)
.create_new(true)
.open(&active_path)
{
Ok(file) => file,
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
let active = read_active_record(&active_path)?;
return resume_existing(active, &input.lane_id, input.resume_token.as_deref());
}
Err(error) => return Err(format!("HOLOLAKE_WRITER_ACQUIRE_FAILED: {error}")),
};
file.write_all(&bytes)
.and_then(|_| file.sync_all())
.map_err(|error| format!("HOLOLAKE_WRITER_ACQUIRE_FAILED: {error}"))?;
Ok(receipt_for(
"ACQUIRED",
&record,
Some(resume_token),
acquired_at_unix_ms,
))
}
fn resume_existing(
record: ActiveWriterRecord,
requested_lane_id: &str,
resume_token: Option<&str>,
) -> Result<WriteLaneReceipt, String> {
if record.lane_id != requested_lane_id {
return Err("HOLOLAKE_ACCOUNT_WRITER_ALREADY_ACTIVE".into());
}
let supplied = resume_token.ok_or("HOLOLAKE_ACCOUNT_WRITER_ALREADY_ACTIVE")?;
if sha256_hex(supplied.as_bytes()) != record.resume_token_sha256 {
return Err("HOLOLAKE_ACCOUNT_WRITER_ALREADY_ACTIVE".into());
}
let observed_at = now_unix_ms()?;
Ok(receipt_for("RESUMED", &record, None, observed_at))
}
fn inspect_at(root: &Path, account_id: &str) -> Result<InspectWriteLaneReceipt, String> {
validate_identifier(account_id, "ACCOUNT")?;
let account_key = sha256_hex(account_id.as_bytes());
let active_path = root
.join("accounts")
.join(&account_key)
.join("active-writer.json");
let observed_at_unix_ms = now_unix_ms()?;
if !active_path.exists() {
return Ok(InspectWriteLaneReceipt {
schema: BRIDGE_SCHEMA,
state: "AVAILABLE",
account_key,
lane_id: None,
owner_instance_id: None,
acquired_at_unix_ms: None,
observed_at_unix_ms,
});
}
let record = read_active_record(&active_path)?;
Ok(InspectWriteLaneReceipt {
schema: BRIDGE_SCHEMA,
state: "ACTIVE",
account_key,
lane_id: Some(record.lane_id),
owner_instance_id: Some(record.owner_instance_id),
acquired_at_unix_ms: Some(record.acquired_at_unix_ms),
observed_at_unix_ms,
})
}
fn release_at(root: &Path, input: ReleaseWriteLaneInput) -> Result<WriteLaneReceipt, String> {
validate_identifier(&input.account_id, "ACCOUNT")?;
validate_identifier(&input.lane_id, "LANE")?;
validate_identifier(&input.owner_instance_id, "OWNER")?;
let account_key = sha256_hex(input.account_id.as_bytes());
let account_root = root.join("accounts").join(&account_key);
let active_path = account_root.join("active-writer.json");
let record = read_active_record(&active_path)?;
if record.lane_id != input.lane_id
|| record.owner_instance_id != input.owner_instance_id
|| record.resume_token_sha256 != sha256_hex(input.resume_token.as_bytes())
{
return Err("HOLOLAKE_WRITER_RELEASE_NOT_AUTHORIZED".into());
}
let released_at = now_unix_ms()?;
let receipt_id = receipt_id("RELEASED", &record, released_at);
let receipts_root = account_root.join("receipts");
fs::create_dir_all(&receipts_root)
.map_err(|error| format!("HOLOLAKE_WRITER_RELEASE_FAILED: {error}"))?;
let released_path = receipts_root.join(format!("{receipt_id}.json"));
fs::rename(&active_path, &released_path)
.map_err(|error| format!("HOLOLAKE_WRITER_RELEASE_FAILED: {error}"))?;
Ok(WriteLaneReceipt {
schema: BRIDGE_SCHEMA,
state: "RELEASED",
account_key: record.account_key,
lane_id: record.lane_id,
owner_instance_id: record.owner_instance_id,
acquired_at_unix_ms: record.acquired_at_unix_ms,
observed_at_unix_ms: released_at,
resume_token: None,
receipt_id,
})
}
fn prepare_account_root(root: &Path, account_key: &str) -> Result<PathBuf, String> {
let accounts_root = root.join("accounts");
fs::create_dir_all(&accounts_root)
.map_err(|error| format!("HOLOLAKE_BRIDGE_STORAGE_UNAVAILABLE: {error}"))?;
let account_root = accounts_root.join(account_key);
fs::create_dir_all(&account_root)
.map_err(|error| format!("HOLOLAKE_BRIDGE_STORAGE_UNAVAILABLE: {error}"))?;
Ok(account_root)
}
fn read_active_record(path: &Path) -> Result<ActiveWriterRecord, String> {
let bytes = fs::read(path).map_err(|error| {
if error.kind() == std::io::ErrorKind::NotFound {
"HOLOLAKE_WRITER_NOT_ACTIVE".to_string()
} else {
format!("HOLOLAKE_WRITER_RECORD_UNREADABLE: {error}")
}
})?;
let record: ActiveWriterRecord = serde_json::from_slice(&bytes)
.map_err(|error| format!("HOLOLAKE_WRITER_RECORD_INVALID: {error}"))?;
if record.schema != BRIDGE_SCHEMA {
return Err("HOLOLAKE_WRITER_RECORD_SCHEMA_UNSUPPORTED".into());
}
Ok(record)
}
fn receipt_for(
state: &'static str,
record: &ActiveWriterRecord,
resume_token: Option<String>,
observed_at_unix_ms: u128,
) -> WriteLaneReceipt {
WriteLaneReceipt {
schema: BRIDGE_SCHEMA,
state,
account_key: record.account_key.clone(),
lane_id: record.lane_id.clone(),
owner_instance_id: record.owner_instance_id.clone(),
acquired_at_unix_ms: record.acquired_at_unix_ms,
observed_at_unix_ms,
resume_token,
receipt_id: receipt_id(state, record, observed_at_unix_ms),
}
}
fn receipt_id(state: &str, record: &ActiveWriterRecord, observed_at_unix_ms: u128) -> String {
sha256_hex(
format!(
"{state}\n{}\n{}\n{}\n{}\n{observed_at_unix_ms}",
record.account_key,
record.lane_id,
record.owner_instance_id,
record.acquired_at_unix_ms
)
.as_bytes(),
)
}
fn validate_identifier(value: &str, kind: &str) -> Result<(), String> {
if value.is_empty()
|| value.len() > MAX_ID_BYTES
|| !value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
{
return Err(format!("HOLOLAKE_{kind}_ID_INVALID"));
}
Ok(())
}
fn now_unix_ms() -> Result<u128, String> {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_millis())
.map_err(|error| format!("HOLOLAKE_SYSTEM_CLOCK_INVALID: {error}"))
}
fn sha256_hex(value: &[u8]) -> String {
digest(&SHA256, value)
.as_ref()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
fn acquire_input(lane_id: &str) -> AcquireWriteLaneInput {
AcquireWriteLaneInput {
account_id: "human-BS-0001".into(),
lane_id: lane_id.into(),
owner_instance_id: "codex-instance-1".into(),
resume_token: None,
}
}
#[test]
fn one_account_cannot_open_two_write_lanes() {
let temp = TempDir::new().unwrap();
let first = acquire_at(temp.path(), acquire_input("DEV-001")).unwrap();
assert_eq!(first.state, "ACQUIRED");
assert_eq!(
acquire_at(temp.path(), acquire_input("DEV-002")).unwrap_err(),
"HOLOLAKE_ACCOUNT_WRITER_ALREADY_ACTIVE"
);
}
#[test]
fn the_same_lane_resumes_after_the_ai_reconnects() {
let temp = TempDir::new().unwrap();
let first = acquire_at(temp.path(), acquire_input("DEV-001")).unwrap();
let mut reconnect = acquire_input("DEV-001");
reconnect.resume_token = first.resume_token.clone();
let resumed = acquire_at(temp.path(), reconnect).unwrap();
assert_eq!(resumed.state, "RESUMED");
assert_eq!(resumed.lane_id, "DEV-001");
assert!(resumed.resume_token.is_none());
}
#[test]
fn a_resume_token_cannot_be_used_to_switch_to_another_lane() {
let temp = TempDir::new().unwrap();
let first = acquire_at(temp.path(), acquire_input("DEV-001")).unwrap();
let mut impostor = acquire_input("DEV-002");
impostor.resume_token = first.resume_token;
assert_eq!(
acquire_at(temp.path(), impostor).unwrap_err(),
"HOLOLAKE_ACCOUNT_WRITER_ALREADY_ACTIVE"
);
}
#[test]
fn explicit_release_creates_a_receipt_then_allows_the_next_lane() {
let temp = TempDir::new().unwrap();
let first = acquire_at(temp.path(), acquire_input("DEV-001")).unwrap();
let released = release_at(
temp.path(),
ReleaseWriteLaneInput {
account_id: "human-BS-0001".into(),
lane_id: "DEV-001".into(),
owner_instance_id: "codex-instance-1".into(),
resume_token: first.resume_token.unwrap(),
},
)
.unwrap();
assert_eq!(released.state, "RELEASED");
assert!(temp
.path()
.join("accounts")
.join(released.account_key)
.join("receipts")
.join(format!("{}.json", released.receipt_id))
.is_file());
let second = acquire_at(temp.path(), acquire_input("DEV-002")).unwrap();
assert_eq!(second.state, "ACQUIRED");
}
#[test]
fn inspect_never_discloses_the_resume_token() {
let temp = TempDir::new().unwrap();
acquire_at(temp.path(), acquire_input("DEV-001")).unwrap();
let observed = inspect_at(temp.path(), "human-BS-0001").unwrap();
assert_eq!(observed.state, "ACTIVE");
assert_eq!(observed.lane_id.as_deref(), Some("DEV-001"));
}
}