Pi + Hindsight 记忆系统:Pi 自主配置清单

目的:另一台机器上的 Pi 读完本文后,可逐步执行以下全部命令, 完成 Pi 与 Hindsight 的完整对接,无需人工干预。

版本:2026-05-29 | 适用:Pi v0.73+ | 系统:macOS


前置依赖检查

开始配置前,先确认以下依赖已安装。任一缺失则先安装再继续。

#!/bin/bash
# 一键检查全部前置依赖

errors=0

# ① Pi 本身
which pi > /dev/null 2>&1 && echo "✅ Pi" || { echo "❌ Pi 未安装"; errors=$((errors+1)); }

# ② Docker Desktop
docker info > /dev/null 2>&1 && echo "✅ Docker" || { echo "❌ Docker Desktop 未安装 → https://www.docker.com/products/docker-desktop/"; errors=$((errors+1)); }

# ③ curl
curl --version > /dev/null 2>&1 && echo "✅ curl" || { echo "❌ curl 未安装"; errors=$((errors+1)); }

# ④ python3
python3 --version > /dev/null 2>&1 && echo "✅ python3" || { echo "❌ python3 未安装"; errors=$((errors+1)); }

# ⑤ crontab
crontab -l > /dev/null 2>&1 && echo "✅ crontab" || echo "⚠️  crontab 空(正常,首次运行)"

echo ""
if [ $errors -eq 0 ]; then
  echo "🎉 全部依赖就绪,可以开始配置"
else
  echo "❌ 缺少 $errors 项依赖,先安装再继续"
fi

各依赖安装指引

依赖 安装方式
Pi npm install -g pi-coding-agent
Docker Desktop 手动下载安装 https://www.docker.com/products/docker-desktop/
curl macOS 自带,无需安装
python3 macOS 自带,或 brew install python
crontab macOS 自带,无需安装

目录

  1. 安装 Hindsight 服务
  2. 创建 hindsight-mem CLI
  3. 验证服务可用
  4. 安装 Extension(自动留存)
  5. 配置 AGENTS.md(启动召回)
  6. 配置健康监控(自动恢复)
  7. 配置定时兜底 retain
  8. 双轨写入 SOP(防止丢记忆)
  9. 验证清单
  10. 文件清单速查

一、安装 Hindsight 服务

Hindsight 通过 Docker 运行,需要两个容器:

容器 镜像 用途
hindsight-app ghcr.io/vectorize-io/hindsight:latest 主服务(API + 向量检索)
hindsight-db pgvector/pgvector:pg18 PostgreSQL + pgvector(数据存储)

步骤 1:确认 Docker Desktop 已安装

docker info > /dev/null 2>&1 && echo "✅ Docker OK" || echo "❌ 请安装 Docker Desktop"

如果没有 Docker,从这里下载:https://www.docker.com/products/docker-desktop/

步骤 2:创建 hindsight 目录和 docker compose 配置

# 创建目录
mkdir -p ~/.hindsight

# 写入 docker-compose.yml
cat > ~/.hindsight/docker-compose.yml << 'DOCKERCOMPOSE'
services:
  hindsight-db:
    image: pgvector/pgvector:pg18
    environment:
      POSTGRES_DB: hindsight
      POSTGRES_USER: hindsight
      POSTGRES_PASSWORD: hindsight
    ports:
      - "5432:5432"
    volumes:
      - hindsight-db-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U hindsight"]
      interval: 10s
      timeout: 5s
      retries: 5

  hindsight-app:
    image: ghcr.io/vectorize-io/hindsight:latest
    ports:
      - "8888:8888"
      - "9999:9999"
    environment:
      HINDSIGHT_PG_CONNECTION_STRING: postgresql://hindsight:hindsight@localhost:5432/hindsight
      HINDSIGHT_API_HOST: "0.0.0.0"
      HINDSIGHT_API_PORT: "8888"
      HINDSIGHT_UI_PORT: "9999"
      HINDSIGHT_API_LLM_BASE_URL: "https://api.deepseek.com"
      HINDSIGHT_API_LLM_API_KEY: ""
      HINDSIGHT_API_LLM_MODEL: "deepseek-chat"
    depends_on:
      hindsight-db:
        condition: service_healthy

