foundation: start native language reality engineering root

This commit is contained in:
冰朔 2026-08-21 14:44:47 +08:00
commit 0dec0b93fc
154 changed files with 49993 additions and 0 deletions

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,139 @@
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.ordinary_user_local_channel_authority, 'EXPLICIT_INITIALIZATION_PLUS_ACCOUNT_SCOPED_SESSION_PLUS_KEYCHAIN_SECRET')
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('ordinary user local channels receive account-scoped IPC authority without claiming a Guanghu number', async () => {
const source = await readFile(path.join(rustRoot, 'numbered_ipc.rs'), 'utf8')
const dispatcher = await readFile(dispatcherPath, 'utf8')
assert.match(source, /AUTHENTICATED_LOCAL_HUMAN:PERSONAL_CHANNEL/)
assert.match(source, /session\.domain == "PERSONAL_CHANNEL"/)
assert.match(source, /session\.host == "local\.hololake"/)
assert.match(source, /current_login_session\(app\)/)
assert.match(source, /HOLOLAKE_NUMBERED_IPC_VERIFIED_HUMAN_REQUIRED/)
assert.match(dispatcher, /fn authenticated_human_subject/)
assert.match(dispatcher, /identity_for_channel_runtime\(app\)/)
assert.match(dispatcher, /external_ai_gateway::get_gateway_status[\s\S]*authenticated_human_subject/)
})
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"\]/)
})