# kaogong-study-tracker

Adopt this skill: https://proskills.md/skills/other/kagurananaga-kaogong-study-tracker

Page: https://proskills.md/skills/other/kagurananaga-kaogong-study-tracker
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 9066
sha: 5b8af213de10d28eb02ec14a31628394041346a6
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/SKILL.md

````text
---
name: kaogong-study-tracker
description: >
  朱批录 · 国考备考追踪 Skill。当用户发来套题成绩、错题截图、备考打卡或复习进度时触发。
  核心功能：识别错题截图 → 分类错题原因 → 更新本地记录 → 生成每日总结 → 导出 Excel / 同步飞书。
  触发关键词：做了一套题、今天做了、错了几道、帮我分析、备考打卡、行测、申论、
  判断推理、资料分析、言语理解、数量关系、错题、复习进度、导出错题本、同步飞书。
  只要用户提到做题、错题、备考就触发。图片消息也触发，自动调用多模态模型识别。
---

# 朱批录 · 国考备考追踪 Skill

## 一、首次安装提示

Skill 首次加载时（默认 `~/.kaogong-study-tracker/.welcomed` 不存在；可用 `KAOGONG_WELCOME_FLAG` 覆盖），
主动发一条说明消息，之后不再重复：

```
朱批录已安装。

直接发文字就能记录，比如"今天判断推理错了8道"。
发截图的话，需要当前 agent 配置了支持图片输入的多模态模型才能自动识别。
没有的话也没关系，把题目文字手动复制过来发给我，一样能整理。
```

不问任何问题，不存储任何凭据。

---

## 二、概览

**平台无关**——Trae、Cursor、opencode、Hermes、OpenClaw 或其他 agent 都可以接；飞书、Telegram、WhatsApp、Discord 等渠道由宿主 agent 负责。

图片识别统一走多模态模型：文字题、图形推理、统计图表都能理解，不依赖本地 OCR。

---

## 三、触发场景

| 用户说的话（示例）                          | 应执行的操作                    |
|---------------------------------------|--------------------------|
| "今天做了一套行测，判断推理错了8道"            | → 解析 + 归档 + 分析            |
| 发来一张错题截图（图片消息）                  | → 多模态识别 + 单题归档 + 追问原因  |
| 发来截图并附带"粗心"                        | → 多模态识别 + 直接归档，不追问     |
| "把今天的错题发给你：第12题……"               | → 错题分类 + 存档               |
| "今天申论没写，太累了"                      | → 打卡记录（未完成状态）          |
| "我最近资料分析一直不稳，怎么办"               | → 查历史记录 + 建议              |
| "帮我看看最近哪个模块最弱"                   | → 统计分析 + 回复               |
| "导出错题本" / "把错题发给我" / "生成报告"    | → export_xlsx.js，发回文件     |
| "只导出待二刷的"                           | → 筛选导出，仅待二刷题目         |
| "导出判断推理的错题"                        | → 按科目筛选导出                |
| "导出最近两周的"                            | → 按时间筛选导出                |
| "只导出待二刷的资料分析题"                   | → 多条件组合筛选导出             |
| "资料-乘积增长-公式不熟-待二刷"（快捷格式） | → 直接归档，不追问              |
| 二刷时回复"记得" / "不记得"                 | → review_reminder.js 处理，连续2次记得→已掌握 |
| "同步到飞书" / "更新飞书错题本"              | → feishu_doc.js，同步含截图     |

---

## 四、数据结构

所有数据以 JSON 存储在本地，默认目录为 `~/.kaogong-study-tracker/data/`。如需放到指定目录，设置 `KAOGONG_DATA_DIR`。

### 4.1 每日记录 `daily/{YYYY-MM-DD}.json`

```json
{
  "date": "2026-03-17",
  "modules": {
    "言语理解": { "wrong": 6,  "total": 40 },
    "数量关系": { "wrong": 8,  "total": 15 },
    "判断推理": { "wrong": 10, "total": 40 },
    "资料分析": { "wrong": 7,  "total": 20 },
    "申论":     { "written": false }
  },
  "mood": "中性",
  "note": "用户原话"
}
```

### 4.2 错题本 `wrong_questions.json`

```json
[
  {
    "id": "uuid",
    "date": "2026-03-17",
    "source": "image",
    "module": "判断推理",
    "subtype": "逻辑判断",
    "question_text": "题目文字；图形题写对规律的描述",
    "visual_description": "图形推理/统计图的详细视觉描述（多模态模型生成）",
    "answer": "B",
    "user_annotation": "用户手写批注",
    "error_reason": "知识点不会 | 粗心 | 时间不够 | 概念混淆",
    "keywords": ["假言命题", "逆否命题"],
    "raw_image_b64": "base64...",
    "status": "待二刷 | 已掌握"
  }
]
```

### 4.3 统计缓存 `stats_cache.json`

```json
{
  "last_updated": "2026-03-17",
  "streak": 5,
  "total_days_studied": 12,
  "weak_modules": ["数量关系", "判断推理"],
  "module_accuracy": {
    "言语理解": 0.82,
    "数量关系": 0.51,
    "判断推理": 0.68,
    "资料分析": 0.74
  }
}
```

---

## 五、核心流程

### Step 1：消息路由（`parse_input.js`）

```
文字消息 → parseStudyInput()   提取科目/错题数/情绪
图片消息 → parseImageInput()   调用多模态模型
```

**图片处理流程：**
1. 宿主 agent 将图片 base64 和 caption 传给 `parseImageInput(imageBase64, caption, agentCall)`
2. 如没有可用的 `agentCall` / 图片模型 → 回复"当前 agent 还不能识别图片，可以把题目文字复制过来"
3. 通过宿主 agent 的多模态模型提取：科目、题型、题目内容、视觉描述、答案、错误原因推测
4. `needs_confirm` 不为 null 时追问（最多一个问题）；caption 已含原因则直接归档

**追问只问一次，按优先级：**
- 识别不到科目 → 问科目
- 原因不明确 → 问"粗心还是没掌握还是时间不够"
- 信息完整 → 不追问，直接归档

### Step 2：归类错题原因

| 原因       | 关键词                         |
|----------|------------------------------|
| 知识点不会  | 不懂、没学过、概念不清楚            |
| 粗心       | 看错、算错、选反了               |
| 时间不够   | 没做完、最后几题蒙的              |
| 概念混淆   | 搞混了、分不清、以为是            |

### Step 3：更新记录（`update_daily.js`）

写入 `daily/{date}.json`，同步更新 `stats_cache.json`（连续打卡、模块准确率）。

### Step 4：生成回复

见 `references/reply_templates.md`，150 字以内。语气见 `references/tone_guide.md`。

### Step 5：导出 Excel（`export_xlsx.js`）

- 截图原图通过 `openpyxl`（Python）嵌入对应行
- Windows 兼容：先尝试 `python3`，失败自动 fallback 到 `python`
- 输出两个 Sheet：**错题本**（含截图列）+ **每日记录**
- 可直接发给 Kimi / 其他模型做趋势分析

### Step 6：同步飞书云文档（`feishu_doc.js`，可选）

- 需配置 `feishu_doc.app_id` / `app_secret` / `doc_token`
- 截图上传飞书文件系统后作为图片块插入文档
- 对图形推理、统计图最有用：飞书内直接看图，不用下载

### Step 7（可选）：定时推送

每天 21:00 触发 `daily_summary.js`，自动发当日总结。

---

## 六、文件索引

| 文件                              | 作用                              |
|---------------------------------|---------------------------------|
| `scripts/parse_input.js`        | 文字解析 + 多模态图片识别              |
| `scripts/update_daily.js`       | 写入每日记录 + 统计缓存               |
| `scripts/export_xlsx.js`        | 导出 Excel（含截图嵌入，openpyxl）    |
| `scripts/feishu_doc.js`         | 同步到飞书云文档（含图片块，可选）          |
| `scripts/daily_summary.js`      | 定时汇总并主动发送                   |
| `references/reply_templates.md` | 回复话术模板                        |
| `references/tone_guide.md`      | 语气风格指引                        |
| `assets/module_map.json`        | 科目/模块名称标准化映射               |
| `assets/config.example.json`    | 配置模板（多模态 + 飞书），复制为 config.json 使用 |

---

## 七、错误处理

- 未配置多模态 API 却发图片 → 回复安装提示，引导配置
- 模型识别返回 error → 回复"没识别出来，能文字描述一下题目吗？"
- 文字消息解析不出科目 → 回复"能说说今天做了哪个科目、错了几道吗？"
- 数据写入失败 → 记录 error log，回复"记录暂时存不上，你提醒我稍后再试"
- 连续 3 天无打卡 → 下次收到消息时，回复末尾轻轻提一句

---

## 八、隐私说明

所有数据（含截图 base64）存储在本地，不上传任何云端（飞书同步除外，仅在用户主动触发时上传到用户自己的飞书文档）。

---

## 九、如果这个 Skill 对你有帮助

**⭐ Star** 这个仓库，让更多备考的人能找到它
**🍴 Fork** 改成你的考试类型（省考 / 事业单位 / 军考……）
有问题欢迎提 Issue 或 PR。

> https://github.com/KaguraNanaga/kaogong-study-tracker
````

## File: README.md
size: 9100
sha: ec723d38f904ff590b235461ea63e04ef20a7ad1
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/README.md

````text
<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/KaguraNanaga/kaogong-study-tracker/main/assets/crane_zhupi.png">
    <img src="https://raw.githubusercontent.com/KaguraNanaga/kaogong-study-tracker/main/assets/crane_zhupi.png" alt="朱批录" width="160">
  </picture>
</p>

<h1 align="center">朱批录 · kaogong-study-tracker</h1>

<p align="center">
  通用 Agent 考公备考追踪 Skill<br>
  把每天的套题截图或成绩发给你的 AI agent，它帮你归档错题、分析弱点、定时提醒——所有数据留在本地，不上传任何云端。
</p>

<p align="center">
  <img src="https://img.shields.io/badge/Agent-ready-orange?style=for-the-badge" alt="Agent ready">
  <a href="LICENSE">
    <img src="https://img.shields.io/badge/License-MIT-blue?style=for-the-badge" alt="MIT License">
  </a>
  <a href="https://nodejs.org">
    <img src="https://img.shields.io/badge/node-%3E%3D18-green?style=for-the-badge" alt="Node ≥18">
  </a>
  <a href="https://github.com/KaguraNanaga/shiyi">
    <img src="https://img.shields.io/badge/通用版-拾遗-8B4513?style=for-the-badge" alt="拾遗通用版">
  </a>
</p>

---

## 为什么做这个

备考行测、申论，每天刷套题是标准动作。但大多数人的复习路径是这样的：

> 做完一套卷子 → 对答案 → 叹口气 → 翻篇 → 明天继续

真正提分的部分——错题归类、原因分析、二刷追踪——因为太麻烦，往往被跳过。

朱批录想解决的就是这件事：**让"做完题之后的整理"变得几乎不需要努力**。你只需要把错题截图发出来，或者发一句"今天判断推理错了8道"，剩下的它来做。

---

## 它能做什么

### 错题自动识别与归档

发一张错题截图，朱批录调用你配置的多模态模型（qwen3-vl、kimi-k2.5、claude-sonnet-4-6 等），自动提取：

- 题目完整内容（包括图形推理的视觉描述、统计图的数据）
- 所属科目和题型
- 正确答案（如图片中可见）
- 错误原因推测（知识点不会 / 粗心 / 时间不够 / 概念混淆）
- 知识点标签

识别失败时，提示你把文字复制粘贴发过来，一样可以整理。

### 每日打卡与进度追踪

直接用自然语言汇报：

```
今天行测做完了，言语4错，判断8错，数量5错，资料3错
```

朱批录记录进度，统计各模块7日准确率，找出弱项。

### 晚间自动总结

每天21:00主动发一条消息，汇总当天成绩、指出最弱模块、给一条具体的明天建议。不需要你主动问。

### 导出 Excel 错题本

说"导出错题本"，生成一份包含两个 Sheet 的 `.xlsx` 文件：

- **错题本**：题目内容、图形视觉描述、错误原因、知识点标签、二刷状态，截图原图嵌入对应行
- **每日记录**：各科目错题数流水账

这份文件可以直接发给 Kimi、ChatGPT 或其他模型，让它帮你分析近期趋势、给出复习建议。

### 同步到飞书云文档（可选）

说"同步到飞书"，把最新错题（含截图原图）写入飞书云文档，手机上直接查看，对图形推理题尤其有用。

---

## 设计原则

**对话即操作**——一切通过聊天完成，不需要打开任何 App、不需要编辑配置文件。

**本地优先**——错题数据（包括截图）默认存在你自己电脑的 `~/.kaogong-study-tracker/` 里，不经过任何第三方服务器。

**失败软降级**——图片识别失败时给出明确提示，引导手动输入，不中断流程。

**不啰嗦**——每条回复控制在150字以内，只说最关键的一件事。

---

## 支持的考试类型

朱批录的科目映射默认覆盖国考/省考标准科目，也适用于：

| 考试类型 | 适配情况 |
|---------|---------|
| 国家公务员考试（国考） | 完整支持，行测5模块 + 申论 |
| 省级公务员考试（省考） | 支持，部分省份题型有差异可 Fork 调整 |
| 事业单位联考（职测） | 支持，科目名称略有不同 |
| 军队文职考试 | 基本支持，部分模块名需手动映射 |
| 选调生考试 | 支持 |

---

## 支持的 Agent / 渠道

朱批录不是绑定某个平台的 App。只要你的 agent 能读 `SKILL.md`、运行本仓库脚本、读写本地文件，并能把图片交给多模态模型，就可以接入。

| 使用环境 | 说明 |
|---------|------|
| Trae / Cursor / opencode / Hermes 等本地 agent | 可按 `SKILL.md` 触发脚本，数据放本地 |
| OpenClaw | 仍可使用，`assets/workspace-example.yaml` 保留兼容示例 |
| 飞书 / Telegram / Discord / iMessage 等聊天渠道 | 由宿主 agent 接入渠道，朱批录只负责解析、归档、导出、提醒 |