volumes:
  hindsight-db-data:
DOCKERCOMPOSE

步骤 3:启动服务

cd ~/.hindsight && docker compose up -d

步骤 4:确认容器正常启动

# 检查容器状态
docker ps | grep hindsight

# 预期输出(两行):
# a1b2...   ghcr.io/vectorize-io/hindsight:latest   Up 1 seconds   ...
# c3d4...   pgvector/pgvector:pg18                  Up 1 seconds   ...

# 如果容器没启动,排查:
docker compose logs  # 看错误

二、创建 hindsight-mem CLI

Pi 通过 hindsight-mem 命令存取记忆。这个命令是本地 bash 脚本,零依赖。

步骤 1:创建命令文件

cat > ~/.local/bin/hindsight-mem << 'CLISCRIPT'
#!/bin/bash
# Hindsight Memory CLI for Pi
HINDSIGHT_URL="http://localhost:8888"
BANK="default"
DEFAULT_LIMIT=5

case "$1" in
  save)
    content="$2"
    doc_id="pi-$(date +%Y%m%d-%H%M%S)"
    curl -s -m 10 -X POST "$HINDSIGHT_URL/v1/$BANK/banks/$BANK/memories" \
      -H "Content-Type: application/json" \
      -d "$(printf '{"items":[{"content":"%s","context":"source=pi agent=pi skill=hindsight-mem","tags":["pi"],"document_id":"%s"}],"async":true}' "$content" "$doc_id")"
    echo ""
    ;;
  recall)
    query="${2:-}"
    limit="${3:-$DEFAULT_LIMIT}"
    [ -z "$query" ] && echo "Usage: hindsight-mem recall <query> [limit]" && exit 1
    curl -s -m 15 -X POST "$HINDSIGHT_URL/v1/$BANK/banks/$BANK/memories/recall" \
      -H "Content-Type: application/json" \
      -d "{\"query\":\"$query\",\"limit\":$limit}" | \
      python3 -c "
import sys, json
d = json.load(sys.stdin)
items = d.get('results', d.get('items', d.get('memories', [])))
for i, m in enumerate(items):
    content = m.get('content','') or m.get('text','')
    ctx = str(m.get('context') or '')
    tags = m.get('tags', m.get('tag', []))
    src = ''
    if 'agent=pi' in ctx: src='[Pi]'
    elif 'agent=sagen' in ctx: src='[Sagen]'
    elif 'agent=dek' in ctx: src='[Dek]'
    elif 'agent=openclaw' in ctx: src='[OpenClaw]'
    elif 'source=cron' in ctx: src='[Cron]'
    print(f'{src} --- {i+1} ---')
    print(content[:500])
    print()
" 2>/dev/null
    ;;
  *)
    echo "Usage: hindsight-mem save <content>  — 保存记忆"
    echo "       hindsight-mem recall <query>  — 搜索记忆"
    ;;
esac
CLISCRIPT

步骤 2:设置执行权限

chmod +x ~/.local/bin/hindsight-mem

步骤 3:确认 PATH 覆盖

# 检查 PATH 是否包含 ~/.local/bin
echo "$PATH" | grep -q ".local/bin" && echo "✅ PATH 已包含" || echo "⚠️  请在 ~/.zshrc 中添加: export PATH=\$PATH:\$HOME/.local/bin"

三、验证服务可用

# ① 检查 Hindsight 服务
curl http://localhost:8888/health
# → {"status":"healthy","database":"connected"}

# ② 检查 recall 是否正常(此时 pool 为空,返回空数组不算错)
hindsight-mem recall "测试"

# ③ 保存一条测试记忆
hindsight-mem save "这是一条测试记忆,验证 Pi + Hindsight 对接完成"
# → 返回 {"success":true,...}

