13 Commits
Author SHA1 Message Date
cat-shark a162bcd043 fix(ci): 加固流水线工具链检查与部署回滚
- 新增 Preflight runner toolchain:显式校验 docker/curl/kubectl,缺失即报错并尝试 apk 自愈
  (2026-11-22 事故:act_runner 官方镜像无 docker CLI,host 模式下 docker login 直接 127)
- Checkout 改为按 SHA 浅拉取,不支持时回退完整克隆
- Setup kubectl 复用镜像内置 kubectl,缺省时才下载
- 移除已废弃的 kubectl --record(1.30+ 已删除),改用 annotate 记录 lpt/deployed-image
- Rollback 增加 deploy_attempted 标记,避免前置步骤失败时回滚掉上一次成功部署
2026-11-22 22:45:55 +08:00
cat-shark cf7518c320 feat: 回忆去掉结束状态,新增按标签查相关导图
- 删除 status/endedAt 与结束接口,回忆只能继续编辑,用时继续累计
- 新增 review_recall_scope_tags 索引表与回填迁移,按标签交集查询保存导图
- 新增 GET /review/recalls/related,分页在 SQL 完成;列表支持 excludeRecallNum
- 范围匹配不到知识碎片时拒绝开始回忆(SCOPE_EMPTY)
2026-11-22 21:41:31 +08:00
cat-shark cf3fa6418b perf: 补齐查询索引并批量失效 AI 任务 2026-11-21 17:47:20 +08:00
cat-shark bc7888ab8c perf: 报告详情把会话任务名并入同一次批量查询 2026-11-21 17:36:41 +08:00
cat-shark 81fdeb5ea2 perf: 批量更新优先级与标签改名,按范围收敛隐私清算 2026-11-21 17:06:16 +08:00
cat-shark e96cb3e3d3 docs: 补充查询次数与加锁形态规则 2026-11-21 16:54:13 +08:00
cat-shark 9c3e22680d fix: 修复回忆列表并发死锁并收敛多表查询 2026-11-21 16:54:07 +08:00
cat-shark 4b65eb57b1 refactor: 回忆改用独立存储与请求响应 DTO,服务按域拆包 2026-11-20 09:38:16 +08:00
cat-shark 5ff692b768 chore: 接入 Checkstyle 门禁 2026-11-20 09:36:46 +08:00
cat-shark 5310f480ce docs: 补齐代码规范与评审清单,记录 HTTP 边界与 Checkstyle 决策 2026-11-20 09:36:38 +08:00
cat-shark ec2f74bf18 docs: 接入共有技能与笔记校验入口,说明 .agents 只放本仓独有内容 2026-11-18 15:01:18 +08:00
cat-shark 27ddf8be5a docs: 规则与技能迁入 .agents/,并接入决策笔记
- roles/ 与 skills/ 迁移到 .agents/ 下,AGENTS.md 引用同步
- 收录 8 篇决策笔记到 .agents/notes/
- .rgignore 排除 archived 历史快照
2026-11-18 15:01:05 +08:00
cat-shark eb3da2e74a fix: 部署流水线改用 https 拉取代码(Gitea 已不再监听 80 端口) 2026-11-08 14:48:26 +08:00
326 changed files with 11330 additions and 4446 deletions
@@ -0,0 +1,43 @@
# Agent Note: 行级数据隔离由租户拦截器统一注入,业务代码不写 created_by
Status: implemented
## Problem
多租户表全靠手写 `WHERE created_by = #{当前用户}`。漏一处就是一个越权读:查询单条记录时不带条件,
别人的任务、报告、残片就会被正主之外的请求读到,而且这类缺口在单模块测试里看不出来——测试用的都是同一个
登录用户。逐个 mapper 补条件也不可行:新增查询随时会漏,评审也盯不住。
## Decision
持久层统一挂 `TenantLineInnerInterceptor`(`MybatisPlusConfig`),在 SELECT / UPDATE / DELETE 上自动追加
`WHERE created_by = #{当前用户}`,业务代码与 mapper XML 一律不写这个条件。
- 租户列固定为 `created_by`,取值优先 `TenantContext` 里显式声明的身份(后台线程:AI 任务、定时收敛),
没有就走 `StpUtil.getLoginIdAsString()`。
- 免过滤表白名单 `EXCLUDE_TABLES`:`user`、`flyway_schema_history`、`databasechangelog`、
`databasechangeloglock`、`ai_usage_records`。加表进白名单等于放弃该表的隔离,必须附带「为什么这张表不是租户表」。
- 拦截器注册顺序固定为「多租户 → 分页」。分页的 `count` 语句从当前已处理的 SQL 派生,顺序颠倒会让 `total`
把其他用户的行也算进去——`records` 仍然正确,只有总数错,靠肉眼几乎发现不了。`MybatisPlusConfigTest`
守住这个顺序。
## Alternatives considered
- **每个 mapper 手写 `created_by` 条件** — 最直白,也不引入 SQL 改写。放弃的原因是覆盖面靠人记忆:所有查询
(含以后新增的)都要记得加,漏一处就是一个静默的越权读,而这类错误不会让任何测试变红。
- **Service 层统一用 AOP 在方法入口校验归属** — 能在业务语义上给出更清楚的报错。但它只管「已取出的记录」,
集合查询(列表、分页、汇总)依然会在 SQL 层返回别人的行,等于把越权数据读进内存再挑出去。
## Consequences
- **收益**:新增查询默认就是安全的,越权读从「写测试才能发现」变成「默认不存在」。归属校验也顺带免费:
查不到别人的记录,自然返回空。
- **代价与已知上限**:所有绕过 SQL 的路径都不受保护——手写 JDBC、直接执行的原生 SQL、跨表 join 里别名的列
需要人工确认;免过滤表白名单是一处集中的风险点,改它等于改安全边界。出现「某接口查不到数据但库里明明有」
时,先查是不是白名单或 `TenantContext` 没设置,而不是去业务代码里找条件。
## Verification
- 配置与顺序:`lpt-be/src/main/java/com/guo/learningprogresstracker/config/MybatisPlusConfig.java`,
`MybatisPlusConfigTest` 断言「租户拦截器先于分页拦截器」。
- 白名单:同一个类里的 `EXCLUDE_TABLES`,静默新增表项即改动安全边界。
@@ -0,0 +1,47 @@
# Agent Note: AI 用量口径——null 不等于 0,计价在 lpt-ai 侧冻结
Status: implemented
## Problem
lpt-ai 的调用会把 token 用量报回 lpt-be,供白名单管理员看总量与费用。这里有三个容易写错、写错还不会报错的地方:
1. 上游有时候根本不返回 `usage`。如果把「没上报」记成 0,用量面板会把一批**未知消耗**显示成「这几次调用没花钱」,
账单与面板永远对不上,而且没人能发现差了。
2. 价格会变。若聚合时按当期价目回算历史,改一次价历史账全部重写,月度对账失去意义。
3. `ai_usage_records` 里还有 `/fetch-title` 这类不消耗 LLM 的记录,混进统计会把「调用次数」和「模型成本」搅在一起。
## Decision
- **`null` 与 `0` 严格区分**:`prompt_tokens` / `completion_tokens` 等列为 `NULL` 表示上游未上报,`0` 表示上游
明确上报为 0。不得用 0 顶替 null。`unreported_usage_calls` 正是靠这个区分统计出来的。
- **计价在 lpt-ai 侧冻结**:`cost_usd` 在任务结算时按当期价目算好随记录落库,lpt-be 只做聚合与汇率换算
(`lpt.ai-usage.usd-to-cny`),改价不重写历史账。
- **统计口径只看 `is_llm_call = 1`**:不消耗 LLM 的调用照常落库(用于调用量排查),但不进用量面板。
- **`user_id` 只是分组维度,不是租户列**:本表在 `EXCLUDE_TABLES` 中,`user_id` 用于按用户分组与筛选;
若改成租户过滤,管理员只能看到自己触发的调用,面板等于永远是空的。
- **上报幂等交给出库方**:`POST /internal/ai-usage/records` 以 `record_id` 唯一索引去重,因此「推送成功但响应
丢失」的重复推送是安全的;失败重试由 lpt-ai 侧 outbox 负责,4xx 属确定性拒绝,丢弃该批并计数,不无限重试。
## Alternatives considered
- **在 lpt-be 侧按当期价目聚合时现算成本** — 少存一列,改价立刻全局生效。放弃是因为它把历史账变成了易变量:
一次调价会让过去几个月的报表同时变化,月初对账没有稳定基线,而账本该是只读的。
- **把「未上报」压成 0,只留一个总数** — 面板实现最简单,表结构也少一列。放弃是因为它抹掉了「我们不知道花了多少」
这个事实:额度异常时无法区分「真的没用量」和「上游没给 usage」。
- **让 lpt-be 反查 lpt-ai 面板取历史用量** — 不用落库,也不必设计上报协议。但面板只是最近若干条的环形缓冲,
进程重启即丢,「长期账本」这个诉求直接落空。
## Consequences
- **收益**:用量面板的数字可以对账——已知消耗、未知消耗、非 LLM 调用分得开;改价不动历史。
- **代价与已知上限**:lpt-be 必须相信 lpt-ai 报来的 `cost_usd`,价目正确性完全取决于 lpt-ai 的 `admin/pricing.ts`
与节假日表(每年需更新)。出现「面板金额与上游账单对不上」时,先核 lpt-ai 的价目与峰谷窗口,再怀疑聚合逻辑。
## Verification
- 表结构与索引:`lpt-be/src/main/resources/db/migration/V20261010_4__add_ai_usage_records.sql`、
`V20261010_5__add_user_id_to_ai_usage_records.sql`。
- 口径与 null 处理:`src/main/resources/mapper/AiUsageRecordMapper.xml`(`is_llm_call = 1` 过滤、
`unreported_usage_calls` 用 `CASE WHEN prompt_tokens IS NULL`),`AiUsageServiceImpl` 的聚合。
- 白名单与令牌:`AiUsageProperties`、`WebMvcConfig` 对 `POST /internal/ai-usage/records` 的排除。
@@ -0,0 +1,50 @@
# Agent Note: 用量归属 mark 跟着请求走,路由信息不进 params
Status: implemented
## Problem
用量要能按用户切分,但 lpt-ai 不知道调用方是谁:它只收到一个 `POST /ai/tasks` 的请求体(`type` + `params`)。
在 lpt-be 侧「提交后再写回归属」也不成立——lpt-ai 可能比 lpt-be 的写回更早结算,形成归属与账目赛跑。
## Decision
归属标记由调用方带过来:`POST /ai/tasks` 接受**顶层**可选字段 `callerRef`(限 64 字符),lpt-be 的
`AiServiceClient` 填当前用户 id,lpt-ai 原样透传,结算时写进用量记录,lpt-be 落到 `user_id`。
三条硬约束,改动时必须同时守住:
1. **不放进 `params`** —— `params` 会喂给 prompt 模板,混进去等于把内部 id 塞进模型输入;
2. **不参与幂等键** —— 幂等键是 `type + params`,`callerRef` 进去会让同一份输入因调用方不同而重复调 LLM;
3. **不进 prompt** —— 它只是记账标记,不是上下文。
配套两条:
- **取不到身份就不带**:`currentCallerRef()` 拿不到登录态时返回 null,请求体里整个键都不写,这笔用量记为「未归属」。
绝不能因为取不到用户让 AI 调用失败。
- **复用已有任务沿用原 `callerRef`**:那次 LLM 调用只发生了一次,账算在原调用方头上;复用方没有产生新 token,
也就不会有新的用量记录。
## Alternatives considered
- **lpt-be 提交任务后写回归属,等结算时再查** — 不用改 AI 侧协议。但它依赖「写回早于结算」的时序假设,
而任务是异步的,lpt-ai 完全可能先结算;一旦发生就是归属丢失或错挂,且没有信号提示。
- **把 `callerRef` 塞进 `params` 顺带透传** — 不必新增顶层字段,实现最省事。放弃是因为 `params` 同时是 prompt
模板输入和幂等键的组成部分,一个记账字段混进去会同时污染模型输入和去重语义。
- **让 lpt-ai 反查 lpt-be 拿归属** — 归属只在一处定义。但那是服务间反向依赖,AI 服务要为此持有一个 lpt-be 的
查询凭据与失败降级路径,为一个记账字段引入的耦合远大于收益。
## Consequences
- **收益**:归属在 LLM 调用之前就已确定,没有「上报先到、归属还没写回」的竞态;AI 服务不需要知道 lpt-be 的任何
用户概念,只透传一个不透明字符串。
- **代价与已知上限**:归属完全依赖调用方老实带上,`callerRef` 是自由字符串——lpt-ai 不做校验也不该做校验,
伪造与错填由 lpt-be 侧负责(它填的是 `StpUtil` 里取到的登录 id)。未归属记录必须作为单独一行存在,
不能为了报表好看塞给某个用户。
## Verification
- 调用方:`src/main/java/com/guo/learningprogresstracker/service/impl/AiServiceClient.java` 的 `currentCallerRef()`
与请求体组装(顶层 `callerRef`),`AiServiceClientAttributionTest`。
- 承接方:lpt-ai `src/routes/ai.ts` 与 `src/task-queue.ts` 的 `callerRef` 透传,报表侧
`breakdown?groupBy=user`(未归属 `key` 为 null、`label` 为「未归属」)。
@@ -0,0 +1,58 @@
# Agent Note: 自由回忆只保存当前导图与本次资料
Status: implemented
## Problem
自由回忆需要持续保存当前输入、提供本次资料,并允许下次接着最后的导图回忆。为每次自动保存维护内容历史,会把编辑、恢复、原文查看和 AI 请求都绑定到版本模型。业务只要求每次回忆的最终内容;不兼容的回忆数据允许一次性删除。
## Decision
每次回忆的 `RecallDocument` 只保存当前 `detail.expression` 和单一 `reference` 来源集合。自动保存覆盖当前导图,不保存中间导图、表达历史、资料历史或对应的版本字段。不同回忆仍是独立记录,各自保留最后保存的导图;“只保留当前内容”不表示整个账号只能有一条回忆记录。
本次资料在创建回忆时取一次,来源不可访问时原地清除正文及依赖它的 AI 结果。下一次创建回忆重新取材。DTO 名称 `ReferenceSnapshot` 只表示本次唯一来源集合,不包含版本号、历史列表或切换入口;普通查询和保存不会生成另一份资料。
`writeToken` 是覆盖写入保护:成功写入替换当前随机令牌,不维护递增内容编号或旧令牌列表。草稿只保留最近一次写入的请求编号与摘要,响应丢失时允许同一请求重试。其他业务收据只保存标识和摘要,不保存历史正文。
创建回忆时,服务端按当前用户、规范化标签集合及并集/交集方式选择最近已结束记录。标签顺序、空格或大小写不构成不同范围,组合方式不同则范围不同。新回忆复制最后导图的文字、节点标识及结构,清空此前帮助标记;资料、提示请求和累计耗时从本次重新建立。没有可用记录时初始化空白根节点。未完成草稿通过恢复接口编辑。
资料目录由 `GET /review/recalls/{num}/references` 分页返回标题与摘要,正文由同一路径下的 `/sources/{sourceId}` 获取。详情只返回资料汇总,避免每次草稿上传都携带全量正文。资料接口不接受版本参数。
AI 执行期间可以暂存一份提交输入,以便重启接手和结果引用校验;终态成功写回后清除 `params_json`,不能据此建立可回看的编辑过程。成功结果保留提示/查漏内容及必要请求信息,不替换当前导图。已显示帮助或原文的事实单独保留,供 AI 区分资料与已知帮助;这些事实不带表达版本或中间导图。具体输出与重试规则归属[AI 协议决策](../../../../../lpt-ai/.agents/notes/implemented/architecture/2026-11-16-recall-strict-protocol.md)。
## 删除范围与同步升级
`V20261116_1__replace_recall_storage.sql` 删除 `review_recall_records`,重建自由回忆的当前记录、请求、收据与所有者锁表,清除 `RECALL_COMPARE`、`TAG_RECALL_COMPARE`、`RECALL_HINT` 和 `RECALL_CHECK` 的既存任务。迁移不回填不兼容的表达历史与资料历史,已执行的历史 Flyway 脚本保持不变。
任务标准导图 `review_standard_mind_maps` 与标签导图 `review_tag_mind_maps` 保留,`StartTask` 的生成和编辑能力保留。被移除的是依赖旧对比记录表的查询、写入、统计和浏览链路,不能重新从旧任务类型写入该表。
表达式与提示结果增加字段后,旧版 `document_json` 不做读取兼容:`V20261118_1__clear_incompatible_recall_data.sql` 清空既有回忆、回忆请求/收据与回忆 AI 任务;运行中遇到无法解析的残留行直接逻辑删除并返回 `STORED_DATA_INVALID`,不保留、不隐藏。旧格式 AI 结果读取失败时按“旧版本格式,请重新请求”展示,不再冒充核验失败。
前端、后端与 AI 服务需要在同一环境同步升级;内容协议没有旧形状兼容适配。技术协议标识、模型名和计价信息保留,它们不表示用户内容版本。
## 关联记录与归属
本篇维护当前内容存储、范围匹配、写入保护、临时 AI 输入和删除迁移。[前端工作区决策](../../../../../lpt-fe/.agents/notes/implemented/feature/2026-11-16-current-recall-workspace.md)维护入口与交互,[AI 协议决策](../../../../../lpt-ai/.agents/notes/implemented/architecture/2026-11-16-recall-strict-protocol.md)维护严格输出和调用预算。三篇部分相关,分别保留;[租户隔离](2026-05-27-tenant-line-row-isolation.md)和[计费规则](2026-10-10-ai-usage-accounting-rules.md)继续维护各自决定。
[2026-11-22 的决定](2026-11-22-recall-map-without-status.md)取代了本篇的两条内容:新建回忆不再自动带入同范围已结束导图,回忆记录也不再区分进行中/已结束(`status`、`endedAt` 与结束接口均已删除);其余当前内容存储规则仍以本篇为准。
## Alternatives considered
- 只隐藏编号和历史入口:可以复用已有异步绑定,改动面较小;但后端仍保存编辑过程,与只保留当前内容的业务要求冲突,因此删除整个内容版本模型。
- 把不兼容回忆回填为当前结构:能保留个人历史;但需要维护旧格式转换与历史引用,业务已允许删除这些数据,因此使用一次性清理迁移。
- 无写入保护地覆盖当前图:实现更短,也没有内容版本;但两个页面可能静默覆盖彼此输入,因此使用单个随机写入令牌与请求幂等控制。
## Consequences
覆盖保存把正文存储限制在每次回忆的一份当前内容,写入保护继续防止多页面静默覆盖。代价是无法恢复某一步编辑,也不能在本次回忆里刷新或切换资料历史;写入令牌与幂等摘要只能解决请求冲突,不能提供内容回滚。
删除迁移会清除既存对比记录和不兼容的自由回忆记录。保留任务标准导图和标签导图不意味着保留依赖这些图的旧回忆对比记录。代码回退不能还原已删除内容,发布时需要明确接受这个数据结果。
若业务以后确实需要编辑回滚、回忆内更新资料或长期保留请求输入,必须重新评估存储与清理规则;不得以恢复编号字段或长期保留 `params_json` 的方式隐式引入历史。
## Verification
- `ReviewRecallServiceIntegrationTest` 校验多次覆盖后先前正文不再落盘、同范围新建仍空白、范围差异、租户隔离、资料分页,以及 AI 终态清除临时输入。
- `ReviewRecallControllerIntegrationTest` 校验无版本 DTO、原文读取与旧请求拒绝;`RecallAiResultValidatorTest` 校验引用是否确实来自本次输入。异步结果不能覆盖后续编辑由服务集成测试验证。
- `RecallStorageMigrationTest` 验证重建存储并删除旧记录、保留任务标准导图和标签导图。迁移在 H2 的 MySQL 模式执行;`MigrationIndexKeyLengthTest` 额外复算 InnoDB 索引键长度,不能替代真实 MySQL 的 DDL 验证。
- 使用 JDK 17 运行 `./mvnw clean test`。
@@ -0,0 +1,39 @@
# Agent Note: 自由回忆记录实际用时与有效时间
Status: implemented
## Problem
自由回忆页需要同时显示“实际用时”和“有效时间”,并按在场段与有交互活动分别累计。记录原先只有 `activeDurationMs`(有效时间)一个累计值,页面既拿不到“服务端已确认 + 本段未上传”的实时总量,也没有实际用时可展示。
直接用 `createdAt → endedAt` 推实际用时实现最省,但草稿允许跨天恢复,会把离开的时间全部算进去。实际用时只用于单条回忆展示,不参与任务统计,没有必要像 `active_duration_ms` 那样为聚合新增数据库列。
## Decision
回忆计时同时累计两个值,契约与页面口径详见[前端工作区决策](../../../../../lpt-fe/.agents/notes/implemented/feature/2026-11-16-recall-time-metrics-and-break.md):
- `Timing` 增加 `segmentActualMs`,与 `segmentActiveMs` 一样是当前编辑段的累计值,单调递增。缺省时取 `segmentActiveMs` 与已确认实际用时的较大值,滚动发布中的旧前端仍可保存并保持单调。
- `RecallDocument` 增加 `acceptedSegmentActualMs`,与 `acceptedSegmentMs` 一同在草稿/结束时累加;`resume` 把两者都归零,开启新编辑段。
- `RecallDetail` / `RecallSummary` 增加可空 `actualDurationMs`。旧记录读不到该字段时为 `null`,不回填;旧草稿第一次携带实际用时后从 0 开始累计。
- 服务端只校验 `0 <= segmentActiveMs <= segmentActualMs`,且两者都不超过本次编辑段墙钟(保留 5 秒容差)。闲置截断和休息冻结由客户端计时器决定,服务端不推断。
- 实际用时只存在回忆文档 JSON 中,不新增 `actual_duration_ms` 列:它不参与 `sumTaskDuration` 聚合,列表与回看都从文档读取。以后确实需要聚合再加列。
- 每次保存成功后,前端把本次上传的段值记为已确认基线,展示值 = 服务端累计 + 未确认增量;恢复草稿重置基线。
## Alternatives considered
- **用 `createdAt → endedAt` 作为实际用时**:不需要改契约;但跨天草稿会把离开时间全算进去,显示几十小时,因此否掉。
- **新增 `actual_duration_ms` 列**:查询与聚合更直接;但当前没有按实际用时聚合的需求,SQL 迁移和冗余同步的代价换不来收益,因此只存文档 JSON。
- **客户端只上报增量**:服务端无需保存 accepted 值;但请求丢失重试、幂等重放和并发写入会让增量边界不可验证,因此沿用累计值 + 服务端 accepted 基线。
- **完全由服务端按墙钟推算实际用时**:不需要客户端计时;但服务端不知道标签页隐藏、休息和闲置,会把整夜算进去,因此保留客户端段计时,服务端只做上限校验。
## Consequences
实际用时的精度依赖前端时钟与闲置窗口,服务端只能拒绝超过编辑段墙钟的值,不能识别一段“5 分钟宽限”是否合理。换设备或清缓存不会丢失已上传的累计值,但未上传的当前段本来就不属于服务端记录。
旧记录没有 `actualDurationMs` 时,前端只显示有效时间,不显示错误的 0。服务端与前端需要同批发布;旧前端缺少 `segmentActualMs` 时按有效时间处理,旧记录不会被补算。
## Verification
- `ReviewRecallServiceIntegrationTest#actualDurationAccumulatesAcrossSegmentsAndNeverDropsBelowActive` 校验跨段累加、恢复归零、旧载荷兼容、实际小于有效与实际超过墙钟被拒绝。
- `ReviewRecallControllerIntegrationTest` 校验接口序列化与既有行为不回退。
- 使用 JDK 17 运行 `./mvnw clean test`。
@@ -0,0 +1,38 @@
# Agent Note: 自由回忆提示锚点、表达式配色与核验原因
Status: implemented
## Problem
提示结果缺少挂载位置:`HintNode.parentId` 只描述提示内部,前端只能挂到根节点。表达式也没有配色字段,用户改色无法持久化。同时 BE 对空提示、判定引文和精确偏移的规则比 AI 服务更严,正常结果可能被判为 `INVALID_AI_RESULT`;失败原因被压缩成一句泛化文案,用户不知道哪条规则没过。`claimPendingTasks()` 每次扫描都执行 RUNNING 回收,条件 UPDATE 在无匹配行时也产生大量日志。
## Decision
- `HintItem` 增加 `anchorNodeId`。LEAF/TREE 必须引用本次提交表达式中的真实节点(根节点 id 也可);KEYWORD/QUESTION 必须为 null。LEAF 恰好 1 个节点;TREE 继续校验单根、无环、≤5 节点。
- 表达式节点增加可选 `style {background, color}`,只接受两个 `#RRGGBB`。配色是展示信息:`RecallAiService.bounded` 在构造 AI 输入时剥掉 style,模型契约保持不变;`carryContent` 复制到新回忆时保留用户显式配色,但清空提示 provenance。
- 核验范围此后收窄:结构、提示锚点、LEAF/TREE 形状先由 lpt-ai 校验,BE 侧只复核引文是否真的来自本次输入,见[校验归属决策](2026-11-18-recall-validation-ownership.md)。
- 校验失败返回可核验的原因(结构与字段/分析判定/提示结构/查漏依据/表达依据/分析覆盖等)。`RecallAiFailure.fromException` 保留校验器/客户端的固定安全文案;`RecallAiService.fail` 使用它;`RecallAiClient.remoteFailure` 只从 AI 服务的固定阶段标记中提取原因,不读取供应商原文。
- `claimPendingTasks()` 的回收最多每 60 秒执行一次;扫描仍为 3 秒,抢占与结果回写不变,只有真正回收任务时打日志。
## Alternatives considered
- **继续挂根节点**:无需契约变更;但树/叶的结构关系无法落到用户导图,因此增加锚点。
- **不持久化配色,只做来源默认色**:实现最小;但用户无法按自己的习惯整理视觉,因此增加 style 字段并剥离 AI 输入。
- **把判定引文限制成只能本单位**:语义更整齐;但 AI 服务允许跨单位上下文,模型正常输出会被 BE 误杀,因此对齐为 EXCLUDED 必须有本单位引文。
- **保留泛化错误**:实现简单;但用户无法定位规则,因此返回固定阶段原因。
- **每次扫描都回收任务**:恢复最快;但正常运行时只会制造 SQL 噪声,因此 60 秒节流。
## Consequences
锚点让叶/树能挂到用户已有结构下,但 AI 等待期间用户删除锚点时会回退根节点;前端需要显示这个回退。
配色进入表达式文档,但没有新增数据库列;新格式记录未选色时按来源默认色或普通节点显示。上一版本保存的文档缺少新增 record 组件,按破坏性变更处理:迁移清空既有回忆,运行中遇到无法解析的残留行直接逻辑删除并返回 `STORED_DATA_INVALID`,不增加读取兼容分支。AI 输入剥离 style 后,模型无法感知用户配色,这是刻意的展示/语义分离。
空提示和跨单位判定引文不再被误判为失败;真正不合规的结果仍失败,并返回具体类别。
回收节流最多延迟约一分钟发现崩溃任务;这是可接受的恢复时间。
## Verification
- `RecallAiResultValidatorTest` 现只覆盖引用一致性与结构错乱 fail-closed,结构类断言由 lpt-ai 的 `recall.test.ts` 承担(见[校验归属决策](2026-11-18-recall-validation-ownership.md))。
- `ReviewRecallServiceIntegrationTest` 覆盖 style 合法/非法、实际用时与有效时间的既有累加不回退。
- `AiTaskServiceImplTest#claimPendingTasks_reclaimsStuckRowsAtMostOncePerMinute` 覆盖回收节流。
- `RecallAiClientTest` 保持错误分类与远程清理行为;`ReviewRecallControllerIntegrationTest` 覆盖接口序列化。
- 使用 JDK 17 运行 `./mvnw clean test`。
@@ -0,0 +1,40 @@
# Agent Note: 记忆回忆链路的校验归属与严格解析收窄
Status: implemented
## Problem
回忆链路的 JSON 出入口原先用一份自建严格 ObjectMapper 覆盖了三个方向:前端请求、落盘的 `document_json`、lpt-ai 返回的 AI 结果。这份严格同时打开 `FAIL_ON_UNKNOWN_PROPERTIES` 与 `FAIL_ON_MISSING_CREATOR_PROPERTIES`,后者在 record 上对**每个构造器组件**生效(`PropertyValueBuffer._findMissing` 在 `isRequired()` 之后立即检查该 feature),因此可空组件也变成必填。
后果是一个正常主流程被整单拒绝:`ExpressionNode.style` 在契约里是可选的(前端类型 `style?: NodeStyle | null`,`fromRecallElixirNode` 只在用户显式选色时才写),而「用 AI 提示把节点挂到导图」产生的节点不带 `style`。只要导图里有一个未配色的非根节点,`PUT /review/recalls/{num}/draft` 与 `POST .../end` 都返回 `400 INVALID_INPUT`「这些内容没能读取」。这个问题只有前端真实请求会触发——Java 测试用 record 序列化生成 body,`style` 永远以 `null` 出现而不是缺席,因此全部单测是绿的。
进一步的审计发现:`RecallAiResultValidator` 把 lpt-ai 的 `normalizeRecallResult` 又重新实现了一遍(结构、条数上限、字段枚举、提示树形状、锚点存在性、分析状态归一、长度上限),而且两套规则已经分叉(限制说明 lpt-ai 上限 5 条、后端 12 条;exclusion 引文的后端判定比 AI 服务更严)。2026-11-16 那次「正常结果被判 `INVALID_AI_RESULT`」的事故正是分叉的直接代价。
## Decision
校验按「谁产出、谁保证」划分,同一个规则不写两遍。
- **外部请求(HTTP body)**:`RecallJson.readInput` 只拒绝未知字段、标量强转与浮点转整,不再要求可选字段必须出现。必填语义由 `ReviewRecallService.validateExpression` / `timing` / `ReviewRecallStore.guard` 承担,它们能给出比 Jackson 更具体的理由。
- **落盘读取(`document_json` / AI 结果回读)**:`RecallJson.readStored` 不做结构限制,形状由写入方保证;读不出来即视为数据损坏。`ReviewRecallStore.load` 与 `RecallPrivacyService.readable` 的 catch 从 `IllegalStateException` 扩到 `IllegalStateException | NullPointerException | ClassCastException`,继续维持「损坏即删行」而不静默隐藏——但仍不捕获任意的 `RuntimeException`,数据库与事务异常必须照常上抛,不能因为一次读失败就删掉用户数据。
- **AI 结果**:结构、条数、枚举、提示树形状、锚点、分析覆盖全部归 lpt-ai 的 `normalizeRecallResult`。后端 `RecallAiResultValidator` 只保留一条不变量:模型声称的引文与表达依据,必须能在本次输入原文里按偏移逐字取回(含不切开代理对)。本服务是落库与展示的边界,这条线必须自己持有,不能靠上游自证。
- **序列化配置不动**:`RecallJson.write` 同时产出幂等摘要(`receipt_key` / `payload_hash`),任何序列化 feature、Module 或字段顺序的变动都会让既有收据失配、把重试判成 `REQUEST_ID_CONFLICT`。因此本轮只调整反序列化侧,并在类注释里写明这条约束。
## Alternatives considered
- **继续让后端做全套 AI 结果校验**:后端确实是落库边界,多一层防线看起来更保险;但两套规则已经分叉并误杀过正常结果,维护成本随每次协议调整翻倍,因此只保留引文一致性这条不可替代的复核,其余交给产出方。
- **整体删掉 `RecallAiResultValidator`,完全信任 lpt-ai**:代码与测试最少,最符合「各服务自证」;但 lpt-ai 的回归或部署漂移会让伪造引文直接进库并展示给用户,而「引文确实来自本次资料」正是这套功能对用户的核心承诺,因此保留最小复核。
- **在前端补 `style: null` 了事**:一行改动即可让当前页面不再 400;但契约里 `style` 本来就是可选的,旧版本地草稿(`recallCache` 里的 `pendingSave`)与任何第三方客户端仍会被打回,服务端「少一个 key 就拒」的陷阱也还在,因此改在接收侧。
- **保留 `FAIL_ON_MISSING_CREATOR_PROPERTIES`,改用 `@JsonProperty(required = true)` 标注必填字段**:能精确表达必填;但实测 Jackson 2.15 下该 feature 仍会否决未被 `required` 标注的缺席组件(`required=false` 也不生效),要真正生效必须去掉这个 feature,因此等价于本方案,只是多一层注解。
## Consequences
前端按 TS 类型省略可选字段不再被拒,`PUT /draft` 与 `/end` 对真实页面恢复可用;后端不再因为协议细微差异误杀 AI 结果,`INVALID_AI_RESULT` 现在只表示「引文不可回溯」这一种情况。
代价是:AI 结果的条数与枚举约束在后端不再有第二道检查,若 lpt-ai 的解析器回归,后端只能靠引文一致性挡掉一部分问题;`RecallAiResultValidatorTest` 的覆盖面相应收窄,原来的结构类断言改为引用 lpt-ai 的 `recall.test.ts`。存储侧的损坏判定从「序列化异常」扩到「形状类异常」,能覆盖字段缺失导致的 `NullPointerException` 与类型不符导致的 `ClassCastException`;数据库与事务异常仍会上抛,排查时从日志里的 `recallNum` 与「旧版本或不兼容文档已删除」入手区分两种情况。
## Verification
- `ReviewRecallControllerIntegrationTest#draftAcceptsOmittedOptionalStyleAndRejectsMissingRequiredFields` 用**手写 JSON 字符串**(不经 Java 序列化)验证:子节点省略 `style` 返回 200;缺 `schemaVersion`、缺节点 `id`、缺 `provenance`、出现未知字段 `carryFrom` 仍返回 400 `INVALID_INPUT`。
- `RecallAiResultValidatorTest` 保留伪造引文、未知 `unitId`、切开代理对、表达依据越界、提示引文伪造与结构错乱 fail-closed 的用例。
- `ReviewRecallServiceIntegrationTest#legacyDocumentsAreDeletedInsteadOfSkippedAndNewRecallStartsEmpty` 改为写入非法 JSON 来构造损坏文档,继续验证「损坏即删除并返回 `STORED_DATA_INVALID`」。
- 使用 JDK 17 运行 `./mvnw test`,全量 602 个用例通过。
@@ -0,0 +1,49 @@
# Agent Note: HTTP 边界不再返回实体,入参改用请求 DTO
Status: implemented
## Problem
接口层的类型直接复用了持久化实体与 `Map`,导致三件事同时发生:
- **实体即契约**:`CommonResult<TaskApplicationEntity>` 这类返回把库表形状暴露成 API。实体加一个字段就等于改接口,
而 `createdBy` / `lastModifiedBy` / `deviceInfo` / `deleted` 这些列本来就不该出现在响应里。
- **`Map<String, String>` 当请求体**:10 个端点用 `@RequestBody Map`,字段名只在 `body.get("xxx")` 里出现,
拼错 key 不报错、无法被 Bean Validation 校验、OpenAPI 文档里是空对象。
- **实体当请求体**:`savePriorityWeights(@RequestBody UserPriorityWeightsEntity)` 让调用方能顺手改 `id`、`createdBy`。
## Decision
在 controller 边界做转换,service 层签名不动:
- 出参:`dto/response/<东西>Response`,字段与实体同名(类型不变),另带 `createdTime` / `lastModifiedTime`;
不含 `createdBy` / `lastModifiedBy` / `deviceInfo` / `deleted`。每个类提供 `static of(Entity)` 工厂,实体为 null 时返回 null。
- `Page<Entity>` 返回:`new Page<>(current, size, total)` + `setRecords(records.stream().map(X::of).toList())`。
- 入参:`dto/request/<动作>Request`,字段名与原先 `body.get("key")` 的 key 完全一致;必要字段加 `@NotBlank` 并在 controller 上 `@Valid`。
- 局部更新改用 `update(new Entity(), lambdaUpdate().set(...))`,显式写「改哪几列」,不再依赖 MyBatis-Plus 的全局 null 策略;
传入空实体是为了让 `MetaObjectHandler` 继续填 `lastModifiedBy` / `lastModifiedTime` / `deviceInfo`。
## Alternatives considered
**① 直接在 service 层返回 DTO,controller 只透传。**
最强理由:转换点更靠里,controller 变薄,未来换实现(比如加缓存层)时不用再改 controller。
否掉的原因:service 接口与实现遍布 40 多个类,签名一改要跟着改 600 多个测试与所有调用方;
而「实体不出 controller」这条约束只需要在边界做一次转换就成立。等真有了第二个入口(gRPC、MQ handler)再下沉不迟。
**② 让实体自己 `@JsonIgnore` 掉审计列,不建 DTO。**
最强理由:改动最小,一个注解解决泄漏,响应体里也不会再有 `createdBy`。
否掉的原因:注解只解决序列化,解决不了「实体能当请求体」和「库表形状即契约」;而且把 API 决策藏在实体里,
以后 lpt-ai 或内部服务需要这些列时会互相拉扯。
**③ 保留 `Map` 请求体,只加 `@Valid` 常量约束。**
最强理由:不动前端契约,也没有 10 个新类。
否掉的原因:`Map` 拿不到字段级校验与文档,`body.get("markerName")` 拼错永远是 null;
本轮恰好要为 18 个出参加 DTO,入参顺手一起做,边际成本远低于再开一轮。
## Consequences
- 响应体少了 4 个字段(`createdBy` / `lastModifiedBy` / `deviceInfo` / `deleted`)。已核对 `lpt-fe`:
这 4 个字段零使用,`createdTime`(16 处)与 `lastModifiedTime`(2 处)保留,前端无需改动。
- service 仍返回实体,controller 里多了一次映射调用;`Page` 需要手工重建(MyBatis-Plus 的 `convert` 返回 `IPage`,类型对不上)。
- 请求 DTO 里加了 `@NotBlank`,校验失败的文案由 DTO 决定;原本由 service 抛 `ErrorParameterException` 的路径仍在(DTO 未覆盖的语义校验)。
- 回归由 608 个测试守住;改动后 `./mvnw validate` 仍为 0 违规。
@@ -0,0 +1,66 @@
# Agent Note: 自由回忆去掉状态与自动带入,任意历史记录都能继续编辑
Status: implemented
## Problem
自由回忆曾把一条记录分成「进行中(ACTIVE)」与「已结束(ENDED)」两种状态:`status` 既落库成列、又进 `RecallDetail`,
还带一个 `endedAt` 字段和 `POST /review/recalls/{num}/end` 端点。只有 `ENDED` 的记录才会被「同范围自动带入」选中,
只有 `ACTIVE` 的记录才允许恢复(`resume`)和保存草稿(`PUT /draft`)。
这套状态带来的是纯粹的摩擦,没有对应的业务收益:
- **用户视角没有「结束」这个动作。** 想再改昨天的回忆,记录已经是 `ENDED`,只能开始新的一次;
而新记录又把上次的导图整棵复制过来,于是旧记录变成一份再也碰不到的副本。
- **自动带入把两条记录耦合成一条链。** 复制只发生在「同范围最近一条已结束」记录上,用户看到的新空白图取决于
是谁先点了结束,行为难以解释;资料、提示与耗时却按本次重新开始,复制过来的节点算不上同一次回忆。
- **状态是第四个写入保护维度。** 编辑者(`editorId`)与写令牌(`writeToken`)已经解决多页面覆盖,
`status` 只是再多一条会在恢复与保存之间产生「已经结束,只能回看」这种前后矛盾的拒绝。
## Decision
自由回忆不再有状态,任意历史记录都能继续编辑:
- 新建回忆永远从空白根节点开始,不再查询「同范围最近已完成导图」;`previousExpression` / `carryContent` 删除。
- `RecallDetail`(含列表 `RecallSummary`)不再有 `status` 与 `endedAt`;`EndRequest` 与 `POST /review/recalls/{num}/end` 删除;
列表接口不再接受 `status` 查询参数。
- 任意记录都能 `POST /resume` 接管编辑:恢复只重置计时编辑段并轮换 `writeToken`;`PUT /draft` 继续可用,
有效时间与实际用时继续累计到同一条记录。
- `ReviewRecallStore.guard` 只校验 `editorId` + `writeToken`,`setEntity` 不再写 `status`;`ReviewRecallEntity` 去掉该字段。
- `V20261122_1__drop_recall_status.sql` 先删含 `status` 的索引 `idx_recall_user_scope_status`,再 `DROP COLUMN status`,
最后按去掉 `status` 的列顺序重建 `idx_recall_user_scope (created_by, scope_type, scope_key, deleted, last_modified_time, id)`。
旧 `document_json` 里的 `detail.status` / `detail.endedAt` 由 `RecallJson.readStored` 的「忽略未知字段」自然丢弃,
不做回填 JSON 的迁移。
- 主动查漏的输入不变:仍是当前 `expression` + 本次 `reference.units`,历史导图从不发送给 AI。
## Alternatives considered
- **保留 `status` 但允许 `ENDED` 记录继续编辑。** 改动最小,`resume` 里去掉一条校验即可;但 `status` 与 `endedAt`
会继续出现在 API 契约和数据库里,用户和前端要一直维护一个不再影响行为的字段,等于把废弃字段当契约留着。
- **把 `status` 换成「已完成/未完成」的展示派生值(例如「最后修改时间早于 N 天」)。** 可以让列表看起来有分组;
但这是前端可以自己算的展示口径,落到后端只是把同一条状态的维护成本换了个名字,且没有任何写入规则依赖它。
- **保留自动带入但改成「带入最近一条同范围记录」。** 能让用户接着上次的图;但复制来的节点与本次资料、本次提示不对应,
且用户无法选择不复制(新回忆只能是复制品),因此直接取消带入,需要接着写时打开原记录继续编辑即可。
## Consequences
收益是契约与数据库各少一列、少一个端点、少一次「同范围历史查询」,恢复与保存不再互相否定;展示与写入规则只剩
`editorId` / `writeToken` 一层,与既有的多页面覆盖语义一致。
代价是:
- **删除列不可逆。** 代码回退到带 `status` 的版本会因缺列直接报错,必须与迁移同批回退或补一次新增列的回填。
- **旧记录的含义变宽。** 以前 `ENDED` 表示「不再修改」,现在任何记录都能被接手;拿到最新写令牌的页面可以覆盖,这是既有语义。
- **列表索引重建。** `idx_recall_user_scope` 的列顺序只服务「按范围过滤 + 最近修改排序」,不能再按 `status` 过滤;
未指定范围时列表仍走 `idx_recall_list (created_by, deleted, last_modified_time, id)`。
## Verification
- `ReviewRecallServiceIntegrationTest`:`creatingRecallAlwaysStartsFromAnEmptyRootEvenWithHistoryInScope` 覆盖同范围有历史导图时新建仍空白;
`anyHistoricalRecallResumesAndKeepsAccumulatingOnTheSameRecord` 覆盖任意记录多次恢复 + 草稿后 `activeDurationMs` / `actualDurationMs`
在同一条记录上继续累计;其余用例去掉了结束动作与状态断言。
- `ReviewRecallControllerIntegrationTest`:详情断言不含 `status` / `endedAt`,`anyHistoricalRecallResumesAgainAndKeepsEditing`
覆盖同一篇记录连续恢复与恢复后保存草稿;旧的未知字段(`carryFrom`)与过期写令牌仍按 400 拒绝。
- `RecallStorageMigrationTest` 断言迁移后 `review_recalls` 不再有 `status` 列;`MigrationIndexKeyLengthTest` 解析全部迁移文件,
会复算重建后的 `idx_recall_user_scope` 键长(564 字节,上限 3072)。
- 使用 JDK 17 运行 `./mvnw test`(611 个测试)。
@@ -0,0 +1,106 @@
# Agent Note: 回忆列表首次请求 500 与逐行 N+1 查询
Status: implemented
## Problem
进入 `/review` 时前端同时发出两个回忆列表请求(「继续上次回忆」的 `status=ACTIVE&pageSize=1` 与「最近回忆」的 `pageSize=4`)。首次进入时其中一个稳定返回
`{"code":500,"message":"操作没有成功,请稍后再试"}`,另一个常常挂到前端 30s 超时才被放弃;刷新一次后又能正常返回。
根因有两层,互相放大:
1. **所有者锁的取法会死锁。** `ReviewRecallStore.lock()` 先发 `INSERT IGNORE INTO review_recall_owner_locks`,行已存在时这条语句只拿
共享锁(S),紧接着的 `SELECT ... FOR UPDATE` 要升级成排他锁(X)。两个并发请求各持 S 锁互等 X 锁,InnoDB 判定死锁并回滚其一,
Spring 抛 `DeadlockLoserDataAccessException`,被 `GlobalExceptionHandler` 兜底成 500。
`SHOW ENGINE INNODB STATUS` 的 `LATEST DETECTED DEADLOCK` 里两条事务都是
`SELECT owner_id FROM review_recall_owner_locks WHERE owner_id = '1' FOR UPDATE`,各自 `HOLDS S, WAITING X`;同一份并发用纯 JDBC 复现,
旧写法 6/6 轮死锁,改成新写法 0/12 次失败。
2. **读路径逐行放大成几十条查询。** `list()` 对每一行都 `store.load()`:按 `recall_num` 回表一次、`reconcile` 做两次全表校验(碎片 id、用户标签)、
再对每个来源 `selectById` 判可达性、最后 `store.detail()` 对每条 AI 请求各查 `review_recall_requests` 与 `ai_tasks` 两次。
样例回忆(13 个来源、13 条 AI 请求)单行约 **47 条 SQL**;远端 MySQL 单程 40–80ms,一次 4 行的列表就是十几秒,整个事务期间一直持着所有者锁,
把第 1 点里的冲突窗口拉到几十秒。而 `list` 返回的 `RecallSummary` 里根本没有 `requests` 字段,那 26 条查询是纯浪费。
## Decision
**锁的形态:** `ReviewRecallMapper.ensureOwnerLock` 改为
`INSERT INTO review_recall_owner_locks (owner_id) VALUES (?) ON DUPLICATE KEY UPDATE owner_id = owner_id`。
命中已有行时 MySQL 对这个「无变化更新」加的是排他锁,随后的 `SELECT ... FOR UPDATE` 在同一事务里已是 X 锁,不再有 S→X 升级,也就没有互等。
读路径继续保留这把所有者锁:`reconcile` 会就地抹除已不可访问的来源,必须和草稿写入串行,否则一次先读后写的草稿提交会把刚抹掉的内容写回来。
**读路径:**
- `list()` 直接用分页行里已经查出来的 `document_json` 解析文档,不再按 `recall_num` 回表;只发 `selectPage` 自带的一次 COUNT,不再额外 `selectCount`。
- 新增 `RecallReferenceLoader.SourceIndex`:按需把「可达碎片 id / 报告 id / 应用场景 id / 任务号 / 用户标签」各查一次(整表 `select(id)` 级别),
标签范围有效性与来源可达性都在内存里判断。`list` 一次建索引、逐行复用;单文档入口按需建一次。原来对每个来源一次 `selectById` 的循环消失。
- 新增 `RecallDetailAssembler`:`review_recall_requests` 与 `ai_tasks` 各一条 `IN` 取齐整批 taskNum,按 `taskNum` 建索引后逐条装饰。
列表走 `summary()`,连这两批都不查;详情、草稿、结束等写路径走 `detail(doc)`,文档内所有 AI 请求共用一次批量取数。
- `RecallExpressionValidator` 只在确实出现新出处时才装配一次详情,把「每条出处各查两次」变成「每次保存最多两次」。
样例回忆上的 SQL 条数:列表 **47 → 7**,详情 **44 → 8**;并发两请求的等待时间从 2.1–4.4s(且约 80% 概率 500)降到 0.4–0.9s,5 轮并发 10 次全部成功。
同一批把其它「随行数/次数放大」的读路径一并收敛(都是换成批量 IN 或一条 SET 更新,不改响应字段):
- `GET /study-sessions/tasks/{num}/reports`:逐个报告查学习预期 → 整页一次 `IN`。
- 标签导图「待更新」:逐张 `UPDATE` → 命中集合一条 `UPDATE ... WHERE id IN (...)`。
- 隐私清算:删除任务时对每个报告/应用场景各递归一次(每次重新加锁 + 重扫整张回忆表)→ 先收集 sourceId 再扫一遍;
`tagsChanged` 里逐篇回忆两次全表校验 → 整批共用一个来源索引。
- `GET /export/range`:逐任务调 `getReviewTaskStats`(每任务 4 条聚合)→ 一批任务一次取齐;`sumTaskDuration` 的整表 `GROUP BY`
加上 `task_num IN (...)` 过滤(T 个任务时约 `4 + 5T` 条降为固定 9 条)。
- `PUT /tasks/priority-weights`:重算全部任务时逐条 `updateById` → 每 200 条一条 `CASE id WHEN ... THEN ...` 更新,
审计列显式写入(身份取不到时不动 `last_modified_by` / `device_info`,避免把旧值清空)。
- `PUT /markers/rename`:逐条标记一次 `exists` + 一次 `update` → 一次预取目标标签命中的对象、一条批量 `UPDATE`、一条批量 `DELETE`。
- 隐私清算按范围类型过滤:标签改名/标签变化只解析 `scope_type='TAG'` 的回忆,删任务只解析该任务的 `TASK` 范围回忆,
不再整表解析 `document_json`。
- `GET /review/report/{id}/structured`:按归属分组时逐个查任务名 → 先收集 ownerTaskNum,一次 `IN` 取齐(会话任务名并入同一次)。
- 回忆删除与隐私抹除:对每条 AI 请求各查各改(每条请求 2–3 条语句)→ 整份回忆一次批量失效
(`invalidateTasks`:查远程任务号 + 改请求 + 改 AI 任务,共 3 条),`deleteUnreadable` 的逐条删除也改成一条。
- `GET /review/feed` 的随机/智能取样:`selectPage` 白算了一条 COUNT → `Page(current, size, false)`。
- 标签范围校验加载标记时只取 `object_num` / `marker_name` 两列,不再把审计列一起搬进内存。
## Alternatives considered
- **读路径完全不加锁。** 列表并发度最高,也能彻底避开锁争用;但 `reconcile` 的抹除是隐私要求,无锁时一次并发草稿保存会用旧文档覆盖抹除结果,
等同于把已删除内容写回来。要安全就得改成带旧文档摘要的 CAS 写入,复杂度和风险都高于本次收益,因此保留锁、只把事务缩短到个位数查询。
- **在登录时就把所有者锁行种好,读路径只做 `SELECT ... FOR UPDATE`。** 稳态下同样没有 S→X 升级,语义更直白;但需要一条回填迁移,
而且「行缺失」的兜底插入仍在,等于两套路径并存。`ON DUPLICATE KEY UPDATE` 一行同时覆盖「确保存在」和「取得排他锁」,故采用后者。
- **捕获死锁后重试。** 能消掉 500,但两个请求仍在做无效功,且重试会掩盖下一次同类写法回归;根因是锁模式,应该在 SQL 形态上消灭。
- **把回忆列表改成单条 JOIN 查询。** 回忆的读取单位是整份 `document_json`(表达树 + 冻结的资料快照),跨表的只有 AI 请求状态;
真正需要跨表的是详情里的两批装饰,`IN` 已经够用,JOIN 只会把 JSON 文档拆成多行再在内存里重组,反而更慢。
- **把 `reconcile` 挪到定时任务、读路径不再校验。** 事务最短,但来源被删除后列表会继续显示 `VALID`/可用正文,直到下一轮扫描,不符合隐私口径。
## 索引补齐
`V20261121_1__add_query_indexes.sql` 补两条被漏掉的索引(2026-11-21 复查发现,不是本次批量化引入的问题):
- `study_expectations (created_by, session_num)`:这张表此前只有主键,而报告分页、报告详情、会话详情都按会话号查它,等于每次全表扫。
- `review_recalls (created_by, deleted, last_modified_time, id)`:原有索引以 `scope_type` / `scope_key` 打头,未指定范围时(首页的「最近回忆」、
`status=ACTIVE` 取草稿)无法利用排序,只能取完 `created_by` 前缀再 filesort;`status` 由索引外过滤(活跃草稿通常就是最近修改的那条)。
两条索引都按「租户拦截器统一追加 `created_by`」的约定以 `created_by` 打头;键长远小于 InnoDB 的 3072 字节上限,`MigrationIndexKeyLengthTest` 已复算。
## Consequences
列表仍是「每个用户串行」的读路径:并发两个列表请求时第二个会等第一个提交,只是等待从几十秒降到几百毫秒。
`list` 现在依赖分页行里的 `document_json`,若以后列表查询改成 `.select(...)` 裁列,必须同时把文档列选回来,否则所有行都会被当成不可读文档删除。
`SourceIndex` 用「整表 id 集合」判断可达性,前提是这些表按 `created_by` 租户过滤(拦截器已保证);绕过租户的查询不能复用这个索引。
`RecallsSummary` 不再经过 `detail()` 装饰,`reference` 也只保留文档里的汇总;如果以后摘要需要展示 AI 请求状态,必须显式调用 `detail()`,不能假设它已经在。
优先级批量重算不再经过 `updateById`,因此自动填充不再参与:`last_modified_time` 由调用方传入,`last_modified_by` / `device_info` 只在取到身份时写入。
新增「任务优先级」批量 SQL 时必须保留 `deleted = 0`(自定义 SQL 不会自动追加逻辑删除条件),租户条件仍由拦截器追加。
已知的下一层瓶颈(语句数已经是常数,但数据量随用户增长):回忆读路径仍会整表取「可达碎片 id + 用户标签」来做范围校验与可达性判断
(`RecallReferenceLoader`),隐私清算 `sourceDeleted` 仍需扫用户全部回忆并解析 `document_json`。要再降一档需要一张「来源 → 回忆」的索引表,
或把范围校验下推成聚合 SQL,属于独立改动。
## Verification
- 真实 MySQL 并发复现:脚本对同一用户并发发两个列表请求,旧锁形态 6/6 轮死锁,新锁形态 0/12 次失败;`performance_schema.data_locks` 中不再出现同事务的 S+X 并存。
- SQL 条数:用 `logging.level...mapper=DEBUG` 抓单次调用语句数,列表 7 条、详情 8 条(改造前 47 / 44)。
- `./mvnw -o validate`(Checkstyle)与 `./mvnw -o test` 全量 609 个用例通过,含 `ReviewRecallServiceIntegrationTest` 的列表删除不可读文档、
资料清除、AI 结果装饰等断言,以及新增的 `PriorityWeightsIntegrationTest`(真实事务里校验批量 CASE 更新写回的值与审计时间)。
- 批量 `CASE id` 更新语句在真实 MySQL 上单独执行验证(同一事务内 affected=2 后回滚),确认语法与索引条件可用;H2 集成测试同时覆盖了
租户拦截器对这条 `UPDATE` 的改写。
- 真实 MySQL 上跑过一遍首页会话的读接口并数语句:`GET /review/feed` 4 条、`GET /review/summary` 3 条、`GET /review/tasks` 6 条、
`GET /tasks` 2 条、`GET /tasks/options` 1 条、`GET /report-fragments/pending-ownership` 1 条、`GET /study-sessions/active` 2 条,
均不随行数增长;迁移在真实库执行成功(`flyway_schema_history` 20261121.1,两条索引已建)。
@@ -0,0 +1,36 @@
# Agent Note: 空范围不能创建、恢复或保存回忆
Status: implemented
## Problem
自由回忆的范围只校验「所选标签在某个碎片上存在」,没有校验「本次范围实际匹配到至少一条碎片」。多标签交集没有同时命中的碎片时,`ReferenceSnapshot` 是 `EMPTY`,但记录仍被创建、仍能进入导图编辑,随后提示和查漏每次都以 `NO_REFERENCE` 失败。用户看到的是一个能画图、却不能使用任何资料辅助的回忆。
线上记录 `RECALL-814013dd-2ce5-4346-af3f-3b8d887bbbce` 就是这种情况:标签 `A` 与「【体验测试】数据库事务学习(2026-11-15)」各命中 2 条碎片,交集为 0,`detail.reference` 为 `EMPTY`。
## Decision
- `ReviewRecallService.create` 在取得 `ReferenceSnapshot` 后检查 `RecallReferenceLoader.knowledgeSources(reference.sources())`;为空时抛 `SCOPE_EMPTY`,不写记录。
- `resume` 与 `draft` 在加载文档后调用同一个 `requireKnowledge` 检查;空范围记录不能接管编辑,也不能继续保存。
- `get`、`list`、删除保持可读/可删:历史里的空范围记录仍能出现在回忆列表并删除,只是不能继续编辑。
- `SCOPE_EMPTY` 是业务错误码,前端据此显示「重新选择范围」,不把空范围伪装成网络失败。
## Alternatives considered
- **只在下一步(提示/查漏)禁用按钮**:改动最小,但用户已经进入导图、画了内容,才发现这个范围没有任何资料;这不是「不进入编辑」,只是把失败推迟。放弃。
- **自动把交集改成并集**:能让范围立刻有碎片,但会静默改变用户选择的复习范围,也无法解释历史快照。放弃。
- **允许进入但只读展示**:用户仍会看到一张不能继续编辑的导图,和「进入导图编辑页面」的边界不清楚;不如直接停在范围选择。放弃。
- **删除历史空范围记录**:等于替用户清理数据,且可能连带删除用户已画的内容;保留历史、禁止编辑即可。放弃。
## Consequences
- 空范围不能再产生新的回忆记录;已存在的空范围记录留在历史中,打开时由前端显示范围错误与「重新选择范围」,后端也拒绝恢复/保存。
- 用户要使用提示或查漏,必须先调整标签或组合方式,使范围至少命中一条知识碎片。
- 新增 `SCOPE_EMPTY` 业务码;没有数据库迁移,也没有改写既有 `document_json`。
- 匹配到碎片但碎片正文为空的情况仍然允许进入(有碎片,只是资料没有可用文本),由提示/查漏的禁用态处理。
## Verification
- `ReviewRecallServiceIntegrationTest.zeroMatchingFragmentsCannotCreateResumeOrDraft`:交集 0 时创建抛 `SCOPE_EMPTY`;把已有记录的快照改为空后,`resume` 与 `draft` 都抛 `SCOPE_EMPTY`。
- 既有创建、恢复、计时累计、资料分页与 AI 终态测试继续通过。
- `./mvnw test` 全绿(新增用例后 612 个测试)。
@@ -0,0 +1,44 @@
# Agent Note: 出包环境由分支绑定,不靠参数切换
Status: implemented
## Problem
同一份代码要出 dev 与 prod 两个包。如果只靠流水线参数(或本地配置)区分环境,那么「用 dev 的代码发到
prod 的 namespace」只是一次手滑——而这类手滑的代价最大:库表迁移已经跑上去、前端已经指到生产后端,
回滚时数据形状已经不匹配。
## Decision
一个分支对一个环境,绑定关系写进流水线第一步并**直接拒绝**不匹配的组合,而不是打印警告。
| 仓库 | dev 分支 | prod 分支 | 说明 |
|---|---|---|---|
| lpt-be / lpt-fe / lpt-ai | `dev` | `master` | `main`(lpt-ai)仅作历史冻结点,不再发版 |
| lpt-android | `dev` | `master` | 两个分支只差默认 API 地址,不参与 k8s 部署 |
| lpt-infra | `master` | `master` | 单分支,靠 `dev/` 与 `prod/` 目录区分清单 |
- 触发方式固定为 `workflow_dispatch` + 选择 `environment`,流水线首步校验「分支 ↔ 环境」,不匹配即 `exit 1`。
- 网关地址、registry 等推动参数全部来自流水线的环境分支开关;**禁止用 tag 触发部署**(tag 打出来就跟分支脱钩了)。
- 跨仓库同环境同批发:`dev` 配 `dev`、`master` 配 `master`。lpt-ai 的结果字段与 lpt-be 的读取形状是硬耦合,
跨环境出包会让旧版读取方**静默降级**,界面不报错。
## Alternatives considered
- **单分支 + 部署参数区分环境** — 不必维护两条长期分支,也少了合并这一步。放弃是因为环境成了「一次运行里的一个
字符串」:谁都能选错,代码里哪一行是生产配置也无从判断,出事后连「线上跑的是哪份代码」都要翻流水线记录才能答。
- **出包后打 tag,用 tag 决定环境** — 发布形态更接近常规 CI。但本项目的分支本身就是环境契约,再叠一层 tag 会让
两个事实源打架;且 tag 一旦从错误分支打出,校验分支就再也拦不住。
## Consequences
- **收益**:环境错配从一个「可能发生的事故」变成一个「跑不起来的流水线」;线上代码与分支一一对应,可以直接回答。
- **代价与已知上限**:每次上生产都要「`dev` 合并进 `master`」这一次显式动作,合并冲突要自己解;`dev` 上验证过的
东西与 `master` 上的形态之间隔了一次合并,必须同批升级关联仓库才不会错配。历史例外:lpt-ai 的 `main` 停在
冻结点 `7c751bf`,看见它在仓库列表里不代表还能发版。
## Verification
- 规则位置:`lpt-be/.gitea/workflows/deploy.yml`、`lpt-fe/.gitea/workflows/deploy.yml`、
`lpt-ai/.gitea/workflows/deploy.yml` 的 `Validate branch ↔ environment` 首步。
- 清单分区:`lpt-infra/dev/` 与 `lpt-infra/prod/`。
@@ -0,0 +1,117 @@
# Agent Note: 用 Checkstyle 在 validate 阶段阻断代码坏味道
Status: implemented
## Problem
格式、命名、复杂度、事务回滚这些坏味道,之前只存在于文档与评审习惯里,没有任何机械检查。结果是**写了没人查**:
全仓存量 692 处违规,横跨 149 个「文件 × 规则」组合,其中 215 处超 120 列、181 处单行语句不带花括号、
154 处一行写多条语句、42 处 `@Transactional` 缺 `rollbackFor`(受检异常抛出去时事务照样提交)。
人工评审兜不住,原因不在态度:
- 一个 PR 的注意力预算有限,几十行格式差异会把真正的行为变更埋掉;
- 同一条规则要在每次评审里重复提,提的人会累,被提的人会当噪音;
- 有些违规(缺 `rollbackFor`、`System.out`、空 catch)在 diff 里根本不显眼,看见了也容易划过去。
## Decision
把能机械判定的纪律交给构建,绑在 `validate` 阶段阻断,而不是写成文档等自觉。
- **工具**:`maven-checkstyle-plugin:3.3.1` + `checkstyle:10.12.4`,`goal` 为 `check`,绑 `validate`,
`failOnViolation=true`。违规即构建失败,不是警告。
- **范围**:只查 `src/main/java`(`includeTestSourceDirectory=false`)。测试里的长断言行、lambda 内联会制造大量假违规,
而假违规会把人训练成习惯性跳过检查。
- **存量**:先用 `suppressions.xml` 做 **文件 × 规则** 基线落地(149 条豁免覆盖 692 处),随后在同一天把 692 处全部改完,
基线缩到 2 条框架约束(见「豁免的现状」)。
- **基线加载**:pom 的 `<suppressionsLocation>` + 配置里的 `${checkstyle.suppressions.file}`。不用 `<propertyExpansion>config_loc=...`
这种更常见的写法:`maven-checkstyle-plugin:3.3.1` 把 `propertyExpansion` 当 properties 文本走 `Properties.load(InputStream)`
(ISO-8859-1),路径里含中文就变乱码(本仓路径含「系统」,实测报 `Unable to find: /run/media/cat/系统/...`)。
`suppressionsLocation` 走 plexus `ResourceManager` 按 basedir 解析,不经那段,含中文路径与任意 CWD 都成立。
- **阈值**:行 120、方法 80 行、文件 400 行、参数 7、圈复杂度 15、嵌套 if/for/try 各 3。
- **跳闸口**:`-Dcheckstyle.skip=true`,只用于本地应急(`failOnViolation` 写死在 pom,user property 覆盖不了它的语义)。
- **文档分工**:规则取值与出处进 `.agents/roles/code-standards.md`;工具查不了但必须人看的项进
`.agents/roles/code-review-checklist.md`。`config/checkstyle/checkstyle.xml` 是唯一事实来源,文档只解释「为什么」。
### 为什么基线粒度是「文件 × 规则」
- **整文件豁免**(`<suppress files="...">` 不带 `checks`)最省事,但它让那个文件**所有**规则一起失效:
一个 800 行的老 controller 被整文件豁免后,新写的 `System.out` 与缺 `rollbackFor` 全放过,等于给最脏的文件开最大口子。
- **行号豁免**(`beginLine` / `endLine`)精度最高,但行号随每次编辑漂移:上面插一行,豁免就落到别的语句上,
或者干脆失效。维护基线的成本会超过改代码本身,而且漂移是静默的。
- **文件 × 规则** 的精度刚好落在可用区间:豁免的是「这个文件在这条规则上的存量」,同一文件的其他规则照样生效;
改到该文件时删掉这一行,就能立刻看到它在这条规则上的真实状态。棘轮规则(豁免只减不增)成立。
## 豁免的现状
`suppressions.xml` 只剩两条,都是「框架规定、改了就坏」,不是债务:
| 豁免 | 为什么必须豁免 |
|---|---|
| `db/migration/**` 的 `TypeName` | Java 迁移类的类名由 Flyway 规定为 `V20261115_2__xxx`,改了就等于让 Flyway 认为已有迁移消失 |
| `LearningProgressTrackerApplication` 的 `HideUtilityClassConstructor` | 启动类只有 `main`;给它加私有构造后 Spring 测试上下文无法实例化,实测 164 个测试报 `No visible constructors` |
692 处是怎么清零的(都是改代码,不是加豁免):
| 规则 | 数量 | 做法 |
|---|---|---|
| `LineLength` / `OneStatementPerLine` / `MultipleVariableDeclarations` / 未用与重复 import | 388 | 全仓跑 palantir-java-format(4 空格 / 120 列),再人工收尾 1 处长行 |
| `NeedBraces` | 181 | 先按行处理单语句体(128 处),再用 Checkstyle 报告的行号精确包住多行体(52 处),剩 4 处手改 |
| `AvoidStarImport` | 51 | 脚本按「文件里用到的类名 ∩ 包内类名」展开成显式 import,共 27 个文件 |
| `transactionRollback` | 42 | 给 44 个 `@Transactional` 补 `rollbackFor = Exception.class`;正则加 `\b` 避免误伤 `@TransactionalEventListener` |
| `FileLength` | 5 | 拆出 `ReviewFeedService`、`ReviewStatsService`、`TagDictionaryService`、`StudySessionConvergenceService`、`StudyReportDraftService`、`RecallExpressionValidator`、`MindMapMatchTool` |
| `CyclomaticComplexity` | 6 | 主干只做分发,分支下沉为私有方法 |
| `ParameterNumber` | 1 | 9 参数方法收成 `SourceContext` record |
| 命名 / 构造器 / `System.out` | 15 | `reportFragmentsController`→`ReportFragmentsController`、`mapStruct`→`mapstruct`、3 个异常处理方法改名、3 个工具类补私有构造、启动打印改 `log.info` |
验证方式:`./mvnw validate` 输出 `You have 0 Checkstyle violations`,`./mvnw test` 为 608 个测试全绿。
过程中两次被测试挡住并纠正:「给启动类加私有构造」与「`@TransactionalEventListener` 被正则误伤」,都已回退/修正。
## Alternatives considered
**① 先把 692 处存量改干净,再一次性开闸。**
最强理由:门禁就该一把落地,基线豁免本质是技术债登记册,「以后再改」在实践中等于永远不改;而且一次格式化能顺手把风格统一掉,
比留 149 条豁免干净得多。
否掉的原因:692 处改动会和真正的功能改动混在同一批提交里,评审无法分辨哪些是行为变更。`LineLength` 与 `NeedBraces`
要求重排语句,重排中混进一个改了分支的差异几乎必然漏过,而格式改错只会由特定输入暴露,测试覆盖不到。
先开闸再棘轮,评审看到的是「删掉一行豁免 + 改动这一处」,可分辨。
**② 引入 `p3c-pmd`(阿里 Java 规约的 PMD 实现)。**
最强理由:规则更贴中文团队习惯(异常命名、常量命名、事务回滚、枚举注释本就是我们引用的上游),规则集覆盖面比这份 Checkstyle 配置更广,
还能一次拿到 `CognitiveComplexity` 这类 Checkstyle 没有的检查。
否掉的原因:`p3c-pmd` 的 PMD 版本锁在 6.15,而 `CognitiveComplexity` 需要 6.35+,两者在同一套 PMD 里只能择一;
且引入第二套工具链意味着两份配置、两套豁免、两倍检查时间,换来的增益与已选的 Checkstyle 模块高度重叠。
**③ 接 SonarQube。**
最强理由:规则最全(认知复杂度、重复字面量、异常被吞、覆盖率趋势),有界面能看历史与责任人,在多人的项目里权威性最高。
否掉的原因:要维护一个实例(数据库、升级、token、webhook),对个人项目这份运维成本不成比例;而且它擅长的是事后看板,
不是 `mvn package` 时的阻断——要的是「提交前就红」,不是一个每周打开看一眼的面板。
**④ 只写规则文档,不加门禁。**
最强理由:成本最低,不改构建时间、不需要豁免、不引入工具链;而且文档能解释「为什么这样写」,工具只能报「哪里错了」。
否掉的原因:这正是当前失效的原因——692 处存量违规就是「写了没人查」的直接证据。文档与工具是分工不是替代:
工具查能机械判定的,文档解释为什么,两者都要有。
## Consequences
**代价:**
- 豁免仍是「文件 × 规则」,将来若被迫新开豁免,被豁免的文件在那条规则上会裸奔;所以新增豁免必须写理由(现状是 0 条债务豁免)。
- 跳过开关存在且好按。遇到「先发出去」的场合会被用,只能靠 PR 说明与 `./mvnw validate` 复跑约束。
- 测试代码完全不查,测试里的长行、魔法数字、`System.out` 仍然是人的活。
- 构建多了一步(秒级),第一次撞上 400 行 / 80 行阈值的类会被迫先拆或先加豁免,这个摩擦是真实的。
**收益:**
- **新文件零豁免**:新建的类一违反就红,不需要任何人先记住规则。
- `validate` 在 `package` 之前,`mvn -f`、CI 的 `docker build`(Dockerfile 里跑 `mvn package -DskipTests`)都拦得住。
- 豁免清单本身就是可数的债务看板:149 条、692 处,改动前后能直接对比。
- 规则取值有了唯一事实来源,文档不必复述模块说明;上游出处(Google Java Style、Spring、p3c、Sonar)写在 `code-standards.md` 里,
下一次加规则有据可依。
## Verification
- 构建配置:`pom.xml` 的 `maven-checkstyle-plugin` 执行段(`checkstyle-validate`)。
- 规则与阈值:`config/checkstyle/checkstyle.xml`;基线:`config/checkstyle/suppressions.xml`。
- 触发:`./mvnw validate`,失败时输出 `文件:行` 与规则名。
- 文档:`.agents/roles/code-standards.md`、`.agents/roles/code-review-checklist.md`、`AGENTS.md` 的「启动命令」节。
@@ -11,6 +11,17 @@
- 参数校验失败:`MethodArgumentNotValidException`,code=400。
- 用户可见错误文案必须口语化、可理解,避免“无法生成”“不存在”等技术化表述;技术细节写入日志。例如无学习报告时应提示“这个任务还没开始学习哦,学习后产生学习报告后再来吧”,而不是“没有学习报告,无法生成思维导图”。
## 出参和入参的边界
- **实体不出 controller**:`CommonResult<XxxEntity>`、`CommonResult<Page<XxxEntity>>` 都不行,出参一律是 `dto/` 下的类。
实体带租户与审计列,库表形状一改就直接击穿 API 契约,前端还得跟着改。
- **请求体用 DTO,不用 `Map<String, String>`**:`Map` 丢类型、丢校验、丢字段名,只能在 service 里 `get("xxx")` 拼字符串;
每个端点一个 request DTO + `@Valid`。
- **`CommonResult` 不写裸类型**:一律 `CommonResult<T>`,哪怕是错误分支也给出 `data` 的类型;裸类型在生成文档与前端类型推导上都退化成 `any`。
存量:`GlobalExceptionHandler` 的 7 个 handler 仍是裸 `CommonResult`。
- **未知异常映射 500**:`@ExceptionHandler(Exception.class)` 返回 `CommonResult.serverError`(code=500),不能复用参数错误的 400,
否则系统故障被说成「参数不对」。存量:该兜底 handler 现在返回 400。
## DTO 转换
- MapStruct 编译期生成 `*ConvertImpl.java`,同名属性自动映射。
+65
View File
@@ -0,0 +1,65 @@
# 后端代码评审清单
- **功能**:列出 Checkstyle 查不了、必须人看才能发现的后端坏味道,每条给出识别方式、改法与当前数量。
- **何时用**:评审 lpt-be 的 PR、改 controller / service / mapper、自查交付前;机械格式与命名问题交给 `./mvnw validate`,不在这里重复。
## 出参与入参
### 1. Controller 出参不出现实体
`CommonResult<XxxEntity>`、`CommonResult<Page<XxxEntity>>` 都算违规;实体带租户与审计列,库表形状一改就击穿 API 契约。
出参放 `dto/`。存量 18 个端点已于 2026-11-19 清零(改为 `dto/response`),新代码别再引入;历史例子: `TaskController#getPriorityWeights`、`StudySessionController#getTaskFragments`。
### 2. 请求体不用 `Map<String, String>`
看到 `@RequestBody Map<String, String> body` 再 `body.get("xxx")` 就是违规:类型、校验、字段名的编译期保护全丢。
每个端点建一个 request DTO + `@Valid`。存量 10 处已于 2026-11-19 清零(改为 `dto/request`);历史例子: `MarkerController#addUserTag`、`ReviewController#saveSortPreference`。
### 3. 局部更新要说清「清空」还是「不动」
`new XxxEntity()` + 只 `set` 变了的字段 + `updateById` 是 patch 实体式更新:想表达的「清空」落不了库(null 被跳过),
行为还依赖全局 null 策略。整对象替换 / `LambdaUpdateWrapper.set(...)` / `XxxPatch` DTO 三选一。存量 17 处已于 2026-11-19 清零(改为 `lambdaUpdate().set(...)`);历史例子: `ReviewServiceImpl#updateReport`、`ReviewServiceImpl#submitFeedback`。
### 4. SQL 不拼字符串
`.last("LIMIT " + n)`、`apply("name = '" + x + "'")` 这类拼接一律违规,哪怕当前值来自内部常量——下一个人会传用户输入。
能参数化就用 `{0}` 占位,表达不了下沉到 mapper 的自定义 SQL。存量 3 处已于 2026-11-19 清零(改用 `selectPage`);历史例子: `ReviewServiceImpl` 与 `ReviewRecallService` 的 `last("LIMIT " + n)`。
### 5. 未知异常映射 500,不伪装成 400
`@ExceptionHandler(Exception.class)` 返回 `CommonResult.error(...)`(code=400)会把系统故障说成「你参数不对」,用户反复重试、值班查不到。
未知异常走 `CommonResult.serverError`(code=500),技术细节写日志。存量已于 2026-11-19 修正:兜底 handler 现在返回 `serverError`(500)。
## 分层与命名
### 6. `service/impl` 只放 `service/` 接口的实现
包名写 `impl` 却没有对应接口的类(`RecallJson`、`AiTaskParams`、`ReviewRecallStore`、`AiServiceClient` 这类工具或客户端也算)就是放错位置:
无接口就别用 `Impl` 后缀,也别放这个包,挪到 `service/`、`client/` 或调用方内部。存量 34 个已于 2026-11-19 挪出 `service/impl`(`service/ai`、`service/recall`、`service/review`、`service/session`)。
### 7. 注释跟随签名,不跟随历史
Javadoc 描述的方法名、参数、返回跟下面那个方法对不上就是违规——例如 `ReviewServiceImpl:371` 的「取任务名」挂在 `submitFeedback` 上。
方法移动、改名、改签名时把注释一起搬;过期注释比没有注释更贵。
### 8. 注释与用户可见文案统一中文
新增英文注释、或把中文提示改成英文都算违规:这个项目的用户文案与注释都是中文,混语种会在同一屏里跳出来。
用户文案还要求口语化(见 `api-response.md`)。历史情况(2026-11-19 前)是混排:`ReviewRecallController:21`、`LoginResult:21` 这类成句英文注释要翻成中文;
`/** REPORT | FRAGMENT */` 这种字段取值说明不算违规。
## 并发与性能
### 9. 循环里发查询(N+1)
`for` / `stream.map` / `forEach` 里出现 `selectOne` / `selectById` / `selectList` / `exists` 就是违规:请求的 SQL 条数会随
行数或子记录数线性增长,而库在远端,单程 40–80ms。识别方式是看循环体内有没有 mapper 调用、以及列表 DTO 的字段是不是
「每行再查一次」补出来的。改法:收集 id/编号 → 一条 `IN` 取齐 → 内存建 Map 装饰;聚合类下推 SQL。
2026-11-21 回忆列表(47 → 7 条)、导出范围(4+5×T → 9 条)已按此收敛。
### 10. 取锁写法会在并发下死锁
同一事务里先 `INSERT IGNORE`(或普通 `INSERT`)拿 S 锁、再 `SELECT ... FOR UPDATE` 升级 X 锁,两个并发请求必然死锁,
表现为接口随机 500,且只在「首次进入页面」这类并发场景出现。识别:锁表的取锁语句是不是两步。
改法见 `data-access.md`「加锁形态」:锁行可能不存在时用 `INSERT ... ON DUPLICATE KEY UPDATE` 再 `FOR UPDATE`,
并用两个并发请求验证。
+105
View File
@@ -0,0 +1,105 @@
# 后端代码规范
- **功能**:说明本项目在格式、命名、注释、复杂度、异常与事务上取哪些值、为什么这样取、出处在哪。
- **何时用**:新写或改动 `src/main/java` 下的类、`validate` 卡住不知道改什么、评审后端代码、想加规则或降豁免时。
## 事实来源是配置文件
- 规则的唯一事实来源是 `config/checkstyle/checkstyle.xml`(模块与阈值)与 `config/checkstyle/suppressions.xml`(存量豁免基线)。
本文件只记「取什么值 + 为什么 + 出处」,不复述 Checkstyle 的模块说明,也不抄上游正文;**两者不一致时以配置文件为准**,并回来改这里。
- 门禁形态:`maven-checkstyle-plugin:3.3.1` + `checkstyle:10.12.4`,绑在 `validate` 阶段,`failOnViolation=true`,
只查 `src/main/java`(`includeTestSourceDirectory=false`)。`./mvnw validate` 即触发,跑 `test` / `package` / CI / Docker 构建都会先撞上它。
- 选型、基线与代价见 [Checkstyle 门禁笔记](../notes/implemented/process/2026-11-19-checkstyle-gate.md)。
## 格式
- **缩进 4 空格,禁 tab**(`FileTabCharacter`)。Google Java Style 是 2 空格、Spring Framework 用 tab,都与本仓既有代码不符;
4 空格是既有代码与 IDE 默认的共同值,换掉要重排全部源文件,收益只在观感。
- **行宽 120**(`LineLength`)。Google 取 100 列,压到 100 会把存量违规从 215 处成倍放大,而 120 列恰好是既有代码排出来的宽度。
- **一行一句、一行一声明**(`OneStatementPerLine`、`MultipleVariableDeclarations`)。出处:Google Java Style §4.3「One statement per line」、
Spring Framework `src/checkstyle/checkstyle.xml` 的 `OneStatementPerLine`。
- **`if` / `for` / `while` / `else` 必须带花括号,即使只有一条语句**(`NeedBraces`)。出处:p3c `NeedBraceRule`。
理由不是风格:省掉花括号后往循环体补第二行是静默改逻辑(新语句落到循环外)。
- **import 不用通配、不留未用与重复**(`AvoidStarImport` / `UnusedImports` / `RedundantImport`)。出处:Google Java Style §3.3.1。
- **文件 ≤ 400 行**(`FileLength`):超了通常说明这个类不止承担一件事,先拆再交。
- **禁 `System.out` / `System.err`**(`RegexpSinglelineJava` 的 `noSystemOut`),日志走 `@Slf4j`。出处:Spring Framework
`src/checkstyle/checkstyle.xml` 中的同类检查。
- **其余机械项**:`ModifierOrder`、`ArrayTypeStyle`(写 `String[] a` 不写 `String a[]`)、`UpperEll`(`1L` 不写 `1l`)、
`EmptyStatement`(多余分号)、`OuterTypeFilename`(公有类名必须等于文件名)、`OneTopLevelClass`(一个文件一个顶层类)。
## 命名
- **类名 UpperCamelCase,只允许字母与数字**(`TypeName`,`^[A-Z][a-zA-Z0-9]*$`):下划线、数字开头都不行;缩写段可以全大写
(`HTTPServer` 能通过,没人要求你写成 `HttpServer`)。出处:p3c `ClassNamingShouldBeCamelRule`、Sonar S101。
- **方法 / 成员 / 局部变量 / 参数一律 lowerCamelCase**(`MethodName`、`MemberName`、`LocalVariableName`、`ParameterName`)。
出处:p3c `LowerCamelCaseVariableNamingRule`、Sonar S100。
- **常量全大写、下划线分隔**(`ConstantName`,`^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$`)。出处:p3c `ConstantFieldShouldBeUpperCaseRule`。
- **包名全小写**(`PackageName`,`^[a-z]+(\.[a-z][a-z0-9]*)*$`)。
- **业务名称以上游术语表为准**:库表、实体、DTO 字段由 `lpt-docs/docs/concepts/README.md` 派生,不另起别名(meta `business-terminology.md`)。
- **异常类以 `Exception` 结尾**(p3c `ExceptionClassShouldEndWithExceptionRule`)、**`service/impl` 下的实现类以 `Impl` 结尾**
(p3c `ServiceOrDaoClassShouldEndWithImplRule`)。这两条 Checkstyle 查不了,靠评审;没有对应接口的类不该叫 `Impl`,见 `code-review-checklist.md`。
## 注释
- **类与公共方法写 Javadoc:做什么、边界条件、为什么这么写**。对齐 Spring Framework `SpringJavadocCheck` 关心的项(描述、`@param`、`@return`、`@throws`)。
注释必须跟着签名走:方法被移动或改名时一起搬,别把「取任务名」留在另一个方法头上。
- **注释与用户可见文案用中文**。用户文案另外还要求口语化(见 `api-response.md`)。
- **枚举常量必须带注释**(p3c `EnumConstantsMustHaveCommentRule`)。
- **不留注释掉的代码**(p3c `RemoveCommentedCodeRule`):历史在 git 里,注释掉的代码既不被编译也不会被清理。
## 复杂度
- **方法 ≤ 80 行**(`MethodLength`)。出处:p3c `MethodTooLongRule` 取同一阈值。
- **参数 ≤ 7**(`ParameterNumber`)。出处:Sonar S107;超了先看是不是该收成参数对象。
- **圈复杂度 ≤ 15**(`CyclomaticComplexity`)。注意这是**圈复杂度**,不是 Sonar S3776 的认知复杂度:两者对不同结构计数不同,
S3776 在本仓没有门禁(Checkstyle 不提供这个指标)。Checkstyle 默认阈值是 10,本仓先取 15(10 会把大量普通分支方法打成违规),
存量 6 处靠豁免挂着,往下收用棘轮。
- **嵌套 `if` / `for` / `try` 各 ≤ 3 层**(`NestedIfDepth` / `NestedForDepth` / `NestedTryDepth`);超了用卫语句提前返回。
- **switch 必须有 `default`**(`MissingSwitchDefault`);**重复字面量收敛成常量**(Sonar S1192)是评审项,Checkstyle 没有等价模块。
## 异常与事务
- **`@Transactional` 必须写 `rollbackFor`**(`RegexpSinglelineJava` 的 `transactionRollback`,正则 `@Transactional(?![^)]*rollbackFor)`)。
出处:p3c `TransactionMustHaveRollbackRule`。默认只对 `RuntimeException` 回滚,受检异常抛出去事务照样提交。
- **不抛裸 `Exception` / `Throwable` / `RuntimeException`**(`IllegalThrows`),自定义异常继承具体基类。出处:Sonar S112。
- **捕获不许吞**(`EmptyCatchBlock` 只放行 `expected` / `ignore` 命名的变量):要么处理,要么记日志再抛。出处:Sonar S1166。
- **不 `printStackTrace()`**(`RegexpSinglelineJava` 的 `noPrintStackTrace`):日志框架之外没有上下文,也没有接收方。出处:Sonar S2139 的意图。
- **`String` 比较用 `equals` 不用 `==`**(`StringLiteralEquality`);**重写 `equals` 必须重写 `hashCode`**(`EqualsHashCode`)。
## 持久化与接口边界
这三块不在这里复述,各由对应规则文件持有:
- **数据访问**(查询结果用类承载、禁 `selectMaps` 取字符串 key、SQL 只留在 mapper、写入形态、实体继承 `BaseEntity`)→ `data-access.md`。
- **出参与入参边界**(Entity 不出 controller、请求体用 DTO 不用 `Map`、未知异常映射 500)→ `api-response.md`。
- **迁移脚本**(Flyway 命名、H2 与 MySQL 的差异)→ `database-migration.md`。
## 豁免只减不增(ratchet)
- **现状:债务豁免为 0**。`suppressions.xml` 里只剩 2 条框架约束(见下节),692 处存量违规已在 2026-11-19 全部改完,
折算为:展开 51 处通配 import、全仓格式化、补 181 处大括号、44 个 `@Transactional` 补 `rollbackFor`、
拆 7 个超长类、抽 6 个复杂方法、改 15 处命名、补 4 个私有构造。
- **新增豁免必须在 PR / 提交说明里写理由**,并说明为什么不能改代码。没有理由的新增豁免等于把门禁关掉一格。
只有「框架规定、改了就坏」才能豁免(见下节两条)。
- 跳闸口只有 `-Dcheckstyle.skip=true`(`failOnViolation` 写死在 pom 里,user property 覆盖不了),**只用于本地应急**;
推之前必须再跑一次 `./mvnw validate`。
## 什么不算违规
- **Flyway Java 迁移类的类名**(`TypeName`):`V20261115_2__xxx.java` 的版本前缀是 Flyway 规定的,不满足
`^[A-Z][a-zA-Z0-9]*$` 属**正当例外**——不要改类名,也不要改 Flyway 的命名约定。这条以目录级豁免写在 `suppressions.xml`。
- **`LearningProgressTrackerApplication` 的 `HideUtilityClassConstructor`**:它是 Spring Boot 启动入口,只有 `main`、没有实例方法,
Checkstyle 按「只有静态成员」的工具类特征判到了。给它加私有构造会让 Spring 测试上下文无法实例化启动类
(实测 164 个测试报 `No visible constructors`),所以只能豁免。
- **名字里的业务缩写**(`taskNum`、`aiTaskNum`):`MemberName` / `ParameterName` 只要求 lowerCamelCase,不要求把缩写展开成 `taskNumber`。
业务名以上游术语表为准,缩写形式同样是术语的一部分。
## 不采纳的上游规则
| 上游规则 | 不采纳的理由 |
|---|---|
| p3c `ClassMustHaveAuthorRule` | 模板里的 `@author` 只会被复制粘贴,换手后立刻过期;问「这行是谁写的、为什么」用 `git blame`,答得比注释准。 |
| p3c `PojoMustOverrideToStringRule` | 实体与 DTO 统一用 Lombok `@Data`,`toString` 已经生成;再加一条规则只会报假违规。 |
| p3c `AvoidNegationOperatorRule` | 会逼出 `x == false` 这种更难读的写法;条件里取反(`!ok` 卫语句)是本项目的正常写法。 |
| Google Java Style 的 2 空格缩进与 100 列 | 与本仓既有代码(4 空格、120 列)不符,切换要重排全部源文件,行为不变、评审成本全落在格式噪音上。 |
| Spring Framework 的 tab 缩进 | 同上;且 tab 的显示宽度取决于编辑器设置,跨机器看 diff 对不齐。 |
+65
View File
@@ -0,0 +1,65 @@
# 数据访问层编码规范
- **功能**:规定数据访问层的写法与查询/取锁形态,避免手写 SQL、按字符串 key 取值、逐行查询和并发死锁。
- **何时用**:编写 Mapper 或查询逻辑、需要聚合或联表、写列表/详情/导出类接口、新增取锁逻辑、评审数据访问代码时。
## 编码规范
### 数据访问层
- **优先使用纯 MyBatis-Plus Java API**(`Wrappers.<T>lambdaQuery()`、`selectList`、`selectById` 等),避免手写 XML SQL
- 复杂查询通过 `Wrappers` 链式构建条件,必要时使用 `.apply()` 拼接原生 SQL 片段
- **查询结果一律用类承载,禁止 `selectMaps` + 字符串 key 取值**
- MyBatis 对 Map 结果直接用 JDBC 列名作 key,不做属性映射:`map-underscore-to-camel-case` 与「属性名大小写不敏感」只对类结果生效。而数据库的标识符大小写规则各不相同(MySQL 保留别名、H2/PostgreSQL 转小写、Oracle 转大写),`row.get("taskNum")` 会在部分库上静默取到 null,表现为「数据莫名变 0」而不是报错
- 单列聚合用 `selectObjs`,多列聚合用下面的自定义 Mapper 方法
- **`Wrapper` 表达不了的查询(`SUM`/`GROUP BY`/多表 `JOIN`)收敛到 Mapper 层**,用自定义方法 + **显式结果类**(`dto/` 下的类或实体),参考 `ReviewRecallMapper.sumTaskDuration` → `dto/recall/TaskRecallDuration`
- 结果映射:列名与属性能对应时可用自动映射,但 `map-underscore-to-camel-case` 必须在 `application.yml` 里显式声明(已配置),不要依赖框架默认值;出现别名、计算列或列名与属性不一致时必须写显式 `<resultMap>`
- **自定义 SQL 不会被 `@TableLogic` 自动追加逻辑删除条件**,必须显式写 `deleted = 0`;租户条件 `created_by = ?` 仍由 `TenantLineInnerInterceptor` 自动追加
- 上述两条不能只靠 mock 单测,需落库集成测试守住(参考 `ReviewFeedbackIntegrationTest`、`AiUsageAggregationIntegrationTest`)
- 反向约束:`Wrapper` 能表达的查询不要为「类型安全」提前下沉为自定义 SQL;确实要下沉时,SQL 只留在 Mapper 层,不要在 service 里拼字符串
## 查询次数
- **一次请求的 SQL 条数必须可数,且与行数、子记录数无关。** 库在远端,单程 40–80ms,条数直接等于延迟:
一页 20 行、每行再查 3 次就是 60 次往返。禁止在 `for` / `stream.map` / `forEach` 里调 mapper(N+1)——
先把需要的 id/编号收集起来,一条 `IN` 取齐再在内存里装饰(范例 `ReviewFeedService.mergeAndConvert`、
`RecallDetailAssembler.facts`)。
- **列表只查列表要用的数据。** DTO 里没有的字段不要顺手查:`RecallSummary` 不含 `requests`,列表就不查 AI 任务;
文档类数据(`document_json`)只要分页行里已经带出来,就不要再按主键回表查一遍。
- **分页只发一次 COUNT。** `selectPage` 自带 COUNT,不要再对同一个 wrapper 调 `selectCount`;不需要总数的列表用
`new Page<>(pageNum, pageSize, false)` 或 `selectList`。
- **聚合下推 SQL,并且带过滤条件。** 计数/求和/分组用 `GROUP BY` + 显式结果类(`ReviewStatsService.fillReviewTaskStats` 的写法),
不要在 Java 里遍历全表累加;聚合语句必须带 `IN (...)`、时间窗等条件,禁止每次请求整表 `GROUP BY`。
- **同一份数据一次请求只查一次。** 同一批 id 的任务名、学习预期、待更新导图被查两遍就合并;命中集合算完再一条
`UPDATE ... WHERE id IN (...)`,不要逐行 `updateById`。
- **验证**:改完列表/详情/导出接口,用 `logging.level.com.guo.learningprogresstracker.mapper=DEBUG` 数单次请求的
`==> Preparing:` 条数,再换一个页大小复核条数不变。2026-11-21 回忆列表就是按这条从 47 条降到 7 条
([记录](../notes/implemented/bug-fix/2026-11-21-recall-owner-lock-deadlock-and-read-batching.md))。
## 加锁形态
- **取同一把行锁必须是单一步骤的排他锁。** 禁止 `INSERT IGNORE`(行已存在时只拿共享锁 S)紧跟 `SELECT ... FOR UPDATE`:
两个并发事务各持 S 锁互等 X 锁,InnoDB 直接判定死锁并回滚其一,接口表现为随机 500。
- **两种允许的写法**:
- 锁行一定存在 → 直接 `SELECT ... WHERE <pk> = ? FOR UPDATE`;
- 锁行可能不存在 → 先 `INSERT INTO ... VALUES (...) ON DUPLICATE KEY UPDATE <pk> = <pk>`(命中已有行时这是排他锁),
再 `SELECT ... FOR UPDATE`。参考 `ReviewRecallMapper.ensureOwnerLock` / `lockUser`。
- **锁内只做必要的语句。** 读路径如果会 `reconcile`/抹除数据,就必须和写入串行;此时锁的持有时间等于该事务里的全部语句数,
按上面的「查询次数」把事务压到个位数。
- **验证**:新增或改动取锁逻辑后,用两个并发请求(或两个 JDBC 事务)跑同一条路径,确认没有再出现
`Deadlock found when trying to get lock`;单线程点一遍不算验证。
## 写入形态
- **禁 patch 实体式更新**:不要 `new XxxEntity()` + 只 `set` 变化字段 + `updateById` 就走。两个理由:一是字段清不空——本仓
未显式配 `update-strategy`,MyBatis-Plus 默认跳过 null 字段,用户点了「清空备注」库里的值还在;二是语义依赖全局配置,
那个默认值改一次,全库的 patch 更新行为一起变且不报错。要局部更新先分清是哪种,三选一:
- **整对象替换**:先查到完整实体、改完字段、`updateById`——适合「表单提交整张卡」的场景。
- **`LambdaUpdateWrapper.set(...)`**:需要显式写 null(真清空)时用,意图写在 `.set(field, null)` 上。
- **`XxxPatch` DTO**:由请求对象表达「哪些字段有值才改」,与 `api-response.md` 的入参规范对齐。
现状 17 处 patch 写法(全仓 27 处 `updateById`,其余是整对象更新),例 `ReviewServiceImpl#updateReport`、`ReviewServiceImpl#submitFeedback`。
- **实体统一继承 `BaseEntity`**:`created_by` / `created_time` / `last_modified_by` / `last_modified_time` / `device_info` / `deleted`
由 `config/AutoTableField` 自动填充与 `@TableLogic` 软删除接管。不继承就少审计列,`created_by` 缺失还会让租户拦截器无列可加。
现状:`entity/` 下 19 个业务实体全部继承(`entity/` 的第 20 个文件是 `BaseEntity` 本身)。
- **SQL 只出现在 Mapper**:service 里不拼 SQL 字符串(当前 3 处 `.last("LIMIT " + n)` 属存量违规,见 `code-review-checklist.md`);
需要分页/限量时用参数化占位符,或用 `Page` / `IPage`,再不行下沉到 mapper。
+88 -11
View File
@@ -14,7 +14,9 @@ on:
env:
REGISTRY: 192.168.123.199:5000
APP: lpt-be
REPO_URL: http://git.cat-shark.xyz/cat-shark/lpt-be.git
REPO_URL: https://git.cat-shark.xyz/cat-shark/lpt-be.git
# 仅在 runner 镜像里没有 kubectl 时才会触发下载(自定义镜像已内置)
KUBECTL_VERSION: v1.32.4
jobs:
build-and-deploy:
@@ -22,6 +24,53 @@ jobs:
env:
KUBECONFIG: /tmp/kubeconfig
steps:
# 2026-11-22 事故复盘:runner 以 host 模式运行(labels 带 :host),
# 官方 act_runner 镜像不含 docker/curl/kubectl,导致 docker login 直接 127。
# 这里前置检查 + 自愈,缺工具就明确报错,而不是在第二步莫名其妙失败。
- name: Preflight runner toolchain
run: |
set -euo pipefail
echo "host=$(uname -sm) uid=$(id -u)"
missing() {
local need=""
for b in docker curl base64 git; do
command -v "$b" >/dev/null 2>&1 || need="$need $b"
done
printf '%s' "$need"
}
NEED="$(missing)"
if [ -n "$NEED" ]; then
echo "runner 缺少工具:$NEED —— 尝试自愈安装(apk)"
if command -v apk >/dev/null 2>&1 && [ "$(id -u)" = 0 ]; then
apk add --no-cache docker-cli curl ca-certificates || true
fi
NEED="$(missing)"
fi
for b in docker curl kubectl git base64; do
if command -v "$b" >/dev/null 2>&1; then
echo "OK $b -> $(command -v "$b")"
else
echo "MISS $b"
fi
done
if [ -n "$NEED" ]; then
echo ""
echo "ERROR: runner 缺少必需工具:$NEED"
echo " 由于 labels 全为 :host,job 直接在 runner 容器内执行,"
echo " docker / curl / kubectl 必须存在于 runner 镜像里。"
echo " 修复:docker build -f /vol1/1000/gitea/runner.Dockerfile -t lpt-runner:0.6.1-tools /vol1/1000/gitea"
echo " cd /vol1/1000/gitea && docker compose up -d runner"
exit 1
fi
docker version --format 'docker client {{.Client.Version}} / server {{.Server.Version}}'
docker info >/dev/null
echo "OK docker daemon reachable"
- name: Validate branch ↔ environment
run: |
set -euo pipefail
@@ -64,8 +113,17 @@ jobs:
- name: Checkout code
run: |
set -euo pipefail
git clone "$REPO_URL" .
git checkout "${{ gitea.sha }}"
SHA="${{ gitea.sha }}"
# 优先只取目标提交(省 10s+);服务器不支持任意 SHA 时回退完整克隆
if ! { git init -q . && git remote add origin "$REPO_URL" \
&& git fetch -q --depth 1 origin "$SHA" && git checkout -q FETCH_HEAD; } 2>/dev/null; then
echo "浅拉取失败,回退完整克隆"
rm -rf .git
git clone -q "$REPO_URL" .
git checkout -q "$SHA"
fi
echo "checked out $(git rev-parse HEAD)"
test "$(git rev-parse HEAD)" = "$SHA"
- name: Login to Docker Registry
run: |
@@ -78,22 +136,30 @@ jobs:
ENV="${{ inputs.environment }}"
TAG="${{ gitea.sha }}-$(date +%s)"
echo "Building $REGISTRY/$APP:$TAG (env tag=$ENV)"
docker build -t "$REGISTRY/$APP:$TAG" -t "$REGISTRY/$APP:$ENV" .
docker build \
-t "$REGISTRY/$APP:$TAG" \
-t "$REGISTRY/$APP:$ENV" .
docker push "$REGISTRY/$APP:$TAG"
docker push "$REGISTRY/$APP:$ENV"
echo "IMAGE_TAG=$TAG"
echo "$TAG" > image_tag.txt
# 同时打 :$TAG(可追溯)与 :$ENV(k8s 环境指针)两个 tag
mkdir -p /tmp/lpt-ci
echo "$TAG" > image_tag.txt
echo "$TAG" > /tmp/lpt-ci/image_tag.txt
echo "IMAGE_TAG=$TAG"
- name: Setup kubectl
run: |
set -euo pipefail
curl -sLO "https://dl.k8s.io/release/v1.30.0/bin/linux/amd64/kubectl"
chmod +x kubectl
mv kubectl /usr/local/bin/
if ! command -v kubectl >/dev/null 2>&1; then
echo "kubectl 不在 runner 镜像中,临时下载 $KUBECTL_VERSION"
curl -fsSLo /usr/local/bin/kubectl \
"https://dl.k8s.io/release/${KUBECTL_VERSION}/bin/linux/amd64/kubectl"
chmod +x /usr/local/bin/kubectl
fi
echo "${{ secrets.KUBECONFIG_B64 }}" | base64 -d > /tmp/kubeconfig
chmod 600 /tmp/kubeconfig
kubectl version --client
kubectl cluster-info --request-timeout=20s
- name: Create/Update imagePullSecret
run: |
@@ -109,15 +175,21 @@ jobs:
run: |
set -euo pipefail
ENV="${{ inputs.environment }}"
IMAGE_TAG="$(cat image_tag.txt 2>/dev/null || cat /tmp/lpt-ci/image_tag.txt 2>/dev/null || echo '')"
IMAGE_TAG="$(cat /tmp/lpt-ci/image_tag.txt 2>/dev/null || echo '')"
if [ -z "$IMAGE_TAG" ]; then
echo "ERROR: IMAGE_TAG 为空,无法部署"
exit 1
fi
# 只有真正进入部署阶段才允许回滚,避免 build/checkout 失败时回滚掉上一次成功的版本
mkdir -p /tmp/lpt-ci
: > /tmp/lpt-ci/deploy_attempted
echo "Deploying $REGISTRY/$APP:$IMAGE_TAG -> namespace lpt-$ENV"
# kubectl 1.30+ 已移除 --record,用 annotate 记录本次部署的镜像
kubectl set image "deployment/$APP" \
"$APP=$REGISTRY/$APP:$IMAGE_TAG" \
-n "lpt-$ENV" --record
-n "lpt-$ENV"
kubectl annotate "deployment/$APP" -n "lpt-$ENV" \
"lpt/deployed-image=$IMAGE_TAG" --overwrite || true
kubectl rollout status "deployment/$APP" \
-n "lpt-$ENV" --timeout=5m
@@ -148,5 +220,10 @@ jobs:
run: |
set -euo pipefail
ENV="${{ inputs.environment }}"
if [ ! -f /tmp/lpt-ci/deploy_attempted ]; then
echo "本次运行未进入部署阶段(失败在 checkout/build/login 等前置步骤),跳过回滚"
echo "避免把上一次成功的部署回滚掉"
exit 0
fi
kubectl rollout undo "deployment/$APP" -n "lpt-$ENV" || true
kubectl rollout status "deployment/$APP" -n "lpt-$ENV" || true
+2
View File
@@ -0,0 +1,2 @@
# Frozen Agent Notes are historical snapshots, not current search authority.
/.agents/notes/archived/
+48 -9
View File
@@ -5,13 +5,41 @@
## 规则与技能位置
- 通用规则(跨仓库):meta 仓库 `.agents/roles/`(本仓库的 Git 提交规范也统一在其中的 `commit-convention.md`,本文件不再重复)
- 本仓库专属规则:`roles/`
- `roles/database-migration.md`:数据库迁移(Flyway Migration)
- `roles/data-access.md`:编码规范 · 数据访问层
- `roles/api-response.md`:响应规范、DTO 转换
- `roles/ownership-and-markers.md`:内容归属与结构化报告(归属-01 / 报告-01)、标记(标记-01)
- `roles/ai-integration.md`:学习引导(复习-06)、AI 异步链路(AI-02)
- 本仓库专属技能:`skills/`(如 `comment-cleanup`)
- 命名:业务概念的英文名以 `lpt-docs/docs/concepts/README.md` 术语表为准,库表、实体、DTO 字段由它派生,不另起别名(规则见 meta `.agents/roles/business-terminology.md`)。
- 本仓库专属规则:`.agents/roles/`
- `.agents/roles/database-migration.md`:数据库迁移(Flyway Migration)
- `.agents/roles/code-standards.md`:后端代码规范的取值与出处(Checkstyle 门禁、棘轮、不采纳的上游规则)
- `.agents/roles/code-review-checklist.md`:Checkstyle 查不了、必须人看的评审项(实体出 controller、Map 请求体、patch 更新等)
- `.agents/roles/data-access.md`:编码规范 · 数据访问层与写入形态
- `.agents/roles/api-response.md`:响应规范、DTO 转换
- `.agents/roles/ownership-and-markers.md`:内容归属与结构化报告(归属-01 / 报告-01)、标记(标记-01)
- `.agents/roles/ai-integration.md`:学习引导(复习-06)、AI 异步链路(AI-02)
- 跨服务校验归属:不写在本仓库,统一按 meta 仓库 `.agents/roles/service-boundaries-and-validation.md`
(结构由产出方保证、LLM 输出在调用模型的那侧校验、接收方只做映射)
- 本仓库专属技能:`.agents/skills/`(如 `comment-cleanup`);决策笔记:`.agents/notes/`(见下节「重要改动必须留笔记」)
> **本仓库的 `.agents/` 只放 lpt-be 独有的东西**(上述专属规则、`comment-cleanup`、本仓笔记)。
> 共有技能(`write-notes-like-deepseek`、`mermaid-diagram`)只在 meta 的 `.agents/skills/`,本仓库不放副本。
> agent 在 meta 根目录运行,改动本仓库用 `subagent(cwd=lpt-be)`;详见 meta `AGENTS.md`。
## 重要改动必须留笔记
规则来源:meta 仓库 `.agents/skills/write-notes-like-deepseek/SKILL.md`(动手前先读它,本文件只列接入约定)。
1. **非平凡改动先立笔记**:改了行为、架构、跨文件契约、流程与工具链、测试策略、落盘/网络/配置格式,
或写了会被以后重新审视的取舍,就在 `.agents/notes/` 下写或更新一篇;纯机械改(样式、格式化、打标、
不改行为的依赖补丁、常规 CRUD)直接提交,不要为了留痕而留痕。
2. **先检索再动手**:`rg --hidden --glob '!.agents/notes/archived/**' "<机制名或关键词>" .agents/notes/`,
有归属就**就地更新那篇**(路径、类名、默认值等事实直接改);决定翻转则新开一篇并互链,禁止把
`## Decision` 改成反面。
3. **生命周期**:动手前写 `proposed/`;落地后移到 `implemented/` 并改成现在时;方案被否决且能防重犯写
`rejected/`;彻底被取代才归档。路径格式 `{proposed|implemented|rejected}/{feature|bug-fix|simplification|architecture|process|testing}/yyyy-mm-dd-主题.md`。
4. **备选方案先写对方最强理由再否决**;真实没考虑过备选就写「无」,不要编造凑数。
5. **提交前跑校验**(在 meta 根目录,无 git hook,靠自觉):
```sh
node .agents/scripts/verify-notes.ts lpt-be
```
未接 CI 强制门,红了先修再交。
## 技术栈
@@ -50,14 +78,14 @@ lpt-be/src/main/java/com/guo/learningprogresstracker/
- entity 使用 `@TableName`、`@TableField` 映射数据库字段。
- mapStruct 承载 DTO 转换。
## API 端点总览(86 个)
## API 端点总览(87 个)
| 模块 | 端点数 | 端点 |
|------|--------|------|
| 登录认证 | 2 | `POST /login`, `POST /logout` |
| 学习会话 | 11 | `PUT /study-sessions/{sessionNum}/expectation`, `GET /study-sessions/{sessionNum}/expectation`, `GET /study-sessions/{sessionNum}`, `POST /study-sessions/{sessionNum}/study-sessions/continue`, `POST /study-sessions/{sessionNum}/study-sessions/pause`, `POST /study-sessions/{sessionNum}/study-sessions/ended`, `POST /study-sessions/{sessionNum}/study-sessions/abort`, `GET /study-sessions/{sessionNum}/all-fragments`, `GET /study-sessions/tasks/{taskNum}/fragments`, `GET /study-sessions/tasks/{taskNum}/reports`, `GET /study-sessions/active` |
| 任务管理 | 15 | `GET/POST /tasks`, `GET/PUT/DELETE /tasks/{taskId}`, `GET/PUT /tasks/priority-weights`, `GET /tasks/options`, `GET/POST /tasks/{taskNum}/applications`, `PUT/DELETE /tasks/applications/{id}`, `GET /tasks/{taskNum}/study-sessions/start-or-continue`, `GET /tasks/{taskNum}/not-ended-study-session`, `GET /tasks/{taskId}/deletion-preview` |
| 复习与导图 | 19 | `GET /review/feed`, `PUT /review/feed/{fragmentId}/feedback`, `POST /review/feed/{fragmentId}/touched`, `GET /review/sort-preference`, `PUT /review/sort-preference`, `GET /review/summary`, `GET /review/tasks`, `GET /review/tasks/{taskNum}`, `GET /review/task/{taskNum}`, `GET /review/report/{id}`, `GET /review/report/{id}/structured`, `PUT /review/report/{id}`, `DELETE /review/report/{id}`, `GET /review/fragment/{id}`, `GET /review/standard-mind-map/{taskNum}`, `PUT /review/standard-mind-map/{taskNum}`, `POST /review/standard-mind-map/{taskNum}/find-node`, `GET /review/standard-mind-map/{taskNum}/recall-records`, `GET /review/standard-mind-map/recall-records/{recordId}` |
| 复习与导图 | 20 | `GET /review/feed`, `PUT /review/feed/{fragmentId}/feedback`, `POST /review/feed/{fragmentId}/touched`, `GET /review/sort-preference`, `PUT /review/sort-preference`, `GET /review/summary`, `GET /review/tasks`, `GET /review/tasks/{taskNum}`, `GET /review/task/{taskNum}`, `GET /review/report/{id}`, `GET /review/report/{id}/structured`, `PUT /review/report/{id}`, `DELETE /review/report/{id}`, `GET /review/fragment/{id}`, `GET /review/standard-mind-map/{taskNum}`, `PUT /review/standard-mind-map/{taskNum}`, `POST /review/standard-mind-map/{taskNum}/find-node`, `GET /review/standard-mind-map/{taskNum}/recall-records`, `GET /review/standard-mind-map/recall-records/{recordId}`, `GET /review/recalls/related` |
| 标签导图 | 4 | `POST /review/tag-mind-map/query`, `PUT /review/tag-mind-map`, `GET /review/tag-mind-map/list`, `POST /review/tag-mind-map/recall-records` |
| 知识碎片 | 6 | `POST /report-fragments`, `PUT /report-fragments/{id}`, `PUT /report-fragments/{id}/ownership`, `DELETE /report-fragments/{id}`, `GET /report-fragments/session/{sessionNum}`, `GET /report-fragments/pending-ownership` |
| 数据导出 | 2 | `GET /export/task/{taskNum}`, `GET /export/range` |
@@ -72,6 +100,10 @@ lpt-be/src/main/java/com/guo/learningprogresstracker/
> 让前端静默隐藏入口,其余 4 个接口直接拒绝。`POST /internal/ai-usage/records` 是 lpt-ai 的上报入口,
> 没有登录态,在 `WebMvcConfig` 里排除了 Sa-Token,改用 `x-api-token` 与 `lpt.ai-usage.report-token` 比对。
> 自由回忆的 `/review/recalls` 系列(创建、列表、详情、恢复、保存、来源、删除)未在本表逐条列出。
> 其中 `GET /review/recalls` 支持可选 `excludeRecallNum`,由 SQL 排除指定的那条回忆(最近回忆首屏用它排除顶部「上次编辑的导图」)。
> `GET /review/recalls/related` 按所选标签(重复 `tags` 参数,1–10 个)查保存过的导图,命中标签多的在前,分页在 SQL 里完成。
## 数据库(11 个核心表)
`users`, `tasks`, `study_sessions`, `study_reports`, `study_report_fragments`, `study_expectations`, `task_applications`, `review_standard_mind_maps`, `review_recall_records`, `user_priority_weights`, `ai_usage_records`
@@ -172,8 +204,15 @@ lpt-be/src/main/java/com/guo/learningprogresstracker/
```bash
mvn clean compile -DskipTests # 编译(需要 JDK 17)
mvn spring-boot:run # 启动(默认 profile: local)
./mvnw validate # 先跑 Checkstyle,违规即失败
```
- **Checkstyle 门禁**:`./mvnw validate` 会先跑 Checkstyle(绑 `validate` 阶段,`failOnViolation=true`,只查 `src/main/java`),
`test` / `package` / CI / Docker 构建都会先撞上它。配置在 `config/checkstyle/`:`checkstyle.xml` 是规则与阈值,
`suppressions.xml` 是存量豁免基线(改到被豁免的文件时顺手删掉对应豁免行)。
- **应急跳闸**:`-Dcheckstyle.skip=true` 只用于本地临时绕过(`failOnViolation` 写死在 pom,user property 覆盖不了),
推之前必须再跑一次 `./mvnw validate`。规则取值、理由与出处见 `.agents/roles/code-standards.md`。
## 关联项目
| 项目 | 路径 | 端口 | 说明 |
+96
View File
@@ -0,0 +1,96 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
<module name="LineLength">
<property name="max" value="120"/>
<property name="fileExtensions" value="java"/>
</module>
<module name="FileTabCharacter"/>
<module name="FileLength">
<property name="max" value="400"/>
<property name="fileExtensions" value="java"/>
</module>
<module name="SuppressionFilter">
<property name="file" value="${checkstyle.suppressions.file}"/>
<property name="optional" value="false"/>
</module>
<module name="TreeWalker">
<module name="AvoidStarImport"/>
<module name="UnusedImports"/>
<module name="RedundantImport"/>
<module name="OneStatementPerLine"/>
<module name="NeedBraces"/>
<module name="EmptyCatchBlock">
<property name="exceptionVariableName" value="expected|ignore"/>
</module>
<module name="EmptyStatement"/>
<module name="MultipleVariableDeclarations"/>
<module name="ModifierOrder"/>
<module name="UpperEll"/>
<module name="ArrayTypeStyle"/>
<module name="OuterTypeFilename"/>
<module name="OneTopLevelClass"/>
<module name="TypeName">
<property name="format" value="^[A-Z][a-zA-Z0-9]*$"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
</module>
<module name="LocalVariableName">
<property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
</module>
<module name="ParameterName">
<property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
</module>
<module name="ConstantName">
<property name="format" value="^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"/>
</module>
<module name="PackageName">
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
</module>
<module name="StringLiteralEquality"/>
<module name="EqualsHashCode"/>
<module name="IllegalThrows"/>
<module name="MissingSwitchDefault"/>
<module name="FallThrough"/>
<module name="HideUtilityClassConstructor"/>
<module name="NestedIfDepth">
<property name="max" value="3"/>
</module>
<module name="NestedForDepth">
<property name="max" value="3"/>
</module>
<module name="NestedTryDepth">
<property name="max" value="3"/>
</module>
<module name="CyclomaticComplexity">
<property name="max" value="15"/>
</module>
<module name="MethodLength">
<property name="max" value="80"/>
</module>
<module name="ParameterNumber">
<property name="max" value="7"/>
</module>
<module name="RegexpSinglelineJava">
<property name="id" value="noSystemOut"/>
<property name="format" value="System\.(out|err)\.print"/>
<property name="maximum" value="0"/>
</module>
<module name="RegexpSinglelineJava">
<property name="id" value="noPrintStackTrace"/>
<property name="format" value="\.printStackTrace\(\)"/>
<property name="maximum" value="0"/>
</module>
<module name="RegexpSinglelineJava">
<property name="id" value="transactionRollback"/>
<property name="format" value="@Transactional\b(?![^)]*rollbackFor)"/>
<property name="maximum" value="0"/>
</module>
</module>
</module>
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
"https://checkstyle.org/dtds/suppressions_1_2.dtd">
<suppressions>
<!-- 设计例外:Flyway Java 迁移类的类名由 Flyway 规定(VyyyyMMdd_n__desc),不满足 TypeName 的大小写规则。
这不是存量债务,是框架约束;迁移类不可改名,改名会让 Flyway 认为已有迁移消失。 -->
<suppress files="src[\\/]main[\\/]java[\\/]db[\\/]migration[\\/].*\.java$" checks="TypeName"/>
<!-- 设计例外:Spring Boot 启动入口只有 static main,Checkstyle 按「只有静态成员」的工具类特征判它。
真给入口类加 private 构造会让 Spring 测试上下文无法实例化启动类(实测 164 个测试报
"No visible constructors in class LearningProgressTrackerApplication"),所以这里只能豁免。 -->
<suppress files="src[\\/]main[\\/]java[\\/]com[\\/]guo[\\/]learningprogresstracker[\\/]LearningProgressTrackerApplication\.java$"
checks="HideUtilityClassConstructor"/>
</suppressions>
+29
View File
@@ -178,6 +178,35 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.3.1</version>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>10.12.4</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>checkstyle-validate</id>
<phase>validate</phase>
<goals>
<goal>check</goal>
</goals>
<configuration>
<configLocation>config/checkstyle/checkstyle.xml</configLocation>
<suppressionsLocation>config/checkstyle/suppressions.xml</suppressionsLocation>
<failOnViolation>true</failOnViolation>
<consoleOutput>true</consoleOutput>
<includeTestSourceDirectory>false</includeTestSourceDirectory>
<inputEncoding>UTF-8</inputEncoding>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
-19
View File
@@ -1,19 +0,0 @@
# 数据访问层编码规范
- **功能**:规定数据访问层的实现方式,避免手写 SQL 与字符串 key 取值带来的跨库隐患。
- **何时用**:编写 Mapper 或查询逻辑、需要聚合或联表、评审数据访问代码时。
## 编码规范
### 数据访问层
- **优先使用纯 MyBatis-Plus Java API**(`Wrappers.<T>lambdaQuery()`、`selectList`、`selectById` 等),避免手写 XML SQL
- 复杂查询通过 `Wrappers` 链式构建条件,必要时使用 `.apply()` 拼接原生 SQL 片段
- **查询结果一律用类承载,禁止 `selectMaps` + 字符串 key 取值**
- MyBatis 对 Map 结果直接用 JDBC 列名作 key,不做属性映射:`map-underscore-to-camel-case` 与「属性名大小写不敏感」只对类结果生效。而数据库的标识符大小写规则各不相同(MySQL 保留别名、H2/PostgreSQL 转小写、Oracle 转大写),`row.get("taskNum")` 会在部分库上静默取到 null,表现为「数据莫名变 0」而不是报错
- 单列聚合用 `selectObjs`,多列聚合用下面的自定义 Mapper 方法
- **`Wrapper` 表达不了的查询(`SUM`/`GROUP BY`/多表 `JOIN`)收敛到 Mapper 层**,用自定义方法 + **显式结果类**(`dto/` 下的类或实体),参考 `ReviewRecallRecordMapper.sumReviewDurationByTask` → `dto/TaskReviewDuration` + `resources/mapper/ReviewRecallRecordMapper.xml`
- 结果映射:列名与属性能对应时可用自动映射,但 `map-underscore-to-camel-case` 必须在 `application.yml` 里显式声明(已配置),不要依赖框架默认值;出现别名、计算列或列名与属性不一致时必须写显式 `<resultMap>`
- **自定义 SQL 不会被 `@TableLogic` 自动追加逻辑删除条件**,必须显式写 `deleted = 0`;租户条件 `created_by = ?` 仍由 `TenantLineInnerInterceptor` 自动追加
- 上述两条不能只靠 mock 单测,需落库集成测试守住(参考 `ReviewDurationIntegrationTest`)
- 反向约束:`Wrapper` 能表达的查询不要为「类型安全」提前下沉为自定义 SQL;确实要下沉时,SQL 只留在 Mapper 层,不要在 service 里拼字符串
@@ -1,6 +1,7 @@
package com.guo.learningprogresstracker;
import cn.dev33.satoken.SaManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -8,12 +9,12 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
* @author guo
* 应用程序启动类
*/
@Slf4j
@SpringBootApplication
public class LearningProgressTrackerApplication {
public static void main(String[] args) {
SpringApplication.run(LearningProgressTrackerApplication.class, args);
System.out.println("启动成功,Sa-Token 配置如下:" + SaManager.getConfig());
log.info("启动成功,Sa-Token 配置如下:{}", SaManager.getConfig());
}
}
@@ -15,51 +15,55 @@ import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(com.guo.learningprogresstracker.exception.RecallBusinessException.class)
public CommonResult<com.guo.learningprogresstracker.dto.recall.RecallDtos.BusinessError> recallBusinessException(
com.guo.learningprogresstracker.exception.RecallBusinessException ex) {
return new CommonResult<>(400, ex.getMessage(), ex.getData());
}
@ExceptionHandler({ErrorParameterException.class})
public CommonResult errorParameterException(ErrorParameterException ex) {
public CommonResult<Void> errorParameterException(ErrorParameterException ex) {
log.warn("参数异常: {}", ex.getMessage(), ex);
return CommonResult.error(ex.getMessage());
}
@ExceptionHandler({NotFindEntitiesException.class})
public CommonResult notFindEntitiesException(NotFindEntitiesException ex) {
public CommonResult<Void> notFindEntitiesException(NotFindEntitiesException ex) {
log.warn("数据不存在: {}", ex.getMessage(), ex);
return CommonResult.error(ex.getMessage());
}
@ExceptionHandler({OperationFailedException.class})
public CommonResult operationFailedException(OperationFailedException ex) {
public CommonResult<Void> operationFailedException(OperationFailedException ex) {
log.warn("操作失败: {}", ex.getMessage(), ex);
return CommonResult.error(ex.getMessage());
}
@ExceptionHandler({AppException.class})
public CommonResult AppException(AppException ex) {
public CommonResult<Void> handleAppException(AppException ex) {
log.error("业务异常: {}", ex.getMessage(), ex);
return CommonResult.serverError(ex.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public CommonResult MyMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
public CommonResult<Void> handleArgumentNotValid(MethodArgumentNotValidException ex) {
BindingResult bindingResult = ex.getBindingResult();
return CommonResult.error(bindingResult.getFieldError().getDefaultMessage());
}
@ExceptionHandler(NotLoginException.class)
public CommonResult handleNotLogin(NotLoginException e, HttpServletRequest req, HttpServletResponse res) {
public CommonResult<Void> handleNotLogin(NotLoginException e, HttpServletRequest req, HttpServletResponse res) {
res.setStatus(HttpStatus.UNAUTHORIZED.value());
return new CommonResult<>(HttpStatus.UNAUTHORIZED.value(), "未登录,请重新登录", null);
}
@ExceptionHandler(Exception.class)
public CommonResult Exception(Exception ex) {
public CommonResult<Void> handleUnexpected(Exception ex) {
log.error("系统异常", ex);
return CommonResult.error("操作没有成功,请稍后再试");
return CommonResult.serverError("操作没有成功,请稍后再试");
}
}
@@ -7,10 +7,8 @@ import jakarta.validation.groups.Default;
*/
public interface Ops {
// 创建组
interface CreateG extends Default {
}
interface CreateG extends Default {}
// 更新组
interface UpdateG {
}
interface UpdateG {}
}
@@ -35,8 +35,8 @@ public class StudyTimePolicy {
*/
private final long minEffectiveTimeSeconds;
public StudyTimePolicy(int workDurationMinutes, int forgetThresholdMinutes,
int forcePauseMinutes, long minEffectiveTimeSeconds) {
public StudyTimePolicy(
int workDurationMinutes, int forgetThresholdMinutes, int forcePauseMinutes, long minEffectiveTimeSeconds) {
if (workDurationMinutes <= 0) {
throw new IllegalArgumentException("番茄钟长度必须大于 0 分钟");
}
@@ -18,13 +18,11 @@ public final class TenantContext {
* @param loginId 登录用户
* @param device 设备类型,可为 null(后台任务通常没有设备信息)
*/
public record Identity(String loginId, String device) {
}
public record Identity(String loginId, String device) {}
private static final ThreadLocal<Identity> CURRENT = new ThreadLocal<>();
private TenantContext() {
}
private TenantContext() {}
/** 取当前执行身份;未设置时返回 null(表示应回落到 StpUtil) */
public static Identity get() {
@@ -1,11 +1,10 @@
package com.guo.learningprogresstracker.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.math.BigDecimal;
import java.util.List;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* AI 用量统计配置。
@@ -3,12 +3,11 @@ package com.guo.learningprogresstracker.config;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.guo.learningprogresstracker.common.TenantContext;
import java.time.LocalDateTime;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDateTime;
/**
* 用于公共字段的自动填充
*
@@ -18,7 +17,6 @@ import java.time.LocalDateTime;
@Slf4j
public class AutoTableField implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "createdBy", AutoTableField::currentLoginId, String.class);
@@ -28,7 +26,6 @@ public class AutoTableField implements MetaObjectHandler {
this.strictInsertFill(metaObject, "deviceInfo", AutoTableField::currentDevice, String.class);
}
@Override
public void updateFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "lastModifiedBy", AutoTableField::currentLoginId, String.class);
@@ -51,5 +48,4 @@ public class AutoTableField implements MetaObjectHandler {
TenantContext.Identity identity = TenantContext.get();
return identity != null ? identity.device() : StpUtil.getLoginDevice();
}
}
@@ -10,5 +10,4 @@ import org.springframework.context.annotation.Configuration;
public class CorsProperties {
private String[] allowedOrigins;
private Boolean allowCredentials;
}
@@ -4,12 +4,11 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.guo.learningprogresstracker.config.serializer.LocalDateTimeSerializer;
import java.time.LocalDateTime;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.time.LocalDateTime;
@Configuration
public class JacksonConfig {
@Bean
@@ -1,18 +1,17 @@
package com.guo.learningprogresstracker.config;
import cn.dev33.satoken.stp.StpUtil;
import com.guo.learningprogresstracker.common.TenantContext;
import net.sf.jsqlparser.expression.StringValue;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import net.sf.jsqlparser.expression.Expression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.guo.learningprogresstracker.common.TenantContext;
import java.util.Arrays;
import java.util.List;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* MyBatis-Plus 多租户配置
@@ -30,12 +29,7 @@ public class MybatisPlusConfig {
* 若按 created_by 过滤,每个人只能看到自己触发的那几次调用,面板等于永远空的。</p>
*/
private static final List<String> EXCLUDE_TABLES = Arrays.asList(
"user",
"flyway_schema_history",
"databasechangelog",
"databasechangeloglock",
"ai_usage_records"
);
"user", "flyway_schema_history", "databasechangelog", "databasechangeloglock", "ai_usage_records");
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
@@ -3,6 +3,7 @@ package com.guo.learningprogresstracker.config;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import java.util.Arrays;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
@@ -10,8 +11,6 @@ import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Arrays;
@Configuration
@RequiredArgsConstructor
@Slf4j
@@ -49,7 +48,8 @@ public class WebMvcConfig implements WebMvcConfigurer {
.allowedOrigins(origins)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(corsProperties.getAllowCredentials() == null || corsProperties.getAllowCredentials());
.allowCredentials(
corsProperties.getAllowCredentials() == null || corsProperties.getAllowCredentials());
}
}
}
@@ -3,13 +3,12 @@ package com.guo.learningprogresstracker.config.serializer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
public LocalDateTimeSerializer() {
super(LocalDateTime.class);
@@ -20,7 +19,7 @@ public class LocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
if (value == null) {
gen.writeNull();
} else {
String formattedDate = value.format(formatter);
String formattedDate = value.format(FORMATTER);
gen.writeString(formattedDate);
}
}
@@ -9,7 +9,13 @@ import com.guo.learningprogresstracker.service.AiTaskService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* AI 异步任务控制层(AI-02)。
@@ -49,8 +55,7 @@ public class AiTaskController {
* @return 无任务时 data 为 null
*/
@GetMapping("/latest")
public CommonResult<AiTaskResponse> getLatestTask(@RequestParam String type,
@RequestParam String targetNum) {
public CommonResult<AiTaskResponse> getLatestTask(@RequestParam String type, @RequestParam String targetNum) {
return CommonResult.success(aiTaskService.findLatest(type, targetNum));
}
}
@@ -9,13 +9,12 @@ import com.guo.learningprogresstracker.dto.request.AiUsageQuery;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.exception.ErrorParameterException;
import com.guo.learningprogresstracker.service.AiUsageService;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 「AI 用量统计」面板查询接口(契约 2)。
*
@@ -8,6 +8,7 @@ import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.exception.ErrorParameterException;
import com.guo.learningprogresstracker.service.AiUsageService;
import jakarta.validation.Valid;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@@ -15,8 +16,6 @@ import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* lpt-ai 用量上报(契约 1)。
*
@@ -43,7 +42,8 @@ public class AiUsageInternalController {
@PostMapping("/records")
public CommonResult<AiUsageIngestResult> report(
@RequestHeader(name = "x-api-token", required = false) String apiToken,
@Valid @RequestBody AiUsageReportRequest request) throws ErrorParameterException {
@Valid @RequestBody AiUsageReportRequest request)
throws ErrorParameterException {
if (!isTokenAccepted(apiToken)) {
return CommonResult.error("上报令牌不正确");
}
@@ -5,12 +5,15 @@ import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
import com.guo.learningprogresstracker.exception.OperationFailedException;
import com.guo.learningprogresstracker.service.ExportService;
import java.time.LocalDate;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* 数据导出控制层(导出-01):把学习报告、知识碎片与任务统计导出为 Markdown / JSON。
@@ -29,8 +32,7 @@ public class ExportController {
*/
@GetMapping("/task/{taskNum}")
public CommonResult<ExportResult> exportTask(
@PathVariable String taskNum,
@RequestParam(defaultValue = "markdown") String format)
@PathVariable String taskNum, @RequestParam(defaultValue = "markdown") String format)
throws NotFindEntitiesException, OperationFailedException {
return CommonResult.success(exportService.exportTask(taskNum, format));
}
@@ -1,24 +1,34 @@
package com.guo.learningprogresstracker.controller;
import com.guo.learningprogresstracker.dto.AiTaskResponse;
import com.guo.learningprogresstracker.dto.ReviewTiming;
import com.guo.learningprogresstracker.dto.request.AiTaskSubmitRequest;
import com.guo.learningprogresstracker.dto.request.ConfirmGuidanceFragmentRequest;
import com.guo.learningprogresstracker.dto.request.GuidanceStartRequest;
import com.guo.learningprogresstracker.dto.request.GuidanceTurnRequest;
import com.guo.learningprogresstracker.dto.response.GuidanceConversationResponse;
import com.guo.learningprogresstracker.dto.response.ReportFragmentResponse;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.entity.ReviewGuidanceConversationEntity;
import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity;
import com.guo.learningprogresstracker.exception.ErrorParameterException;
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
import com.guo.learningprogresstracker.service.AiTaskService;
import com.guo.learningprogresstracker.service.GuidanceService;
import com.guo.learningprogresstracker.dto.AiTaskResponse;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
import java.util.LinkedHashMap;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 学习引导控制层(复习-06)。
@@ -42,11 +52,10 @@ public class GuidanceController {
*/
@PostMapping
@Operation(summary = "开启学习引导:返回引导编号与首个 AI 任务编号")
public CommonResult<Map<String, Object>> start(@RequestBody Map<String, String> body)
public CommonResult<Map<String, Object>> start(@Valid @RequestBody GuidanceStartRequest request)
throws NotFindEntitiesException, ErrorParameterException {
String taskNum = body == null ? null : body.get("taskNum");
String concept = body == null ? null : body.get("concept");
ReviewGuidanceConversationEntity conversation = guidanceService.start(taskNum, concept);
ReviewGuidanceConversationEntity conversation =
guidanceService.start(request.getTaskNum(), request.getConcept());
Map<String, Object> result = new LinkedHashMap<>();
result.put("guidanceNum", conversation.getGuidanceNum());
@@ -60,10 +69,10 @@ public class GuidanceController {
* 继续一轮:提交用户的回答/追问,返回本轮 AI 任务编号
*/
@PostMapping("/{guidanceNum}/turns")
public CommonResult<AiTaskResponse> continueTurn(@PathVariable String guidanceNum,
@RequestBody Map<String, String> body)
public CommonResult<AiTaskResponse> continueTurn(
@PathVariable String guidanceNum, @Valid @RequestBody GuidanceTurnRequest request)
throws NotFindEntitiesException, ErrorParameterException {
guidanceService.appendUserTurn(guidanceNum, body == null ? null : body.get("message"));
guidanceService.appendUserTurn(guidanceNum, request.getMessage());
return CommonResult.success(submitTurn(guidanceNum));
}
@@ -71,9 +80,9 @@ public class GuidanceController {
* 读取这次引导的当前状态(含对话轮次),用于离开页面后回来继续
*/
@GetMapping("/{guidanceNum}")
public CommonResult<ReviewGuidanceConversationEntity> getConversation(@PathVariable String guidanceNum)
public CommonResult<GuidanceConversationResponse> getConversation(@PathVariable String guidanceNum)
throws NotFindEntitiesException {
return CommonResult.success(guidanceService.getByGuidanceNum(guidanceNum));
return CommonResult.success(GuidanceConversationResponse.of(guidanceService.getByGuidanceNum(guidanceNum)));
}
/**
@@ -81,16 +90,16 @@ public class GuidanceController {
* <p>不确认就不产生任何数据。</p>
*/
@PostMapping("/{guidanceNum}/fragments")
public CommonResult<StudyReportFragmentsEntity> confirmFragment(@PathVariable String guidanceNum,
@RequestBody Map<String, Object> body)
public CommonResult<ReportFragmentResponse> confirmFragment(
@PathVariable String guidanceNum, @RequestBody ConfirmGuidanceFragmentRequest request)
throws ErrorParameterException, NotFindEntitiesException {
String content = body == null ? null : (String) body.get("content");
ReviewTiming timing = new ReviewTiming(
parseTime(body == null ? null : body.get("reviewStartedAt")),
parseTime(body == null ? null : body.get("reviewLastInteractionAt")),
body != null && body.get("reviewDurationSeconds") instanceof Number number
? number.intValue() : null);
return CommonResult.success(guidanceService.confirmFragment(guidanceNum, content, timing));
parseTime(request.getReviewStartedAt()),
parseTime(request.getReviewLastInteractionAt()),
request.getReviewDurationSeconds());
String content = request.getContent();
return CommonResult.success(
ReportFragmentResponse.of(guidanceService.confirmFragment(guidanceNum, content, timing)));
}
/**
@@ -1,8 +1,8 @@
package com.guo.learningprogresstracker.controller;
import com.guo.learningprogresstracker.dto.LoginResult;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.dto.request.LoginBody;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.exception.AppException;
import com.guo.learningprogresstracker.service.AiUsageService;
import com.guo.learningprogresstracker.service.LoginService;
@@ -14,7 +14,6 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@CrossOrigin
@RestController
@RequiredArgsConstructor
@@ -32,7 +31,7 @@ public class LoginController {
// 用量面板的入口是否显示由服务端白名单决定,前端只读这个布尔值
boolean aiAdmin = aiUsageService.isAdmin();
// todo 参数传递未加密
return CommonResult.success("登录成功!", new LoginResult(token, aiAdmin));
return CommonResult.success("登录成功!", new LoginResult(token, aiAdmin, userId));
}
@Operation(summary = "退出登录API")
@@ -1,21 +1,34 @@
package com.guo.learningprogresstracker.controller;
import com.guo.learningprogresstracker.dto.MarkerUsage;
import com.guo.learningprogresstracker.dto.request.AddUserTagRequest;
import com.guo.learningprogresstracker.dto.request.CreateDictionaryTagRequest;
import com.guo.learningprogresstracker.dto.request.RenameDictionaryTagRequest;
import com.guo.learningprogresstracker.dto.request.RenameUserTagRequest;
import com.guo.learningprogresstracker.dto.response.MarkerResponse;
import com.guo.learningprogresstracker.dto.response.UserTagResponse;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.entity.MarkerEntity;
import com.guo.learningprogresstracker.entity.UserTagEntity;
import com.guo.learningprogresstracker.enums.MarkerObjectTypeEnum;
import com.guo.learningprogresstracker.exception.ErrorParameterException;
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
import com.guo.learningprogresstracker.service.MarkerService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* 统一标记控制层(标记-01)。
@@ -35,20 +48,26 @@ public class MarkerController {
* 列出某个对象上的全部标记(系统标记与用户标签一起返回,前端按 kind 区分展示)
*/
@GetMapping
public CommonResult<List<MarkerEntity>> listByObject(@RequestParam String objectType,
@RequestParam String objectNum) {
return CommonResult.success(markerService.listByObject(MarkerObjectTypeEnum.parse(objectType), objectNum));
public CommonResult<List<MarkerResponse>> listByObject(
@RequestParam String objectType, @RequestParam String objectNum) {
return CommonResult.success(
markerService.listByObject(MarkerObjectTypeEnum.parse(objectType), objectNum).stream()
.map(MarkerResponse::of)
.toList());
}
/**
* 批量列出多个对象的标记(列表页一次取回一页,避免逐个请求)
*/
@PostMapping("/batch")
public CommonResult<Map<String, List<MarkerEntity>>> listByObjects(
@RequestParam String objectType,
@RequestBody Collection<String> objectNums) {
return CommonResult.success(
markerService.listByObjects(MarkerObjectTypeEnum.parse(objectType), objectNums));
public CommonResult<Map<String, List<MarkerResponse>>> listByObjects(
@RequestParam String objectType, @RequestBody Collection<String> objectNums) {
Map<String, List<MarkerResponse>> result = new LinkedHashMap<>();
markerService
.listByObjects(MarkerObjectTypeEnum.parse(objectType), objectNums)
.forEach((key, value) ->
result.put(key, value.stream().map(MarkerResponse::of).toList()));
return CommonResult.success(result);
}
/**
@@ -56,13 +75,10 @@ public class MarkerController {
*/
@PostMapping
@Operation(summary = "打用户标签;系统标记只能由系统写入,不开放此接口")
public CommonResult<MarkerEntity> addUserTag(@RequestBody Map<String, String> body)
public CommonResult<MarkerResponse> addUserTag(@Valid @RequestBody AddUserTagRequest request)
throws ErrorParameterException, NotFindEntitiesException {
String objectType = body == null ? null : body.get("objectType");
String objectNum = body == null ? null : body.get("objectNum");
String markerName = body == null ? null : body.get("markerName");
return CommonResult.success(
markerService.addUserTag(MarkerObjectTypeEnum.parse(objectType), objectNum, markerName));
return CommonResult.success(MarkerResponse.of(markerService.addUserTag(
MarkerObjectTypeEnum.parse(request.getObjectType()), request.getObjectNum(), request.getMarkerName())));
}
/**
@@ -79,18 +95,17 @@ public class MarkerController {
* 重命名一个用户标签(影响所有带该标签的对象)
*/
@PutMapping("/rename")
public CommonResult<Integer> renameUserTag(@RequestBody Map<String, String> body)
public CommonResult<Integer> renameUserTag(@Valid @RequestBody RenameUserTagRequest request)
throws ErrorParameterException {
String from = body == null ? null : body.get("oldName");
String to = body == null ? null : body.get("newName");
return CommonResult.success(markerService.renameUserTag(from, to));
return CommonResult.success(markerService.renameUserTag(request.getOldName(), request.getNewName()));
}
/**
* 按标记筛选对象(点标签即筛选):返回带该标记的对象标识列表
*/
@GetMapping("/filter")
public CommonResult<List<String>> filterByMarker(@RequestParam String objectType,
public CommonResult<List<String>> filterByMarker(
@RequestParam String objectType,
@RequestParam String markerName,
@RequestParam(required = false) String markerValue,
@RequestParam(required = false) String kind) {
@@ -102,37 +117,38 @@ public class MarkerController {
* 当前用户用过的标签及使用情况(标签管理入口)
*/
@GetMapping("/tags")
public CommonResult<List<MarkerUsage>> listUserTagUsage() {
return CommonResult.success(markerService.listUserTagUsage());
public CommonResult<List<MarkerUsage>> listUserTagUsage(@RequestParam(required = false) String objectType) {
return CommonResult.success(
markerService.listUserTagUsage(objectType == null ? null : MarkerObjectTypeEnum.parse(objectType)));
}
/**
* 标签字典:打标签的候选标签(尚未挂在任何对象上的也算)
*/
@GetMapping("/tags/dictionary")
public CommonResult<List<UserTagEntity>> listDictionaryTags() {
return CommonResult.success(markerService.listDictionaryTags());
public CommonResult<List<UserTagResponse>> listDictionaryTags() {
return CommonResult.success(markerService.listDictionaryTags().stream()
.map(UserTagResponse::of)
.toList());
}
/**
* 往字典里新建一个(空)标签;同名(按去空格、大小写不敏感)已存在时幂等返回既有项
*/
@PostMapping("/tags/dictionary")
public CommonResult<UserTagEntity> createDictionaryTag(@RequestBody Map<String, String> body)
public CommonResult<UserTagResponse> createDictionaryTag(@Valid @RequestBody CreateDictionaryTagRequest request)
throws ErrorParameterException {
String tagName = body == null ? null : body.get("tagName");
return CommonResult.success(markerService.createDictionaryTag(tagName));
return CommonResult.success(UserTagResponse.of(markerService.createDictionaryTag(request.getTagName())));
}
/**
* 字典标签改名:只影响候选,不改动任何对象上已经打好的标记
*/
@PutMapping("/tags/dictionary/{id}")
public CommonResult<UserTagEntity> renameDictionaryTag(@PathVariable Integer id,
@RequestBody Map<String, String> body)
public CommonResult<UserTagResponse> renameDictionaryTag(
@PathVariable Integer id, @Valid @RequestBody RenameDictionaryTagRequest request)
throws ErrorParameterException, NotFindEntitiesException {
String newName = body == null ? null : body.get("newName");
return CommonResult.success(markerService.renameDictionaryTag(id, newName));
return CommonResult.success(UserTagResponse.of(markerService.renameDictionaryTag(id, request.getNewName())));
}
/**
@@ -1,18 +1,24 @@
package com.guo.learningprogresstracker.controller;
import com.guo.learningprogresstracker.dto.request.AssignOwnershipRequest;
import com.guo.learningprogresstracker.dto.request.CreateFragmentsRequest;
import com.guo.learningprogresstracker.dto.request.UpdateFragmentsRequest;
import com.guo.learningprogresstracker.dto.response.ReportFragmentResponse;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity;
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
import com.guo.learningprogresstracker.service.impl.StudyReportFragmentsServiceImpl;
import jakarta.validation.Valid;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 知识碎片控制层(归属-01 起同时承载「内容归属」的调整动作)。
@@ -21,14 +27,15 @@ import java.util.Map;
@RestController
@Validated
@RequiredArgsConstructor
public class reportFragmentsController {
public class ReportFragmentsController {
private final StudyReportFragmentsServiceImpl studyReportFragmentsServiceImpl;
/**
* 创建知识碎片(记录上下文为当前学习会话,内容归属默认取该会话所属任务)
*/
@PostMapping
public CommonResult<Void> createFragments(@Valid @RequestBody CreateFragmentsRequest request) throws NotFindEntitiesException {
public CommonResult<Void> createFragments(@Valid @RequestBody CreateFragmentsRequest request)
throws NotFindEntitiesException {
studyReportFragmentsServiceImpl.createFragments(request);
return CommonResult.success();
}
@@ -37,8 +44,8 @@ public class reportFragmentsController {
* 修改知识碎片正文与内容归属(记录上下文不可变)
*/
@PutMapping("/{id}")
public CommonResult<Void> updateFragments(@PathVariable Integer id,
@RequestBody UpdateFragmentsRequest request) throws NotFindEntitiesException {
public CommonResult<Void> updateFragments(@PathVariable Integer id, @RequestBody UpdateFragmentsRequest request)
throws NotFindEntitiesException {
studyReportFragmentsServiceImpl.updateFragments(id, request);
return CommonResult.success();
}
@@ -47,10 +54,10 @@ public class reportFragmentsController {
* 调整内容归属;body 传 {"ownerTaskNum": "TASK-xxx"},传空字符串表示清空归属(回到待归类)
*/
@PutMapping("/{id}/ownership")
public CommonResult<Void> assignOwnership(@PathVariable Integer id,
@RequestBody Map<String, String> body) throws NotFindEntitiesException {
String ownerTaskNum = body == null ? null : body.get("ownerTaskNum");
studyReportFragmentsServiceImpl.assignOwnership(id, ownerTaskNum);
public CommonResult<Void> assignOwnership(
@PathVariable Integer id, @Valid @RequestBody AssignOwnershipRequest request)
throws NotFindEntitiesException {
studyReportFragmentsServiceImpl.assignOwnership(id, request.getOwnerTaskNum());
return CommonResult.success();
}
@@ -67,8 +74,11 @@ public class reportFragmentsController {
* 获取指定会话产生的所有知识碎片(记录上下文为会话)
*/
@GetMapping("/session/{sessionNum}")
public CommonResult<List<StudyReportFragmentsEntity>> getFragmentsBySession(@PathVariable String sessionNum) {
List<StudyReportFragmentsEntity> fragments = studyReportFragmentsServiceImpl.getFragmentsBySession(sessionNum);
public CommonResult<List<ReportFragmentResponse>> getFragmentsBySession(@PathVariable String sessionNum) {
List<ReportFragmentResponse> fragments =
studyReportFragmentsServiceImpl.getFragmentsBySession(sessionNum).stream()
.map(ReportFragmentResponse::of)
.toList();
return CommonResult.success(fragments);
}
@@ -76,7 +86,9 @@ public class reportFragmentsController {
* 待归类内容:还没有确定内容归属的碎片
*/
@GetMapping("/pending-ownership")
public CommonResult<List<StudyReportFragmentsEntity>> getPendingOwnershipFragments() {
return CommonResult.success(studyReportFragmentsServiceImpl.getPendingOwnershipFragments());
public CommonResult<List<ReportFragmentResponse>> getPendingOwnershipFragments() {
return CommonResult.success(studyReportFragmentsServiceImpl.getPendingOwnershipFragments().stream()
.map(ReportFragmentResponse::of)
.toList());
}
}
@@ -1,30 +1,38 @@
package com.guo.learningprogresstracker.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guo.learningprogresstracker.dto.ReviewFeedItem;
import com.guo.learningprogresstracker.dto.ReviewSortPreference;
import com.guo.learningprogresstracker.dto.ReviewSummary;
import com.guo.learningprogresstracker.dto.ReviewTaskStats;
import com.guo.learningprogresstracker.dto.StudyReportDetail;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guo.learningprogresstracker.dto.request.UpdateStandardMindMapRequest;
import com.guo.learningprogresstracker.dto.request.FindNodeRequest;
import com.guo.learningprogresstracker.dto.request.ReviewFeedbackRequest;
import com.guo.learningprogresstracker.dto.request.SortPreferenceRequest;
import com.guo.learningprogresstracker.dto.request.UpdateStandardMindMapRequest;
import com.guo.learningprogresstracker.dto.request.UpdateStudyReportRequest;
import com.guo.learningprogresstracker.dto.response.ReportFragmentResponse;
import com.guo.learningprogresstracker.dto.response.StandardMindMapResponse;
import com.guo.learningprogresstracker.dto.response.StudyReportResponse;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity;
import com.guo.learningprogresstracker.entity.ReviewStandardMindMapEntity;
import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity;
import com.guo.learningprogresstracker.entity.StudyReportsEntity;
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
import com.guo.learningprogresstracker.exception.OperationFailedException;
import com.guo.learningprogresstracker.service.ReviewService;
import com.guo.learningprogresstracker.service.StandardMindMapService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* 复习模块控制层 — 复习内容滚动展示与交互
@@ -44,8 +52,7 @@ public class ReviewController {
*/
@GetMapping("/feed")
public CommonResult<List<ReviewFeedItem>> getReviewFeed(
@RequestParam(defaultValue = "30") int limit,
@RequestParam(defaultValue = "recent") String mode) {
@RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "recent") String mode) {
return CommonResult.success(reviewService.getReviewFeed(limit, mode));
}
@@ -55,8 +62,8 @@ public class ReviewController {
*/
@PutMapping("/feed/{fragmentId}/feedback")
public CommonResult<ReviewFeedbackRequest> submitFeedback(
@PathVariable Integer fragmentId,
@RequestBody ReviewFeedbackRequest request) throws NotFindEntitiesException {
@PathVariable Integer fragmentId, @RequestBody ReviewFeedbackRequest request)
throws NotFindEntitiesException {
return CommonResult.success(reviewService.submitFeedback(fragmentId, request));
}
@@ -81,9 +88,8 @@ public class ReviewController {
* 保存复习排序偏好(复习-01):三档预设,不做精确权重。
*/
@PutMapping("/sort-preference")
public CommonResult<ReviewSortPreference> saveSortPreference(@RequestBody Map<String, String> body) {
String preset = body == null ? null : body.get("preset");
return CommonResult.success(reviewService.saveSortPreference(preset));
public CommonResult<ReviewSortPreference> saveSortPreference(@RequestBody SortPreferenceRequest request) {
return CommonResult.success(reviewService.saveSortPreference(request.getPreset()));
}
/**
@@ -132,8 +138,8 @@ public class ReviewController {
* 获取报告详情(原始实体)
*/
@GetMapping("/report/{id}")
public CommonResult<StudyReportsEntity> getReportDetail(@PathVariable int id) throws NotFindEntitiesException {
return CommonResult.success(reviewService.getReportDetail(id));
public CommonResult<StudyReportResponse> getReportDetail(@PathVariable int id) throws NotFindEntitiesException {
return CommonResult.success(StudyReportResponse.of(reviewService.getReportDetail(id)));
}
/**
@@ -149,8 +155,7 @@ public class ReviewController {
* 修改学习报告的三段文本
*/
@PutMapping("/report/{id}")
public CommonResult<Void> updateReport(@PathVariable int id,
@RequestBody UpdateStudyReportRequest request)
public CommonResult<Void> updateReport(@PathVariable int id, @RequestBody UpdateStudyReportRequest request)
throws NotFindEntitiesException {
reviewService.updateReport(id, request);
return CommonResult.success();
@@ -169,8 +174,9 @@ public class ReviewController {
* 获取残片详情
*/
@GetMapping("/fragment/{id}")
public CommonResult<StudyReportFragmentsEntity> getFragmentDetail(@PathVariable int id) throws NotFindEntitiesException {
return CommonResult.success(reviewService.getFragmentDetail(id));
public CommonResult<ReportFragmentResponse> getFragmentDetail(@PathVariable int id)
throws NotFindEntitiesException {
return CommonResult.success(ReportFragmentResponse.of(reviewService.getFragmentDetail(id)));
}
// ============ 标准思维导图与回忆对比 ============
@@ -182,19 +188,20 @@ public class ReviewController {
* {@code POST /ai/tasks}(type=MIND_MAP)后轮询结果。</p>
*/
@GetMapping("/standard-mind-map/{taskNum}")
public CommonResult<ReviewStandardMindMapEntity> getStandardMindMap(
@PathVariable String taskNum) throws NotFindEntitiesException {
return CommonResult.success(standardMindMapService.getExisting(taskNum));
public CommonResult<StandardMindMapResponse> getStandardMindMap(@PathVariable String taskNum)
throws NotFindEntitiesException {
return CommonResult.success(StandardMindMapResponse.of(standardMindMapService.getExisting(taskNum)));
}
/**
* 用户编辑标准思维导图(大纲文本形式)
*/
@PutMapping("/standard-mind-map/{taskNum}")
public CommonResult<ReviewStandardMindMapEntity> updateStandardMindMap(
@PathVariable String taskNum,
@Valid @RequestBody UpdateStandardMindMapRequest request) throws NotFindEntitiesException {
return CommonResult.success(standardMindMapService.updateByOutline(taskNum, request.getOutline()));
public CommonResult<StandardMindMapResponse> updateStandardMindMap(
@PathVariable String taskNum, @Valid @RequestBody UpdateStandardMindMapRequest request)
throws NotFindEntitiesException {
return CommonResult.success(
StandardMindMapResponse.of(standardMindMapService.updateByOutline(taskNum, request.getOutline())));
}
/**
@@ -202,27 +209,9 @@ public class ReviewController {
*/
@PostMapping("/standard-mind-map/{taskNum}/find-node")
public CommonResult<Map<String, Object>> findNode(
@PathVariable String taskNum,
@RequestBody Map<String, String> body) throws NotFindEntitiesException, OperationFailedException {
String content = body != null ? body.getOrDefault("content", "") : "";
@PathVariable String taskNum, @RequestBody FindNodeRequest request)
throws NotFindEntitiesException, OperationFailedException {
String content = request == null || request.getContent() == null ? "" : request.getContent();
return CommonResult.success(standardMindMapService.findNode(taskNum, content));
}
/**
* 获取该任务的所有回忆对比记录
*/
@GetMapping("/standard-mind-map/{taskNum}/recall-records")
public CommonResult<List<ReviewRecallRecordEntity>> listRecallRecords(
@PathVariable String taskNum) throws NotFindEntitiesException {
return CommonResult.success(standardMindMapService.listRecallRecords(taskNum));
}
/**
* 获取单条回忆对比记录详情
*/
@GetMapping("/standard-mind-map/recall-records/{recordId}")
public CommonResult<ReviewRecallRecordEntity> getRecallRecord(
@PathVariable Integer recordId) throws NotFindEntitiesException {
return CommonResult.success(standardMindMapService.getRecallRecord(recordId));
}
}
@@ -0,0 +1,100 @@
package com.guo.learningprogresstracker.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.CreateRecallRequest;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallDetail;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallPage;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceContent;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferencePage;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.RelatedRecallPage;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ResumeRequest;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.SaveDraftRequest;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.service.ai.RecallJson;
import com.guo.learningprogresstracker.service.recall.ReviewRecallService;
import lombok.RequiredArgsConstructor;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/review/recalls")
@RequiredArgsConstructor
public class ReviewRecallController {
private final ReviewRecallService service;
private final RecallJson json;
@PostMapping
public CommonResult<RecallDetail> create(@RequestBody JsonNode body) {
return CommonResult.success(service.create(json.readInput(body, CreateRecallRequest.class)));
}
@GetMapping
public CommonResult<RecallPage> list(
@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "20") int pageSize,
@RequestParam(required = false) String scopeType,
@RequestParam(required = false) String taskNum,
@RequestParam MultiValueMap<String, String> query,
@RequestParam(required = false) String combineMode,
@RequestParam(required = false) String excludeRecallNum) {
// Read repeated values verbatim: a comma can be part of a single tag name.
return CommonResult.success(service.list(
pageNum, pageSize, scopeType, taskNum, query.get("tags"), combineMode, excludeRecallNum));
}
/**
* 总览「相关导图」:按所选标签查保存过的导图。
*
* <p>标签用重复参数传({@code ?tags=A&tags=B}),与列表一致:逗号可能是标签名的一部分。
* 路径写在 {@code /{recallNum}} 之前,避免被单条回忆的详情路由抢走。</p>
*/
@GetMapping("/related")
public CommonResult<RelatedRecallPage> related(
@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "10") int pageSize,
@RequestParam MultiValueMap<String, String> query) {
return CommonResult.success(service.related(pageNum, pageSize, query.get("tags")));
}
@GetMapping("/{recallNum}")
public CommonResult<RecallDetail> get(@PathVariable String recallNum) {
return CommonResult.success(service.get(recallNum));
}
@PostMapping("/{recallNum}/resume")
public CommonResult<RecallDetail> resume(@PathVariable String recallNum, @RequestBody JsonNode body) {
return CommonResult.success(service.resume(recallNum, json.readInput(body, ResumeRequest.class)));
}
@PutMapping("/{recallNum}/draft")
public CommonResult<RecallDetail> draft(@PathVariable String recallNum, @RequestBody JsonNode body) {
return CommonResult.success(service.draft(recallNum, json.readInput(body, SaveDraftRequest.class)));
}
@GetMapping("/{recallNum}/references")
public CommonResult<ReferencePage> references(
@PathVariable String recallNum,
@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "10") int pageSize) {
return CommonResult.success(service.references(recallNum, pageNum, pageSize));
}
@GetMapping("/{recallNum}/references/sources/{sourceId}")
public CommonResult<ReferenceContent> source(@PathVariable String recallNum, @PathVariable String sourceId) {
return CommonResult.success(service.source(recallNum, sourceId));
}
@DeleteMapping("/{recallNum}")
public CommonResult<Void> delete(@PathVariable String recallNum) {
service.delete(recallNum);
return CommonResult.success();
}
}
@@ -1,13 +1,15 @@
package com.guo.learningprogresstracker.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.protobuf.ServiceException;
import com.guo.learningprogresstracker.dto.request.AbortStudySessionRequest;
import com.guo.learningprogresstracker.dto.request.EndedStudySessionRequest;
import com.guo.learningprogresstracker.dto.request.UpsertExpectationRequest;
import com.guo.learningprogresstracker.dto.response.ReportFragmentResponse;
import com.guo.learningprogresstracker.dto.response.StudyExpectationResponse;
import com.guo.learningprogresstracker.dto.response.StudyReportResponse;
import com.guo.learningprogresstracker.dto.response.StudySessionResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.entity.StudyExpectationsEntity;
import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity;
import com.guo.learningprogresstracker.entity.StudyReportsEntity;
import com.guo.learningprogresstracker.exception.ErrorParameterException;
@@ -15,12 +17,18 @@ import com.guo.learningprogresstracker.service.StudyExpectationsService;
import com.guo.learningprogresstracker.service.impl.StudySessionsServiceImpl;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import java.time.LocalDateTime;
import java.util.ArrayList;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.time.LocalDateTime;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* 学习会话控制层
@@ -39,26 +47,27 @@ public class StudySessionController {
* 创建/更新学习会话的学习预期
*/
@PutMapping("/{sessionNum}/expectation")
public CommonResult<StudyExpectationsEntity> upsertExpectation(
@PathVariable("sessionNum") String sessionNum,
@Valid @RequestBody UpsertExpectationRequest request) throws ErrorParameterException {
return CommonResult.success(studyExpectationsService.upsertExpectation(sessionNum, request.getDescription()));
public CommonResult<StudyExpectationResponse> upsertExpectation(
@PathVariable("sessionNum") String sessionNum, @Valid @RequestBody UpsertExpectationRequest request)
throws ErrorParameterException {
return CommonResult.success(StudyExpectationResponse.of(
studyExpectationsService.upsertExpectation(sessionNum, request.getDescription())));
}
/**
* 获取学习会话的学习预期
*/
@GetMapping("/{sessionNum}/expectation")
public CommonResult<StudyExpectationsEntity> getExpectation(
@PathVariable("sessionNum") String sessionNum) {
return CommonResult.success(studyExpectationsService.getBySessionNum(sessionNum));
public CommonResult<StudyExpectationResponse> getExpectation(@PathVariable("sessionNum") String sessionNum) {
return CommonResult.success(StudyExpectationResponse.of(studyExpectationsService.getBySessionNum(sessionNum)));
}
/**
* 通过sessionNum获取一个【学习会话】
*/
@GetMapping("/{sessionNum}")
public CommonResult<StudySessionResponse> getStudySessionBySessionNum(@NotEmpty(message = "请提供学习会话编号") @PathVariable String sessionNum) throws ErrorParameterException {
public CommonResult<StudySessionResponse> getStudySessionBySessionNum(
@NotEmpty(message = "请提供学习会话编号") @PathVariable String sessionNum) throws ErrorParameterException {
// 通过 service 层获取,包含归属校验
StudySessionResponse response = studySessionsServiceImpl.getStudySessionBySessionNum(sessionNum);
return CommonResult.success(response);
@@ -68,7 +77,8 @@ public class StudySessionController {
* 开始一个【学习会话】
*/
@PostMapping("/{sessionNum}/study-sessions/continue")
public CommonResult<Void> startStudySession(@PathVariable("sessionNum") String sessionNum) throws ErrorParameterException, ServiceException {
public CommonResult<Void> startStudySession(@PathVariable("sessionNum") String sessionNum)
throws ErrorParameterException, ServiceException {
studySessionsServiceImpl.continueStudySession(sessionNum);
return CommonResult.success();
}
@@ -77,7 +87,8 @@ public class StudySessionController {
* 暂停一个【学习会话】
*/
@PostMapping("/{sessionNum}/study-sessions/pause")
public CommonResult<Void> pauseStudySession(@PathVariable("sessionNum") String sessionNum,
public CommonResult<Void> pauseStudySession(
@PathVariable("sessionNum") String sessionNum,
@RequestParam(value = "endTime", required = false) LocalDateTime endTime)
throws ErrorParameterException, ServiceException {
studySessionsServiceImpl.pauseStudySession(sessionNum, endTime);
@@ -88,9 +99,11 @@ public class StudySessionController {
* 结束一个【学习会话】
*/
@PostMapping("/{sessionNum}/study-sessions/ended")
public CommonResult<Void> endedStudySession(@PathVariable("sessionNum") String sessionNum,
@Valid @RequestBody EndedStudySessionRequest request) throws ErrorParameterException {
String message = studySessionsServiceImpl.endedStudySession(sessionNum,
public CommonResult<Void> endedStudySession(
@PathVariable("sessionNum") String sessionNum, @Valid @RequestBody EndedStudySessionRequest request)
throws ErrorParameterException {
String message = studySessionsServiceImpl.endedStudySession(
sessionNum,
new com.guo.learningprogresstracker.dto.ReportSections(
request.getSessionSummary(), request.getExpectationVerdict(), request.getFreeSummary()));
return message != null ? CommonResult.success(message) : CommonResult.success();
@@ -100,8 +113,9 @@ public class StudySessionController {
* 误操作结束一个【学习会话】:需输入确认语,严格零数据(删除会话与预期),仅未产生学习残片时可用
*/
@PostMapping("/{sessionNum}/study-sessions/abort")
public CommonResult<Void> abortStudySession(@PathVariable("sessionNum") String sessionNum,
@Valid @RequestBody AbortStudySessionRequest request) throws ErrorParameterException {
public CommonResult<Void> abortStudySession(
@PathVariable("sessionNum") String sessionNum, @Valid @RequestBody AbortStudySessionRequest request)
throws ErrorParameterException {
studySessionsServiceImpl.abortStudySession(sessionNum, request.getConfirmation());
return CommonResult.success();
}
@@ -110,36 +124,45 @@ public class StudySessionController {
* 获取【学习会话】所有的学习残片数据,以列表返回
*/
@GetMapping("/{sessionNum}/all-fragments")
public CommonResult<ArrayList<String>> getAllFragments(@PathVariable("sessionNum") String sessionNum) throws ErrorParameterException {
public CommonResult<ArrayList<String>> getAllFragments(@PathVariable("sessionNum") String sessionNum)
throws ErrorParameterException {
ArrayList<String> allFragments = studySessionsServiceImpl.getAllFragments(sessionNum);
return CommonResult.success(allFragments);
}
/** 分页查询任务的残片历史 */
@GetMapping("/tasks/{taskNum}/fragments")
public CommonResult<Page<StudyReportFragmentsEntity>> getTaskFragments(
public CommonResult<Page<ReportFragmentResponse>> getTaskFragments(
@PathVariable String taskNum,
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(required = false) String keyword) {
return CommonResult.success(studySessionsServiceImpl.getTaskFragments(taskNum, page, size, keyword));
Page<StudyReportFragmentsEntity> entities =
studySessionsServiceImpl.getTaskFragments(taskNum, page, size, keyword);
Page<ReportFragmentResponse> result =
new Page<>(entities.getCurrent(), entities.getSize(), entities.getTotal());
result.setRecords(
entities.getRecords().stream().map(ReportFragmentResponse::of).toList());
return CommonResult.success(result);
}
/** 分页查询任务的报告历史 */
@GetMapping("/tasks/{taskNum}/reports")
public CommonResult<Page<StudyReportsEntity>> getTaskReports(
public CommonResult<Page<StudyReportResponse>> getTaskReports(
@PathVariable String taskNum,
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(required = false) String keyword) {
return CommonResult.success(studySessionsServiceImpl.getTaskReports(taskNum, page, size, keyword));
Page<StudyReportsEntity> entities = studySessionsServiceImpl.getTaskReports(taskNum, page, size, keyword);
Page<StudyReportResponse> result = new Page<>(entities.getCurrent(), entities.getSize(), entities.getTotal());
result.setRecords(
entities.getRecords().stream().map(StudyReportResponse::of).toList());
return CommonResult.success(result);
}
/** 查询当前是否有活跃会话(用于跨页面恢复 + 阻止多任务) */
@GetMapping("/active")
public CommonResult<StudySessionResponse> getActiveSession(
@RequestParam(required = false) String excludeTaskNum) {
public CommonResult<StudySessionResponse> getActiveSession(@RequestParam(required = false) String excludeTaskNum) {
return CommonResult.success(studySessionsServiceImpl.getActiveSession(excludeTaskNum));
}
}
@@ -6,17 +6,20 @@ import com.guo.learningprogresstracker.dto.TagMindMapView;
import com.guo.learningprogresstracker.dto.TagScope;
import com.guo.learningprogresstracker.dto.request.TagScopeRequest;
import com.guo.learningprogresstracker.dto.request.UpdateTagMindMapRequest;
import com.guo.learningprogresstracker.dto.response.TagMindMapResponse;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity;
import com.guo.learningprogresstracker.entity.ReviewTagMindMapEntity;
import com.guo.learningprogresstracker.exception.ErrorParameterException;
import com.guo.learningprogresstracker.service.ReviewTagMindMapService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* 标签导图控制层(闭环-04)。
@@ -24,8 +27,7 @@ import java.util.List;
* <p>按标签复习与按任务复习并存:任务导图仍走 {@code /review/standard-mind-map/{taskNum}},
* 这里只负责以「标签集合 + 取数模式」为范围的那一半。</p>
*
* <p>生成与回忆对比都不在请求线程里等 AI:由前端提交 {@code POST /ai/tasks}
* (type=TAG_MIND_MAP / TAG_RECALL_COMPARE)后轮询结果,与既有 AI 任务链路同一约定。</p>
* <p>生成走 {@code POST /ai/tasks}(type=TAG_MIND_MAP),复习统一进入自由回忆工作区。</p>
*/
@RequestMapping("/review/tag-mind-map")
@RestController
@@ -52,10 +54,11 @@ public class TagMindMapController {
* 用户编辑标签导图(大纲文本形式);该范围还没有导图时保存即为新建。
*/
@PutMapping
public CommonResult<ReviewTagMindMapEntity> updateTagMindMap(
@Valid @RequestBody UpdateTagMindMapRequest request) throws ErrorParameterException {
public CommonResult<TagMindMapResponse> updateTagMindMap(@Valid @RequestBody UpdateTagMindMapRequest request)
throws ErrorParameterException {
TagScope scope = reviewTagMindMapService.resolveScope(request.getTags(), request.getMode());
return CommonResult.success(reviewTagMindMapService.updateByOutline(scope, request.getOutline()));
return CommonResult.success(
TagMindMapResponse.of(reviewTagMindMapService.updateByOutline(scope, request.getOutline())));
}
/**
@@ -70,14 +73,4 @@ public class TagMindMapController {
@RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {
return CommonResult.success(reviewTagMindMapService.listMaps(pageNum, pageSize));
}
/**
* 该范围的回忆对比记录(倒序,最近一次在最前);范围里没有记录时返回空列表。
*/
@PostMapping("/recall-records")
public CommonResult<List<ReviewRecallRecordEntity>> listRecallRecords(
@Valid @RequestBody TagScopeRequest request) throws ErrorParameterException {
TagScope scope = reviewTagMindMapService.resolveScope(request.getTags(), request.getMode());
return CommonResult.success(reviewTagMindMapService.listRecallRecords(scope));
}
}
@@ -6,13 +6,14 @@ import com.guo.learningprogresstracker.common.Ops;
import com.guo.learningprogresstracker.dto.TaskInfo;
import com.guo.learningprogresstracker.dto.TaskOption;
import com.guo.learningprogresstracker.dto.request.CreateTaskApplicationRequest;
import com.guo.learningprogresstracker.dto.response.StudySessionResponse;
import com.guo.learningprogresstracker.dto.response.TaskInfoResponse;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.dto.request.PriorityWeightsRequest;
import com.guo.learningprogresstracker.dto.request.TaskRequest;
import com.guo.learningprogresstracker.dto.request.UpdateTaskApplicationRequest;
import com.guo.learningprogresstracker.entity.TaskApplicationEntity;
import com.guo.learningprogresstracker.entity.UserPriorityWeightsEntity;
import com.guo.learningprogresstracker.dto.response.PriorityWeightsResponse;
import com.guo.learningprogresstracker.dto.response.StudySessionResponse;
import com.guo.learningprogresstracker.dto.response.TaskApplicationResponse;
import com.guo.learningprogresstracker.dto.response.TaskInfoResponse;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.exception.ErrorParameterException;
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
import com.guo.learningprogresstracker.service.PriorityWeightsService;
@@ -21,6 +22,8 @@ import com.guo.learningprogresstracker.service.impl.StudySessionsServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import java.rmi.ServerException;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
@@ -33,9 +36,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.rmi.ServerException;
import java.util.List;
/**
* 任务控制层
*
@@ -55,20 +55,21 @@ public class TaskController {
@GetMapping("/priority-weights")
@Operation(summary = "获取优先级维度权重配置")
public CommonResult<UserPriorityWeightsEntity> getPriorityWeights() {
return CommonResult.success(priorityWeightsService.getWeights());
public CommonResult<PriorityWeightsResponse> getPriorityWeights() {
return CommonResult.success(PriorityWeightsResponse.of(priorityWeightsService.getWeights()));
}
@PutMapping("/priority-weights")
@Operation(summary = "保存优先级维度权重配置并重算全部任务优先级")
public CommonResult<UserPriorityWeightsEntity> savePriorityWeights(
@RequestBody UserPriorityWeightsEntity weights) throws ErrorParameterException {
return CommonResult.success(priorityWeightsService.saveWeights(weights));
public CommonResult<PriorityWeightsResponse> savePriorityWeights(@Valid @RequestBody PriorityWeightsRequest request)
throws ErrorParameterException {
return CommonResult.success(PriorityWeightsResponse.of(priorityWeightsService.saveWeights(request.toEntity())));
}
@PostMapping
@Operation(summary = "添加新任务")
public CommonResult<String> addTask(@RequestBody @Validated({Ops.CreateG.class}) TaskRequest taskRequest) throws ErrorParameterException {
public CommonResult<String> addTask(@RequestBody @Validated({Ops.CreateG.class}) TaskRequest taskRequest)
throws ErrorParameterException {
return CommonResult.success("请求成功", tasksService.addTask(taskRequest));
}
@@ -80,7 +81,8 @@ public class TaskController {
@PutMapping("/{taskId}")
@Operation(summary = "更新任务详情")
public CommonResult<Void> updateTask(@PathVariable("taskId") String taskId, @Validated(Ops.UpdateG.class) @RequestBody TaskRequest updatedTask) {
public CommonResult<Void> updateTask(
@PathVariable("taskId") String taskId, @Validated(Ops.UpdateG.class) @RequestBody TaskRequest updatedTask) {
tasksService.updateTask(taskId, updatedTask);
return CommonResult.success();
}
@@ -101,25 +103,28 @@ public class TaskController {
@GetMapping("/{taskNum}/applications")
@Operation(summary = "获取任务应用场景列表")
public CommonResult<List<TaskApplicationEntity>> getApplications(@PathVariable String taskNum) throws NotFindEntitiesException {
return CommonResult.success(tasksService.getApplications(taskNum));
public CommonResult<List<TaskApplicationResponse>> getApplications(@PathVariable String taskNum)
throws NotFindEntitiesException {
return CommonResult.success(tasksService.getApplications(taskNum).stream()
.map(TaskApplicationResponse::of)
.toList());
}
@PostMapping("/{taskNum}/applications")
@Operation(summary = "创建任务应用场景")
public CommonResult<TaskApplicationEntity> createApplication(
@PathVariable String taskNum,
@Valid @RequestBody CreateTaskApplicationRequest request) throws NotFindEntitiesException {
public CommonResult<TaskApplicationResponse> createApplication(
@PathVariable String taskNum, @Valid @RequestBody CreateTaskApplicationRequest request)
throws NotFindEntitiesException {
request.setTaskNum(taskNum);
return CommonResult.success(tasksService.createApplication(request));
return CommonResult.success(TaskApplicationResponse.of(tasksService.createApplication(request)));
}
@PutMapping("/applications/{id}")
@Operation(summary = "更新任务应用场景")
public CommonResult<TaskApplicationEntity> updateApplication(
@PathVariable Integer id,
@Valid @RequestBody UpdateTaskApplicationRequest request) throws NotFindEntitiesException {
return CommonResult.success(tasksService.updateApplication(id, request));
public CommonResult<TaskApplicationResponse> updateApplication(
@PathVariable Integer id, @Valid @RequestBody UpdateTaskApplicationRequest request)
throws NotFindEntitiesException {
return CommonResult.success(TaskApplicationResponse.of(tasksService.updateApplication(id, request)));
}
@DeleteMapping("/applications/{id}")
@@ -137,7 +142,8 @@ public class TaskController {
@GetMapping
@Operation(summary = "获取所有任务列表")
public CommonResult<Page<TaskInfo>> tasksList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
public CommonResult<Page<TaskInfo>> tasksList(
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
return CommonResult.success(tasksService.taskList(pageNum, pageSize));
}
@@ -146,19 +152,19 @@ public class TaskController {
* 开始或继续一个【学习会话】
*/
@GetMapping("/{taskNum}/study-sessions/start-or-continue")
public CommonResult<StudySessionResponse> startOrContinueStudySession(@NotEmpty(message = "请提供任务编号")
@PathVariable String taskNum) throws NotFindEntitiesException, ServiceException {
public CommonResult<StudySessionResponse> startOrContinueStudySession(
@NotEmpty(message = "请提供任务编号") @PathVariable String taskNum)
throws NotFindEntitiesException, ErrorParameterException, ServiceException {
StudySessionResponse response = studySessionsServiceImpl.startOrContinueStudySession(taskNum);
return CommonResult.success(response);
}
/**
* 通过学习任务num获取该任务的未结束会话
*/
@GetMapping("/{taskNum}/not-ended-study-session")
public CommonResult<StudySessionResponse> getNotEndedStudySessionByTaskNum(@NotEmpty(message = "请提供任务编号")
@PathVariable String taskNum) throws ErrorParameterException {
public CommonResult<StudySessionResponse> getNotEndedStudySessionByTaskNum(
@NotEmpty(message = "请提供任务编号") @PathVariable String taskNum) throws ErrorParameterException {
StudySessionResponse response = studySessionsServiceImpl.getNotEndedStudySessionByTaskNum(taskNum);
return CommonResult.success(response);
}
@@ -3,13 +3,12 @@ package com.guo.learningprogresstracker.controller;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.utils.TitleFetcher;
import io.swagger.v3.oas.annotations.Operation;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/utils")
public class UtilsController {
@@ -2,10 +2,9 @@ package com.guo.learningprogresstracker.dto;
import com.guo.learningprogresstracker.entity.AiTaskEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.Map;
import lombok.Data;
/**
* AI 任务对外视图(AI-02)。
@@ -18,7 +17,7 @@ public class AiTaskResponse {
@Schema(description = "AI 任务编号")
private String taskNum;
@Schema(description = "任务类型:RECALL_COMPARE / MIND_MAP / REPORT_DRAFT")
@Schema(description = "任务类型:RECALL_HINT / RECALL_CHECK / MIND_MAP / TAG_MIND_MAP / REPORT_DRAFT / GUIDANCE")
private String type;
@Schema(description = "目标编号:学习任务编号或学习会话编号")
@@ -30,6 +29,8 @@ public class AiTaskResponse {
@Schema(description = "失败原因(用户可见文案)")
private String errorMessage;
private String errorCode;
@Schema(description = "提交时间")
private LocalDateTime createdTime;
@@ -39,6 +40,28 @@ public class AiTaskResponse {
@Schema(description = "成功结果,随任务类型不同;未完成时为 null")
private Map<String, Object> result;
@com.fasterxml.jackson.annotation.JsonGetter("createdTime")
public Object createdTimeJson() {
return createdTime == null
? null
: isRecall()
? createdTime.atZone(java.time.ZoneId.systemDefault()).toInstant()
: createdTime;
}
@com.fasterxml.jackson.annotation.JsonGetter("finishedTime")
public Object finishedTimeJson() {
return finishedTime == null
? null
: isRecall()
? finishedTime.atZone(java.time.ZoneId.systemDefault()).toInstant()
: finishedTime;
}
private boolean isRecall() {
return "RECALL_HINT".equals(type) || "RECALL_CHECK".equals(type);
}
public static AiTaskResponse from(AiTaskEntity entity, Map<String, Object> result) {
AiTaskResponse response = new AiTaskResponse();
response.setTaskNum(entity.getTaskNum());
@@ -46,6 +69,7 @@ public class AiTaskResponse {
response.setTargetNum(entity.getTargetNum());
response.setStatus(entity.getStatus());
response.setErrorMessage(entity.getErrorMessage());
response.setErrorCode(entity.getErrorCode());
response.setCreatedTime(entity.getCreatedTime());
response.setFinishedTime(entity.getFinishedTime());
response.setResult(result);
@@ -1,8 +1,7 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.math.BigDecimal;
import lombok.Data;
/**
* 用量按任务类型 / 模型 / 用户分组的一项(契约 2.4、v2 第 4.2 节,{@code GET /ai/usage/breakdown})。
@@ -1,8 +1,7 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.math.BigDecimal;
import lombok.Data;
/**
* 用量按任务类型 / 模型分组的聚合结果(Mapper 层直接映射,契约 2.4)。
@@ -1,8 +1,7 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.math.BigDecimal;
import lombok.Data;
/**
* 用量趋势的一个分桶(契约 2.3,{@code GET /ai/usage/series})。
@@ -1,8 +1,7 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.math.BigDecimal;
import lombok.Data;
/**
* 用量趋势的分桶聚合结果(Mapper 层直接映射,契约 2.3)。
@@ -1,8 +1,7 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.math.BigDecimal;
import lombok.Data;
/**
* AI 用量汇总(契约 2.2,{@code GET /ai/usage/summary})。
@@ -1,8 +1,7 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.math.BigDecimal;
import lombok.Data;
/**
* 用量汇总的聚合结果(Mapper 层直接映射,契约 2.2)。
@@ -1,11 +1,10 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
/**
* 一次导出的完整文档(导出-01)。Markdown 与 JSON 都由它渲染,保证两种格式内容一致。
@@ -1,8 +1,7 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.time.LocalDateTime;
import lombok.Data;
/**
* 导出的一条内容(学习报告或知识碎片,导出-01)。
@@ -12,9 +11,14 @@ public class ExportEntry {
private Integer id;
/** 记录上下文:产生这条内容的学习会话编号 */
/** 兼容字段:仅 SESSION 来源填写;复习行为不伪造学习会话。 */
private String sessionNum;
/** SESSION / REVIEW,独立于内容归属。 */
private String contextType;
private String contextNum;
private LocalDateTime createdTime;
/** 报告或碎片的原文 */
@@ -1,9 +1,8 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
/**
* 导出文档中的一个学习任务段落(导出-01)。
@@ -17,4 +17,7 @@ public class LoginResult {
/** 该用户是否在 {@code lpt.ai-usage.admin-usernames} 白名单里 */
private boolean aiAdmin;
/** Stable opaque account identity for user-isolated draft caches; never an AI prompt field. */
private String accountId;
}
@@ -6,5 +6,4 @@ package com.guo.learningprogresstracker.dto;
* <p>碎片正文之外带一个可空的 {@code reportRef}:指向同源的报告上下文。
* LLM 据此知道哪些碎片来自带报告的那次会话,从而只从中提取与这些碎片相关的内容。</p>
*/
public record MindMapFragmentPayload(String content, String reportRef) {
}
public record MindMapFragmentPayload(String content, String reportRef) {}
@@ -14,16 +14,14 @@ import io.swagger.v3.oas.annotations.media.Schema;
* 用于告诉 LLM 哪份报告与哪批碎片同源;{@code taskName} 帮助它判断领域是否一致。</p>
*/
public record MindMapReportContext(
@Schema(description = "报告所属会话编号,用于与碎片记录上下文关联")
String ref,
@Schema(description = "报告所属会话编号,用于与碎片记录上下文关联") String ref,
@Schema(description = "产生该报告的会话所属任务名(仅作判断领域的参考,报告可能来自旁支任务)")
String taskName,
@Schema(description = "会话摘要:这次实际学了什么")
String sessionSummary,
@Schema(description = "预期达成判断:对照学习预期得出的结论")
String expectationVerdict,
@Schema(description = "自由总结:用户对本次学习的叙述")
String freeSummary) {
@Schema(description = "会话摘要:这次实际学了什么") String sessionSummary,
@Schema(description = "预期达成判断:对照学习预期得出的结论") String expectationVerdict,
@Schema(description = "自由总结:用户对本次学习的叙述") String freeSummary) {
/** 三段是否都为空白:全空的报告没有参考价值,不进入导图上下文 */
public boolean isBlank() {
@@ -1,30 +0,0 @@
package com.guo.learningprogresstracker.dto;
/**
* 一次回忆对比的结果(AI-02)。
*
* <p>对比在 AI 任务执行器里完成,因此不再把「标准导图实体」直接返回给提交接口;
* 这个结果写进 AI 任务的 {@code result_payload},由前端在轮询到成功后再取详情。</p>
*
* @param standardMapId 对比所用的标准导图 ID
* @param recallRecordId 本次生成的回忆记录 ID
* @param recallRatio 覆盖率(0-1)
* @param matchedCount 命中节点数
* @param missedCount 遗漏节点数
* @param extraCount 额外节点数
*/
public record RecallCompareOutcome(Integer standardMapId, Integer recallRecordId, Double recallRatio,
Integer matchedCount, Integer missedCount, Integer extraCount) {
/** 转成 AI 任务结果载荷 */
public java.util.Map<String, Object> toPayload() {
java.util.Map<String, Object> payload = new java.util.LinkedHashMap<>();
payload.put("standardMapId", standardMapId);
payload.put("recallRecordId", recallRecordId);
payload.put("recallRatio", recallRatio);
payload.put("matchedCount", matchedCount);
payload.put("missedCount", missedCount);
payload.put("extraCount", extraCount);
return payload;
}
}
@@ -1,8 +1,7 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.time.LocalDateTime;
import lombok.Data;
/**
* 复习滚动 feed 条目 / 任务记录条目。
@@ -14,10 +14,6 @@ import io.swagger.v3.oas.annotations.media.Schema;
* 任务删除后残留的报告也不计入。</p>
*/
public record ReviewSummary(
@Schema(description = "任务总数")
long taskTotal,
@Schema(description = "学习报告总数")
long reportTotal,
@Schema(description = "学习碎片总数")
long fragmentTotal) {
}
@Schema(description = "任务总数") long taskTotal,
@Schema(description = "学习报告总数") long reportTotal,
@Schema(description = "学习碎片总数") long fragmentTotal) {}
@@ -11,5 +11,4 @@ import java.time.LocalDateTime;
* @param lastInteractionAt 最近一次交互时刻
* @param durationSeconds 前端结算出的净耗时(秒)
*/
public record ReviewTiming(LocalDateTime startedAt, LocalDateTime lastInteractionAt, Integer durationSeconds) {
}
public record ReviewTiming(LocalDateTime startedAt, LocalDateTime lastInteractionAt, Integer durationSeconds) {}
@@ -3,10 +3,9 @@ package com.guo.learningprogresstracker.dto;
import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity;
import com.guo.learningprogresstracker.entity.StudyReportsEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
/**
* 学习报告详情(归属-01:结构化报告)。
@@ -1,8 +1,7 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.time.LocalDateTime;
import lombok.Data;
@Data
public class StudySessionsDto {
@@ -1,10 +1,9 @@
package com.guo.learningprogresstracker.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
import lombok.Data;
/**
* 已有标签导图的摘要(闭环-04):用于「已生成的标签导图」列表。
@@ -1,11 +1,9 @@
package com.guo.learningprogresstracker.dto;
import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity;
import com.guo.learningprogresstracker.entity.ReviewTagMindMapEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
import lombok.Data;
/**
* 一个标签复习范围的当前状态(闭环-04)。
@@ -28,7 +26,4 @@ public class TagMindMapView {
@Schema(description = "该范围已有的标签导图;没有时为 null")
private ReviewTagMindMapEntity map;
@Schema(description = "该范围最近一次回忆对比记录;没复习过时为 null")
private ReviewRecallRecordEntity latestRecallRecord;
}
@@ -1,7 +1,6 @@
package com.guo.learningprogresstracker.dto;
import com.guo.learningprogresstracker.enums.TagCombineModeEnum;
import java.util.List;
/**
@@ -24,9 +24,6 @@ public class TaskDeletionSummary {
@Schema(description = "将软删除的标准思维导图数")
private int deletedMindMaps;
@Schema(description = "将软删除的回忆记录数")
private int deletedRecallRecords;
@Schema(description = "将软删除的应用场景数")
private int deletedApplications;
}
@@ -12,8 +12,5 @@ import io.swagger.v3.oas.annotations.media.Schema;
* <p>排序与任务列表一致(优先级倒序),保证下拉里的顺序稳定。</p>
*/
public record TaskOption(
@Schema(description = "任务编号")
String taskNum,
@Schema(description = "任务名称")
String taskName) {
}
@Schema(description = "任务编号") String taskNum,
@Schema(description = "任务名称") String taskName) {}
@@ -0,0 +1,19 @@
package com.guo.learningprogresstracker.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* 批量重算优先级的一行输入(权重保存时用)。
*
* <p>优先级仍由 {@code CalculatedPriorityTool} 在 Java 侧算出,这里只负责把「主键 + 算好的值」交给一条
* CASE 更新,避免逐任务 {@code updateById} 变成 N 次往返。</p>
*/
@Data
@AllArgsConstructor
public class TaskPriorityUpdate {
private Integer id;
private Double calculatedPriority;
}
@@ -1,19 +0,0 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
/**
* 任务最近一次回忆对比的覆盖率(复习-04)。
*
* <p>原先按任务取「最近一条回忆记录」是把该任务的全部回忆记录(含体积较大的
* {@code compare_result} JSON)拉回内存再逐条取第一条。改为在 SQL 侧按任务分组取最新,
* 返回行数等于任务数,不随复习次数增长。</p>
*/
@Data
public class TaskRecallRatio {
private String taskNum;
/** 最近一次回忆对比的覆盖率(0-1);记录里为空时按 0 处理 */
private Double recallRatio;
}
@@ -1,16 +0,0 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
/**
* 任务维度的复习耗时聚合结果(复习-07)。
* <p>由 Mapper 层的聚合查询直接映射,避免用 Map 承载查询结果。</p>
*/
@Data
public class TaskReviewDuration {
private String taskNum;
/** 该任务累计复习耗时(秒) */
private Long reviewDurationSeconds;
}
@@ -0,0 +1,197 @@
package com.guo.learningprogresstracker.dto.recall;
import java.time.Instant;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
/** Free recall stores one current expression and one current reference set per recall. */
public final class RecallDtos {
private RecallDtos() {}
public record ScopeInput(String type, String taskNum, List<String> tags, String combineMode) {}
public record ScopeSnapshot(
String type,
String taskNum,
List<String> tags,
List<String> normalizedTags,
String combineMode,
String scopeKey,
String displayName,
Instant selectedAt) {}
public record Provenance(String kind, String recallNum, String requestTaskNum, String itemId) {}
public record NodeStyle(String background, String color) {}
public record ExpressionNode(
String id,
String title,
String notes,
List<Provenance> provenance,
NodeStyle style,
List<ExpressionNode> children) {}
public record Expression(int schemaVersion, ExpressionNode root) {}
public record Timing(long segmentActiveMs, Long segmentActualMs, Instant lastInteractionAt) {
/** 兼容尚未上报实际用时的调用方:实际按有效时间处理。 */
public Timing(long segmentActiveMs, Instant lastInteractionAt) {
this(segmentActiveMs, segmentActiveMs, lastInteractionAt);
}
}
public record Entry(String type, String sourceType, String entityId) {}
public record CreateRecallRequest(String clientRequestId, String editorId, ScopeInput scope, Entry entry) {}
public record EditorGuard(String editorId, String writeToken) {}
public record ResumeRequest(String clientRequestId, String editorId, String writeToken) {}
public record SaveDraftRequest(
String clientRequestId, String editorId, String writeToken, Expression expression, Timing timing) {}
public record AiParams(int schemaVersion, String requestId, String editorId, String writeToken, String hintForm) {}
public record ReferenceSource(
String sourceId,
String type,
String entityId,
String title,
String content,
String role,
String contextType,
String contextNum,
List<String> relatedFragmentSourceIds,
String status) {}
public record ReferenceSourceSummary(String sourceId, String title, String preview, String role, String status) {}
public record ReferencePage(int current, int size, long total, List<ReferenceSourceSummary> records) {}
public record ReferenceContent(String sourceId, String title, String content, String role, String status) {}
public record ReferenceSummary(String status, long total, List<String> limitations) {}
public record ReferenceUnit(
String unitId, String sourceId, int start, int end, String text, String role, String status) {}
/** One source set captured when this recall starts; it is replaced only by starting a new recall. */
public record ReferenceSnapshot(
String status, List<ReferenceSource> sources, List<ReferenceUnit> units, List<String> limitations) {}
public record Citation(String unitId, int start, int end, String quote) {}
public record ExpressionEvidence(String nodeId, String field, int start, int end, String quote) {}
public record UnitAssessment(
String unitId, String status, String reason, String exclusion, List<Citation> citations) {}
public record HintNode(String id, String parentId, String text) {}
public record HintItem(
String id, String form, String clue, String anchorNodeId, List<HintNode> nodes, List<Citation> citations) {}
public record Finding(
String id,
String category,
String clue,
String explanation,
List<Citation> citations,
List<ExpressionEvidence> expressionEvidence) {}
public record RecallAiResult(
int schemaVersion,
String kind,
String model,
String analysisStatus,
List<UnitAssessment> assessments,
List<HintItem> hints,
List<Finding> findings,
List<String> limitations) {}
public record AiReferenceUnit(
String unitId,
String sourceId,
String sourceType,
String role,
String title,
int start,
int end,
String text,
List<String> relatedFragmentSourceIds) {}
public record AiScope(String type, String displayName, List<String> tags, String combineMode) {}
public record Limits(int maxHintItems, int maxHintNodes, int maxFindings) {}
/** AI input expression: presentation-only style is not part of the semantic contract. */
public record AiExpressionNode(
String id, String title, String notes, List<Provenance> provenance, List<AiExpressionNode> children) {}
public record AiExpression(int schemaVersion, AiExpressionNode root) {}
public record RecallAiParams(
int schemaVersion,
String promptVersion,
AiScope scope,
AiExpression expression,
String hintForm,
List<AiReferenceUnit> units,
Limits limits,
List<String> limitations) {}
public record RecallRequest(
String requestId,
String taskNum,
String type,
String hintForm,
String promptVersion,
String status,
String errorCode,
String errorMessage,
Instant submittedAt,
Instant finishedAt,
RecallAiResult result) {}
public record RecallPage(long current, long size, long total, List<RecallSummary> records) {}
/** 相关导图的一行:回忆摘要 + 它与所选标签的交集(归一化名)。 */
public record RelatedRecallSummary(RecallSummary recall, List<String> matchedTags) {}
public record RelatedRecallPage(int current, int size, long total, List<RelatedRecallSummary> records) {}
public record BusinessError(String reason) {}
@Data
public static class RecallSummary {
private String recallNum;
private ScopeSnapshot scope;
private String scopeStatus;
private long activeDurationMs;
private Long actualDurationMs;
private Instant createdAt;
private Instant updatedAt;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class RecallDetail extends RecallSummary {
private String editorId;
private String writeToken;
private Expression expression;
private ReferenceSummary reference;
private List<RecallRequest> requests;
}
/** Persisted aggregate under a database lock, never returned to the client. */
@Data
public static class RecallDocument {
private RecallDetail detail;
private ReferenceSnapshot reference;
private Instant epochStartedAt;
private long acceptedSegmentMs;
private Long acceptedSegmentActualMs;
private String lastDraftRequestId;
private String lastDraftPayloadHash;
}
}
@@ -0,0 +1,10 @@
package com.guo.learningprogresstracker.dto.recall;
import lombok.Data;
/** 「相关导图」分页查询的行:只带回忆号与命中标签数,排序与分页由 SQL 决定,Java 侧不再重排。 */
@Data
public class RelatedRecallRow {
private String recallNum;
private long matchedTagCount;
}
@@ -0,0 +1,9 @@
package com.guo.learningprogresstracker.dto.recall;
import lombok.Data;
@Data
public class TaskRecallDuration {
private String taskNum;
private Long activeDurationMs;
}
@@ -0,0 +1,18 @@
package com.guo.learningprogresstracker.dto.request;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/** 给对象打用户标签的请求。 */
@Data
public class AddUserTagRequest {
@NotBlank(message = "对象类型不能为空")
private String objectType;
@NotBlank(message = "对象编号不能为空")
private String objectNum;
@NotBlank(message = "标签名不能为空")
private String markerName;
}
@@ -1,9 +1,8 @@
package com.guo.learningprogresstracker.dto.request;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import java.util.Map;
import lombok.Data;
/**
* 提交 AI 任务请求(AI-02)。
@@ -3,9 +3,8 @@ package com.guo.learningprogresstracker.dto.request;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.math.BigDecimal;
import lombok.Data;
/**
* 一条 AI 用量记录(契约 1)。
@@ -2,9 +2,8 @@ package com.guo.learningprogresstracker.dto.request;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.util.List;
import lombok.Data;
/**
* lpt-ai 用量上报请求体(契约 1,{@code POST /internal/ai-usage/records})。
@@ -0,0 +1,10 @@
package com.guo.learningprogresstracker.dto.request;
import lombok.Data;
/** 调整知识碎片内容归属;ownerTaskNum 传空字符串表示清空归属(回到待归类)。 */
@Data
public class AssignOwnershipRequest {
private String ownerTaskNum;
}
@@ -0,0 +1,13 @@
package com.guo.learningprogresstracker.dto.request;
import lombok.Data;
/** 确认引导产出、记成知识碎片的请求。 */
@Data
public class ConfirmGuidanceFragmentRequest {
private String content;
private String reviewStartedAt;
private String reviewLastInteractionAt;
private Integer reviewDurationSeconds;
}
@@ -0,0 +1,12 @@
package com.guo.learningprogresstracker.dto.request;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/** 新建标签字典项的请求。 */
@Data
public class CreateDictionaryTagRequest {
@NotBlank(message = "标签名不能为空")
private String tagName;
}
@@ -0,0 +1,10 @@
package com.guo.learningprogresstracker.dto.request;
import lombok.Data;
/** 在标准思维导图里查找最接近的节点。 */
@Data
public class FindNodeRequest {
private String content;
}
@@ -0,0 +1,15 @@
package com.guo.learningprogresstracker.dto.request;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/** 开始一次学习引导的请求。 */
@Data
public class GuidanceStartRequest {
@NotBlank(message = "任务编号不能为空")
private String taskNum;
@NotBlank(message = "概念不能为空")
private String concept;
}
@@ -0,0 +1,12 @@
package com.guo.learningprogresstracker.dto.request;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/** 提交一轮用户发言的请求。 */
@Data
public class GuidanceTurnRequest {
@NotBlank(message = "发言内容不能为空")
private String message;
}
@@ -0,0 +1,25 @@
package com.guo.learningprogresstracker.dto.request;
import com.guo.learningprogresstracker.entity.UserPriorityWeightsEntity;
import lombok.Data;
/** 优先级权重保存请求。 */
@Data
public class PriorityWeightsRequest {
private Double urgencyWeight;
private Double importanceWeight;
private Double contentDifficultyWeight;
private Double futureValueWeight;
private Double subjectivePriorityWeight;
public UserPriorityWeightsEntity toEntity() {
UserPriorityWeightsEntity entity = new UserPriorityWeightsEntity();
entity.setUrgencyWeight(urgencyWeight);
entity.setImportanceWeight(importanceWeight);
entity.setContentDifficultyWeight(contentDifficultyWeight);
entity.setFutureValueWeight(futureValueWeight);
entity.setSubjectivePriorityWeight(subjectivePriorityWeight);
return entity;
}
}
@@ -1,31 +0,0 @@
package com.guo.learningprogresstracker.dto.request;
import com.fasterxml.jackson.annotation.JsonFormat;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 用户回忆对比请求
*/
@Data
public class RecallCompareRequest {
@NotBlank(message = "请先填写回忆大纲")
private String recallOutline;
/** 复习起点节点路径(以 / 分隔),null 为任务维度 */
private String focusPath;
/** 本次回忆复习开始时刻(本地时间),复习-07 */
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
private LocalDateTime reviewStartedAt;
/** 最近一次交互时刻(本地时间),供服务端按 5 分钟空闲截断,复习-07 */
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
private LocalDateTime reviewLastInteractionAt;
/** 前端按 5 分钟空闲截断后的净耗时(秒),复习-07 */
private Integer reviewDurationSeconds;
}
@@ -0,0 +1,12 @@
package com.guo.learningprogresstracker.dto.request;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/** 重命名标签字典项的请求。 */
@Data
public class RenameDictionaryTagRequest {
@NotBlank(message = "标签名不能为空")
private String newName;
}
@@ -0,0 +1,15 @@
package com.guo.learningprogresstracker.dto.request;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/** 重命名用户标签的请求(影响所有带该标签的对象)。 */
@Data
public class RenameUserTagRequest {
@NotBlank(message = "原标签名不能为空")
private String oldName;
@NotBlank(message = "新标签名不能为空")
private String newName;
}
@@ -0,0 +1,10 @@
package com.guo.learningprogresstracker.dto.request;
import lombok.Data;
/** 保存复习排序偏好的请求(preset 取值见 ReviewSortPresetEnum,非法值回落默认档)。 */
@Data
public class SortPreferenceRequest {
private String preset;
}

Some files were not shown because too many files have changed in this diff Show More