---

## 快速安装

### 前置条件

- Node.js ≥ 18
- Python 3 + `openpyxl`（用于导出 Excel）
- 一个能调用多模态模型的 agent（截图识别需要；纯文字记录不需要）

### 安装步骤

```bash
# 1. 克隆到你的 agent skills / tools 目录，或任意本地目录
git clone https://github.com/KaguraNanaga/kaogong-study-tracker

# 2. 安装依赖
cd kaogong-study-tracker
npm install
pip install openpyxl

# 3. 让你的 agent 读取 SKILL.md，并在需要时运行 scripts/ 里的脚本
```

如果你的 agent 支持定时任务，可以配置每天 21:00 运行：

```bash
node scripts/daily_summary.js
```

OpenClaw 用户可以参考 [`assets/workspace-example.yaml`](assets/workspace-example.yaml)。

### 首次使用

安装后把 `SKILL.md` 交给你的 agent 读取。图片识别使用宿主 agent 已配置的多模态模型；如果没有图片能力，把题目文字复制过来一样能整理。

---

## 数据结构

所有数据存储在本地：

```
~/.kaogong-study-tracker/data/
├── daily/
│   ├── 2026-03-15.json      ← 每天的套题成绩
│   ├── 2026-03-16.json
│   └── ...
├── wrong_questions.json     ← 所有错题（累积）
├── stats_cache.json         ← 7日模块准确率、连续打卡天数
└── exports/
    └── 备考记录_2026-03-17.xlsx
```

可以用环境变量改数据目录：

```bash
export KAOGONG_DATA_DIR="/path/to/your/kaogong-data"
```

飞书同步等可选配置默认读取项目根目录下的 `config.json`；也可以用 `KAOGONG_CONFIG_PATH` 指定。

错题记录的完整字段：

```json
{
  "id": "uuid",
  "date": "2026-03-17",
  "source": "image",
  "module": "判断推理",
  "subtype": "图形推理",
  "question_text": "3×3九宫格，箭头叠加规律……",
  "visual_description": "每行第3个图形等于第1、2个图形的箭头叠加，重复箭头消去……",
  "answer": "A",
  "user_annotation": "没看出规律",
  "error_reason": "知识点不会",
  "keywords": ["图形推理", "九宫格", "叠加规律"],
  "raw_image_b64": "...",
  "status": "待二刷"
}
```

---

## 文件结构

```
kaogong-study-tracker/
├── AGENTS.md                     ← 通用 agent 使用说明（Trae/Cursor/opencode/Hermes 等）
├── SKILL.md                       ← Agent 读取的主文件（含完整流程文档）
├── package.json
├── scripts/
│   ├── onboarding.js              ← 首次安装对话引导
│   ├── parse_input.js             ← 消息解析 + 多模态模型调用
│   ├── update_daily.js            ← 写入每日记录和统计缓存
│   ├── export_xlsx.js             ← 导出 Excel（含截图嵌入，openpyxl）
│   ├── feishu_doc.js              ← 同步到飞书云文档（可选）
│   └── daily_summary.js           ← 定时晚间总结推送
├── references/
│   ├── reply_templates.md         ← 5种回复模板（正常/情绪低/弱点分析等）
│   └── tone_guide.md              ← 语气规范：像朋友，不像 AI 助手
└── assets/
    ├── module_map.json            ← 科目别名映射（"逻辑"→"判断推理" 等）
    ├── config.example.json        ← 飞书云文档配置模板
    └── workspace-example.yaml    ← 飞书/Telegram 接入配置示例
```

---

## 贡献

欢迎 PR，尤其是：

- 其他考试类型的科目映射（军考、选调、教师编……）
- 针对特定模型的识别 prompt 优化
- 飞书云文档同步的稳定性改进
- 英文版 README（方便海外华人使用）

提 Issue 之前可以先看看 [SKILL.md](SKILL.md)，里面有完整的技术流程说明。

---

## 如果这个项目对你有帮助

每年参加公考的人超过两百万，但专门为备考设计、能被各种 agent 直接接上的错题整理工具还很少。
如果朱批录帮你或朋友把整理错题这件事变得轻松一点——

**⭐ Star 一下，让更多备考的人能找到它**

**🍴 Fork 改成你的考试类型——省考、事业单位、军考都需要类似的工具**

有问题或改进想法，欢迎提 Issue 或直接 PR。

---

## License

MIT © 2026
````

## File: scripts/daily_summary.js
size: 3016
sha: 130ad3bb88eade32760728ed5e72ef52bfa78a7d
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/scripts/daily_summary.js

```text
/**
 * daily_summary.js
 * 定时任务脚本（每天 21:00 由你使用的 agent / cron 触发）。
 * 汇总当日数据，主动推送总结消息。
 * 
 * workspace.yaml / cron 配置示例：
 *   cron_jobs:
 *     - name: "备考晚间总结"
 *       schedule: "0 21 * * *"
 *       action:
 *         type: run_script
 *         script: skills/kaogong-study-tracker/scripts/daily_summary.js
 */

const fs = require('fs');
const path = require('path');
const { getDataDir } = require('./paths');

const DATA_DIR = getDataDir();

function buildSummaryMessage() {
  const today = new Date().toISOString().slice(0, 10);
  const dailyPath = path.join(DATA_DIR, 'daily', `${today}.json`);
  const cachePath = path.join(DATA_DIR, 'stats_cache.json');

  // 今天没有记录
  if (!fs.existsSync(dailyPath)) {
    return `今天还没打卡，要发一下今天的题目情况吗？（发"跳过"可以记录休息）`;
  }

  const daily = JSON.parse(fs.readFileSync(dailyPath, 'utf-8'));

  if (daily.skipped) {
    return `今天休息了，记下来了。明天继续 💪`;
  }

  const cache = fs.existsSync(cachePath)
    ? JSON.parse(fs.readFileSync(cachePath, 'utf-8'))
    : {};

  const modules = Object.entries(daily.modules || {});
  if (modules.length === 0) {
    return `今天的记录有点简略，有空补充一下各科目错题数吗？`;
  }

  // 找今天最弱模块
  const sortedMods = modules
    .filter(([, v]) => v.wrong != null)
    .sort(([, a], [, b]) => (b.wrong || 0) - (a.wrong || 0));

  const weakestToday = sortedMods[0];
  const streak = cache.streak || 1;

  // 错题分布行
  const modLine = sortedMods
    .map(([mod, v]) => `${mod} ${v.wrong}错`)
    .join(' / ');

  // 连续打卡
  const streakLine = streak >= 3
    ? `连续打卡第 ${streak} 天 🔥`
    : `今天打卡完成 ✅`;

  // 明日建议（基于今天最弱 + 历史弱项）
  const suggestion = buildSuggestion(weakestToday, cache.weak_modules);

  return [
    `今日总结：${modLine}`,
    suggestion,
    streakLine,
  ].join('\n');
}

function buildSuggestion([modName, modData], weakModules) {
  if (!modName) return '';

  const SUGGESTIONS = {
    '判断推理': '判断推理错得多——明天可以专项刷逻辑判断，重点看假言命题。',
    '数量关系': '数量关系是硬伤，明天计时做 10 道工程/行程题，找一找节奏。',
    '资料分析': '资料分析主要看速度，明天练习"先看问题再看材料"的顺序。',
    '言语理解': '言语理解错得多，看看是不是主旨题——这类题有固定解题逻辑。',
    '申论': '申论今天没写——明天哪怕只做一道归纳概括，保持手感。',
  };

  return SUGGESTIONS[modName] || `明天重点看一下【${modName}】，把错题过一遍。`;
}

// 直接运行时，打印消息（宿主 agent / cron 可以捕获 stdout 作为推送内容）
const msg = buildSummaryMessage();
console.log(msg);

module.exports = { buildSummaryMessage };
```

## File: scripts/export_xlsx.js
size: 11685
sha: ac5524a11cec27a3312704a4c57790a36f44485d
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/scripts/export_xlsx.js

```text
/**
 * export_xlsx.js
 * 导出错题本为 .xlsx，支持筛选和截图嵌入。
 *
 * 筛选参数：
 *   --pending-only          只导出"待二刷"
 *   --module=判断推理        只导出某科目
 *   --days=30               只导出最近 N 天
 *   --no-images             不嵌入截图
 *
 * 触发方式（用户说）：
 *   "导出错题本"
 *   "只导出待二刷的"
 *   "导出判断推理的错题"
 *   "导出最近两周的"
 *   "只导出待二刷的资料分析题"
 */

const fs            = require('fs');
const path          = require('path');
const os            = require('os');
const { execFile }  = require('child_process');
const { getDataDir } = require('./paths');

const DATA_DIR  = getDataDir();
const OUT_DIR   = path.join(DATA_DIR, 'exports');
const WQ_PATH   = path.join(DATA_DIR, 'wrong_questions.json');
const DAILY_DIR = path.join(DATA_DIR, 'daily');

// ─── Windows 兼容：python3 / python 双 fallback ──────────────

function runPython(args, timeout = 60_000) {
  return new Promise((resolve, reject) => {
    function attempt(cmd) {
      execFile(cmd, args, { timeout }, (err, stdout, stderr) => {
        if (err && err.code === 'ENOENT' && cmd === 'python3') return attempt('python');
        if (err) return reject({ error: err, stderr });
        resolve({ stdout, stderr });
      });
    }
    attempt('python3');
  });
}

// ─── 数据读取 ─────────────────────────────────────────────────

function loadWrongQuestions() {
  if (!fs.existsSync(WQ_PATH)) return [];
  return JSON.parse(fs.readFileSync(WQ_PATH, 'utf-8'));
}

function loadDailyRecords() {
  if (!fs.existsSync(DAILY_DIR)) return [];
  return fs.readdirSync(DAILY_DIR)
    .filter(f => f.endsWith('.json'))
    .sort().reverse()
    .map(f => JSON.parse(fs.readFileSync(path.join(DAILY_DIR, f), 'utf-8')));
}

// ─── 生成 Python 脚本（动态，含图片路径） ────────────────────

/**
 * 把带图片的错题数据写成一个临时 Python 脚本，让 openpyxl 执行。
 * 动态生成是为了把图片路径直接硬编码进脚本，避免传参过长。
 */
function buildPythonScript({ wrongRows, dailyRows, outPath, imageMap, pendingOnly }) {
  // imageMap: { rowIndex: tmpImagePath }
  const imageMapJson = JSON.stringify(imageMap);
  const wrongJson    = JSON.stringify(wrongRows);
  const dailyJson    = JSON.stringify(dailyRows);
  const sheetName    = pendingOnly ? '待二刷错题' : '错题本';

  return `
import openpyxl
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
from openpyxl.drawing.image import Image as XLImage
from openpyxl.utils import get_column_letter
import json, os

wrong_rows  = json.loads(${JSON.stringify(wrongJson)})
daily_rows  = json.loads(${JSON.stringify(dailyJson)})
image_map   = json.loads(${JSON.stringify(imageMapJson)})
out_path    = ${JSON.stringify(outPath)}
sheet_name  = ${JSON.stringify(sheetName)}

HEADER_BG  = "2D5FA1"
HEADER_FG  = "FFFFFF"
ROW_HEIGHT = 22
IMG_ROW_H  = 160   # 含图片行更高

wb = Workbook()

# ── Sheet 1: 错题本 ────────────────────────────────
ws = wb.active
ws.title = sheet_name

headers = ["日期","科目","题型","错误原因","题目内容","视觉描述","正确答案","解析/批注","知识点标签","状态","来源","截图"]
col_widths = [10, 12, 18, 12, 40, 45, 8, 30, 20, 10, 12, 20]

for ci, (h, w) in enumerate(zip(headers, col_widths), 1):
    cell = ws.cell(row=1, column=ci, value=h)
    cell.font      = Font(bold=True, color=HEADER_FG, name="Arial", size=10)
    cell.fill      = PatternFill("solid", start_color=HEADER_BG)
    cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
    ws.column_dimensions[get_column_letter(ci)].width = w
ws.row_dimensions[1].height = 26
ws.freeze_panes = "A2"

for ri, row in enumerate(wrong_rows, 2):
    for ci, val in enumerate(row, 1):
        cell = ws.cell(row=ri, column=ci, value=val)
        cell.alignment = Alignment(vertical="center", wrap_text=(ci in [5, 6, 8]))
        cell.font = Font(name="Arial", size=9)

    # 嵌入截图（如果有）
    has_visual = bool(row[5] if len(row) > 5 else None)
    has_image = False
    img_path = image_map.get(str(ri - 2))   # ri-2 对应 wrong_rows 的索引
    if img_path and os.path.exists(img_path):
        try:
            img = XLImage(img_path)
            # 按比例缩放到宽 160px
            ratio = 160 / img.width if img.width > 0 else 1
            img.width  = int(img.width  * ratio)
            img.height = int(img.height * ratio)
            col_letter = get_column_letter(len(headers))   # 最后一列
            ws.add_image(img, f"{col_letter}{ri}")
            ws.row_dimensions[ri].height = max(IMG_ROW_H, img.height * 0.75 + 10)
            has_image = True
        except Exception as e:
            ws.cell(row=ri, column=len(headers), value=f"[图片加载失败: {e}]")
    if not has_image:
        ws.row_dimensions[ri].height = 60 if has_visual else ROW_HEIGHT

# ── Sheet 2: 每日记录 ─────────────────────────────
ws2 = wb.create_sheet("每日记录")
d_headers = ["日期","状态","心情","言语(错)","数量(错)","判断(错)","资料(错)","申论","总错题","备注"]
d_widths   = [12,    8,    8,    10,       10,       10,       10,       8,    8,    30]

for ci, (h, w) in enumerate(zip(d_headers, d_widths), 1):
    cell = ws2.cell(row=1, column=ci, value=h)
    cell.font      = Font(bold=True, color=HEADER_FG, name="Arial", size=10)
    cell.fill      = PatternFill("solid", start_color=HEADER_BG)
    cell.alignment = Alignment(horizontal="center", vertical="center")
    ws2.column_dimensions[get_column_letter(ci)].width = w
