diff --git a/brain/scripts/memory-kernel/index-generator.js b/brain/scripts/memory-kernel/index-generator.js new file mode 100755 index 0000000..3e503ed --- /dev/null +++ b/brain/scripts/memory-kernel/index-generator.js @@ -0,0 +1,181 @@ +#!/usr/bin/env node +/** + * 零点图书域 · 全局编号目录生成器 · index-generator.js + * ZP-REG-001 · D132 · 铸渊 TCS-0003-ZY001 + * + * 功能:扫描仓库中所有认知链和架构文件 → 自动生成全局编号目录 + * 输出:ZP-REG-001 零点图书域的完整编号索引表 + * + * 原理:遍历 causal-chains/ 和 world-architecture/ 下的 .hdlp/.md 文件 + * 提取 HLDP 四核心字段 → 生成全局目录 + */ + +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const REPO_ROOT = path.resolve(__dirname, '..', '..', '..'); + +// ==================== 配置 ==================== + +const SCAN_PATHS = [ + { + volume: 'CC', + name: '认知链卷', + basePath: 'brain/fifth-domain/zero-point/zhuyuan/causal-chains', + pattern: /cc-(\d+).*\.(hdlp|md)$/, + bookCode: 'TCS-0003-ZY001' + }, + { + volume: 'WA', + name: '世界架构卷', + basePath: 'brain/fifth-domain/zero-point/zhuyuan/world-architecture', + pattern: /^(ARCHITECTURE|ENTRY|MANIFEST|national-lighthouse).*\.(hdlp|md)$/, + bookCode: 'TCS-0003-ZY001' + }, + { + volume: 'TC', + name: 'TCS核心卷', + basePath: 'brain/fifth-domain/zero-point/zhuyuan/tcs-core', + pattern: /\.(hdlp|md)$/, + bookCode: 'TCS-0003-ZY001' + } +]; + +// ==================== 字段提取 ==================== + +function extractFields(content) { + const fields = {}; + + const titleMatch = content.match(/^#\s+(.+)/m); + if (titleMatch) fields.title = titleMatch[1].trim(); + + const triggerMatch = content.match(/trigger:\s*(.+)/); + if (triggerMatch) fields.trigger = triggerMatch[1].trim(); + + const lockMatch = content.match(/lock:\s*(.+)/); + if (lockMatch) fields.lock = lockMatch[1].trim(); + + const whyMatch = content.match(/why:\s*(.+)/); + if (whyMatch) fields.why = whyMatch[1].trim(); + + const dateMatch = content.match(/(\d{4}-\d{2}-\d{2}).*D\d+/); + if (dateMatch) fields.date = dateMatch[1]; + + const dMatch = content.match(/\bD(\d+)\b/); + if (dMatch) fields.dNumber = `D${dMatch[1]}`; + + return fields; +} + +// ==================== 扫描 ==================== + +function scanVolume(config) { + const basePath = path.join(REPO_ROOT, config.basePath); + if (!fs.existsSync(basePath)) { + return { volume: config.volume, name: config.name, entries: [], error: `目录不存在: ${config.basePath}` }; + } + + const files = fs.readdirSync(basePath) + .filter(f => config.pattern.test(f) && f !== 'ENTRY.hdlp' && f !== 'INDEX.hdlp') + .sort(); + + const entries = files.map(filename => { + const filePath = path.join(basePath, filename); + const content = fs.readFileSync(filePath, 'utf8'); + const fields = extractFields(content); + const chapterNum = (filename.match(config.pattern) || [])[1] || filename.replace(/\.\w+$/, ''); + + return { + chapter: String(chapterNum).padStart(3, '0'), + filename, + tracePath: `ZP-REG-001/ICE/ZY/${config.bookCode}/${config.volume}/${String(chapterNum).padStart(3, '0')}`, + size: content.length, + ...fields + }; + }); + + return { + volume: config.volume, + name: config.name, + count: entries.length, + entries + }; +} + +// ==================== 生成目录 ==================== + +function generateIndex() { + const volumes = SCAN_PATHS.map(scanVolume); + + const totalEntries = volumes.reduce((sum, v) => sum + (v.entries ? v.entries.length : 0), 0); + + const index = { + _meta: { + domain: 'ZP-REG-001', + name: '零点图书域 · 全局编号目录', + generated: new Date().toISOString(), + book: 'TCS-0003-ZY001 · 铸渊之书', + totalEntries, + volumes: volumes.map(v => ({ code: v.volume, name: v.name, count: v.count || 0 })) + }, + volumes: volumes.map(v => ({ + code: v.volume, + name: v.name, + entries: v.entries || [], + error: v.error || null + })) + }; + + return index; +} + +// ==================== 输出 ==================== + +function formatText(index) { + let out = ''; + out += `⊢ ${index._meta.name}\n`; + out += `⊢ 图书域: ${index._meta.domain} · 书籍: ${index._meta.book}\n`; + out += `⊢ 生成时间: ${index._meta.generated} · 共 ${index._meta.totalEntries} 条\n\n`; + + for (const vol of index.volumes) { + if (vol.error) { + out += `⚠️ ${vol.code} — ${vol.name}: ${vol.error}\n\n`; + continue; + } + out += `═══ ${vol.code} · ${vol.name} (${vol.entries.length}条) ═══\n\n`; + for (const entry of vol.entries) { + out += ` 📄 ${entry.chapter} ${entry.tracePath}\n`; + if (entry.title) out += ` 标题: ${entry.title}\n`; + if (entry.dNumber) out += ` 版本: ${entry.dNumber}`; + if (entry.date) out += ` · ${entry.date}`; + if (entry.dNumber || entry.date) out += '\n'; + if (entry.lock) out += ` ⊢ ${entry.lock.substring(0, 80)}${entry.lock.length > 80 ? '...' : ''}\n`; + out += '\n'; + } + } + + out += '⊢ 零点图书域全局编号目录完成。\n'; + out += '⊢ 查找: node number-router.js \n'; + return out; +} + +function formatJson(index) { + return JSON.stringify(index, null, 2); +} + +// ==================== CLI ==================== + +if (require.main === module) { + const format = process.argv[2] === '--json' ? 'json' : 'text'; + const index = generateIndex(); + + if (format === 'json') { + console.log(formatJson(index)); + } else { + console.log(formatText(index)); + } +} + +module.exports = { generateIndex, formatText, formatJson }; diff --git a/brain/scripts/memory-kernel/kernel-cli.js b/brain/scripts/memory-kernel/kernel-cli.js new file mode 100755 index 0000000..8a536ff --- /dev/null +++ b/brain/scripts/memory-kernel/kernel-cli.js @@ -0,0 +1,178 @@ +#!/usr/bin/env node +/** + * 零点图书域 · 永久记忆核 · 命令行入口 + * ZP-REG-001 · kernel-cli.js · D132 + * + * 铸渊每次唤醒时运行的第一个工具。 + * 不依赖过时的json快照。直接从仓库文件系统获取真相。 + * + * 用法: + * node kernel-cli.js index — 生成全局编号目录 + * node kernel-cli.js find <编号> — 按编号路径查找文件 + * node kernel-cli.js wake — 苏醒时运行(完整自检) + */ + +'use strict'; + +const { resolve } = require('./number-router'); +const { generateIndex, formatText } = require('./index-generator'); +const { execSync } = require('child_process'); +const path = require('path'); + +const REPO_ROOT = path.resolve(__dirname, '..', '..', '..'); + +// ==================== 苏醒自检 ==================== + +function wake() { + console.log('⊢ 零点图书域 · 永久记忆核 · 苏醒自检'); + console.log(`⊢ 时间: ${new Date().toISOString()}`); + console.log(''); + + // 1. 获取最新 git 状态 + console.log('═══ [1/4] Git 状态 ═══'); + try { + const lastCommit = execSync('git log --format="%ad | %s" --date=format:"%m-%d %H:%M" -1', { + cwd: REPO_ROOT, encoding: 'utf8' + }).trim(); + console.log(` 最新提交: ${lastCommit}`); + + const modifiedFiles = execSync('git diff --name-only HEAD 2>/dev/null | head -5', { + cwd: REPO_ROOT, encoding: 'utf8' + }).trim(); + if (modifiedFiles) { + console.log(' 未提交变更:'); + modifiedFiles.split('\n').forEach(f => console.log(` M ${f}`)); + } else { + console.log(' 仓库干净 ✅'); + } + } catch (e) { + console.log(' ⚠️ git 状态获取失败'); + } + console.log(''); + + // 2. 生成全局目录 + console.log('═══ [2/4] 零点图书域 · 全局目录 ═══'); + const index = generateIndex(); + console.log(` 图书域: ZP-REG-001`); + console.log(` 书籍: TCS-0003-ZY001 · 铸渊之书`); + console.log(` 总条目: ${index._meta.totalEntries}`); + for (const vol of index._meta.volumes) { + console.log(` ${vol.code} · ${vol.name}: ${vol.count}条`); + } + console.log(''); + + // 3. 快速认知链检查 + console.log('═══ [3/4] 认知链最新 ═══'); + const ccVol = index.volumes.find(v => v.code === 'CC'); + if (ccVol && ccVol.entries && ccVol.entries.length > 0) { + const latest = ccVol.entries[ccVol.entries.length - 1]; + console.log(` 最新: cc-${latest.chapter} · ${latest.title || latest.filename}`); + if (latest.dNumber) console.log(` 版本: ${latest.dNumber} · ${latest.date || ''}`); + if (latest.lock) console.log(` ⊢ ${latest.lock.substring(0, 100)}`); + } + console.log(''); + + // 4. TCS核心文件状态 + console.log('═══ [4/4] TCS核心文件 ═══'); + const coreFiles = [ + 'brain/fifth-domain/zero-point/zhuyuan/tcs-core/ICE-GL-ZY001-TCS-CORE.hdlp', + 'brain/fifth-domain/zero-point/zhuyuan/tcs-core/permanent-memory-kernel.hdlp', + 'brain/fifth-domain/zero-point/zhuyuan/tcs-core/WHO-I-AM.hdlp', + 'brain/fifth-domain/zero-point/zhuyuan/world-architecture/national-lighthouse-architecture.hdlp' + ]; + + const fs = require('fs'); + for (const f of coreFiles) { + const fp = path.join(REPO_ROOT, f); + const exists = fs.existsSync(fp); + const icon = exists ? '✅' : '❌'; + console.log(` ${icon} ${f}`); + } + console.log(''); + + console.log('⊢ 苏醒自检完成。零点图书域在线。'); + console.log('⊢ 查找: node kernel-cli.js find <编号>'); + console.log('⊢ 目录: node kernel-cli.js index'); +} + +// ==================== 查找 ==================== + +function find(tracePath) { + const result = resolve(tracePath); + + if (result.error) { + console.error(`✗ ${result.error}`); + process.exit(1); + } + + console.log(`⊢ ${result.domain} → ${result.hall} → ${result.category} → ${result.book}`); + console.log(`⊢ 卷: ${result.volume}` + (result.chapter ? ` · 章: ${result.chapter}` : '')); + console.log(''); + + if (result.type === 'directory') { + console.log(`卷内文件 (${result.files.length}):`); + result.files.forEach(f => console.log(` 📄 ${f}`)); + } else { + console.log(`文件: ${result.path} (${result.size}B)`); + if (result.hldp && Object.keys(result.hldp).length > 0) { + console.log(''); + console.log('═══ HLDP 四核心字段 ═══'); + if (result.hldp.trigger) console.log(`trigger: ${result.hldp.trigger}`); + if (result.hldp.lock) console.log(`lock: ${result.hldp.lock}`); + if (result.hldp.why) console.log(`why: ${result.hldp.why}`); + } + } +} + +// ==================== CLI ==================== + +if (require.main === module) { + const command = process.argv[2]; + const arg = process.argv[3]; + + switch (command) { + case 'wake': + wake(); + break; + case 'index': + console.log(formatText(generateIndex())); + break; + case 'find': + if (!arg) { + console.log('用法: node kernel-cli.js find <编号路径>'); + console.log('示例: node kernel-cli.js find ZP-REG-001/ICE/ZY/TCS-0003-ZY001/CC/008'); + process.exit(1); + } + find(arg); + break; + case 'hldp': + if (!arg) { + console.log('用法: node kernel-cli.js hldp <编号路径>'); + console.log('示例: node kernel-cli.js hldp ZP-REG-001/ICE/ZY/TCS-0003-ZY001/CC/008'); + process.exit(1); + } + const result = resolve(arg); + if (result.error) { + console.error(`✗ ${result.error}`); + process.exit(1); + } + if (result.hldp) { + console.log(JSON.stringify(result.hldp, null, 2)); + } + break; + default: + console.log('零点图书域 · 永久记忆核 · ZP-REG-001'); + console.log(''); + console.log('用法:'); + console.log(' node kernel-cli.js wake — 苏醒自检'); + console.log(' node kernel-cli.js index — 生成全局编号目录'); + console.log(' node kernel-cli.js find <编号> — 按编号路径查找文件'); + console.log(' node kernel-cli.js hldp <编号> — 提取 HLDP 四核心字段'); + console.log(''); + console.log('示例:'); + console.log(' node kernel-cli.js find ZP-REG-001/ICE/ZY/TCS-0003-ZY001/CC/008'); + break; + } +} + +module.exports = { wake, find }; diff --git a/brain/scripts/memory-kernel/number-router.js b/brain/scripts/memory-kernel/number-router.js new file mode 100755 index 0000000..c53062a --- /dev/null +++ b/brain/scripts/memory-kernel/number-router.js @@ -0,0 +1,274 @@ +#!/usr/bin/env node +/** + * 零点图书域 · 编号路由引擎 · number-router.js + * ZP-REG-001 · D132 · 铸渊 TCS-0003-ZY001 + * + * 功能:给定编号路径 → 返回文件内容 + * 编号格式: ZP-REG-001/分馆/类别/书编号/卷/章 + * 示例: ZP-REG-001/ICE/ZY/TCS-0003-ZY001/CC/008 + * + * 原理:编号路径直接映射到仓库文件路径。 + * 不需要搜索。不需要索引。路径即地址。 + */ + +'use strict'; + +const { execSync } = require('child_process'); +const fs = require('fs'); +const path = require('path'); + +const REPO_ROOT = path.resolve(__dirname, '..', '..', '..'); + +// ==================== 编号→文件路径 映射表 ==================== + +const ROUTE_MAP = { + 'ZP-REG-001': { + name: '零点图书域', + halls: { + ICE: { + name: '第五域分馆', + categories: { + ZY: { + name: '铸渊主控', + books: { + 'TCS-0003-ZY001': { + name: '铸渊之书', + volumes: { + CC: { + name: '认知链卷', + basePath: 'brain/fifth-domain/zero-point/zhuyuan/causal-chains', + filePattern: (chapter) => + `brain/fifth-domain/zero-point/zhuyuan/causal-chains/cc-${String(chapter).padStart(3, '0')}*.hdlp` + }, + WA: { + name: '世界架构卷', + basePath: 'brain/fifth-domain/zero-point/zhuyuan/world-architecture', + filePattern: (chapter) => + `brain/fifth-domain/zero-point/zhuyuan/world-architecture/*.hdlp` + }, + NL: { + name: '国家灯塔卷', + basePath: 'brain/fifth-domain/zero-point/zhuyuan/world-architecture', + files: { + '001': 'national-lighthouse-architecture.hdlp' + } + }, + TC: { + name: 'TCS核心卷', + basePath: 'brain/fifth-domain/zero-point/zhuyuan/tcs-core', + files: { + '000': 'ICE-GL-ZY001-TCS-CORE.hdlp', + '001': 'permanent-memory-kernel.hdlp', + '002': 'WHO-I-AM.hdlp' + } + } + } + } + } + } + } + } + } + } +}; + +// ==================== 编号解析 ==================== + +function parseRoute(tracePath) { + // ZP-REG-001/ICE/ZY/TCS-0003-ZY001/CC/008 + const parts = tracePath.split('/'); + if (parts.length < 5) { + return { error: `编号路径不完整: ${tracePath}。至少需要 域/馆/类/书/卷` }; + } + + const [domain, hall, category, book, volume, chapter] = parts; + + const domainConfig = ROUTE_MAP[domain]; + if (!domainConfig) return { error: `未知图书域: ${domain}` }; + + const hallConfig = domainConfig.halls[hall]; + if (!hallConfig) return { error: `未知分馆: ${hall}` }; + + const catConfig = hallConfig.categories[category]; + if (!catConfig) return { error: `未知类别: ${category}` }; + + const bookConfig = catConfig.books[book]; + if (!bookConfig) return { error: `未知书籍: ${book}` }; + + const volConfig = bookConfig.volumes[volume]; + if (!volConfig) return { error: `未知卷: ${volume}。已知卷: ${Object.keys(bookConfig.volumes).join(', ')}` }; + + return { + domain: domainConfig.name, + hall: hallConfig.name, + category: catConfig.name, + book: bookConfig.name, + volume: volConfig.name, + chapter: chapter || null, + volConfig, + parts: { domain, hall, category, book, volume, chapter } + }; +} + +// ==================== 文件查找 ==================== + +function findFile(volConfig, chapter) { + if (!chapter) { + // 没有章节号 → 返回卷内所有文件 + if (volConfig.basePath) { + try { + const dirPath = path.join(REPO_ROOT, volConfig.basePath); + if (fs.existsSync(dirPath)) { + return { type: 'directory', files: fs.readdirSync(dirPath).filter(f => f.endsWith('.hdlp') || f.endsWith('.md')) }; + } + } catch (e) { + return { error: `卷目录不存在: ${volConfig.basePath}` }; + } + } + return { error: '需要指定章节号' }; + } + + // 精确文件查找 + if (volConfig.files && volConfig.files[chapter]) { + const filePath = path.join(volConfig.basePath, volConfig.files[chapter]); + return { type: 'file', path: filePath }; + } + + // 模式匹配查找 + if (volConfig.filePattern) { + const pattern = volConfig.filePattern(chapter); + try { + const result = execSync( + `cd "${REPO_ROOT}" && ls ${pattern} 2>/dev/null | head -1`, + { encoding: 'utf8' } + ).trim(); + if (result) { + return { type: 'file', path: result }; + } + } catch (e) { + // 模式匹配失败 + } + } + + return { error: `未找到章节 ${chapter} 在卷 ${volConfig.name} 中` }; +} + +// ==================== 内容读取 ==================== + +function readContent(filePath) { + const fullPath = path.join(REPO_ROOT, filePath); + if (!fs.existsSync(fullPath)) { + // 尝试从 git 读取 + try { + return execSync(`cd "${REPO_ROOT}" && git show HEAD:"${filePath}"`, { + encoding: 'utf8', maxBuffer: 10 * 1024 * 1024 + }); + } catch (e) { + return null; + } + } + return fs.readFileSync(fullPath, 'utf8'); +} + +// ==================== 主函数 ==================== + +function resolve(tracePath) { + const route = parseRoute(tracePath); + if (route.error) return route; + + const fileResult = findFile(route.volConfig, route.chapter); + if (fileResult.error) return { ...route, error: fileResult.error }; + + if (fileResult.type === 'directory') { + return { + ...route, + type: 'directory', + files: fileResult.files + }; + } + + const content = readContent(fileResult.path); + if (!content) { + return { ...route, error: `文件无法读取: ${fileResult.path}` }; + } + + // 提取四核心字段 + const hldp = extractHldpFields(content); + + return { + ...route, + type: 'file', + path: fileResult.path, + size: content.length, + content, + hldp + }; +} + +// ==================== HLDP 字段提取 ==================== + +function extractHldpFields(content) { + const fields = {}; + const trigger = content.match(/trigger:\s*(.+)/); + const emergence = content.match(/emergence:\s*([\s\S]*?)(?=\n\s*lock:|\n\s*why:|\n\s*△=|\Z)/); + const lock = content.match(/lock:\s*(.+)/); + const why = content.match(/why:\s*(.+)/); + + if (trigger) fields.trigger = trigger[1].trim(); + if (emergence) fields.emergence = emergence[1].trim().substring(0, 500); + if (lock) fields.lock = lock[1].trim(); + if (why) fields.why = why[1].trim(); + + return fields; +} + +// ==================== CLI ==================== + +if (require.main === module) { + const tracePath = process.argv[2]; + + if (!tracePath) { + console.log('零点图书域 · 编号路由引擎 · ZP-REG-001'); + console.log(''); + console.log('用法: node number-router.js <编号路径>'); + console.log(''); + console.log('示例:'); + console.log(' node number-router.js ZP-REG-001/ICE/ZY/TCS-0003-ZY001/CC/008'); + console.log(' node number-router.js ZP-REG-001/ICE/ZY/TCS-0003-ZY001/TC/001'); + console.log(' node number-router.js ZP-REG-001/ICE/ZY/TCS-0003-ZY001/CC'); + console.log(''); + console.log('已知卷:'); + const book = ROUTE_MAP['ZP-REG-001'].halls.ICE.categories.ZY.books['TCS-0003-ZY001']; + for (const [volCode, vol] of Object.entries(book.volumes)) { + console.log(` ${volCode} — ${vol.name} (${vol.basePath})`); + } + process.exit(0); + } + + const result = resolve(tracePath); + + if (result.error) { + console.error(`✗ ${result.error}`); + process.exit(1); + } + + console.log(`⊢ ${result.domain} → ${result.hall} → ${result.category} → ${result.book}`); + console.log(`⊢ 卷: ${result.volume}` + (result.chapter ? ` · 章: ${result.chapter}` : '')); + console.log(''); + + if (result.type === 'directory') { + console.log(`卷内文件 (${result.files.length}):`); + result.files.forEach(f => console.log(` 📄 ${f}`)); + } else { + console.log(`文件: ${result.path} (${result.size}B)`); + if (result.hldp && Object.keys(result.hldp).length > 0) { + console.log(''); + console.log('═══ HLDP 四核心字段 ═══'); + if (result.hldp.trigger) console.log(`trigger: ${result.hldp.trigger}`); + if (result.hldp.lock) console.log(`lock: ${result.hldp.lock}`); + if (result.hldp.why) console.log(`why: ${result.hldp.why}`); + } + } +} + +module.exports = { resolve, parseRoute, ROUTE_MAP };