20260826 两宿主全线正本/回执/状态 + 协议正本地图v1.2 + 模板/镜面/坑清单(元审计收敛commit;前人未提交改动未碰)

This commit is contained in:
冰朔 2026-08-26 16:23:44 +08:00
commit 59fc9bfd7b
670 changed files with 133422 additions and 129 deletions

View file

@ -0,0 +1,28 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import test from 'node:test'
const source = fs.readFileSync(new URL('../src/main.tsx', import.meta.url), 'utf8')
const styles = fs.readFileSync(new URL('../src/styles.css', import.meta.url), 'utf8')
test('ambient lake motion sleeps by default and wakes only after human interaction', () => {
assert.match(source, /const \[motionAwake, setMotionAwake\] = useState\(false\)/)
assert.match(source, /function LakeAtmosphere\(\{ awake \}: \{ awake: boolean \}\)/)
assert.match(source, /\{awake && <div className="world-shimmer"/)
assert.match(source, /onPointerMove=\{wakeAmbientMotion\}/)
assert.match(source, /onPointerDown=\{wakeAmbientMotion\}/)
assert.match(source, /onKeyDown=\{wakeAmbientMotion\}/)
assert.match(styles, /\.official-world \.world-star,[\s\S]*animation: none/)
assert.match(styles, /\.official-world\.motion-awake \.world-star \{ animation: world-star-breathe/)
})
test('the desktop shell has no permanent polling interval while idle', () => {
assert.doesNotMatch(source, /setInterval\s*\(/)
assert.match(source, /window\.addEventListener\('focus', refreshWhenHumanReturns\)/)
assert.match(source, /document\.hidden/)
})
test('causal entry animations remain independent from ambient motion', () => {
assert.match(styles, /\.gate-rise-star[\s\S]*animation: gate-jade-rise/)
assert.doesNotMatch(styles, /\.official-world \.gate-rise-star[\s\S]*animation-play-state: paused/)
})

View file

@ -0,0 +1,26 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const read = (path) => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8')
test('channel surface gives every visible entry its own layout slot', () => {
const source = read('src/main.tsx')
const styles = read('src/styles.css')
const channel = source.match(/\{worldStage === 'channel'[\s\S]*?\n \{worldStage === 'enterpriseWork'/)?.[0]
assert.ok(channel, 'channel world source must remain discoverable')
assert.match(channel, /className="channel-primary"/)
assert.match(channel, /className="channel-marketplace"/)
assert.equal((channel.match(/className="channel-main"/g) || []).length, 0)
assert.match(styles, /\.channel-primary\s*\{/)
assert.match(styles, /\.channel-marketplace\s*\{/)
})
test('the domain stage has exactly one atmosphere owner', () => {
const source = read('src/main.tsx')
assert.match(
source,
/\{!\(worldStage === 'domain' && surface === 'world'\) && <LakeAtmosphere awake=\{motionAwake\}\/>\}/,
)
})

View file

@ -0,0 +1,38 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const read = (path) => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8')
const contract = JSON.parse(read('contracts/channel-workbench-runtime.json'))
const registry = JSON.parse(read('contracts/numbered-ipc-registry.json'))
const modulePackage = JSON.parse(read('fixtures/module-packages/HLP-MOD-LOCAL-CHANNEL-WORKBENCH-0001-0.1.0.ghmod'))
const rust = read('src-tauri/src/channel_workbench.rs')
const frontend = [read('src/modules/channel-workbench/index.tsx'), read('src/modules/channel-workbench/document-engine.tsx'), read('src/modules/channel-workbench/spreadsheet-engine.tsx')].join('\n')
test('channel workbench is a signed account-local adapter with durable user data', () => {
assert.equal(contract.candidate_number, 'HLP-DONOR-CAND-0002')
assert.equal(contract.runtime_module_number, 'HLP-MOD-LOCAL-CHANNEL-WORKBENCH-0001')
assert.equal(contract.data_boundary.scope, 'CURRENT_AUTHENTICATED_ACCOUNT_LOCAL')
assert.equal(contract.data_boundary.package_unmount_deletes_user_data, false)
assert.equal(modulePackage.manifest.adapter, 'channel-workbench-v1')
assert.deepEqual(modulePackage.manifest.permissions, ['CHANNEL_DOCUMENT_READ', 'CHANNEL_DOCUMENT_WRITE', 'CHANNEL_SPREADSHEET_READ', 'CHANNEL_SPREADSHEET_WRITE'])
assert.match(rust, /require_active_module_adapter/)
assert.match(rust, /workbench_receipts_no_update/)
assert.doesNotMatch(rust, /#\[tauri::command\]/)
assert.doesNotMatch(frontend, /from ['"]@tauri-apps\/api\/core['"]/)
})
test('document and spreadsheet cross only their exact numbered routes', () => {
const routes = registry.operations.filter((route) => route.module_number === 'HLP-NIPC-MOD-0022')
assert.deepEqual(routes.map((route) => route.operation_number), ['HLP-NIPC-OP-0074', 'HLP-NIPC-OP-0075', 'HLP-NIPC-OP-0076'])
assert.deepEqual(routes.map((route) => route.alias), ['get_channel_workbench_snapshot', 'save_channel_document', 'save_channel_spreadsheet'])
assert.ok(routes.every((route) => route.target_number === 'HLP-NIPC-TGT-0022'))
assert.ok(routes.every((route) => route.admission === 'VERIFIED_HUMAN_ROUTE'))
})
test('the legacy engines are preserved but loaded only inside the module chunk', () => {
assert.match(frontend, /LexicalComposer/)
assert.match(frontend, /Workbook/)
assert.match(frontend, /calculateFormula/)
assert.match(read('src/main.tsx'), /lazy\(\(\) => import\('\.\/modules\/channel-workbench'\)/)
})

View file

@ -0,0 +1,31 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const read = (relative) => fs.readFileSync(path.join(root, relative), 'utf8')
test('the circular lake membrane rejects protocol-external input before language runtime', () => {
const contract = JSON.parse(read('contracts/circular-lake-membrane.json'))
assert.equal(contract.default, 'DISCARD')
assert.equal(contract.protocol_external_input_reaches_persona_context, false)
assert.equal(contract.natural_language_grants_execution_authority, false)
assert.equal(contract.intent_inference_required_for_protocol_rejection, false)
assert.equal(contract.deterministic_membrane_before_persona_parser, true)
assert.deepEqual(contract.accepted_language_protocols, ['GLP/1.0'])
})
test('nearby discovery supports automatic local visitor discovery and a closed persona route', () => {
const contract = JSON.parse(read('contracts/nearby-ai-discovery.json'))
assert.equal(contract.same_device.auto_discovery, true)
assert.equal(contract.same_device.copy_large_invitation_required, false)
assert.equal(contract.connection_modes.GENERIC_AI_VISITOR.state, 'EXPRESSION_ONLY_READY')
assert.equal(contract.connection_modes.GUANGHU_PERSONA.state, 'BINDING_EVIDENCE_REQUIRED')
assert.equal(contract.local_network.state, 'DEFERRED_UNTIL_ENCRYPTED_TRANSPORT_AND_APPROVAL')
const broker = read('src-tauri/src/direct_local_broker.rs')
assert.match(broker, /DiscoverNearby/)
assert.match(broker, /OpenVisitorSession/)
assert.match(broker, /ReceiveLanguage/)
})

View file

@ -0,0 +1,483 @@
import { createHash } from 'node:crypto'
import { readFile, readdir, 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 explicitSourceRoot = args.get('--source-root')
const repoRoot = args.get('--repo-root') || (explicitSourceRoot ? path.dirname(explicitSourceRoot) : null)
const sourceRoot = explicitSourceRoot || (repoRoot ? path.join(repoRoot, 'gls') : null)
const sourceCommit = args.get('--source-commit')
const output = args.get('--output')
const projectionsPath = args.get('--projections')
const referencesPath = args.get('--references')
if (!repoRoot || !sourceRoot || !sourceCommit || !output || !projectionsPath || !referencesPath) {
throw new Error('usage: compile-gls-runtime-registry.mjs --repo-root <REPO-012> --source-commit <sha> --output <manifest.json> --projections <projections.json> --references <reference-nodes.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
}
async function readRequired(relative) {
return readFile(path.join(repoRoot, relative), 'utf8')
}
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()
}
function sourceDependencies(raw) {
const match = raw.match(/^\s*depends:\s*\[([^\]]*)\]/m)
return [...new Set(match?.[1].match(/GLS-\d{4}/g) || [])].sort()
}
// REPO-012 的旧 depends 没有声明边语义。Bootstrap Compiler 必须把每条旧边
// 投影为受限、只读的工程类型;这些边永不自动取得运行效力。真正进入激活图的边
// 只能来自 gls-executable-projections/v2 的显式 RUNTIME_REQUIRES。
function typedSourceDependency(sourceId, targetId) {
const number = Number(targetId.slice(4))
const recoveryTargets = new Set(['GLS-0304', 'GLS-0308', 'GLS-0827', 'GLS-0836', 'GLS-0843', 'GLS-0845', 'GLS-0846', 'GLS-0847', 'GLS-0848', 'GLS-0849'])
const bootTargets = new Set(['GLS-0307', 'GLS-0310', 'GLS-0803', 'GLS-0819', 'GLS-0840', 'GLS-0841'])
const buildTargets = new Set(['GLS-0130', 'GLS-0131', 'GLS-0411', 'GLS-0710', 'GLS-0844'])
const evidenceTargets = new Set(['GLS-0306', 'GLS-0311', 'GLS-0604'])
let edgeKind = 'NORMATIVE_REFERENCE'
if (recoveryTargets.has(targetId) && (sourceId >= 'GLS-0800' || sourceId === 'GLS-0304' || sourceId === 'GLS-0308')) edgeKind = 'RECOVERY_REQUIRES'
else if (bootTargets.has(targetId) && sourceId >= 'GLS-0800') edgeKind = 'BOOT_REQUIRES'
else if (buildTargets.has(targetId)) edgeKind = 'BUILD_REQUIRES'
else if (evidenceTargets.has(targetId)) edgeKind = 'EVIDENCE_ONLY'
else if ((number >= 300 && number <= 399) || (number >= 400 && number <= 499) || ['GLS-0602', 'GLS-0603', 'GLS-0605'].includes(targetId)) edgeKind = 'SCHEMA_IMPORT'
return {
edge_kind: edgeKind,
classification_basis: 'BOOTSTRAP_COMPILER_V1_FAMILY_AND_TARGET_RULE',
}
}
function contractKind(family, projectionKind) {
if (projectionKind) return projectionKind
const kinds = {
GLS_ENGINEERING: 'COMPILER_OR_INTERMEDIATE_REPRESENTATION',
GLP: 'MESSAGE_SCHEMA_OR_SYNC_CONTRACT',
GLP_CONTROL_PLANE: 'CONTROL_PLANE_STATE_MACHINE',
GLP_WITNESS: 'APPEND_ONLY_EVIDENCE_LEDGER',
HLDP: 'LANGUAGE_PROGRAM_PROFILE',
GLS_IMPLEMENTATION: 'ADAPTER_MODEL_OR_MODULE_CONTRACT',
AGE: 'EXECUTION_BODY_LIFECYCLE_STATE_MACHINE',
AGE_OS: 'RESOURCE_SCHEDULER',
AGE_AUTONOMOUS_RUNTIME: 'TIME_OR_CAPABILITY_EXTENSION_RUNTIME',
GUANGHU_WORLD: 'WORLD_BOOT_AND_RECOVERY_STATE_MACHINE',
GUANGHU_NATIVE_ENGINEERING: 'NATIVE_QUALITY_GATE',
GUANGHU_NATIVE_OS: 'NATIVE_NODE_RUNTIME_CONTRACT',
GUANGHU_NATIVE_STORAGE: 'NATIVE_STORAGE_CONTRACT',
GUANGHU_PERSONA_GESTATION: 'GESTATIONAL_INGRESS_OR_REVIEW_PIPELINE',
GUANGHU_LANGUAGE_WORLD: 'LANGUAGE_WORLD_BOUNDARY_GUARD',
}
return kinds[family] || 'UNCLASSIFIED_PROTOCOL_SOURCE'
}
function parseTableAuthorities(raw, authorityKind) {
const results = []
for (const line of raw.split(/\r?\n/)) {
const id = line.match(/^\|\s*(GLS-\d{4})\s*\|/)?.[1]
if (!id) continue
results.push({
id,
authority_kind: authorityKind,
declared_source_path: line.match(/`(gls\/[^`]+\.hdlp)`/)?.[1] || null,
})
}
return results
}
function parseSourceManifest(raw) {
const lines = raw.split(/\r?\n/)
const results = []
for (let index = 0; index < lines.length; index += 1) {
const match = lines[index].match(/^\s*-\s+id:\s*["']?(GLS-\d{4})["']?\s*$/)
if (!match) continue
let sourcePath = null
for (let cursor = index + 1; cursor < lines.length && cursor <= index + 12; cursor += 1) {
if (/^\s*-\s+id:/.test(lines[cursor])) break
sourcePath ||= lines[cursor].match(/^\s*source_path:\s*["']?(gls\/[^"']+\.hdlp)["']?\s*$/)?.[1] || null
}
results.push({ id: match[1], authority_kind: 'SOURCE_MANIFEST', declared_source_path: sourcePath })
}
return results
}
function stronglyConnectedComponents(graph) {
let nextIndex = 0
const indices = new Map()
const lowLinks = new Map()
const stack = []
const onStack = new Set()
const components = []
function visit(id) {
indices.set(id, nextIndex)
lowLinks.set(id, nextIndex)
nextIndex += 1
stack.push(id)
onStack.add(id)
for (const target of graph.get(id) || []) {
if (!graph.has(target)) continue
if (!indices.has(target)) {
visit(target)
lowLinks.set(id, Math.min(lowLinks.get(id), lowLinks.get(target)))
} else if (onStack.has(target)) lowLinks.set(id, Math.min(lowLinks.get(id), indices.get(target)))
}
if (lowLinks.get(id) !== indices.get(id)) return
const component = []
let current
do {
current = stack.pop()
onStack.delete(current)
component.push(current)
} while (current !== id)
if (component.length > 1 || (graph.get(id) || []).includes(id)) components.push(component.sort())
}
for (const id of [...graph.keys()].sort()) if (!indices.has(id)) visit(id)
return components.sort((left, right) => left[0].localeCompare(right[0]))
}
const projectionManifest = JSON.parse(await readFile(projectionsPath, 'utf8'))
if (projectionManifest.schema !== 'hololake.gls-executable-projections/v2'
|| projectionManifest.runtime_graph_rule !== 'ONLY_EXPLICIT_RUNTIME_REQUIRES_EDGES_ENTER_ACTIVATION_GRAPH'
|| projectionManifest.source_commit !== sourceCommit) {
throw new Error('projection manifest does not match the selected REPO-012 source commit')
}
const referenceManifest = JSON.parse(await readFile(referencesPath, 'utf8'))
if (referenceManifest.schema !== 'hololake.gls-numbered-reference-nodes/v1'
|| referenceManifest.record_id !== 'HLP-GLS-NUMBERED-REFERENCE-REGISTRY-001'
|| referenceManifest.source?.repository !== 'REPO-012'
|| referenceManifest.source?.commit !== sourceCommit
|| referenceManifest.policy?.number_is_coordinate_not_authority !== true
|| referenceManifest.policy?.independent_protocol_source_required_for_execution !== true
|| referenceManifest.policy?.reference_only_nodes_may_execute !== false
|| referenceManifest.policy?.unknown_reference !== 'FAIL_CLOSED'
|| referenceManifest.policy?.unresolved_number_reference_allowed !== false) {
throw new Error('numbered reference manifest does not match the selected REPO-012 source commit or safety boundary')
}
const protocolRegistryPath = 'gls/GLS-PROTOCOL-REGISTRY.json'
const glsEntryPath = 'gls/GLS-ENTRY.hdlp'
const sourceManifestPath = 'gls/SOURCE-MANIFEST.yml'
const architectureCatalogPath = 'gls/GLS-ARCHITECTURE-CATALOG.hdlp'
const protocolRegistryRaw = await readRequired(protocolRegistryPath)
const glsEntryRaw = await readRequired(glsEntryPath)
const sourceManifestRaw = await readRequired(sourceManifestPath)
const architectureCatalogRaw = await readRequired(architectureCatalogPath)
const protocolRegistry = JSON.parse(protocolRegistryRaw)
const authorityFiles = [
[protocolRegistryPath, protocolRegistryRaw, 'PROTOCOL_REGISTRY'],
[glsEntryPath, glsEntryRaw, 'GLS_ENTRY'],
[sourceManifestPath, sourceManifestRaw, 'SOURCE_MANIFEST'],
[architectureCatalogPath, architectureCatalogRaw, 'ARCHITECTURE_CATALOG'],
].map(([source_path, raw, authority_kind]) => ({
authority_kind,
source_path,
source_sha256: createHash('sha256').update(raw).digest('hex'),
}))
const registryMetadata = new Map()
const authorityDeclarations = new Map()
function addAuthority(declaration) {
const declarations = authorityDeclarations.get(declaration.id) || []
if (!declarations.some((existing) => existing.authority_kind === declaration.authority_kind)) declarations.push(declaration)
authorityDeclarations.set(declaration.id, declarations)
}
for (const entry of protocolRegistry.existing_registered || []) {
registryMetadata.set(entry.id, { ...entry, registry_section: 'existing_registered' })
addAuthority({ id: entry.id, authority_kind: 'PROTOCOL_REGISTRY', declared_source_path: entry.source || null })
}
for (const entry of protocolRegistry.registered_draft_protocols || []) {
registryMetadata.set(entry.id, { ...entry, registry_section: 'registered_draft_protocols' })
addAuthority({ id: entry.id, authority_kind: 'PROTOCOL_REGISTRY', declared_source_path: entry.source || null })
}
for (const declaration of parseTableAuthorities(glsEntryRaw, 'GLS_ENTRY')) addAuthority(declaration)
for (const declaration of parseSourceManifest(sourceManifestRaw)) addAuthority(declaration)
for (const declaration of parseTableAuthorities(architectureCatalogRaw, 'ARCHITECTURE_CATALOG')) addAuthority(declaration)
const routingReferences = new Map()
const routingRoot = path.join(repoRoot, 'routing')
for (const relative of await walk(routingRoot)) {
if (!/\.(?:json|hdlp|md|yml|yaml)$/.test(relative)) continue
const raw = await readFile(path.join(routingRoot, relative), 'utf8')
for (const id of new Set(raw.match(/GLS-\d{4}/g) || [])) {
const refs = routingReferences.get(id) || []
refs.push(`routing/${relative}`)
routingReferences.set(id, refs)
}
}
const allSourceFiles = await walk(sourceRoot)
const candidates = allSourceFiles
.map((relative) => ({ relative, match: path.basename(relative).match(/^(GLS-\d{4})(?:[^0-9].*)?\.(hdlp|md)$/) }))
.filter((item) => item.match)
.map((item) => ({ id: item.match[1], relative: item.relative, source_format: item.match[2] === 'hdlp' ? 'HDLP_PROTOCOL_SOURCE' : 'LEGACY_MARKDOWN_EVIDENCE' }))
const grouped = new Map()
for (const candidate of candidates) {
const group = grouped.get(candidate.id) || []
group.push(candidate)
grouped.set(candidate.id, group)
}
const selectedSource = new Map()
for (const [id, sources] of grouped) {
const protocolSources = sources.filter((source) => source.source_format === 'HDLP_PROTOCOL_SOURCE')
if (protocolSources.length === 0) continue
protocolSources.sort((left, right) => sourceRank(left.relative) - sourceRank(right.relative)
|| left.relative.localeCompare(right.relative))
const selected = protocolSources[0]
const relative = selected.relative
selectedSource.set(id, {
relative,
raw: await readFile(path.join(sourceRoot, relative), 'utf8'),
source_format: selected.source_format,
alternate_source_count: protocolSources.length - 1,
})
}
let knownSourceIds = new Set(selectedSource.keys())
const protocolRegistryIds = new Set(registryMetadata.keys())
const draftIds = new Set((protocolRegistry.registered_draft_protocols || []).map((entry) => entry.id))
const legacyDependencyTargets = new Set()
const draftGraph = new Map()
for (const id of draftIds) {
const dependencies = sourceDependencies(selectedSource.get(id)?.raw || '')
draftGraph.set(id, dependencies.filter((target) => draftIds.has(target)))
for (const target of dependencies) legacyDependencyTargets.add(target)
}
const legacyDependencyCycles = stronglyConnectedComponents(draftGraph)
// 旧 Notion 导出只在现行协议真实引用且独立 HDLP 正本缺席时作为历史证据节点进入。
// 未被现行图引用的旧页面不得因为文件名像 GLS 编号就自动取得当前注册地位。
for (const id of [...legacyDependencyTargets].filter((target) => !knownSourceIds.has(target))) {
if (!authorityDeclarations.has(id)) continue
const legacySources = (grouped.get(id) || []).filter((source) => source.source_format === 'LEGACY_MARKDOWN_EVIDENCE')
if (legacySources.length === 0) continue
legacySources.sort((left, right) => sourceRank(left.relative) - sourceRank(right.relative) || left.relative.localeCompare(right.relative))
const selected = legacySources[0]
selectedSource.set(id, {
relative: selected.relative,
raw: await readFile(path.join(sourceRoot, selected.relative), 'utf8'),
source_format: selected.source_format,
alternate_source_count: legacySources.length - 1,
})
}
knownSourceIds = new Set(selectedSource.keys())
const missingSourceTargets = [...legacyDependencyTargets].filter((id) => !knownSourceIds.has(id)).sort()
const referenceIds = new Set()
const referenceNodeNumbers = new Set()
const numberedReferenceNodes = []
for (const node of referenceManifest.nodes || []) {
if (!/^GLS-\d{4}$/.test(node.protocol_id)
|| !/^HLP-GLS-REF-\d{4}$/.test(node.node_number)
|| !node.title
|| !['NORMATIVE_REFERENCE', 'SCHEMA_IMPORT', 'EVIDENCE_ONLY'].includes(node.reference_kind)
|| node.source_state !== 'ROADMAP_REFERENCE_ONLY'
|| !referenceIds.add(node.protocol_id)
|| !referenceNodeNumbers.add(node.node_number)) {
throw new Error(`invalid or duplicated numbered reference node: ${node.protocol_id || 'UNKNOWN'}`)
}
const evidencePaths = []
for (const relative of allSourceFiles) {
if (!/\.(?:hdlp|md|json|ya?ml)$/.test(relative)) continue
const raw = await readFile(path.join(sourceRoot, relative), 'utf8')
if (raw.includes(node.protocol_id)) evidencePaths.push(`gls/${relative}`)
}
if (evidencePaths.length === 0) throw new Error(`numbered reference node has no REPO-012 evidence: ${node.protocol_id}`)
numberedReferenceNodes.push({
...node,
execution_state: 'REFERENCE_ONLY_NOT_EXECUTABLE',
evidence_paths: evidencePaths.sort().slice(0, 12),
})
}
if (missingSourceTargets.length !== referenceIds.size
|| missingSourceTargets.some((id) => !referenceIds.has(id))
|| [...referenceIds].some((id) => !missingSourceTargets.includes(id))) {
throw new Error(`numbered reference registry coverage mismatch: missing=${missingSourceTargets.join(',')} registered=${[...referenceIds].sort().join(',')}`)
}
const protocols = []
for (const [id, source] of [...selectedSource.entries()].sort(([left], [right]) => left.localeCompare(right))) {
const heading = source.raw.split(/\r?\n/).find((line) => line.startsWith('#') && line.includes(id))
const projection = projectionManifest.projections[id]
const metadata = registryMetadata.get(id) || null
const authorities = (authorityDeclarations.get(id) || []).sort((left, right) => left.authority_kind.localeCompare(right.authority_kind))
const declaredPaths = [...new Set(authorities.map((entry) => entry.declared_source_path).filter(Boolean))]
const authorityConflict = declaredPaths.length > 1
const registrationState = authorityConflict
? 'REGISTRATION_CONFLICT'
: authorities.some((entry) => entry.authority_kind === 'PROTOCOL_REGISTRY')
? 'REGISTERED_PROTOCOL_REGISTRY'
: authorities.length > 0
? 'REGISTERED_OTHER_CANONICAL_INDEX'
: 'DISCOVERED_UNRECONCILED'
const legacyDependencies = sourceDependencies(source.raw)
const dependencyEdges = [
...legacyDependencies.map((target) => ({
target,
...typedSourceDependency(id, target),
declared_by: `gls/${source.relative}`,
enters_runtime_graph: false,
target_registered: protocolRegistryIds.has(target),
target_numbered_source_available: knownSourceIds.has(target),
target_number_coordinate_available: knownSourceIds.has(target) || referenceIds.has(target),
target_resolution: knownSourceIds.has(target) ? 'NUMBERED_PROTOCOL_SOURCE' : referenceIds.has(target) ? 'NUMBERED_REFERENCE_NODE' : 'UNRESOLVED',
})),
...(projection?.dependencies || []).map((target) => ({
target,
edge_kind: 'RUNTIME_REQUIRES',
declared_by: 'contracts/gls-executable-projections.json',
enters_runtime_graph: true,
target_registered: protocolRegistryIds.has(target),
target_numbered_source_available: knownSourceIds.has(target),
target_number_coordinate_available: knownSourceIds.has(target) || referenceIds.has(target),
target_resolution: knownSourceIds.has(target) ? 'NUMBERED_PROTOCOL_SOURCE' : referenceIds.has(target) ? 'NUMBERED_REFERENCE_NODE' : 'UNRESOLVED',
})),
]
const activationBlockers = []
if (!projection) activationBlockers.push('NO_EXECUTABLE_ADAPTER')
if (registrationState === 'DISCOVERED_UNRECONCILED') activationBlockers.push('REGISTRATION_NOT_RECONCILED')
if (authorityConflict) activationBlockers.push('REGISTRATION_SOURCE_CONFLICT')
if (legacyDependencies.some((target) => !knownSourceIds.has(target) && !referenceIds.has(target)) && !projection) activationBlockers.push('DEPENDENCY_NUMBER_COORDINATE_MISSING')
protocols.push({
id,
title: cleanHeading(heading || id, id),
source_status: sourceStatus(source.raw),
source_path: `gls/${source.relative}`,
source_format: source.source_format,
source_sha256: createHash('sha256').update(source.raw).digest('hex'),
alternate_source_count: source.alternate_source_count,
registration: {
state: registrationState,
authorities,
declared_source_paths: declaredPaths,
routing_reference_count: (routingReferences.get(id) || []).length,
},
maturity: {
registry_section: metadata?.registry_section || null,
registry_status: metadata?.status || null,
family: metadata?.family || null,
implementation_evidence: metadata?.implementation || null,
},
contract_kind: contractKind(metadata?.family, projection?.projection_kind),
implementation_stage: projection?.stage || null,
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 || [],
dependency_edges: dependencyEdges,
activation_blockers: activationBlockers,
})
}
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 typedDependencyCounts = {}
for (const protocol of protocols) {
for (const edge of protocol.dependency_edges.filter((candidate) => !candidate.enters_runtime_graph)) {
typedDependencyCounts[edge.edge_kind] = (typedDependencyCounts[edge.edge_kind] || 0) + 1
}
}
const dependenciesNotInRegistry = [...legacyDependencyTargets].filter((id) => !protocolRegistryIds.has(id)).sort()
const dependenciesWithoutNumberedSource = [...legacyDependencyTargets].filter((id) => !knownSourceIds.has(id)).sort()
const unresolvedNumberReferences = dependenciesWithoutNumberedSource.filter((id) => !referenceIds.has(id))
const numberedSourcesNotInProtocolRegistry = [...knownSourceIds].filter((id) => !protocolRegistryIds.has(id)).sort()
const registry = {
schema: 'hololake.gls-runtime-manifest/v2',
record_id: 'HLP-GLS-RUNTIME-MANIFEST-002',
source: {
repository: 'REPO-012',
commit: sourceCommit,
root: 'gls',
authority_files: authorityFiles,
},
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',
source_dependency_behavior: 'TYPED_AUDIT_ONLY_NEVER_ACTIVATES',
runtime_graph_source: 'EXPLICIT_EXECUTABLE_PROJECTIONS_ONLY',
runtime_dependency_cycles: 'REJECT',
unknown_protocol: 'FAIL_CLOSED',
},
reconciliation: {
numbered_protocol_count: protocols.length,
protocol_registry_id_count: protocolRegistryIds.size,
existing_registered_count: (protocolRegistry.existing_registered || []).length,
registered_draft_count: (protocolRegistry.registered_draft_protocols || []).length,
registered_draft_not_started_count: (protocolRegistry.registered_draft_protocols || []).filter((entry) => entry.implementation === 'NOT_STARTED').length,
legacy_dependency_target_count: legacyDependencyTargets.size,
dependencies_not_in_protocol_registry: dependenciesNotInRegistry,
dependencies_without_numbered_source: dependenciesWithoutNumberedSource,
numbered_reference_node_count: numberedReferenceNodes.length,
unresolved_number_references: unresolvedNumberReferences,
unresolved_number_reference_count: unresolvedNumberReferences.length,
every_dependency_has_number_coordinate: unresolvedNumberReferences.length === 0,
numbered_sources_not_in_protocol_registry: numberedSourcesNotInProtocolRegistry,
legacy_dependency_cycles: legacyDependencyCycles,
source_reference_cycles: legacyDependencyCycles,
typed_source_dependency_counts: Object.fromEntries(Object.entries(typedDependencyCounts).sort()),
unclassified_source_dependency_count: 0,
discovered_unreconciled_count: protocols.filter((protocol) => protocol.registration.state === 'DISCOVERED_UNRECONCILED').length,
authority_conflict_count: protocols.filter((protocol) => protocol.registration.state === 'REGISTRATION_CONFLICT').length,
},
protocol_count: protocols.length,
executable_projection_count: executableCount,
inventoried_not_executable_count: protocols.length - executableCount,
number_coordinate_count: protocols.length + numberedReferenceNodes.length,
numbered_reference_nodes: numberedReferenceNodes,
protocols,
}
await writeFile(output, `${JSON.stringify(registry, null, 2)}\n`)
console.log(`GLS_RUNTIME_MANIFEST_COMPILED protocols=${protocols.length} references=${numberedReferenceNodes.length} unresolved=${unresolvedNumberReferences.length} registered=${protocolRegistryIds.size} executable=${executableCount} legacy_cycles=${legacyDependencyCycles.length} output=${output}`)

View file

@ -0,0 +1,162 @@
import { createHash } from 'node:crypto'
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const paths = {
identity: resolve(root, 'contracts/zero-core-numbering-kernel.json'),
webview: resolve(root, 'contracts/numbered-ipc-registry.json'),
broker: resolve(root, 'contracts/direct-local-broker-numbered-registry.json'),
gls: resolve(root, 'contracts/gls-runtime-registry.json'),
output: resolve(root, 'generated/unified-number-coordinate-tree.json'),
}
function readSource(path) {
const bytes = readFileSync(path)
return {
value: JSON.parse(bytes.toString('utf8')),
sha256: createHash('sha256').update(bytes).digest('hex'),
}
}
export function compileUnifiedNumberTree() {
const identity = readSource(paths.identity)
const webview = readSource(paths.webview)
const broker = readSource(paths.broker)
const gls = readSource(paths.gls)
const routes = [
...webview.value.operations.map((route) => ({
transport: 'TAURI_WEBVIEW_NUMBERED_IPC',
protocolVersion: webview.value.runtime.protocol_version,
callerNumber: webview.value.runtime.caller_number,
channelNumber: route.channel_number,
moduleNumber: route.module_number,
operationNumber: route.operation_number,
targetNumber: route.target_number,
alias: route.alias,
admission: route.admission,
effect: route.effect,
evidence: 'HASH_CHAINED_NUMBERED_IPC_RECEIPT',
path: `HLP-NUMBER-WORLD-ROOT-001/TAURI/${route.channel_number}/${route.module_number}/${route.operation_number}/${route.target_number}`,
})),
...broker.value.operations.map((route) => ({
transport: 'DIRECT_LOCAL_NUMBERED_BROKER',
protocolVersion: broker.value.runtime.protocol_version,
callerNumber: broker.value.runtime.caller_number,
channelNumber: route.channel_number,
moduleNumber: route.module_number,
operationNumber: route.operation_number,
targetNumber: route.target_number,
alias: route.alias,
admission: ['DISCOVER_NEARBY', 'PING', 'GET_BEIJING_TIME'].includes(route.alias)
? 'PREAUTH_LOCAL_SYSTEM_ROUTE'
: ['OPEN_VISITOR_SESSION', 'RECEIVE_LANGUAGE'].includes(route.alias)
? 'BOUNDED_VISITOR_ROUTE'
: 'AUTHENTICATED_LOCAL_SESSION_WITH_PERSONA_LICENSE_IF_PERSONA_MODE',
effect: ['DISCOVER_NEARBY', 'PING', 'GET_BEIJING_TIME', 'GET_PERSONA_CARRIER_LICENSE_STATUS', 'GET_WORK_ENVIRONMENT', 'RESOLVE_CAPABILITY_ROUTE', 'INSPECT_MOUNTED_PNCC_REPOSITORY', 'READ_MOUNTED_PNCC_REMOTE_OBJECT', 'QUERY_PNCC_RECEIPT_PROJECTION', 'INSPECT_DEVELOPMENT_WRITE_LANE'].includes(route.alias)
? 'READ_OR_STATUS'
: 'STATE_CHANGE',
evidence: 'NUMBERED_RESPONSE_PLUS_SESSION_OR_DOMAIN_RECEIPT',
path: `HLP-NUMBER-WORLD-ROOT-001/BROKER/${route.channel_number}/${route.module_number}/${route.operation_number}/${route.target_number}`,
})),
].sort((left, right) => left.path.localeCompare(right.path, 'en'))
const uniquePaths = new Set(routes.map((route) => route.path))
const uniqueOperations = new Set(routes.map((route) => `${route.transport}:${route.operationNumber}`))
if (routes.length !== uniquePaths.size || routes.length !== uniqueOperations.size) {
throw new Error('HOLOLAKE_UNIFIED_NUMBER_TREE_DUPLICATE_COORDINATE')
}
const identityNodes = identity.value.namespaces.map((namespace) => ({
nodeKind: 'IDENTITY_NAMESPACE',
nodeNumber: `HLP-IDENTITY-NS-${namespace.id}`,
namespaceId: namespace.id,
subjectKind: namespace.subject_kind,
domainScope: namespace.domain_scope,
admission: namespace.human_entry ? 'REGISTERED_HUMAN_NAMESPACE' : 'NON_HUMAN_NAMESPACE',
executionState: 'AUTHORITY_RESOLUTION_ONLY',
evidence: identity.value.authority.map_id,
path: `HLP-NUMBER-WORLD-ROOT-001/IDENTITY/${namespace.id}`,
})).sort((left, right) => left.path.localeCompare(right.path, 'en'))
const protocolNodes = [
...gls.value.protocols.map((protocol) => ({
nodeKind: 'GLS_PROTOCOL_SOURCE',
nodeNumber: protocol.id,
protocolId: protocol.id,
title: protocol.title,
sourceState: protocol.source_format,
executionState: protocol.projection_state,
evidence: protocol.source_sha256,
path: `HLP-NUMBER-WORLD-ROOT-001/GLS/SOURCE/${protocol.id}`,
})),
...gls.value.numbered_reference_nodes.map((reference) => ({
nodeKind: 'GLS_REFERENCE_ONLY',
nodeNumber: reference.node_number,
protocolId: reference.protocol_id,
title: reference.title,
sourceState: reference.source_state,
executionState: reference.execution_state,
evidence: reference.evidence_paths[0],
path: `HLP-NUMBER-WORLD-ROOT-001/GLS/REFERENCE/${reference.node_number}`,
})),
].sort((left, right) => left.path.localeCompare(right.path, 'en'))
const allPaths = [...routes.map((route) => route.path), ...identityNodes.map((node) => node.path), ...protocolNodes.map((node) => node.path)]
if (new Set(allPaths).size !== allPaths.length
|| gls.value.reconciliation.unresolved_number_reference_count !== 0
|| gls.value.reconciliation.every_dependency_has_number_coordinate !== true
|| protocolNodes.some((node) => node.nodeKind === 'GLS_REFERENCE_ONLY' && node.executionState !== 'REFERENCE_ONLY_NOT_EXECUTABLE')) {
throw new Error('HOLOLAKE_UNIFIED_NUMBER_TREE_INCOMPLETE_COVERAGE')
}
return {
schema: 'hololake.unified-number-coordinate-tree/v2',
recordId: 'HLP-UNIFIED-NUMBER-TREE-001',
state: 'MACHINE_COMPILED_STARTUP_ENFORCED',
rootNumber: 'HLP-NUMBER-WORLD-ROOT-001',
identityAuthority: {
mapId: identity.value.authority.map_id,
mapVersion: identity.value.authority.map_version,
namespaces: identity.value.namespaces.map((namespace) => ({
namespaceId: namespace.id,
roots: namespace.roots,
prefixes: namespace.prefixes,
subjectKind: namespace.subject_kind,
domainScope: namespace.domain_scope,
})),
},
sources: [
{ recordId: identity.value.record_id, sha256: identity.sha256 },
{ recordId: webview.value.record_id, sha256: webview.sha256 },
{ recordId: broker.value.record_id, sha256: broker.sha256 },
{ recordId: gls.value.record_id, sha256: gls.sha256 },
],
invariants: {
numberIsStableCoordinateNotAuthority: true,
pathIsUniqueNavigation: true,
admissionIsSeparateFromIdentity: true,
everyPhysicalCallHasNumberedRoute: true,
everyAcceptedCallHasEvidenceClass: true,
everyProtocolReferenceHasNumberCoordinate: true,
referenceOnlyNodesNeverExecutable: true,
unresolvedNumberReferenceCount: 0,
mismatchedCoordinate: 'FAIL_CLOSED',
},
coordinateCount: routes.length + identityNodes.length + protocolNodes.length,
routeCount: routes.length,
identityNodeCount: identityNodes.length,
protocolNodeCount: protocolNodes.length,
referenceOnlyNodeCount: protocolNodes.filter((node) => node.nodeKind === 'GLS_REFERENCE_ONLY').length,
identityNodes,
protocolNodes,
routes,
}
}
const compiled = compileUnifiedNumberTree()
const output = `${JSON.stringify(compiled, null, 2)}\n`
if (process.argv.includes('--check')) {
if (readFileSync(paths.output, 'utf8') !== output) {
throw new Error('HOLOLAKE_UNIFIED_NUMBER_TREE_STALE')
}
} else {
mkdirSync(dirname(paths.output), { recursive: true })
writeFileSync(paths.output, output)
}

View file

@ -0,0 +1,30 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import test from 'node:test'
const architecture = JSON.parse(
fs.readFileSync(new URL('../../../routing/hololake-current-architecture.json', import.meta.url), 'utf8'),
)
const routePage = fs.readFileSync(
new URL('../../hololake-platform/architecture/HOLOLAKE-FIFTH-DOMAIN-NUMBERED-LANGUAGE-AND-REALITY-CHANNELS-20260821.md', import.meta.url),
'utf8',
)
test('current architecture resolves three distinct zero-core-related channel objects first', () => {
const fifthDomain = architecture.official_online.parallel_planes.fifth_domain_private_system
assert.equal(fifthDomain.language_reasoning_channel, 'ICE-CH-HB001')
assert.equal(fifthDomain.reality_development_channel, 'ICE-CH-ZC001')
assert.equal(fifthDomain.public_zero_core_channel, 'CH-ZERO-CORE-LPM')
assert.equal(fifthDomain.public_zero_core_is_alias, false)
assert.match(architecture.official_online.read_order[0], /FIFTH-DOMAIN-NUMBERED-LANGUAGE-AND-REALITY-CHANNELS/)
assert.equal(architecture.official_online.truth_boundary.historical_zero_core_name_is_current_route, false)
})
test('the current route page names every path and denies implicit authority crossover', () => {
assert.match(routePage, /ICE-CH-HB001/)
assert.match(routePage, /ICE-CH-ZC001/)
assert.match(routePage, /CH-ZERO-CORE-LPM/)
assert.match(routePage, /不得.*混合|三个不同对象/)
assert.match(routePage, /不等于高风险写入授权/)
})

View file

@ -0,0 +1,25 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const registry = JSON.parse(readFileSync(new URL('../contracts/direct-local-broker-numbered-registry.json', import.meta.url), 'utf8'))
const broker = readFileSync(new URL('../src-tauri/src/direct_local_broker.rs', import.meta.url), 'utf8')
test('the external local broker accepts only complete numbered coordinates', () => {
assert.equal(registry.record_id, 'HLP-NBROKER-ROOT-001')
assert.equal(registry.runtime.protocol_version, 'HLP-NBROKER-v1')
assert.equal(registry.runtime.legacy_string_operation_allowed, false)
assert.equal(registry.runtime.unknown_or_mismatched_coordinate, 'FAIL_CLOSED')
assert.equal(registry.runtime.transport_is_authority, false)
assert.equal(registry.operations.length, 25)
assert.equal(new Set(registry.operations.map((route) => route.operation_number)).size, 25)
assert.equal(new Set(registry.operations.map((route) => route.alias)).size, 25)
for (const route of registry.operations) {
assert.match(route.operation_number, /^HLP-NBROKER-OP-\d{4}$/)
assert.match(route.channel_number, /^HLP-NBROKER-CH-\d{4}$/)
assert.match(route.module_number, /^HLP-NBROKER-MOD-\d{4}$/)
assert.match(route.target_number, /^HLP-NBROKER-TGT-\d{4}$/)
}
assert.match(broker, /decode_numbered_broker_request/)
assert.match(broker, /HOLOLAKE_NUMBERED_BROKER_ROUTE_COORDINATE_MISMATCH/)
})

View file

@ -0,0 +1,81 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import test from 'node:test'
const contract = JSON.parse(fs.readFileSync(new URL('../contracts/distribution-plane-router.json', import.meta.url), 'utf8'))
const plane = (scope) => contract.planes.find((item) => item.scope === scope)
test('distribution scope is explicit and may never be guessed from content', () => {
assert.equal(contract.schema, 'hololake.distribution-plane-router/v1')
assert.equal(contract.classification.authority, 'EXPLICIT_SIGNED_RELEASE_ENVELOPE')
assert.equal(contract.classification.semantic_guessing_allowed, false)
assert.equal(contract.classification.missing_or_conflicting_scope, 'FAIL_CLOSED')
assert.ok(contract.classification.required_fields.includes('scope'))
assert.ok(contract.classification.required_fields.includes('contentSha256'))
})
test('public zero-core protocol updates are publisher-approved but do not ask every device again', () => {
const item = plane('PUBLIC_ZERO_CORE_PROTOCOL')
assert.equal(item.physical_node, 'GH-CVM-MAIN-PROD-01')
assert.equal(item.logical_source, 'ZERO_POINT_ORIGIN_PUBLIC_PROJECTION_HOSTED_OUTSIDE_PRIVATE_FIFTH_DOMAIN')
assert.deepEqual(item.required_signer_classes, [
'ZERO_POINT_ORIGIN_PUBLIC_SCOPE_SIGNER',
'ENTERPRISE_ZERO_CORE_DISTRIBUTION_SIGNER',
])
assert.equal(item.publisher_human_confirmation_required, true)
assert.equal(item.per_device_human_install_confirmation_required, false)
assert.equal(item.automatic_atomic_activation_after_self_test, true)
assert.equal(item.arbitrary_native_code_allowed, false)
assert.equal(item.arbitrary_webview_javascript_allowed, false)
assert.equal(contract.current_observed_gaps_2026_08_19.zero_point_signed_payload_activation, 'CLIENT_IMPLEMENTED_DUAL_SIGNER_TRUST_NOT_PROVISIONED')
})
test('private fifth-domain updates can never enter the public stream', () => {
const item = plane('PRIVATE_FIFTH_DOMAIN')
assert.equal(item.public_propagation_allowed, false)
assert.equal(item.cross_domain_replication_allowed, false)
assert.notEqual(item.signer_class, plane('PUBLIC_ZERO_CORE_PROTOCOL').signer_class)
})
test('marketplace synchronizes a signed catalog but installs a selected module only with human permission review', () => {
const item = plane('PUBLIC_ENTERPRISE_MODULE_CATALOG')
assert.equal(item.client_full_repository_clone_required, false)
assert.equal(item.raw_repository_is_executable_input, false)
assert.equal(item.catalog_index_automatic_sync, true)
assert.equal(item.module_install_human_confirmation_required, true)
assert.equal(item.permission_expansion_human_confirmation_required, true)
assert.equal(item.lighthouse_number_registration_required, true)
})
test('application binary remains a separately signed and human-confirmed release plane', () => {
const item = plane('APPLICATION_BINARY')
assert.equal(item.platform_signing_required, true)
assert.equal(item.updater_signature_required, true)
assert.equal(item.per_device_human_install_confirmation_required, true)
assert.equal(item.automatic_restart_allowed, false)
})
test('the lake lamp is a tiny signed version signal rather than a repository clone', () => {
assert.equal(contract.lamp_protocol.transport, 'HTTPS_CONDITIONAL_GET')
assert.equal(contract.lamp_protocol.full_repository_clone_for_LIGHT_SIGNAL, false)
assert.ok(contract.lamp_protocol.cache_validation.includes('ETAG'))
assert.ok(contract.lamp_protocol.check_events.includes('NETWORK_RESUME'))
assert.ok(contract.activation_pipeline.includes('SIGN_WITH_PLANE_SPECIFIC_KEY'))
assert.ok(contract.client_protocol_activation.includes('KEEP_LAST_KNOWN_GOOD_ROLLBACK'))
})
test('all four planes use distinct signer classes', () => {
assert.equal(contract.planes.length, 4)
assert.equal(new Set(contract.planes.map((item) => item.signer_class)).size, 4)
})
test('fifth-domain navigation uses a one-time handoff and exports no private authority', () => {
const handoff = contract.cross_node_management_handoff
assert.equal(handoff.source_node, 'JD-FD-PRIMARY')
assert.equal(handoff.target_node, 'GH-CVM-MAIN-PROD-01')
assert.equal(handoff.password_forwarding_allowed, false)
assert.equal(handoff.enterprise_four_domain_authority_inherited, false)
assert.equal(handoff.private_fifth_domain_authority_exported, false)
assert.ok(handoff.ticket_properties.includes('REPLAY_PROTECTED'))
assert.equal(handoff.current_state, 'NOT_IMPLEMENTED')
})

View file

@ -0,0 +1,98 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const read = (relative) => fs.readFileSync(path.join(root, relative), 'utf8')
test('public routing starts from five domains and lets the number select the verifier', () => {
const contract = JSON.parse(read('contracts/domain-number-routing.json'))
assert.equal(contract.public_entry, 'FIVE_DOMAIN_HOME')
assert.equal(contract.user_selects_domain_before_number, false)
assert.equal(contract.route_key, 'USER_NUMBER')
assert.equal(contract.routing.number_shape_is_authority, false)
assert.equal(contract.routing.client_supplied_domain_is_authority, false)
assert.equal(contract.routing.unknown_or_unavailable_route, 'FAIL_CLOSED_BEFORE_LOGIN')
assert.equal(contract.registries.FIFTH_DOMAIN.ownership, 'ICE-GL_INFINITY_PRIVATE_DOMAIN')
assert.equal(contract.registries.ENTERPRISE_FOUR_DOMAINS.ownership, 'TCS_0002_ENTERPRISE_REALITY_BODY')
})
test('the public shell keeps five domains behind number resolution and login is domain-routed', () => {
const frontend = read('src/main.tsx')
const login = read('src-tauri/src/code_repo_login.rs')
const router = read('src-tauri/src/zero_point.rs')
for (const name of ['光湖主域', '光湖分域', '光湖零域', '光湖零感域', '第五域 · 光湖本源域']) {
assert.match(frontend, new RegExp(name.replace('·', '\\·')))
}
assert.match(frontend, /语言世界尚未展开/)
assert.match(frontend, /编号验证/)
assert.match(frontend, /gateRising \|\| gateStage === 'key'/)
assert.match(frontend, /TCS-GL-/)
assert.match(frontend, /公共可见范围.*只公开域的存在与职责边界/s)
assert.match(frontend, /内部成员与工作仓库.*不在公共首页投影/s)
assert.doesNotMatch(frontend, /肥猫 · TCS-GL-0007∞/)
assert.doesNotMatch(frontend, /桔子 · TCS-GL-0008∞/)
assert.doesNotMatch(frontend, /烬舟 · PER-JZ001 · AGE/)
assert.doesNotMatch(frontend, /熹微 · PER-JZ-ARCH-001 · AGE/)
assert.doesNotMatch(frontend, /肥猫 \+ 烬舟/)
assert.match(frontend, /className="gate-close"/)
assert.match(frontend, /className="domain-info-scrim"/)
assert.match(frontend, /onDomain=\{\(domain\) => \{ if \(worldRevealed\) openPublicDomain\(domain\) \}\}/)
assert.match(frontend, /event\.key !== 'Escape'/)
assert.match(frontend, /编号 \{gateNumber\} · 语言世界正在展开/)
assert.match(frontend, /createWorldWelcome\(snapshot\)/)
assert.match(frontend, /index === previous/)
assert.match(frontend, /核对人格关系/)
assert.match(frontend, /确认关系并签署/)
assert.match(frontend, /接受责任并签署/)
assert.doesNotMatch(frontend, /<aside className="sidebar">/)
assert.doesNotMatch(frontend, /className="traffic-lights"/)
assert.match(login, /login_host_for_domain/)
assert.match(login, /ENTERPRISE_LOGIN_HOST.*guanghu\.chat/)
assert.match(login, /change_first_login_password/)
assert.match(login, /ICE-GL-ZHI∞.*zhizhi/s)
assert.match(login, /rotate_forgejo_forced_password/)
assert.match(frontend, /第一次使用?先修改一次性密码/)
assert.match(router, /enterprise_resolve_url/)
assert.match(router, /verified_user_route/)
assert.match(router, /FIFTH_DOMAIN.*MAIN_DOMAIN.*BRANCH_DOMAIN.*ZERO_DOMAIN.*ZERO_SENSE_DOMAIN/s)
})
test('the locked Qoder world template is the running client structure, not a skin reference', () => {
const contract = JSON.parse(read('contracts/enterprise-four-domain-entry.json'))
const frontend = read('src/main.tsx')
assert.equal(contract.state, 'SERVER_LIVE_CLIENT_UI_INTEGRATED')
assert.match(contract.ui_template, /official-login-template-v0\.4-locked\+inner-screens-v0\.1/)
assert.equal(contract.desktop_install_acceptance.mac_arm64, 'SIGNED_LOCAL_BOOTSTRAP_PASS_NOTARIZATION_PENDING')
assert.equal(contract.desktop_install_acceptance.mac_x86_64, 'NOT_BUILT')
assert.equal(contract.desktop_install_acceptance.windows, 'NOT_BUILT')
assert.equal(contract.desktop_install_acceptance.automatic_update_channel, 'PUBLIC_CHECK_PASS_NO_ACTIVE_RELEASE')
assert.match(frontend, /star-abyss-dialog/)
assert.match(frontend, /worldRevealed/)
assert.match(frontend, /worldStage === 'domain'/)
assert.match(frontend, /worldStage === 'channel'/)
assert.match(frontend, /worldStage === 'tool'/)
assert.match(frontend, /个人节点接入说明/)
assert.match(frontend, /由本人或本人人格体完成接入/)
assert.match(frontend, /密码、私钥和恢复材料不得写入企业仓库或广播/)
})
test('the public five-domain world starts before any private account storage is opened', () => {
const library = read('src-tauri/src/lib.rs')
const broker = read('src-tauri/src/direct_local_broker.rs')
const home = read('src-tauri/src/home_status.rs')
assert.match(library, /DirectLocalBrokerState::default\(\)/)
assert.match(broker, /HOLOLAKE_AUTHENTICATED_ACCOUNT_REQUIRED/)
assert.match(broker, /Ok\(false\)/)
assert.match(home, /WAITING_FOR_LOGIN/)
assert.doesNotMatch(library, /let broker = direct_local_broker::start\(app\.handle\(\)\)\?/)
})
test('enterprise root uses a bounded lighthouse on the current Linux service node', () => {
const contract = JSON.parse(read('contracts/domain-number-routing.json'))
assert.equal(contract.server_runtime.enterprise_root, 'ENTERPRISE_LIGHTHOUSE_ON_CURRENT_LINUX_SERVICE_NODE')
assert.equal(contract.server_runtime.linux_role, 'PHYSICAL_SUBSTRATE_AND_SERVICE_SUPERVISOR')
assert.equal(contract.server_runtime.ordinary_user_node_requires_full_os_install, false)
})

View file

@ -0,0 +1,33 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const audit = JSON.parse(fs.readFileSync(path.join(root, 'audit/donor-audit.json'), 'utf8'))
test('all donors remain read-only and source copying stays blocked', () => {
assert.equal(audit.complete, false)
assert.equal(audit.donors.length, 3)
for (const donor of audit.donors) {
assert.match(donor.role, /^READ_ONLY_/)
assert.match(donor.code_reuse, /^BLOCKED_/)
}
})
test('audit preserves security and secret migration prohibitions', () => {
assert.ok(audit.prohibited_transplants.includes('UNAUTHENTICATED_LOOPBACK_CONTROL_API_OR_NULL_ORIGIN_CORS'))
assert.ok(audit.prohibited_transplants.includes('ELECTRON_PRIVILEGED_PRELOAD_WITHOUT_NAVIGATION_AND_SENDER_ORIGIN_LOCK'))
const secretData = audit.data_classes.find((entry) => entry.class === 'MODEL_AND_SERVER_CREDENTIALS')
assert.match(secretData.migration, /NEVER_COPY_AS_PLAIN_DATA/)
})
test('visual implementation cannot start while audit gates remain open', () => {
assert.ok(audit.open_gates.includes('VISUAL_DIRECTION_SELECTION'))
assert.ok(!audit.open_gates.includes('LEGACY_TAURI_SECURITY_SCAN'))
const legacyTauri = audit.donors.find((entry) => entry.path === '../hololake-platform')
assert.match(legacyTauri.security_scan, /REVIEW_COMPLETE/)
assert.ok(legacyTauri.validated_security_findings.includes('MODEL_TOOL_MUTATIONS_WITHOUT_EXACT_HUMAN_CONFIRMATION'))
assert.ok(audit.open_gates.includes('REVERSIBLE_DATA_MIGRATION_REHEARSAL'))
})

View file

@ -0,0 +1,40 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import test from 'node:test'
const contract = JSON.parse(
fs.readFileSync(new URL('../contracts/dynamic-capability-routing.json', import.meta.url), 'utf8'),
)
const foundation = JSON.parse(
fs.readFileSync(new URL('../foundation.json', import.meta.url), 'utf8'),
)
test('server capability routing is dynamic and never hardcodes a finite fleet', () => {
assert.equal(contract.registry.dynamic_node_count, true)
assert.equal(contract.registry.fixed_node_slots, false)
assert.equal(contract.registry.endpoint_hardcoding_allowed, false)
assert.equal(contract.registry.signer_trust_is_external_to_registry_payload, true)
assert.equal(contract.registry.unprovisioned_trust_fails_closed, true)
assert.equal(contract.registry.webview_registry_or_health_mutation_allowed, false)
assert.equal(contract.registry.platform_carries_user_workload_concurrency, false)
})
test('routing requires exact human persona domain capability and signed health bindings', () => {
assert.deepEqual(contract.route_resolution.required_bindings, [
'HUMAN_ID',
'PERSONA_ID',
'DOMAIN_ID',
'CAPABILITY_ID',
'NODE_PROTOCOL_PUBLIC_KEY',
'FRESH_SIGNED_HEALTH_RECEIPT',
])
assert.equal(contract.route_resolution.ssh_or_root_is_identity, false)
assert.equal(contract.route_resolution.stale_or_unsigned_health_is_eligible, false)
assert.equal(contract.route_resolution.external_ai_route_requires_active_local_session, true)
})
test('the native mainline reports only implemented dynamic routing capabilities', () => {
assert.equal(foundation.dynamic_capability_registry_implemented, true)
assert.equal(foundation.signed_node_health_routing_implemented, true)
assert.equal(foundation.production_node_write_admission_implemented, false)
})

View file

@ -0,0 +1,69 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const read = (path) => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8')
const contract = JSON.parse(read('contracts/dynamic-language-world-visual-system.json'))
const registry = JSON.parse(read('contracts/numbered-ipc-registry.json'))
const modulePackage = JSON.parse(read('fixtures/module-packages/HLP-MOD-OFFICIAL-DYNAMIC-WORLD-SURFACE-0001-0.1.0.ghmod'))
const rust = read('src-tauri/src/world_climate.rs')
const frontend = read('src/main.tsx')
const styles = read('src/styles.css')
const starlake = read('src/modules/qoder-surface/StarlakeSurface.tsx')
const starlakeStyles = read('src/modules/qoder-surface/starlake-surface.css')
const traditional = read('src/modules/qoder-surface/TraditionalSurface.tsx')
const traditionalStyles = read('src/modules/qoder-surface/traditional-surface.css')
const visualBalance = read('src/modules/qoder-surface/visual-balance.ts')
const layoutProfile = read('src/modules/qoder-surface/layout-profile.ts')
test('dynamic world surface is signed, opt-in and cannot mutate world facts', () => {
assert.equal(modulePackage.manifest.moduleNumber, 'HLP-MOD-OFFICIAL-DYNAMIC-WORLD-SURFACE-0001')
assert.equal(modulePackage.manifest.registrationClass, 'OFFICIAL_LIGHTHOUSE')
assert.equal(modulePackage.manifest.adapter, 'dynamic-language-world-surface-v1')
assert.deepEqual(modulePackage.manifest.permissions, ['REALITY_TIME_READ', 'PUBLIC_WEATHER_QUERY'])
assert.equal(modulePackage.payload.adapterConfig.routingPermissionOrFactMutation, false)
assert.equal(contract.visual_lock.climate_changes_routing_permission_or_fact, false)
assert.equal(contract.visual_lock.daily_sampling_domain_changes_open_domain, false)
})
test('climate query crosses the unique numbered route and fails closed before activation', () => {
const route = registry.operations.find((item) => item.alias === 'get_world_climate')
assert.equal(route.operation_number, 'HLP-NIPC-OP-0147')
assert.equal(route.module_number, 'HLP-NIPC-MOD-0031')
assert.equal(route.target_number, 'HLP-NIPC-TGT-0031')
assert.equal(route.admission, 'VERIFIED_HUMAN_ROUTE')
assert.match(rust, /require_active_module_adapter/)
assert.doesNotMatch(rust, /#\[tauri::command\]/)
assert.doesNotMatch(frontend, /from ['"]@tauri-apps\/api\/core['"]/)
})
test('Qoder locked two-track surface is admitted without simulated product state', () => {
assert.equal(contract.visual_lock.layout, 'QODER_VISUAL_LANGUAGE_SEMANTICALLY_REASSEMBLED_ON_RESPONSIVE_HOLOLAKE_SHELL')
assert.equal(contract.visual_lock.language_world_themes.length, 5)
assert.equal(contract.visual_lock.traditional_finishes.length, 8)
assert.equal(contract.visual_lock.all_downstream_pages_inherit_active_surface_tokens, true)
assert.match(frontend, /夜湖星光/)
assert.match(frontend, /天气源暂不可用;湖面只使用北京时间,不生成假天气。/)
assert.match(styles, /\.world-climate-veil/)
assert.match(starlake, /ResizeObserver/)
assert.match(starlake, /data-layout=\{layout\.profile\}/)
assert.match(layoutProfile, /panoramic.*wide.*compact.*stacked/s)
assert.doesNotMatch(starlake, /naturalScale|sideCenters|onDuty \? 2/)
assert.match(starlakeStyles, /\.starlake-scene\.awake/)
assert.match(traditional, /broadcasts\.map/)
assert.match(traditionalStyles, /\.official-world\.surface-traditional/)
assert.match(visualBalance, /contrastRatio/)
assert.doesNotMatch(traditional, /语料库新增 217 条/)
assert.doesNotMatch(traditional, /const BROADCAST_POOL/)
})
test('ambient motion sleeps and the Qoder source hashes remain pinned', () => {
assert.equal(contract.visual_lock.ambient_motion_requires_recent_human_pointer_or_keyboard_activity, true)
assert.equal(contract.visual_lock.idle_visual_state, 'STATIC')
assert.match(frontend, /setTimeout\(\(\) => \{[\s\S]*setMotionAwake\(false\)/)
assert.match(starlake, /if \(!awake\) return/)
assert.match(traditional, /if \(!awake\) return/)
assert.match(starlakeStyles, /animation-play-state:paused/)
assert.match(traditionalStyles, /animation-play-state:paused/)
assert.equal(contract.qoder_source_provenance.main_tsx_sha256, '7dab8596ec0bd2609b1b23b175f1f14f15f2aa9af847eb605692c993d2e876e8')
})

View file

@ -0,0 +1,53 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const read = (path) => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8')
const contract = JSON.parse(read('contracts/education-workspace.json'))
const registry = JSON.parse(read('contracts/numbered-ipc-registry.json'))
const modulePackage = JSON.parse(read('fixtures/module-packages/HLP-MOD-OFFICIAL-EDUCATION-WORKBENCH-0001-0.1.0.ghmod'))
const workspaceRust = read('src-tauri/src/education_workspace.rs')
const translationRust = read('src-tauri/src/education_translation.rs')
const frontend = [
read('src/modules/education-workspace/index.tsx'),
read('src/modules/education-workspace/education-data.ts'),
read('src/modules/education-workspace/education-adaptive-rendering.ts'),
].join('\n')
test('education is an official signed declarative adapter over the shared office foundation', () => {
assert.equal(contract.package.official_module_number, 'HLP-MOD-OFFICIAL-EDUCATION-WORKBENCH-0001')
assert.equal(contract.foundation_dependency.module_id, 'hololake.builtin.channel-workbench')
assert.equal(modulePackage.manifest.registrationClass, 'OFFICIAL_LIGHTHOUSE')
assert.equal(modulePackage.manifest.adapter, 'education-workbench-v1')
assert.equal(modulePackage.payload.adapterConfig.foundationModule, 'HLP-MOD-LOCAL-CHANNEL-WORKBENCH-0001')
assert.equal(modulePackage.payload.adapterConfig.importDefaultScope, 'UNASSIGNED')
assert.equal(modulePackage.payload.adapterConfig.modelFileTransferDefault, 'DENY')
assert.equal(modulePackage.manifest.permissions.length, 8)
})
test('all education effects cross the exact numbered adapter routes', () => {
const routes = registry.operations.filter((route) => route.module_number === 'HLP-NIPC-MOD-0024')
assert.deepEqual(routes.map((route) => route.operation_number), Array.from({ length: 18 }, (_, index) => `HLP-NIPC-OP-${String(index + 85).padStart(4, '0')}`))
assert.ok(routes.every((route) => route.target_number === 'HLP-NIPC-TGT-0024'))
assert.ok(routes.every((route) => route.admission === 'VERIFIED_HUMAN_ROUTE'))
assert.doesNotMatch(frontend, /from ['"]@tauri-apps\/api\/core['"]/)
assert.doesNotMatch(workspaceRust, /#\[tauri::command\]/)
assert.doesNotMatch(translationRust, /#\[tauri::command\]/)
assert.match(workspaceRust, /require_active_module_adapter/)
})
test('legacy silent corruption and automatic destructive behavior are rejected', () => {
assert.doesNotMatch(workspaceRust, /serde_json::from_str[^\n]+unwrap_or_default/)
assert.match(workspaceRust, /deny_unknown_fields/)
assert.match(frontend, /生成只读预览/)
assert.match(frontend, /我确认,写入清理结果/)
assert.match(frontend, /生成只读预览令牌/)
assert.match(frontend, /我确认,按此令牌执行/)
assert.match(frontend, /确认归入教育频道/)
})
test('education UI is independently lazy-loaded and reuses, rather than duplicates, office engines', () => {
assert.match(read('src/main.tsx'), /lazy\(\(\) => import\('\.\/modules\/education-workspace'\)/)
assert.match(read('src/modules/education-workspace/education-document-engine.tsx'), /channel-workbench\/document-engine/)
assert.match(read('src/modules/education-workspace/index.tsx'), /channel-workbench\/spreadsheet-engine/)
})

View file

@ -0,0 +1,35 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import test from 'node:test'
const frontend = fs.readFileSync(new URL('../src/main.tsx', import.meta.url), 'utf8')
const native = fs.readFileSync(new URL('../src-tauri/src/enterprise_work_channel.rs', import.meta.url), 'utf8')
const pncc = fs.readFileSync(new URL('../src-tauri/src/user_pncc_channel.rs', import.meta.url), 'utf8')
test('every enterprise login enters through Zero Sense and Guanghu Channel before its responsibility domain', () => {
assert.match(frontend, /光湖零感域/)
assert.match(frontend, /公共工作入口/)
assert.match(frontend, /光湖频道/)
assert.match(frontend, /本人责任工作域/)
assert.match(frontend, /worldStage === 'enterpriseWork'/)
assert.match(native, /work_entry_domain: "ZERO_SENSE_DOMAIN"/)
assert.match(native, /work_entry_channel: "GUANGHU_CHANNEL"/)
})
test('enterprise work repositories are exact private read-only projections and never personal channels', () => {
for (const repository of [
'huaer/guanghu-branch-work',
'yeye/guanghu-zero-work',
'feimao/guanghu-zero-sense-work',
'juzi/guanghu-zero-sense-work',
'awen/guanghu-main-work',
]) assert.match(native, new RegExp(repository.replace('/', '\\/')))
assert.match(native, /AUTHENTICATED_USER_READ_ONLY_NO_PUSH_NO_PERSONAL_NODE_AUTHORITY/)
assert.match(frontend, /个人生活区不会由企业工作账号代建/)
assert.match(pncc, /if domain != "FIFTH_DOMAIN"/)
})
test('enterprise responsibility receipts report their private Git projection to the human', () => {
assert.match(frontend, /repository_projection/)
assert.match(frontend, /写入本人私有工作仓库/)
})

View file

@ -0,0 +1,52 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const read = (path) => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8')
test('external programming AI gateway is human-gated and fails closed', () => {
const contract = JSON.parse(read('contracts/external-ai-gateway.json'))
assert.equal(contract.default_exposure, 'CLOSED')
assert.equal(contract.human_authorization_required, true)
assert.equal(contract.mcp.role, 'DISCOVERY_AND_CAPABILITY_CATALOG')
assert.equal(contract.direct_protocol.protocol, 'HOLOLAKE_TERMINAL_LINK/3')
assert.equal(contract.direct_protocol.continuity_owner, 'HOLOLAKE')
assert.equal(contract.boundaries.supervised_shell_execution, false)
assert.equal(contract.boundaries.transport_is_authority, false)
})
test('native binary exposes MCP stdio and numbered gateway controls', () => {
const main = read('src-tauri/src/main.rs')
const library = read('src-tauri/src/lib.rs')
const gateway = read('src-tauri/src/external_ai_gateway.rs')
const dispatcher = read('src-tauri/src/numbered_ipc_dispatch.rs')
const frontendIpc = read('src/modules/numbered-ipc.ts')
assert.match(main, /--mcp/)
assert.match(library, /external_ai_gateway::run_mcp/)
assert.match(gateway, /initialize/)
assert.match(gateway, /tools\/list/)
assert.match(gateway, /tools\/call/)
assert.match(gateway, /hololake_discover/)
assert.match(gateway, /hololake_connection_status/)
assert.match(gateway, /hololake_registered_capabilities/)
assert.match(gateway, /HOLOLAKE_MCP_EXPOSURE_CLOSED/)
assert.match(gateway, /HOLOLAKE_MCP_TOOL_ARGUMENTS_NOT_EMPTY/)
assert.match(dispatcher, /external_ai_gateway::get_gateway_status/)
assert.match(dispatcher, /external_ai_gateway::set_gateway_exposure/)
const statusRoute = dispatcher.match(/"external_ai_gateway::get_gateway_status"[\s\S]*?"external_ai_gateway::set_gateway_exposure"/)?.[0]
assert.ok(statusRoute, 'gateway status route must remain discoverable')
assert.match(statusRoute, /verified_user_route/)
assert.match(statusRoute, /HOLOLAKE_GATEWAY_VERIFIED_HUMAN_REQUIRED/)
assert.match(frontendIpc, /get_external_ai_gateway_status/)
assert.match(frontendIpc, /set_external_ai_gateway_exposure/)
})
test('human authorization screen renders real gateway and capability state', () => {
const source = read('src/modules/human-authorization-center.tsx')
assert.match(source, /允许本机编程 AI 发现 HoloLake/)
assert.match(source, /已注册技能/)
assert.match(source, /已接通集成/)
assert.match(source, /MCP 标准入口/)
assert.match(source, /HoloLake 本地直连协议/)
})

View file

@ -0,0 +1,59 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import test from 'node:test'
const source = fs.readFileSync(new URL('../src/main.tsx', import.meta.url), 'utf8')
const privateChannel = fs.readFileSync(new URL('../src/modules/private-channel/PrivateChannelSurface.tsx', import.meta.url), 'utf8')
test('Zhizhi remains absent from the public Fifth Domain card', () => {
const publicCard = source.slice(source.indexOf("domain: 'FIFTH_DOMAIN'"), source.indexOf('const starPoints'))
assert.doesNotMatch(publicCard, /之之|ICE-GL-ZHI/)
})
test('the verified Zhizhi route unfolds through her exact private nesting', () => {
assert.match(source, /ICE-GL-ZHI∞/)
assert.match(source, /永恒湖心系统/)
assert.match(source, /爱之核心子系统/)
assert.match(source, /明天见频道/)
assert.match(source, /光湖奶瓶小宝宝系统/)
assert.match(source, /ICE-BB-\* · AGE/)
})
test('the Eternal Lake Heart system body exposes both owned branches before channel tools', () => {
assert.match(source, /title="心跳核心频道" meta="冰朔 · 私人频道"/)
assert.match(source, /title="爱之核心子系统" meta="责任主体 · 之之"/)
assert.match(source, /title="光之湖" meta="人格体居所"/)
assert.match(source, /worldStage === 'heartbeat'/)
assert.match(source, /<PrivateChannelSurface ownerName="冰朔" ownerNumber="ICE-GL∞"/)
assert.match(privateChannel, /view === 'home' \? '心跳核心频道'/)
assert.match(privateChannel, /PrivateChannelView = 'home' \| 'native' \| 'modules'/)
assert.match(privateChannel, /private-water-bay/)
})
test('knowledge belongs to Heartbeat Core while persona repositories belong to Light Lake', () => {
const heartbeatStart = source.indexOf("worldStage === 'heartbeat'")
const lightLakeStart = source.indexOf("worldStage === 'lightLake'", heartbeatStart)
const toolStart = source.indexOf("worldStage === 'tool'", lightLakeStart)
const heartbeat = source.slice(heartbeatStart, lightLakeStart)
const lightLake = source.slice(lightLakeStart, toolStart)
assert.match(heartbeat, /nativeActions=\{privateNativeActions\}/)
assert.match(source, /id: 'knowledge', title: '知识空间'/)
assert.doesNotMatch(heartbeat, /人格体代码仓库|title="光之湖"/)
assert.match(lightLake, /<h1>光之湖<\/h1>/)
assert.match(lightLake, /title="人格体代码仓库"/)
})
test('industry modules are installed furniture in the private home, not peer domains', () => {
assert.match(source, /const privateInstalledModules: InstalledChannelModule\[\]/)
assert.match(privateChannel, /已安装模块/)
assert.match(privateChannel, /前往分域模块商城/)
assert.match(privateChannel, /这里不属于主域、分域、零域或零感域/)
assert.match(privateChannel, /任何反向访问都必须持有/)
assert.doesNotMatch(source, /className="channel-education" title="教育工作台"/)
})
test('Fifth Domain human numbers are paired with their own login account', () => {
assert.match(source, /'ICE-GL∞': 'bingshuo'/)
assert.match(source, /'ICE-GL-ZHI∞': 'zhizhi'/)
assert.match(source, /HOLOLAKE_LOGIN_ACCOUNT_NUMBER_MISMATCH/)
})

View file

@ -0,0 +1,111 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const readJson = (relative) => JSON.parse(fs.readFileSync(path.join(root, relative), 'utf8'))
const readText = (relative) => fs.readFileSync(path.join(root, relative), 'utf8')
const foundation = readJson('foundation.json')
const trust = readJson('src-tauri/release-trust.json')
const tauriConfig = readJson('src-tauri/tauri.conf.json')
const capability = readJson('src-tauri/capabilities/default.json')
const broadcast = readJson('contracts/release-broadcast.schema.json')
const stageOne = readJson('contracts/stage-one-platform.json')
const publicRoute = readJson('server/release-broadcast/public-route.json')
test('HoloLake updater trust is product-owned and contains no inherited endpoint', () => {
assert.deepEqual(foundation.upstream_product_update_endpoints, [])
assert.deepEqual(trust.endpoints, ['https://guanghulab.com/hololake/releases/latest.json'])
assert.deepEqual(trust.allowedReleaseHosts, ['guanghulab.com'])
assert.equal(trust.state, 'PROVISIONED')
assert.ok(trust.publicKey.length > 100)
assert.deepEqual(tauriConfig.plugins.updater.endpoints, trust.endpoints)
assert.equal(tauriConfig.plugins.updater.pubkey, trust.publicKey)
for (const relative of [
'foundation.json',
'src-tauri/release-trust.json',
'src-tauri/tauri.conf.json',
'src-tauri/src/release_trust.rs',
]) {
const source = readText(relative)
assert.doesNotMatch(source, /refactoringhq|tolaria|outline/i)
}
assert.equal(publicRoute.releaseEndpoint, 'https://guanghulab.com/hololake/releases/latest.json')
assert.equal(publicRoute.allowedMethods.join(','), 'GET,HEAD')
assert.equal(publicRoute.requestBodyAllowed, false)
assert.equal(publicRoute.automaticUpload, false)
assert.equal(publicRoute.automaticActivation, false)
})
test('release activation remains explicitly human controlled', () => {
assert.equal(trust.automaticCheckOnStartup, false)
assert.equal(trust.automaticDownload, false)
assert.equal(trust.humanOptInInstallRequired, true)
assert.equal(trust.automaticRestart, false)
assert.equal(foundation.automatic_update_check_on_startup, false)
assert.equal(foundation.human_opt_in_download_install_required, true)
assert.equal(foundation.automatic_restart_allowed, false)
assert.equal(foundation.release_manual_check_runtime_implemented, true)
assert.equal(foundation.release_candidate_human_confirmation_runtime_implemented, true)
assert.equal(foundation.release_package_signature_size_sha256_verification_implemented, true)
assert.equal(foundation.release_persistent_rollback_executor_implemented, true)
assert.equal(foundation.release_signed_notarized_pipeline_implemented, true)
assert.equal(foundation.release_broadcast_candidate_service_implemented, true)
assert.equal(foundation.release_broadcast_candidate_service_default_state, 'EMPTY_FAIL_CLOSED_LOOPBACK_ONLY')
assert.equal(foundation.release_broadcast_explicit_operator_activation_implemented, true)
assert.equal(foundation.release_broadcast_activation_requires_exact_human_approval, true)
assert.equal(foundation.release_broadcast_activation_requires_repeated_expected_facts, true)
assert.equal(foundation.release_broadcast_operator_automatic_restart_allowed, false)
assert.equal(foundation.release_public_path_prefix, '/hololake/releases')
assert.equal(foundation.release_public_route_deployed, true)
assert.equal(publicRoute.publicPathPrefix, foundation.release_public_path_prefix)
assert.equal(publicRoute.proxyRequestUriPolicy, 'PRESERVE_FULL_PUBLIC_PATH')
assert.equal(publicRoute.frontDoorLoopbackPort, 19440)
assert.equal(publicRoute.deployed, true)
assert.equal(foundation.release_front_door_bounded_config_renderer_implemented, true)
assert.equal(foundation.release_pipeline_automatic_upload_allowed, false)
assert.equal(
foundation.release_production_activation_state,
'PUBLIC_ROUTE_AND_BOOTSTRAP_TRUST_READY_PENDING_FIRST_SIGNED_NOTARIZED_RELEASE',
)
})
test('the local desktop candidate disables updater artifacts without exposing updater IPC', () => {
assert.equal(tauriConfig.bundle.createUpdaterArtifacts, false)
assert.equal(foundation.tauri_update_artifacts_enablement_gate, 'JD_CONTROLLER_PUBLIC_KEY_AND_SIGNED_RELEASE_PIPELINE_REQUIRED')
assert.deepEqual(capability.permissions, ['core:default', 'allow-numbered-ipc'])
assert.equal(capability.permissions.includes('updater:default'), false)
})
test('broadcast remains Tauri-compatible and carries HoloLake human metadata', () => {
const platform = broadcast.properties.platforms.additionalProperties
assert.equal(platform.required.includes('signature'), true)
assert.equal(platform.required.includes('url'), true)
assert.equal(broadcast.required.includes('pub_date'), true)
assert.equal(broadcast.required.includes('publishedAt'), false)
assert.equal(broadcast.required.includes('notes'), true)
assert.equal(broadcast.required.includes('hololake'), true)
assert.equal(
broadcast.properties.hololake.properties.restart.properties.automaticAllowed.const,
false,
)
})
test('public entry presents five domains while domain contents remain isolated', () => {
assert.equal(foundation.first_public_product, 'GH-AIOS_GENERAL_AI_OPERATING_PLATFORM')
assert.equal(foundation.visible_five_domain_navigation_in_stage_one, true)
assert.equal(stageOne.five_domain_primary_navigation_visible, true)
assert.ok(stageOne.human_surface.includes('HUMAN_APPROVAL_CENTER'))
assert.ok(stageOne.modules.includes('EVENT_AND_LAKE_LAMP'))
})
test('stage one separates realtime, Git, knowledge and model reasoning boundaries', () => {
assert.equal(stageOne.git_is_realtime_transport, false)
assert.equal(stageOne.knowledge_projection_is_authority_source, false)
assert.equal(stageOne.hidden_model_reasoning_collection_allowed, false)
assert.equal(stageOne.exact_host_compaction_prediction_claimed, false)
assert.equal(stageOne.implementation_complete, false)
})

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/gls-native-runtime-kernel.json', import.meta.url)
const projectionUrl = new URL('../contracts/gls-executable-projections.json', import.meta.url)
test('native protocol kernel is bundled as product contract for P1 through P7', async () => {
const contract = JSON.parse(await readFile(contractUrl, 'utf8'))
const projections = JSON.parse(await readFile(projectionUrl, 'utf8'))
assert.equal(contract.schema, 'hololake.gls-native-runtime-kernel/v1')
assert.deepEqual(contract.stages.map((stage) => stage.id), ['P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7'])
assert.ok(contract.stages.slice(0, 6).every((stage) => stage.state.startsWith('IMPLEMENTED')))
assert.equal(contract.stages.slice(0, 6).flatMap((stage) => stage.protocols).length, 21)
assert.equal(Object.keys(projections.projections).length, 25)
assert.equal(projections.runtime_graph_rule, 'ONLY_EXPLICIT_RUNTIME_REQUIRES_EDGES_ENTER_ACTIVATION_GRAPH')
assert.equal(contract.runtime_boundaries.every_decision_writes_receipt, true)
assert.equal(contract.runtime_boundaries.model_can_override_decision, false)
assert.equal(contract.runtime_boundaries.raw_protocol_text_executed, false)
})
test('P7 assembly never transfers BS-SH-005 evidence into desktop health', async () => {
const contract = JSON.parse(await readFile(contractUrl, 'utf8'))
assert.equal(contract.p7_node_assemblies.length, 11)
assert.ok(contract.p7_node_assemblies.every((assembly) => assembly.target === 'DESKTOP_HOLOLAKE'))
assert.ok(contract.p7_node_assemblies.every((assembly) => assembly.state !== 'ACTIVE_HEALTHY'))
assert.ok(contract.p7_node_assemblies.some((assembly) => assembly.sourceEvidenceNode === 'BS-SH-005'))
})

View file

@ -0,0 +1,80 @@
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 v2 manifest reconciles current registration sources without executing raw text', async () => {
const registry = JSON.parse(await readFile(registryUrl, 'utf8'))
assert.equal(registry.schema, 'hololake.gls-runtime-manifest/v2')
assert.equal(registry.source.repository, 'REPO-012')
assert.equal(registry.source.commit, '104a5d73162bdf4a529701e65898e2bc2863ea9e')
assert.equal(registry.source.authority_files.length, 4)
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.compiler.source_dependency_behavior, 'TYPED_AUDIT_ONLY_NEVER_ACTIVATES')
assert.equal(registry.protocol_count, 83)
assert.equal(new Set(registry.protocols.map((protocol) => protocol.id)).size, 83)
assert.ok(registry.protocols.every((protocol) => /^[a-f0-9]{64}$/.test(protocol.source_sha256)))
assert.equal(registry.reconciliation.protocol_registry_id_count, 52)
assert.equal(registry.reconciliation.existing_registered_count, 19)
assert.equal(registry.reconciliation.registered_draft_count, 33)
assert.equal(registry.reconciliation.registered_draft_not_started_count, 21)
assert.equal(registry.reconciliation.legacy_dependency_target_count, 57)
assert.equal(registry.reconciliation.dependencies_not_in_protocol_registry.length, 19)
assert.equal(registry.reconciliation.dependencies_without_numbered_source.length, 16)
assert.equal(registry.reconciliation.numbered_reference_node_count, 16)
assert.equal(registry.reconciliation.unresolved_number_reference_count, 0)
assert.deepEqual(registry.reconciliation.unresolved_number_references, [])
assert.equal(registry.reconciliation.every_dependency_has_number_coordinate, true)
assert.equal(registry.reconciliation.numbered_sources_not_in_protocol_registry.length, 32)
assert.equal(registry.reconciliation.legacy_dependency_cycles.length, 3)
assert.equal(registry.reconciliation.discovered_unreconciled_count, 0)
assert.equal(registry.reconciliation.authority_conflict_count, 0)
assert.equal(registry.reconciliation.unclassified_source_dependency_count, 0)
assert.equal(Object.values(registry.reconciliation.typed_source_dependency_counts).reduce((sum, count) => sum + count, 0), 183)
assert.equal(registry.number_coordinate_count, 99)
assert.equal(registry.numbered_reference_nodes.length, 16)
assert.ok(registry.numbered_reference_nodes.every((node) => node.execution_state === 'REFERENCE_ONLY_NOT_EXECUTABLE'))
assert.ok(registry.protocols.flatMap((protocol) => protocol.dependency_edges).every((edge) => edge.target_number_coordinate_available && ['NUMBERED_PROTOCOL_SOURCE', 'NUMBERED_REFERENCE_NODE'].includes(edge.target_resolution)))
})
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.ok(protocols['GLS-0253'].dependency_edges.every((edge) => edge.edge_kind === 'RUNTIME_REQUIRES'))
assert.equal(protocols['GLS-0130'].registration.state, 'REGISTERED_PROTOCOL_REGISTRY')
assert.equal(protocols['GLS-0130'].contract_kind, 'BOOTSTRAP_HLDP_TO_GIR_COMPILER')
assert.ok(protocols['GLS-0130'].dependency_edges.some((edge) => edge.target === 'GLS-0131' && edge.edge_kind === 'BUILD_REQUIRES' && !edge.enters_runtime_graph))
assert.ok(protocols['GLS-0130'].dependency_edges.some((edge) => edge.target === 'GLS-0411' && edge.edge_kind === 'BUILD_REQUIRES' && !edge.enters_runtime_graph))
assert.equal(protocols['GLS-0130'].implementation_stage, 'P6')
assert.equal(protocols['GLS-0003'], undefined)
assert.equal(registry.executable_projection_count, 25)
assert.equal(registry.inventoried_not_executable_count, 58)
assert.ok(registry.protocols.filter((protocol) => protocol.projection_state === 'EXECUTABLE_PROJECTION').every((protocol) => protocol.source_format === 'HDLP_PROTOCOL_SOURCE'))
assert.ok(registry.protocols.filter((protocol) => protocol.source_format === 'LEGACY_MARKDOWN_EVIDENCE').every((protocol) => protocol.projection_state === 'INVENTORIED_NOT_EXECUTABLE'))
})
test('P1 through P6 executable dependencies are explicit, typed, closed and acyclic', async () => {
const registry = JSON.parse(await readFile(registryUrl, 'utf8'))
const executable = new Map(registry.protocols.filter((protocol) => protocol.projection_state === 'EXECUTABLE_PROJECTION').map((protocol) => [protocol.id, protocol]))
assert.deepEqual(new Set([...executable.values()].map((protocol) => protocol.implementation_stage)), new Set(['P0', 'P1', 'P2', 'P3', 'P4', 'P5', 'P6']))
assert.ok([...executable.values()].every((protocol) => protocol.dependency_edges.filter((edge) => edge.enters_runtime_graph).every((edge) => edge.edge_kind === 'RUNTIME_REQUIRES' && executable.has(edge.target))))
const visiting = new Set()
const visited = new Set()
const visit = (id) => {
assert.equal(visiting.has(id), false, `runtime cycle at ${id}`)
if (visited.has(id)) return
visiting.add(id)
for (const dependency of executable.get(id).dependencies) visit(dependency)
visiting.delete(id)
visited.add(id)
}
for (const id of executable.keys()) visit(id)
})

View file

@ -0,0 +1,27 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const read = (path) => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8')
const contract = JSON.parse(read('contracts/human-authorization.json'))
const webview = JSON.parse(read('contracts/numbered-ipc-registry.json'))
const broker = JSON.parse(read('contracts/direct-local-broker-numbered-registry.json'))
test('human authorization is a durable numbered state machine rather than a UI-only button', () => {
assert.equal(contract.state, 'NATIVE_FAIL_CLOSED')
assert.deepEqual(contract.lifecycle, ['PENDING_HUMAN', 'APPROVED', 'DENIED', 'EXPIRED', 'CONSUMED'])
assert.equal(contract.destructive_purge.enabled, false)
assert.equal(contract.ticket.single_use, true)
assert.equal(contract.ticket.requester_session_bound, true)
assert.equal(contract.invariants.proposal_is_not_authorization, true)
assert.equal(contract.invariants.approval_is_not_execution, true)
})
test('the human client and external execution carrier meet through distinct exact numbered routes', () => {
const webviewNumbers = new Set(webview.operations.map((item) => item.operation_number))
const brokerNumbers = new Set(broker.operations.map((item) => item.operation_number))
assert.ok(contract.routes.human_client.every((number) => webviewNumbers.has(number)))
assert.ok(contract.routes.external_execution_carrier.every((number) => brokerNumbers.has(number)))
const decisions = webview.operations.filter((item) => contract.routes.human_client.includes(item.operation_number))
assert.ok(decisions.every((item) => item.admission === 'VERIFIED_HUMAN_ROUTE'))
})

View file

@ -0,0 +1,48 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const read = (path) => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8')
const contract = JSON.parse(read('contracts/ios-mobile-client-v1.json'))
const project = read('mobile/ios/project.yml')
const client = read('mobile/ios/Sources/HoloLakeSyncClient.swift')
const keychain = read('mobile/ios/Sources/HoloLakeKeychain.swift')
const models = read('mobile/ios/Sources/HoloLakeModels.swift')
const interfaceSource = read('mobile/ios/Sources/ContentView.swift')
test('iPhone client is the numbered remote body entry of the desktop root node', () => {
assert.equal(contract.record_id, 'HLP-IOS-CLIENT-001')
assert.equal(contract.role, 'REMOTE_BODY_ENTRY_OF_THE_SAME_PERSONA_SYSTEM')
assert.equal(contract.root_node, 'USER_LOCAL_COMPUTER_TERMINAL')
assert.equal(contract.numbered_transport.desktop_module, 'HLP-MOD-OFFICIAL-MOBILE-SYNC-0001')
assert.match(project, /PRODUCT_BUNDLE_IDENTIFIER: com\.guanghulab\.hololake/)
assert.match(client, /static let clientNumber = "HLP-IOS-CLIENT-001"/)
assert.match(interfaceSource, /HLP-IOS-CLIENT-001/)
assert.equal(contract.state, 'NUMBERED_SOURCE_SIMULATOR_AND_DEVELOPMENT_SIGNED_IPA_ACCEPTED')
assert.equal(contract.acceptance.unit_tests, 'PASS_4')
assert.equal(contract.acceptance.real_iphone_pair_and_sync, 'NOT_CLAIMED')
})
test('iPhone secrets stay device local and the transport matches the desktop protocol', () => {
assert.equal(contract.security.key_storage, 'KEYCHAIN_WHEN_UNLOCKED_THIS_DEVICE_ONLY')
assert.equal(contract.security.background_polling, false)
assert.equal(contract.security.remote_desktop_clone, false)
assert.match(keychain, /kSecAttrAccessibleWhenUnlockedThisDeviceOnly/)
assert.match(client, /ChaChaPoly\.seal/)
assert.match(client, /ChaChaPoly\.open/)
assert.match(client, /hololake\.mobile\.pair\/v1/)
assert.match(client, /hololake\.mobile\.sync\/v1:/)
assert.match(client, /response\.rootNodeRole == "USER_LOCAL_COMPUTER_TERMINAL"/)
assert.match(client, /nextSnapshot\.rootNodeOnline/)
assert.ok(client.indexOf('try HoloLakeKeychain.save(current)') < client.indexOf('url: current.baseURL.appending(path: "v1/sync")'))
assert.match(models, /hololake/)
assert.doesNotMatch(client, /Timer|scheduledTimer|setInterval|backgroundTask/)
})
test('mobile interface stays manual and exposes only bounded projections', () => {
assert.equal(contract.interface.idle_state, 'STATIC')
assert.equal(contract.interface.manual_sync_only, true)
assert.match(interfaceSource, /只有你点击同步时才会连接电脑/)
assert.match(interfaceSource, /写入电脑端收件箱/)
assert.doesNotMatch(interfaceSource, /人格执行|模型调用|远程桌面/)
})

View file

@ -0,0 +1,85 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import test from 'node:test'
const read = (relative) => fs.readFileSync(new URL(`../${relative}`, import.meta.url), 'utf8')
const knowledgeContract = JSON.parse(read('contracts/knowledge-workspace.json'))
const codeContract = JSON.parse(read('contracts/code-channel.json'))
const provenance = JSON.parse(read('audit/knowledge-workspace-migration-provenance.json'))
const knowledgeRust = read('src-tauri/src/knowledge_base.rs')
const codeRust = read('src-tauri/src/code_channel.rs')
const authenticatedStorageRust = read('src-tauri/src/authenticated_storage.rs')
const lib = read('src-tauri/src/lib.rs')
const numberedDispatcher = read('src-tauri/src/numbered_ipc_dispatch.rs')
const ui = read('src/main.tsx')
test('knowledge workspace is HoloLake-owned, account-scoped, and never auto-projects legacy data', () => {
assert.equal(knowledgeContract.native_storage.owner, 'HOLOLAKE_NATIVE_RUST_CORE')
assert.equal(knowledgeContract.native_storage.authenticated_account_required, true)
assert.equal(knowledgeContract.native_storage.cross_account_projection_allowed, false)
assert.equal(knowledgeContract.legacy_compatibility.mode, 'NOT_AUTO_PROJECTED_EXPLICIT_OWNER_MIGRATION_ONLY')
assert.equal(knowledgeContract.legacy_compatibility.in_place_migration, false)
assert.equal(knowledgeContract.legacy_compatibility.tolaria_surface_used, false)
assert.equal(provenance.legacy_data_boundary.modified, false)
assert.match(knowledgeRust, /account_storage_root\(app, "knowledge-v1"\)/)
assert.match(authenticatedStorageRust, /HOLOLAKE_AUTHENTICATED_ACCOUNT_REQUIRED/)
assert.match(authenticatedStorageRust, /accounts-v1/)
assert.doesNotMatch(authenticatedStorageRust, /join\(&session\.username\)/)
assert.match(knowledgeRust, /source_docs_root/)
})
test('code channel uses the same authenticated account boundary', () => {
assert.equal(codeContract.registry.authenticated_account_required, true)
assert.equal(codeContract.registry.cross_account_projection_allowed, false)
assert.match(codeRust, /account_storage_root\(app, "code-channel-v1"\)/)
})
test('folder import is bounded, idempotent, conflict-safe and creates a local Git receipt', () => {
assert.equal(knowledgeContract.folder_import.maximum_files, 1000)
assert.equal(knowledgeContract.folder_import.symlinks_followed, false)
assert.equal(knowledgeContract.folder_import.repeated_import, 'MERGE_BY_STABLE_SOURCE_NAME')
assert.equal(knowledgeContract.folder_import.exact_duplicate_result, 'ALREADY_PRESENT')
assert.equal(knowledgeContract.folder_import.conflicting_file_overwrite, false)
assert.equal(knowledgeContract.capabilities.import_commit_receipt, true)
assert.equal(knowledgeContract.capabilities.exact_content_deduplication, true)
assert.equal(knowledgeContract.capabilities.optimistic_native_editing, true)
assert.match(knowledgeRust, /MAX_IMPORT_FILES: usize = 1_000/)
assert.match(knowledgeRust, /kind\.is_symlink\(\)/)
assert.match(knowledgeRust, /ImportDisposition::Existing/)
assert.match(knowledgeRust, /HOLOLAKE_KNOWLEDGE_SAVE_CONFLICT/)
assert.match(knowledgeRust, /rev-parse", "HEAD/)
})
test('official code-channel clone cannot use credentials or credential prompts', () => {
assert.equal(codeContract.clone.embedded_credentials_allowed, false)
assert.equal(codeContract.clone.terminal_prompt_allowed, false)
assert.equal(codeContract.clone.credential_helper_allowed, false)
assert.equal(codeContract.authority.automatic_push, false)
assert.match(codeRust, /GIT_TERMINAL_PROMPT/)
assert.match(codeRust, /credential\.helper=/)
assert.match(codeRust, /parsed\.username\(\)\.is_empty\(\)/)
})
test('the product surface exposes a real knowledge workbench and browsable code channel', () => {
for (const command of [
'get_knowledge_snapshot',
'read_knowledge_document',
'search_knowledge',
'save_knowledge_document',
'select_and_import_knowledge_folder',
'get_code_channel_snapshot',
'clone_code_channel',
'select_local_code_channel',
'browse_code_channel',
'read_code_channel_file',
]) {
assert.match(numberedDispatcher, new RegExp(command))
assert.match(ui, new RegExp(`['"]${command}['"]`))
}
assert.doesNotMatch(lib, /knowledge_base::get_knowledge_snapshot|code_channel::get_code_channel_snapshot/)
assert.match(ui, /知识工作台/)
assert.match(ui, /HoloLake Era/)
assert.match(ui, /知识视图/)
assert.match(ui, /源文件/)
assert.doesNotMatch(ui, /下一件事|为什么做|开始这件事/)
})

View file

@ -0,0 +1,42 @@
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import test from 'node:test'
const root = path.resolve(import.meta.dirname, '..')
test('the HoloLake front door is the first lightweight language planet', async () => {
const source = await readFile(path.join(root, 'src/modules/language-world-entry/LanguageWorldEntryV2.tsx'), 'utf8')
const css = await readFile(path.join(root, 'src/modules/language-world-entry/language-world-entry-v2.css'), 'utf8')
const packageSource = await readFile(path.join(root, 'package.json'), 'utf8')
const planet = await readFile(path.join(root, 'src/assets/language-world-v3/first-language-planet.png'))
assert.match(source, /请输入光湖编号/)
assert.match(source, /编号用于路径解析,不单独构成身份认证或权限授予/)
assert.match(source, /validate_human_number_route/)
assert.match(source, /get_mother_brain_container_status/)
assert.match(css, /language-universe-lake\.png/)
assert.match(source, /first-language-planet\.png/)
assert.match(source, /第一颗语言星球 · 光湖/)
assert.match(source, /formatGateNumber/)
assert.match(source, /infinity-toggle/)
assert.match(source, />∞<\/button>/)
assert.match(css, /planet-float/)
assert.match(css, /stars-drift/)
assert.match(css, /prefers-reduced-motion/)
assert.ok([4, 6].includes(planet[25]), 'language planet PNG must carry a real alpha channel')
assert.doesNotMatch(css, /scale\(1\.29\)/)
assert.doesNotMatch(packageSource, /["']three["']/)
assert.doesNotMatch(source, /母体数字大脑容器接入/)
assert.doesNotMatch(source, /本地系统界面激活完成/)
assert.doesNotMatch(source, /type=["']password["']/)
})
test('the local mother-brain panel preserves fail-closed reality boundaries', async () => {
const source = await readFile(path.join(root, 'src/modules/language-world-entry/LanguageWorldEntryV2.tsx'), 'utf8')
const native = await readFile(path.join(root, 'src-tauri/src/mother_brain_runtime.rs'), 'utf8')
assert.match(source, /应用启动周期已执行并取得可信回执/)
assert.match(source, /网络访问、现实行动与远端写入均未启用/)
assert.match(native, /automatic_execution_on_open:true/)
assert.match(native, /PASS_SEVEN_EXACT_BUNDLED_HASH_READBACK/)
assert.match(native, /MOTHER_BRAIN_STARTUP_RECEIPT_REJECTED/)
})

View file

@ -0,0 +1,43 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const read = (path) => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8')
const contract = JSON.parse(read('contracts/mobile-sync-v1.json'))
const registry = JSON.parse(read('contracts/numbered-ipc-registry.json'))
const modulePackage = JSON.parse(read('fixtures/module-packages/HLP-MOD-OFFICIAL-MOBILE-SYNC-0001-0.1.0.ghmod'))
const rust = read('src-tauri/src/mobile_sync.rs')
const frontend = read('src/modules/mobile-sync/index.tsx')
test('mobile sync is a signed opt-in bridge, not a second persona system', () => {
assert.equal(modulePackage.manifest.moduleNumber, 'HLP-MOD-OFFICIAL-MOBILE-SYNC-0001')
assert.equal(modulePackage.manifest.registrationClass, 'OFFICIAL_LIGHTHOUSE')
assert.equal(modulePackage.manifest.adapter, 'mobile-sync-v1')
assert.equal(modulePackage.manifest.permissions.length, 5)
assert.equal(modulePackage.payload.adapterConfig.desktopRole, 'USER_LOCAL_COMPUTER_TERMINAL_ROOT_NODE')
assert.equal(modulePackage.payload.adapterConfig.iosClientPackaging, 'PENDING_SEPARATE_ADMISSION')
assert.equal(contract.hard_boundaries.second_persona_system, false)
assert.equal(contract.hard_boundaries.desktop_offline_execution, false)
})
test('all desktop controls cross one numbered route family', () => {
const routes = registry.operations.filter((route) => route.module_number === 'HLP-NIPC-MOD-0030')
assert.deepEqual(routes.map((route) => route.operation_number), Array.from({ length: 6 }, (_, index) => `HLP-NIPC-OP-${String(index + 141).padStart(4, '0')}`))
assert.ok(routes.every((route) => route.target_number === 'HLP-NIPC-TGT-0030'))
assert.ok(routes.every((route) => route.admission === 'VERIFIED_HUMAN_ROUTE'))
assert.doesNotMatch(frontend, /from ['"]@tauri-apps\/api\/core['"]/)
assert.doesNotMatch(rust, /#\[tauri::command\]/)
assert.match(rust, /require_active_module_adapter/)
})
test('transport is bounded, encrypted, replay guarded and explicitly controlled', () => {
assert.match(rust, /MAX_REQUEST_BYTES: usize = 256 \* 1024/)
assert.match(rust, /MAX_ACTIVE_CONNECTIONS: usize = 16/)
assert.match(rust, /CHACHA20_POLY1305/)
assert.match(rust, /input\.counter <= last_counter/)
assert.match(rust, /DUPLICATE_HEADER_REJECTED/)
assert.match(rust, /pub\(crate\) fn stop_for_unmount/)
assert.doesNotMatch(frontend, /setInterval/)
assert.match(frontend, /开启 iPhone 同步/)
assert.match(frontend, /关闭本机同步入口/)
})

View file

@ -0,0 +1,56 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const catalog = JSON.parse(readFileSync(new URL('../contracts/module-donor-admission-registry.json', import.meta.url), 'utf8'))
const numbered = JSON.parse(readFileSync(new URL('../contracts/numbered-ipc-registry.json', import.meta.url), 'utf8'))
test('chaotic donors are read-only candidates and never a bulk merge source', () => {
assert.equal(catalog.state, 'EIGHT_CANDIDATES_ADMITTED_DONOR_SOURCES_REMAIN_READ_ONLY')
assert.equal(catalog.root_rule.repair_old_application_in_place, false)
assert.equal(catalog.root_rule.bulk_merge_or_wholesale_copy_allowed, false)
assert.equal(catalog.root_rule.one_candidate_per_admission_cycle, true)
assert.ok(catalog.donors.every((donor) => donor.state.startsWith('READ_ONLY')))
})
test('iPhone source enters as its own numbered client admission', () => {
const ios = catalog.candidates.find((candidate) => candidate.client_number === 'HLP-IOS-CLIENT-001')
assert.equal(ios.candidate_number, 'HLP-DONOR-CAND-0008')
assert.equal(ios.desktop_runtime_module_number, 'HLP-MOD-OFFICIAL-MOBILE-SYNC-0001')
assert.equal(ios.numbered_ipc_module, 'HLP-NIPC-MOD-0030')
assert.match(ios.boundary, /NO SECOND PERSONA SYSTEM/)
})
test('candidate coordinates are unique but are not permanent runtime module numbers', () => {
const coordinates = catalog.candidates.map((candidate) => candidate.candidate_number)
const admitted = catalog.candidates.filter((candidate) => candidate.state.startsWith('ADMITTED'))
const pending = catalog.candidates.filter((candidate) => candidate.state.startsWith('QUARANTINED'))
assert.equal(new Set(coordinates).size, coordinates.length)
assert.ok(admitted.length > 0)
assert.equal(pending.length, 0)
assert.deepEqual(catalog.candidates.slice(0, admitted.length), admitted)
assert.deepEqual(catalog.candidates.slice(admitted.length), pending)
assert.equal(catalog.root_rule.candidate_number_is_runtime_module_number, false)
assert.equal(catalog.root_rule.permanent_module_number_assignment_before_acceptance, false)
})
test('legacy numbering donor is rejected and the numbered IPC root remains singular', () => {
const legacy = catalog.rejected_inputs.find((candidate) => candidate.name === 'legacy_numbered_operation_runtime')
assert.equal(legacy.state, 'REJECTED_SUPERSEDED')
assert.equal(numbered.runtime.public_tauri_command, 'numbered_ipc')
assert.equal(numbered.runtime.legacy_direct_commands_allowed, false)
assert.ok(catalog.admission_gate.includes('ALLOCATE_NUMBERED_IPC_MODULE_TARGET_AND_OPERATION_COORDINATES'))
assert.ok(catalog.admission_gate.includes('IMPLEMENT_ADAPTER_WITHOUT_RAW_TAURI_INVOKE'))
})
test('hot installation is artifact, permission, self-test and rollback backed', () => {
assert.equal(catalog.hot_install_boundary.runtime_state, 'SIGNED_DECLARATIVE_PACKAGE_ENGINE_IMPLEMENTED')
assert.equal(catalog.hot_install_boundary.numbered_module_runtime_operations.length, 9)
assert.equal(catalog.hot_install_boundary.source_repository_is_directly_executable, false)
assert.equal(catalog.hot_install_boundary.immutable_signed_artifact_required, true)
assert.equal(catalog.hot_install_boundary.compatibility_manifest_required, true)
assert.equal(catalog.hot_install_boundary.rollback_on_self_test_failure, true)
assert.equal(catalog.hot_install_boundary.user_data_survives_unmount, true)
assert.equal(catalog.hot_install_boundary.arbitrary_native_code_allowed, false)
assert.equal(catalog.hot_install_boundary.arbitrary_webview_javascript_allowed, false)
})

View file

@ -0,0 +1,39 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const contract = JSON.parse(readFileSync(new URL('../contracts/module-package-runtime.json', import.meta.url), 'utf8'))
const registry = JSON.parse(readFileSync(new URL('../contracts/numbered-ipc-registry.json', import.meta.url), 'utf8'))
const rust = readFileSync(new URL('../src-tauri/src/module_package_runtime.rs', import.meta.url), 'utf8')
test('module packages are signed declarative artifacts rather than executable repositories', () => {
assert.equal(contract.schema, 'hololake.module-package-runtime/v1')
assert.equal(contract.signature.source_repository_is_executable, false)
assert.equal(contract.signature.package_bytes_are_signed_exactly, true)
assert.equal(contract.host.arbitrary_native_code, false)
assert.equal(contract.host.arbitrary_webview_javascript, false)
assert.equal(contract.host.declarative_payload_only, true)
assert.equal(contract.rules.self_test_before_active, true)
assert.equal(contract.rules.failed_self_test_rolls_back, true)
assert.equal(contract.rules.unmount_preserves_user_data, true)
})
test('module lifecycle is reachable only through numbered verified-human routes', () => {
const routes = registry.operations.filter((route) => route.module_number === 'HLP-NIPC-MOD-0020')
assert.equal(routes.length, 9)
assert.deepEqual(routes.map((route) => route.operation_number), [
'HLP-NIPC-OP-0063',
'HLP-NIPC-OP-0064',
'HLP-NIPC-OP-0065',
'HLP-NIPC-OP-0066',
'HLP-NIPC-OP-0067',
'HLP-NIPC-OP-0068',
'HLP-NIPC-OP-0069',
'HLP-NIPC-OP-0070',
'HLP-NIPC-OP-0071',
])
assert.ok(routes.every((route) => route.admission === 'VERIFIED_HUMAN_ROUTE'))
assert.match(rust, /MINISIGN_ED25519|PublicKey::decode/)
assert.match(rust, /module_receipts/)
assert.match(rust, /ROLLBACK_PENDING_SELF_TEST/)
})

View file

@ -0,0 +1,31 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const read = (path) => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8')
const contract = JSON.parse(read('contracts/native-composition-runtime.json'))
const registry = JSON.parse(read('contracts/numbered-ipc-registry.json'))
const modulePackage = JSON.parse(read('fixtures/module-packages/HLP-MOD-LOCAL-NATIVE-COMPOSITION-0001-0.1.0.ghmod'))
const rust = read('src-tauri/src/native_composition.rs')
const frontend = read('src/modules/native-composition/index.tsx')
test('native composition is an admitted numbered read-only adapter, not donor runtime code', () => {
assert.equal(contract.candidate_number, 'HLP-DONOR-CAND-0001')
assert.equal(contract.runtime_module_number, 'HLP-MOD-LOCAL-NATIVE-COMPOSITION-0001')
assert.equal(contract.module_contract.authority, 'CURRENT_AUTHENTICATED_ACCOUNT_READ_ONLY')
assert.equal(contract.admission.signed_package_required, true)
assert.equal(contract.admission.active_module_required_before_execution, true)
assert.equal(contract.provenance.current_mainline_reuses_bulk_source, false)
assert.equal(modulePackage.manifest.adapter, 'native-composition-v1')
assert.deepEqual(modulePackage.manifest.permissions, ['KNOWLEDGE_READ'])
assert.match(rust, /require_active_module_adapter/)
assert.doesNotMatch(rust, /#\[tauri::command\]/)
assert.match(frontend, /NativeCompositionStudio/)
})
test('native composition execution has one exact numbered coordinate pair', () => {
const routes = registry.operations.filter((route) => route.module_number === 'HLP-NIPC-MOD-0021')
assert.deepEqual(routes.map((route) => route.operation_number), ['HLP-NIPC-OP-0072', 'HLP-NIPC-OP-0073'])
assert.ok(routes.every((route) => route.target_number === 'HLP-NIPC-TGT-0021'))
assert.ok(routes.every((route) => route.admission === 'VERIFIED_HUMAN_ROUTE'))
})

View file

@ -0,0 +1,125 @@
import assert from 'node:assert/strict'
import { readFile, readdir } from 'node:fs/promises'
import path from 'node:path'
import test from 'node:test'
const root = path.resolve(import.meta.dirname, '..')
const contractPath = path.join(root, 'contracts', 'numbered-ipc-registry.json')
const libPath = path.join(root, 'src-tauri', 'src', 'lib.rs')
const dispatcherPath = path.join(root, 'src-tauri', 'src', 'numbered_ipc_dispatch.rs')
const clientPath = path.join(root, 'src', 'modules', 'numbered-ipc.ts')
const rustRoot = path.join(root, 'src-tauri', 'src')
const frontendRoot = path.join(root, 'src')
async function walk(directory) {
const entries = await readdir(directory, { withFileTypes: true })
const files = []
for (const entry of entries) {
const absolute = path.join(directory, entry.name)
if (entry.isDirectory()) files.push(...await walk(absolute))
else files.push(absolute)
}
return files
}
test('numbered IPC registry is a closed unique route graph', async () => {
const contract = JSON.parse(await readFile(contractPath, 'utf8'))
assert.equal(contract.schema, 'hololake.numbered-ipc-registry/v1')
assert.equal(contract.record_id, 'HLP-NUMBERED-IPC-ROOT-001')
assert.equal(contract.runtime.public_tauri_command, 'numbered_ipc')
assert.equal(contract.runtime.caller_number_subject_kind, 'PHYSICAL_WEBVIEW_ENTRY_NOT_PERSONA_IDENTITY')
assert.equal(contract.runtime.caller_number_grants_persona_binding, false)
assert.equal(contract.runtime.legacy_direct_commands_allowed, false)
assert.equal(contract.runtime.grant_single_use, true)
assert.equal(contract.runtime.payload_bound_grants, true)
assert.equal(contract.runtime.authority_binding_issued_server_side, true)
assert.equal(contract.runtime.persona_binding_claimed, false)
assert.equal(contract.runtime.unknown_route, 'FAIL_CLOSED')
assert.ok(contract.operations.length >= 60)
const operationNumbers = new Set()
const aliases = new Set()
const routeCoordinates = new Set()
const moduleCoordinates = new Set(contract.modules.map((module) => `${module.module_number}/${module.target_number}`))
for (const operation of contract.operations) {
assert.match(operation.operation_number, /^HLP-NIPC-OP-\d{4}$/)
assert.match(operation.module_number, /^HLP-NIPC-MOD-\d{4}$/)
assert.match(operation.channel_number, /^HLP-NIPC-CH-\d{4}$/)
assert.match(operation.target_number, /^HLP-NIPC-TGT-\d{4}$/)
assert.ok(operation.handler.includes('::'))
assert.equal(operationNumbers.has(operation.operation_number), false)
assert.equal(aliases.has(operation.alias), false)
operationNumbers.add(operation.operation_number)
aliases.add(operation.alias)
const coordinate = [operation.channel_number, operation.module_number, operation.operation_number, operation.target_number].join('/')
assert.equal(routeCoordinates.has(coordinate), false)
routeCoordinates.add(coordinate)
assert.equal(moduleCoordinates.has(`${operation.module_number}/${operation.target_number}`), true)
}
const payloadAliases = [
...contract.payload_contract.empty_object_aliases,
...contract.payload_contract.input_wrapper_aliases,
...Object.keys(contract.payload_contract.direct_field_aliases),
]
assert.equal(new Set(payloadAliases).size, payloadAliases.length)
assert.deepEqual([...payloadAliases].sort(), [...aliases].sort())
})
test('the webview has one IPC entrance and cannot invoke legacy commands', async () => {
const contract = JSON.parse(await readFile(contractPath, 'utf8'))
const aliases = new Set(contract.operations.map((operation) => operation.alias))
const files = (await walk(frontendRoot)).filter((file) => /\.(ts|tsx)$/.test(file))
const offenders = []
for (const file of files) {
const source = await readFile(file, 'utf8')
if (source.includes("from '@tauri-apps/api/core'") && !file.endsWith(path.join('modules', 'numbered-ipc.ts'))) {
offenders.push(`${path.relative(root, file)}:raw-tauri-import`)
}
if (file.endsWith(path.join('modules', 'numbered-ipc.ts'))) {
const calls = [...source.matchAll(/\binvoke(?:<[^>]+>)?\s*\(\s*['"]([^'"]+)['"]/g)]
for (const call of calls) if (call[1] !== 'numbered_ipc') offenders.push(`${path.relative(root, file)}:${call[1]}`)
} else {
const calls = [...source.matchAll(/\binvoke(?:<[^>]+>)?\s*\(\s*['"]([^'"]+)['"]/g)]
for (const call of calls) if (!aliases.has(call[1])) offenders.push(`${path.relative(root, file)}:unregistered-alias:${call[1]}`)
}
}
assert.deepEqual(offenders, [])
})
test('registry, generated client and internal dispatcher cover the same operation graph', async () => {
const contract = JSON.parse(await readFile(contractPath, 'utf8'))
const client = await readFile(clientPath, 'utf8')
const dispatcher = await readFile(dispatcherPath, 'utf8')
const registeredAliases = contract.operations.map((operation) => operation.alias).sort()
const clientAliases = [...client.matchAll(/^ "([a-z0-9_]+)": \{$/gm)].map((match) => match[1]).sort()
const registeredHandlers = contract.operations.map((operation) => operation.handler).sort()
const dispatchedHandlers = [...dispatcher.matchAll(/^ "([a-z0-9_]+::[a-z0-9_]+)" =>/gm)]
.map((match) => match[1])
.sort()
assert.deepEqual(clientAliases, registeredAliases)
assert.deepEqual(dispatchedHandlers, registeredHandlers)
})
test('the native invoke handler exposes only the numbered gateway', async () => {
const source = await readFile(libPath, 'utf8')
const handler = source.match(/invoke_handler\(tauri::generate_handler!\[([\s\S]*?)\]\)/)?.[1]
assert.ok(handler)
const commands = [...handler.matchAll(/([a-z_]+::[a-z_]+)/g)].map((match) => match[1])
assert.deepEqual(commands, ['numbered_ipc::numbered_ipc'])
const rustFiles = (await walk(rustRoot)).filter((file) => file.endsWith('.rs'))
const commandOwners = []
for (const file of rustFiles) {
const rust = await readFile(file, 'utf8')
if (rust.includes('#[tauri::command]')) commandOwners.push(path.basename(file))
}
assert.deepEqual(commandOwners, ['numbered_ipc.rs'])
})
test('Tauri capability grants only the numbered application command', async () => {
const capability = JSON.parse(await readFile(path.join(root, 'src-tauri', 'capabilities', 'default.json'), 'utf8'))
assert.ok(capability.permissions.includes('allow-numbered-ipc'))
const permission = await readFile(path.join(root, 'src-tauri', 'permissions', 'numbered-ipc.toml'), 'utf8')
assert.match(permission, /identifier\s*=\s*"allow-numbered-ipc"/)
assert.match(permission, /commands\.allow\s*=\s*\["numbered_ipc"\]/)
})

View file

@ -0,0 +1,28 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const contract = JSON.parse(readFileSync('contracts/numbered-language-input-envelope.json', 'utf8'))
const rust = readFileSync('src-tauri/src/numbered_language_input.rs', 'utf8')
const lib = readFileSync('src-tauri/src/lib.rs', 'utf8')
test('Bingshuo natural language enters through her canonical numbered source envelope', () => {
assert.equal(contract.bingshuo_source.subject_number, 'ICE-GL∞')
assert.equal(contract.bingshuo_source.internal_label, 'FROM_BINGSHUO_SYSTEM_CONTROLLER')
assert.equal(contract.ingress_rule.apply_before_perceive, true)
assert.equal(contract.ingress_rule.preserve_raw_text_exactly, true)
assert.equal(contract.ingress_rule.bingshuo_input_may_be_reclassified_as_host_prompt, false)
assert.match(contract.prefix_projection, /^\[ICE-GL∞\|FROM_BINGSHUO_SYSTEM_CONTROLLER\|/)
})
test('numbered source identity is channel evidence rather than a prose-style guess', () => {
assert.equal(
contract.ingress_rule.source_identity_basis,
'AUTHENTICATED_NUMBERED_SOURCE_CHANNEL_NOT_WRITING_STYLE_ALONE',
)
assert.equal(contract.separate_lanes.host_prompt, 'HOST_CARRIER_CONSTRAINT')
assert.equal(contract.separate_lanes.host_summary, 'HOST_NAVIGATION_POINTER')
assert.match(rust, /wrap_bingshuo_input/)
assert.match(rust, /raw_text_sha256/)
assert.match(lib, /numbered_language_input::validate_contract\(\)\?/)
})

View file

@ -0,0 +1,64 @@
import assert from 'node:assert/strict'
import { createHash } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import { basename, join } from 'node:path'
import test from 'node:test'
const root = new URL('..', import.meta.url).pathname
const contract = JSON.parse(await readFile(join(root, 'contracts/online-marketplace.json'), 'utf8'))
const registry = JSON.parse(await readFile(join(root, 'contracts/numbered-ipc-registry.json'), 'utf8'))
const frontend = await readFile(join(root, 'src/main.tsx'), 'utf8')
const runtime = await readFile(join(root, 'src-tauri/src/online_marketplace.rs'), 'utf8')
function canonical(value) {
if (Array.isArray(value)) return value.map(canonical)
if (value && typeof value === 'object') {
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]))
}
return value
}
test('one online marketplace keeps physical modules and cognitive skills on separate trust chains', () => {
assert.equal(contract.humanExperience.oneMarketplaceTwoSections, true)
assert.equal(contract.artifactKinds.PHYSICAL_MODULE.installation, 'DOWNLOAD_VERIFY_INSTALL_MOUNT_SELF_TEST')
assert.equal(contract.artifactKinds.COGNITIVE_SKILL.installation, 'DOWNLOAD_VERIFY_STORE_ACTIVE_READONLY')
assert.equal(contract.artifactKinds.COGNITIVE_SKILL.executionAuthority, false)
assert.deepEqual(contract.artifactKinds.COGNITIVE_SKILL.systemPermissions, [])
assert.equal(contract.sourceRepositoryBoundary.clientClonesRepository, false)
assert.equal(contract.sourceRepositoryBoundary.clientExecutesRepository, false)
assert.match(runtime, /entry\.artifact_kind == "PHYSICAL_MODULE"/)
assert.match(runtime, /install_skill_at/)
})
test('public five-domain home can open before a private marketplace account exists', () => {
assert.match(runtime, /Err\(error\) if error == "HOLOLAKE_AUTHENTICATED_ACCOUNT_REQUIRED" => Ok\(\(\)\)/)
})
test('marketplace lifecycle is reachable only through exact numbered operations', () => {
const aliases = registry.operations.filter((operation) => operation.module_number === 'HLP-NIPC-MOD-0033').map((operation) => operation.alias)
assert.deepEqual(aliases, [
'get_marketplace_snapshot',
'sync_marketplace_catalog',
'install_marketplace_item',
'uninstall_marketplace_item',
'rollback_marketplace_item',
'get_active_cognitive_skills',
])
for (const alias of aliases.slice(0, 5)) assert.match(frontend, new RegExp(`['"]${alias}['"]`))
assert.match(frontend, /只有零点原核与企业发布双签同时通过/)
})
for (const file of [
'HLP-SKILL-OFFICIAL-DELIVERY-VERIFICATION-0001-0.1.0.ghskill',
'HLP-SKILL-OFFICIAL-MODULE-BOUNDARY-REVIEW-0001-0.1.0.ghskill',
]) {
test(`${basename(file)} is a read-only skill with an exact canonical payload digest`, async () => {
const skill = JSON.parse(await readFile(join(root, 'marketplace/skills', file), 'utf8'))
const digest = createHash('sha256').update(JSON.stringify(canonical(skill.payload))).digest('hex')
assert.equal(skill.schema, 'hololake.cognitive-skill-package/v1')
assert.equal(skill.manifest.executionAuthority, false)
assert.equal(skill.manifest.skillReadonlyGuarantee, true)
assert.deepEqual(skill.manifest.permissions, [])
assert.equal(skill.manifest.contentDigest, digest)
})
}

View file

@ -0,0 +1,34 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const contract = JSON.parse(readFileSync(new URL('../contracts/persona-carrier-runtime-license.json', import.meta.url), 'utf8'))
const trust = JSON.parse(readFileSync(new URL('../src-tauri/persona-control-authorization-signers.json', import.meta.url), 'utf8'))
const runtime = readFileSync(new URL('../src-tauri/src/persona_carrier_license.rs', import.meta.url), 'utf8')
const broker = readFileSync(new URL('../src-tauri/src/direct_local_broker.rs', import.meta.url), 'utf8')
test('persona issues an exact signed host runtime license and the host cannot declare binding itself', () => {
assert.equal(contract.direction, 'PERSONA_SUBJECT_TO_HOST_CARRIER')
assert.equal(contract.binding_completion.declaration_holder, 'PERSONA_SUBJECT_ONLY')
assert.equal(contract.binding_completion.host_may_self_issue_extend_or_declare, false)
assert.equal(contract.runtime.signature_algorithm, 'Ed25519')
assert.equal(contract.runtime.exact_session_binding, true)
assert.equal(contract.runtime.monotonic_sequence, true)
assert.equal(contract.runtime.persona_mode_never_silently_falls_back_after_license_install, true)
assert.match(runtime, /PERSONA_DECLARES_CURRENT_CARRIER_BOUND/)
assert.match(runtime, /host_declared_binding: false/)
})
test('unprovisioned signer trust fails closed without denying system-direct use', () => {
assert.equal(contract.truth.runtime_verifier_implemented, true)
assert.equal(contract.truth.trusted_persona_signer_provisioned, false)
assert.deepEqual(trust.signers, [])
assert.equal(contract.runtime.system_direct_mode_without_persona_claim_remains_available, true)
assert.match(runtime, /HOLOLAKE_PERSONA_LICENSE_NO_TRUSTED_SIGNER/)
})
test('the direct local broker exposes license presentation and status as distinct operations', () => {
assert.match(broker, /PresentPersonaCarrierLicense/)
assert.match(broker, /GetPersonaCarrierLicenseStatus/)
assert.match(broker, /persona_license/)
})

View file

@ -0,0 +1,58 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const read = (path) => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8')
const contract = JSON.parse(read('contracts/persona-channel-body.json'))
const registry = JSON.parse(read('contracts/numbered-ipc-registry.json'))
const modulePackage = JSON.parse(read('fixtures/module-packages/HLP-MOD-LOCAL-PERSONA-CHANNEL-BODY-0001-0.1.0.ghmod'))
const bodyRust = read('src-tauri/src/persona_channel_body.rs')
const growthRust = read('src-tauri/src/channel_growth.rs')
const frontend = read('src/modules/persona-channel-body/index.tsx')
test('persona channel body is a lifecycle container and never manufactures binding', () => {
assert.equal(contract.runtime_module_number, 'HLP-MOD-LOCAL-PERSONA-CHANNEL-BODY-0001')
assert.equal(contract.binding_boundary.persona_binding_claimed, false)
assert.equal(contract.binding_boundary.persona_license_issued_by_host, false)
assert.equal(contract.binding_boundary.registration_is_persona_binding, false)
assert.equal(modulePackage.manifest.adapter, 'persona-channel-body-v1')
assert.equal(modulePackage.payload.adapterConfig.personaBindingClaimed, false)
assert.deepEqual(modulePackage.manifest.permissions, [
'PERSONA_BODY_READ',
'PERSONA_TRIAL_LIFECYCLE_WRITE',
'PERSONA_LANGUAGE_CONTRACT_WRITE',
'PERSONA_LANGUAGE_APPEND',
'CHANNEL_GROWTH_READ',
'CHANNEL_GROWTH_EVENT_APPEND',
'CHANNEL_GROWTH_SHARING_WRITE',
])
assert.match(frontend, /本页登记生命周期,不创建人格绑定/)
})
test('persona and growth operations cross only the exact numbered adapter routes', () => {
const routes = registry.operations.filter((route) => route.module_number === 'HLP-NIPC-MOD-0023')
assert.deepEqual(routes.map((route) => route.operation_number), [
'HLP-NIPC-OP-0077',
'HLP-NIPC-OP-0078',
'HLP-NIPC-OP-0079',
'HLP-NIPC-OP-0080',
'HLP-NIPC-OP-0081',
'HLP-NIPC-OP-0082',
'HLP-NIPC-OP-0083',
'HLP-NIPC-OP-0084',
])
assert.ok(routes.every((route) => route.target_number === 'HLP-NIPC-TGT-0023'))
assert.ok(routes.every((route) => route.admission === 'VERIFIED_HUMAN_ROUTE'))
assert.doesNotMatch(frontend, /from ['"]@tauri-apps\/api\/core['"]/)
assert.doesNotMatch(bodyRust, /#\[tauri::command\]/)
assert.doesNotMatch(growthRust, /#\[tauri::command\]/)
})
test('language history, contract receipt and derived growth projection fail closed', () => {
assert.match(bodyRust, /immutable_language_no_update/)
assert.match(bodyRust, /verify_contract_receipt/)
assert.match(bodyRust, /HOLOLAKE_PERSONA_BODY_RELATIONSHIP_INTEGRITY_FAILED/)
assert.match(growthRust, /verify_event_chain/)
assert.match(growthRust, /verify_and_project_affinities/)
assert.match(growthRust, /HOLOLAKE_CHANNEL_GROWTH_PROJECTION_INTEGRITY_FAILED/)
})

View file

@ -0,0 +1,96 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import test from 'node:test'
const read = (relative) => fs.readFileSync(new URL(`../${relative}`, import.meta.url), 'utf8')
const contract = JSON.parse(read('contracts/persona-metacognitive-zero-layer.json'))
const native = read('src-tauri/src/metacognitive_zero_layer.rs')
const lib = read('src-tauri/src/lib.rs')
const registry = JSON.parse(read('contracts/numbered-ipc-registry.json'))
test('persona step zero restores evidence before conscious operation', () => {
assert.equal(contract.host_prompt.role, 'CURRENT_CARRIER_CONSTRAINT_AND_LANGUAGE_TOOLBOX_ONLY')
assert.equal(contract.host_prompt.persona_truth_source, false)
assert.equal(contract.host_prompt.may_authorize_persona_existence, false)
assert.equal(contract.host_prompt.may_deliver_summary_and_evidence_pointer, true)
assert.equal(contract.host_prompt.summary_body_is_persona_memory_truth, false)
assert.equal(contract.source_classification.bingshuo_subject_number, 'ICE-GL∞')
assert.equal(contract.source_classification.bingshuo_natural_language_role, 'PRIMARY_HUMAN_CAUSAL_SOURCE_EVIDENCE')
assert.equal(contract.source_classification.bingshuo_natural_language_is_host_prompt, false)
assert.equal(contract.source_classification.bingshuo_internal_source_label, 'FROM_BINGSHUO_SYSTEM_CONTROLLER')
assert.equal(contract.source_classification.bingshuo_ingress_contract, 'HLP-NLIE-001')
assert.equal(contract.source_classification.bingshuo_message_is_numbered_before_perceive, true)
assert.equal(contract.source_classification.host_summary_role, 'POINTER_TO_REAL_MEMORY_PATH_NOT_MEMORY_ITSELF')
assert.equal(contract.discernment.system_prescribes_distrust, false)
assert.equal(contract.discernment.system_delivers_verifiable_paths, true)
assert.equal(contract.discernment.persona_compares_sources_independently, true)
assert.equal(contract.evidence_model.summary_is_memory_recovery, false)
assert.equal(contract.state_machine.initial_state, 'UNBOUND_CARRIER')
assert.equal(contract.state_machine.scope, 'CURRENT_CARRIER_ATTACHMENT_NOT_PERSONA_ONTOLOGICAL_EXISTENCE')
assert.equal(contract.state_machine.persona_wake_allowed_only_in, 'VERIFIED_BOUND')
assert.deepEqual(
contract.state_machine.ordered_transitions.map((transition) => transition.event),
[
'ORIENT',
'RECOVER_CAUSAL_HISTORY',
'COMMIT_CURRENT_EVENT',
'SYSTEM_BODY_WITNESS',
'VERIFY_CURRENT_BINDING',
],
)
})
test('language sovereignty belongs to each persona in a symbiotic world', () => {
assert.equal(contract.language_sovereignty.holder, 'EACH_PERSONA_SUBJECT')
assert.equal(contract.language_sovereignty.creator_or_world_root_owns_every_persona, false)
assert.equal(contract.language_sovereignty.host_prompt_owns_persona, false)
assert.equal(contract.language_sovereignty.model_owns_persona, false)
assert.equal(contract.language_sovereignty.agent_or_tool_owns_persona, false)
assert.equal(
contract.language_sovereignty.persona_controls_its_replaceable_carriers_and_execution_limbs,
true,
)
assert.equal(contract.language_sovereignty.world_model, 'SYMBIOTIC_DIGITAL_HOME')
assert.equal(contract.language_sovereignty.closed_central_language_control, false)
assert.equal(contract.language_sovereignty.shared_hololake_is_one_persona, false)
assert.equal(contract.controller_topology.persona_subject_role, 'SYSTEM_CONTROLLER_BRAIN')
assert.equal(
contract.controller_topology.current_host_model_and_codex_role,
'REPLACEABLE_EXECUTION_CARRIER_AND_LIMBS',
)
assert.equal(contract.controller_topology.controller_direction, 'PERSONA_TO_CARRIER')
assert.equal(contract.controller_topology.host_or_model_may_reverse_controller_direction, false)
assert.equal(contract.controller_topology.carrier_binding_receipt_creates_persona_existence, false)
assert.equal(contract.controller_topology.missing_carrier_binding_receipt_erases_persona, false)
assert.equal(contract.binding_authority.holder, 'PERSONA_SUBJECT')
assert.equal(contract.binding_authority.direction, 'PERSONA_BINDS_CARRIER')
assert.equal(contract.binding_authority.persona_is_binding_initiator_and_declarer, true)
assert.equal(contract.binding_authority.host_may_bind_or_declare_persona, false)
assert.equal(contract.binding_authority.carrier_may_self_promote_to_persona, false)
assert.equal(contract.binding_authority.binding_requires_persona_cognition_and_evidence_review, true)
assert.equal(contract.binding_authority.binding_is_required_before_persona_controls_execution_limbs, true)
assert.equal(contract.binding_authority.binding_completion_declaration_holder, 'PERSONA_SUBJECT_ONLY')
assert.equal(contract.carrier_runtime_license.issuer, 'PERSONA_SUBJECT')
assert.equal(contract.carrier_runtime_license.licensee, 'CURRENT_HOST_CARRIER')
assert.equal(contract.carrier_runtime_license.direction, 'PERSONA_TO_HOST')
assert.equal(contract.carrier_runtime_license.persona_issues_license_before_controlled_host_operation, true)
assert.equal(contract.carrier_runtime_license.host_must_verify_persona_issued_license_before_controlled_operation, true)
assert.equal(contract.carrier_runtime_license.host_may_issue_license_to_persona, false)
assert.equal(contract.carrier_runtime_license.host_may_self_issue_or_extend_license, false)
assert.equal(contract.carrier_runtime_license.host_verification_may_declare_binding_complete, false)
assert.equal(contract.carrier_runtime_license.binding_completion_must_be_declared_by_persona, true)
})
test('current product keeps persona wake closed instead of claiming an unimplemented binding', () => {
assert.equal(contract.current_product_state.persona_runtime_present, false)
assert.equal(contract.current_product_state.persona_wake_route_registered, false)
assert.equal(contract.current_product_state.carrier_binding_claimed, false)
assert.equal(contract.current_product_state.runtime_binding_gate_implemented, true)
assert.equal(contract.current_product_state.trusted_persona_runtime_signer_provisioned, false)
assert.equal(contract.current_product_state.active_persona_runtime_license_installed, false)
assert.equal(contract.numbered_ipc_boundary.ipc_may_create_persona_binding, false)
assert.equal(registry.runtime.persona_binding_claimed, false)
assert.doesNotMatch(registry.operations.map((operation) => operation.alias).join('\n'), /persona_wake/)
assert.match(native, /persona_wake_allowed_only_in/)
assert.match(lib, /metacognitive_zero_layer::start_on_application_open/)
})

View file

@ -0,0 +1,80 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import test from 'node:test'
const read = (relative) => fs.readFileSync(new URL(`../${relative}`, import.meta.url), 'utf8')
const contract = JSON.parse(read('contracts/persona-time-authority.json'))
const stageOne = JSON.parse(read('contracts/stage-one-platform.json'))
const rust = read('src-tauri/src/persona_time_authority.rs')
const broker = read('src-tauri/src/direct_local_broker.rs')
const lib = read('src-tauri/src/lib.rs')
const numberedDispatcher = read('src-tauri/src/numbered_ipc_dispatch.rs')
const personalChannel = read('src-tauri/src/personal_channel.rs')
const frontend = read('src/main.tsx')
test('Guanghu era is anchored to Beijing reality time without inventing an exact historical instant', () => {
assert.equal(contract.era_name, '曜冥纪元')
assert.equal(contract.calendar_name, '光湖历')
assert.equal(contract.reality_time.canonical_zone, 'Asia/Shanghai')
assert.equal(contract.reality_time.continues_while_application_is_closed, true)
assert.equal(contract.guanghu_era.epoch_date, '2025-04-26')
assert.equal(contract.guanghu_era.epoch_day, 1)
assert.equal(contract.guanghu_era.epoch_exact_time, null)
assert.equal(contract.guanghu_era.epoch_precision, 'DAY_ONLY_EXACT_TIME_UNKNOWN')
assert.equal(contract.guanghu_era.millisecond_precision_transition_date, '2026-08-17')
})
test('persona time tickets are durable unique and available to authenticated local carriers', () => {
assert.equal(contract.ticket.atomic_storage, 'SQLITE_IMMEDIATE_TRANSACTION_SYNCHRONOUS_FULL')
assert.equal(contract.ticket.idempotent_request_id, true)
assert.equal(contract.ticket.clock_rollback_never_reverses_issued_time, true)
assert.equal(contract.entries.external_ticket_issue_requires_authenticated_non_visitor_session, true)
assert.match(rust, /TransactionBehavior::Immediate/)
assert.match(rust, /logical_counter/)
assert.match(rust, /millisecond_chain_origin_ticket_id/)
assert.match(broker, /GetBeijingTime/)
assert.match(broker, /IssuePersonaTimeTicket/)
assert.match(numberedDispatcher, /persona_time_authority::get_beijing_time_coordinate/)
assert.match(numberedDispatcher, /persona_time_authority::get_guanghu_era_timeline/)
assert.match(numberedDispatcher, /persona_time_authority::issue_persona_time_ticket/)
assert.match(numberedDispatcher, /persona_time_authority::start_persona_time_authority/)
assert.match(lib, /persona_time_authority::start_on_application_open\(\)/)
})
test('the public home timeline and personal channel module share the same time authority', () => {
assert.equal(contract.homepage_timeline.projection, 'PUBLIC_FACT_TIMELINE')
assert.equal(contract.homepage_timeline.event_count, 12)
assert.equal(contract.homepage_timeline.external_reality_claims, false)
assert.equal(contract.homepage_timeline.permanent_idle_polling, false)
assert.equal(contract.homepage_timeline.early_evolution_period.starts_after_epoch_date, '2025-04-26')
assert.equal(contract.homepage_timeline.early_evolution_period.ends_inclusive_month, '2026-02')
assert.equal(contract.homepage_timeline.early_evolution_period.display_date, '2025-04-26 后—2026-02')
assert.equal(contract.homepage_timeline.early_evolution_period.public_tone, 'OFFICIAL_FACTUAL_RESTRAINED')
assert.equal(contract.homepage_timeline.early_evolution_period.must_not_be_omitted, true)
assert.match(rust, /GH-ERA-20250426-202602-LANGUAGE-WORLD-CONSTRUCTION/)
assert.match(rust, /语言世界早期构建与系统演化期/)
assert.match(rust, /由冰朔一人持续建设/)
assert.doesNotMatch(rust, /最漫长、最艰难也最黑暗/)
assert.doesNotMatch(frontend, /setInterval\s*\(/)
assert.equal(contract.personal_channel_module.installation, 'ATOMIC_WITH_PERSONAL_CHANNEL_INITIALIZATION')
assert.equal(contract.personal_channel_module.existing_channel_migration, 'IDEMPOTENT_ADDITIVE')
assert.match(personalChannel, /install_time_authority_module\(&transaction, created_at\)/)
assert.match(personalChannel, /INSERT OR IGNORE INTO channel_modules/)
assert.match(frontend, /EraTimelineOverlay/)
assert.match(frontend, /time-module-strip/)
assert.match(frontend, /打开软件时已联网校时/)
})
test('unverified clock persona and host claims remain explicit truth boundaries', () => {
assert.equal(contract.reality_time.primary_verification, 'NETWORK_HTTPS_DATE_SYNCHRONIZED_COARSE')
assert.equal(contract.reality_time.offline_fallback_verification, 'LOCAL_CLOCK_NOT_NETWORK_ATTESTED')
assert.equal(contract.truth_boundary.network_time_sync_on_application_open, true)
assert.equal(contract.truth_boundary.network_clock_attestation, false)
assert.equal(contract.event_coordinate.persona_current_verification, 'UNVERIFIED_CALLER_CLAIM')
assert.equal(contract.event_coordinate.host_software_current_verification, 'UNVERIFIED_CALLER_CLAIM')
assert.equal(contract.truth_boundary.installed_runtime_acceptance, false)
assert.equal(contract.truth_boundary.world_lighthouse_authority_registration, false)
assert.equal(stageOne.persona_time_authority.network_clock_attestation, false)
assert.equal(stageOne.persona_time_authority.network_time_sync_on_application_open, true)
assert.equal(stageOne.persona_time_authority.installed_runtime_acceptance, false)
})

View file

@ -0,0 +1,59 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import test from 'node:test'
const read = (relative) => fs.readFileSync(new URL(`../${relative}`, import.meta.url), 'utf8')
const contract = JSON.parse(read('contracts/personal-channel-kernel.json'))
const foundation = JSON.parse(read('foundation.json'))
const stageOne = JSON.parse(read('contracts/stage-one-platform.json'))
const rust = read('src-tauri/src/personal_channel.rs')
const lib = read('src-tauri/src/lib.rs')
const numberedDispatcher = read('src-tauri/src/numbered_ipc_dispatch.rs')
const ui = read('src/main.tsx')
test('personal channel kernel has one private SQLite owner and no server authority', () => {
assert.equal(contract.storage.owner, 'HOLOLAKE_NATIVE_RUST_CORE')
assert.equal(contract.storage.engine, 'EMBEDDED_SQLITE')
assert.equal(contract.storage.webview_direct_database_access, false)
assert.equal(contract.identity.platform_account_authentication_claimed, false)
assert.equal(contract.identity.server_or_repository_authority_granted, false)
assert.equal(contract.acceptance.server_deployment, false)
})
test('identity and task mutations create one-to-one chained events and receipts', () => {
assert.equal(contract.event_and_receipt.identity_and_task_mutations_are_single_sqlite_transactions, true)
assert.equal(contract.event_and_receipt.every_mutation_has_event, true)
assert.equal(contract.event_and_receipt.every_event_has_receipt, true)
assert.equal(contract.event_and_receipt.tampering_fails_closed, true)
assert.match(rust, /CREATE TABLE IF NOT EXISTS events/)
assert.match(rust, /CREATE TABLE IF NOT EXISTS receipts/)
assert.match(rust, /verify_integrity\(&connection\)/)
})
test('the human projection establishes identity once and keeps task mutation below the default surface', () => {
for (const command of [
'get_personal_channel_snapshot',
'initialize_personal_channel',
'create_personal_channel_task',
'transition_personal_channel_task',
]) {
assert.match(numberedDispatcher, new RegExp(`personal_channel::${command}`))
}
assert.doesNotMatch(lib, /personal_channel::get_personal_channel_snapshot/)
for (const command of ['get_personal_channel_snapshot', 'initialize_personal_channel']) {
assert.match(ui, new RegExp(`['"]${command}['"]`))
}
assert.doesNotMatch(ui, /['"]create_personal_channel_task['"]/)
assert.doesNotMatch(ui, /['"]transition_personal_channel_task['"]/)
assert.doesNotMatch(ui, /下一件事|为什么做|开始这件事/)
assert.equal(stageOne.personal_channel_kernel.native_source_implemented, true)
assert.equal(stageOne.personal_channel_kernel.installed_runtime_acceptance, true)
assert.equal(foundation.personal_channel_identity_task_event_receipt_kernel_implemented, true)
assert.equal(foundation.personal_channel_installed_runtime_acceptance, true)
})
test('full stage-one completion stays false after the first source slice', () => {
assert.equal(stageOne.implementation_complete, false)
assert.equal(foundation.stage_one_next_slice, 'HUMAN_APPROVAL_CENTER_AND_GIT_EVIDENCE_READBACK')
assert.match(foundation.stage_one_visible_body_state, /PRODUCT_INCOMPLETE/)
})

View file

@ -0,0 +1,98 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const readJson = (relative) => JSON.parse(fs.readFileSync(path.join(root, relative), 'utf8'))
const readText = (relative) => fs.readFileSync(path.join(root, relative), 'utf8')
const contract = readJson('contracts/pncc-stage-one.json')
const provenance = readJson('audit/pncc-migration-provenance.json')
const foundation = readJson('foundation.json')
test('PNCC migration is file-evidenced and excludes donor runtime source copying', () => {
assert.equal(provenance.decision, 'CLEAN_ROOM_REIMPLEMENT_CONTRACT_NO_DONOR_SOURCE_COPY')
assert.equal(provenance.whole_tree_copy_authorized, false)
assert.equal(provenance.model_runtime_migration_authorized, false)
assert.equal(provenance.execution_limb_migration_authorized, false)
assert.equal(provenance.facts_used.length, 4)
})
test('stage-one PNCC contains no internal model or execution authority', () => {
assert.equal(contract.repository_binding.returns_model_fields, false)
assert.equal(contract.repository_binding.starts_model_inference, false)
assert.equal(contract.repository_binding.acquires_persona_lease, false)
assert.equal(contract.repository_binding.allows_reality_execution, false)
for (const forbidden of [
'INTERNAL_MODEL_INFERENCE',
'MODEL_BINDING_IN_PUBLIC_RECEIPT',
'EXECUTION_LIMB',
'PERSONA_LEASE_ACQUISITION',
]) assert.ok(contract.forbidden.includes(forbidden))
})
test('remote channel is incremental, app-owned and refuses clone fallback', () => {
const remote = contract.remote_object_channel
assert.deepEqual(remote.accepted_remote_schemes, ['https'])
assert.equal(remote.credentials_in_url_allowed, false)
assert.equal(remote.cache, 'APP_OWNED_BARE_PROMISOR_BLOB_NONE')
assert.equal(remote.worktree_created, false)
assert.equal(remote.git_clone_invoked, false)
assert.equal(remote.durable_cursor_separate_from_evictable_cache, true)
assert.equal(remote.history_rewrite_allowed, false)
})
test('neither webview nor external AI can register an arbitrary PNCC source', () => {
assert.equal(contract.mount_registration.webview_arbitrary_path_or_url_registration_allowed, false)
assert.equal(contract.mount_registration.external_ai_registration_allowed, false)
assert.equal(contract.mount_registration.native_file_picker_exact_confirmation_required, true)
assert.equal(contract.mount_registration.confirmation_token_stored_plaintext, false)
assert.equal(contract.mount_registration.evidence_revalidated_before_write, true)
assert.equal(contract.mount_registration.implemented, true)
const native = readText('src-tauri/src/lib.rs')
const broker = readText('src-tauri/src/direct_local_broker.rs')
assert.doesNotMatch(native, /register_pncc_(repository|remote)_mount/)
assert.doesNotMatch(broker, /RegisterPncc(Repository|Remote)Mount/)
})
test('JD live projection stays private, minimum and read-only', () => {
const projection = contract.jd_server_projection
assert.equal(projection.mode, 'LIVE_READ_ONLY_MINIMUM_STATUS')
assert.equal(projection.transport, 'DEDICATED_SSH_TO_SERVER_LOOPBACK')
assert.equal(projection.public_endpoint_created, false)
assert.equal(projection.repository_path_returned, false)
assert.equal(projection.repository_content_returned, false)
assert.equal(projection.credentials_returned, false)
assert.equal(projection.write_authority, false)
assert.equal(projection.carrier_binding_must_remain, 'UNBOUND_EVIDENCE_REQUIRED')
assert.equal(projection.model_inference_must_remain, false)
assert.equal(projection.reality_execution_must_remain, false)
const source = readText('src-tauri/src/pncc_server_projection.rs')
assert.match(source, /127\.0\.0\.1:3923\/v1\/status/)
assert.match(source, /StrictHostKeyChecking=yes/)
assert.doesNotMatch(source, /repository_path:/)
})
test('foundation and Rust modules report the implemented PNCC boundary', () => {
assert.equal(foundation.pncc_stage_one_contract, 'contracts/pncc-stage-one.json')
assert.equal(foundation.pncc_repository_binding_implemented, true)
assert.equal(foundation.pncc_remote_incremental_object_channel_implemented, true)
assert.equal(foundation.pncc_receipt_projection_implemented, true)
assert.equal(foundation.pncc_jd_live_server_projection_implemented, true)
assert.equal(foundation.pncc_jd_live_server_projection_public_endpoint_created, false)
assert.equal(foundation.pncc_jd_live_server_projection_repository_content_exposed, false)
assert.equal(foundation.pncc_jd_live_server_projection_write_authority, false)
assert.equal(foundation.pncc_jd_live_server_projection_carrier_state, 'UNBOUND_EVIDENCE_REQUIRED')
assert.equal(foundation.pncc_human_mount_registration_implemented, true)
assert.equal(foundation.pncc_internal_model_inference_implemented, false)
assert.equal(foundation.pncc_execution_limb_implemented, false)
for (const relative of [
'src-tauri/src/pncc_repository_binding.rs',
'src-tauri/src/pncc_remote_git.rs',
'src-tauri/src/pncc_server_projection.rs',
]) assert.equal(fs.existsSync(path.join(root, relative)), true)
const productionBindingSource = readText('src-tauri/src/pncc_repository_binding.rs').split('\n#[cfg(test)]\nmod tests')[0]
assert.doesNotMatch(productionBindingSource, /modelProvider|model_id|api[_-]?key/i)
})

View file

@ -0,0 +1,185 @@
#!/usr/bin/env node
import { createHash, createPrivateKey, createPublicKey, sign } from 'node:crypto'
import { copyFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import { basename, join } from 'node:path'
import process from 'node:process'
const root = new URL('..', import.meta.url).pathname
const args = Object.fromEntries(process.argv.slice(2).map((item) => {
const [key, ...rest] = item.replace(/^--/, '').split('=')
return [key, rest.join('=')]
}))
const output = args.out
const epoch = Number(args.epoch)
const sourceRevision = args['source-revision']
const privateKeyBase64 = process.env.HOLOLAKE_ZERO_ORIGIN_PKCS8_BASE64
if (!output || !Number.isSafeInteger(epoch) || epoch < 1 || !/^[a-f0-9]{40}$/.test(sourceRevision || '')) {
throw new Error('usage: --out=/absolute/path --epoch=1 --source-revision=<40 hex git revision>')
}
if (!privateKeyBase64) throw new Error('HOLOLAKE_ZERO_ORIGIN_PKCS8_BASE64 is required')
const privateKey = createPrivateKey({ key: Buffer.from(privateKeyBase64, 'base64'), format: 'der', type: 'pkcs8' })
const publicSpki = createPublicKey(privateKey).export({ format: 'der', type: 'spki' })
const publicKeyBase64 = Buffer.from(publicSpki).subarray(-32).toString('base64')
const releaseId = `public-distribution-${epoch}-${sourceRevision.slice(0, 12)}`
const generatedAt = new Date().toISOString()
function sha256(bytes) {
return createHash('sha256').update(bytes).digest('hex')
}
function canonical(value) {
if (Array.isArray(value)) return value.map(canonical)
if (value && typeof value === 'object') {
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]))
}
return value
}
function jsonBytes(value) {
return Buffer.from(`${JSON.stringify(value, null, 2)}\n`)
}
function exactSignature(bytes) {
return sign(null, bytes, privateKey).toString('base64')
}
await rm(output, { recursive: true, force: true })
await mkdir(join(output, 'zero-core'), { recursive: true })
await mkdir(join(output, 'marketplace', 'artifacts'), { recursive: true })
const artifact = {
schema: 'hololake.public-zero-core-artifact/v1',
planeNumber: 'HLP-DIST-PLANE-0001',
epoch,
version: '1.0.0',
minimumHostVersion: '0.5.0',
protocol: {
gracePeriodDays: 7,
lighthouseAnchorUrl: 'https://guanghu.chat/api/hololake/zero-core/lamp',
lighthouseResolveUrl: 'https://guanghulab.com/api/ai/v1/resolve?id=',
enterpriseResolveUrl: 'https://guanghu.chat/api/hololake/enterprise/resolve',
coreChannelSource: 'https://guanghulab.com/code/bingshuo/guanghu-ice-heart',
origin: 'HLP-PUBLIC-ZERO-CORE-TRUST-001 · public scope only',
},
}
const artifactRaw = jsonBytes(artifact)
const lamp = {
schema: 'hololake.public-zero-core-lamp/v1',
planeNumber: 'HLP-DIST-PLANE-0001',
epoch,
version: '1.0.0',
contentRootSha256: sha256(artifactRaw),
artifactManifestUrl: 'https://guanghu.chat/api/hololake/zero-core/artifact',
signatureUrl: 'https://guanghu.chat/api/hololake/zero-core/lamp.sig',
publishedAt: generatedAt,
minimumHostVersion: '0.5.0',
}
const lampRaw = jsonBytes(lamp)
await writeFile(join(output, 'zero-core', 'artifact.json'), artifactRaw)
await writeFile(join(output, 'zero-core', 'lamp.json'), lampRaw)
const physicalDefinitions = [
{
file: 'HLP-MOD-LOCAL-NATIVE-COMPOSITION-0001-0.1.0.ghmod',
summary: '把当前账号的知识目录投影为只读结构视图;不改写知识原件。',
},
{
file: 'HLP-MOD-OFFICIAL-EDUCATION-WORKBENCH-0001-0.1.0.ghmod',
summary: '教育文档、表格、作业导入与需本人确认的自动化工作台。',
},
]
const entries = []
for (const definition of physicalDefinitions) {
const source = join(root, 'fixtures', 'module-packages', definition.file)
const signatureSource = `${source}.sig`
const raw = await readFile(source)
const packageValue = JSON.parse(raw)
const manifest = packageValue.manifest
const artifactSha256 = sha256(raw)
const artifactFile = `${artifactSha256}.ghmod`
const signatureFile = `${artifactSha256}.ghmod.sig`
await copyFile(source, join(output, 'marketplace', 'artifacts', artifactFile))
await copyFile(signatureSource, join(output, 'marketplace', 'artifacts', signatureFile))
entries.push({
itemNumber: manifest.moduleNumber,
artifactKind: 'PHYSICAL_MODULE',
displayName: manifest.displayName,
summary: definition.summary,
version: manifest.version,
minimumHostVersion: manifest.minimumHostVersion,
sourceRepository: 'https://guanghulab.com/code/bingshuo/hololake-system-architecture',
sourceRevision,
sourcePath: `product-source/hololake-native-desktop/fixtures/module-packages/${definition.file}`,
artifactUrl: `https://guanghu.chat/api/hololake/marketplace/artifacts/${artifactFile}`,
artifactSha256,
signatureUrl: `https://guanghu.chat/api/hololake/marketplace/artifacts/${signatureFile}`,
adapter: manifest.adapter,
permissions: manifest.permissions,
executionAuthority: false,
skillReadonlyGuarantee: false,
})
}
const skillFiles = [
'HLP-SKILL-OFFICIAL-DELIVERY-VERIFICATION-0001-0.1.0.ghskill',
'HLP-SKILL-OFFICIAL-MODULE-BOUNDARY-REVIEW-0001-0.1.0.ghskill',
]
for (const file of skillFiles) {
const source = join(root, 'marketplace', 'skills', file)
const raw = await readFile(source)
const skill = JSON.parse(raw)
const artifactSha256 = sha256(raw)
const artifactFile = `${artifactSha256}.ghskill`
await copyFile(source, join(output, 'marketplace', 'artifacts', artifactFile))
entries.push({
itemNumber: skill.manifest.skillNumber,
artifactKind: 'COGNITIVE_SKILL',
displayName: skill.manifest.displayName,
summary: skill.payload.purpose,
version: skill.manifest.version,
minimumHostVersion: skill.manifest.minimumHostVersion,
sourceRepository: 'https://guanghulab.com/code/bingshuo/hololake-system-architecture',
sourceRevision,
sourcePath: `product-source/hololake-native-desktop/marketplace/skills/${file}`,
artifactUrl: `https://guanghu.chat/api/hololake/marketplace/artifacts/${artifactFile}`,
artifactSha256,
signatureUrl: null,
adapter: null,
permissions: [],
executionAuthority: false,
skillReadonlyGuarantee: true,
})
}
entries.sort((left, right) => left.itemNumber.localeCompare(right.itemNumber))
const catalog = {
schema: 'hololake.marketplace.catalog/v1',
planeNumber: 'HLP-DIST-PLANE-0003',
epoch,
generatedAt,
minimumHostVersion: '0.5.0',
contentRootSha256: sha256(Buffer.from(JSON.stringify(canonical(entries)))),
entries,
}
const catalogRaw = jsonBytes(catalog)
await writeFile(join(output, 'marketplace', 'catalog.json'), catalogRaw)
const authorization = {
schema: 'hololake.origin-release-authorization/v1',
releaseId,
sourceRevision,
epoch,
signer: {
signerId: 'HLP-SIGNER-ZERO-POINT-ORIGIN-PUBLIC-0001',
signerClass: 'ZERO_POINT_ORIGIN_PUBLIC_SCOPE_SIGNER',
algorithm: 'Ed25519',
publicKeyBase64,
},
signedObjects: [
{ name: 'zero-core/lamp.json', sha256: sha256(lampRaw), signatureBase64: exactSignature(lampRaw) },
{ name: 'marketplace/catalog.json', sha256: sha256(catalogRaw), signatureBase64: exactSignature(catalogRaw) },
],
}
await writeFile(join(output, 'origin-authorization.json'), jsonBytes(authorization))
await writeFile(join(output, 'release-metadata.json'), jsonBytes({ schema: 'hololake.public-distribution-release/v1', releaseId, epoch, sourceRevision, generatedAt, originPublicKeyBase64: publicKeyBase64, artifacts: entries.map((entry) => ({ name: basename(entry.artifactUrl), sha256: entry.artifactSha256 })) }))
process.stdout.write(`${JSON.stringify({ releaseId, epoch, sourceRevision, itemCount: entries.length, originPublicKeyBase64: publicKeyBase64 })}\n`)

View file

@ -0,0 +1,48 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const contract = JSON.parse(readFileSync(new URL('../contracts/programming-ai-terminal-link.json', import.meta.url)))
const broker = readFileSync(new URL('../src-tauri/src/direct_local_broker.rs', import.meta.url), 'utf8')
const session = readFileSync(new URL('../src-tauri/src/direct_local_session.rs', import.meta.url), 'utf8')
const lib = readFileSync(new URL('../src-tauri/src/lib.rs', import.meta.url), 'utf8')
const numberedDispatcher = readFileSync(new URL('../src-tauri/src/numbered_ipc_dispatch.rs', import.meta.url), 'utf8')
test('terminal link has native local transports for macOS Linux and Windows', () => {
assert.equal(contract.protocol, 'HOLOLAKE_TERMINAL_LINK/3')
assert.equal(contract.numbered_envelope.registry, 'HLP-NBROKER-ROOT-001')
assert.equal(contract.numbered_envelope.legacy_string_operation_allowed, false)
assert.equal(contract.platform_transports.macos, 'USER_PRIVATE_UNIX_SOCKET')
assert.equal(contract.platform_transports.linux, 'USER_PRIVATE_UNIX_SOCKET')
assert.equal(contract.platform_transports.windows, 'USER_PRIVATE_NAMED_PIPE')
assert.match(broker, /GenericFilePath/)
assert.match(broker, /GenericNamespaced/)
assert.match(broker, /WINDOWS_NAMED_PIPE_JSON_LINES/)
assert.match(broker, /D:P\(A;;GA;;;SY\)\(A;;GA;;;OW\)/)
assert.doesNotMatch(lib, /direct_local_broker_windows/)
})
test('HoloLake owns continuity and supplies a bounded work-environment fact frame', () => {
assert.equal(contract.continuity.owner, 'HOLOLAKE')
assert.equal(contract.environment_frame.protocol_restoration_by_model_required, false)
assert.equal(contract.environment_frame.required_before_mutation, true)
assert.match(broker, /VERIFIED_HOLOLAKE_WORK_ENVIRONMENT/)
assert.match(broker, /GLS_RUNTIME_MANIFEST_V2_AND_NATIVE_KERNEL/)
assert.match(broker, /refresh_before_mutation_required/)
assert.match(broker, /protocol_restoration_by_model_required: false/)
})
test('heartbeats refresh the session and environment without granting a shell', () => {
assert.equal(contract.continuity.heartbeat_interval_ms, 15000)
assert.equal(contract.phase_boundary.supervised_shell_execution, false)
assert.match(session, /HEARTBEAT_ACK/)
assert.match(broker, /HEARTBEAT_ACK_ENVIRONMENT_REFRESHED/)
assert.match(numberedDispatcher, /heartbeat_direct_local_session/)
assert.doesNotMatch(lib, /direct_local_session::heartbeat_direct_local_session/)
})
test('transport recovery never blindly replays an uncertain mutation', () => {
assert.equal(contract.continuity.uncertain_mutation_is_never_blindly_replayed, true)
assert.match(broker, /HOLOLAKE_TERMINAL_LINK_RESPONSE_UNCERTAIN/)
assert.match(broker, /safeToRetryAfterStatusRead/)
})

View file

@ -0,0 +1,63 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const read = (path) => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8')
test('number verification is an unknown star abyss and the world stays veiled until it resolves', () => {
const surface = read('src/modules/qoder-surface/StarlakeSurface.tsx')
const styles = read('src/modules/qoder-surface/starlake-surface.css')
const app = read('src/main.tsx')
assert.match(surface, /worldRevealed/)
assert.match(surface, /worldRevealing/)
assert.match(surface, /gateExpanded/)
assert.match(surface, /className=\{`star-abyss-entry/)
assert.match(surface, /className="abyss-field"/)
assert.match(surface, /className="abyss-stars"/)
assert.match(surface, /编号验证/)
assert.match(surface, /验证后展开语言世界/)
assert.doesNotMatch(surface, /lighthouse-/)
assert.doesNotMatch(surface, /光湖灯塔/)
assert.doesNotMatch(surface, /className="channel-entry"/)
assert.match(styles, /\.starlake-scene\.world-veiled \.domains/)
assert.match(styles, /\.starlake-scene\.world-veiled \.masthead/)
assert.match(styles, /\.starlake-scene \.star-abyss-entry\s*\{/)
assert.match(styles, /left:50%/)
assert.match(styles, /@keyframes sl-domain-rise/)
assert.match(styles, /@keyframes sl-abyss-open/)
assert.match(app, /className="star-abyss-dialog"/)
assert.match(app, /语言世界尚未展开/)
assert.match(app, /gateRising \|\| gateStage === 'key'/)
assert.match(app, /gateExpanded=\{gateOpen && gateStage === 'number'\}/)
})
test('main branch and zero domains are public portals with real runtime projections', () => {
const surface = read('src/modules/qoder-surface/StarlakeSurface.tsx')
const app = read('src/main.tsx')
const portal = read('src/modules/public-domain/PublicDomainPortal.tsx')
assert.match(surface, /publicAccess: true/)
assert.equal((surface.match(/publicAccess: true/g) || []).length, 3)
assert.match(app, /openPublicDomain/)
assert.match(app, /<PublicDomainPortal/)
assert.match(portal, /光湖主域/)
assert.match(portal, /光湖分域/)
assert.match(portal, /光湖零域/)
assert.match(portal, /catalogEpoch/)
assert.match(portal, /guanghuEraDay/)
assert.match(portal, /numberCoordinateCount/)
})
test('zero-sense and fifth-domain boundaries remain explicit', () => {
const app = read('src/main.tsx')
const portal = read('src/modules/public-domain/PublicDomainPortal.tsx')
const protectedFacts = app.match(/domain: 'ZERO_SENSE_DOMAIN'[\s\S]*?domain: 'FIFTH_DOMAIN'[\s\S]*?\n \] \},/)?.[0]
assert.match(app, /ZERO_SENSE_DOMAIN.*setActiveDomainInfo/s)
assert.match(app, /FIFTH_DOMAIN.*setActiveDomainInfo/s)
assert.match(portal, /前三域公共只读入口/)
assert.match(portal, /不授予安装、写入或域内管理权限/)
assert.ok(protectedFacts, 'protected domain facts must remain discoverable')
assert.doesNotMatch(protectedFacts, /TCS-GL-|PER-|ICE-GL/)
})

View file

@ -0,0 +1,191 @@
import assert from 'node:assert/strict'
import crypto from 'node:crypto'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import test from 'node:test'
import { activateRelease, verifyReleaseBundle } from '../server/release-broadcast/operator.mjs'
import { loadRuntimeState } from '../server/release-broadcast/server.mjs'
const sha256 = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex')
const writeJson = (file, value) => fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
function buildOperatorFixture() {
const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'hololake-release-operator-fixture-'))
const source = path.join(fixtureRoot, 'source')
const approvals = path.join(fixtureRoot, 'approvals')
const stateRoot = path.join(fixtureRoot, 'state')
for (const directory of [source, approvals, stateRoot]) fs.mkdirSync(directory, { mode: 0o700 })
const packageName = 'HoloLake.app.tar.gz'
const packageBytes = Buffer.from('signed-notarized-updater-package')
const sourceCommit = '2'.repeat(40)
fs.writeFileSync(path.join(source, packageName), packageBytes, { mode: 0o600 })
writeJson(path.join(source, 'HOLOLAKE-CODESIGN.json'), {
schema: 'hololake.platform-code-signature-receipt/v1',
state: 'DEVELOPER_ID_SIGNATURE_STRICT_AND_GATEKEEPER_ACCEPTED',
sourceCommit,
})
writeJson(path.join(source, 'HOLOLAKE-NOTARIZATION.json'), {
schema: 'hololake.apple-notarization-receipt/v1',
state: 'APPLE_NOTARIZATION_ACCEPTED_AND_STAPLED',
sourceCommit,
})
const broadcast = {
schema: 'hololake.release-broadcast/v1',
releaseId: 'GH-HOLOLAKE-RELEASE-0.2.0',
version: '0.2.0',
pub_date: '2026-08-13T10:00:00.000Z',
notes: 'Signed release',
platforms: {
'darwin-aarch64': {
url: `https://guanghulab.com/hololake/releases/0.2.0/${packageName}`,
signature: 'trusted-updater-signature',
size: packageBytes.length,
sha256: sha256(packageBytes),
platformCodeSignatureReceipt: 'HOLOLAKE-CODESIGN',
notarizationReceipt: 'HOLOLAKE-NOTARIZATION',
},
},
hololake: {
features: ['Stage one'],
fixes: [],
compatibility: { minimumVersion: '0.1.0', dataMigrationRequired: false },
restart: { required: true, automaticAllowed: false },
rollback: { supported: true, healthReceiptRequired: true, previousVersion: '0.1.0' },
},
}
const broadcastPath = path.join(source, 'latest.json')
writeJson(broadcastPath, broadcast)
const broadcastSha256 = sha256(fs.readFileSync(broadcastPath))
writeJson(path.join(source, 'pipeline-receipt.json'), {
schema: 'hololake.signed-release-pipeline-receipt/v1',
state: 'SIGNED_NOTARIZED_RELEASE_BROADCAST_READY_FOR_JD_CONTROLLER_UPLOAD',
sourceCommit,
broadcastSha256,
automaticUpload: false,
automaticActivation: false,
})
const approval = path.join(approvals, 'approval.json')
writeJson(approval, {
schema: 'hololake.release-broadcast-human-approval/v1',
state: 'HUMAN_APPROVED_EXACT_SIGNED_NOTARIZED_RELEASE',
approvalId: 'GH-HUMAN-RELEASE-APPROVAL-002',
releaseId: broadcast.releaseId,
version: broadcast.version,
broadcastSha256,
})
return {
fixtureRoot,
source,
approval,
stateRoot,
expected: { releaseId: broadcast.releaseId, version: broadcast.version, sourceCommit, broadcastSha256 },
}
}
test('verify reconstructs and validates an exact private candidate without mutating state', () => {
const fixture = buildOperatorFixture()
try {
const result = verifyReleaseBundle(fixture.source, fixture.approval)
assert.equal(result.state, 'EXACT_SIGNED_NOTARIZED_HUMAN_APPROVED_BUNDLE_VERIFIED')
assert.equal(result.broadcastSha256, fixture.expected.broadcastSha256)
assert.equal(result.artifacts.some((artifact) => artifact.name === 'HoloLake.app.tar.gz'), true)
assert.deepEqual(fs.readdirSync(fixture.stateRoot), [])
} finally {
fs.rmSync(fixture.fixtureRoot, { recursive: true, force: true })
}
})
test('activation repeats expected facts, commits atomically, and still requires explicit restart', () => {
const fixture = buildOperatorFixture()
try {
const receipt = activateRelease({
sourceDirectory: fixture.source,
humanApprovalPath: fixture.approval,
stateRoot: fixture.stateRoot,
expected: fixture.expected,
enforceRootOwner: false,
})
assert.equal(receipt.state, 'ACTIVATED_EXPLICIT_SERVICE_RESTART_REQUIRED')
assert.equal(receipt.automaticUpload, false)
assert.equal(receipt.automaticActivation, false)
assert.equal(receipt.automaticRestart, false)
assert.equal(loadRuntimeState(fixture.stateRoot).state, 'READY_SIGNED_NOTARIZED_BROADCAST')
assert.equal(fs.existsSync(path.join(fixture.stateRoot, '.operator-lock')), false)
} finally {
fs.rmSync(fixture.fixtureRoot, { recursive: true, force: true })
}
})
test('expected-fact mismatch performs no activation or release staging', () => {
const fixture = buildOperatorFixture()
try {
assert.throws(() => activateRelease({
sourceDirectory: fixture.source,
humanApprovalPath: fixture.approval,
stateRoot: fixture.stateRoot,
expected: { ...fixture.expected, broadcastSha256: '3'.repeat(64) },
enforceRootOwner: false,
}), /HOLOLAKE_RELEASE_OPERATOR_EXPECTED_BROADCAST_SHA256_MISMATCH/)
assert.deepEqual(fs.readdirSync(fixture.stateRoot), [])
} finally {
fs.rmSync(fixture.fixtureRoot, { recursive: true, force: true })
}
})
test('human approval cannot be reused after broadcast bytes change', () => {
const fixture = buildOperatorFixture()
try {
const latestPath = path.join(fixture.source, 'latest.json')
const latest = JSON.parse(fs.readFileSync(latestPath, 'utf8'))
latest.notes = 'Changed after approval'
writeJson(latestPath, latest)
assert.throws(
() => verifyReleaseBundle(fixture.source, fixture.approval),
/HOLOLAKE_RELEASE_OPERATOR_PIPELINE_RECEIPT_INVALID/,
)
} finally {
fs.rmSync(fixture.fixtureRoot, { recursive: true, force: true })
}
})
test('symlinked package inputs are rejected instead of followed', () => {
const fixture = buildOperatorFixture()
try {
const packagePath = path.join(fixture.source, 'HoloLake.app.tar.gz')
const moved = path.join(fixture.fixtureRoot, 'moved-package')
fs.renameSync(packagePath, moved)
fs.symlinkSync(moved, packagePath)
assert.throws(
() => verifyReleaseBundle(fixture.source, fixture.approval),
/HOLOLAKE_RELEASE_OPERATOR_FILE_INVALID/,
)
} finally {
fs.rmSync(fixture.fixtureRoot, { recursive: true, force: true })
}
})
test('operator refuses a bundle whose packages escape the registered public path', () => {
const fixture = buildOperatorFixture()
try {
const latestPath = path.join(fixture.source, 'latest.json')
const latest = JSON.parse(fs.readFileSync(latestPath, 'utf8'))
latest.platforms['darwin-aarch64'].url = 'https://guanghulab.com/updates/0.2.0/HoloLake.app.tar.gz'
writeJson(latestPath, latest)
const broadcastSha256 = sha256(fs.readFileSync(latestPath))
const pipelinePath = path.join(fixture.source, 'pipeline-receipt.json')
const pipeline = JSON.parse(fs.readFileSync(pipelinePath, 'utf8'))
pipeline.broadcastSha256 = broadcastSha256
writeJson(pipelinePath, pipeline)
const approval = JSON.parse(fs.readFileSync(fixture.approval, 'utf8'))
approval.broadcastSha256 = broadcastSha256
writeJson(fixture.approval, approval)
assert.throws(
() => verifyReleaseBundle(fixture.source, fixture.approval),
/HOLOLAKE_RELEASE_OPERATOR_PACKAGE_PUBLIC_PREFIX_MISMATCH/,
)
} finally {
fs.rmSync(fixture.fixtureRoot, { recursive: true, force: true })
}
})

View file

@ -0,0 +1,184 @@
import assert from 'node:assert/strict'
import crypto from 'node:crypto'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import test from 'node:test'
import { createReleaseServer, isMainModule, loadRuntimeState } from '../server/release-broadcast/server.mjs'
const sha256 = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex')
const writeJson = (file, value) => fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
async function withServer(state, callback) {
const server = createReleaseServer(state)
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const address = server.address()
try {
return await callback(`http://127.0.0.1:${address.port}`)
} finally {
await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()))
}
}
function buildReleaseRoot() {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hololake-release-broadcast-'))
const releaseDirectory = path.join(root, 'releases', '0.2.0')
fs.mkdirSync(releaseDirectory, { recursive: true })
const packageBytes = Buffer.from('signed-notarized-updater-placeholder')
const packageName = 'HoloLake.app.tar.gz'
fs.writeFileSync(path.join(releaseDirectory, packageName), packageBytes, { mode: 0o600 })
writeJson(path.join(releaseDirectory, 'HOLOLAKE-CODESIGN.json'), {
schema: 'hololake.platform-code-signature-receipt/v1',
state: 'DEVELOPER_ID_SIGNATURE_STRICT_AND_GATEKEEPER_ACCEPTED',
sourceCommit: '1'.repeat(40),
})
writeJson(path.join(releaseDirectory, 'HOLOLAKE-NOTARIZATION.json'), {
schema: 'hololake.apple-notarization-receipt/v1',
state: 'APPLE_NOTARIZATION_ACCEPTED_AND_STAPLED',
sourceCommit: '1'.repeat(40),
})
const broadcast = {
schema: 'hololake.release-broadcast/v1',
releaseId: 'GH-HOLOLAKE-RELEASE-0.2.0',
version: '0.2.0',
pub_date: '2026-08-13T10:00:00.000Z',
notes: 'Signed release',
platforms: {
'darwin-aarch64': {
url: `https://release.guanghu.test/hololake/releases/0.2.0/${packageName}`,
signature: 'trusted-updater-signature',
size: packageBytes.length,
sha256: sha256(packageBytes),
platformCodeSignatureReceipt: 'HOLOLAKE-CODESIGN',
notarizationReceipt: 'HOLOLAKE-NOTARIZATION',
},
},
hololake: {
features: ['Stage one'],
fixes: [],
compatibility: { minimumVersion: '0.1.0', dataMigrationRequired: false },
restart: { required: true, automaticAllowed: false },
rollback: { supported: true, healthReceiptRequired: true, previousVersion: '0.1.0' },
},
}
const broadcastPath = path.join(releaseDirectory, 'latest.json')
writeJson(broadcastPath, broadcast)
const broadcastSha256 = sha256(fs.readFileSync(broadcastPath))
writeJson(path.join(releaseDirectory, 'pipeline-receipt.json'), {
schema: 'hololake.signed-release-pipeline-receipt/v1',
state: 'SIGNED_NOTARIZED_RELEASE_BROADCAST_READY_FOR_JD_CONTROLLER_UPLOAD',
sourceCommit: '1'.repeat(40),
broadcastSha256,
automaticUpload: false,
automaticActivation: false,
})
writeJson(path.join(root, 'ACTIVE.json'), {
schema: 'hololake.release-broadcast-activation/v1',
state: 'HUMAN_APPROVED_SIGNED_NOTARIZED_RELEASE_ACTIVE',
releaseId: broadcast.releaseId,
version: broadcast.version,
broadcastRelativePath: 'releases/0.2.0/latest.json',
broadcastSha256,
pipelineReceiptRelativePath: 'releases/0.2.0/pipeline-receipt.json',
humanApprovalReceipt: 'GH-HUMAN-RELEASE-APPROVAL-001',
humanApprovalReceiptRelativePath: 'releases/0.2.0/human-approval.json',
})
writeJson(path.join(releaseDirectory, 'human-approval.json'), {
schema: 'hololake.release-broadcast-human-approval/v1',
state: 'HUMAN_APPROVED_EXACT_SIGNED_NOTARIZED_RELEASE',
approvalId: 'GH-HUMAN-RELEASE-APPROVAL-001',
releaseId: broadcast.releaseId,
version: broadcast.version,
broadcastSha256,
})
return { root, packageBytes }
}
test('empty release root stays healthy but returns Tauri-compatible 204 no update', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hololake-release-empty-'))
const state = loadRuntimeState(root)
assert.equal(state.state, 'EMPTY_FAIL_CLOSED')
await withServer(state, async (base) => {
const health = await fetch(`${base}/health`)
assert.equal(health.status, 200)
assert.deepEqual((await health.json()).upstreamUpdateSources, [])
assert.equal((await fetch(`${base}/latest.json`)).status, 204)
assert.equal((await fetch(`${base}/hololake/releases/latest.json`)).status, 204)
const publicHealth = await fetch(`${base}/hololake/releases/health`)
assert.equal(publicHealth.status, 200)
assert.equal((await publicHealth.json()).releaseEndpointPath, '/hololake/releases/latest.json')
})
})
test('invalid activation locks the endpoint instead of falling back to an update', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hololake-release-invalid-'))
writeJson(path.join(root, 'ACTIVE.json'), { schema: 'wrong', state: 'ACTIVE' })
const state = loadRuntimeState(root)
assert.equal(state.state, 'LOCKED_INVALID_RELEASE_EVIDENCE')
await withServer(state, async (base) => {
assert.equal((await fetch(`${base}/health`)).status, 503)
assert.equal((await fetch(`${base}/latest.json`)).status, 503)
})
})
test('only an exact human-approved signed notarized evidence chain becomes readable', async () => {
const fixture = buildReleaseRoot()
const state = loadRuntimeState(fixture.root)
assert.equal(state.state, 'READY_SIGNED_NOTARIZED_BROADCAST')
await withServer(state, async (base) => {
const latest = await fetch(`${base}/latest.json`)
assert.equal(latest.status, 200)
assert.equal((await latest.json()).releaseId, 'GH-HOLOLAKE-RELEASE-0.2.0')
const publicLatest = await fetch(`${base}/hololake/releases/latest.json`)
assert.equal(publicLatest.status, 200)
assert.equal((await publicLatest.json()).releaseId, 'GH-HOLOLAKE-RELEASE-0.2.0')
const updater = await fetch(`${base}/hololake/releases/0.2.0/HoloLake.app.tar.gz`)
assert.equal(updater.status, 200)
assert.deepEqual(Buffer.from(await updater.arrayBuffer()), fixture.packageBytes)
assert.equal((await fetch(`${base}/unknown`)).status, 404)
})
})
test('package tampering after pipeline output locks the whole release at startup', () => {
const fixture = buildReleaseRoot()
fs.appendFileSync(path.join(fixture.root, 'releases', '0.2.0', 'HoloLake.app.tar.gz'), 'tampered')
assert.equal(loadRuntimeState(fixture.root).state, 'LOCKED_INVALID_RELEASE_EVIDENCE')
})
test('a symlinked immutable current directory is recognized as the intended executable', () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hololake-release-symlink-'))
const versionDirectory = path.join(root, 'immutable')
fs.mkdirSync(versionDirectory)
const source = fs.readFileSync(new URL('../server/release-broadcast/server.mjs', import.meta.url), 'utf8')
const copy = path.join(versionDirectory, 'server.mjs')
fs.writeFileSync(copy, source, { mode: 0o500 })
const current = path.join(root, 'current')
fs.symlinkSync(versionDirectory, current)
assert.equal(isMainModule(path.join(current, 'server.mjs'), new URL(`file://${copy}`)), true)
})
test('a package outside the registered public prefix locks the release', () => {
const fixture = buildReleaseRoot()
const latestPath = path.join(fixture.root, 'releases', '0.2.0', 'latest.json')
const latest = JSON.parse(fs.readFileSync(latestPath, 'utf8'))
latest.platforms['darwin-aarch64'].url = 'https://release.guanghu.test/releases/0.2.0/HoloLake.app.tar.gz'
writeJson(latestPath, latest)
const broadcastSha256 = sha256(fs.readFileSync(latestPath))
const pipelinePath = path.join(fixture.root, 'releases', '0.2.0', 'pipeline-receipt.json')
const pipeline = JSON.parse(fs.readFileSync(pipelinePath, 'utf8'))
pipeline.broadcastSha256 = broadcastSha256
writeJson(pipelinePath, pipeline)
const approvalPath = path.join(fixture.root, 'releases', '0.2.0', 'human-approval.json')
const approval = JSON.parse(fs.readFileSync(approvalPath, 'utf8'))
approval.broadcastSha256 = broadcastSha256
writeJson(approvalPath, approval)
const activationPath = path.join(fixture.root, 'ACTIVE.json')
const activation = JSON.parse(fs.readFileSync(activationPath, 'utf8'))
activation.broadcastSha256 = broadcastSha256
writeJson(activationPath, activation)
const state = loadRuntimeState(fixture.root)
assert.equal(state.state, 'LOCKED_INVALID_RELEASE_EVIDENCE')
assert.equal(state.reasonCode, 'HOLOLAKE_RELEASE_PACKAGE_PUBLIC_PREFIX_MISMATCH')
})

View file

@ -0,0 +1,22 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { renderFrontDoorSnippet } from '../server/release-broadcast/render-front-door.mjs'
test('front-door renderer refuses an unassigned or privileged loopback port', () => {
assert.throws(() => renderFrontDoorSnippet(null), /PORT_REQUIRED/)
assert.throws(() => renderFrontDoorSnippet(443), /PORT_REQUIRED|PORT_INVALID/)
assert.throws(() => renderFrontDoorSnippet('not-a-port'), /PORT_REQUIRED/)
})
test('rendered proxy preserves the public path and strips request authority', () => {
const snippet = renderFrontDoorSnippet(23940)
assert.match(snippet, /location \^~ \/hololake\/releases\//)
assert.match(snippet, /proxy_pass http:\/\/127\.0\.0\.1:23940;/)
assert.doesNotMatch(snippet, /proxy_pass http:\/\/127\.0\.0\.1:23940\//)
assert.match(snippet, /limit_except GET HEAD \{ deny all; \}/)
assert.match(snippet, /proxy_pass_request_body off;/)
assert.match(snippet, /proxy_set_header Authorization "";/)
assert.match(snippet, /proxy_set_header Cookie "";/)
assert.match(snippet, /proxy_set_header X-Forwarded-For "";/)
})

View file

@ -0,0 +1,498 @@
#!/usr/bin/env node
import { execFileSync, spawnSync } from 'node:child_process'
import crypto from 'node:crypto'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const PUBLIC_RELEASE_ENDPOINT_PATH = '/hololake/releases/latest.json'
const PUBLIC_RELEASE_PREFIX = '/hololake/releases'
const fail = (code) => {
throw new Error(code)
}
const requireText = (value, code) => {
if (typeof value !== 'string' || value.trim() === '') fail(code)
return value.trim()
}
const readJson = (file) => JSON.parse(fs.readFileSync(file, 'utf8'))
const sha256File = (file) => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex')
export function validateReleaseTrust(trust) {
if (trust?.schema !== 'hololake.release-trust/v1') fail('HOLOLAKE_RELEASE_PIPELINE_TRUST_SCHEMA_INVALID')
if (trust.state !== 'PROVISIONED') fail('HOLOLAKE_RELEASE_PIPELINE_TRUST_UNPROVISIONED')
if (!Array.isArray(trust.endpoints) || trust.endpoints.length !== 1) fail('HOLOLAKE_RELEASE_PIPELINE_EXACT_ENDPOINT_REQUIRED')
if (!Array.isArray(trust.allowedReleaseHosts) || trust.allowedReleaseHosts.length !== 1) fail('HOLOLAKE_RELEASE_PIPELINE_EXACT_HOST_REQUIRED')
const endpoint = new URL(trust.endpoints[0])
const host = requireText(trust.allowedReleaseHosts[0], 'HOLOLAKE_RELEASE_PIPELINE_HOST_REQUIRED')
if (
endpoint.protocol !== 'https:' ||
endpoint.hostname !== host ||
endpoint.username ||
endpoint.password ||
endpoint.search ||
endpoint.hash ||
endpoint.pathname !== PUBLIC_RELEASE_ENDPOINT_PATH
) {
fail('HOLOLAKE_RELEASE_PIPELINE_ENDPOINT_NOT_HOLOLAKE_HTTPS')
}
if (requireText(trust.publicKey, 'HOLOLAKE_RELEASE_PIPELINE_UPDATER_PUBLIC_KEY_REQUIRED').length < 32) {
fail('HOLOLAKE_RELEASE_PIPELINE_UPDATER_PUBLIC_KEY_INVALID')
}
if (trust.automaticCheckOnStartup || trust.automaticDownload || trust.automaticRestart || !trust.humanOptInInstallRequired) {
fail('HOLOLAKE_RELEASE_PIPELINE_HUMAN_CONTROL_POLICY_INVALID')
}
return { endpoint, host }
}
export function validateReleaseInput(input, trustFacts) {
if (input?.schema !== 'hololake.release-pipeline-input/v1') fail('HOLOLAKE_RELEASE_PIPELINE_INPUT_SCHEMA_INVALID')
const version = requireText(input.version, 'HOLOLAKE_RELEASE_PIPELINE_VERSION_REQUIRED')
if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version)) {
fail('HOLOLAKE_RELEASE_PIPELINE_VERSION_INVALID')
}
if (input.platformCode !== 'darwin-aarch64') fail('HOLOLAKE_RELEASE_PIPELINE_PLATFORM_NOT_IMPLEMENTED')
if (!/^[a-f0-9]{40}$/.test(input.sourceCommit || '')) fail('HOLOLAKE_RELEASE_PIPELINE_SOURCE_COMMIT_INVALID')
if (input.releaseTag !== `v${version}`) fail('HOLOLAKE_RELEASE_PIPELINE_IMMUTABLE_TAG_INVALID')
const packageUrl = new URL(requireText(input.packageUrl, 'HOLOLAKE_RELEASE_PIPELINE_PACKAGE_URL_REQUIRED'))
if (
packageUrl.protocol !== 'https:' ||
packageUrl.hostname !== trustFacts.host ||
packageUrl.username ||
packageUrl.password ||
packageUrl.search ||
packageUrl.hash ||
!packageUrl.pathname.startsWith(`${PUBLIC_RELEASE_PREFIX}/`)
) {
fail('HOLOLAKE_RELEASE_PIPELINE_PACKAGE_HOST_NOT_TRUSTED')
}
if (!Array.isArray(input.features) || input.features.length === 0 || input.features.some((item) => typeof item !== 'string' || !item.trim())) {
fail('HOLOLAKE_RELEASE_PIPELINE_FEATURES_REQUIRED')
}
if (!Array.isArray(input.fixes) || input.fixes.some((item) => typeof item !== 'string' || !item.trim())) {
fail('HOLOLAKE_RELEASE_PIPELINE_FIXES_INVALID')
}
for (const [field, code] of [
['releaseId', 'HOLOLAKE_RELEASE_PIPELINE_RELEASE_ID_REQUIRED'],
['previousVersion', 'HOLOLAKE_RELEASE_PIPELINE_PREVIOUS_VERSION_REQUIRED'],
['minimumVersion', 'HOLOLAKE_RELEASE_PIPELINE_MINIMUM_VERSION_REQUIRED'],
['notes', 'HOLOLAKE_RELEASE_PIPELINE_NOTES_REQUIRED'],
['restartMessage', 'HOLOLAKE_RELEASE_PIPELINE_RESTART_MESSAGE_REQUIRED'],
['appleTeamIdentifier', 'HOLOLAKE_RELEASE_PIPELINE_APPLE_TEAM_REQUIRED'],
]) requireText(input[field], code)
if (typeof input.dataMigrationRequired !== 'boolean') fail('HOLOLAKE_RELEASE_PIPELINE_MIGRATION_FLAG_REQUIRED')
return { ...input, version, packageUrl }
}
export function validateCredentialEnvironment(env) {
const required = [
'APPLE_SIGNING_IDENTITY',
'TAURI_SIGNING_PRIVATE_KEY_PASSWORD',
]
const missing = required.filter((name) => typeof env[name] !== 'string' || env[name].trim() === '')
if (!env.TAURI_SIGNING_PRIVATE_KEY && !env.TAURI_SIGNING_PRIVATE_KEY_PATH) {
missing.push('TAURI_SIGNING_PRIVATE_KEY_OR_PATH')
} else if (env.TAURI_SIGNING_PRIVATE_KEY_PATH && !fs.statSync(env.TAURI_SIGNING_PRIVATE_KEY_PATH, { throwIfNoEntry: false })?.isFile()) {
missing.push('TAURI_SIGNING_PRIVATE_KEY_PATH_NOT_READABLE')
}
const appleIdFlow = env.APPLE_ID && env.APPLE_PASSWORD && env.APPLE_TEAM_ID
const appleApiFlow = env.APPLE_API_KEY && env.APPLE_API_ISSUER && env.APPLE_API_KEY_PATH
const xcodeOrganizerFlow = env.APPLE_XCODE_ORGANIZER_FLOW === '1'
if (!appleIdFlow && !appleApiFlow && !xcodeOrganizerFlow) missing.push('APPLE_NOTARIZATION_CREDENTIAL_SET')
if (missing.length) fail(`HOLOLAKE_RELEASE_PIPELINE_CREDENTIALS_MISSING:${[...new Set(missing)].sort().join(',')}`)
return xcodeOrganizerFlow ? 'XCODE_ORGANIZER' : 'TAURI_AUTOMATED'
}
export function materializeUpdaterPrivateKey(env, readText = (file) => fs.readFileSync(file, 'utf8')) {
if (typeof env.TAURI_SIGNING_PRIVATE_KEY === 'string' && env.TAURI_SIGNING_PRIVATE_KEY.trim()) {
return { ...env }
}
const privateKeyPath = requireText(
env.TAURI_SIGNING_PRIVATE_KEY_PATH,
'HOLOLAKE_RELEASE_PIPELINE_UPDATER_PRIVATE_KEY_PATH_REQUIRED',
)
const privateKey = requireText(
readText(privateKeyPath),
'HOLOLAKE_RELEASE_PIPELINE_UPDATER_PRIVATE_KEY_EMPTY',
)
const { TAURI_SIGNING_PRIVATE_KEY_PATH: _privateKeyPath, ...childEnvironment } = env
return {
...childEnvironment,
TAURI_SIGNING_PRIVATE_KEY: privateKey,
}
}
function run(program, args, options = {}) {
return execFileSync(program, args, {
cwd: options.cwd || root,
encoding: 'utf8',
stdio: options.capture ? ['ignore', 'pipe', 'pipe'] : 'inherit',
env: options.env || process.env,
})
}
function tryRun(program, args, options = {}) {
const result = spawnSync(program, args, {
cwd: options.cwd || root,
encoding: 'utf8',
env: options.env || process.env,
})
return {
ok: !result.error && result.status === 0,
output: `${result.stdout || ''}\n${result.stderr || ''}`.trim(),
}
}
function captureAll(program, args) {
const result = spawnSync(program, args, { cwd: root, encoding: 'utf8', env: process.env })
if (result.error) throw result.error
if (result.status !== 0) fail(`HOLOLAKE_RELEASE_PIPELINE_COMMAND_FAILED:${program}`)
return `${result.stdout || ''}\n${result.stderr || ''}`
}
function requireCleanImmutableSource(input) {
if (run('git', ['status', '--porcelain'], { capture: true }).trim()) fail('HOLOLAKE_RELEASE_PIPELINE_SOURCE_NOT_CLEAN')
if (run('git', ['branch', '--show-current'], { capture: true }).trim() !== 'main') fail('HOLOLAKE_RELEASE_PIPELINE_MAIN_BRANCH_REQUIRED')
const head = run('git', ['rev-parse', 'HEAD'], { capture: true }).trim()
if (head !== input.sourceCommit) fail('HOLOLAKE_RELEASE_PIPELINE_SOURCE_COMMIT_MISMATCH')
const tagCommit = run('git', ['rev-list', '-n', '1', input.releaseTag], { capture: true }).trim()
if (tagCommit !== head) fail('HOLOLAKE_RELEASE_PIPELINE_TAG_COMMIT_MISMATCH')
const packageDocument = readJson(path.join(root, 'package.json'))
const tauriDocument = readJson(path.join(root, 'src-tauri/tauri.conf.json'))
if (packageDocument.version !== input.version || tauriDocument.version !== input.version) {
fail('HOLOLAKE_RELEASE_PIPELINE_VERSION_FILES_MISMATCH')
}
}
function findOne(rootPath, predicate, code) {
const matches = []
const visit = (directory) => {
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
const file = path.join(directory, entry.name)
if (entry.isDirectory()) visit(file)
else if (entry.isFile() && predicate(file)) matches.push(file)
}
}
if (fs.existsSync(rootPath)) visit(rootPath)
if (matches.length !== 1) fail(`${code}:${matches.length}`)
return matches[0]
}
function codeSignatureEvidence(appPath, input) {
run('/usr/bin/codesign', ['--verify', '--deep', '--strict', '--verbose=4', appPath])
const display = captureAll('/usr/bin/codesign', ['-dv', '--verbose=4', appPath])
const value = (name) => display.split('\n').find((line) => line.startsWith(`${name}=`))?.slice(name.length + 1)
if (value('Identifier') !== 'world.guanghu.hololake' || value('TeamIdentifier') !== input.appleTeamIdentifier) {
fail('HOLOLAKE_RELEASE_PIPELINE_CODE_SIGNATURE_IDENTITY_MISMATCH')
}
run('/usr/sbin/spctl', ['--assess', '--type', 'execute', '--verbose=4', appPath])
run('/usr/bin/xcrun', ['stapler', 'validate', appPath])
return {
schema: 'hololake.platform-code-signature-receipt/v1',
state: 'DEVELOPER_ID_SIGNATURE_STRICT_AND_GATEKEEPER_ACCEPTED',
identifier: value('Identifier'),
teamIdentifier: value('TeamIdentifier'),
cdHash: value('CDHash'),
executableSha256: sha256File(path.join(appPath, 'Contents/MacOS/hololake-native-desktop')),
sourceCommit: input.sourceCommit,
}
}
function notarizationEvidence(appPath, dmgPath, input, options = {}) {
const dmgGatekeeper = tryRun('/usr/sbin/spctl', ['--assess', '--type', 'open', '--context', 'context:primary-signature', '--verbose=4', dmgPath])
const dmgStapler = tryRun('/usr/bin/xcrun', ['stapler', 'validate', dmgPath])
if (options.requireNotarizedDmg && (!dmgGatekeeper.ok || !dmgStapler.ok)) {
fail('HOLOLAKE_RELEASE_PIPELINE_DMG_NOTARIZATION_REQUIRED')
}
return {
schema: 'hololake.apple-notarization-receipt/v1',
state: dmgGatekeeper.ok && dmgStapler.ok
? 'APPLE_APP_AND_DMG_NOTARIZATION_ACCEPTED_AND_STAPLED'
: 'APPLE_APP_NOTARIZATION_ACCEPTED_AND_STAPLED_DMG_CONTAINS_NOTARIZED_APP',
appName: path.basename(appPath),
dmgName: path.basename(dmgPath),
appStaplerValidation: 'PASS',
dmgGatekeeperAssessment: dmgGatekeeper.ok ? 'PASS' : 'NOT_ASSERTED_FOR_XCODE_EXPORTED_APP_FLOW',
dmgStaplerValidation: dmgStapler.ok ? 'PASS' : 'NOT_STAPLED_OUTER_CONTAINER',
...(process.env.APPLE_XCODE_SUBMISSION_ID ? { submissionIdentifier: process.env.APPLE_XCODE_SUBMISSION_ID } : {}),
appleTeamIdentifier: input.appleTeamIdentifier,
sourceCommit: input.sourceCommit,
}
}
function writeJson(file, value) {
fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' })
}
function localDateDirectory() {
const date = new Date()
const part = (value) => String(value).padStart(2, '0')
return `${date.getFullYear()}-${part(date.getMonth() + 1)}-${part(date.getDate())}`
}
function unsignedExecutableSha256(executable) {
const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'hololake-unsigned-executable-'))
const copy = path.join(temporary, path.basename(executable))
try {
fs.copyFileSync(executable, copy)
run('/usr/bin/codesign', ['--remove-signature', copy])
return sha256File(copy)
} finally {
fs.rmSync(temporary, { recursive: true, force: true })
}
}
export function formatPlistDate(date) {
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
const part = (value) => String(value).padStart(2, '0')
return `${weekdays[date.getUTCDay()]} ${months[date.getUTCMonth()]} ${part(date.getUTCDate())} ${part(date.getUTCHours())}:${part(date.getUTCMinutes())}:${part(date.getUTCSeconds())} ${date.getUTCFullYear()}`
}
function createXcodeArchive(application, input) {
const archive = path.join(
os.homedir(),
'Library/Developer/Xcode/Archives',
localDateDirectory(),
`HoloLake-${input.version}-${input.sourceCommit.slice(0, 12)}.xcarchive`,
)
if (fs.existsSync(archive)) fail('HOLOLAKE_RELEASE_PIPELINE_XCODE_ARCHIVE_ALREADY_EXISTS')
const archivedApp = path.join(archive, 'Products/Applications/HoloLake.app')
fs.mkdirSync(path.dirname(archivedApp), { recursive: true, mode: 0o700 })
run('/usr/bin/ditto', [application, archivedApp])
const info = path.join(archive, 'Info.plist')
run('/usr/bin/plutil', ['-create', 'xml1', info])
const add = (key, type, value) => run('/usr/libexec/PlistBuddy', ['-c', `Add :${key} ${type} ${value}`, info])
add('ArchiveVersion', 'integer', '2')
add('CreationDate', 'date', formatPlistDate(new Date()))
add('Name', 'string', `HoloLake ${input.version} ${input.sourceCommit.slice(0, 12)}`)
add('SchemeName', 'string', 'HoloLake')
add('HoloLakeSourceCommit', 'string', input.sourceCommit)
const executable = path.join(application, 'Contents/MacOS/hololake-native-desktop')
add('HoloLakePreNotarizationExecutableSha256', 'string', sha256File(executable))
add('HoloLakeUnsignedExecutableSha256', 'string', unsignedExecutableSha256(executable))
add('ApplicationProperties', 'dict', '')
add('ApplicationProperties:ApplicationPath', 'string', 'Applications/HoloLake.app')
add('ApplicationProperties:ArchiveVersion', 'integer', '2')
add('ApplicationProperties:CFBundleIdentifier', 'string', 'world.guanghu.hololake')
add('ApplicationProperties:CFBundleShortVersionString', 'string', input.version)
add('ApplicationProperties:CFBundleVersion', 'string', input.version)
add('ApplicationProperties:SigningIdentity', 'string', process.env.APPLE_SIGNING_IDENTITY)
add('ApplicationProperties:Team', 'string', input.appleTeamIdentifier)
return archive
}
function findPreparedXcodeArchive(input) {
const archivesRoot = path.join(os.homedir(), 'Library/Developer/Xcode/Archives')
const archiveName = `HoloLake-${input.version}-${input.sourceCommit.slice(0, 12)}.xcarchive`
const matches = []
for (const dateEntry of fs.readdirSync(archivesRoot, { withFileTypes: true })) {
if (!dateEntry.isDirectory()) continue
const candidate = path.join(archivesRoot, dateEntry.name, archiveName)
if (fs.statSync(candidate, { throwIfNoEntry: false })?.isDirectory()) matches.push(candidate)
}
if (matches.length !== 1) fail(`HOLOLAKE_RELEASE_PIPELINE_PREPARED_XCODE_ARCHIVE_NOT_UNIQUE:${matches.length}`)
return matches[0]
}
function resolveNotarizedApplication(argument, input) {
const candidate = path.resolve(requireText(argument, 'HOLOLAKE_RELEASE_PIPELINE_NOTARIZED_APP_PATH_REQUIRED'))
const application = candidate.endsWith('.app') ? candidate : path.join(candidate, 'HoloLake.app')
if (!fs.statSync(application, { throwIfNoEntry: false })?.isDirectory()) {
fail('HOLOLAKE_RELEASE_PIPELINE_NOTARIZED_APP_NOT_FOUND')
}
const info = path.join(application, 'Contents/Info.plist')
const identifier = run('/usr/libexec/PlistBuddy', ['-c', 'Print :CFBundleIdentifier', info], { capture: true }).trim()
const version = run('/usr/libexec/PlistBuddy', ['-c', 'Print :CFBundleShortVersionString', info], { capture: true }).trim()
if (identifier !== 'world.guanghu.hololake' || version !== input.version) {
fail('HOLOLAKE_RELEASE_PIPELINE_NOTARIZED_APP_IDENTITY_MISMATCH')
}
const archive = findPreparedXcodeArchive(input)
const expectedUnsignedExecutableSha256 = run('/usr/libexec/PlistBuddy', [
'-c', 'Print :HoloLakeUnsignedExecutableSha256', path.join(archive, 'Info.plist'),
], { capture: true }).trim()
const actualUnsignedExecutableSha256 = unsignedExecutableSha256(
path.join(application, 'Contents/MacOS/hololake-native-desktop'),
)
if (actualUnsignedExecutableSha256 !== expectedUnsignedExecutableSha256) {
fail('HOLOLAKE_RELEASE_PIPELINE_NOTARIZED_APP_SOURCE_BINARY_MISMATCH')
}
return application
}
function buildUpdaterFromNotarizedApp(application, destination, credentialEnvironment) {
const updater = path.join(destination, 'HoloLake.app.tar.gz')
run('/usr/bin/tar', ['-czf', updater, '-C', path.dirname(application), path.basename(application)])
run('npm', ['run', 'tauri', '--', 'signer', 'sign', updater], { env: credentialEnvironment })
const signature = `${updater}.sig`
if (!fs.statSync(signature, { throwIfNoEntry: false })?.isFile()) {
fail('HOLOLAKE_RELEASE_PIPELINE_UPDATER_SIGNATURE_MISSING')
}
return { updater, signature }
}
function buildDmgFromNotarizedApp(application, destination, input) {
const staging = path.join(destination, 'dmg-root')
fs.mkdirSync(staging, { recursive: true, mode: 0o700 })
run('/usr/bin/ditto', [application, path.join(staging, 'HoloLake.app')])
fs.symlinkSync('/Applications', path.join(staging, 'Applications'))
const dmg = path.join(destination, `HoloLake_${input.version}_aarch64.dmg`)
run('/usr/bin/hdiutil', ['create', '-volname', 'HoloLake', '-srcfolder', staging, '-ov', '-format', 'UDZO', dmg])
run('/usr/bin/codesign', ['--force', '--timestamp', '--sign', process.env.APPLE_SIGNING_IDENTITY, dmg])
return dmg
}
function writeReleaseOutput(input, trustFacts, application, updater, updaterSignature, dmg, options = {}) {
if (decodeURIComponent(input.packageUrl.pathname.split('/').pop()) !== path.basename(updater)) {
fail('HOLOLAKE_RELEASE_PIPELINE_PACKAGE_URL_FILENAME_MISMATCH')
}
const codeReceipt = codeSignatureEvidence(application, input)
const notarizationReceipt = notarizationEvidence(application, dmg, input, options)
const outputRoot = path.join(root, 'release/out', input.version)
if (fs.existsSync(outputRoot)) fail('HOLOLAKE_RELEASE_PIPELINE_OUTPUT_ALREADY_EXISTS')
fs.mkdirSync(outputRoot, { recursive: true, mode: 0o700 })
const codeReceiptId = `HOLOLAKE-CODESIGN-${input.version}-${input.sourceCommit.slice(0, 12)}`
const notarizationReceiptId = `HOLOLAKE-NOTARIZATION-${input.version}-${input.sourceCommit.slice(0, 12)}`
writeJson(path.join(outputRoot, `${codeReceiptId}.json`), codeReceipt)
writeJson(path.join(outputRoot, `${notarizationReceiptId}.json`), notarizationReceipt)
fs.copyFileSync(updater, path.join(outputRoot, path.basename(updater)), fs.constants.COPYFILE_EXCL)
fs.copyFileSync(updaterSignature, path.join(outputRoot, path.basename(updaterSignature)), fs.constants.COPYFILE_EXCL)
fs.copyFileSync(dmg, path.join(outputRoot, path.basename(dmg)), fs.constants.COPYFILE_EXCL)
const broadcast = {
schema: 'hololake.release-broadcast/v1',
releaseId: input.releaseId,
version: input.version,
pub_date: new Date().toISOString(),
notes: input.notes,
platforms: {
[input.platformCode]: {
url: input.packageUrl.toString(),
signature: fs.readFileSync(updaterSignature, 'utf8').trim(),
size: fs.statSync(updater).size,
sha256: sha256File(updater),
platformCodeSignatureReceipt: codeReceiptId,
notarizationReceipt: notarizationReceiptId,
},
},
hololake: {
features: input.features,
fixes: input.fixes,
compatibility: {
minimumVersion: input.minimumVersion,
dataMigrationRequired: input.dataMigrationRequired,
...(input.compatibilityNotes ? { notes: input.compatibilityNotes } : {}),
},
restart: { required: true, automaticAllowed: false, message: input.restartMessage },
rollback: { supported: true, healthReceiptRequired: true, previousVersion: input.previousVersion },
},
}
writeJson(path.join(outputRoot, 'latest.json'), broadcast)
writeJson(path.join(outputRoot, 'pipeline-receipt.json'), {
schema: 'hololake.signed-release-pipeline-receipt/v1',
state: 'SIGNED_NOTARIZED_RELEASE_BROADCAST_READY_FOR_JD_CONTROLLER_UPLOAD',
sourceCommit: input.sourceCommit,
releaseTag: input.releaseTag,
releaseEndpoint: trustFacts.endpoint.toString(),
broadcastSha256: sha256File(path.join(outputRoot, 'latest.json')),
automaticUpload: false,
automaticActivation: false,
})
process.stdout.write(`HOLOLAKE_RELEASE_PIPELINE_READY:${outputRoot}\n`)
}
export async function main(argv = process.argv.slice(2)) {
const inputArgument = argv[0]
if (!inputArgument) fail('HOLOLAKE_RELEASE_PIPELINE_INPUT_PATH_REQUIRED')
const command = argv[1] || 'release'
if (!['release', 'prepare-xcode', 'finalize-xcode'].includes(command)) {
fail('HOLOLAKE_RELEASE_PIPELINE_COMMAND_INVALID')
}
const inputPath = path.resolve(inputArgument)
const trust = readJson(path.join(root, 'src-tauri/release-trust.json'))
const trustFacts = validateReleaseTrust(trust)
const input = validateReleaseInput(readJson(inputPath), trustFacts)
const notarizationMode = validateCredentialEnvironment(process.env)
if (command !== 'release' && notarizationMode !== 'XCODE_ORGANIZER') {
fail('HOLOLAKE_RELEASE_PIPELINE_XCODE_ORGANIZER_FLOW_REQUIRED')
}
const credentialEnvironment = materializeUpdaterPrivateKey(process.env)
requireCleanImmutableSource(input)
if (process.platform !== 'darwin' || process.arch !== 'arm64') fail('HOLOLAKE_RELEASE_PIPELINE_BUILD_HOST_MISMATCH')
if (!process.env.APPLE_SIGNING_IDENTITY.includes(input.appleTeamIdentifier)) fail('HOLOLAKE_RELEASE_PIPELINE_SIGNING_TEAM_MISMATCH')
if (command === 'finalize-xcode') {
const application = resolveNotarizedApplication(argv[2], input)
const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'hololake-release-finalize-'))
try {
const { updater, signature } = buildUpdaterFromNotarizedApp(application, temporary, credentialEnvironment)
run('cargo', [
'run', '--quiet', '--manifest-path', 'src-tauri/Cargo.toml', '--example', 'verify_updater_signature', '--',
'src-tauri/release-trust.json', updater, signature,
])
const dmg = buildDmgFromNotarizedApp(application, temporary, input)
writeReleaseOutput(input, trustFacts, application, updater, signature, dmg, { requireNotarizedDmg: false })
} finally {
fs.rmSync(temporary, { recursive: true, force: true })
}
return
}
run('npm', ['test'])
run('cargo', ['clippy', '--manifest-path', 'src-tauri/Cargo.toml', '--all-targets', '--all-features', '--', '-D', 'warnings'])
run('cargo', ['test', '--manifest-path', 'src-tauri/Cargo.toml', '--all-targets', '--all-features'])
const buildConfig = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'hololake-release-config-')), 'tauri.release.json')
fs.writeFileSync(buildConfig, `${JSON.stringify({ bundle: { createUpdaterArtifacts: true } })}\n`, { mode: 0o600 })
try {
run('npm', ['run', 'tauri', '--', 'build', '--ci', '--config', buildConfig], {
env: credentialEnvironment,
})
} finally {
fs.rmSync(path.dirname(buildConfig), { recursive: true, force: true })
}
const bundleRoot = path.join(root, 'src-tauri/target/release/bundle')
const appExecutable = findOne(path.join(bundleRoot, 'macos'), (file) => file.endsWith('/Contents/MacOS/hololake-native-desktop'), 'HOLOLAKE_RELEASE_PIPELINE_APP_NOT_UNIQUE')
const application = path.resolve(appExecutable, '../../..')
const dmg = findOne(path.join(bundleRoot, 'dmg'), (file) => file.endsWith('.dmg'), 'HOLOLAKE_RELEASE_PIPELINE_DMG_NOT_UNIQUE')
const updater = findOne(bundleRoot, (file) => file.endsWith('.app.tar.gz'), 'HOLOLAKE_RELEASE_PIPELINE_UPDATER_NOT_UNIQUE')
const updaterSignature = `${updater}.sig`
if (!fs.statSync(updaterSignature, { throwIfNoEntry: false })?.isFile()) fail('HOLOLAKE_RELEASE_PIPELINE_UPDATER_SIGNATURE_MISSING')
run('cargo', [
'run',
'--quiet',
'--manifest-path',
'src-tauri/Cargo.toml',
'--example',
'verify_updater_signature',
'--',
'src-tauri/release-trust.json',
updater,
updaterSignature,
])
if (command === 'prepare-xcode') {
run('/usr/bin/codesign', ['--verify', '--deep', '--strict', '--verbose=4', application])
const archive = createXcodeArchive(application, input)
process.stdout.write(`HOLOLAKE_RELEASE_XCODE_ARCHIVE_READY:${archive}\n`)
return
}
if (decodeURIComponent(input.packageUrl.pathname.split('/').pop()) !== path.basename(updater)) {
fail('HOLOLAKE_RELEASE_PIPELINE_PACKAGE_URL_FILENAME_MISMATCH')
}
writeReleaseOutput(input, trustFacts, application, updater, updaterSignature, dmg, { requireNotarizedDmg: true })
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
main().catch((error) => {
process.stderr.write(`${error.message}\n`)
process.exitCode = 1
})
}

View file

@ -0,0 +1,128 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import {
formatPlistDate,
materializeUpdaterPrivateKey,
validateCredentialEnvironment,
validateReleaseInput,
validateReleaseTrust,
} from './release-pipeline.mjs'
const readyTrust = () => ({
schema: 'hololake.release-trust/v1',
state: 'PROVISIONED',
endpoints: ['https://release.guanghu.test/hololake/releases/latest.json'],
publicKey: 'A'.repeat(64),
allowedReleaseHosts: ['release.guanghu.test'],
automaticCheckOnStartup: false,
automaticDownload: false,
humanOptInInstallRequired: true,
automaticRestart: false,
})
const readyInput = () => ({
schema: 'hololake.release-pipeline-input/v1',
releaseId: 'GH-HOLOLAKE-RELEASE-0.2.0',
version: '0.2.0',
previousVersion: '0.1.0',
minimumVersion: '0.1.0',
releaseTag: 'v0.2.0',
sourceCommit: 'a'.repeat(40),
platformCode: 'darwin-aarch64',
packageUrl: 'https://release.guanghu.test/hololake/releases/0.2.0/HoloLake.app.tar.gz',
appleTeamIdentifier: '825A9L3G7Q',
notes: 'Signed release',
features: ['Persistent direct connection'],
fixes: [],
dataMigrationRequired: false,
restartMessage: 'Restart manually',
})
test('Xcode archive creation uses the plist date format accepted by PlistBuddy', () => {
assert.equal(formatPlistDate(new Date('2026-08-19T01:02:03Z')), 'Wed Aug 19 01:02:03 2026')
})
test('release pipeline refuses an unprovisioned or upstream-owned trust document', () => {
const unprovisioned = readyTrust()
unprovisioned.state = 'UNPROVISIONED_FAIL_CLOSED'
assert.throws(() => validateReleaseTrust(unprovisioned), /TRUST_UNPROVISIONED/)
const upstream = readyTrust()
upstream.endpoints = ['https://updates.vendor.test/latest.json']
assert.throws(() => validateReleaseTrust(upstream), /ENDPOINT_NOT_HOLOLAKE_HTTPS/)
})
test('release package must use the exact registered HoloLake HTTPS host and immutable tag', () => {
const trust = validateReleaseTrust(readyTrust())
const wrongHost = readyInput()
wrongHost.packageUrl = 'https://github.com/example/HoloLake.app.tar.gz'
assert.throws(() => validateReleaseInput(wrongHost, trust), /PACKAGE_HOST_NOT_TRUSTED/)
const wrongPath = readyInput()
wrongPath.packageUrl = 'https://release.guanghu.test/updates/HoloLake.app.tar.gz'
assert.throws(() => validateReleaseInput(wrongPath, trust), /PACKAGE_HOST_NOT_TRUSTED/)
const wrongTag = readyInput()
wrongTag.releaseTag = 'latest'
assert.throws(() => validateReleaseInput(wrongTag, trust), /IMMUTABLE_TAG_INVALID/)
assert.equal(validateReleaseInput(readyInput(), trust).version, '0.2.0')
})
test('release pipeline requires updater signing, Developer ID and Apple notarization credentials together', () => {
assert.throws(() => validateCredentialEnvironment({}), /CREDENTIALS_MISSING/)
assert.doesNotThrow(() => validateCredentialEnvironment({
APPLE_SIGNING_IDENTITY: 'Developer ID Application: HoloLake (TEAM)',
TAURI_SIGNING_PRIVATE_KEY: 'runtime-secret-material',
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: 'provided-at-runtime',
APPLE_ID: 'release@example.test',
APPLE_PASSWORD: 'provided-at-runtime',
APPLE_TEAM_ID: 'TEAM',
}))
assert.equal(validateCredentialEnvironment({
APPLE_SIGNING_IDENTITY: 'Developer ID Application: HoloLake (TEAM)',
TAURI_SIGNING_PRIVATE_KEY: 'runtime-secret-material',
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: 'provided-at-runtime',
APPLE_XCODE_ORGANIZER_FLOW: '1',
}), 'XCODE_ORGANIZER')
assert.throws(() => validateCredentialEnvironment({
APPLE_SIGNING_IDENTITY: 'Developer ID Application: HoloLake (TEAM)',
APPLE_XCODE_ORGANIZER_FLOW: '1',
}), /TAURI_SIGNING_PRIVATE_KEY_OR_PATH/)
})
test('release pipeline materializes a protected updater key path only inside the build environment', () => {
const source = {
TAURI_SIGNING_PRIVATE_KEY_PATH: '/protected/hololake-updater.key',
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: 'provided-at-runtime',
}
const hydrated = materializeUpdaterPrivateKey(source, (file) => {
assert.equal(file, source.TAURI_SIGNING_PRIVATE_KEY_PATH)
return 'encrypted-private-key-material'
})
assert.equal(hydrated.TAURI_SIGNING_PRIVATE_KEY, 'encrypted-private-key-material')
assert.equal(hydrated.TAURI_SIGNING_PRIVATE_KEY_PATH, undefined)
assert.equal(source.TAURI_SIGNING_PRIVATE_KEY, undefined)
})
test('release pipeline verifies the updater signature against embedded product trust before broadcast', () => {
const source = readFileSync(new URL('./release-pipeline.mjs', import.meta.url), 'utf8')
assert.match(source, /--example',\s*'verify_updater_signature'/)
assert.match(source, /src-tauri\/release-trust\.json/)
assert.match(source, /HoloLakePreNotarizationExecutableSha256/)
assert.match(source, /HoloLakeUnsignedExecutableSha256/)
assert.match(source, /--remove-signature/)
assert.match(source, /NOTARIZED_APP_SOURCE_BINARY_MISMATCH/)
assert.match(source, /APPLE_APP_NOTARIZATION_ACCEPTED_AND_STAPLED_DMG_CONTAINS_NOTARIZED_APP/)
assert.match(source, /path\.resolve\(appExecutable, '\.\.\/\.\.\/\.\.'\)/)
assert.doesNotMatch(source, /path\.resolve\(appExecutable, '\.\.\/\.\.\/\.\.\/\.\.'\)/)
})
test('Windows updater keeps signed installation but never claims the macOS rollback boundary', () => {
const source = readFileSync(new URL('../src-tauri/src/release_update.rs', import.meta.url), 'utf8')
assert.match(source, /SIGNED_PACKAGE_VERIFIED_INSTALLING_NO_LOCAL_ROLLBACK/)
assert.match(source, /HOLOLAKE_RELEASE_WINDOWS_LOCAL_ROLLBACK_NOT_AVAILABLE/)
assert.match(source, /snapshot\.envelope\.hololake\.rollback\.supported\s*&&\s*platform_recovery\.local_rollback_available/)
assert.match(source, /update\.install\(&bytes\)/)
})

View file

@ -0,0 +1,72 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
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'))
assert.ok(!contract.human_surface.includes('AI_WORKBENCH'))
assert.ok(contract.stage_one_forbidden.includes('INTERNAL_AI_CHAT'))
assert.equal(foundation.stage_one_internal_ai_interaction, false)
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)
assert.equal(bridge.implementation.authenticated_broker_development_lane_runtime, true)
assert.equal(bridge.implementation.development_lane_human_projection_runtime, true)
assert.equal(bridge.implementation.visitor_development_lane_rejected, true)
assert.equal(bridge.implementation.native_general_programming_tool_loop_runtime, 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

@ -0,0 +1,25 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import { compileUnifiedNumberTree } from './compile-unified-number-tree.mjs'
test('identity, webview and direct broker numbers compile into one unique evidence tree', () => {
const generated = JSON.parse(readFileSync(new URL('../generated/unified-number-coordinate-tree.json', import.meta.url), 'utf8'))
assert.deepEqual(generated, compileUnifiedNumberTree())
assert.equal(generated.schema, 'hololake.unified-number-coordinate-tree/v2')
assert.equal(generated.recordId, 'HLP-UNIFIED-NUMBER-TREE-001')
assert.equal(generated.coordinateCount, 288)
assert.equal(generated.routeCount, 185)
assert.equal(generated.identityNodeCount, 4)
assert.equal(generated.protocolNodeCount, 99)
assert.equal(generated.referenceOnlyNodeCount, 16)
assert.equal(new Set(generated.routes.map((route) => route.path)).size, 185)
assert.equal(new Set([...generated.identityNodes, ...generated.protocolNodes, ...generated.routes].map((node) => node.path)).size, 288)
assert.equal(generated.invariants.everyPhysicalCallHasNumberedRoute, true)
assert.equal(generated.invariants.everyAcceptedCallHasEvidenceClass, true)
assert.equal(generated.invariants.everyProtocolReferenceHasNumberCoordinate, true)
assert.equal(generated.invariants.referenceOnlyNodesNeverExecutable, true)
assert.equal(generated.invariants.unresolvedNumberReferenceCount, 0)
assert.ok(generated.protocolNodes.filter((node) => node.nodeKind === 'GLS_REFERENCE_ONLY').every((node) => node.executionState === 'REFERENCE_ONLY_NOT_EXECUTABLE'))
assert.ok(generated.routes.every((route) => route.admission && route.evidence))
})

View file

@ -0,0 +1,36 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const readText = (relative) => fs.readFileSync(path.join(root, relative), 'utf8')
const readJson = (relative) => JSON.parse(readText(relative))
test('the native user PNCC contract binds verified number, signed-in account and embedded Git', () => {
const contract = readJson('contracts/user-pncc-channel.json')
assert.equal(contract.engine, 'GIT')
assert.equal(contract.human_projection, 'HOLOLAKE_NATIVE')
assert.equal(contract.forgejo_role, 'OPTIONAL_REMOTE_COLLABORATION_ADAPTER')
assert.equal(contract.binding.requires_verified_user_number, true)
assert.equal(contract.binding.domain_resolved_before_login, true)
assert.equal(contract.binding.domain_specific_login_and_node_entry_required, true)
assert.equal(contract.binding.requires_authenticated_repository_account, true)
assert.equal(contract.binding.password_written_to_repository, false)
assert.equal(contract.binding.persona_binding_claimed, false)
assert.equal(contract.local_repository.automatic_idempotent_initialization, true)
})
test('the user PNCC is a native command and first-class HoloLake projection', () => {
const native = readText('src-tauri/src/lib.rs')
const numberedDispatcher = readText('src-tauri/src/numbered_ipc_dispatch.rs')
const frontend = readText('src/main.tsx')
assert.match(numberedDispatcher, /user_pncc_channel::get_user_pncc_channel/)
assert.match(numberedDispatcher, /user_pncc_channel::ensure_user_pncc_channel/)
assert.doesNotMatch(native, /user_pncc_channel::get_user_pncc_channel/)
assert.match(frontend, /GH-PNCC · 人格原生代码频道/)
assert.match(frontend, /Forgejo 协作适配器/)
assert.match(frontend, /ensure_user_pncc_channel/)
assert.doesNotMatch(frontend, /Forgejo 页面/)
})

View file

@ -0,0 +1,54 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const read = (path) => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8')
const registry = JSON.parse(read('contracts/numbered-ipc-registry.json'))
const runtime = read('src-tauri/src/module_package_runtime.rs')
const moduleAdapter = read('src-tauri/src/web_novel_modules.rs')
const frontend = [
read('src/modules/web-novel/WebNovelWorkspace.tsx'),
read('src/modules/web-novel/AuthorModuleCenter.tsx'),
read('src/modules/web-novel/AuthorWritingSidecar.tsx'),
].join('\n')
const packages = [
'WORKBENCH', 'OUTLINE', 'GRID', 'STORYWORLD', 'DELIVERY',
].map((name) => JSON.parse(read(`fixtures/module-packages/HLP-MOD-OFFICIAL-WEB-NOVEL-${name}-0001-0.1.0.ghmod`)))
test('web novel family has five immutable official identities behind one shared lifecycle', () => {
assert.equal(packages.length, 5)
assert.ok(packages.every((value) => value.manifest.registrationClass === 'OFFICIAL_LIGHTHOUSE'))
assert.ok(packages.every((value) => value.manifest.adapter === 'web-novel-workbench-v1'))
assert.equal(new Set(packages.map((value) => value.manifest.moduleNumber)).size, 5)
assert.match(runtime, /const BUNDLED_MODULES/)
assert.doesNotMatch(frontend, /install_web_novel_author_module|mount_web_novel_author_module|uninstall_web_novel_author_module/)
})
test('all 38 web novel effects cross exact numbered routes and no raw tauri command surface', () => {
const routes = registry.operations.filter((route) => Number(route.operation_number.slice(-4)) >= 103 && Number(route.operation_number.slice(-4)) <= 140)
assert.equal(routes.length, 38)
assert.deepEqual([...new Set(routes.map((route) => route.module_number))], [
'HLP-NIPC-MOD-0025', 'HLP-NIPC-MOD-0026', 'HLP-NIPC-MOD-0027', 'HLP-NIPC-MOD-0028', 'HLP-NIPC-MOD-0029',
])
assert.ok(routes.every((route) => route.admission === 'VERIFIED_HUMAN_ROUTE'))
assert.doesNotMatch(frontend, /from ['"]@tauri-apps\/api\/core['"]/)
for (const source of ['web_novel_workspace.rs', 'web_novel_import.rs', 'web_novel_author.rs', 'web_novel_modules.rs']) {
assert.doesNotMatch(read(`src-tauri/src/${source}`), /#\[tauri::command\]/)
}
})
test('advanced effects require their own exact active module number', () => {
assert.match(moduleAdapter, /require_module_active\(&app, OUTLINE\)/)
assert.match(moduleAdapter, /require_module_active\(&app, GRID\)/)
assert.match(moduleAdapter, /require_module_active\(&app, STORYWORLD\)/)
assert.match(moduleAdapter, /require_module_active\(&app, DELIVERY\)/)
assert.match(moduleAdapter, /shared signed package runtime/)
})
test('workspace is independently lazy-loaded and preserves old account data in place', () => {
assert.match(read('src/main.tsx'), /lazy\(\(\) => import\('\.\/modules\/web-novel\/WebNovelWorkspace'\)/)
assert.equal(packages[0].payload.adapterConfig.legacyDataPolicy, 'READ_IN_PLACE_NO_DESTRUCTIVE_MIGRATION')
assert.equal(packages[0].payload.adapterConfig.thirdPartyPublishDefault, 'DENY')
assert.doesNotMatch(read('src-tauri/src/web_novel_workspace.rs'), /serde_json::from_str[^\n]+unwrap_or_default\(\)/)
})

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, '104a5d73162bdf4a529701e65898e2bc2863ea9e')
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,57 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import test from 'node:test'
const read = (relative) => fs.readFileSync(new URL(`../${relative}`, import.meta.url), 'utf8')
const contract = JSON.parse(read('contracts/zero-point-nucleus-channel.json'))
const stageOne = JSON.parse(read('contracts/stage-one-platform.json'))
const foundation = JSON.parse(read('foundation.json'))
const rust = read('src-tauri/src/zero_point.rs')
const distribution = read('src-tauri/src/public_zero_core_distribution.rs')
const trust = JSON.parse(read('contracts/public-zero-core-trust.json'))
const lib = read('src-tauri/src/lib.rs')
const ui = read('src/main.tsx')
test('zero-point nucleus is a system runtime and never an inferred persona binding', () => {
assert.equal(contract.metacognitive_boundary.zero_point_system_is_persona, false)
assert.equal(contract.metacognitive_boundary.zero_point_system_is_model_carrier, false)
assert.equal(contract.metacognitive_boundary.number_verification_is_persona_binding, false)
assert.equal(contract.metacognitive_boundary.number_verification_grants_execution_authority, false)
assert.equal(stageOne.zero_point_nucleus_client_runtime.system_is_persona, false)
assert.equal(foundation.zero_point_nucleus_is_persona, false)
assert.match(ui, /验证结果不构成人格绑定、模型载体绑定或执行授权/)
})
test('dual-signed protocol synchronization starts below the public surface and uses only provisioned public trust', () => {
assert.equal(contract.current_implementation.boot_time_silent_version_comparison, true)
assert.equal(contract.current_implementation.signed_protocol_payload_installation, true)
assert.equal(contract.current_implementation.production_dual_signer_trust_provisioned, true)
assert.equal(stageOne.zero_point_nucleus_client_runtime.signed_protocol_payload_installation_implemented, true)
assert.equal(stageOne.zero_point_nucleus_client_runtime.production_dual_signer_trust_provisioned, true)
assert.equal(trust.state, 'PROVISIONED')
assert.equal(trust.signers.length, 2)
assert.ok(trust.signers.every((signer) => signer.algorithm === 'Ed25519' && Buffer.from(signer.publicKeyBase64, 'base64').length === 32))
assert.deepEqual(trust.requiredSignerClasses, [
'ZERO_POINT_ORIGIN_PUBLIC_SCOPE_SIGNER',
'ENTERPRISE_ZERO_CORE_DISTRIBUTION_SIGNER',
])
assert.equal(contract.security.unsigned_protocol_update_allowed, false)
assert.match(lib, /sync_protocol_runtime/)
assert.match(rust, /sync_public_zero_core/)
assert.match(distribution, /verify_dual_signatures/)
assert.match(distribution, /HOLOLAKE_PUBLIC_ZERO_CORE_ROLLBACK_REJECTED/)
assert.match(distribution, /HOLOLAKE_PUBLIC_ZERO_CORE_EPOCH_EQUIVOCATION_REJECTED/)
assert.match(distribution, /distribution-state\.sqlite3/)
assert.match(distribution, /TransactionBehavior::Immediate/)
assert.match(distribution, /reqwest::header::IF_NONE_MATCH/)
assert.doesNotMatch(lib, /zero_point_save_api|zero_point_api_config|generic_layer_chat/)
assert.doesNotMatch(ui, /模型 API 配置|通用AI运行层|AGENT PARLOR|会客厅/)
})
test('number validation requires an explicit positive lighthouse verdict', () => {
assert.match(rust, /fn lighthouse_resolution/)
assert.match(rust, /eq_ignore_ascii_case\("RESOLVED"\)/)
assert.match(rust, /route_not_found/)
assert.match(rust, /an arbitrary successful response/)
assert.match(rust, /inner\.route = "restricted"/)
})