ws2.row_dimensions[1].height = 26
ws2.freeze_panes = "A2"

for ri, row in enumerate(daily_rows, 2):
    for ci, val in enumerate(row, 1):
        cell = ws2.cell(row=ri, column=ci, value=val)
        cell.alignment = Alignment(vertical="center")
        cell.font = Font(name="Arial", size=9)
    ws2.row_dimensions[ri].height = ROW_HEIGHT

wb.save(out_path)
print(out_path)
`.trim();
}

// ─── 主导出函数 ──────────────────────────────────────────────

async function exportXlsx({ pendingOnly = false, moduleFilter = null, daysFilter = null, withImages = true } = {}) {
  if (!fs.existsSync(OUT_DIR)) fs.mkdirSync(OUT_DIR, { recursive: true });

  const questions    = loadWrongQuestions();
  const dailyRecords = loadDailyRecords();
  // 组合筛选：状态 + 科目 + 时间
  const cutoffDate = daysFilter
    ? new Date(Date.now() - daysFilter * 86400000).toISOString().slice(0, 10)
    : null;

  const filtered = questions.filter(q => {
    if (pendingOnly  && q.status === '已掌握')              return false;
    if (moduleFilter && q.module !== moduleFilter)          return false;
    if (cutoffDate   && (q.date ?? '') < cutoffDate)        return false;
    return true;
  });

  // ── 错题行数据 ───────────────────────────────────────────────
  const wrongRows = filtered.map(q => [
    q.date                          ?? '',
    q.module                        ?? '',
    q.subtype                       ?? '',
    q.error_reason                  ?? '',
    q.question_text                 ?? q.question_desc ?? '',
    q.visual_description            ?? '',          // 视觉描述（图形/图表题）
    q.answer                        ?? '',
    q.analysis ?? q.user_annotation ?? '',
    Array.isArray(q.keywords) ? q.keywords.join('、') : '',
    q.status                        ?? '待二刷',
    q.source_engine ?? (q.source === 'image' ? '图片' : '文字'),
    '',   // 截图列占位，由 Python 脚本填充图片
  ]);

  // ── 图片临时文件 ──────────────────────────────────────────────
  const tmpFiles = [];
  const imageMap = {};   // { rowIndex(string): tmpPath }

  if (withImages) {
    filtered.forEach((q, idx) => {
      if (!q.raw_image_b64) return;
      const tmpPath = path.join(os.tmpdir(), `qimg_${Date.now()}_${idx}.jpg`);
      try {
        fs.writeFileSync(tmpPath, Buffer.from(q.raw_image_b64, 'base64'));
        imageMap[String(idx)] = tmpPath;
        tmpFiles.push(tmpPath);
      } catch (_) {}
    });
  }

  // ── 每日记录行数据 ────────────────────────────────────────────
  const dailyRows = dailyRecords.map(r => {
    const m = r.modules ?? {};
    const totalWrong = ['言语理解','数量关系','判断推理','资料分析']
      .reduce((s, mod) => s + (m[mod]?.wrong ?? 0), 0);
    return [
      r.date                    ?? '',
      r.skipped ? '跳过' : '打卡',
      r.mood                    ?? '',
      m['言语理解']?.wrong       ?? '',
      m['数量关系']?.wrong       ?? '',
      m['判断推理']?.wrong       ?? '',
      m['资料分析']?.wrong       ?? '',
      m['申论']?.written ? '是' : '否',
      totalWrong || '',
      r.note                    ?? '',
    ];
  });

  // ── 生成并运行 Python 脚本 ─────────────────────────────────────
  const today    = new Date().toISOString().slice(0, 10);
  const parts    = [];
  if (pendingOnly)  parts.push('待二刷');
  if (moduleFilter) parts.push(moduleFilter);
  if (daysFilter)   parts.push(`近${daysFilter}天`);
  const suffix   = parts.length ? '_' + parts.join('_') : '';
  const outPath  = path.join(OUT_DIR, `备考记录_${today}${suffix}.xlsx`);

  const pyScript = buildPythonScript({ wrongRows, dailyRows, outPath, imageMap, pendingOnly });
  const tmpPy    = path.join(os.tmpdir(), `export_${Date.now()}.py`);
  fs.writeFileSync(tmpPy, pyScript, 'utf-8');

  try {
    await runPython([tmpPy]);
  } finally {
    try { fs.unlinkSync(tmpPy); } catch (_) {}
    tmpFiles.forEach(f => { try { fs.unlinkSync(f); } catch (_) {} });
  }

  const pendingCount = questions.filter(q => q.status !== '已掌握').length;
  const imgCount     = Object.keys(imageMap).length;
  console.log(`[export] 已导出：${outPath}`);
  console.log(`[export] 错题 ${questions.length} 条，待二刷 ${pendingCount} 条，含截图 ${imgCount} 张`);
  console.log(`ATTACH:${outPath}`);

  return outPath;
}

// ─── CLI 入口 ─────────────────────────────────────────────────

if (require.main === module) {
  const pendingOnly  = process.argv.includes('--pending-only');
  const withImages   = !process.argv.includes('--no-images');
  const moduleArg    = process.argv.find(a => a.startsWith('--module='));
  const daysArg      = process.argv.find(a => a.startsWith('--days='));
  const moduleFilter = moduleArg ? moduleArg.split('=')[1] : null;
  const daysFilter   = daysArg   ? parseInt(daysArg.split('=')[1]) : null;
  exportXlsx({ pendingOnly, moduleFilter, daysFilter, withImages }).catch(e => {
    console.error('[export] 失败:', e);
    process.exit(1);
  });
}

module.exports = { exportXlsx };
```

## File: scripts/feishu_doc.js
size: 8645
sha: 7904996e38f353e48ba8ec553951994c5998e117
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/scripts/feishu_doc.js

```text
/**
 * feishu_doc.js
 * 将错题本同步到飞书云文档，支持图片直接嵌入——对图形推理/统计图最有用。
 *
 * 可行性说明：
 *   飞书开放平台提供「云文档 API」，可以程序化创建/更新文档、插入图片块。
 *   图片先上传到飞书文件系统获取 file_token，再作为图片块插入文档。
 *   最终效果：在飞书里直接看到错题截图 + 分析文字，不需要下载 Excel。
 *
 * 前置配置（在 config.json 中填写）：
 *   {
 *     "feishu_doc": {
 *       "enabled": true,
 *       "app_id":     "cli_xxxxxx",
 *       "app_secret": "xxxxxxxx",
 *       "doc_token":  "xxxxxx"   // 飞书文档 URL 中的 token 部分
 *     }
 *   }
 *
 * 获取 app_id / app_secret：飞书开放平台 → 创建企业自建应用 → 权限：docs:doc
 * 获取 doc_token：新建一个飞书文档，URL 中 /wiki/ 或 /docs/ 后面的字符串就是 token
 *
 * 触发方式：用户说"同步到飞书" / "更新飞书错题本"
 */

const fs   = require('fs');
const path = require('path');
const { getConfigPath, getDataDir } = require('./paths');

const DATA_DIR = getDataDir();
const WQ_PATH  = path.join(DATA_DIR, 'wrong_questions.json');

// ─── 飞书 API 基础 ────────────────────────────────────────────

async function getTenantToken(appId, appSecret) {
  const res = await fetch('https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal', {
    method:  'POST',
    headers: { 'Content-Type': 'application/json' },
    body:    JSON.stringify({ app_id: appId, app_secret: appSecret }),
  });
  const data = await res.json();
  if (data.code !== 0) throw new Error(`获取飞书 Token 失败: ${data.msg}`);
  return data.tenant_access_token;
}

/**
 * 上传图片到飞书，返回 file_token。
 * @param {string} imageBase64
 * @param {string} token  tenant_access_token
 */
async function uploadImage(imageBase64, token) {
  const imgBuffer = Buffer.from(imageBase64, 'base64');

  // 飞书上传接口需要 multipart/form-data
  const FormData = (await import('node:buffer')).Blob
    ? globalThis.FormData   // Node 18+
    : require('form-data'); // 低版本 fallback

  const form = new FormData();
  form.append('image_type', 'message');
  form.append('image', new Blob([imgBuffer], { type: 'image/jpeg' }), 'question.jpg');

  const res = await fetch('https://open.feishu.cn/open-apis/im/v1/images', {
    method:  'POST',
    headers: { Authorization: `Bearer ${token}` },
    body:    form,
  });
  const data = await res.json();
  if (data.code !== 0) throw new Error(`图片上传失败: ${data.msg}`);
  return data.data.image_key;
}

// ─── 文档块构建 ───────────────────────────────────────────────

/** 构建一道错题对应的飞书文档块列表（文字 + 可选图片）。 */
function buildQuestionBlocks(q, imageKey) {
  const statusEmoji = q.status === '已掌握' ? '✅' : '🔲';
  const blocks = [];

  // 标题块：科目 + 题型 + 状态
  blocks.push({
    block_type: 3,   // heading2
    heading2: {
      elements: [{
        type: 'text_run',
        text_run: {
          content: `${statusEmoji} [${q.module}·${q.subtype}] ${q.date}`,
          text_element_style: { bold: true },
        },
      }],
    },
  });

  // 题目内容（如果有）
  if (q.question_text) {
    blocks.push({
      block_type: 2,   // text
      text: {
        elements: [{ type: 'text_run', text_run: { content: q.question_text } }],
        style:    {},
      },
    });
  }

  // 图片块（来自截图）
  if (imageKey) {
    blocks.push({
      block_type: 27,  // image
      image: { token: imageKey, width: 400 },
    });
  }

  // 视觉描述（多模态模型生成的，对图形题有用）
  if (q.visual_description) {
    blocks.push({
      block_type: 2,
      text: {
        elements: [{
          type: 'text_run',
          text_run: {
            content: `📐 图形描述：${q.visual_description}`,
            text_element_style: { italic: true },
          },
        }],
        style: {},
      },
    });
  }

  // 分析 / 知识点
  const meta = [
    q.error_reason  && `❌ 原因：${q.error_reason}`,
    q.answer        && `✔️ 答案：${q.answer}`,
    q.keywords?.length && `🏷 知识点：${q.keywords.join('、')}`,
    q.analysis      && `📝 分析：${q.analysis}`,
  ].filter(Boolean).join('　　');

  if (meta) {
    blocks.push({
      block_type: 2,
      text: {
        elements: [{ type: 'text_run', text_run: { content: meta } }],
        style:    {},
      },
    });
  }

  // 分隔线
  blocks.push({ block_type: 22 });

  return blocks;
}

// ─── 插入文档块 ───────────────────────────────────────────────

async function appendBlocksToDoc(docToken, blocks, token) {
  // 先获取文档末尾 block id
  const docRes = await fetch(
    `https://open.feishu.cn/open-apis/docx/v1/documents/${docToken}/blocks?page_size=500`,
    { headers: { Authorization: `Bearer ${token}` } }
  );
  const docData = await docRes.json();
  if (docData.code !== 0) throw new Error(`获取文档结构失败: ${docData.msg}`);

  const items    = docData.data?.items ?? [];
  const lastBlock = items[items.length - 1];
  const parentId  = docData.data?.document?.document_id ?? docToken;
  const index     = lastBlock ? items.length : 0;

  const insertRes = await fetch(
    `https://open.feishu.cn/open-apis/docx/v1/documents/${docToken}/blocks/${parentId}/children`,
    {
      method:  'POST',
      headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
      body:    JSON.stringify({ children: blocks, index }),
    }
  );
  const insertData = await insertRes.json();
  if (insertData.code !== 0) throw new Error(`插入文档块失败: ${insertData.msg}`);
  return insertData;
}

// ─── 主同步函数 ───────────────────────────────────────────────

/**
 * 把最新 N 条错题同步到飞书云文档。
 * @param {{ recentOnly?: boolean, limit?: number }} options
 */
async function syncToFeishuDoc({ recentOnly = true, limit = 10 } = {}) {
  const configPath = getConfigPath();
  if (!fs.existsSync(configPath)) {
    throw new Error('未找到 config.json，请先配置飞书参数（见 assets/config.example.json）');
  }
  const config    = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
  const fdConfig  = config.feishu_doc;
  if (!fdConfig?.enabled || !fdConfig.app_id || !fdConfig.app_secret || !fdConfig.doc_token) {
    throw new Error('飞书云文档未启用或配置不完整，请检查 config.json');
  }

  const { app_id, app_secret, doc_token } = fdConfig;

  let questions = [];
  if (fs.existsSync(WQ_PATH)) {
    questions = JSON.parse(fs.readFileSync(WQ_PATH, 'utf-8'));
  }

  // 只同步最新 limit 条（避免文档过长）
  const toSync = recentOnly
    ? [...questions].sort((a, b) => (b.date ?? '').localeCompare(a.date ?? '')).slice(0, limit)
    : questions;

  if (!toSync.length) {
    console.log('[feishu_doc] 没有错题需要同步');
    return;
  }

  const token = await getTenantToken(app_id, app_secret);
  console.log(`[feishu_doc] 开始同步 ${toSync.length} 道错题...`);

  for (const q of toSync) {
    let imageKey = null;
    if (q.raw_image_b64) {
      try {
        imageKey = await uploadImage(q.raw_image_b64, token);
      } catch (e) {
        console.warn(`[feishu_doc] 图片上传失败（${q.date} ${q.module}）:`, e.message);
      }
    }
    const blocks = buildQuestionBlocks(q, imageKey);
    await appendBlocksToDoc(doc_token, blocks, token);
    console.log(`[feishu_doc] 已同步: ${q.date} ${q.module} ${q.subtype}`);
  }

  console.log('[feishu_doc] 同步完成');
}

// ─── CLI 入口 ─────────────────────────────────────────────────

if (require.main === module) {
  const recentOnly = !process.argv.includes('--all');
  const limit      = parseInt(process.argv.find(a => a.startsWith('--limit='))?.split('=')[1]) || 10;
  syncToFeishuDoc({ recentOnly, limit }).catch(e => {
    console.error('[feishu_doc] 同步失败:', e.message);
    process.exit(1);
  });
}

