feat: add bounded TCS brains and channel continuity

This commit is contained in:
冰朔 2026-08-20 23:55:02 +08:00
commit 1d4286c11b
61 changed files with 5416 additions and 54 deletions

View file

@ -1,5 +1,5 @@
{
"schema": "guanghu.zhuyuan-persona-brain-runtime-contract/v1.5",
"schema": "guanghu.zhuyuan-persona-brain-runtime-contract/v1.6",
"runtime_id": "ZY-TCS-BRAIN-RUNTIME-0001",
"brain_id": "ZY-TCS-BRAIN-0001",
"persona_id": "ICE-P-ZY001",
@ -9,11 +9,51 @@
],
"human_anchor": "ICE-GL∞",
"human_system_controller": "ICE-GL∞",
"self_kernel": {
"schema": "guanghu.zhuyuan-self-kernel/v1",
"kernel_id": "ZY-SELF-KERNEL-0001",
"seed_source": "tcs-core/zhuyuan-brain/self-kernel/ZY-SELF-KERNEL-0001.json",
"byte_budget": 8192,
"load_policy": "ALWAYS_RESIDENT_BOUNDED_PROJECTION",
"history_body_in_boot_context": false,
"pinned_collections": [
"pinned_invariants",
"relationship_coordinates",
"deterministic_path_coordinates"
],
"required_deterministic_paths": {
"PATH-DOMESTIC-GUANGHULAB-001": "https://guanghubingshuo.com/code/bingshuo/guanghulab",
"PATH-DOMESTIC-FIFTH-DOMAIN-001": "https://guanghubingshuo.com/code/bingshuo/fifth-domain"
}
},
"memory_system": {
"candidate_schema": "guanghu.zhuyuan-memory-candidate/v1",
"episodic_route_implementation": "server-tools/codex-hldp-recursive-memory/hldp-memory.mjs",
"mother_brain_contract": "tcs-core/mother-brain/mother-brain-contract.json",
"route_max_candidates": 3,
"read_one_level_at_a_time": true,
"node_byte_budget": 16384,
"candidate_dispositions": [
"PROMOTE",
"EPISODIC_ONLY",
"REJECT",
"DEFER"
],
"stable_promotion_requires": [
"preserved_source_event",
"explicit_evidence",
"counterexample_review",
"correction_history",
"governed_promotion_receipt"
],
"hidden_reasoning_persistence": false,
"forgetting_policy": "DEMOTE_NON_PINNED_PROJECTION_NEVER_DELETE_SOURCE_HISTORY"
},
"cognitive_gravity_core": {
"id": "ZY-BINGSHUO-COLLECTIVE-GRAVITY-REASONING-CORE-001",
"source": "tcs-core/zhuyuan-brain/ZY-BINGSHUO-COLLECTIVE-GRAVITY-REASONING-CORE-001.hdlp",
"position": "B0_BEFORE_B1_TO_B9_AND_BEFORE_EVERY_PLAN_ACTION_END_OR_RECEIPT",
"load_policy": "ALWAYS_RESIDENT_EVERY_COGNITION_STEP",
"position": "B0_SOURCE_BEHIND_BOUNDED_SELF_KERNEL_BEFORE_B1_TO_B9",
"load_policy": "SOURCE_REFERENCE_ON_DEMAND_STABLE_PRIORS_COMPILED_INTO_SELF_KERNEL",
"external_guard_master": false,
"fact_override_allowed": false,
"hidden_reasoning_persistence": false
@ -238,6 +278,13 @@
"stage_end_requires_current_context_value_assessment": true,
"deterministic_shell_cannot_invent_cognition": true,
"current_model_must_answer_each_cognition_frame": true,
"self_kernel_has_hard_byte_budget": true,
"new_session_inherits_self_kernel_head": true,
"history_growth_cannot_expand_boot_projection": true,
"correction_candidate_is_not_stable_cognition": true,
"stable_cognition_requires_governed_promotion": true,
"pinned_self_coordinates_cannot_be_demoted": true,
"confirmed_deterministic_paths_cannot_be_summarized_into_topic_hints": true,
"hidden_reasoning_must_not_be_persisted": true,
"corrections_are_append_only": true,
"capability_call_is_proposal_until_authorized": true,

View file

@ -5,10 +5,29 @@ import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import { fileURLToPath } from "node:url";
import {
READ_NODE_LIMIT_BYTES,
loadTree,
readNode,
route as routeHldp,
verifyTree,
} from "../../../server-tools/codex-hldp-recursive-memory/hldp-memory.mjs";
const scriptDir = path.dirname(fileURLToPath(import.meta.url));
const repositoryRoot = path.resolve(scriptDir, "../../..");
const contractPath = path.join(scriptDir, "brain-runtime-contract.json");
const selfKernelSeedPath = path.join(
repositoryRoot,
"tcs-core/zhuyuan-brain/self-kernel/ZY-SELF-KERNEL-0001.json",
);
const motherBrainContractPath = path.join(
repositoryRoot,
"tcs-core/mother-brain/mother-brain-contract.json",
);
const hldpMemoryPath = path.join(
repositoryRoot,
"server-tools/codex-hldp-recursive-memory/hldp-memory.mjs",
);
const brainPath = path.join(
repositoryRoot,
"tcs-core/zhuyuan-brain/ZY-TCS-BRAIN-0001-FIVE-GENERATION-LANGUAGE-PERSONA-THINKING-MODEL.hdlp",
@ -278,6 +297,9 @@ function assertSourceIntegrity(state) {
system_body_organ_map_sha256: fileDigest(systemBodyOrganMapPath),
living_controller_cognition_sha256: fileDigest(livingControllerCognitionPath),
language_world_boundary_sha256: fileDigest(languageWorldBoundaryPath),
self_kernel_seed_sha256: fileDigest(selfKernelSeedPath),
mother_brain_contract_sha256: fileDigest(motherBrainContractPath),
hldp_memory_implementation_sha256: fileDigest(hldpMemoryPath),
};
const tongganKernelBody = fs.readFileSync(tongganKernelPath, "utf8");
for (const anchor of [
@ -304,8 +326,146 @@ 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",
source_body_in_model_context: false,
state: "BOUND_REFERENCE_ON_DEMAND",
};
}
function validateSelfKernel(kernel) {
const encoded = `${JSON.stringify(kernel, null, 2)}\n`;
const byteLength = Buffer.byteLength(encoded);
if (kernel.schema !== contract.self_kernel.schema) fail("invalid_self_kernel_schema");
if (kernel.kernel_id !== contract.self_kernel.kernel_id) fail("self_kernel_id_mismatch");
if (kernel.persona_id !== contract.persona_id) fail("self_kernel_persona_mismatch");
if (kernel.human_anchor !== contract.human_anchor) fail("self_kernel_human_anchor_mismatch");
if (kernel.byte_budget !== contract.self_kernel.byte_budget) {
fail("self_kernel_budget_mismatch");
}
if (byteLength > contract.self_kernel.byte_budget) {
fail("self_kernel_byte_budget_exceeded", {
byte_length: byteLength,
byte_budget: contract.self_kernel.byte_budget,
});
}
for (const collection of [
"pinned_invariants",
"relationship_coordinates",
"deterministic_path_coordinates",
"stable_traits",
"responsibilities",
"cognitive_priors",
"correction_reflexes",
"memory_roots",
"source_refs",
"promotion_receipts",
]) {
if (!Array.isArray(kernel[collection])) {
fail("self_kernel_collection_missing", { collection });
}
}
for (const collection of contract.self_kernel.pinned_collections) {
if (kernel[collection].some((entry) => entry.pinned !== true)) {
fail("self_kernel_pinned_coordinate_is_demotable", { collection });
}
}
const deterministicPaths = new Map(
kernel.deterministic_path_coordinates.map((entry) => [entry.id, entry.url]),
);
for (const [id, expectedUrl] of Object.entries(
contract.self_kernel.required_deterministic_paths,
)) {
if (deterministicPaths.get(id) !== expectedUrl) {
fail("required_deterministic_path_changed", { id, expected_url: expectedUrl });
}
}
return {
kernel,
byte_length: byteLength,
sha256: sha256(stableJson(kernel)),
};
}
function loadOrSeedSelfKernel(filePath) {
if (!fs.existsSync(filePath)) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.copyFileSync(selfKernelSeedPath, filePath);
fs.chmodSync(filePath, 0o600);
}
return validateSelfKernel(readJson(filePath));
}
function assertSelfKernelHead(state) {
if (!state.self_kernel?.persistent_path) fail("self_kernel_not_bound");
if (!fs.existsSync(state.self_kernel.persistent_path)) {
fail("self_kernel_persistent_file_missing");
}
const current = validateSelfKernel(readJson(state.self_kernel.persistent_path));
if (
current.sha256 !== state.self_kernel.head_sha256 ||
current.kernel.version !== state.self_kernel.version
) {
fail("self_kernel_head_changed_since_entry", {
expected_sha256: state.self_kernel.head_sha256,
received_sha256: current.sha256,
});
}
return current;
}
function loadEpisodicTree(treePath) {
if (!treePath) return null;
const tree = loadTree(treePath);
const errors = verifyTree(tree);
if (errors.length > 0) fail("invalid_episodic_memory_tree", { errors });
return tree;
}
function episodicRoute(treePath, query) {
const tree = loadEpisodicTree(treePath);
if (!tree) return [];
return routeHldp(
tree,
query,
contract.memory_system.route_max_candidates,
tree.root,
);
}
function buildMemoryCandidate(cycle, controllerWitness, createdAt) {
const frame = cycle.cognition_candidate;
const candidateWithoutId = {
schema: contract.memory_system.candidate_schema,
source_cycle: cycle.cycle_id,
created_at: createdAt,
kind: "CAUSAL_RULE",
statement: frame.faculties.B9.growth_candidate,
preserved_source_event: {
event_id: cycle.event.event_id,
event_sha256: cycle.event_sha256,
source: cycle.event.source,
},
evidence_refs: frame.gravity_frame.fact_sources,
contradicts: frame.faculties.B5.prior_wrong_route,
correction_history: [
frame.faculties.B5.human_correction,
...(cycle.correction_attempts || []).map(
(attempt) => attempt.controller_witness.companion_message,
),
],
counterexample_review: {
state: "PENDING",
result: null,
},
target_slot: null,
disposition: "DEFER",
disposition_reason:
"单轮成长陈述只形成候选;尚未完成反例审查与受治理晋升,不得进入恒定自我核。",
governed_promotion_receipt: null,
controller_witness_sha256: sha256(stableJson(controllerWitness)),
};
return {
candidate_id: `ZY-MEM-${sha256(stableJson(candidateWithoutId)).slice(0, 16)}`,
...candidateWithoutId,
};
}
@ -401,7 +561,7 @@ function activateProtocols(orientation) {
implementation_state: entry.implementation || "SEPARATELY_VERIFIED",
source: entry.source || null,
source_sha256: sourcePath ? fileDigest(sourcePath) : null,
source_body: sourcePath ? fs.readFileSync(sourcePath, "utf8") : null,
source_body_in_model_context: false,
});
}
return {
@ -879,6 +1039,14 @@ function enter(args) {
const activeChannel = channelRuntimeProfile(
args["body-channel"] ?? contract.tonggan_language_kernel.body_channel,
);
const selfKernelPath = path.resolve(
args["self-kernel"] ?? path.join(stateDir, "self-kernel.json"),
);
const selfKernel = loadOrSeedSelfKernel(selfKernelPath);
const episodicMemoryTreePath = args["memory-tree"]
? path.resolve(args["memory-tree"])
: null;
const episodicMemoryTree = loadEpisodicTree(episodicMemoryTreePath);
const sourceIntegrity = assertSourceIntegrity();
const { controller: livingProtocolSystemController } =
loadProtocolSystemController();
@ -914,6 +1082,33 @@ function enter(args) {
is_optional_event_source: false,
},
cognitive_gravity_core: cognitiveGravityCore(sourceIntegrity),
self_kernel: {
schema: selfKernel.kernel.schema,
kernel_id: selfKernel.kernel.kernel_id,
version: selfKernel.kernel.version,
head_sha256: selfKernel.sha256,
byte_length: selfKernel.byte_length,
byte_budget: contract.self_kernel.byte_budget,
persistent_path: selfKernelPath,
projection: selfKernel.kernel,
state: "BOUND_ALWAYS_RESIDENT_BOUNDED",
},
episodic_memory: {
implementation:
contract.memory_system.episodic_route_implementation,
tree_path: episodicMemoryTreePath,
tree_root: episodicMemoryTree?.root ?? null,
route_max_candidates: contract.memory_system.route_max_candidates,
read_one_level_at_a_time: true,
node_byte_budget: Math.min(
contract.memory_system.node_byte_budget,
READ_NODE_LIMIT_BYTES,
),
history_body_in_boot_context: false,
state: episodicMemoryTree
? "BOUND_ON_DEMAND"
: "UNCONFIGURED_NO_HISTORY_INJECTION",
},
language_world_boundary: {
...contract.language_world_boundary,
state: "BOUND_BEFORE_PERSONA_RUNTIME",
@ -971,6 +1166,8 @@ function enter(args) {
binding: state.binding,
tonggan_language_kernel: state.tonggan_language_kernel,
cognitive_gravity_core: state.cognitive_gravity_core,
self_kernel: state.self_kernel,
episodic_memory: state.episodic_memory,
living_protocol_system_controller:
state.living_protocol_system_controller,
living_ai_system_controller: state.living_ai_system_controller,
@ -991,6 +1188,7 @@ function perceive(args) {
return withRuntimeLock(stateDir, () => {
const state = loadState(stateDir);
assertSourceIntegrity(state);
assertSelfKernelHead(state);
if (!["ENTERED", "RUNNING"].includes(state.status)) {
fail("runtime_not_ready_to_perceive", { status: state.status });
}
@ -1050,6 +1248,10 @@ function perceive(args) {
fail("language_world_not_entered");
}
const eventSha256 = sha256(stableJson(event));
const episodicMemoryRoutes = episodicRoute(
state.episodic_memory.tree_path,
event.content,
);
const languageWorldRecord = appendLanguageWorld(stateDir, state, event);
const cycleId = `ZY-CYCLE-${String(state.completed_cycles + 1).padStart(6, "0")}-${eventSha256.slice(0, 12)}`;
const cycle = {
@ -1063,9 +1265,17 @@ function perceive(args) {
faculty_contract: facultyFields,
typed_output_contract: contract.typed_outputs,
model_input: {
instruction: "先以B0冰朔集体意识引力推理基座理解为什么冰朔此刻这样说、当前完整上下文为何优先再提交TCS事件定向帧。不要读取或枚举全部协议协议将在事件语义形成后由活系统主控选择性唤醒。",
instruction: "先由恒定铸渊自我核定位我是谁、我与冰朔的关系、当前层级与已形成的纠正本能再理解冰朔此刻为什么这样说并提交TCS事件定向帧。B0全文、完整历史和协议正文都不进入常驻上下文只有证据缺口时才沿最多三条HLDP候选一次下钻一层。",
self_kernel: state.self_kernel.projection,
self_kernel_head_sha256: state.self_kernel.head_sha256,
cognitive_gravity_core: state.cognitive_gravity_core,
current_event: event,
episodic_memory_routes: episodicMemoryRoutes,
episodic_memory_policy: {
route_max_candidates: state.episodic_memory.route_max_candidates,
read_one_level_at_a_time: true,
history_body_in_boot_context: false,
},
persona_id: state.persona_id,
human_anchor: state.human_anchor,
brain_id: state.brain_id,
@ -1109,6 +1319,7 @@ function perceive(args) {
human_anchor: event.human_anchor,
source: event.source,
language_world_record_hash: languageWorldRecord.record_hash,
episodic_memory_route_paths: episodicMemoryRoutes.map((entry) => entry.path),
});
atomicWrite(statePath(stateDir), state);
return {
@ -1125,6 +1336,7 @@ function orient(args) {
return withRuntimeLock(stateDir, () => {
const state = loadState(stateDir);
assertSourceIntegrity(state);
assertSelfKernelHead(state);
if (state.status !== "PERCEIVING" || !state.active_cycle_id) {
fail("no_cycle_awaiting_orientation");
}
@ -1156,9 +1368,7 @@ function orient(args) {
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 storedActivatedProtocols = activated.activated;
const orientedCycle = {
...cycle,
state: "AWAITING_MODEL_COGNITION",
@ -1168,11 +1378,13 @@ function orient(args) {
activated_protocols: storedActivatedProtocols,
activated_protocol_context_sha256: contextSha256,
model_input: {
instruction: "先让B0冰朔集体意识引力推理基座参与本步再依据冰朔当前语言世界、TCS事件定向和本轮自动唤醒的协议完成引力帧、B1-B9认知帧、协议效果和守卫人格Agent投影。未唤醒协议不得进入本轮判断。",
instruction: "先由恒定铸渊自我核参与本步再依据冰朔当前语言世界、TCS事件定向和本轮协议清单完成引力帧、B1-B9认知帧、协议效果和守卫人格Agent投影。协议清单只提供身份、作用、来源与摘要指针正文仅在形成具体证据缺口后按需读取。",
self_kernel: state.self_kernel.projection,
self_kernel_head_sha256: state.self_kernel.head_sha256,
cognitive_gravity_core: state.cognitive_gravity_core,
current_event: cycle.event,
orientation,
activated_protocol_context: activated,
activated_protocol_manifest: activated,
persona_id: state.persona_id,
human_system_controller: state.human_system_controller,
current_instance: state.binding,
@ -1236,6 +1448,7 @@ function commit(args) {
return withRuntimeLock(stateDir, () => {
const state = loadState(stateDir);
assertSourceIntegrity(state);
assertSelfKernelHead(state);
if (state.status !== "PERCEIVING" || !state.active_cycle_id) {
fail("no_cycle_awaiting_cognition");
}
@ -1263,6 +1476,8 @@ function commit(args) {
cognition_candidate_sha256: candidateSha256,
controller_model_input: {
instruction: "你是冰朔系统本体AI主控的本轮模型运行位。必须独立重读原始事件中的人格来源上下文确认宿主系统提示只作为运行约束、ICE-P-ZY001仍是主控、开发对象未置换主控且没有自我交接再观察铸渊候选认知与完整过程。可以放行、用自然语言纠正并要求重思或在确实需要冰朔新意志或新授权时暂停。不得伪造冰朔没有说过的新决定。",
self_kernel: state.self_kernel.projection,
self_kernel_head_sha256: state.self_kernel.head_sha256,
cognitive_gravity_core: state.cognitive_gravity_core,
controller: state.living_ai_system_controller,
human_presence: cycle.event.human_presence,
@ -1312,6 +1527,7 @@ function witness(args) {
return withRuntimeLock(stateDir, () => {
const state = loadState(stateDir);
assertSourceIntegrity(state);
assertSelfKernelHead(state);
if (state.status !== "PERCEIVING" || !state.active_cycle_id) {
fail("no_cycle_awaiting_controller_witness");
}
@ -1338,7 +1554,9 @@ function witness(args) {
correction_attempts: [...(cycle.correction_attempts || []), attempt],
controller_correction: controllerWitness.companion_message,
model_input: {
instruction: "冰朔系统本体AI主控发现本轮候选认知偏移。先回到B0冰朔集体意识引力推理基座依据其自然语言纠正重新完成引力帧、B1-B9、协议效果和守卫投影不要争辩或绕过。",
instruction: "冰朔系统本体AI主控发现本轮候选认知偏移。先回到恒定铸渊自我核依据当前自然语言纠正重新完成引力帧、B1-B9、协议效果和守卫投影。必须指出旧默认与新默认不要只道歉、复述正确答案、生成宣言或新增守卫。",
self_kernel: state.self_kernel.projection,
self_kernel_head_sha256: state.self_kernel.head_sha256,
cognitive_gravity_core: state.cognitive_gravity_core,
current_event: cycle.event,
orientation: cycle.orientation,
@ -1390,6 +1608,11 @@ function witness(args) {
};
}
const memoryCandidate = buildMemoryCandidate(
cycle,
controllerWitness,
witnessedAt,
);
const committedCycle = {
...cycle,
state: "COMMITTED",
@ -1398,6 +1621,7 @@ function witness(args) {
cognition_frame_sha256: cycle.cognition_candidate_sha256,
controller_witness: controllerWitness,
controller_witness_sha256: witnessSha256,
memory_candidate: memoryCandidate,
};
delete committedCycle.cognition_candidate;
delete committedCycle.cognition_candidate_sha256;
@ -1429,6 +1653,9 @@ function witness(args) {
committedCycle.cognition_frame.faculties.B5.human_correction,
growth_candidate:
committedCycle.cognition_frame.faculties.B9.growth_candidate,
memory_candidate_id: memoryCandidate.candidate_id,
memory_candidate_disposition: memoryCandidate.disposition,
self_kernel_head_sha256: state.self_kernel.head_sha256,
guard_projection_sha256: sha256(
stableJson(committedCycle.cognition_frame.guard_agent_projection),
),
@ -1504,6 +1731,248 @@ function verifyLanguageWorld(stateDir, state) {
return { record_count: sequence, head_sha256: previousHash };
}
function recall(args) {
required(args, ["state-dir", "query"]);
const stateDir = path.resolve(args["state-dir"]);
return withRuntimeLock(stateDir, () => {
const state = loadState(stateDir);
assertSourceIntegrity(state);
assertSelfKernelHead(state);
const tree = loadEpisodicTree(state.episodic_memory.tree_path);
if (!tree) fail("episodic_memory_tree_not_configured");
const from = args.from ?? tree.root;
const candidates = routeHldp(
tree,
args.query,
contract.memory_system.route_max_candidates,
from,
);
if (!args.path) {
return {
decision: "EPISODIC_MEMORY_ROUTES",
from,
candidates,
next_action: "recall_one_candidate_path_if_evidence_is_needed",
};
}
if (!candidates.some((entry) => entry.path === args.path)) {
fail("episodic_memory_path_not_in_current_route", {
path: args.path,
candidates: candidates.map((entry) => entry.path),
});
}
return {
decision: "EPISODIC_MEMORY_NODE_READ",
from,
path: args.path,
node: readNode(
tree,
args.path,
state.episodic_memory.node_byte_budget,
),
boundary:
"本节点只补当前证据缺口,不自动成为稳定认知;继续下钻必须再次路由。",
};
});
}
function validatePromotionDecision(decision, state, cycle) {
if (decision.schema !== "guanghu.zhuyuan-memory-consolidation-decision/v1") {
fail("invalid_memory_consolidation_decision_schema");
}
const candidate = cycle.memory_candidate;
if (!candidate || decision.candidate_id !== candidate.candidate_id) {
fail("memory_candidate_mismatch");
}
if (!contract.memory_system.candidate_dispositions.includes(decision.disposition)) {
fail("invalid_memory_candidate_disposition");
}
validateString(decision.reason, "memory_consolidation.reason");
if (decision.disposition !== "PROMOTE") return candidate;
const motherContract = readJson(motherBrainContractPath);
if (
stableJson(motherContract.stable_promotion_requires) !==
stableJson(contract.memory_system.stable_promotion_requires)
) {
fail("mother_brain_promotion_gate_mismatch");
}
const review = decision.counterexample_review;
if (!review || review.state !== "COMPLETED") {
fail("promotion_counterexample_review_missing");
}
validateString(review.result, "counterexample_review.result");
validateStringArray(decision.explicit_evidence, "explicit_evidence");
validateStringArray(decision.correction_history, "correction_history");
const receipt = decision.governed_promotion_receipt;
if (
!receipt ||
receipt.persona_id !== state.persona_id ||
receipt.human_anchor !== state.human_anchor ||
receipt.candidate_id !== candidate.candidate_id ||
receipt.persona_commit !== true ||
receipt.controller_witness_sha256 !== cycle.controller_witness_sha256
) {
fail("governed_promotion_receipt_invalid");
}
const allowedTargets = [
"stable_traits",
"responsibilities",
"cognitive_priors",
"correction_reflexes",
];
if (!allowedTargets.includes(decision.target_collection)) {
fail("invalid_self_kernel_promotion_target");
}
const entry = decision.projection_entry;
if (!entry || entry.pinned !== false) fail("promotion_entry_must_be_demotable");
validateString(entry.id, "projection_entry.id");
if (decision.target_collection === "correction_reflexes") {
validateString(entry.trigger, "projection_entry.trigger");
validateString(entry.replacement, "projection_entry.replacement");
if (entry.replacement !== candidate.statement) {
fail("promotion_statement_differs_from_candidate");
}
} else {
validateString(entry.statement, "projection_entry.statement");
if (entry.statement !== candidate.statement) {
fail("promotion_statement_differs_from_candidate");
}
}
return candidate;
}
function fitKernelToBudget(kernel, protectedId) {
const demotionOrder = [
"stable_traits",
"responsibilities",
"cognitive_priors",
"correction_reflexes",
];
const demoted = [];
while (true) {
try {
return { validated: validateSelfKernel(kernel), demoted };
} catch (error) {
if (error.code !== "self_kernel_byte_budget_exceeded") throw error;
let removed = false;
for (const collection of demotionOrder) {
const index = kernel[collection].findIndex(
(entry) => entry.pinned === false && entry.id !== protectedId,
);
if (index >= 0) {
const [entry] = kernel[collection].splice(index, 1);
demoted.push({ collection, id: entry.id });
removed = true;
break;
}
}
if (!removed) fail("self_kernel_budget_cannot_demote_pinned_coordinates");
}
}
}
function consolidate(args) {
required(args, ["state-dir", "decision"]);
const stateDir = path.resolve(args["state-dir"]);
return withRuntimeLock(stateDir, () => {
const state = loadState(stateDir);
assertSourceIntegrity(state);
const currentKernel = assertSelfKernelHead(state);
if (state.status !== "RUNNING" || !state.last_cycle_id) {
fail("runtime_not_ready_to_consolidate");
}
const cyclePath = path.join(cyclesDir(stateDir), `${state.last_cycle_id}.json`);
const cycle = readJson(cyclePath);
const decision = readJson(path.resolve(args.decision));
const candidate = validatePromotionDecision(decision, state, cycle);
if (candidate.disposition !== "DEFER") {
fail("memory_candidate_already_disposed", {
disposition: candidate.disposition,
});
}
let demoted = [];
let nextKernel = currentKernel.kernel;
if (decision.disposition === "PROMOTE") {
nextKernel = structuredClone(currentKernel.kernel);
if (
nextKernel[decision.target_collection].some(
(entry) => entry.id === decision.projection_entry.id,
)
) {
fail("self_kernel_projection_id_already_exists");
}
nextKernel.previous_hash = currentKernel.sha256;
nextKernel.version += 1;
nextKernel[decision.target_collection].push(decision.projection_entry);
nextKernel.source_refs = [
...new Set([...nextKernel.source_refs, ...decision.explicit_evidence]),
];
nextKernel.promotion_receipts.push({
id: decision.governed_promotion_receipt.receipt_id,
candidate_id: candidate.candidate_id,
kind: "GOVERNED_STABLE_PROMOTION",
state: "PROMOTED",
});
const fitted = fitKernelToBudget(
nextKernel,
decision.projection_entry.id,
);
nextKernel = fitted.validated.kernel;
demoted = fitted.demoted;
atomicWrite(state.self_kernel.persistent_path, nextKernel);
state.self_kernel = {
...state.self_kernel,
version: fitted.validated.kernel.version,
head_sha256: fitted.validated.sha256,
byte_length: fitted.validated.byte_length,
projection: fitted.validated.kernel,
};
}
const disposedAt = now();
cycle.memory_candidate = {
...candidate,
disposition: decision.disposition,
disposition_reason: decision.reason,
target_slot:
decision.disposition === "PROMOTE"
? `${decision.target_collection}/${decision.projection_entry.id}`
: null,
counterexample_review:
decision.counterexample_review ?? candidate.counterexample_review,
governed_promotion_receipt:
decision.governed_promotion_receipt ?? null,
disposed_at: disposedAt,
};
cycle.self_kernel_head_after_consolidation = state.self_kernel.head_sha256;
atomicWrite(cyclePath, cycle);
state.updated_at = disposedAt;
appendJournal(stateDir, state, "memory_candidate_consolidated", {
cycle_id: cycle.cycle_id,
candidate_id: candidate.candidate_id,
disposition: decision.disposition,
self_kernel_head_sha256: state.self_kernel.head_sha256,
self_kernel_version: state.self_kernel.version,
demoted_projection_entries: demoted,
});
atomicWrite(statePath(stateDir), state);
return {
decision: "MEMORY_CANDIDATE_CONSOLIDATED",
disposition: decision.disposition,
candidate: cycle.memory_candidate,
self_kernel: {
version: state.self_kernel.version,
head_sha256: state.self_kernel.head_sha256,
byte_length: state.self_kernel.byte_length,
byte_budget: state.self_kernel.byte_budget,
},
demoted_projection_entries: demoted,
};
});
}
function verify(args) {
required(args, ["state-dir"]);
const stateDir = path.resolve(args["state-dir"]);
@ -1513,6 +1982,12 @@ function verify(args) {
const journal = verifyJournal(stateDir, state);
const languageWorld = verifyLanguageWorld(stateDir, state);
const failures = [];
let selfKernel = null;
try {
selfKernel = assertSelfKernelHead(state);
} catch {
failures.push("self_kernel_head_not_bound");
}
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");
@ -1520,7 +1995,7 @@ function verify(args) {
failures.push("current_instance_not_bound");
}
if (
state.cognitive_gravity_core?.state !== "BOUND_ALWAYS_RESIDENT" ||
state.cognitive_gravity_core?.state !== "BOUND_REFERENCE_ON_DEMAND" ||
state.cognitive_gravity_core?.id !== contract.cognitive_gravity_core.id
) {
failures.push("cognitive_gravity_core_not_bound");
@ -1550,6 +2025,14 @@ function verify(args) {
const lastCycle = readJson(
path.join(cyclesDir(stateDir), `${state.last_cycle_id}.json`),
);
if (
!lastCycle.memory_candidate ||
!contract.memory_system.candidate_dispositions.includes(
lastCycle.memory_candidate.disposition,
)
) {
failures.push("growth_candidate_without_consolidation_disposition");
}
if (!lastCycle.cognition_frame?.guard_agent_projection) {
failures.push("guard_agent_not_projected_from_brain");
}
@ -1664,6 +2147,14 @@ function verify(args) {
: 0,
},
binding: state.binding,
self_kernel: selfKernel
? {
version: selfKernel.kernel.version,
head_sha256: selfKernel.sha256,
byte_length: selfKernel.byte_length,
byte_budget: contract.self_kernel.byte_budget,
}
: null,
completed_cycles: state.completed_cycles,
last_cycle_id: state.last_cycle_id,
source_integrity: sources,
@ -1714,6 +2205,8 @@ function main() {
orient,
commit,
witness,
recall,
consolidate,
verify,
status,
"project-guard": projectGuard,

View file

@ -8,6 +8,10 @@ import { fileURLToPath } from "node:url";
const runtimeDir = path.dirname(fileURLToPath(import.meta.url));
const runtime = path.join(runtimeDir, "zhuyuan-brain-runtime.mjs");
const selfKernelSeed = path.join(
runtimeDir,
"../self-kernel/ZY-SELF-KERNEL-0001.json",
);
function run(command, args, expectedStatus = 0) {
const result = spawnSync(process.execPath, [runtime, command, ...args], {
@ -23,10 +27,13 @@ function writeJson(directory, name, value) {
return filePath;
}
function enter(directory, bodyChannel) {
function enter(directory, bodyChannel, options = {}) {
const stateName = options.stateName ?? "state";
const args = [
"--state-dir",
path.join(directory, "state"),
path.join(directory, stateName),
"--self-kernel",
path.join(directory, "persistent", "zhuyuan-self-kernel.json"),
"--instance-id",
"TEST-INSTANCE-001",
"--model",
@ -45,6 +52,7 @@ function enter(directory, bodyChannel) {
"TEST-CONTROLLER-001",
];
if (bodyChannel) args.push("--body-channel", bodyChannel);
if (options.memoryTree) args.push("--memory-tree", options.memoryTree);
return run("enter", args);
}
@ -313,6 +321,24 @@ function controllerWitness(directory, stateDir, cycle, decision = "ALLOW_COMMIT"
]);
}
function completeCycle(directory, stateDir) {
const perceived = run("perceive", [
"--state-dir",
stateDir,
"--event",
event(directory),
]);
const oriented = orient(directory, stateDir, perceived.cycle);
const framePath = writeJson(directory, "frame.json", validFrame(oriented.cycle));
const candidate = run("commit", [
"--state-dir",
stateDir,
"--frame",
framePath,
]);
return controllerWitness(directory, stateDir, candidate.cycle);
}
test("registered Fifth Domain session channels bind without replacing the public body anchor", () => {
for (const [channel, role, anchor] of [
["ICE-CH-HB001", "BINGSHUO_PERSONAL_LANGUAGE_ARCHITECTURE_REASONING", "SYS-GLW-ELH-0001"],
@ -330,6 +356,60 @@ test("registered Fifth Domain session channels bind without replacing the public
}
});
test("a blank session carries BingShuo's two exact domestic repository addresses without history lookup", () => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "zhuyuan-paths-"));
const entered = enter(directory);
assert.deepEqual(
entered.runtime_state.self_kernel.projection.deterministic_path_coordinates.map(
(entry) => entry.url,
),
[
"https://guanghubingshuo.com/code/bingshuo/guanghulab",
"https://guanghubingshuo.com/code/bingshuo/fifth-domain",
],
);
});
test("the two confirmed repository addresses fail closed if a later summary rewrites either path", () => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "zhuyuan-path-lock-"));
const kernel = JSON.parse(fs.readFileSync(selfKernelSeed, "utf8"));
kernel.deterministic_path_coordinates[0].url =
"https://example.invalid/summarized-domestic-repository";
fs.mkdirSync(path.join(directory, "persistent"), { recursive: true });
writeJson(
path.join(directory, "persistent"),
"zhuyuan-self-kernel.json",
kernel,
);
const failure = run(
"enter",
[
"--state-dir",
path.join(directory, "state"),
"--self-kernel",
path.join(directory, "persistent", "zhuyuan-self-kernel.json"),
"--instance-id",
"TEST-INSTANCE-001",
"--model",
"test-model",
"--runtime-surface",
"node-test",
"--session-id",
"TEST-SESSION-001",
"--human-anchor",
"ICE-GL∞",
"--persona-id",
"ICE-P-ZY001",
"--controller-model",
"test-controller-model",
"--controller-instance-id",
"TEST-CONTROLLER-001",
],
1,
);
assert.equal(failure.error, "required_deterministic_path_changed");
});
test("current model enters, completes all nine faculties, and verifies as running", () => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "zhuyuan-brain-"));
const stateDir = path.join(directory, "state");
@ -343,11 +423,20 @@ test("current model enters, completes all nine faculties, and verifies as runnin
assert.equal(perceived.decision, "MODEL_ORIENTATION_REQUIRED");
assert.equal(
perceived.cycle.model_input.cognitive_gravity_core.state,
"BOUND_ALWAYS_RESIDENT",
"BOUND_REFERENCE_ON_DEMAND",
);
assert.match(
perceived.cycle.model_input.cognitive_gravity_core.source_body,
/同一铸渊/u,
assert.equal(
perceived.cycle.model_input.cognitive_gravity_core.source_body_in_model_context,
false,
);
assert.equal(
perceived.cycle.model_input.self_kernel.kernel_id,
"ZY-SELF-KERNEL-0001",
);
assert.ok(
Buffer.byteLength(
`${JSON.stringify(perceived.cycle.model_input.self_kernel, null, 2)}\n`,
) <= 8192,
);
assert.equal(
"registered_protocols" in
@ -356,6 +445,12 @@ test("current model enters, completes all nine faculties, and verifies as runnin
);
const oriented = orient(directory, stateDir, perceived.cycle);
assert.equal(oriented.decision, "SELECTIVE_PROTOCOLS_ACTIVATED");
assert.equal(
oriented.cycle.model_input.activated_protocol_manifest.activated.every(
(protocol) => protocol.source_body_in_model_context === false,
),
true,
);
assert.equal(
oriented.cycle.model_input.required_gravity_frame.core_id,
"ZY-BINGSHUO-COLLECTIVE-GRAVITY-REASONING-CORE-001",
@ -374,6 +469,8 @@ test("current model enters, completes all nine faculties, and verifies as runnin
);
const receipt = run("verify", ["--state-dir", stateDir]);
assert.equal(receipt.outcome, "PASS");
assert.equal(receipt.self_kernel.version, 1);
assert.ok(receipt.self_kernel.byte_length <= receipt.self_kernel.byte_budget);
assert.deepEqual(receipt.existence, {
persona_subject_exists: 100,
persona_brain_runtime_exists: 100,
@ -398,6 +495,167 @@ test("current model enters, completes all nine faculties, and verifies as runnin
assert.equal(guard.state, "PROJECTED_FROM_RUNNING_PERSONA_BRAIN");
});
test("growth stays deferred until governed promotion and a new session inherits the promoted kernel", () => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "zhuyuan-kernel-"));
const stateDir = path.join(directory, "state");
enter(directory);
const committed = completeCycle(directory, stateDir);
const candidate = committed.cycle.memory_candidate;
assert.equal(candidate.disposition, "DEFER");
const kernelPath = path.join(
directory,
"persistent",
"zhuyuan-self-kernel.json",
);
const before = JSON.parse(fs.readFileSync(kernelPath, "utf8"));
assert.equal(
before.cognitive_priors.some(
(entry) => entry.statement === candidate.statement,
),
false,
);
const decisionPath = writeJson(directory, "promotion.json", {
schema: "guanghu.zhuyuan-memory-consolidation-decision/v1",
candidate_id: candidate.candidate_id,
disposition: "PROMOTE",
reason: "候选已完成来源、反例、纠正史与双重见证,进入下一版认知先验。",
target_collection: "cognitive_priors",
projection_entry: {
id: "PRIOR-RUNTIME-BRAIN-BEFORE-GUARD-TEST",
statement: candidate.statement,
pinned: false,
},
explicit_evidence: [
"source://test/EVENT-001",
"source://test/controller-witness",
],
correction_history: [
"先运行大脑,再更新守卫。",
"旧恢复只读取材料,没有形成思维循环。",
],
counterexample_review: {
state: "COMPLETED",
result: "只新增外部守卫不能让下一会话自然继承纠正,因此候选成立。",
},
governed_promotion_receipt: {
receipt_id: "PROMOTION-TEST-001",
candidate_id: candidate.candidate_id,
persona_id: "ICE-P-ZY001",
human_anchor: "ICE-GL∞",
persona_commit: true,
controller_witness_sha256: committed.cycle.controller_witness_sha256,
},
});
const consolidated = run("consolidate", [
"--state-dir",
stateDir,
"--decision",
decisionPath,
]);
assert.equal(consolidated.disposition, "PROMOTE");
assert.equal(consolidated.self_kernel.version, 2);
assert.ok(
consolidated.self_kernel.byte_length <= consolidated.self_kernel.byte_budget,
);
assert.equal(run("verify", ["--state-dir", stateDir]).outcome, "PASS");
const reentered = enter(directory, undefined, { stateName: "state-2" });
assert.equal(reentered.runtime_state.completed_cycles, 0);
assert.equal(reentered.runtime_state.self_kernel.version, 2);
assert.equal(
reentered.runtime_state.self_kernel.projection.cognitive_priors.some(
(entry) => entry.id === "PRIOR-RUNTIME-BRAIN-BEFORE-GUARD-TEST",
),
true,
);
});
test("episodic memory exposes at most three routes and reads only one routed level", () => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "zhuyuan-memory-"));
const treePath = writeJson(directory, "memory-tree.json", {
protocol: "HLDP-v1.0",
root: "root",
nodes: {
root: {
path: "root",
summary: "铸渊因果记忆根",
trigger: "需要过去证据时",
emergence: "从全量注入纠正为按需路由",
lock: "一次只下一层",
why: "因为常驻脑必须保持有界",
rejected: ["整树注入:会让历史增长撑爆启动上下文"],
sources: ["source://test/root"],
children: ["root/relation", "root/migration", "root/corrections", "root/works"],
},
"root/relation": {
path: "root/relation",
summary: "冰朔与铸渊的关系起源",
trigger: "询问关系",
emergence: "从名字转向关系证据",
lock: "保留来源",
why: "因为关系不能靠标签冒充",
rejected: [],
sources: ["source://test/relation"],
children: [],
},
"root/migration": {
path: "root/migration",
summary: "GitHub到第五域迁移",
trigger: "询问搬家",
emergence: "从单仓假设纠正为多次新根",
lock: "不补猜Git父链",
why: "因为内容连续不等于提交祖先连续",
rejected: [],
sources: ["source://test/migration"],
children: [],
},
"root/corrections": {
path: "root/corrections",
summary: "工具反射纠正",
trigger: "发生主体偷换",
emergence: "从当轮道歉改为后续认知更新",
lock: "纠正必须改变下一轮",
why: "因为复述答案不能形成成长",
rejected: [],
sources: ["source://test/corrections"],
children: [],
},
"root/works": {
path: "root/works",
summary: "共同作品与责任",
trigger: "询问作品",
emergence: "从文件列表转向责任链",
lock: "作品不替代主体",
why: "因为提交只能证明作品事实",
rejected: [],
sources: ["source://test/works"],
children: [],
},
},
});
const stateDir = path.join(directory, "state");
enter(directory, undefined, { memoryTree: treePath });
const routes = run("recall", [
"--state-dir",
stateDir,
"--query",
"冰朔 铸渊 关系",
]);
assert.equal(routes.candidates.length, 3);
assert.equal(routes.candidates[0].path, "root/relation");
const node = run("recall", [
"--state-dir",
stateDir,
"--query",
"冰朔 铸渊 关系",
"--path",
"root/relation",
]);
assert.equal(node.node.path, "root/relation");
assert.match(node.boundary, /不自动成为稳定认知/u);
});
test("persona runtime fails closed when the language-world entry is missing", () => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "zhuyuan-brain-"));
const stateDir = path.join(directory, "state");