feat: enforce Guanghu-native HoloLake runtime laws

This commit is contained in:
冰朔 2026-08-04 23:11:25 +08:00
commit 67e6fcdd38
57 changed files with 1765 additions and 1504 deletions

View file

@ -0,0 +1,157 @@
#!/usr/bin/env bash
set -Eeuo pipefail
repository_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
receipt_path=${1:-}
if [[ -z "${receipt_path}" ]]; then
echo "usage: run-hololake-native-quality-gate.sh <receipt-output-outside-repository>" >&2
exit 2
fi
mkdir -p "$(dirname "${receipt_path}")"
receipt_parent=$(cd "$(dirname "${receipt_path}")" && pwd)
receipt_path="${receipt_parent}/$(basename "${receipt_path}")"
case "${receipt_path}" in
"${repository_root}" | "${repository_root}"/*)
echo "quality receipt must be written outside the source repository" >&2
exit 2
;;
esac
commit=$(git -C "${repository_root}" rev-parse HEAD)
tree=$(git -C "${repository_root}" rev-parse 'HEAD^{tree}')
branch=$(git -C "${repository_root}" branch --show-current)
profile_id=$(node -p \
"JSON.parse(require('fs').readFileSync(process.argv[1], 'utf8')).profileId" \
"${repository_root}/standards/guanghu-native-engineering-profile.json")
started_at=$(date -u '+%Y-%m-%dT%H:%M:%SZ')
current_gate=initialization
passed_gates=
write_receipt() {
local result=$1
local total_score=$2
local failed_gate=${3:-none}
{
echo "schema: hololake.guanghu-native-code-quality-receipt/v1"
echo "protocol: GLS-0844"
echo "acronym: GHNQG"
echo "authority: HLP-MOD-CODE-CHANNEL"
echo "product: HoloLake"
echo "profile: ${profile_id}"
echo "result: ${result}"
echo "total_score: ${total_score}"
echo "partial_acceptance: false"
echo "source:"
echo " branch: ${branch:-DETACHED}"
echo " commit: ${commit}"
echo " tree: ${tree}"
echo "started_at: ${started_at}"
echo "completed_at: $(date -u '+%Y-%m-%dT%H:%M:%SZ')"
echo "failed_gate: ${failed_gate}"
echo "gates:"
if [[ -n "${passed_gates}" ]]; then
while IFS= read -r gate; do
echo " ${gate}: 100"
done <<<"${passed_gates}"
fi
if [[ "${result}" != "PASS_100" ]]; then
echo " ${failed_gate}: 0"
fi
echo "external_observers:"
echo " authority: none"
echo " blocking: false"
} >"${receipt_path}"
}
on_error() {
local exit_code=$?
trap - ERR
write_receipt FAIL_0 0 "${current_gate}"
echo "GHNQG_FAIL_0 gate=${current_gate} receipt=${receipt_path}" >&2
exit "${exit_code}"
}
trap on_error ERR
run_gate() {
current_gate=$1
shift
"$@"
passed_gates="${passed_gates}${passed_gates:+$'\n'}${current_gate}"
}
run_package_tool() {
local tool=$1
shift
if command -v pnpm >/dev/null 2>&1; then
pnpm --dir "${repository_root}" exec "${tool}" "$@"
return
fi
if [[ -x "${repository_root}/node_modules/.bin/${tool}" ]]; then
(
cd "${repository_root}"
"node_modules/.bin/${tool}" "$@"
)
return
fi
echo "${tool} is unavailable; install the locked HoloLake dependencies first" >&2
return 127
}
run_gate clean_source_tree \
bash -c '[[ -z "$(git -C "$1" status --porcelain --untracked-files=all)" ]]' \
_ "${repository_root}"
run_gate diff_whitespace git -C "${repository_root}" diff --check HEAD
run_gate registered_protocol_profile \
bash "${repository_root}/scripts/test-guanghu-native-authority.sh"
run_gate automatic_protocol_bindings \
node "${repository_root}/scripts/validate-guanghu-native-profile.mjs"
run_gate frontend_zero_warning_lint \
run_package_tool eslint . --max-warnings=0
run_gate frontend_type_contract \
run_package_tool tsc -b
run_gate frontend_build \
run_package_tool vite build
run_gate frontend_unit_and_integration_tests \
run_package_tool vitest run
run_gate auditable_native_core_lines_and_functions_100 \
run_package_tool vitest run \
--config vitest.guanghu-native.config.ts --coverage
run_gate rust_format \
cargo fmt --all --manifest-path "${repository_root}/src-tauri/Cargo.toml" -- --check
run_gate rust_unit_and_integration_tests \
cargo test --manifest-path "${repository_root}/src-tauri/Cargo.toml" \
--all-targets -- --test-threads=1
run_gate rust_zero_warning_lint \
cargo clippy --manifest-path "${repository_root}/src-tauri/Cargo.toml" \
--all-targets -- -D warnings
run_gate bundled_world_and_protocol_validation \
cargo run --quiet \
--manifest-path "${repository_root}/guanghu-os/Cargo.toml" \
-p ghctl -- wake "${repository_root}/guanghu-os/world-seed"
run_gate shell_syntax \
bash -c '
while IFS= read -r script; do
[[ -z "$script" ]] && continue
bash -n "$1/$script"
done < <(git -C "$1" ls-files "*.sh" ".husky/*")
' _ "${repository_root}"
current_gate=sensitive_information_scan
if git -C "${repository_root}" grep -nEI \
'BEGIN [A-Z ]*PRIVATE KEY|AKID[A-Za-z0-9]{13,}|(password|secret|access[_-]?token)[[:space:]]*[:=][[:space:]]*["'\''][^"'\'']{12,}' \
-- .; then
false
fi
passed_gates="${passed_gates}${passed_gates:+$'\n'}${current_gate}"
current_gate=source_tree_fingerprint
[[ "${commit}" =~ ^[0-9a-f]{40}$ ]]
[[ "${tree}" =~ ^[0-9a-f]{40}$ ]]
index_fingerprint=$(git -C "${repository_root}" ls-files -s | shasum -a 256 | awk '{print $1}')
[[ "${index_fingerprint}" =~ ^[0-9a-f]{64}$ ]]
passed_gates="${passed_gates}${passed_gates:+$'\n'}${current_gate}"
write_receipt PASS_100 100
echo "GHNQG_PASS_100 commit=${commit} tree=${tree} index=${index_fingerprint} receipt=${receipt_path}"

View file

@ -22,13 +22,6 @@ const coverageRequire = createCoverageRequire()
const { createCoverageMap } = coverageRequire('istanbul-lib-coverage')
const libReport = coverageRequire('istanbul-lib-report')
const reports = coverageRequire('istanbul-reports')
const thresholdPercent = Number(process.env.VITEST_COVERAGE_THRESHOLD ?? '70')
const thresholds = {
lines: metricThreshold('LINES'),
functions: metricThreshold('FUNCTIONS'),
branches: metricThreshold('BRANCHES'),
statements: metricThreshold('STATEMENTS'),
}
function positiveInteger(value, name) {
if (/^[1-9][0-9]*$/.test(value)) {
@ -39,11 +32,6 @@ function positiveInteger(value, name) {
process.exit(2)
}
function metricThreshold(metricName) {
const value = process.env[`VITEST_COVERAGE_${metricName}_THRESHOLD`]
return value === undefined ? thresholdPercent : Number(value)
}
function createCoverageRequire() {
const require = createRequire(import.meta.url)
const coveragePackagePath = require.resolve('@vitest/coverage-v8/package.json')
@ -166,29 +154,14 @@ function printCoverageSummary(summary) {
const item = summary[metric]
console.log(
`${metric.padEnd(10)} ${String(item.pct).padStart(6)}% `
+ `(${item.covered}/${item.total}, threshold ${thresholds[metric]}%)`,
+ `(${item.covered}/${item.total}, observation only)`,
)
}
}
function checkCoverageThresholds(coverageMap) {
function printObservedCoverage(coverageMap) {
const summary = coverageMap.getCoverageSummary().toJSON()
printCoverageSummary(summary)
const failures = Object.entries(thresholds)
.filter(([metric, threshold]) => summary[metric].pct < threshold)
if (failures.length === 0) {
return
}
for (const [metric, threshold] of failures) {
console.error(
`Coverage for ${metric} (${summary[metric].pct}%) does not meet threshold ${threshold}%`,
)
}
process.exit(1)
}
await clearVitestCache()
@ -196,5 +169,5 @@ await runShards()
const coverageMap = await mergeCoverage()
await writeCoverageReports(coverageMap)
checkCoverageThresholds(coverageMap)
printObservedCoverage(coverageMap)
await rm(shardRoot, { recursive: true, force: true })

View file

@ -0,0 +1,55 @@
#!/usr/bin/env bash
set -euo pipefail
repository_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
active_authority_surfaces=(
"AGENTS.md"
".github/HOOKS.md"
".github/SETUP.md"
".github/workflows/ci.yml"
".github/workflows/README.md"
".husky/pre-push"
"scripts/run-hololake-native-quality-gate.sh"
".claude/settings.local.json"
".chunk/config.json"
".chunk/README.md"
".chunk/run-rust-gate.sh"
"vite.config.ts"
"scripts/run-vitest-coverage-shards.mjs"
"src/components/FeedbackDialog.tsx"
"src/components/FeedbackDialog.test.tsx"
"src/constants/feedback.ts"
"tests/smoke/contribute-modal.spec.ts"
"site/reference/contribute.md"
"site/public/landing/sponsors/SOURCES.md"
"src-tauri/resources/agent-docs/pages/reference/contribute.md"
"docs/GETTING-STARTED.md"
)
existing_surfaces=()
for relative_path in "${active_authority_surfaces[@]}"; do
if [[ -e "${repository_root}/${relative_path}" ]]; then
existing_surfaces+=("${repository_root}/${relative_path}")
fi
done
if grep -Ein 'codescene|codacy|codecov' "${existing_surfaces[@]}"; then
echo "third-party quality authority remains on an active HoloLake surface" >&2
exit 1
fi
if grep -Ein \
'fail-under-(lines|functions)[[:space:]]+(70|85)|coverage[^[:cntrl:]]*(>=|≥)[[:space:]]*(70|85)%|threshold[^[:cntrl:]]*(70|85)' \
"${existing_surfaces[@]}"; then
echo "partial percentage quality authority remains on an active HoloLake surface" >&2
exit 1
fi
grep -Fq 'GLS-0844' "${repository_root}/AGENTS.md"
grep -Fq 'GHNQG_PASS_100' "${repository_root}/.husky/pre-push"
grep -Fq 'run-hololake-native-quality-gate.sh' "${repository_root}/.husky/pre-push"
grep -Fq 'run-hololake-native-quality-gate.sh' "${repository_root}/.github/workflows/ci.yml"
grep -Fq 'test:native-authority' "${repository_root}/.github/workflows/ci.yml"
echo "GUANGHU_NATIVE_AUTHORITY_OK"

View file

@ -0,0 +1,148 @@
import { readFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const profilePath = resolve(root, 'standards/guanghu-native-engineering-profile.json')
const profile = JSON.parse(readFileSync(profilePath, 'utf8'))
const failures = []
const requireTruth = (condition, id) => {
if (!condition) failures.push(id)
}
const source = relativePath => readFileSync(resolve(root, relativePath), 'utf8')
requireTruth(profile.schema === 'guanghu.native-engineering-profile/v1', 'profile_schema')
requireTruth(profile.authority.repository === 'REPO-012', 'authority_repository')
requireTruth(/^[0-9a-f]{40}$/.test(profile.authority.commit), 'authority_commit')
requireTruth(profile.decisionModel.aggregateRule === 'ALL_REQUIRED_GATES_100_OR_TOTAL_0', 'binary_aggregate')
requireTruth(profile.decisionModel.externalScoringHasAuthority === false, 'external_authority')
const protocols = new Set(profile.protocolBindings.map(binding => binding.protocol))
for (const required of ['GLS-0110', 'GLS-0200', 'GLS-0230', 'GLS-0306', 'GLS-0311', 'GLS-0400', 'GLS-0708', 'GLS-0710', 'GLS-0803', 'GLS-0810', 'GLS-0842', 'GLS-0844']) {
requireTruth(protocols.has(required), `protocol_${required}`)
}
for (const binding of profile.protocolBindings) {
requireTruth(
Array.isArray(binding.implementation)
&& binding.implementation.length > 0
&& binding.implementation.every(path => source(path).length > 0),
`implementation_${binding.protocol}`,
)
}
const triggers = new Map(profile.automaticTriggers.map(trigger => [trigger.event, trigger]))
for (const required of [
'development_start',
'test_start',
'build_start',
'source_commit',
'source_publish',
'code_channel_review',
'living_system_event',
'model_plan_returned',
'server_model_request',
'execution_receipt_requested',
]) {
requireTruth(triggers.has(required), `trigger_${required}`)
}
const packageJson = JSON.parse(source('package.json'))
requireTruth(packageJson.scripts.predev === 'pnpm test:native-authority', 'trigger_predev')
requireTruth(packageJson.scripts.pretest === 'pnpm test:native-authority', 'trigger_pretest')
requireTruth(
packageJson.scripts.prebuild.includes('test:native-authority')
&& packageJson.scripts.prebuild.includes('test:native-core'),
'trigger_prebuild',
)
requireTruth(source('.husky/pre-commit').includes('test-guanghu-native-authority.sh'), 'trigger_precommit')
requireTruth(
source('.husky/pre-push').includes('test:native-authority')
|| source('.husky/pre-push').includes('run-hololake-native-quality-gate.sh'),
'trigger_prepush',
)
requireTruth(source('.github/workflows/ci.yml').includes('test:native-authority'), 'trigger_ci')
requireTruth(
source('.github/workflows/ci.yml').includes('run-hololake-native-quality-gate.sh'),
'trigger_ci_hololake_gate',
)
const nativeQualityGate = source('scripts/run-hololake-native-quality-gate.sh')
for (const requiredGate of [
'clean_source_tree',
'registered_protocol_profile',
'automatic_protocol_bindings',
'frontend_zero_warning_lint',
'frontend_type_contract',
'frontend_build',
'frontend_unit_and_integration_tests',
'auditable_native_core_lines_and_functions_100',
'rust_format',
'rust_unit_and_integration_tests',
'rust_zero_warning_lint',
'bundled_world_and_protocol_validation',
'shell_syntax',
'sensitive_information_scan',
'source_tree_fingerprint',
]) {
requireTruth(nativeQualityGate.includes(requiredGate), `hololake_gate_${requiredGate}`)
}
requireTruth(
!nativeQualityGate.includes('codescene')
&& !nativeQualityGate.includes('codacy')
&& !nativeQualityGate.includes('codecov'),
'hololake_gate_no_external_authority',
)
requireTruth(source('vitest.guanghu-native.config.ts').includes('lines: 100'), 'native_core_lines_100')
requireTruth(source('vitest.guanghu-native.config.ts').includes('functions: 100'), 'native_core_functions_100')
const contract = source('src/lib/guanghuLivingSystem.ts')
requireTruth(contract.includes('personaSystem: GuanghuPersonaSystemContext'), 'persona_context')
requireTruth(contract.includes('currentSystemState: GuanghuCurrentSystemState'), 'system_state')
requireTruth(contract.includes('knowledgeState: GuanghuKnowledgeState'), 'knowledge_state')
requireTruth(contract.includes('permissionBoundary: GuanghuPermissionBoundary'), 'permission_boundary')
requireTruth(contract.includes('responsibilityBoundary: GuanghuResponsibilityBoundary'), 'responsibility_boundary')
requireTruth(contract.includes('capabilityRegistry: GuanghuCapabilityRegistration[]'), 'capability_registry')
requireTruth(contract.includes('uiProjection: GuanghuUIProjection'), 'ui_projection')
requireTruth(contract.includes('navigationAction: GuanghuNavigationAction'), 'navigation_action')
requireTruth(contract.includes('capabilityCall: GuanghuCapabilityCall | null'), 'capability_call')
requireTruth(contract.includes('receiptSchema: GuanghuReceiptSchema'), 'receipt_schema')
requireTruth(contract.includes('guanghu_living_system_success_evidence_required'), 'evidence_required')
const planner = source('src/utils/planGuanghuLivingSystem.ts')
requireTruth(planner.includes("runtimeBinding?.status === 'verified'"), 'verified_runtime_binding')
const nativeBridge = source('src-tauri/src/guanghu_living_system.rs')
requireTruth(!nativeBridge.includes('guanghu-os-bs-sh-005'), 'legacy_server_route_closed')
requireTruth(!nativeBridge.includes('ensure_lighthouse_tunnel'), 'legacy_tunnel_closed')
for (const field of [
'persona_system: Value',
'current_system_state: Value',
'knowledge_state: Value',
'permission_boundary: Value',
'responsibility_boundary: Value',
'capability_registry: Vec<Value>',
]) {
requireTruth(nativeBridge.includes(field), `native_bridge_${field.split(':')[0]}`)
}
requireTruth(
nativeBridge.includes('guanghu_living_system_runtime_binding_invalid'),
'native_bridge_runtime_binding',
)
if (failures.length > 0) {
process.stdout.write(JSON.stringify({
schema: 'guanghu.native-engineering-receipt/v1',
profileId: profile.profileId,
state: 'FAIL_0',
failures,
}, null, 2) + '\n')
process.exit(1)
}
process.stdout.write(JSON.stringify({
schema: 'guanghu.native-engineering-receipt/v1',
profileId: profile.profileId,
authorityCommit: profile.authority.commit,
state: 'PASS_100',
gates: profile.requiredInvariants,
}, null, 2) + '\n')