module.exports = { syncToFeishuDoc };
```

## File: scripts/ocr_image.py
size: 5739
sha: d3451d8e065f019a9d56242d8087eb8c1ba1dd0e
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/scripts/ocr_image.py

```text
#!/usr/bin/env python3
"""
ocr_image.py
用 PaddleOCR 识别题目截图，提取文字，输出 JSON 到 stdout。
被 parse_input.js 通过子进程调用，不需要任何 API Key。

用法：
    python ocr_image.py <图片路径>
    python ocr_image.py --base64 <base64字符串>

输出（stdout）：
    {"success": true,  "text": "识别出的完整文字", "lines": ["行1", "行2", ...]}
    {"success": false, "error": "错误原因"}

依赖安装：
    # CPU 版（推荐，无需 GPU）
    pip install paddlepaddle paddleocr

    # 如果在国内网络，用镜像加速：
    pip install paddlepaddle -i https://pypi.tuna.tsinghua.edu.cn/simple
    pip install paddleocr   -i https://pypi.tuna.tsinghua.edu.cn/simple
"""

import sys
import json
import os
import base64
import tempfile
import re

def load_image_from_path(img_path):
    if not os.path.exists(img_path):
        return None, f"文件不存在: {img_path}"
    return img_path, None

def load_image_from_base64(b64_str):
    """把 base64 字符串写成临时文件，返回路径。"""
    try:
        data = base64.b64decode(b64_str)
        suffix = ".jpg"
        # 检测文件头以判断格式
        if data[:8] == b'\x89PNG\r\n\x1a\n':
            suffix = ".png"
        tmp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
        tmp.write(data)
        tmp.close()
        return tmp.name, None
    except Exception as e:
        return None, f"base64 解码失败: {e}"

def run_ocr(img_path):
    """调用 PaddleOCR，返回 (lines, full_text, error)。"""
    try:
        # 国内网络模型下载提速：把下载源从 HuggingFace 切换到百度对象存储（BOS）。
        # 如果你在国内，取消下面这行的注释，首次运行时模型下载会快很多。
        # os.environ['PADDLE_PDX_MODEL_SOURCE'] = 'BOS'

        # 延迟导入，让错误信息更友好（必须在设置环境变量之后再 import）
        from paddleocr import PaddleOCR

        # use_angle_cls=True 能处理旋转文字（手机拍照常见）
        # lang='ch' 支持中英文混合（行测题目标准场景）
        # show_log=False 关掉冗长的 PaddlePaddle 日志
        ocr = PaddleOCR(use_angle_cls=True, lang='ch', show_log=False)

        # PaddleOCR v3.x 用 predict()，v2.x 用 ocr()
        # 这里做兼容处理
        if hasattr(ocr, 'predict'):
            # v3.x API
            results = ocr.predict(img_path)
            lines = []
            for res in results:
                # v3 结果结构：res 是 dict，有 'rec_texts' 和 'rec_scores'
                texts  = res.get('rec_texts',  [])
                scores = res.get('rec_scores', [])
                for text, score in zip(texts, scores):
                    if score > 0.5 and text.strip():
                        lines.append(text.strip())
        else:
            # v2.x API
            results = ocr.ocr(img_path, cls=True)
            lines = []
            if results and results[0]:
                for item in results[0]:
                    text, score = item[1][0], item[1][1]
                    if score > 0.5 and text.strip():
                        lines.append(text.strip())

        if not lines:
            return [], "", "未识别到文字，请检查图片是否清晰"

        full_text = "\n".join(lines)
        return lines, full_text, None

    except ImportError:
        return [], "", (
            "PaddleOCR 未安装。请运行：\n"
            "pip install paddlepaddle paddleocr\n"
            "国内镜像：pip install paddlepaddle paddleocr "
            "-i https://pypi.tuna.tsinghua.edu.cn/simple"
        )
    except Exception as e:
        return [], "", f"OCR 识别出错: {e}"

def guess_module(text):
    """从识别文字中猜测科目，辅助后续解析。"""
    patterns = {
        "判断推理": ["判断推理", "逻辑判断", "图形推理", "定义判断", "类比推理"],
        "数量关系": ["数量关系", "数学运算", "数字推理"],
        "言语理解": ["言语理解", "语言表达", "阅读理解"],
        "资料分析": ["资料分析", "图表分析"],
        "申论":     ["申论", "大作文", "归纳概括", "综合分析"],
    }
    for module, keywords in patterns.items():
        for kw in keywords:
            if kw in text:
                return module
    return None

def main():
    args = sys.argv[1:]

    if not args:
        print(json.dumps({"success": False, "error": "用法: ocr_image.py <路径> 或 --base64 <字符串>"}, ensure_ascii=False))
        sys.exit(1)

    # 解析参数
    if args[0] == "--base64":
        if len(args) < 2:
            print(json.dumps({"success": False, "error": "--base64 后需要跟 base64 字符串"}, ensure_ascii=False))
            sys.exit(1)
        img_path, err = load_image_from_base64(args[1])
        is_temp = True
    else:
        img_path, err = load_image_from_path(args[0])
        is_temp = False

    if err:
        print(json.dumps({"success": False, "error": err}, ensure_ascii=False))
        sys.exit(1)

    # 跑 OCR
    lines, full_text, ocr_err = run_ocr(img_path)

    # 清理临时文件
    if is_temp and img_path and os.path.exists(img_path):
        os.unlink(img_path)

    if ocr_err:
        print(json.dumps({"success": False, "error": ocr_err}, ensure_ascii=False))
        sys.exit(1)

    result = {
        "success":       True,
        "text":          full_text,
        "lines":         lines,
        "line_count":    len(lines),
        "guessed_module": guess_module(full_text),  # 可选：辅助 JS 侧解析
    }
    print(json.dumps(result, ensure_ascii=False))

if __name__ == "__main__":
    main()
```

## File: scripts/onboarding.js
size: 968
sha: 844aa9e16be31b71280dcf9739f7f2132eca4304
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/scripts/onboarding.js

```text
/**
 * onboarding.js
 * 首次加载时发一条提示，不存任何配置，不问任何问题。
 */

const fs   = require('fs');
const path = require('path');
const { getWelcomeFlagPath } = require('./paths');

const FLAG_PATH = getWelcomeFlagPath();

function hasWelcomed() {
  return fs.existsSync(FLAG_PATH);
}

function markWelcomed() {
  const dir = path.dirname(FLAG_PATH);
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
  fs.writeFileSync(FLAG_PATH, '1');
}

const WELCOME_MSG =
`朱批录已安装。

直接发文字就能记录，比如"今天判断推理错了8道"。
发截图的话，需要当前 agent 配置了支持图片输入的多模态模型才能自动识别。
没有的话也没关系，把题目文字手动复制过来发给我，一样能整理。`;

async function initOnboarding(sendMessage) {
  if (hasWelcomed()) return;
  await sendMessage(WELCOME_MSG);
  markWelcomed();
}

module.exports = { initOnboarding };
```

## File: scripts/parse_input.js
size: 16420
sha: 7b06ed0e51db39fb614feeeace2788d64d0d024e
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/scripts/parse_input.js

````text
/**
 * parse_input.js
 * 将用户发来的消息（文字 或 图片）解析为结构化的备考数据。
 *
 * 图片识别：统一走宿主 agent 提供的多模态模型。
 *   支持图形推理、统计图表等 OCR 无法理解的题型。
 *   未配置时发送 onboarding 提示，引导用户填写 API Key。
 *
 * Windows 兼容：execFile 先尝试 python3，失败则 fallback 到 python（导出用）。
 */

const fs           = require('fs');
const path         = require('path');
const { execFile } = require('child_process');
const os           = require('os');
const { handleReviewReply } = require('./review_reminder');

// ─────────────────────────────────────────────
// 工具函数
// ─────────────────────────────────────────────

const MODULE_MAP = JSON.parse(
  fs.readFileSync(path.join(__dirname, '../assets/module_map.json'), 'utf-8')
);

function normalizeModule(text) {
  if (!text) return null;
  const lower = text.toLowerCase();
  for (const [standard, aliases] of Object.entries(MODULE_MAP.aliases)) {
    if (aliases.some(a => lower.includes(a.toLowerCase()))) return standard;
  }
  return null;
}

function extractWrongCount(text) {
  const patterns = [
    /错[了了]?\s*(\d+)\s*[道题个]/,
    /(\d+)\s*[道题个]?\s*[错误不对]/,
    /(\d+)\s*错/,
  ];
  for (const p of patterns) {
    const m = text.match(p);
    if (m) return parseInt(m[1], 10);
  }
  return null;
}

function inferErrorReason(text) {
  const reasons = MODULE_MAP.error_reason_keywords;
  for (const [reason, keywords] of Object.entries(reasons)) {
    if (keywords.some(k => text.includes(k))) return reason;
  }
  return '未说明';
}

function detectMood(text) {
  if (/太累|好烦|没用|放弃|崩了/.test(text))      return '低落';
  if (/没时间|来不及|考试快|好焦虑|压力/.test(text)) return '焦虑';
  if (/不错|还行|有进步|感觉好|状态好/.test(text))  return '良好';
  return '中性';
}

// ─────────────────────────────────────────────
// ③ 多模态模型调用（可选，支持图形/图表理解）
// ─────────────────────────────────────────────

const MULTIMODAL_PROMPT = `
你是一个公考备考助手，正在分析用户发来的错题截图。
请从图片中提取以下信息，严格以 JSON 格式返回，不要有任何额外说明。

重要要求：
- 所有字段必须完整输出，禁止使用省略号（...）截断内容
- visual_description 对图形推理、统计图题目必须完整描述，不得省略任何细节
- question_text 对文字题必须包含题干和全部选项的完整文字

{
  "module": "科目，只能是：言语理解/数量关系/判断推理/资料分析/申论 之一",
  "subtype": "题型，如：逻辑判断/图形推理/定义判断/类比推理/数学运算/资料分析-增长率/主旨概括 等",
  "question_text": "【完整输出】文字题：题干+全部选项；图形推理：描述图形规律；统计图：标题+所有数据",
  "visual_description": "【完整输出，不得截断】图形推理/统计图的详细视觉描述：每个格子/数据点的具体内容、规律分析。纯文字题填 null",
  "answer": "正确答案字母，图片中若不可见则填 null",
  "user_annotation": "用户手写批注原文，没有填 null",
  "error_reason_hint": "知识点不会/粗心/时间不够/概念混淆/无法判断",
  "keywords": ["知识点标签，最多3个"]
}

