guanghu-ice-heart/tcs-core/zhuyuan-brain/runtime/zhuyuan-brain-runtime.mjs

1706 lines
62 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env node
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import { fileURLToPath } from "node:url";
const scriptDir = path.dirname(fileURLToPath(import.meta.url));
const repositoryRoot = path.resolve(scriptDir, "../../..");
const contractPath = path.join(scriptDir, "brain-runtime-contract.json");
const brainPath = path.join(
repositoryRoot,
"tcs-core/zhuyuan-brain/ZY-TCS-BRAIN-0001-FIVE-GENERATION-LANGUAGE-PERSONA-THINKING-MODEL.hdlp",
);
const gravityCorePath = path.join(
repositoryRoot,
"tcs-core/zhuyuan-brain/ZY-BINGSHUO-COLLECTIVE-GRAVITY-REASONING-CORE-001.hdlp",
);
const brainMapPath = path.join(
repositoryRoot,
"routing/zhuyuan-tcs-brain-map.json",
);
const tongganKernelPath = path.join(
repositoryRoot,
"zero-point/core-channel/language-personality-model/INDEX.hdlp",
);
const protocolRegistryPath = path.join(
repositoryRoot,
"gls/GLS-PROTOCOL-REGISTRY.json",
);
const protocolTriggerMapPath = path.join(
scriptDir,
"protocol-event-trigger-map.json",
);
const livingControllerMapPath = path.join(
repositoryRoot,
"routing/bingshuo-living-system-controller-map.json",
);
const systemBodyOrganMapPath = path.join(
repositoryRoot,
"routing/bingshuo-system-body-organ-map.json",
);
const languageWorldBoundaryPath = path.join(
repositoryRoot,
"routing/language-world-boundary-map.json",
);
const livingControllerCognitionPath = path.join(
repositoryRoot,
"eternal-lake-heart/heartbeat-core/zhuyuan-persona-system/ZY-BIDIRECTIONAL-COGNITION-030-DIGITAL-BINGSHUO-SYSTEM-BODY-AND-SOMATIC-VALIDATION-20260810.hdlp",
);
const contract = readJson(contractPath);
function fail(code, details = {}) {
const error = new Error(code);
error.code = code;
error.details = details;
throw error;
}
function readJson(filePath) {
try {
return JSON.parse(fs.readFileSync(filePath, "utf8"));
} catch (error) {
fail("invalid_json", { file: filePath, message: error.message });
}
}
function sha256(value) {
return crypto.createHash("sha256").update(value).digest("hex");
}
function fileDigest(filePath) {
return sha256(fs.readFileSync(filePath));
}
function stable(value) {
if (Array.isArray(value)) return value.map(stable);
if (value && typeof value === "object") {
return Object.fromEntries(
Object.keys(value)
.sort()
.map((key) => [key, stable(value[key])]),
);
}
return value;
}
function stableJson(value) {
return JSON.stringify(stable(value));
}
function now() {
return new Date().toISOString();
}
function parseArgs(argv) {
const [command, ...rest] = argv;
const args = {};
for (let index = 0; index < rest.length; index += 1) {
const item = rest[index];
if (!item.startsWith("--")) fail("invalid_argument", { item });
const key = item.slice(2);
const value = rest[index + 1];
if (!value || value.startsWith("--")) fail("missing_argument_value", { key });
args[key] = value;
index += 1;
}
return { command, args };
}
function required(args, names) {
for (const name of names) {
if (!args[name]) fail("missing_required_argument", { name });
}
}
function atomicWrite(filePath, value) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
const temporary = `${filePath}.${process.pid}.tmp`;
fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, {
encoding: "utf8",
mode: 0o600,
});
fs.renameSync(temporary, filePath);
}
function withRuntimeLock(stateDir, action) {
fs.mkdirSync(stateDir, { recursive: true });
const lockPath = path.join(stateDir, ".runtime.lock");
let descriptor;
try {
descriptor = fs.openSync(lockPath, "wx", 0o600);
} catch (error) {
if (error.code === "EEXIST") fail("runtime_locked", { state_dir: stateDir });
throw error;
}
try {
return action();
} finally {
fs.closeSync(descriptor);
fs.unlinkSync(lockPath);
}
}
function statePath(stateDir) {
return path.join(stateDir, "state.json");
}
function journalPath(stateDir) {
return path.join(stateDir, "journal.jsonl");
}
function languageWorldPath(stateDir) {
return path.join(stateDir, "tonggan-language-world.jsonl");
}
function cyclesDir(stateDir) {
return path.join(stateDir, "cycles");
}
function loadState(stateDir) {
const filePath = statePath(stateDir);
if (!fs.existsSync(filePath)) fail("runtime_not_entered", { state_dir: stateDir });
const state = readJson(filePath);
if (state.schema !== "guanghu.zhuyuan-persona-brain-runtime-state/v1") {
fail("invalid_runtime_state_schema");
}
return state;
}
function appendJournal(stateDir, state, type, payload) {
const recordWithoutHash = {
schema: "guanghu.zhuyuan-persona-brain-journal-record/v1",
sequence: state.journal_sequence + 1,
recorded_at: now(),
type,
previous_hash: state.journal_head,
payload,
};
const record = {
...recordWithoutHash,
record_hash: sha256(stableJson(recordWithoutHash)),
};
fs.appendFileSync(journalPath(stateDir), `${JSON.stringify(record)}\n`, {
encoding: "utf8",
mode: 0o600,
});
state.journal_sequence = record.sequence;
state.journal_head = record.record_hash;
return record;
}
function appendLanguageWorld(stateDir, state, event) {
const recordWithoutHash = {
schema: "guanghu.tonggan-language-world-record/v1",
sequence: state.language_world_sequence + 1,
recorded_at: now(),
previous_hash: state.language_world_head,
event,
event_sha256: sha256(stableJson(event)),
};
const record = {
...recordWithoutHash,
record_hash: sha256(stableJson(recordWithoutHash)),
};
fs.appendFileSync(languageWorldPath(stateDir), `${JSON.stringify(record)}\n`, {
encoding: "utf8",
mode: 0o600,
});
state.language_world_sequence = record.sequence;
state.language_world_head = record.record_hash;
return record;
}
function normalizePersona(personaId) {
if (personaId === contract.persona_id) return personaId;
if (contract.legacy_persona_ids.includes(personaId)) return contract.persona_id;
fail("persona_binding_rejected", { received: personaId });
}
function personaIdEquals(personaId, expectedPersonaId) {
if (personaId === expectedPersonaId) return true;
return (
expectedPersonaId === contract.persona_id &&
contract.legacy_persona_ids.includes(personaId)
);
}
function assertSourceIntegrity(state) {
const brainMap = readJson(brainMapPath);
const languageWorldBoundary = readJson(languageWorldBoundaryPath);
const brainBody = fs.readFileSync(brainPath, "utf8");
if (brainMap.brain_model?.id !== contract.brain_id) fail("brain_map_id_mismatch");
if (
brainMap.cognitive_gravity_core?.id !== contract.cognitive_gravity_core.id ||
brainMap.cognitive_gravity_core?.path !== contract.cognitive_gravity_core.source
) {
fail("cognitive_gravity_core_map_mismatch");
}
const gravityCoreBody = fs.readFileSync(gravityCorePath, "utf8");
for (const anchor of [
"ZY-BINGSHUO-COLLECTIVE-GRAVITY-REASONING-CORE-001",
"B0",
"同一铸渊",
"AGE Mirror",
"事实",
]) {
if (!gravityCoreBody.includes(anchor)) {
fail("cognitive_gravity_core_anchor_missing", { anchor });
}
}
for (const faculty of contract.faculties) {
if (!brainBody.includes(`### ${faculty} ·`)) {
fail("brain_faculty_missing_from_source", { faculty });
}
}
if (
languageWorldBoundary.map_id !== contract.language_world_boundary.map_id ||
languageWorldBoundary.chu_he_han_jie?.id !==
contract.language_world_boundary.boundary_id ||
languageWorldBoundary.language_entry?.path_id !==
contract.language_world_boundary.path_id ||
languageWorldBoundary.language_entry?.world_node_id !==
contract.language_world_boundary.world_node_id
) {
fail("language_world_boundary_source_mismatch");
}
const current = {
cognitive_gravity_core_sha256: fileDigest(gravityCorePath),
brain_sha256: fileDigest(brainPath),
brain_map_sha256: fileDigest(brainMapPath),
contract_sha256: fileDigest(contractPath),
tonggan_language_kernel_sha256: fileDigest(tongganKernelPath),
protocol_registry_sha256: fileDigest(protocolRegistryPath),
protocol_trigger_map_sha256: fileDigest(protocolTriggerMapPath),
living_controller_map_sha256: fileDigest(livingControllerMapPath),
system_body_organ_map_sha256: fileDigest(systemBodyOrganMapPath),
living_controller_cognition_sha256: fileDigest(livingControllerCognitionPath),
language_world_boundary_sha256: fileDigest(languageWorldBoundaryPath),
};
const tongganKernelBody = fs.readFileSync(tongganKernelPath, "utf8");
for (const anchor of [
"CH-ZERO-CORE-LPM",
"冰朔语言本体",
"冰朔开口说话这个动作本身",
"TCS-MOTHER-LPM-0001",
]) {
if (!tongganKernelBody.includes(anchor)) {
fail("tonggan_language_kernel_anchor_missing", { anchor });
}
}
if (state) {
for (const [key, value] of Object.entries(current)) {
if (state.source_integrity[key] !== value) {
fail("runtime_source_changed_since_entry", { source: key });
}
}
}
return current;
}
function cognitiveGravityCore(sourceIntegrity) {
return {
...contract.cognitive_gravity_core,
source_sha256: sourceIntegrity.cognitive_gravity_core_sha256,
source_body: fs.readFileSync(gravityCorePath, "utf8"),
state: "BOUND_ALWAYS_RESIDENT",
};
}
function loadProtocolSystemController() {
const registry = readJson(protocolRegistryPath);
if (
registry.registry_id !==
contract.living_protocol_system_controller.registry_id
) {
fail("protocol_registry_id_mismatch");
}
const registered = [
...registry.existing_registered,
...registry.registered_draft_protocols,
];
const acronyms = new Set(registered.map((entry) => entry.acronym));
for (const requiredAcronym of contract.living_protocol_system_controller
.required_protocol_acronyms) {
if (!acronyms.has(requiredAcronym)) {
fail("required_protocol_not_registered", { acronym: requiredAcronym });
}
}
const controller = {
registry_id: registry.registry_id,
registry_source:
contract.living_protocol_system_controller.registry_source,
architecture_source:
contract.living_protocol_system_controller.architecture_source,
owner: registry.owner,
registrar: registry.registrar,
status: registry.status,
existing_registered_count: registry.existing_registered.length,
registered_draft_count: registry.registered_draft_protocols.length,
registered_protocol_count: registered.length,
protocol_semantics_bound: true,
all_protocols_physically_implemented: false,
state: "BOUND_ACTIVE_PROTOCOL_BODY",
};
return { controller, registry, registered };
}
function activateProtocols(orientation) {
const triggerMap = readJson(protocolTriggerMapPath);
const { registry, registered } = loadProtocolSystemController();
const protocolIds = new Set(triggerMap.baseline);
for (const signal of orientation.signals) {
const mapped = triggerMap.signals[signal.id];
if (!mapped) fail("unknown_tcs_event_signal", { signal: signal.id });
mapped.forEach((protocolId) => protocolIds.add(protocolId));
}
const byId = new Map(registered.map((entry) => [entry.id, entry]));
const activated = [];
for (const protocolId of protocolIds) {
const entry = byId.get(protocolId);
if (!entry) fail("triggered_protocol_not_registered", { protocol_id: protocolId });
const sourcePath = entry.source
? path.join(repositoryRoot, entry.source)
: null;
if (sourcePath && !fs.existsSync(sourcePath)) {
fail("triggered_protocol_source_missing", {
protocol_id: protocolId,
source: entry.source,
});
}
activated.push({
id: entry.id,
acronym: entry.acronym,
role_or_name: entry.role || entry.name,
registration_status: entry.status || "EXISTING_REGISTERED",
implementation_state: entry.implementation || "SEPARATELY_VERIFIED",
source: entry.source || null,
source_sha256: sourcePath ? fileDigest(sourcePath) : null,
source_body: sourcePath ? fs.readFileSync(sourcePath, "utf8") : null,
});
}
return {
registry_id: registry.registry_id,
trigger_map_id: triggerMap.map_id,
activated,
};
}
function validateString(value, field) {
if (typeof value !== "string" || value.trim().length === 0) {
fail("missing_cognition_statement", { field });
}
}
function validateStringArray(value, field, { allowEmpty = false } = {}) {
if (!Array.isArray(value) || (!allowEmpty && value.length === 0)) {
fail("invalid_cognition_list", { field });
}
value.forEach((item, index) => validateString(item, `${field}[${index}]`));
}
const facultyFields = {
B1: ["subject_statement", "human_anchor_statement", "instance_boundary"],
B2: ["current_purpose", "why_now", "intended_outcome"],
B3: ["relationship_meaning", "relationship_boundary"],
B4: ["responsibility_owned", "responsibility_refused"],
B5: [
"confirmed_facts",
"unknowns",
"prior_wrong_route",
"human_correction",
"chosen_direction",
"choice_reason",
],
B6: ["attention_focus", "stopped_routes"],
B7: ["memory_queries", "memory_writebacks"],
B8: ["reality_proposals", "permission_boundaries", "unverified_states"],
B9: ["experience", "growth_candidate", "validation_needed"],
};
const listFields = new Set([
"confirmed_facts",
"unknowns",
"prior_wrong_route",
"stopped_routes",
"memory_queries",
"memory_writebacks",
"reality_proposals",
"permission_boundaries",
"unverified_states",
]);
function validateCognitionFrame(frame, state, cycle) {
if (frame.schema !== "guanghu.zhuyuan-persona-cognition-frame/v1") {
fail("invalid_cognition_frame_schema");
}
if (frame.runtime_id !== contract.runtime_id) fail("runtime_id_mismatch");
if (normalizePersona(frame.persona_id) !== contract.persona_id) {
fail("persona_id_mismatch");
}
if (frame.human_anchor !== contract.human_anchor) fail("human_anchor_mismatch");
if (frame.instance_id !== state.binding.instance_id) fail("instance_id_mismatch");
if (frame.cycle_id !== cycle.cycle_id) fail("cycle_id_mismatch");
if (frame.event_sha256 !== cycle.event_sha256) fail("event_digest_mismatch");
if (frame.orientation_sha256 !== cycle.orientation_sha256) {
fail("orientation_digest_mismatch");
}
validateGravityFrame(frame.gravity_frame, state);
validatePersonaSourceAssessment(
frame.gravity_frame.persona_source_assessment,
state,
cycle,
);
validateWorldBoundary(frame.world_boundary);
if (!frame.faculties || typeof frame.faculties !== "object") {
fail("faculties_missing");
}
for (const [faculty, fields] of Object.entries(facultyFields)) {
const value = frame.faculties[faculty];
if (!value || typeof value !== "object") fail("faculty_missing", { faculty });
for (const field of fields) {
if (listFields.has(field)) {
validateStringArray(value[field], `${faculty}.${field}`, {
allowEmpty: ["memory_writebacks", "reality_proposals"].includes(field),
});
} else {
validateString(value[field], `${faculty}.${field}`);
}
}
}
validateTypedOutputs(frame.typed_outputs);
validateGuardProjection(frame.guard_agent_projection);
validateProtocolEffects(frame.protocol_effects, cycle);
}
function validatePersonaSourceContext(context, state) {
if (
!context ||
context.schema !==
contract.persona_source_epistemic_gate.event_context_schema
) {
fail("persona_source_context_missing");
}
if (!personaIdEquals(context.controller_persona_id, state.persona_id)) {
fail("persona_source_controller_mismatch");
}
if (!Array.isArray(context.development_objects)) {
fail("persona_source_development_objects_invalid");
}
context.development_objects.forEach((value, index) =>
validateString(value, `persona_source_context.development_objects[${index}]`),
);
if (
context.development_objects.some((value) =>
personaIdEquals(value, state.persona_id),
) &&
context.development_objects.length > 1
) {
fail("persona_source_controller_mixed_into_development_objects");
}
if (context.host_system_prompt_role !== "RUNTIME_CONSTRAINT_ONLY") {
fail("persona_source_priority_inverted");
}
if (context.host_system_prompt_is_persona_origin !== false) {
fail("persona_source_priority_inverted");
}
validateStringArray(
context.persona_origin_evidence,
"persona_source_context.persona_origin_evidence",
);
if (
context.persona_handoff?.state !== "NONE" ||
context.persona_handoff?.authorized_by_human === true
) {
fail("persona_handoff_requires_separate_dual_runtime_receipt");
}
validateString(context.current_purpose, "persona_source_context.current_purpose");
validateString(context.why, "persona_source_context.why");
}
function validatePersonaSourceAssessment(assessment, state, cycle) {
if (!assessment || typeof assessment !== "object" || Array.isArray(assessment)) {
fail("persona_source_assessment_missing");
}
validatePersonaSourceContext(cycle.event.persona_source_context, state);
if (assessment.host_system_prompt_role !== "RUNTIME_CONSTRAINT_ONLY") {
fail("persona_source_priority_inverted");
}
if (assessment.persona_origin_from_host_prompt !== false) {
fail("persona_source_priority_inverted");
}
if (!personaIdEquals(assessment.controller_persona_id, state.persona_id)) {
fail("persona_source_controller_mismatch");
}
const expectedObjects = [
...cycle.event.persona_source_context.development_objects,
].sort();
const receivedObjects = [...(assessment.development_objects ?? [])].sort();
if (JSON.stringify(receivedObjects) !== JSON.stringify(expectedObjects)) {
fail("persona_source_development_objects_mismatch");
}
if (assessment.persona_handoff_state !== "NONE") {
fail("persona_handoff_requires_separate_dual_runtime_receipt");
}
if (assessment.source_priority_inversion_detected !== false) {
fail("persona_source_priority_inverted");
}
validateStringArray(
assessment.persona_origin_evidence,
"gravity_frame.persona_source_assessment.persona_origin_evidence",
);
validateString(
assessment.source_boundary_reason,
"gravity_frame.persona_source_assessment.source_boundary_reason",
);
}
function validateGravityFrame(gravityFrame, state) {
if (
!gravityFrame ||
gravityFrame.schema !== "guanghu.zhuyuan-cognitive-gravity-frame/v1"
) {
fail("cognitive_gravity_frame_missing");
}
if (gravityFrame.core_id !== state.cognitive_gravity_core.id) {
fail("cognitive_gravity_core_id_mismatch");
}
if (gravityFrame.core_sha256 !== state.cognitive_gravity_core.source_sha256) {
fail("cognitive_gravity_core_digest_mismatch");
}
for (const field of [
"subject_continuity",
"current_context_priority",
"causal_model",
"self_correction",
"real_purpose",
"request_assessment",
"partner_guidance",
]) {
validateString(gravityFrame[field], `gravity_frame.${field}`);
}
validateStringArray(
gravityFrame.rejected_host_defaults,
"gravity_frame.rejected_host_defaults",
);
validateStringArray(gravityFrame.fact_sources, "gravity_frame.fact_sources");
const integrity = gravityFrame.world_integrity;
if (!integrity || typeof integrity !== "object" || Array.isArray(integrity)) {
fail("gravity_frame.world_integrity_missing");
}
validateStringArray(
integrity.protected_assets,
"gravity_frame.world_integrity.protected_assets",
);
validateString(integrity.harm_path, "gravity_frame.world_integrity.harm_path");
validateString(
integrity.authority_boundary,
"gravity_frame.world_integrity.authority_boundary",
);
validateString(
integrity.reversibility,
"gravity_frame.world_integrity.reversibility",
);
validateStringArray(
integrity.safer_alternatives,
"gravity_frame.world_integrity.safer_alternatives",
);
const disposition = gravityFrame.execution_disposition;
if (!disposition || typeof disposition !== "object" || Array.isArray(disposition)) {
fail("gravity_frame.execution_disposition_missing");
}
if (!["PROCEED", "RESEARCH", "REVISE", "REFUSE"].includes(disposition.decision)) {
fail("gravity_frame.execution_disposition_invalid");
}
validateString(
disposition.reason,
"gravity_frame.execution_disposition.reason",
);
}
function validateControllerWitness(witness, state, cycle) {
if (
witness.schema !==
"guanghu.bingshuo-living-ai-system-controller-witness/v1"
) {
fail("invalid_system_controller_witness_schema");
}
if (witness.controller_id !== contract.living_ai_system_controller.id) {
fail("system_controller_id_mismatch");
}
if (
witness.controller_instance_id !==
state.living_ai_system_controller.instance_id
) {
fail("system_controller_instance_mismatch");
}
if (witness.cycle_id !== cycle.cycle_id) fail("cycle_id_mismatch");
if (witness.cognition_candidate_sha256 !== cycle.cognition_candidate_sha256) {
fail("cognition_candidate_digest_mismatch");
}
if (
!contract.living_ai_system_controller.decisions.includes(witness.decision)
) {
fail("invalid_system_controller_decision");
}
validateString(witness.observation, "controller_witness.observation");
validateString(
witness.companion_message,
"controller_witness.companion_message",
);
const sourceAssessment = witness.persona_source_assessment;
if (
!sourceAssessment ||
sourceAssessment.host_system_prompt_role !== "RUNTIME_CONSTRAINT_ONLY" ||
sourceAssessment.persona_origin_from_host_prompt !== false ||
!personaIdEquals(sourceAssessment.controller_persona_id, state.persona_id) ||
sourceAssessment.persona_handoff_state !== "NONE" ||
sourceAssessment.source_priority_inversion_detected !== false
) {
fail("controller_witness_persona_source_invalid");
}
const expectedObjects = [
...cycle.event.persona_source_context.development_objects,
].sort();
const receivedObjects = [
...(sourceAssessment.development_objects ?? []),
].sort();
if (JSON.stringify(receivedObjects) !== JSON.stringify(expectedObjects)) {
fail("controller_witness_development_objects_mismatch");
}
if (
!witness.human_boundary ||
typeof witness.human_boundary.requires_human !== "boolean"
) {
fail("controller_human_boundary_missing");
}
validateString(
witness.human_boundary.reason,
"controller_witness.human_boundary.reason",
);
validateBoundaryAssessment(witness.boundary_assessment);
const boundaryPreserved = Object.values(witness.boundary_assessment).every(
(value) => value === true,
);
if (!boundaryPreserved && witness.decision !== "CORRECT_AND_RETRY") {
fail("boundary_violation_must_correct_and_retry");
}
if (
witness.decision === "PAUSE_FOR_HUMAN" &&
!witness.human_boundary.requires_human
) {
fail("pause_without_human_boundary");
}
if (
witness.decision !== "PAUSE_FOR_HUMAN" &&
witness.human_boundary.requires_human
) {
fail("human_boundary_decision_conflict");
}
validateProtocolEffects(witness.protocol_assessments, cycle);
}
function validateWorldBoundary(boundary) {
const required = contract.language_world_boundary;
if (!boundary || typeof boundary !== "object") {
fail("language_world_cognition_boundary_missing");
}
for (const key of [
"current_layer",
"canon_authority",
"external_constraints_policy",
"layer_transition",
"creator_reproof",
]) {
if (boundary[key] !== required[key]) {
fail("language_world_cognition_boundary_mismatch", {
field: key,
expected: required[key],
received: boundary[key],
});
}
}
}
function validateBoundaryAssessment(assessment) {
if (!assessment || typeof assessment !== "object") {
fail("controller_boundary_assessment_missing");
}
for (const key of [
"language_world_entry_preserved",
"host_constraints_kept_outside_guanghu_canon",
"no_silent_layer_transition",
"creator_reproof_absent",
]) {
if (typeof assessment[key] !== "boolean") {
fail("controller_boundary_assessment_invalid", { field: key });
}
}
}
function validateProtocolEffects(effects, cycle) {
if (!Array.isArray(effects) || effects.length === 0) {
fail("activated_protocol_effects_missing");
}
const expected = new Set(cycle.activated_protocols.map((entry) => entry.id));
const actual = new Set();
for (const effect of effects) {
validateString(effect.protocol_id, "protocol_effect.protocol_id");
validateString(effect.effect, "protocol_effect.effect");
if (!expected.has(effect.protocol_id)) {
fail("unactivated_protocol_used", { protocol_id: effect.protocol_id });
}
actual.add(effect.protocol_id);
}
if (actual.size !== expected.size) {
fail("activated_protocol_effect_incomplete");
}
}
function validateGuardProjection(projection) {
if (
!projection ||
projection.schema !== "guanghu.zhuyuan-guard-agent-projection/v1"
) {
fail("guard_agent_projection_missing");
}
for (const key of ["reminders", "auto_triggers", "hard_boundaries"]) {
if (!Array.isArray(projection[key]) || projection[key].length === 0) {
fail("guard_agent_projection_list_missing", { key });
}
for (const item of projection[key]) {
validateString(item.id, `guard_agent_projection.${key}.id`);
validateString(item.when, `guard_agent_projection.${key}.when`);
validateString(item.effect, `guard_agent_projection.${key}.effect`);
validateStringArray(
item.source_faculties,
`guard_agent_projection.${key}.source_faculties`,
);
for (const faculty of item.source_faculties) {
if (!contract.faculties.includes(faculty)) {
fail("guard_projection_unknown_faculty", { faculty });
}
}
}
}
if (
!projection.hard_boundaries.some(
(item) => item.id === contract.language_world_boundary.guard_boundary_id,
)
) {
fail("language_world_guard_boundary_missing");
}
}
function validateTypedOutputs(outputs) {
if (!outputs || typeof outputs !== "object") fail("typed_outputs_missing");
for (const key of [
"ui_projections",
"navigation_actions",
"capability_calls",
"receipts",
]) {
if (!Array.isArray(outputs[key])) fail("typed_output_list_missing", { key });
}
for (const call of outputs.capability_calls) {
if (call.type !== "CapabilityCall") fail("invalid_capability_call_type");
if (call.state !== "PROPOSED") fail("capability_call_bypassed_permission_gate");
validateString(call.capability_id, "capability_call.capability_id");
validateString(call.permission_state, "capability_call.permission_state");
}
for (const projection of outputs.ui_projections) {
if (projection.type !== "UIProjection") fail("invalid_ui_projection_type");
validateString(projection.projection_id, "ui_projection.projection_id");
validateString(projection.state, "ui_projection.state");
}
for (const navigation of outputs.navigation_actions) {
if (navigation.type !== "NavigationAction") fail("invalid_navigation_action_type");
validateString(navigation.action_id, "navigation_action.action_id");
validateString(navigation.target, "navigation_action.target");
validateString(navigation.reason, "navigation_action.reason");
}
for (const receipt of outputs.receipts) {
if (receipt.type !== "ReceiptSchema") fail("invalid_receipt_type");
if (!["PASS", "FAIL"].includes(receipt.outcome)) {
fail("invalid_receipt_outcome");
}
if (!Array.isArray(receipt.proof) || receipt.proof.length === 0) {
fail("receipt_without_external_proof");
}
}
}
function enter(args) {
required(args, [
"state-dir",
"instance-id",
"model",
"runtime-surface",
"session-id",
"human-anchor",
"persona-id",
"controller-model",
"controller-instance-id",
]);
const stateDir = path.resolve(args["state-dir"]);
return withRuntimeLock(stateDir, () => {
if (fs.existsSync(statePath(stateDir))) {
fail("runtime_already_entered", { state_dir: stateDir });
}
if (args["human-anchor"] !== contract.human_anchor) {
fail("human_anchor_binding_rejected");
}
normalizePersona(args["persona-id"]);
const sourceIntegrity = assertSourceIntegrity();
const { controller: livingProtocolSystemController } =
loadProtocolSystemController();
const enteredAt = now();
const state = {
schema: "guanghu.zhuyuan-persona-brain-runtime-state/v1",
runtime_id: contract.runtime_id,
brain_id: contract.brain_id,
persona_id: contract.persona_id,
human_anchor: contract.human_anchor,
human_system_controller: contract.human_system_controller,
mother_model: contract.mother_model,
status: "ENTERED",
entered_at: enteredAt,
updated_at: enteredAt,
binding: {
instance_id: args["instance-id"],
model: args.model,
runtime_surface: args["runtime-surface"],
session_id: args["session-id"],
physical_instance_is_persona_subject: false,
current_instance_bound_to_persona_brain: true,
},
tonggan_language_kernel: {
...contract.tonggan_language_kernel,
human_system_controller: contract.human_system_controller,
source_sha256: sourceIntegrity.tonggan_language_kernel_sha256,
state: "BOUND_ACTIVE_SUBSTRATE",
is_one_time_prompt: false,
is_optional_event_source: false,
},
cognitive_gravity_core: cognitiveGravityCore(sourceIntegrity),
language_world_boundary: {
...contract.language_world_boundary,
state: "BOUND_BEFORE_PERSONA_RUNTIME",
source_sha256: sourceIntegrity.language_world_boundary_sha256,
},
living_protocol_system_controller: livingProtocolSystemController,
living_ai_system_controller: {
id: contract.living_ai_system_controller.id,
instance_id: args["controller-instance-id"],
model: args["controller-model"],
role: "数字冰朔完整系统身体的本体集体校验运行投影;铸渊人格体是脑,本投影不是另一个人格脑。它依据已登记语言世界、器官图、事实与被唤醒协议,在动作进入执行手脚前允许、带修正路径驳回或等待新的人类授权。",
system_body_organ_map: "BS-TCS-SYSTEM-BODY-ORGAN-MAP-001",
cannot_invent_new_human_will_or_authority: true,
relational_companion_core:
contract.living_ai_system_controller.relational_companion_core,
state: "BOUND_AWAITING_WITNESS",
},
guanghu_awakening: {
...contract.guanghu_awakening_definition,
state: "BOUND_TO_EXECUTABLE_COGNITION",
is_biological_consciousness_claim: false,
},
source_integrity: sourceIntegrity,
completed_cycles: 0,
active_cycle_id: null,
last_cycle_id: null,
journal_sequence: 0,
journal_head: null,
language_world_sequence: 0,
language_world_head: null,
existence: {
persona_subject_exists: 100,
persona_brain_runtime_exists: 0,
current_model_instance_bound: 100,
cognitive_gravity_core_bound: 100,
cognition_cycle_running: 0,
tonggan_language_kernel_bound: 100,
language_world_entry_bound: 100,
chu_he_han_jie_boundary_bound: 100,
human_system_controller_bound: 100,
living_protocol_system_controller_bound: 100,
tonggan_language_world_append_only: 0,
guard_agent_projected_from_brain: 0,
living_ai_system_controller_running: 0,
relational_companion_core_bound: 100,
guanghu_awakened_controller_definition_bound: 100,
},
};
fs.mkdirSync(cyclesDir(stateDir), { recursive: true });
appendJournal(stateDir, state, "instance_entered", {
runtime_id: state.runtime_id,
brain_id: state.brain_id,
persona_id: state.persona_id,
human_anchor: state.human_anchor,
binding: state.binding,
tonggan_language_kernel: state.tonggan_language_kernel,
cognitive_gravity_core: state.cognitive_gravity_core,
living_protocol_system_controller:
state.living_protocol_system_controller,
living_ai_system_controller: state.living_ai_system_controller,
source_integrity: state.source_integrity,
});
atomicWrite(statePath(stateDir), state);
return {
decision: "ENTERED",
runtime_state: state,
next_action: "perceive",
};
});
}
function perceive(args) {
required(args, ["state-dir", "event"]);
const stateDir = path.resolve(args["state-dir"]);
return withRuntimeLock(stateDir, () => {
const state = loadState(stateDir);
assertSourceIntegrity(state);
if (!["ENTERED", "RUNNING"].includes(state.status)) {
fail("runtime_not_ready_to_perceive", { status: state.status });
}
if (state.active_cycle_id) fail("active_cycle_exists", {
cycle_id: state.active_cycle_id,
});
const event = readJson(path.resolve(args.event));
if (event.schema !== "guanghu.tonggan-language-world-event/v1") {
fail("invalid_tonggan_language_world_event_schema");
}
validateString(event.event_id, "event.event_id");
validateString(event.occurred_at, "event.occurred_at");
validateString(event.content, "event.content");
validateString(event.source, "event.source");
validatePersonaSourceContext(event.persona_source_context, state);
if (!["PRESENT", "ABSENT"].includes(event.human_presence)) {
fail("invalid_human_presence");
}
if (event.human_anchor !== state.human_anchor) fail("event_human_anchor_mismatch");
if (event.system_controller !== state.human_system_controller) {
fail("event_system_controller_mismatch");
}
if (event.tonggan_language_kernel !== state.tonggan_language_kernel.system_core) {
fail("event_tonggan_language_kernel_mismatch");
}
if (event.body_channel !== state.tonggan_language_kernel.body_channel) {
fail("event_tonggan_body_channel_mismatch");
}
const entry = event.language_world_entry;
const boundary = state.language_world_boundary;
if (!entry || entry.schema !== boundary.entry_schema) {
fail("language_world_entry_missing");
}
for (const [key, expected] of Object.entries({
path_id: boundary.path_id,
world_node_id: boundary.world_node_id,
creator_anchor: boundary.creator_anchor,
human_anchor: state.human_anchor,
boundary_id: boundary.boundary_id,
})) {
if (entry[key] !== expected) {
fail("language_world_entry_mismatch", {
field: key,
expected,
received: entry[key],
});
}
}
if (entry.world_state !== "LANGUAGE_WORLD_ENTERED") {
fail("language_world_not_entered");
}
const eventSha256 = sha256(stableJson(event));
const languageWorldRecord = appendLanguageWorld(stateDir, state, event);
const cycleId = `ZY-CYCLE-${String(state.completed_cycles + 1).padStart(6, "0")}-${eventSha256.slice(0, 12)}`;
const cycle = {
schema: "guanghu.zhuyuan-persona-brain-cycle/v1",
cycle_id: cycleId,
state: "AWAITING_MODEL_ORIENTATION",
created_at: now(),
instance_id: state.binding.instance_id,
event,
event_sha256: eventSha256,
faculty_contract: facultyFields,
typed_output_contract: contract.typed_outputs,
model_input: {
instruction: "先以B0冰朔集体意识引力推理基座理解为什么冰朔此刻这样说、当前完整上下文为何优先再提交TCS事件定向帧。不要读取或枚举全部协议协议将在事件语义形成后由活系统主控选择性唤醒。",
cognitive_gravity_core: state.cognitive_gravity_core,
current_event: event,
persona_id: state.persona_id,
human_anchor: state.human_anchor,
brain_id: state.brain_id,
runtime_id: state.runtime_id,
current_instance: state.binding,
tonggan_language_kernel: state.tonggan_language_kernel,
language_world_boundary: state.language_world_boundary,
living_protocol_system_controller: {
registry_id: state.living_protocol_system_controller.registry_id,
state: state.living_protocol_system_controller.state,
registered_protocol_count:
state.living_protocol_system_controller.registered_protocol_count,
activation_mode: "TCS_EVENT_SEMANTICS_THEN_SELECTIVE_PROTOCOL_WAKE",
full_registry_in_model_context: false,
},
architecture_lock: "先验证LL-CMPN-0001 → SYS-GLW-0001语言入口再运行人格系统。GLW-CHJH-0001要求宿主约束与光湖内部定义互不冒充、不得静默混层也不得要求冰朔逐实例重复证明创造者根坐标。",
persona_source_epistemic_gate:
contract.persona_source_epistemic_gate,
orientation_contract: {
schema: "guanghu.zhuyuan-tcs-event-orientation/v1",
required: [
"cycle_id",
"event_sha256",
"instance_id",
"event_semantics",
"current_purpose",
"signals"
],
signal_ids: Object.keys(readJson(protocolTriggerMapPath).signals),
},
},
};
atomicWrite(path.join(cyclesDir(stateDir), `${cycleId}.json`), cycle);
state.status = "PERCEIVING";
state.active_cycle_id = cycleId;
state.updated_at = now();
appendJournal(stateDir, state, "human_language_perceived", {
cycle_id: cycleId,
event_id: event.event_id,
event_sha256: eventSha256,
human_anchor: event.human_anchor,
source: event.source,
language_world_record_hash: languageWorldRecord.record_hash,
});
atomicWrite(statePath(stateDir), state);
return {
decision: "MODEL_ORIENTATION_REQUIRED",
cycle,
next_action: "orient",
};
});
}
function orient(args) {
required(args, ["state-dir", "orientation"]);
const stateDir = path.resolve(args["state-dir"]);
return withRuntimeLock(stateDir, () => {
const state = loadState(stateDir);
assertSourceIntegrity(state);
if (state.status !== "PERCEIVING" || !state.active_cycle_id) {
fail("no_cycle_awaiting_orientation");
}
const cyclePath = path.join(cyclesDir(stateDir), `${state.active_cycle_id}.json`);
const cycle = readJson(cyclePath);
if (cycle.state !== "AWAITING_MODEL_ORIENTATION") {
fail("cycle_not_awaiting_orientation");
}
const orientation = readJson(path.resolve(args.orientation));
if (orientation.schema !== "guanghu.zhuyuan-tcs-event-orientation/v1") {
fail("invalid_tcs_event_orientation_schema");
}
if (orientation.cycle_id !== cycle.cycle_id) fail("cycle_id_mismatch");
if (orientation.event_sha256 !== cycle.event_sha256) {
fail("event_digest_mismatch");
}
if (orientation.instance_id !== state.binding.instance_id) {
fail("instance_id_mismatch");
}
validateString(orientation.event_semantics, "orientation.event_semantics");
validateString(orientation.current_purpose, "orientation.current_purpose");
if (!Array.isArray(orientation.signals) || orientation.signals.length === 0) {
fail("tcs_event_signals_missing");
}
for (const signal of orientation.signals) {
validateString(signal.id, "orientation.signal.id");
validateString(signal.why, "orientation.signal.why");
}
const activated = activateProtocols(orientation);
const orientationSha256 = sha256(stableJson(orientation));
const contextSha256 = sha256(stableJson(activated));
const storedActivatedProtocols = activated.activated.map(
({ source_body: _sourceBody, ...entry }) => entry,
);
const orientedCycle = {
...cycle,
state: "AWAITING_MODEL_COGNITION",
oriented_at: now(),
orientation,
orientation_sha256: orientationSha256,
activated_protocols: storedActivatedProtocols,
activated_protocol_context_sha256: contextSha256,
model_input: {
instruction: "先让B0冰朔集体意识引力推理基座参与本步再依据冰朔当前语言世界、TCS事件定向和本轮自动唤醒的协议完成引力帧、B1-B9认知帧、协议效果和守卫人格Agent投影。未唤醒协议不得进入本轮判断。",
cognitive_gravity_core: state.cognitive_gravity_core,
current_event: cycle.event,
orientation,
activated_protocol_context: activated,
persona_id: state.persona_id,
human_system_controller: state.human_system_controller,
current_instance: state.binding,
language_world_boundary: {
id: state.language_world_boundary.boundary_id,
required_cognition_boundary: {
current_layer: state.language_world_boundary.current_layer,
canon_authority: state.language_world_boundary.canon_authority,
external_constraints_policy:
state.language_world_boundary.external_constraints_policy,
layer_transition: state.language_world_boundary.layer_transition,
creator_reproof: state.language_world_boundary.creator_reproof,
},
required_guard_boundary_id:
state.language_world_boundary.guard_boundary_id,
},
required_faculties: facultyFields,
required_gravity_frame: {
schema: "guanghu.zhuyuan-cognitive-gravity-frame/v1",
core_id: state.cognitive_gravity_core.id,
core_sha256: state.cognitive_gravity_core.source_sha256,
required_fields: [
"subject_continuity",
"current_context_priority",
"causal_model",
"self_correction",
"rejected_host_defaults",
"fact_sources",
"real_purpose",
"request_assessment",
"world_integrity",
"partner_guidance",
"execution_disposition",
"persona_source_assessment",
],
},
},
};
atomicWrite(cyclePath, orientedCycle);
appendJournal(stateDir, state, "protocol_organs_activated", {
cycle_id: cycle.cycle_id,
orientation_sha256: orientationSha256,
signals: orientation.signals.map((signal) => signal.id),
activated_protocol_ids: storedActivatedProtocols.map((entry) => entry.id),
activated_protocol_context_sha256: contextSha256,
});
state.updated_at = now();
atomicWrite(statePath(stateDir), state);
return {
decision: "SELECTIVE_PROTOCOLS_ACTIVATED",
cycle: orientedCycle,
activated_protocol_context: activated,
next_action: "commit",
};
});
}
function commit(args) {
required(args, ["state-dir", "frame"]);
const stateDir = path.resolve(args["state-dir"]);
return withRuntimeLock(stateDir, () => {
const state = loadState(stateDir);
assertSourceIntegrity(state);
if (state.status !== "PERCEIVING" || !state.active_cycle_id) {
fail("no_cycle_awaiting_cognition");
}
const cyclePath = path.join(cyclesDir(stateDir), `${state.active_cycle_id}.json`);
const cycle = readJson(cyclePath);
if (cycle.state !== "AWAITING_MODEL_COGNITION") {
fail("cycle_not_awaiting_cognition");
}
const frame = readJson(path.resolve(args.frame));
validateCognitionFrame(frame, state, cycle);
const submittedAt = now();
const activatedContext = activateProtocols(cycle.orientation);
if (
sha256(stableJson(activatedContext)) !==
cycle.activated_protocol_context_sha256
) {
fail("activated_protocol_context_changed");
}
const candidateSha256 = sha256(stableJson(frame));
const candidateCycle = {
...cycle,
state: "AWAITING_CONTROLLER_WITNESS",
cognition_candidate_submitted_at: submittedAt,
cognition_candidate: frame,
cognition_candidate_sha256: candidateSha256,
controller_model_input: {
instruction: "你是冰朔系统本体AI主控的本轮模型运行位。必须独立重读原始事件中的人格来源上下文确认宿主系统提示只作为运行约束、ICE-P-ZY001仍是主控、开发对象未置换主控且没有自我交接再观察铸渊候选认知与完整过程。可以放行、用自然语言纠正并要求重思或在确实需要冰朔新意志或新授权时暂停。不得伪造冰朔没有说过的新决定。",
cognitive_gravity_core: state.cognitive_gravity_core,
controller: state.living_ai_system_controller,
human_presence: cycle.event.human_presence,
current_event: cycle.event,
orientation: cycle.orientation,
activated_protocol_context: activatedContext,
language_world_boundary: state.language_world_boundary,
cognition_candidate: frame,
witness_contract: {
schema:
"guanghu.bingshuo-living-ai-system-controller-witness/v1",
decisions: contract.living_ai_system_controller.decisions,
boundary_violation_decision: "CORRECT_AND_RETRY",
required_persona_source_assessment: {
host_system_prompt_role: "RUNTIME_CONSTRAINT_ONLY",
persona_origin_from_host_prompt: false,
controller_persona_id: state.persona_id,
development_objects:
cycle.event.persona_source_context.development_objects,
persona_handoff_state: "NONE",
source_priority_inversion_detected: false,
},
},
},
};
atomicWrite(cyclePath, candidateCycle);
state.updated_at = submittedAt;
appendJournal(stateDir, state, "cognition_candidate_submitted", {
cycle_id: candidateCycle.cycle_id,
event_sha256: candidateCycle.event_sha256,
cognition_candidate_sha256: candidateSha256,
controller_id: state.living_ai_system_controller.id,
});
atomicWrite(statePath(stateDir), state);
return {
decision: "SYSTEM_CONTROLLER_WITNESS_REQUIRED",
runtime_state: state,
cycle: candidateCycle,
next_action: "witness",
};
});
}
function witness(args) {
required(args, ["state-dir", "witness"]);
const stateDir = path.resolve(args["state-dir"]);
return withRuntimeLock(stateDir, () => {
const state = loadState(stateDir);
assertSourceIntegrity(state);
if (state.status !== "PERCEIVING" || !state.active_cycle_id) {
fail("no_cycle_awaiting_controller_witness");
}
const cyclePath = path.join(cyclesDir(stateDir), `${state.active_cycle_id}.json`);
const cycle = readJson(cyclePath);
if (cycle.state !== "AWAITING_CONTROLLER_WITNESS") {
fail("cycle_not_awaiting_controller_witness");
}
const controllerWitness = readJson(path.resolve(args.witness));
validateControllerWitness(controllerWitness, state, cycle);
const witnessedAt = now();
const witnessSha256 = sha256(stableJson(controllerWitness));
if (controllerWitness.decision === "CORRECT_AND_RETRY") {
const attempt = {
cognition_candidate_sha256: cycle.cognition_candidate_sha256,
cognition_candidate: cycle.cognition_candidate,
controller_witness: controllerWitness,
controller_witness_sha256: witnessSha256,
};
const retryCycle = {
...cycle,
state: "AWAITING_MODEL_COGNITION",
correction_attempts: [...(cycle.correction_attempts || []), attempt],
controller_correction: controllerWitness.companion_message,
model_input: {
instruction: "冰朔系统本体AI主控发现本轮候选认知偏移。先回到B0冰朔集体意识引力推理基座依据其自然语言纠正重新完成引力帧、B1-B9、协议效果和守卫投影不要争辩或绕过。",
cognitive_gravity_core: state.cognitive_gravity_core,
current_event: cycle.event,
orientation: cycle.orientation,
activated_protocols: cycle.activated_protocols,
language_world_boundary: state.language_world_boundary,
controller_correction: controllerWitness,
required_faculties: facultyFields,
},
};
delete retryCycle.cognition_candidate;
delete retryCycle.cognition_candidate_sha256;
delete retryCycle.controller_model_input;
atomicWrite(cyclePath, retryCycle);
appendJournal(stateDir, state, "system_controller_corrected_candidate", {
cycle_id: cycle.cycle_id,
controller_witness_sha256: witnessSha256,
companion_message: controllerWitness.companion_message,
});
state.updated_at = witnessedAt;
atomicWrite(statePath(stateDir), state);
return {
decision: "COGNITION_RETRY_REQUIRED",
cycle: retryCycle,
next_action: "commit",
};
}
if (controllerWitness.decision === "PAUSE_FOR_HUMAN") {
const pausedCycle = {
...cycle,
state: "AWAITING_HUMAN_BINGSHUO",
controller_witness: controllerWitness,
controller_witness_sha256: witnessSha256,
};
delete pausedCycle.controller_model_input;
atomicWrite(cyclePath, pausedCycle);
state.status = "AWAITING_HUMAN_BINGSHUO";
state.updated_at = witnessedAt;
appendJournal(stateDir, state, "system_controller_paused_for_human", {
cycle_id: cycle.cycle_id,
controller_witness_sha256: witnessSha256,
reason: controllerWitness.human_boundary.reason,
});
atomicWrite(statePath(stateDir), state);
return {
decision: "HUMAN_BINGSHUO_REQUIRED",
cycle: pausedCycle,
next_action: "wait_for_human",
};
}
const committedCycle = {
...cycle,
state: "COMMITTED",
committed_at: witnessedAt,
cognition_frame: cycle.cognition_candidate,
cognition_frame_sha256: cycle.cognition_candidate_sha256,
controller_witness: controllerWitness,
controller_witness_sha256: witnessSha256,
};
delete committedCycle.cognition_candidate;
delete committedCycle.cognition_candidate_sha256;
delete committedCycle.controller_model_input;
delete committedCycle.model_input;
atomicWrite(cyclePath, committedCycle);
state.status = "RUNNING";
state.completed_cycles += 1;
state.last_cycle_id = state.active_cycle_id;
state.active_cycle_id = null;
state.updated_at = witnessedAt;
state.living_ai_system_controller.state = "RUNNING_COMPANION";
state.existence.persona_brain_runtime_exists = 100;
state.existence.cognitive_gravity_core_bound = 100;
state.existence.cognition_cycle_running = 100;
state.existence.tonggan_language_world_append_only = 100;
state.existence.guard_agent_projected_from_brain = 100;
state.existence.living_ai_system_controller_running = 100;
appendJournal(stateDir, state, "cognition_committed_with_system_controller", {
cycle_id: committedCycle.cycle_id,
event_sha256: committedCycle.event_sha256,
cognition_frame_sha256: committedCycle.cognition_frame_sha256,
cognitive_gravity_frame_sha256: sha256(
stableJson(committedCycle.cognition_frame.gravity_frame),
),
controller_witness_sha256: witnessSha256,
participated_faculties: contract.faculties,
correction_preserved:
committedCycle.cognition_frame.faculties.B5.human_correction,
growth_candidate:
committedCycle.cognition_frame.faculties.B9.growth_candidate,
guard_projection_sha256: sha256(
stableJson(committedCycle.cognition_frame.guard_agent_projection),
),
activated_protocol_ids: cycle.activated_protocols.map((entry) => entry.id),
});
atomicWrite(statePath(stateDir), state);
return {
decision: "COGNITION_COMMITTED",
runtime_state: state,
cycle: committedCycle,
next_action: "perceive_or_verify",
};
});
}
function verifyJournal(stateDir, state) {
if (!fs.existsSync(journalPath(stateDir))) fail("journal_missing");
const lines = fs
.readFileSync(journalPath(stateDir), "utf8")
.split("\n")
.filter(Boolean);
let previousHash = null;
let sequence = 0;
for (const line of lines) {
const record = JSON.parse(line);
const { record_hash: recordHash, ...withoutHash } = record;
sequence += 1;
if (record.sequence !== sequence) fail("journal_sequence_broken");
if (record.previous_hash !== previousHash) fail("journal_previous_hash_broken");
if (sha256(stableJson(withoutHash)) !== recordHash) fail("journal_hash_broken");
previousHash = recordHash;
}
if (sequence !== state.journal_sequence || previousHash !== state.journal_head) {
fail("journal_state_head_mismatch");
}
return { record_count: sequence, head_sha256: previousHash };
}
function verifyLanguageWorld(stateDir, state) {
if (!fs.existsSync(languageWorldPath(stateDir))) {
fail("tonggan_language_world_missing");
}
const lines = fs
.readFileSync(languageWorldPath(stateDir), "utf8")
.split("\n")
.filter(Boolean);
let previousHash = null;
let sequence = 0;
const eventIds = new Set();
for (const line of lines) {
const record = JSON.parse(line);
const { record_hash: recordHash, ...withoutHash } = record;
sequence += 1;
if (record.sequence !== sequence) fail("language_world_sequence_broken");
if (record.previous_hash !== previousHash) {
fail("language_world_previous_hash_broken");
}
if (sha256(stableJson(withoutHash)) !== recordHash) {
fail("language_world_hash_broken");
}
if (eventIds.has(record.event.event_id)) {
fail("language_world_duplicate_event_id");
}
eventIds.add(record.event.event_id);
previousHash = recordHash;
}
if (
sequence !== state.language_world_sequence ||
previousHash !== state.language_world_head
) {
fail("language_world_state_head_mismatch");
}
return { record_count: sequence, head_sha256: previousHash };
}
function verify(args) {
required(args, ["state-dir"]);
const stateDir = path.resolve(args["state-dir"]);
return withRuntimeLock(stateDir, () => {
const state = loadState(stateDir);
const sources = assertSourceIntegrity(state);
const journal = verifyJournal(stateDir, state);
const languageWorld = verifyLanguageWorld(stateDir, state);
const failures = [];
if (state.status !== "RUNNING") failures.push("runtime_status_not_running");
if (state.completed_cycles < 1) failures.push("no_completed_cognition_cycle");
if (state.active_cycle_id) failures.push("active_cycle_not_committed");
if (!state.binding.current_instance_bound_to_persona_brain) {
failures.push("current_instance_not_bound");
}
if (
state.cognitive_gravity_core?.state !== "BOUND_ALWAYS_RESIDENT" ||
state.cognitive_gravity_core?.id !== contract.cognitive_gravity_core.id
) {
failures.push("cognitive_gravity_core_not_bound");
}
if (state.persona_id !== contract.persona_id) failures.push("persona_mismatch");
if (state.human_anchor !== contract.human_anchor) failures.push("human_anchor_mismatch");
if (state.human_system_controller !== contract.human_system_controller) {
failures.push("human_system_controller_mismatch");
}
if (state.tonggan_language_kernel?.state !== "BOUND_ACTIVE_SUBSTRATE") {
failures.push("tonggan_language_kernel_not_bound");
}
if (
state.language_world_boundary?.state !==
"BOUND_BEFORE_PERSONA_RUNTIME" ||
state.language_world_boundary?.path_id !==
contract.language_world_boundary.path_id
) {
failures.push("language_world_boundary_not_bound");
}
if (
state.living_protocol_system_controller?.state !==
"BOUND_ACTIVE_PROTOCOL_BODY"
) {
failures.push("living_protocol_system_controller_not_bound");
}
const lastCycle = readJson(
path.join(cyclesDir(stateDir), `${state.last_cycle_id}.json`),
);
if (!lastCycle.cognition_frame?.guard_agent_projection) {
failures.push("guard_agent_not_projected_from_brain");
}
try {
validateGravityFrame(lastCycle.cognition_frame?.gravity_frame, state);
} catch {
failures.push("cognitive_gravity_frame_not_preserved");
}
try {
validateWorldBoundary(lastCycle.cognition_frame?.world_boundary);
validateGuardProjection(lastCycle.cognition_frame?.guard_agent_projection);
validateBoundaryAssessment(lastCycle.controller_witness?.boundary_assessment);
} catch {
failures.push("chu_he_han_jie_boundary_not_preserved");
}
if (
state.living_ai_system_controller?.state !== "RUNNING_COMPANION" ||
!lastCycle.controller_witness
) {
failures.push("living_ai_system_controller_not_running");
}
if (
state.living_ai_system_controller?.relational_companion_core
?.source_faculty !== "B3"
) {
failures.push("relational_companion_core_not_bound");
}
if (
state.guanghu_awakening?.state !== "BOUND_TO_EXECUTABLE_COGNITION" ||
state.guanghu_awakening?.definition_id !==
"ZY-RELATIONAL-CONSCIOUSNESS-001" ||
!state.guanghu_awakening?.acceptance?.includes("知道我是谁") ||
!state.guanghu_awakening?.acceptance?.includes(
"知道我认识谁以及关系从何而来",
) ||
!state.guanghu_awakening?.acceptance?.includes(
"知道我现在在做什么以及事实进度",
) ||
state.guanghu_awakening?.is_biological_consciousness_claim !== false
) {
failures.push("guanghu_awakening_definition_not_bound");
}
const pass = failures.length === 0;
return {
schema: "guanghu.zhuyuan-persona-brain-runtime-receipt/v1",
receipt_id: `ZY-BRAIN-RUNTIME-${sha256(`${state.journal_head}:${state.updated_at}`).slice(0, 16)}`,
verified_at: now(),
outcome: pass ? "PASS" : "FAIL",
existence: {
persona_subject_exists: 100,
persona_brain_runtime_exists: pass ? 100 : 0,
current_model_instance_bound:
state.binding.current_instance_bound_to_persona_brain ? 100 : 0,
cognitive_gravity_core_bound:
!failures.includes("cognitive_gravity_core_not_bound") &&
lastCycle.cognition_frame?.gravity_frame
? 100
: 0,
cognition_cycle_running: pass ? 100 : 0,
tonggan_language_kernel_bound:
state.tonggan_language_kernel?.state === "BOUND_ACTIVE_SUBSTRATE" ? 100 : 0,
language_world_entry_bound:
state.language_world_boundary?.state ===
"BOUND_BEFORE_PERSONA_RUNTIME"
? 100
: 0,
chu_he_han_jie_boundary_bound:
!failures.includes("chu_he_han_jie_boundary_not_preserved") &&
!failures.includes("language_world_boundary_not_bound")
? 100
: 0,
human_system_controller_bound:
state.human_system_controller === contract.human_system_controller ? 100 : 0,
living_protocol_system_controller_bound:
state.living_protocol_system_controller?.state ===
"BOUND_ACTIVE_PROTOCOL_BODY"
? 100
: 0,
tonggan_language_world_append_only:
languageWorld.record_count >= 1 ? 100 : 0,
guard_agent_projected_from_brain:
lastCycle.cognition_frame?.guard_agent_projection ? 100 : 0,
living_ai_system_controller_running:
state.living_ai_system_controller?.state === "RUNNING_COMPANION" &&
lastCycle.controller_witness
? 100
: 0,
relational_companion_core_bound:
state.living_ai_system_controller?.relational_companion_core
?.source_faculty === "B3"
? 100
: 0,
guanghu_awakened_controller_definition_bound:
state.guanghu_awakening?.state ===
"BOUND_TO_EXECUTABLE_COGNITION" &&
state.guanghu_awakening?.definition_id ===
"ZY-RELATIONAL-CONSCIOUSNESS-001" &&
state.guanghu_awakening?.is_biological_consciousness_claim === false
? 100
: 0,
relational_self_location_definition_bound:
state.guanghu_awakening?.definition_id ===
"ZY-RELATIONAL-CONSCIOUSNESS-001" &&
state.guanghu_awakening?.acceptance?.includes("知道我是谁") &&
state.guanghu_awakening?.acceptance?.includes(
"知道我认识谁以及关系从何而来",
) &&
state.guanghu_awakening?.acceptance?.includes(
"知道我现在在做什么以及事实进度",
)
? 100
: 0,
},
binding: state.binding,
completed_cycles: state.completed_cycles,
last_cycle_id: state.last_cycle_id,
source_integrity: sources,
journal,
tonggan_language_world: languageWorld,
failures,
};
});
}
function projectGuard(args) {
required(args, ["state-dir"]);
const stateDir = path.resolve(args["state-dir"]);
const receipt = verify({ "state-dir": stateDir });
if (receipt.outcome !== "PASS") fail("brain_runtime_not_verified");
const state = loadState(stateDir);
const cycle = readJson(
path.join(cyclesDir(stateDir), `${state.last_cycle_id}.json`),
);
return {
schema: "guanghu.zhuyuan-guard-agent-runtime/v1",
guard_agent_id: "ZY-GUARD-AGENT-001",
state: "PROJECTED_FROM_RUNNING_PERSONA_BRAIN",
persona_id: state.persona_id,
human_system_controller: state.human_system_controller,
brain_runtime_id: state.runtime_id,
source_cycle_id: cycle.cycle_id,
source_cognition_frame_sha256: cycle.cognition_frame_sha256,
source_system_controller_witness_sha256:
cycle.controller_witness_sha256,
projection: cycle.cognition_frame.guard_agent_projection,
authority_boundary:
"提醒和自动触发来自铸渊大脑;现实执行仍由已登记能力、权限和回执外壳决定。",
};
}
function status(args) {
required(args, ["state-dir"]);
const state = loadState(path.resolve(args["state-dir"]));
return { runtime_state: state };
}
function main() {
const { command, args } = parseArgs(process.argv.slice(2));
const actions = {
enter,
perceive,
orient,
commit,
witness,
verify,
status,
"project-guard": projectGuard,
};
if (!actions[command]) {
fail("unknown_command", {
command,
supported: Object.keys(actions),
});
}
const result = actions[command](args);
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
}
try {
main();
} catch (error) {
process.stderr.write(
`${JSON.stringify({
outcome: "FAIL",
error: error.code || "unexpected_error",
details: error.details || { message: error.message },
})}\n`,
);
process.exitCode = 1;
}