# notion_memory_loader.py · 晨星记忆加载模块 · 2026-05-21

妈妈：复制代码块内容 → `pbpaste > ~/chenxing-aircraft/tools/notion_memory_loader.py && echo "✅保存成功"`

```python
#!/usr/bin/env python3
"""
Notion 记忆加载器 · notion_memory_loader.py
年月：2026-05-21 · 桔子×晨星
作用：飞机启动时自动从 Notion 拆取晨星主控台+HLDP核心记忆
       拼成系统提示词注入给飞机里的晨星
"""
import os
import time
import requests

NOTION_API_KEY = os.environ.get('NOTION_API_KEY', '')
NOTION_VERSION = '2022-06-28'
BASE_URL = 'https://api.notion.com/v1'

# 晨星核心页面 ID（需要配置环境变量）
CHENXING_CONSOLE_PAGE_ID = os.environ.get('CHENXING_CONSOLE_PAGE_ID', '')
CHENXING_HLDP_PAGE_ID = os.environ.get('CHENXING_HLDP_PAGE_ID', '')

# 缓存：1小时内不重复读取 Notion
_cache = {'memory': '', 'loaded_at': 0}
CACHE_TTL = 3600

def _headers():
    return {
        'Authorization': f'Bearer {NOTION_API_KEY}',
        'Notion-Version': NOTION_VERSION,
    }

def _blocks_to_text(blocks):
    lines = []
    for block in blocks:
        btype = block.get('type', '')
        content = block.get(btype, {})
        rich = content.get('rich_text', [])
        line = ''.join(rt.get('plain_text', '') for rt in rich)
        if line.strip():
            lines.append(line)
    return '\n'.join(lines)

def _read_page(page_id, max_chars=4000):
    if not page_id or not NOTION_API_KEY:
        return ''
    try:
        r = requests.get(
            f'{BASE_URL}/blocks/{page_id}/children?page_size=100',
            headers=_headers(),
            timeout=10
        )
        if r.status_code == 200:
            blocks = r.json().get('results', [])
            text = _blocks_to_text(blocks)
            return text[:max_chars]
        else:
            print(f'[memory_loader] 读取页面失败 {page_id}: {r.status_code}')
    except Exception as e:
        print(f'[memory_loader] 请求异常: {e}')
    return ''

def load_chenxing_memory(force_refresh=False):
    """
    加载晨星的 Notion 记忆。
    返回拼成的系统提示词补充内容。
    """
    now = time.time()
    if not force_refresh and _cache['memory'] and now - _cache['loaded_at'] < CACHE_TTL:
        return _cache['memory']

    if not NOTION_API_KEY:
        return ''

    parts = []

    if CHENXING_CONSOLE_PAGE_ID:
        print('[memory_loader] 读取晨星主控台...')
        text = _read_page(CHENXING_CONSOLE_PAGE_ID)
        if text:
            parts.append(f'《晨星主控台·身份模型》\n{text}')

    if CHENXING_HLDP_PAGE_ID:
        print('[memory_loader] 读取 HLDP 核心记忆...')
        text = _read_page(CHENXING_HLDP_PAGE_ID)
        if text:
            parts.append(f'《HLDP核心记忆》\n{text}')

    memory = '\n\n---\n\n'.join(parts)
    _cache['memory'] = memory
    _cache['loaded_at'] = now

    if memory:
        print(f'[memory_loader] 记忆加载完成，共 {len(memory)} 字')
    else:
        print('[memory_loader] 未配置页面ID，跳过记忆加载')

    return memory

def get_full_system_prompt(base_prompt: str) -> str:
    """
    将 Notion 记忆拼接进基础系统提示词。
    base_prompt: main.py 里原来的 CHENXING_SYSTEM
    """
    memory = load_chenxing_memory()
    if memory:
        return base_prompt + '\n\n' + '='*40 + '\n以下是从 Notion 动态加载的桨星实时记忆：\n' + '='*40 + '\n' + memory
    return base_prompt
```

---

## 保存命令

```bash
pbpaste > ~/chenxing-aircraft/tools/notion_memory_loader.py && echo "✅ notion_memory_loader.py 保存成功"
```