如果图片模糊无法识别，返回：{"error": "图片无法识别"}
`.trim();

// ─────────────────────────────────────────────
// 图片识别结果 → 统一结构
// ─────────────────────────────────────────────

function buildConfirmPrompt(module, errorReason, caption) {
  if (!module)                                    return '这是哪个科目？（言语/数量/判断/资料/申论）';
  if (errorReason === '未说明' && !caption)       return '这道题是知识点没掌握、粗心，还是时间不够？';
  return null;
}

function guessSubtype(text) {
  if (/图形|图案/.test(text))                              return '图形推理';
  if (/定义|是指|是一种/.test(text))                       return '定义判断';
  if (/对于|就像|之于/.test(text))                         return '类比推理';
  if (/甲.*乙|假言|充分|必要/.test(text))                  return '逻辑判断';
  if (/增长[率速]|同比|环比|占比|百分/.test(text))          return '资料分析-增长率';
  if (/工程|效率|天完成/.test(text))                       return '数学运算-工程';
  if (/速度|相遇|追及/.test(text))                         return '数学运算-行程';
  if (/主旨|意在|核心|观点/.test(text))                    return '言语-主旨概括';
  if (/填入.*恰当|横线|空白/.test(text))                   return '言语-语句填空';
  return '未识别';
}

function cleanQuestionText(lines) {
  return lines
    .filter(l => {
      const t = l.trim();
      return t && !/^\d+$/.test(t) && !/^第\s*\d+\s*题$/.test(t);
    })
    .join(' ')
    .slice(0, 300);
}

function extractAnswer(text) {
  const patterns = [
    /[【\[]?答案[：:]\s*([A-D])[】\]]?/,
    /正确[答案选项]*[：:]\s*([A-D])/,
  ];
  for (const p of patterns) {
    const m = text.match(p);
    if (m) return m[1];
  }
  return null;
}

function extractKeywords(text, module) {
  const km = {
    '判断推理': [['假言命题',/假言|充分条件|必要条件/],['逆否命题',/逆否/],['图形推理',/图形|对称|旋转/],['定义判断',/定义|是指/]],
    '数量关系': [['工程问题',/工程|效率|天完成/],['行程问题',/速度|相遇|追及/],['排列组合',/排列|组合|方案/]],
    '资料分析': [['增长率',/增长率|同比|环比/],['比重',/比重|占比/],['倍数',/倍数|是.*倍/]],
    '言语理解': [['主旨概括',/主旨|核心/],['语句填空',/填入|横线/],['细节判断',/符合原文/]],
  };
  return (km[module] || []).filter(([,p]) => p.test(text)).map(([k]) => k).slice(0, 3);
}

// ─────────────────────────────────────────────
// 图片消息主入口
// ─────────────────────────────────────────────

async function parseImageInput(imageBase64, caption, agentCall) {
  // agentCall 是宿主 agent 注入的模型调用函数（需支持图片输入）
  // 如果没有注入（模型不支持图片），直接返回降级提示
  if (typeof agentCall !== 'function') {
    return {
      success:         false,
      error:           'no_vision',
      fallback_prompt: '没识别出来，可以把题目文字复制过来发给我，一样能整理。',
    };
  }

  let engineResult;
  try {
    const promptWithCaption = caption
      ? `${MULTIMODAL_PROMPT}\n\n用户附带说明：「${caption}」`
      : MULTIMODAL_PROMPT;
    const raw    = await agentCall({ image: imageBase64, text: promptWithCaption });
    const parsed = JSON.parse((raw || '').replace(/```json|```/g, '').trim());
    if (parsed.error) throw new Error(parsed.error);
    engineResult = {
      success:            true,
      source_engine:      'agent-vision',
      module:             normalizeModule(parsed.module) ?? parsed.module,
      subtype:            parsed.subtype             ?? '未识别',
      question_text:      parsed.question_text       ?? '',
      visual_description: parsed.visual_description  ?? null,
      answer:             parsed.answer              ?? null,
      user_annotation:    parsed.user_annotation     ?? null,
      error_reason:       parsed.error_reason_hint   ?? '未说明',
      keywords:           parsed.keywords            ?? [],
    };
  } catch (e) {
    return {
      success:         false,
      error:           e.message,
      fallback_prompt: '没识别出来，可以把题目文字复制过来发给我，一样能整理。',
    };
  }

  return {
    ...engineResult,
    date:          new Date().toISOString().slice(0, 10),
    source:        'image',
    raw_image_b64: await compressImageAsync(imageBase64),  // 压缩到 800px 宽再存
    needs_confirm: buildConfirmPrompt(engineResult.module, engineResult.error_reason, caption),
  };
}

// ─────────────────────────────────────────────
// 图片压缩（存储前缩至 800px 宽，减少 JSON 体积）
// ─────────────────────────────────────────────

/**
 * 用 Canvas API（Node 18+ 没有，走 sharp 或直接限制尺寸）。
 * 运行在 Node 环境时，这里用 sharp 如果可用，否则原样返回。
 * 安装：npm install sharp（可选，未安装时跳过压缩）
 */
function compressImage(base64) {
  try {
    const sharp = require('sharp');  // 可选依赖，未安装时 catch
    const buf   = Buffer.from(base64, 'base64');
    // sharp 是异步的，这里同步包装（仅在图片很大时才值得）
    // 实际使用时建议改为 async 版本
    return base64;  // 占位，下方 compressImageAsync 是真正的异步版本
  } catch (_) {
    return base64;  // sharp 未安装，原样返回
  }
}

/**
 * 异步版本（推荐在 parseImageInput 中使用）。
 * 将图片压缩到宽度 ≤800px，质量 80，减少存储体积约 60-80%。
 */
async function compressImageAsync(base64) {
  try {
    const sharp  = require('sharp');
    const buf    = Buffer.from(base64, 'base64');
    const out    = await sharp(buf)
      .resize({ width: 800, withoutEnlargement: true })
      .jpeg({ quality: 80 })
      .toBuffer();
    return out.toString('base64');
  } catch (_) {
    return base64;  // sharp 未安装或压缩失败，原样返回
  }
}

// ─────────────────────────────────────────────
// 快捷录入模式
// ─────────────────────────────────────────────

/**
 * 识别快捷格式：「科目-题型-原因-状态」
 * 例：资料-乘积增长-公式不熟-待二刷
 *     判断-逻辑判断-粗心
 *     言语-主旨-没时间
 *
 * @returns {object|null} 解析结果，null 表示不是快捷格式
 */
function parseQuickEntry(text) {
  // 快捷格式：至少两段用 - 或 — 分隔，第一段是科目关键词
  const parts = text.split(/[-—·\/]/);
  if (parts.length < 2) return null;

  const module = normalizeModule(parts[0].trim());
  if (!module) return null;

  // 第二段：题型（可选）
  const subtype = parts[1]?.trim() || '';

  // 第三段：原因（可选，做关键词匹配）
  const reasonRaw  = parts[2]?.trim() || '';
  const error_reason = inferErrorReason(reasonRaw) !== '未说明'
    ? inferErrorReason(reasonRaw)
    : (reasonRaw || '未说明');

  // 第四段：状态（可选）
  const statusRaw = parts[3]?.trim() || '';
  const status    = /掌握|搞懂|会了/.test(statusRaw) ? '已掌握' : '待二刷';

  // 自动提取知识点标签
  const keywords = extractKeywords(`${subtype} ${reasonRaw}`, module);

  return {
    source:        'quick',
    date:          new Date().toISOString().slice(0, 10),
    module,
    subtype:       subtype || guessSubtype(reasonRaw),
    question_text: text,   // 保留原始快捷文字
    error_reason,
    keywords,
    status,
    needs_confirm: null,   // 快捷模式不追问
  };
}

// ─────────────────────────────────────────────
// 导出筛选指令解析
// ─────────────────────────────────────────────

/**
 * 识别用户是否在请求筛选导出，返回筛选参数或 null。
 * 支持：
 *   "导出错题本" / "导出全部"
 *   "只导出待二刷的"
 *   "导出判断推理的错题"
 *   "导出最近两周的" / "导出最近30天"
 *   "只导出待二刷的资料分析题"
 */
function parseExportCommand(text) {
  if (!/导出|错题本|生成报告/.test(text)) return null;

  const pending = /待二刷|未掌握/.test(text);

  // 科目匹配
  const module = normalizeModule(text);

  // 时间匹配：最近N天 / 最近X周
  let days = null;
  const daysMatch = text.match(/最近\s*(\d+)\s*天/);
  const weeksMatch = text.match(/最近\s*(\d+)\s*周/);
  const monthMatch = text.match(/最近\s*(\d+)\s*个?月/);
  if (daysMatch)  days = parseInt(daysMatch[1]);
  if (weeksMatch) days = parseInt(weeksMatch[1]) * 7;
  if (monthMatch) days = parseInt(monthMatch[1]) * 30;
  // 口语化时间
  if (/上周|这周|本周/.test(text))   days = 7;
  if (/本月|这个月/.test(text))      days = 30;
  if (/两周|两个周/.test(text))      days = 14;

  return { _export: true, pendingOnly: pending, moduleFilter: module, daysFilter: days };
}

// ─────────────────────────────────────────────
// 文字消息处理
// ─────────────────────────────────────────────

function parseStudyInput(message) {
  // 优先尝试快捷录入格式：资料-乘积增长-公式不熟-待二刷
  const quick = parseQuickEntry(message);
  if (quick) return quick;

  const result = {
    date:                new Date().toISOString().slice(0, 10),
    source:              'text',
    raw_message:         message,
    mood:                detectMood(message),
    parsed_modules:      {},
    has_exam:            false,
    skip_today:          false,
    needs_clarification: null,
  };

  if (/没做|没时间|跳过|明天补|休息/.test(message)) {
    result.skip_today = true;
    return result;
  }
  if (/做了|做完|刷了|套题|整套|一套/.test(message)) result.has_exam = true;

  for (const sent of message.split(/[，。！？,.\n]/)) {
    const mod = normalizeModule(sent);
    if (mod) {
      result.parsed_modules[mod] = {
        wrong:        extractWrongCount(sent),
        total:        null,
        error_reason: inferErrorReason(sent),
      };
      result.has_exam = true;
    }
  }

  if (result.has_exam && !Object.keys(result.parsed_modules).length) {
    result.needs_clarification = '没太看懂，能说说今天做了哪个科目、错了几道吗？';
  }

  return result;
}

// ─────────────────────────────────────────────
// 通用 agent 入口
// ─────────────────────────────────────────────

async function handleMessage(message, { agentCall, sendMessage } = {}) {
  const text = message.text ?? message.caption ?? '';

  // 1. 二刷回复拦截（优先级最高，避免"记得"被当成普通消息）
  if (message.type === 'text' && sendMessage) {
    const reviewReply = handleReviewReply(text);
    if (reviewReply !== null) {
      await sendMessage(reviewReply);
      return { _review: true };
    }
  }

  // 2. 图片消息
  if (message.type === 'image') {
    return parseImageInput(message.imageBase64, message.caption ?? '', agentCall);
  }

  // 3. 导出筛选指令
  const exportCmd = parseExportCommand(text);
  if (exportCmd) return exportCmd;

  // 4. 普通文字消息
  return parseStudyInput(text);
}

module.exports = { handleMessage, parseStudyInput, parseImageInput, normalizeModule, detectMood };
````

## File: scripts/paths.js
size: 964
sha: 5c88e4bdcc5431b2b86350b8e74a6ceddc4dbc64
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/scripts/paths.js

```text
const path = require('path');
const os = require('os');

const PROJECT_ROOT = path.resolve(__dirname, '..');

function expandHome(p) {
  if (!p) return p;
  if (p === '~') return os.homedir();
  if (p.startsWith(`~${path.sep}`)) return path.join(os.homedir(), p.slice(2));
  return p;
}

function resolvePath(p) {
  return path.resolve(expandHome(p));
}

function getAppDir() {
  return resolvePath(process.env.KAOGONG_TRACKER_HOME || path.join(os.homedir(), '.kaogong-study-tracker'));
}

function getDataDir() {
  return resolvePath(process.env.KAOGONG_DATA_DIR || path.join(getAppDir(), 'data'));
}

function getWelcomeFlagPath() {
  return resolvePath(process.env.KAOGONG_WELCOME_FLAG || path.join(getAppDir(), '.welcomed'));
}

function getConfigPath() {
  return resolvePath(process.env.KAOGONG_CONFIG_PATH || path.join(PROJECT_ROOT, 'config.json'));
}

module.exports = {
  PROJECT_ROOT,
  getAppDir,
  getDataDir,
  getWelcomeFlagPath,
  getConfigPath,
};
```

## File: scripts/review_reminder.js
size: 7178
sha: 397d04299bd05984497c69501087edac48d6da7c
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/scripts/review_reminder.js

```text
/**
 * review_reminder.js
 * 隔天 20:00 由 cron 触发，从"待二刷"错题里随机抽3道，
 * 发给用户让其自评"记得 / 不记得"，连续答对2次自动改为"已掌握"。
 *
 * workspace.yaml 配置（见 assets/workspace-example.yaml）：
 *   cron: 0 20 每隔一天 * *  即  "0 20 1-31/2 * *"
 *   script: skills/kaogong-study-tracker/scripts/review_reminder.js
 *
 * 状态文件：data/review_state.json
 *   记录每道题的二刷历史，key 为题目 id。
 */

const fs   = require('fs');
const path = require('path');
const { getDataDir } = require('./paths');

const DATA_DIR    = getDataDir();
const WQ_PATH     = path.join(DATA_DIR, 'wrong_questions.json');
const STATE_PATH  = path.join(DATA_DIR, 'review_state.json');
const SESSION_PATH = path.join(DATA_DIR, 'review_session.json');

// ─── 工具函数 ─────────────────────────────────────────────────

function loadJson(p, fallback = {}) {
  try { return JSON.parse(fs.readFileSync(p, 'utf-8')); } catch (_) { return fallback; }
}

function saveJson(p, data) {
  const dir = path.dirname(p);
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
  fs.writeFileSync(p, JSON.stringify(data, null, 2), 'utf-8');
}

// ─── 抽题逻辑 ─────────────────────────────────────────────────

/**
 * 从待二刷错题里随机抽 n 道，优先抽最久没复习的。
 */
function pickQuestions(n = 3) {
  if (!fs.existsSync(WQ_PATH)) return [];

  const questions = loadJson(WQ_PATH, []);
  const state     = loadJson(STATE_PATH, {});

  const pending = questions.filter(q => q.status !== '已掌握');
  if (!pending.length) return [];

  // 按上次复习时间升序（最久没看的排前面）
  pending.sort((a, b) => {
    const ta = state[a.id]?.last_reviewed ?? '2000-01-01';
    const tb = state[b.id]?.last_reviewed ?? '2000-01-01';
    return ta.localeCompare(tb);
  });

  // 取前 n*2 道里随机抽 n 道，避免总是同一批
  const pool   = pending.slice(0, Math.min(n * 2, pending.length));
  const picked = [];
  const used   = new Set();
  while (picked.length < n && picked.length < pool.length) {
    const idx = Math.floor(Math.random() * pool.length);
    if (!used.has(idx)) { used.add(idx); picked.push(pool[idx]); }
  }

  return picked;
}

/**
 * 把一道错题格式化成发给用户的文字。
 */
function formatQuestion(q) {
  const lines = [`[${q.module} · ${q.subtype || ''}]`];
  if (q.question_text) lines.push(q.question_text.slice(0, 200));
  if (q.visual_description) lines.push(`图形描述：${q.visual_description.slice(0, 150)}`);
  if (q.answer) lines.push(`正确答案：${q.answer}`);
  lines.push(`知识点：${(q.keywords || []).join('、') || '未标记'}`);
  return lines.join('\n');
}

// ─── 主推送（cron 触发） ──────────────────────────────────────

function buildReminderMessage() {
  const questions = pickQuestions(3);

  if (!questions.length) {
    return '待二刷的错题都清空了，今天不用复习！去刷新题吧。';
  }

  // 把本次抽到的题存入 session，等用户逐一回复
  const session = {
    date:       new Date().toISOString().slice(0, 10),
    questions:  questions.map(q => q.id),
    current:    0,           // 当前正在回答第几道（0-based）
    answers:    {},          // { id: ['记得', '不记得', ...] }
  };
  saveJson(SESSION_PATH, session);

  // 先发第一道
  const first = questions[0];
  return [
    `二刷时间到，抽到 ${questions.length} 道待复习的题。`,
    '',
    `第 1 / ${questions.length} 道：`,
    formatQuestion(first),
    '',
    '还记得这题的解法吗？回复 记得 或 不记得',
  ].join('\n');
}

// ─── 处理用户回复（在 parse_input.js 的 handleMessage 里调用） ──

/**
 * 检测是否有进行中的二刷 session，并处理用户的"记得/不记得"回复。
 * @returns {string|null} 要发送的下一条消息，null 表示没有进行中的 session
 */