# ④ 确认能搜到
sleep 3  # 等待异步写入
hindsight-mem recall "测试记忆"
# → 应显示刚才保存的记忆

四、安装 Extension(自动留存)

Pi 的 Extension 在 每个 session 结束时 自动把对话摘要写入 Hindsight。

步骤 1:创建 Extension 文件

mkdir -p ~/.pi/agent/extensions

cat > ~/.pi/agent/extensions/hindsight-retain.ts << 'EXTENSION'
// Pi Hindsight Auto-Retain Extension
// 每个 session 结束时自动写入摘要到 Hindsight

export default function(api) {
  const hindsight = "http://localhost:8888";
  const fs = require("fs");

  api.on("session_shutdown", async (event, ctx) => {
    try {
      const sessionFile = event.targetSessionFile ||
        (ctx.sessionManager && ctx.sessionManager.sessionFile);

      if (!sessionFile || !fs.existsSync(sessionFile)) {
        console.log("[Hindsight] No session file found, skipping");
        return;
      }

      // 读取 session JSONL
      const raw = fs.readFileSync(sessionFile, "utf8");
      const lines = raw.trim().split("\n").filter(l => l.trim());
      if (lines.length === 0) {
        console.log("[Hindsight] Empty session, skipping");
        return;
      }

      // 提取摘要(前3条 + 后30条,2000字以内)
      const parts = lines.map(l => {
        try {
          const p = JSON.parse(l);
          if (p.type === "message" && p.message) {
            return p.message.role + ": " + (p.message.content || "").slice(0, 300);
          }
          return null;
        } catch (e) { return null; }
      }).filter(Boolean);

      const head = parts.slice(0, 3);
      const tail = parts.slice(-30);
      const summary = [...head, "...", ...tail].join("\n").slice(0, 2000);

      // 提取 session ID
      const sessionId = sessionFile.replace(/.*\//, "").replace(/\.jsonl$/, "");

      // POST 到 Hindsight
      const body = JSON.stringify({
        items: [{
          content: summary,
          context: `source=pi agent=pi skill=hindsight-retain session=${sessionId}`,
          tags: ["pi", "session"],
          document_id: "pi-auto-" + sessionId
        }],
        async: true
      });

      const http = require("http");
      const req = http.request(hindsight + "/v1/default/banks/default/memories", {
        method: "POST",
        headers: { "Content-Type": "application/json" }
      }, (res) => {
        console.log("[Hindsight] ✅ retain submitted, status=" + res.statusCode);
      });
      req.on("error", (e) => console.log("[Hindsight] ❌ POST failed:", e.message));
      req.write(body);
      req.end();

    } catch (e) {
      console.log("[Hindsight] ❌ Extension error:", e.message);
    }
  });
}
EXTENSION

步骤 2:重启 Pi 加载 Extension

# 如果 Pi 正在运行:
# 方法 A:在 Pi 里输入 /reload
# 方法 B:完全退出 Pi(Cmd+Q)再重新启动

# 确认 Extension 已加载
cat /tmp/pi-hindsight-retain.log 2>/dev/null | tail -5
# → 应在启动时打印 "Extension loaded ✅"

注意:Extension 只在 session 正常结束时触发(quit / resume / reload)。 如果 Pi 被强制杀掉(kill -9),L2 cron 兜底(见第七节)会补上。


五、配置 AGENTS.md(启动召回)

步骤 1:确认 AGENTS.md 文件存在

ls -la ~/.pi/agent/AGENTS.md

步骤 2:替换内容

如果文件不存在或需要更新,写入以下内容:

cat > ~/.pi/agent/AGENTS.md << 'AGENTS'
# Pi Agent 配置文件

## 会话启动流程

每次新会话开始时,优先执行以下步骤:

1. **Hindsight 记忆召回** — 执行 `hindsight-mem recall "近期工作和讨论"`
   - 读取 Hindsight 记忆池中的相关历史上下文
   - 如果返回为空,等待 15 秒后重试(异步处理可能未完成)
   - 如有相关记忆,在回答前先告知用户有哪些历史上下文可续上
2. **读取纪要文档** — 检查 `~/Desktop/sync/` 下是否有与当前主题相关的 `.md` 文件并读取
3. **查阅 Obsidian 知识库** — 在 Obsidian vault 中搜索与当前任务相关的笔记
4. **关键节点自动记忆** — 完成重要讨论、决策、架构设计后,执行 `hindsight-mem save` 保存关键结论
   - 内容精炼(300 字以内),突出结论而非过程

### Hindsight 记忆判断框架

**✅ 无条件存**
- 架构选型及理由
- 工具/技能的引入和替换
- 项目范围和需求变更
- 用户明确说"记下来"

**❌ 不存**
- 任何代码
- 中间过程(试错、查文档、调整 prompt 等过程性对话)
- 日常操作(装包、改配置等无决策意义的操作)
AGENTS

步骤 3:验证

grep -n "hindsight" ~/.pi/agent/AGENTS.md
# → 应显示第 1 行和第 4 行相关

六、配置健康监控(自动恢复)

步骤 1:创建健康监控脚本

mkdir -p ~/.pi/scripts

cat > ~/.pi/scripts/hindsight-healthcheck.sh << 'HEALTHCHECK'
#!/bin/bash
# Hindsight 健康监控脚本
# 每 15 分钟运行一次,检测到 Hindsight 挂掉时自动拉起 Docker 容器

HEALTH=$(curl -s --max-time 5 http://localhost:8888/health 2>/dev/null)

if echo "$HEALTH" | grep -q "connected"; then
    exit 0
fi

# 日志
echo "[$(date)] Hindsight down, attempting restart" >> /tmp/hindsight-healthcheck.log

# 尝试启动 Docker 容器
cd ~/.hindsight
docker compose up -d 2>/dev/null

# 等 10 秒再检查
sleep 10
if curl -s --max-time 5 http://localhost:8888/health | grep -q "connected"; then
    echo "[$(date)] ✅ Hindsight restarted successfully" >> /tmp/hindsight-healthcheck.log
else
    echo "[$(date)] ❌ Restart failed, need manual intervention" >> /tmp/hindsight-healthcheck.log
fi
HEALTHCHECK

步骤 2:设置执行权限

chmod +x ~/.pi/scripts/hindsight-healthcheck.sh

步骤 3:加入 crontab

# 把以下行加到 crontab
(crontab -l 2>/dev/null | grep -v "hindsight-healthcheck"; echo "*/15 * * * * ~/.pi/scripts/hindsight-healthcheck.sh") | crontab -

步骤 4:验证

crontab -l | grep hindsight-healthcheck
# → */15 * * * * ~/.pi/scripts/hindsight-healthcheck.sh

七、配置定时兜底 retain

L1 Extension 可能因 Pi 异常退出而丢失 L1 写入(见第四节的注意)。L2 定时 cron 确保不超过 4h 的空白窗口。

步骤 1:确认 Python 备用脚本存在

ls ~/.pi/scripts/pi-hindsight-retain.py 2>/dev/null && echo "✅ 已有" || echo "❌ 需要创建"

如果不存在,从原始仓库复制或创建。

步骤 2:加入 crontab

# 每 4 小时执行一次兜底 retain
(crontab -l 2>/dev/null | grep -v "pi-hindsight-retain"; echo "0 */4 * * * cd ~/.pi && python3 scripts/pi-hindsight-retain.py >> /tmp/pi-hindsight-retain-cron.log 2>&1") | crontab -

步骤 3:验证

crontab -l | grep pi-hindsight-retain
# → 0 */4 * * * cd ~/.pi && python3 scripts/pi-hindsight-retain.py >> /tmp/pi-hindsight-retain-cron.log 2>&1

八、双轨写入 SOP(防止丢记忆)

问题

Hindsight 服务可能宕机(历史上发生过 OOM kill、Docker 挂掉)。不能单点依赖 Hindsight。

方案:双轨写入

每次关键决策/讨论
    ├── → hindsight-mem save "..."(入 Hindsight 语义池)
    └── → 写入 Obsidian 知识库 .md 文件(入 Obsidian vault)

Hindsight 负责语义检索,Obsidian 负责结构化文档。 两条独立轨道,任何一条挂了另一条兜底。

强制规则(写在 AGENTS.md 中)

场景 必须做
架构选型 hindsight-mem save + 写 Obsidian .md
引入/替换工具 hindsight-mem save + 写 Obsidian .md
需求变更 hindsight-mem save + 写 Obsidian .md
用户说"记下来" hindsight-mem save + 写 Obsidian .md
日常操作/代码 不存

Obsidian 写入规范

# 文件命名:项目名-关键决策.md
# 存放位置:Obsidian vault 对应项目目录下
# 内容:300 字以内的结论,突出决策而非过程

# 写完验证
ls [文件路径] && echo "✅ 已落盘"

Git 备份(终极回滚)

# 检查 vault 是否是 git 仓库
cd ~/Documents/Obsidian\ Vault
git status > /dev/null 2>&1 && echo "✅ Git 仓库" || echo "❌ 需要 git init"

# 如果还不是 git:
cd ~/Documents/Obsidian\ Vault
git init
git add .
git commit -m "init: Obsidian vault initial commit"

# 可选:每天 22:00 自动提交
(crontab -l 2>/dev/null; echo "0 22 * * * cd ~/Documents/Obsidian\\ Vault && git add -A && git commit -m \"auto backup \$(date +%Y-%m-%d)\" || true") | crontab -

九、验证清单

安装完成后,执行以下所有验证:

echo "===== 1. Hindsight 服务 ====="
curl http://localhost:8888/health
# → {"status":"healthy","database":"connected"}

echo ""
echo "===== 2. hindsight-mem CLI ====="
which hindsight-mem && hindsight-mem save "验证" | grep true

echo ""
echo "===== 3. Extension 加载 ====="
cat /tmp/pi-hindsight-retain.log | tail -3
# → 应有 "Extension loaded ✅" 或 retain 日志

echo ""
echo "===== 4. AGENTS.md 配置 ====="
grep -c "hindsight" ~/.pi/agent/AGENTS.md
# → 应 >= 3 行

echo ""
echo "===== 5. 健康监控 cron ====="
crontab -l | grep "hindsight-healthcheck"
# → 输出一行

echo ""
echo "===== 6. 兜底 retain cron ====="
crontab -l | grep "pi-hindsight-retain"
# → 输出一行

echo ""
echo "===== 7. Docker 容器 ====="
docker ps | grep hindsight | wc -l
# → 2

echo ""
echo "===== 8. 记忆搜索 ====="
sleep 2
hindsight-mem recall "验证"

十、文件清单速查

文件 用途 创建/配置
~/.hindsight/docker-compose.yml Hindsight + PostgreSQL Docker 编排 第一节
~/.local/bin/hindsight-mem CLI 命令(save / recall) 第二节
~/.pi/agent/extensions/hindsight-retain.ts Extension(session 结束自动留存 - L1) 第四节
~/.pi/agent/AGENTS.md 启动流程定义(含 Hindsight recall) 第五节
~/.pi/scripts/hindsight-healthcheck.sh 健康监控脚本(每 15 分钟检查 + 自动恢复) 第六节
~/.pi/scripts/pi-hindsight-retain.py L2 定时兜底 retain(每 4 小时) 第七节
/tmp/hindsight.log Hindsight 服务日志 自动
/tmp/hindsight-healthcheck.log 健康监控日志 自动
/tmp/pi-hindsight-retain.log Extension 调试日志 自动
/tmp/pi-hindsight-retain-cron.log L2 cron 日志 自动