feat: add bounded TCS brains and channel continuity
This commit is contained in:
parent
08598d6356
commit
1d4286c11b
61 changed files with 5416 additions and 54 deletions
|
|
@ -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,
|
||||
|
|
|
|||
Loading…
Reference in a new issue