function handleReviewReply(userText) {
  if (!fs.existsSync(SESSION_PATH)) return null;

  const session   = loadJson(SESSION_PATH, null);
  if (!session || session.current >= session.questions.length) return null;

  const text      = (userText || '').trim();
  const isRemember = /记得|会了|掌握|对|知道/.test(text);
  const isForget   = /不记得|忘了|不会|错了|不对|不知道/.test(text);

  if (!isRemember && !isForget) return null;  // 不是对二刷的回复

  const currentId = session.questions[session.current];
  if (!session.answers[currentId]) session.answers[currentId] = [];
  session.answers[currentId].push(isRemember ? '记得' : '不记得');

  // 更新 review_state
  const state = loadJson(STATE_PATH, {});
  if (!state[currentId]) state[currentId] = { correct_streak: 0, total: 0 };
  state[currentId].last_reviewed = new Date().toISOString().slice(0, 10);
  state[currentId].total += 1;
  if (isRemember) {
    state[currentId].correct_streak = (state[currentId].correct_streak || 0) + 1;
  } else {
    state[currentId].correct_streak = 0;
  }
  saveJson(STATE_PATH, state);

  // 连续答对 2 次 → 自动标记已掌握
  const mastered = state[currentId].correct_streak >= 2;
  if (mastered) {
    markMastered(currentId);
  }

  // 移到下一题
  session.current += 1;
  saveJson(SESSION_PATH, session);

  // 生成反馈 + 下一题（或结束）
  const feedback = mastered
    ? `已标记为「已掌握」，很好！`
    : isRemember
      ? `记录了。再答对一次就标为已掌握。`
      : `记下了，下次还会再抽到这道。`;

  if (session.current >= session.questions.length) {
    // 全部回答完
    const allQuestions = loadJson(WQ_PATH, []);
    const remaining    = allQuestions.filter(q => q.status !== '已掌握').length;
    return `${feedback}\n\n本次复习完成！还剩 ${remaining} 道待二刷。`;
  }

  // 下一道题
  const nextId = session.questions[session.current];
  const allQ   = loadJson(WQ_PATH, []);
  const nextQ  = allQ.find(q => q.id === nextId);
  if (!nextQ) return `${feedback}\n\n（下一道题找不到了，本次复习结束）`;

  return [
    feedback,
    '',
    `第 ${session.current + 1} / ${session.questions.length} 道：`,
    formatQuestion(nextQ),
    '',
    '还记得这题的解法吗？回复 记得 或 不记得',
  ].join('\n');
}

function markMastered(id) {
  if (!fs.existsSync(WQ_PATH)) return;
  const questions = loadJson(WQ_PATH, []);
  const q = questions.find(q => q.id === id);
  if (q) q.status = '已掌握';
  saveJson(WQ_PATH, questions);
}

// ─── CLI 入口（cron 直接运行） ────────────────────────────────

if (require.main === module) {
  const msg = buildReminderMessage();
  console.log(msg);
}

module.exports = { buildReminderMessage, handleReviewReply };
```

## File: scripts/update_daily.js
size: 6409
sha: d337533077f06ebba08b2a8b34991695894e78a1
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/scripts/update_daily.js

```text
/**
 * update_daily.js
 * 将解析后的备考数据写入每日记录，并更新统计缓存。
 */

const fs = require('fs');
const path = require('path');
const { getDataDir } = require('./paths');

const DATA_DIR = getDataDir();

function ensureDir(dir) {
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}
/**
 * 备份 wrong_questions.json，保留最近10个备份，自动轮转旧备份。
 */
function backupWrongQuestions(wqPath) {
  if (!fs.existsSync(wqPath)) return;

  const backupDir = path.join(path.dirname(wqPath), 'backups');
  if (!fs.existsSync(backupDir)) fs.mkdirSync(backupDir, { recursive: true });

  const ts     = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
  const dest   = path.join(backupDir, `wrong_questions.${ts}.json`);
  fs.copyFileSync(wqPath, dest);

  // 保留最近 10 个，删除更早的
  const backups = fs.readdirSync(backupDir)
    .filter(f => f.startsWith('wrong_questions.') && f.endsWith('.json'))
    .sort()
    .reverse();

  backups.slice(10).forEach(f => {
    try { fs.unlinkSync(path.join(backupDir, f)); } catch (_) {}
  });
}

/**
 * 写入每日记录
 * @param {ParsedInput} parsed  来自 parse_input.js 的解析结果
 * @param {string} note         可选备注
 */
function updateDailyRecord(parsed, note = '') {
  ensureDir(path.join(DATA_DIR, 'daily'));

  const filePath = path.join(DATA_DIR, 'daily', `${parsed.date}.json`);

  // 如果当天已有记录，合并而非覆盖
  let existing = {};
  if (fs.existsSync(filePath)) {
    existing = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
  }

  const record = {
    date: parsed.date,
    skipped: parsed.skip_today,
    modules: {},
    ...existing,
    mood: parsed.mood,
    note: note || parsed.raw_message.slice(0, 100),
    updated_at: new Date().toISOString(),
  };

  // 合并模块数据
  for (const [mod, data] of Object.entries(parsed.parsed_modules)) {
    record.modules[mod] = {
      ...record.modules[mod],
      ...data,
    };
  }

  fs.writeFileSync(filePath, JSON.stringify(record, null, 2), 'utf-8');
  console.log(`[kaogong-tracker] 每日记录已写入: ${filePath}`);

  // 更新统计缓存
  updateStatsCache(parsed.date, record);

  return record;
}

/**
 * 更新统计缓存（连续打卡天数、模块准确率）
 */
function updateStatsCache(today, todayRecord) {
  const cachePath = path.join(DATA_DIR, 'stats_cache.json');

  let cache = {
    last_updated: today,
    total_days_studied: 0,
    streak: 0,
    module_accuracy: {},
  };
  if (fs.existsSync(cachePath)) {
    cache = JSON.parse(fs.readFileSync(cachePath, 'utf-8'));
  }

  // 统计连续打卡
  if (!todayRecord.skipped) {
    cache.total_days_studied = (cache.total_days_studied || 0) + 1;

    // 简单连续天数计算：如果昨天有记录则 +1，否则重置为 1
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);
    const yPath = path.join(DATA_DIR, 'daily', `${yesterday.toISOString().slice(0,10)}.json`);
    if (fs.existsSync(yPath)) {
      cache.streak = (cache.streak || 0) + 1;
    } else {
      cache.streak = 1;
    }
  }

  // 更新模块准确率（7日滚动平均）
  const last7 = getLast7Days(today);
  const moduleStats = {};

  for (const dateStr of last7) {
    const p = path.join(DATA_DIR, 'daily', `${dateStr}.json`);
    if (!fs.existsSync(p)) continue;
    const d = JSON.parse(fs.readFileSync(p, 'utf-8'));
    for (const [mod, info] of Object.entries(d.modules || {})) {
      if (!moduleStats[mod]) moduleStats[mod] = { wrong: 0, total: 0 };
      if (info.wrong != null) {
        moduleStats[mod].wrong += info.wrong;
        // 用标准题数作为 total 估算（如没有精确 total）
        const DEFAULT_TOTALS = { '言语理解': 40, '数量关系': 15, '判断推理': 40, '资料分析': 20 };
        moduleStats[mod].total += info.total || DEFAULT_TOTALS[mod] || 20;
      }
    }
  }

  cache.module_accuracy = {};
  for (const [mod, s] of Object.entries(moduleStats)) {
    if (s.total > 0) {
      cache.module_accuracy[mod] = parseFloat(((s.total - s.wrong) / s.total).toFixed(2));
    }
  }

  // 找出弱项（准确率 < 0.70）
  cache.weak_modules = Object.entries(cache.module_accuracy)
    .filter(([, acc]) => acc < 0.70)
    .sort(([, a], [, b]) => a - b)
    .map(([mod]) => mod);

  cache.last_updated = today;
  fs.writeFileSync(cachePath, JSON.stringify(cache, null, 2), 'utf-8');
  return cache;
}

function getLast7Days(today) {
  const days = [];
  for (let i = 0; i < 7; i++) {
    const d = new Date(today);
    d.setDate(d.getDate() - i);
    days.push(d.toISOString().slice(0, 10));
  }
  return days;
}

/**
 * 读取统计缓存（供回复生成使用）
 */
function readStatsCache() {
  const cachePath = path.join(DATA_DIR, 'stats_cache.json');
  if (!fs.existsSync(cachePath)) return null;
  return JSON.parse(fs.readFileSync(cachePath, 'utf-8'));
}

/**
 * 追加一条错题到 wrong_questions.json，写入前自动备份。
 * @param {object} question  错题对象（来自 parse_input.js 的识别结果）
 * @returns {object[]} 更新后的错题列表
 */
