# 后端接口契约与开发记录 - 日期 / 轮次:2026-09-19 / 第 1 轮 - 输入:00 / 10 / 20 / 30 / 40 / prototype / openspec `daily-plan-engine` / `tasks/0913-EnglishStudyAnalysis` 03§6、04、05§3/§4/§6/§8 - 应用的历史教训:无 - 结论:接口就绪,可对接 ## 独立理解 本需求的数据本质是:**课程只读、学习结果只写服务端**。要记的是孩子每一次可判定行为(拼读三关、听力播放、阅读完成、书写打卡、闯关逐题+汇总、请假、跳卡),以及由这些行为推导出的 SRS 项、当日五张卡状态、星星和连续天数。要算的是 Asia/Shanghai 的日型与周上下文、到期复习、卡完成聚合、顺延一次、升降档、日/周指标和微信原文。要持久化的是 `docs/data/learning/{child_id}/` 下的 profile / srs / days / plans / events JSONL / reports;课程文件只消费 `docs/data/curriculum/` 顶层对象 + `units/groups/books/letters`,不另造。V1 按主 agent 裁决 #1–#10:生成 `c1/c2/c3/c5/c6` 无 `c4`、星星分母 7、`card_skip` 仅服务端写、阅读只走 `/api/records`、`(childId,id)` 幂等、卡 `done` 只由服务端聚合。 ## 上游核对 ### 原型数据流 → 接口覆盖 | 原型交互(展示 / 操作) | 数据从哪来 / 存到哪 | 本轮接口 | | --- | --- | --- | | Today 五卡、进度 N/5、星星 x/7 | 展示计划真源 | `GET /api/plan/today` | | 拼一拼 4 词 × 3 关 | 写 phonics 事件,服务端翻卡 | `POST /api/events` type=`phonics` | | 听一听累计 ≥45s 且播放 ≥1 | 写 listening | `POST /api/events` type=`listening` | | 读一读听完整本 / 翻完 | 阅读唯一入口 | `POST /api/records`(转 1 条 `reading`) | | 写一写长按家长确认 / 微信「写好了」 | 成人门禁是前端;完成仍走契约 | `POST /api/plan/{date}/cards/c5/complete` 或 `writing_checkin` | | 闯关逐题 + 收星 | quiz + summary | `POST /api/events` `quiz` / `quiz_summary` | | 家长跳过听一听 | 卡变 skipped,孩子待办移除 | `POST /api/plan/{date}/cards/c2/skip` → 服务端 `card_skip` | | 请假休息态 | 无卡、提醒静默 | `POST /api/days/{date}/off` | | 连续天数 / 累计星 | days 真源 | `GET /api/days/streak` | | 家长周报数字 | 报告真源 | `GET /api/reports/weekly` | | 空周「还没有记录」 | `hasData=false` 仅 week | 同上,无事件周 | | 微信 morning / nudge / 周六 | 后端渲染原文 | `GET /api/plan/today/wechat-text?kind=` | | 日报空日不打扰 | wakeAgent=false / 空体 | `GET /api/reports/daily?format=wechat` | | 离线队列 / 成人解锁 / 书架文案 | 前端态,本轮不存 | 重放走 events 幂等;书架读 `plan/today` | | 课程周规则、字母、书 | 只读 curriculum | `GET /api/curriculum/week` | | 旧 localStorage 同步 | 一次性迁移 | `POST /api/srs/sync` | ### 上游编号落点 | 上游 | 本步落点 | | --- | --- | | 00 裁决 #1 五卡无 c4、7 星 | `plan_engine` 仅 `features.speaking=true` 才出 c4;`totalStars=len(cards)+2` | | 00 裁决 #2 `card_skip` | skip API 服务端写入,客户端 POST events 拒绝该 type | | 00 裁决 #3 阅读唯一入口 | `records` 增 `plan_item_id/mode/event_id`,进程内 ingest 一条 reading | | 00 裁决 #4 幂等 | `(childId,id)`;重放返回原 ids,不改 SRS/星 | | 00 裁决 #5 卡完成聚合 | `plan_engine.card_done`:c1 四词三关、c2 play+时长、c3 reading+mode、c5 checkin/complete、c6 题数+summary | | 00 裁决 #6 顺延一次 | `settle_yesterday`:未 carriedOver → deferred 并占今日容量;已 carriedOver → `skipped(carry_over_expired)` | | 00 裁决 #7 课程只消费 | `curriculum.py` 四文件 + 实际 schema 数组键 | | 00 裁决 #8 Hermes 脚本验收 | `deploy/hermes/…/scripts/*.sh` Git Bash 实测 | | 00 裁决 #9 书架映射 | 本轮只保证 `plan/today` 字段足够派生三条提示(前端 7.7) | | 00 裁决 #10 写一写门禁不改契约 | 仍是 `/complete` + `writing_checkin` | | 10 R1–R3 / R6–R14 | 计划即时生成、限额、课程诊断、SRS、仓促、sync、事件、records 兼容、报告、Hermes、原子写+gitignore+token | | 20 F1/F2/F10–F22、数据与状态 | 日型、五卡、hastyMs=1500、事件≤200、stars 只增、周六 15 题、升降档、5xx 文件名 | | 30 / prototype | 上表逐条接住;写字完成权在前端,后端不提供孩子可点的「自己完成」旁路以外的新 type | | 40 第 3 轮通过 | 无契约级返工 | | openspec daily-plan / events / report / hermes | 路径与字段未改名;`planItemId="{date}:{cardId}"` | | 05 §3 模型 / §4 API / §6 模块 / §8 Hermes | 路由六组 + records 兼容;skill/cron/README | | 04 状态机 / dueScore / 升降档 / 迁移 / profile | `srs_engine` + `days_support` + `default_profile`(04 §13 默认值) | | 03 §6 微信模板 | `wechat_templates`:≤3 行、无「说一说 / 8 颗星」、nudge 空体、周报「【本周英语报告」 | ### 本步自行补齐的小缺口(不改范围) 1. `writing_checkin` 若无 `planItemId`,服务端补 `{事件日}:c5`,便于 Hermes 脚本只传 type+payload。 2. `force` 拒绝条件按 **planItemId 日期前缀**,不按事件 `at` 的日历日(跨日补记仍锁当日计划)。 3. 日报/周报事件归属:`planItemId` 前缀 **或** `at` 落在该日,避免补记日 `wakeAgent` 误判。 4. 近窗内不足 3 个「已有计划的工作日」不降档,避免新孩子被当成 0 完成。 5. 每张卡 `done` 即 `days.starsTotal +1`;五卡全 done 无 skip 再 `+2`。`note_study_day` 只记学习日,不再重复加星。 6. `parse_week` 正确解析 `2026-W39`(避免把 `W` 替换成 `-W` 后截断)。 无影响功能范围的大缺口,**不建议返工**。 ## 接口契约 除特别说明外:query `child_id` 默认 `default`;时间 Asia/Shanghai;JSON `application/json`;微信原文 `text/plain; charset=utf-8`。联调入口 `http://127.0.0.1/estudy/api/...`(Nginx → 8120)。直连验收用 `http://127.0.0.1:8120/api/...`。 通用错误: | HTTP | 何时 | 响应 | | --- | --- | --- | | 400 | 校验失败 / 超限 / force 冲突 / 非 writing 调 complete | `{"detail":"<中文或英文原因>"}` | | 401 | 声明 `hermes`/`wechat` 身份但 token 无/错 | `{"detail":"invalid or missing X-Easy-Token"}` | | 404 | 卡或 SRS 项不存在 | `{"detail":"card not found: c2"}` / `item not found` | | 500 | 课程缺失或结构不合法 | `{"detail":"curriculum missing: hf-words.json"}` | `EASYSTUDY_TOKEN` 为空时不校验(本机开发)。非空时:Hermes 写接口带 `X-Easy-Token`;局域网前端不带 token 仍可 skip(`source=parent`)。 ### `GET /api/health` 用途:存活检查(既有,未改语义)。 响应:`{"status":"ok","version":"0.1.0"}` ### `GET /api/curriculum/week` 用途:本周单元、高频词组、字母游标、当前书与 D1/D2/D3。 请求:`GET /api/curriculum/week?date=2026-09-21` 响应示例(实测): ```json { "week": {"id": "W1", "rule": "短 a:-at -an -ap -ag", "words": ["cat", "hat", "bat", "mat"]}, "hfGroup": {"id": "A", "words": ["I", "a", "the", "is"]}, "letter": {"upper": "B", "lower": "b"}, "book": {"bookId": "stage-03__NobodyWantedToPlay", "title": "Nobody Wanted to Play", "day": "D2"} } ``` 错误:缺文件 → 500,`detail` 含文件名。 ### `GET /api/plan/today` 用途:取当日计划;文件不存在则即时生成并落盘。 请求:`GET /api/plan/today?child_id=docsnap2&date=2026-09-21` 响应要点(实测 52.7 ms 首次、再次 `generatedAt` 相同 `2026-09-19T08:12:44+08:00`): ```json { "date": "2026-09-21", "dayType": "weekday", "generatedAt": "2026-09-19T08:12:44+08:00", "version": 1, "week": {"id": "W1", "rule": "短 a:-at -an -ap -ag", "episode": null}, "cards": [ { "id": "c1", "type": "phonics", "title": "拼一拼", "icon": "🔤", "minutes": 3, "status": "pending", "stars": 1, "deeplink": "/learn/stage-03__NobodyWantedToPlay?plan=2026-09-21:c1&words=cat,hat,bat,mat", "items": [ {"itemId": "word:cat", "role": "new"}, {"itemId": "word:hat", "role": "new"}, {"itemId": "word:bat", "role": "review"}, {"itemId": "word:mat", "role": "review"} ] }, { "id": "c2", "type": "listening", "placeholder": true, "clipId": "book-audio:stage-03__NobodyWantedToPlay", "audioUrl": "/estudy/audio/books/stage-03/Nobody%20Wanted%20to%20Play.mp3", "targetSec": 45, "deeplink": null }, { "id": "c3", "type": "reading", "deeplink": "/book/stage-03__NobodyWantedToPlay/read?plan=2026-09-21:c3&mode=listen", "mode": "listen", "readable": false }, {"id": "c5", "type": "writing", "letters": "Aa", "words": ["the", "is"], "deeplink": null}, { "id": "c6", "type": "quiz", "deeplink": "/quiz/stage-03__NobodyWantedToPlay?plan=2026-09-21:c6&mode=review", "questions": [{"itemId": "word:cat", "qtype": "spell_pick", "filler": false}] } ], "summary": {"totalStars": 7, "earnedStars": 0, "completedCards": 0, "streak": 0, "level": "standard", "startedAt": null} } ``` 实测:五卡顺序 `c1,c2,c3,c5,c6`,无 `c4`,`sum(minutes)=17≤20`。周日 `date=2026-09-20` → `dayType=sunday`,`cards=[]`,`totalStars=0`。 ### `POST /api/plan/generate` 用途:显式生成;`force=true` 且当日已有带 `planItemId` 的事件 → 400。 请求:`POST /api/plan/generate?child_id=docsnap2&date=2026-09-21&force=true` 错误(实测):`{"detail":"当日已有学习记录"}` ### `GET /api/plan/today/wechat-text` 用途:Hermes 原文。`kind=morning|nudge|saturday`。空串 → **空体 200**。 请求:`GET /api/plan/today/wechat-text?child_id=docsnap2&date=2026-09-21&kind=morning` 响应(实测,3 行,含五卡图标与 `/today`,无「说一说 / 8 颗星」): ``` 小丫,今天的英语小任务来啦 🌟 🔤 拼一拼 👂 听一听 📖 读一读《Nobody Wanted To Play》 ✏️ 写一写 Aa + the is 🏆 闯关 点这里开始 👉 http://192.168.11.94/estudy/today ``` `kind=nudge` 且只剩 c5/c6 时含「还有 2 张卡」与「7 颗星」(`nudgetest` 实测)。五卡全 `done` → `Content-Length: 0`。 ### `POST /api/plan/{date}/cards/{cardId}/skip` 请求: ```json {"reason": "device"} ``` `reason` 建议 `device|time|other`。无 Hermes token → `source=parent`。已 skipped 再调不重复写事件。 响应:完整计划;该卡 `status=skipped`。404:卡不在当日计划。 ### `POST /api/plan/{date}/cards/{cardId}/complete` 仅 `type=writing`(c5)。写服务端 `card_complete`,卡变 `done`。 错误:非 writing → 400 `only writing cards can be completed manually`。 ### `POST /api/events` 单条或数组 ≤200。客户端允许:`phonics|quiz|quiz_summary|spelling|reading|listening|writing_checkin`。拒绝:`card_complete|day_complete|card_skip|sync|day_off|speaking|test`。 `id` 必须以 `evt_` 开头。`planItemId` 形如 `2026-09-21:c1`。 请求示例: ```json { "id": "evt_72bf4ec7a3c0426a972c543ecc2e0620", "childId": "docsnap2", "type": "phonics", "at": "2026-09-19T08:12:44+08:00", "planItemId": "2026-09-21:c1", "itemId": "word:cat", "payload": { "stage": "listen_pick", "firstAttemptCorrect": true, "attempts": 1, "responseMs": 2100, "hasty": false } } ``` 响应(实测): ```json { "ok": true, "ids": ["evt_72bf4ec7a3c0426a972c543ecc2e0620"], "srsUpdates": [{"itemId": "word:cat", "from": "learning", "to": "learning", "dueAt": "2026-09-20T00:00:00+08:00"}], "card": {"id": "c1", "status": "in_progress", "stars": 1} } ``` 同 id 重发:相同 `ids`,`srsUpdates=[]`,JSONL 不加行。201 条 → 400 `batch exceeds 200 events`。`type=card_complete` → 400 `type card_complete is not accepted from clients`。 各 type payload 必填: | type | 必填字段 | | --- | --- | | phonics | stage=`listen_pick\|scramble\|spell`, firstAttemptCorrect, attempts, responseMs | | quiz | qtype, correct, firstAttemptCorrect, attempts, responseMs, hasty, chosen, answer | | quiz_summary | total, correct(可选 hasty) | | spelling | firstAttemptCorrect, mistakeCount, completedAfterRetry | | listening | clipId, playCount, sentencePlayCount, durationSec, free | | writing_checkin | photo, source=`wechat\|parent` | | reading | 请走 records,不要直接 POST | `writing_checkin` 的 `source=wechat` 在配置了 TOKEN 时必须带正确 `X-Easy-Token`。 ### `GET /api/events` `?from=&to=&type=&planItemId=&limit=500`(`from`/`to` 为日期)。 响应:`{"events":[...],"count":1}` ### `GET /api/srs/due` `?date=&kinds=word,phoneme&limit=20` 返回 `items[]`,已按 `dueScore` 降序;只含 `dueAt ≤ 当日 23:59`。 ### `GET /api/srs/items` `?status=&kind=` 项含 05 §3.2 字段:`itemId/status/dueAt/wrongCount/history/sources/...` ### `POST /api/srs/items/{itemId}/reset` 置 `new`,保留 `history`。路径允许 `word:cat`。 响应(实测):`status=new`,`history` 仍 1 条。404:项不存在。 ### `POST /api/srs/sync` 请求: ```json {"child_id": "synctest", "lastBookId": "stage-03__x", "states": [ {"bookId": "...", "words": {"cat": {"status": "mastered", ...}}} ]} ``` 响应:`{"migratedItems":19,"migratedEvents":N}`。原样再传 → `0,0`。`mastered→weekly`,跨书同词合并,不倒退服务端已推进状态。 ### `POST /api/records`(兼容扩展) 旧 body 仍成功,响应保持 `{ok,id,record}`。新增可选 `plan_item_id`、`mode`=`listen|read|review`、`event_id`。服务端转一条 `reading`(`id=event_id` 或 `evt_rec_`+record.id)。`completed && unknown_words` 的词进入 SRS `new`,`sources` 含 `reader`。 旧 body 实测:`{"ok":true,"id":"20260919-081244-c84e","record":{...,"plan_item_id":null,"mode":null}}`。 ### `GET /api/reports/daily` `?date=&format=json|wechat` json 实测(完成 c5 + 跳过 c2): ```json { "date": "2026-09-21", "earnedStars": 1, "completedCards": ["c5"], "skippedCards": ["c2"], "deferredCards": [], "streak": 0, "highlights": ["今天有认真完成任务"], "hastyCount": 0, "tomorrow": "cat / hat", "wakeAgent": true } ``` 无事件日:`wakeAgent=false`。`format=wechat` 且 `wakeAgent=false` → 空体 200。23:30 scheduler 落盘;缺失时即时聚合。 ### `GET /api/reports/weekly` `?week=2026-W38&format=json|wechat` 有数据周字段(实测无 `speaking`):`week, hasData, completedDays, plannedDays, completionRate, stars, streak, firstTryRate, weakWords, weakPhonemes, confusionPairs, weakHfWords, newMastered, booksRead, unknownWordsChange, skippedCards, expiredCarryovers, hastyCount, levelChange, nextWeek`。 空周:`{"hasData":false,"week":"2026-W01"}`。 wechat 实测开头:`【本周英语报告 W38】...`,链接 `/parent/report?week=`。 ### `POST /api/days/{date}/off` ```json {"reason": "rest", "source": "parent"} ``` `source=hermes|wechat` 且配置了 TOKEN 时必须带对 token。计划改为 `dayType=day_off`、`cards=[]`,写 `day_off` 事件。当周 `graceLeft` 减 1,streak 不断。 响应含 `ok/plan/streak`。 ### `GET /api/days/streak` ```json {"streak": 2, "graceLeft": 1, "starsTotal": 0} ``` 工作日 `done≥minCardsForDay(默认4)` 记学习日;周日不计不断;`graceLeft` 按**查询日所在 ISO 周**。请假日与查询日跨周时,当周 grace 不变(「每周一次」记在请假日那一周)。 ## 数据结构与存储 根目录:`docs/data/learning/{child_id}/`(gitignore)。路径分桶锁 + `.tmp` + `os.replace`;JSONL 加锁追加。 ``` profile.json # 04 §13:nick、限额、hastyMs=1500、cursors、features.speaking=false、publicBaseUrl srs.json # items[itemId] 状态机 days.json # studyDays、off、graceByWeek、starsTotal plans/YYYY-MM-DD.json events/YYYY-MM.jsonl reports/daily/YYYY-MM-DD.json reports/weekly/YYYY-Www.json ``` 课程只读:`docs/data/curriculum/{phonics-units,hf-words,ort-sequence,letters}.json`(顶层对象,数组键 `units/groups/books/letters`),mtime 缓存,缺文件 `CurriculumError`。 `itemId`:`word:{lower}` / `phoneme:{ipa}`。`dueScore = overdueHours + wrongCount×8 + confusionWeight×4 − passCount×2`。 SRS:`new→learning→weekly`(不同日 ≥2 次 correct,同日只 1 个 correctDay;不足 `extendCount≤2` 各延 3 天)→`monthly`→`mastered`(90 天抽检回 weekly)。`pass` 不推进。选择题首次对且 `responseMs≥1500` 才 `correct`;`<1500` 且错 → `hasty` 只加 `hastyCount`。 卡状态:`pending → in_progress → done`;`deferred` 只一次;`skipped` 不占完成、不加该卡星。服务端卡完成写 `evt_srv_{date}_{cardId}`;五卡全 done 无 skip 写 `day_complete` 并 +2 星。 备份:`python deploy/backup/backup_learning.py --dest