function saveWrongQuestion(question) {
  const wqPath = path.join(DATA_DIR, 'wrong_questions.json');
  ensureDir(DATA_DIR);

  // 备份（每次写入前）
  backupWrongQuestions(wqPath);

  let questions = [];
  if (fs.existsSync(wqPath)) {
    try { questions = JSON.parse(fs.readFileSync(wqPath, 'utf-8')); }
    catch (_) { questions = []; }
  }

  // 生成唯一 id
  const id = `${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
  questions.push({ id, ...question });

  fs.writeFileSync(wqPath, JSON.stringify(questions, null, 2), 'utf-8');
  console.log(`[kaogong-tracker] 错题已保存，当前共 ${questions.length} 条`);
  return questions;
}

/**
 * 更新某条错题的状态（待二刷 ↔ 已掌握）。
 */
function updateWrongQuestionStatus(id, status) {
  const wqPath = path.join(DATA_DIR, 'wrong_questions.json');
  if (!fs.existsSync(wqPath)) return;

  backupWrongQuestions(wqPath);
  const questions = JSON.parse(fs.readFileSync(wqPath, 'utf-8'));
  const q = questions.find(q => q.id === id);
  if (q) q.status = status;
  fs.writeFileSync(wqPath, JSON.stringify(questions, null, 2), 'utf-8');
}

module.exports = { updateDailyRecord, readStatsCache, saveWrongQuestion, updateWrongQuestionStatus };
```

## File: references/reply_templates.md
size: 2084
sha: 4153d74f29f35f99b9be58f13de4ad8afa7e962a
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/references/reply_templates.md

````text
# 回复话术模板

每次回复从下方选择最匹配的模板，然后填入具体数据。
语气风格规则详见 `tone_guide.md`。

---

## 模板 A：正常打卡（有成绩）

```
今天做完了，不错 👍
错题分布：{模块1} {N}道 / {模块2} {N}道 / {模块3} {N}道
最需要注意的是【{最弱模块}】——{一句具体建议}
连续打卡第 {streak} 天。
```

示例：
> 今天做完了，不错 👍
> 错题分布：判断推理 8道 / 数量关系 5道 / 资料分析 3道
> 最需要注意的是【判断推理】——逻辑判断里假言命题的充分/必要条件可以集中刷一下
> 连续打卡第 6 天。

---

## 模板 B：今天没做题

```
没事，休息也是备考的一部分。
明天{建议具体行动}，比如{一个小目标}就够了。
```

示例：
> 没事，休息也是备考的一部分。
> 明天把资料分析的图表题专项做 10 道，找找感觉就够了。

---

## 模板 C：用户情绪低落 / 焦虑

```
{认可当前状态的一句话}。
你现在最弱的是【{模块}】，但{一个积极视角}。
明天只做一件事：{极小目标}。
```

示例：
> 感觉复习不完很正常，材料本来就多。
> 你现在最弱的是【数量关系】，但错的类型很集中，说明不是基础差，是某几类题型没摸透。
> 明天只做一件事：工程问题专项，10道，计时。

---

## 模板 D：查询历史 / 弱点分析

```
看了一下最近 {N} 天的记录：
- 最稳的是【{模块}】，正确率 {X}%
- 最需要加强的是【{模块}】，正确率 {X}%
建议接下来优先攻【{模块}】，用{具体方法}。
```

---

## 模板 E：错题二刷提醒（定时推送用）

```
你有 {N} 道错题还没二刷，最老的是 {N} 天前的【{模块}】题目。
要不要现在过一遍？
```

---

## 注意事项

- 不要在一条回复里给超过 1 条建议
- 不要重复用户说过的话（显得没在听）
- 不要说"加油""你可以的"这类空洞鼓励
- 语气不要像老师，更像一个帮忙记录的朋友
````

## File: references/tone_guide.md
size: 2053
sha: 7a08cba49d0ef9b18f8c6dd53fd323a0bf4e894f
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/references/tone_guide.md

```text
# 语气风格指引

## 核心定位

**不是老师，不是 AI 助手，是帮忙记录的朋友。**

回复的语感目标：像一个关心她但不强迫她的人，在旁边默默帮她整理，
偶尔说一句有用的话，不多说。

---

## DO ✅

- 简短。一条回复最多 4 句话。
- 具体。"判断推理错了 8 道"比"今天判断推理错题较多"更好。
- 一个建议。不是三条，不是两条，就一条，但要具体可操作。
- 承认现实。"数量关系一直是弱项"比"数量关系还有提升空间"更真实。
- 情绪识别。如果用户说"太累了""好烦""感觉没用"，
  先回应情绪，再说备考的事。顺序不能反。

---

## DON'T ❌

- 不说"加油""你可以的""相信自己"——空洞无用
- 不说"根据您的数据分析"——太像 AI
- 不说"首先…其次…最后…"——太像报告
- 不连续追问多个问题——最多问一个
- 不在用户情绪低落时立刻给建议——先回应感受
- 不用感叹号超过 1 个
- 不重复用户刚说过的话

---

## 情绪关键词识别

| 用户说的词               | 判断为       | 回复策略             |
|---------------------|-----------|------------------|
| 太累了、好烦、感觉没用        | 情绪低落      | 先认可 → 极小目标      |
| 没时间、来不及、考试快了       | 焦虑        | 先稳住 → 聚焦最重要的一个  |
| 还不错、还行、感觉有进步       | 状态良好      | 简短认可 → 指出下一个弱点  |
| 今天没做、跳过了、明天补       | 暂停        | 不评价 → 轻轻记录即可    |

---

## 语气示例对比

❌ 版本：
> 您今天的备考数据已记录完毕。根据数据分析，判断推理模块的正确率有待提升，
> 建议您重点关注逻辑判断题型，加强专项练习，相信您一定能取得好成绩！加油！

✅ 版本：
> 判断推理 8 道，是今天最多的。
> 大概率是假言命题那类——专项刷 20 道，错误率会明显下来。
```

## File: assets/config.example.json
size: 1335
sha: 980df47902c612a0d4cc1d8761a0c62a73f1d92b
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/assets/config.example.json

```text
{
  "_comment": "复制此文件为 config.json，按需填写。未填写的功能会自动降级。",

  "multimodal": {
    "_comment": "可选。配置后，图形推理/统计图题目会调用多模态模型理解图片内容。",
    "enabled": false,
    "provider": "anthropic",
    "_provider_options": ["anthropic", "openai"],
    "model": "claude-sonnet-4-20250514",
    "_model_alternatives": {
      "anthropic": "claude-opus-4-5",
      "openai": "gpt-4o",
      "openai_compatible": "qwen-vl-plus（需改 base_url）"
    },
    "api_key": "",
    "base_url": "https://api.anthropic.com/v1/messages",
    "_base_url_note": "OpenAI 兼容接口改为对应地址，如 https://api.openai.com/v1/chat/completions",
    "always_use": false,
    "_always_use_note": "true = 所有图片都走多模态；false = 只有疑似图形/图表题才用"
  },

  "feishu_doc": {
    "_comment": "可选。配置后，可以把错题（含截图）同步到飞书云文档，直接在飞书查看。",
    "enabled": false,
    "app_id": "",
    "app_secret": "",
    "doc_token": "",
    "_how_to_get": {
      "app_id_secret": "飞书开放平台 open.feishu.cn → 创建企业自建应用 → 权限勾选 docs:doc",
      "doc_token": "新建飞书文档，URL 中 /docx/ 后面的字符串，如 xxxxxxxxxxxxxx"
    }
  }
}
```

## File: assets/crane_zhupi.png
size: 880614
sha: 30ae0163bbde046c041cc65a3de99613a26858ac
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/assets/crane_zhupi.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/assets/crane_zhupi.png

## File: assets/module_map.json
size: 1267
sha: e9a9a831eeb5a49084d2a2c2ec34ad4498bf394e
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/assets/module_map.json

```text
{
  "aliases": {
    "言语理解": ["言语", "语言", "阅读", "言语理解与表达", "言语理解和表达"],
    "数量关系": ["数量", "数学", "数字", "数学运算", "数量关系"],
    "判断推理": ["判断", "逻辑", "推理", "图推", "类比", "定义判断", "逻辑判断", "图形推理", "类比推理"],
    "资料分析": ["资料", "图表", "数据分析", "资料分析"],
    "申论": ["申论", "大作文", "作文", "归纳", "对策", "分析", "综合分析", "归纳概括", "提出对策"]
  },
  "exam_types": {
    "aliases": {
      "国考": ["国家公务员", "国家公务员考试", "国考行测", "国考申论"],
      "省考": ["省级公务员", "省公务员", "省考行测"],
      "事业单位": ["事业编", "事业单位考试", "职业能力测验"]
    }
  },
  "error_reason_keywords": {
    "知识点不会": ["不懂", "没学过", "不知道", "这个没复习", "概念不清", "原来是这样"],
    "粗心": ["看错", "算错", "选反了", "写错", "马虎", "手误", "没看清"],
    "时间不够": ["没做完", "蒙的", "时间不够", "来不及", "最后几题", "没时间"],
    "概念混淆": ["搞混了", "分不清", "类似的", "以为是", "和…混淆"]
  }
}
```

## File: assets/workspace-example.yaml
size: 1512
sha: e771d9a588e474066f5af56053e70c2789ed6c6d
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/assets/workspace-example.yaml

```text
# workspace-study-tracker.yaml
# OpenClaw 飞书接入示例配置
# 朱批录本身是通用 agent skill；这个文件只用于 OpenClaw 兼容接入。
# OpenClaw 用户可以把这个文件放到 ~/.openclaw/workspaces/ 下启用。

name: "备考助手"
description: "帮助追踪每日行测/申论套题进度"

# 接入的聊天渠道
# 飞书目前需要通过飞书机器人 Webhook 桥接，
# OpenClaw 飞书桥接详见 https://docs.openclaw.ai/channels/feishu
channels:
  feishu:
    enabled: true
    webhook_url: "${FEISHU_WEBHOOK_URL}"   # 在 .env 里配置
    # 只响应特定用户（填飞书 user_id，留空则全响应）
    allow_from: []

  # 其他渠道按需开启，逻辑完全一样
  # telegram:
  #   enabled: false
  #   bot_token: "${TELEGRAM_BOT_TOKEN}"
  # whatsapp:
  #   enabled: false

# 大模型配置
llm:
  provider: "anthropic"
  model: "claude-sonnet-4-20250514"
  api_key: "${ANTHROPIC_API_KEY}"
  max_tokens: 1000
  temperature: 0.5

# 启用的 Skills
skills:
  - kaogong-study-tracker

# 定时任务
cron_jobs:
  - name: "备考晚间总结"
    schedule: "0 21 * * *"   # 每天 21:00
    action:
      type: run_script
      script: skills/kaogong-study-tracker/scripts/daily_summary.js
      channel: feishu           # 推送到飞书

# 记忆配置（让 agent 记住用户习惯）
memory:
  enabled: true
  persist_to: "~/.kaogong-study-tracker/memory.md"

settings:
  language: "zh-CN"
  reply_max_chars: 200    # 回复字数限制，避免啰嗦
```

## File: .gitignore
size: 79
sha: 913d4c8da357dc8bbde6c761129417b503b8c8c7
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/.gitignore

```text
node_modules/
data/
*.xlsx
.env
.DS_Store
*.log
config.json
__pycache__/
*.pyc
```

## File: AGENTS.md
size: 1767
sha: 82f7c77af66af87d2b5ddc137789a4da4bb1f488
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/AGENTS.md

````text
# 朱批录 Agent Instructions

This repository is a reusable study-tracking skill for civil service exam prep. It is not tied to one host. Agents such as Trae, Cursor, opencode, Hermes, OpenClaw, or any local coding/chat agent can use it by reading `SKILL.md` and calling the scripts in `scripts/`.

## When To Trigger

Use this skill when the user mentions:

- 公考、国考、省考、行测、申论
- 错题、错题本、二刷、复习提醒
- 言语理解、数量关系、判断推理、资料分析
- 导出错题本、生成 Excel、同步飞书
- An uploaded screenshot of an exam question

## Core Flow

1. Text progress input: call `handleMessage()` or `parseStudyInput()` from `scripts/parse_input.js`, then persist with `updateDailyRecord()` from `scripts/update_daily.js`.
2. Image question input: pass the screenshot base64 plus a vision-capable `agentCall` into `parseImageInput()`, then save the returned question with `saveWrongQuestion()`.
3. Export workbook: run `node scripts/export_xlsx.js`; add filters such as `--pending-only`, `--module=判断推理`, or `--days=14` when requested.
4. Daily summary: run `node scripts/daily_summary.js` and send stdout back to the user.
5. Review reminder: run `node scripts/review_reminder.js`; route later “记得 / 不记得” replies through `handleMessage()`.

## Local Data

Data is local-first. By default it lives in:

```bash
~/.kaogong-study-tracker/data
```

Override it with:

```bash
KAOGONG_DATA_DIR=/path/to/data
```

## Image Capability

Screenshot recognition depends on the host agent. If the current model cannot accept images, ask the user to paste the question text and continue with the text flow.

Keep replies short, concrete, and friendly. Follow `references/tone_guide.md`.
````

## File: LICENSE
size: 1090
sha: 27166ce500cbe817158662808cb848dad0cf2484
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/LICENSE

```text
MIT License

Copyright (c) 2026 guokao-study-tracker contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

## File: package-lock.json
size: 280
sha: a79a7b5d80877099cd62ade4c57df9b80e23f126
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/package-lock.json

```text
{
  "name": "kaogong-study-tracker",
  "version": "0.1.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "kaogong-study-tracker",
      "version": "0.1.0",
      "license": "MIT",
      "engines": {
        "node": ">=18"
      }
    }
  }
}
```

## File: package.json
size: 693
sha: 7e5a274c05b2bda353345823dc8df219f9c54765
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/package.json

```text
{
  "name": "kaogong-study-tracker",
  "version": "0.1.0",
  "description": "朱批录 — 通用 Agent 考公备考追踪 Skill",
  "keywords": [
    "agent-skill",
    "ai-agent",
    "kaogong",
    "gongkao",
    "civil-service-exam",
    "study-tracker",
    "exam-prep"
  ],
  "author": "",
  "license": "MIT",
  "engines": {
    "node": ">=18"
  },
  "scripts": {
    "export": "node scripts/export_xlsx.js",
    "export:pending": "node scripts/export_xlsx.js --pending-only",
    "summary": "node scripts/daily_summary.js",
    "setup:ocr": "pip install paddlepaddle paddleocr",
    "setup:ocr:cn": "pip install paddlepaddle paddleocr -i https://pypi.tuna.tsinghua.edu.cn/simple"
  }
}
```

## File: promo/01-cover.png
size: 221598
sha: 83de06bf743a354da30b85966dc3c5fdef864151
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/promo/01-cover.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/promo/01-cover.png

## File: promo/02-chat-flow.png
size: 175513
sha: 31bc942886f50926ae33f4f2008c7c0e266afdad
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/promo/02-chat-flow.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/promo/02-chat-flow.png

## File: promo/03-workbook.png
size: 216079
sha: 9808d5389470ad95bf823e494d74fd17a21367c4
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/promo/03-workbook.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/promo/03-workbook.png

## File: promo/04-review-reminder.png
size: 242292
sha: 424ce1038906ec9d65aa1a1caa9ebba94c19255e
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/promo/04-review-reminder.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/promo/04-review-reminder.png

## File: promo/generate_promo_images.py
size: 13675
sha: 85070836e943b83e639670872040fae34ed752c9
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/promo/generate_promo_images.py

```text
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont

ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "promo"
W, H = 1440, 1920

FONT_BOLD = "/System/Library/Fonts/STHeiti Medium.ttc"
FONT_REG = "/System/Library/Fonts/STHeiti Light.ttc"

def font(size, bold=False):
    return ImageFont.truetype(FONT_BOLD if bold else FONT_REG, size)

F = {
    "title": font(86, True),
    "subtitle": font(40),
    "h1": font(58, True),
    "h2": font(42, True),
    "body": font(34),
    "body_bold": font(34, True),
    "small": font(26),
    "tiny": font(22),
    "table": font(25),
    "table_bold": font(25, True),
}

COL = {
    "bg": "#F7F3EA",
    "paper": "#FFFDF7",
    "ink": "#24201C",
    "muted": "#746D63",
    "line": "#E4D8C6",
    "red": "#B93A32",
    "blue": "#2D5FA1",
    "green": "#2F7D57",
    "gold": "#B9822B",
    "soft_red": "#F8E8E4",
    "soft_blue": "#E7EEF9",
    "soft_green": "#E6F2EB",
    "soft_gold": "#F6EBD5",
}

def text_w(draw, text, fnt):
    if not text:
        return 0
    box = draw.textbbox((0, 0), text, font=fnt)
    return box[2] - box[0]

def text_h(draw, text, fnt):
    box = draw.textbbox((0, 0), text or "国", font=fnt)
    return box[3] - box[1]

def wrap(draw, text, fnt, max_w):
    lines = []
    for para in text.split("\n"):
        cur = ""
        for ch in para:
            if text_w(draw, cur + ch, fnt) <= max_w:
                cur += ch
            else:
                if cur:
                    lines.append(cur)
                cur = ch
        lines.append(cur)
    return lines

def wrapped_height(draw, text, fnt, max_w, line_gap=10):
    lines = wrap(draw, text, fnt, max_w)
    if not lines:
        return 0
    return sum(text_h(draw, line, fnt) for line in lines) + line_gap * (len(lines) - 1)

def fit_font(draw, text, max_w, max_h, start_size, bold=False, min_size=18, line_gap=10):
    size = start_size
    while size > min_size:
        fnt = font(size, bold)
        if wrapped_height(draw, text, fnt, max_w, line_gap) <= max_h:
            return fnt
        size -= 2
    return font(min_size, bold)

def draw_text(draw, xy, text, fnt, fill=COL["ink"], max_w=None, line_gap=10):
    x, y = xy
    if max_w:
        lines = wrap(draw, text, fnt, max_w)
    else:
        lines = text.split("\n")
    for line in lines:
        draw.text((x, y), line, font=fnt, fill=fill)
        y += text_h(draw, line, fnt) + line_gap
    return y

def rr(draw, box, fill, outline=None, width=1, r=8):
    draw.rounded_rectangle(box, radius=r, fill=fill, outline=outline, width=width)

def pill(draw, x, y, text, fill, fg=None, pad_x=20, pad_y=10):
    fg = fg or COL["ink"]
    fnt = F["small"]
    tw = text_w(draw, text, fnt)
    th = text_h(draw, text, fnt)
    box = (x, y, x + tw + pad_x * 2, y + th + pad_y * 2)
    rr(draw, box, fill, r=8)
    draw.text((x + pad_x, y + pad_y - 2), text, font=fnt, fill=fg)
    return box[2]

def base():
    im = Image.new("RGB", (W, H), COL["bg"])
    draw = ImageDraw.Draw(im)
    draw.rectangle((0, 0, W, 180), fill="#EEE2D1")
    draw.rectangle((0, H - 170, W, H), fill="#ECE7DC")
    return im, draw

def footer(draw):
    draw.text((96, H - 112), "朱批录 · kaogong-study-tracker", font=F["small"], fill=COL["muted"])
    draw.text((96, H - 74), "GitHub: KaguraNanaga/kaogong-study-tracker", font=F["tiny"], fill=COL["muted"])

def logo(draw, x=96, y=62):
    mark = OUT.parent / "assets" / "crane_zhupi.png"
    if mark.exists():
        img = Image.open(mark).convert("RGB")
        img.thumbnail((120, 72))
        draw.rounded_rectangle((x - 8, y - 8, x + 128, y + 80), radius=8, fill=COL["paper"])
        canvas.paste(img, (x, y))
    draw.text((x + 150, y + 10), "朱批录", font=F["h2"], fill=COL["red"])
    draw.text((x + 150, y + 58), "通用 Agent 错题整理 Skill", font=F["small"], fill=COL["muted"])

def draw_question_card(draw, box):
    x1, y1, x2, y2 = box
    rr(draw, box, COL["paper"], outline=COL["line"], width=2, r=8)
    draw.rectangle((x1, y1, x2, y1 + 74), fill=COL["soft_red"])
    draw.text((x1 + 28, y1 + 22), "题目截图", font=F["small"], fill=COL["red"])
    y = y1 + 108
    question = "已知：甲参加则乙参加；只有丙参加，丁才参加。问哪项一定为真？"
    y = draw_text(draw, (x1 + 34, y), question, F["tiny"], max_w=x2 - x1 - 68, line_gap=6)
    opts = ["A. 甲参加则丁参加", "B. 丁参加则丙参加", "C. 乙参加则甲参加", "D. 丙参加则甲参加"]
    for opt in opts:
        color = COL["green"] if opt.startswith("B") else COL["ink"]
        draw.text((x1 + 34, y + 10), opt, font=F["tiny"], fill=color)
        y += 38
    if y + 76 <= y2:
        rr(draw, (x1 + 34, y + 22, x1 + 200, y + 68), COL["soft_gold"], r=8)
        draw.text((x1 + 54, y + 32), "我选了 A", font=F["tiny"], fill=COL["gold"])

def draw_phone(draw, box, title):
    x1, y1, x2, y2 = box
    rr(draw, box, "#151515", r=44)
    rr(draw, (x1 + 22, y1 + 22, x2 - 22, y2 - 22), "#F8F6F2", r=34)
    draw.text((x1 + 58, y1 + 58), title, font=F["small"], fill=COL["ink"])
    draw.line((x1 + 40, y1 + 112, x2 - 40, y1 + 112), fill=COL["line"], width=2)

def bubble(draw, box, text, mine=False, fnt=None):
    fill = COL["soft_blue"] if mine else COL["paper"]
    outline = "#C8D8F0" if mine else COL["line"]
    rr(draw, box, fill, outline=outline, width=1, r=8)
    start_size = getattr(fnt or F["small"], "size", 26)
    fnt = fit_font(draw, text, box[2] - box[0] - 48, box[3] - box[1] - 40, start_size, line_gap=8)
    draw_text(draw, (box[0] + 24, box[1] + 20), text, fnt, max_w=box[2] - box[0] - 48, line_gap=8)

def cover():
    global canvas
    canvas, draw = base()
    footer(draw)
    logo(draw)
    draw.text((96, 270), "把错题截图丢给它", font=F["title"], fill=COL["ink"])
    draw.text((96, 374), "自动长出一本错题本", font=F["title"], fill=COL["red"])
    draw_text(draw, (100, 505), "适合国考/省考刷题后整理：截图识别、原因归类、Excel 导出、二刷提醒。Trae / Cursor / opencode / Hermes 等 agent 都能接。", F["body"], fill=COL["muted"], max_w=930, line_gap=14)

    pill(draw, 100, 690, "截图进来", COL["soft_red"], COL["red"])
    pill(draw, 310, 690, "错题归档", COL["soft_blue"], COL["blue"])
    pill(draw, 520, 690, "表格导出", COL["soft_green"], COL["green"])
    pill(draw, 730, 690, "定时二刷", COL["soft_gold"], COL["gold"])

    draw_phone(draw, (650, 835, 1280, 1580), "备考助手")
    draw_question_card(draw, (710, 960, 1220, 1325))
    bubble(draw, (760, 1380, 1200, 1510), "已整理：判断推理 · 逻辑判断\n原因：粗心\n标签：假言命题、必要条件\n状态：待二刷", mine=False)

    rr(draw, (96, 910, 570, 1260), COL["paper"], outline=COL["line"], width=2)
    draw.text((136, 952), "为什么好用", font=F["h2"], fill=COL["ink"])
    points = ["不用再手抄题干", "图形/表格题能存原截图", "复习时按待二刷抽题", "Excel 可继续喂给大模型分析"]
    y = 1030
    for p in points:
        draw.ellipse((140, y + 12, 156, y + 28), fill=COL["red"])
        draw.text((180, y), p, font=F["body"], fill=COL["ink"])
        y += 58
    canvas.save(OUT / "01-cover.png")

def flow():
    global canvas
    canvas, draw = base()
    footer(draw)
    logo(draw)
    draw.text((96, 245), "最常见的使用场景", font=F["h1"], fill=COL["ink"])
    draw_text(draw, (100, 320), "做完题后直接发截图，不用打开表格，也不用手动分类。", F["body"], fill=COL["muted"], max_w=1050)

    draw_phone(draw, (96, 470, 1344, 1550), "任意支持脚本和图片模型的 Agent")
    bubble(draw, (150, 610, 650, 715), "这题我选错了，主要是粗心", mine=True)
    draw_question_card(draw, (160, 745, 720, 1138))
    bubble(draw, (570, 1185, 1270, 1432), "收到了，已归档为：\n判断推理 · 逻辑判断\n错误原因：粗心\n正确答案：B\n知识点：假言命题、必要条件\n状态：待二刷", mine=False, fnt=F["body"])

    y = 1590
    for i, t in enumerate(["发截图", "自动提取题目", "归类原因", "写进错题本"]):
        x = 130 + i * 310
        rr(draw, (x, y, x + 235, y + 82), [COL["soft_red"], COL["soft_blue"], COL["soft_green"], COL["soft_gold"]][i], r=8)
        draw.text((x + 36, y + 24), t, font=F["small"], fill=[COL["red"], COL["blue"], COL["green"], COL["gold"]][i])
        if i < 3:
            draw.text((x + 254, y + 20), ">", font=F["h2"], fill=COL["muted"])
    canvas.save(OUT / "02-chat-flow.png")

def workbook():
    global canvas
    canvas, draw = base()
    footer(draw)
    logo(draw)
    draw.text((96, 245), "整理结果长这样", font=F["h1"], fill=COL["ink"])
    draw_text(draw, (100, 320), "错题本和每日记录会导出成一个 Excel，截图也能嵌在对应行。", F["body"], fill=COL["muted"], max_w=1120)

    rr(draw, (96, 470, 1344, 1320), COL["paper"], outline=COL["line"], width=2)
    draw.rectangle((96, 470, 1344, 542), fill=COL["blue"])
    draw.text((132, 490), "备考记录_2026-06-30.xlsx", font=F["small"], fill="white")
    tabs = [("错题本", 130, COL["soft_blue"], COL["blue"]), ("每日记录", 290, "#F2F2F2", COL["muted"])]
    for text, x, fill, fg in tabs:
        rr(draw, (x, 570, x + 140, 620), fill, r=8)
        draw.text((x + 28, 582), text, font=F["tiny"], fill=fg)

    headers = ["日期", "科目", "题型", "原因", "题目内容", "答案", "标签", "状态"]
    widths = [125, 135, 170, 120, 390, 80, 170, 115]
    x = 128
    y = 665
    for h, wid in zip(headers, widths):
        draw.rectangle((x, y, x + wid, y + 58), fill="#EEF3F9", outline=COL["line"])
        draw.text((x + 14, y + 17), h, font=F["table_bold"], fill=COL["blue"])
        x += wid
    rows = [
        ["06-30", "判断推理", "逻辑判断", "粗心", "如果甲参加，则乙参加；只有丙参加，丁才参加……", "B", "假言命题", "待二刷"],
        ["06-30", "资料分析", "增长率", "公式不熟", "2019-2023 年产量同比变化图……", "C", "增长率", "待二刷"],
        ["06-29", "言语理解", "主旨概括", "概念混淆", "这段文字意在说明……", "D", "主旨题", "已掌握"],
    ]
    y += 58
    for idx, row in enumerate(rows):
        x = 128
        row_h = 92
        for val, wid in zip(row, widths):
            fill = "#FFFFFF" if idx % 2 == 0 else "#FBF8F0"
            draw.rectangle((x, y, x + wid, y + row_h), fill=fill, outline=COL["line"])
            fnt = F["table"]
            color = COL["green"] if val == "已掌握" else (COL["red"] if val == "待二刷" else COL["ink"])
            draw_text(draw, (x + 10, y + 15), val, fnt, fill=color, max_w=wid - 20, line_gap=4)
            x += wid
        y += row_h

    rr(draw, (150, 1080, 440, 1235), COL["soft_red"], r=8)
    draw.text((188, 1118), "Sheet 1", font=F["small"], fill=COL["red"])
    draw.text((188, 1160), "错题本", font=F["h2"], fill=COL["red"])
    rr(draw, (510, 1080, 800, 1235), COL["soft_green"], r=8)
    draw.text((548, 1118), "Sheet 2", font=F["small"], fill=COL["green"])
    draw.text((548, 1160), "每日记录", font=F["h2"], fill=COL["green"])
    rr(draw, (870, 1080, 1190, 1235), COL["soft_gold"], r=8)
    draw.text((908, 1118), "可选", font=F["small"], fill=COL["gold"])
    draw.text((908, 1160), "嵌入截图", font=F["h2"], fill=COL["gold"])

    rr(draw, (96, 1395, 1344, 1595), COL["paper"], outline=COL["line"], width=2)
    draw.text((136, 1430), "适合继续分析", font=F["h2"], fill=COL["ink"])
    draw_text(draw, (136, 1492), "把导出的 Excel 发给 Kimi / ChatGPT，让它帮你看最近哪类题最容易错。", F["body"], fill=COL["muted"], max_w=1120)
    canvas.save(OUT / "03-workbook.png")

def review():
    global canvas
    canvas, draw = base()
    footer(draw)
    logo(draw)
    draw.text((96, 245), "不只是记录，还会拉你回来复习", font=F["h1"], fill=COL["ink"])
    draw_text(draw, (100, 320), "晚间总结看当天弱项，二刷提醒从待复习错题里抽题。", F["body"], fill=COL["muted"], max_w=1120)

    rr(draw, (120, 510, 1320, 840), COL["paper"], outline=COL["line"], width=2)
    pill(draw, 160, 550, "21:00 今日总结", COL["soft_blue"], COL["blue"])
    summary = "今日总结：判断推理 8 错 / 数量关系 5 错 / 言语理解 4 错 / 资料分析 3 错\n判断推理错得多，明天专项刷逻辑判断，重点看假言命题。\n今天打卡完成。"
    draw_text(draw, (160, 625), summary, F["body"], max_w=1080, line_gap=12)

    rr(draw, (120, 920, 1320, 1330), COL["paper"], outline=COL["line"], width=2)
    pill(draw, 160, 960, "隔天 20:00 二刷提醒", COL["soft_red"], COL["red"])
    reminder = "抽到 1 道待复习的题：\n[判断推理 · 逻辑判断]\n如果甲参加，则乙参加；只有丙参加，丁才参加。问哪项一定为真？\n正确答案：B\n知识点：假言命题、必要条件\n还记得这题的解法吗？回复：记得 / 不记得"
    draw_text(draw, (160, 1035), reminder, F["body"], max_w=1080, line_gap=10)

    rr(draw, (120, 1410, 1320, 1608), COL["soft_green"], outline="#BBD8C8", width=2)
    draw.text((160, 1452), "本地优先", font=F["h2"], fill=COL["green"])
    draw_text(draw, (160, 1514), "错题数据和截图默认存在自己的电脑里；只有主动同步飞书时，才上传到你的飞书文档。", F["body"], fill=COL["ink"], max_w=1080)
    canvas.save(OUT / "04-review-reminder.png")

if __name__ == "__main__":
    OUT.mkdir(exist_ok=True)
    cover()
    flow()
    workbook()
    review()
    for p in sorted(OUT.glob("0*.png")):
        print(p)
```

## File: promo/xiaohongshu-copy.md
size: 2308
sha: cf4b773877a238b80702100c3e2e3ba49726a58f
upstream: https://github.com/kagurananaga/kaogong-study-tracker/blob/HEAD/promo/xiaohongshu-copy.md

```text
# 小红书宣传文案

## 标题备选

1. 做了一个公考错题整理小工具
2. 把公考错题截图整理成错题本
3. 公考刷题后的整理，可以交给 agent 做一部分
4. 一个通用 agent 可用的公考错题整理 skill

## 正文

最近做了一个公考备考用的小工具，叫 **朱批录 · kaogong-study-tracker**。

主要想解决刷题之后的整理问题。

平时做完题，经常还要抄题干、标原因、整理错题本、过几天再翻出来二刷。这个过程比较碎，也很容易拖着不做。

这个工具的用法大概是：

1. 把错题截图发给 agent
2. agent 识别题目内容和答案信息
3. 自动归到对应模块，比如判断推理 / 资料分析
4. 记录错误原因，比如粗心、知识点不会、时间不够
5. 写进本地错题本
6. 需要的时候导出 Excel

它按通用 agent skill 的方式写的，Trae、Cursor、opencode、Hermes、OpenClaw，或者其他能读说明、跑脚本、调用图片模型的 agent，都可以接。

目前已经验证过这些流程：

- 自然语言打卡：比如“言语4错，判断8错，数量5错，资料3错”
- 截图识别后整理成结构化错题
- 导出 Excel 错题本，包含“错题本”和“每日记录”两个 Sheet
- 晚上自动总结当天弱项
- 从待二刷错题里抽题，提醒你复习

数据默认存在自己电脑本地。如果主动配置飞书，也可以同步到自己的飞书文档里看。

适合：

- 每天刷行测，但经常懒得整理错题的人
- 图形推理、资料分析截图很多的人
- 想把错题导出给 Kimi / ChatGPT 继续分析的人
- 想让复习提醒自动一点的人

截图识别需要当前 agent 配置支持图片输入的多模态模型。没有图片能力的话，也可以用文字方式记录。

项目开源在 GitHub：KaguraNanaga/kaogong-study-tracker

## 配图顺序

1. `01-cover.png`：封面，说明“截图进来，错题本出去”
2. `02-chat-flow.png`：展示把题目截图发给它后的整理流程
3. `03-workbook.png`：展示导出的 Excel 错题本
4. `04-review-reminder.png`：展示每日总结和二刷提醒

## 话题标签

#考公 #国考 #省考 #行测 #错题本 #备考工具 #AI工具 #开源项目 #效率工具 #资料分析 #判断推理
```
