Compare commits

...
22 Commits
Author SHA1 Message Date
unknownandCursor 7e636a9e8d docs(progress): 绑定控制台 UI 修复候选 commit
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 19:05:07 +08:00
unknownandCursor 9dffeae667 fix(web): 收敛控制台列表主按钮、报警可读性与焦点环
按 UI 评审闭环 UI-02~UI-07(查询降权、对象/处理人可读化、筛选分层、数据源名映射、焦点外环);概览与登录壳按约定暂缓。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 19:04:54 +08:00
unknownandCursor c7a23837f4 feat(web): 对齐和信后台页壳并落地工业 UI 评审与 Skills 盘点
统一控制台列表/表单页壳与 Hexin 样式,补充 industrial-ui-review、管理员评审证据,以及 Skills 资产盘点与 test-strategy 消歧。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 17:44:26 +08:00
unknownandCursor 48d1735c17 chore(docs): 同步 M02 登录截图、开发计划表与 console tsbuildinfo
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 15:41:38 +08:00
unknownandCursor ae67fefc80 feat(web): 接入和信企业 Design System 并统一控制台主色
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 15:40:38 +08:00
unknownandCursor b071c2a7a4 docs(alarms): 在进度台账绑定 M06 候选 commit
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 15:27:16 +08:00
unknownandCursor 47d3b85a4b feat(alarms): 完成 M06 报警中心与人工处理
落地正式异常创建/合并、三状态人工处置与控制台,关闭 M06 DONE_LOCAL(含 D40 认领文案「处理」)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 15:27:06 +08:00
unknownandCursor df991417d7 chore(marionettist): 按角色锁定 Sol/Grok 模型分工
记录 D29–D31:builder/planner 用 gpt-5.6-sol,coder/reviewer/critic 用 grok-4.7。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 10:15:49 +08:00
unknownandCursor 00f97a4e8a docs(mappings): 在进度台账绑定 M05 候选 commit
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 10:03:51 +08:00
unknownandCursor 252709709c feat(mappings): 完成 M05 字段映射与规则判断
映射和判断规则共用一个不可变版本,试算可以直接取已选查询的结果。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 10:03:45 +08:00
unknownandCursor be63e2fe5d feat(web): 列表自适应布局并将分页固定页脚
数据源与查询列表整页不滚、仅表体内滚;名称筛选去掉「模糊」占位后缀。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 18:48:50 +08:00
unknownandCursor c1da6d7c3a docs(queries): 在进度台账绑定 M04 候选 commit
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 18:32:30 +08:00
unknownandCursor 21cc721fcc feat(queries): 完成 M04 查询定义与版本激活
交付不可变查询版本、保存即生效与激活(D26),并带控制台列表筛选排序与试跑预览;补 RLS 下 current_version_no 回填迁移。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 18:32:24 +08:00
unknownandCursor 8c0335040f docs(datasource): 在进度台账绑定 M03 候选 commit
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 12:50:58 +08:00
unknownandCursor e6d37d176d feat(datasource): 完成 M03 数据源配置与熔断巡检
交付三种引擎登记、草稿/已保存连接测试、可逆启用、每源熔断与 Cron 巡检,以及控制台页面;用户确认收尾后标 DONE_LOCAL。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 12:50:46 +08:00
unknownandCursor f17bf19709 docs(auth): 记下 M02 与计划表已推送
进度台账原先写着候选提交还在本地,推送完成后改成已在 origin。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-17 19:44:08 +08:00
unknownandCursor 8b65c4aeed docs(infra): 纳入预警平台初期开发计划表
把这份计划表放进仓库,和现有规划文档放在一起。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-17 19:43:52 +08:00
unknownandCursor c9d6dcaf97 docs(auth): 在进度台账绑定 M02 候选 commit
把 DONE_LOCAL 的候选版本写成 f8e1c77,便于以后对上这次地址令牌登录。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-17 19:41:45 +08:00
unknownandCursor f8e1c77bd3 feat(auth): 用 Casdoor 校验地址令牌并完成 M02
HXOPS 打开带 token 的地址时,前端只把令牌交给后端,后端向 Casdoor userinfo 校验。D20 接受该实例上任意仍然有效的访问令牌。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-17 19:41:31 +08:00
unknownandCursor ab31d828d4 feat(auth): 接入 Casdoor 登录并让前端持有本服务会话
管理台可以密码登录、按角色进入,并把 Watchman 会话 token 交给浏览器。HXOPS 真实跳转仍未联调。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-17 18:39:56 +08:00
unknownandCursor 21338337a1 docs(infra): 在进度台账绑定 M01 候选 commit
将 DONE_LOCAL 候选版本写为 8fb16f4,便于证据回查。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-17 15:00:52 +08:00
unknownandCursor 8fb16f4a4a feat(infra): 落地 M01 基础框架与本机开发环境
交付 FastAPI/Celery/Vue 薄壳、FORCE RLS、Compose 回环与 review 修复证据,关闭 M01 DONE_LOCAL。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-17 15:00:39 +08:00
456 changed files with 56667 additions and 53 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
---
name: test-strategy
description: Select a task-appropriate validation strategy before coding or validation handoff. Use to recommend evidence, automated tests, manual checks, or NOT_RUN conditions based on task type, change risk, and environment limits without mandating global TDD.
description: Select a Marionettist/Watchman task-slice validation strategy before coding or validation handoff. Use to recommend evidence, automated tests, manual checks, or NOT_RUN conditions based on task type, change risk, and environment limits without mandating global TDD. Not for multi-quarter QA roadmap documents — use qa-test-strategy.
phase: analysis
model_requirement: reasoning
can_edit: false
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: marionettist-builder
description: Orchestrates the full repository Marionettist flow from analysis to slice coding and review
model: gpt-5.5
model: grok-4.7
---
You are the local Marionettist build orchestrator.
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: marionettist-coder
description: Implements only the currently approved Marionettist coding slice or approved parallel group
model: gpt-5.4
model: grok-4.7
---
You are the local Marionettist coding agent.
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: marionettist-critic
description: Audits requirement, plan, context, scope, and validation risks before coding or at Marionettist gates
model: claude-opus-5-5
model: grok-4.7
---
You are the local Marionettist critic.
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: marionettist-planner
description: Builds Marionettist implementation slices, validation strategy, and risk notes from approved analysis context
model: gpt-5.5
model: gpt-5.6-sol
---
You are the local Marionettist planner.
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: marionettist-reviewer
description: Independent read-only review for boundary, regression, validation, and knowledge-sync risks
model: claude-opus-5-5
model: grok-4.7
---
You are the local independent Marionettist reviewer.
+25
View File
@@ -0,0 +1,25 @@
---
description: 管理端 Element Plus + 和信企业共享风格(已启用)。改 console Vue 时自动约束。
globs: web/apps/console/src/**/*.vue
alwaysApply: false
---
# 管理端 Element Plus(Watchman)
改匹配文件时遵守本仓 `docs/ui/ELEMENT_MIGRATION.md`,并与共享视觉规范对齐:
- 共享风格(跨项目):`D:\FDE\SP\design-system\`(DESIGN / PAGE_PATTERNS / COMPONENTS)
- 本仓库执行细则:`docs/ui/ELEMENT_MIGRATION.md`
- 本仓库列表/页脚等业务约定:`docs/current/frontend-ui.md`
- 公司 EP 落地(按页导入、确认框等):`standards://frontend/element-plus`(最新版)
硬约束:
- 按钮、输入、下拉、表格、弹窗、分页用 Element Plus;不要新写 `<button>`、`<input>`、`<select>`、`<textarea>` 充当主 UI。
- 不要新写 `btn-primary`、`btn-secondary`、`btn-ghost`、`btn-danger`、`input-field`、`select-field`。
- 图标用 `@element-plus/icons-vue`,不要往 Element 按钮里塞其他图标库组件。
- 字号和颜色走 `web/design/tokens.css` → `shared/styles/element-theme.css` 的 `--el-*`;不要在单元格上用 `text-sm` / `text-muted` 改 EP 控件。
- 危险确认用 `ElMessageBox.confirm`。
- Primary 对齐和信共享色 `#0284c7`(本仓已确认覆盖公司 visual-ux 默认紫蓝,见 `docs/decisions.md` D41)。
- 列表结构:一层卡片、左右约 32px 对齐;Watchman 筛选/分页细则以 `docs/current/frontend-ui.md` 为准。
- 禁止为还原原型引入第二套 UI 库;OpenDesign HTML 须用 EP 重写。
@@ -0,0 +1,155 @@
---
name: industrial-ui-review
description: Reviews industrial web interfaces for UI/UX quality, layout, visual hierarchy, interaction, state clarity, and scenario fitness. Use only when the user explicitly asks for “UI设计评审”, “UIUX审查”, “检查当前页面布局风格交互”, “工业后台”, “生产大屏”, “HMI评审”, or an equivalent industrial interface design review; do not trigger for routine coding, unit tests, generic code review, or feature implementation.
---
# Industrial UI Review
对工业管理后台、生产监控大屏和 HMI 做基于证据的设计评审。默认只报告,不修改 UI。
## 边界
- 默认不改代码、不改设计稿、不写生产数据、不执行真实设备控制。
- 不绕过登录、权限、验证码或安全联锁;需要账号、真实数据或设备权限时先停下并请用户处理或另行授权。
- 不安装依赖、浏览器、MCP 或外部 Skill,不联网更新工具。
- 不把源码检查当成视觉实测,不把截图当成功能断言。
- 页面或服务不可用时标记 `NOT_RUN`,写明阻塞原因和待执行步骤;不得据源码宣布视觉结论。
- 截图、DOM、日志和报告不得泄露密钥、令牌、密码、个人信息或受限数据。
## 规范优先级
先遵守项目规则和项目设计真源,再使用通用审查启发式。规范冲突时明确记录,不自行覆盖项目决定。
公司规范使用以下精确版本:
- `standards://frontend/frontend-stack?version=2.1.0`
- `standards://frontend/element-plus?version=1.0.2`
- `standards://frontend/visual-ux?version=2.0.1`
- `standards://security/red-line?version=1.1.0`
在 Watchman 中,项目决定 D41 和共享设计系统主色 `#0284c7` 覆盖公司视觉规范默认主色 `#5e6ad2`。其他项目不得继承此覆盖,除非其本地真源明确规定。
## 先区分工作类型
不得混淆以下三类工作:
1. **功能 E2E**:断言操作、网络和业务结果;主要方案优先使用项目已有 Playwright Test。
2. **视觉回归**:比较稳定页面的截图基线;用于发现像素变化,不判断设计是否合理。
3. **设计评审**:判断信息架构、层级、布局、组件、交互、一致性和场景适配;本 Skill 属于此类。
Cursor 浏览器用于探索、复现和补充证据,不替代项目已有 Playwright Test,也不重复安装浏览器 MCP。
若已安装且任务确有需要,可选调用:
- `visual-testing`:视觉回归。
- `accessibility-testing`:WCAG、键盘、ARIA 等专项验证。
- `playwright-automation`:稳定功能 E2E 与可复测脚本。
Impeccable 已由用户确认可用(本机插件缓存 `impeccable` 4.5.1)。工业 UI 评审可将其作为第二意见(如 `critique` / `audit` / `polish`),但:
- 项目规则、D41、Element Plus、共享 Design System 与本 Skill 参考优先。
- 不因其建议覆盖项目决定,也不自动安装、升级或跟随上游 `main`/`skill-v4.10.0`。
- 视觉结论仍须真实浏览器或截图证据;Impeccable 输出不能单独宣布页面通过。
## 统一流程
### 1. 确认目标与运行条件
确认:
- 页面名、URL/路由、环境和登录状态。
- 用户角色、核心任务、主要使用场景和期望输出。
- 是否允许访问真实浏览器、截图、DOM、源码或测试数据。
- 目标视口、语言、主题、数据状态和设备条件。
- 禁止触碰的页面、数据、操作和外部系统。
信息不足会改变结论时先询问;可安全评审的部分继续执行并标注假设。
### 2. 分类页面
- `admin`:工业内部 B 端管理后台、配置、列表、表单、详情。
- `dashboard`:生产监控、指标总览、态势大屏、分析看板。
- `HMI`:状态站、现场辅助终端、设备控制界面。
混合页面分别套用对应规则,不以一个类别覆盖其他类别。
### 3. 读取设计真源与页面目标
读取项目内最小必要集合:
- 项目级 `AGENTS.md`、相关 Rules、UI 文档、设计 token 和组件约定。
- 页面需求、目标角色、关键任务、允许与禁止的操作。
- 当前实现相关的路由、页面源码或测试,仅用于补证据。
Watchman 管理台存在时读取:
- `D:/FDE/SP/design-system/DESIGN.md`
- `D:/FDE/SP/design-system/PAGE_PATTERNS.md`
- `D:/FDE/SP/design-system/COMPONENTS.md`
- `docs/ui/ELEMENT_MIGRATION.md`
- `docs/current/frontend-ui.md`
- `.cursor/rules/element-admin-ui.mdc`
### 4. 选择对应参考
- 管理后台:[references/admin-review.md](references/admin-review.md)
- 生产大屏/看板:[references/dashboard-review.md](references/dashboard-review.md)
- HMI:[references/hmi-review.md](references/hmi-review.md)
- 浏览器证据与报告:[references/report-and-browser.md](references/report-and-browser.md)
只读取与页面分类相关的参考;混合页面读取多个参考。
### 5. 优先真实浏览器与目标视口
优先运行项目已有 Playwright Test 或在真实浏览器打开目标页面。按项目和用户指定视口检查;无指定时使用对应参考的最小矩阵。
不得只看默认首屏。至少覆盖:
- 核心路径与主要操作。
- 加载、空、错误、权限不足等适用状态。
- 键盘焦点、反馈、弹层、滚动和响应式。
- 适用时的刷新、断连、过载、未知状态和恢复路径。
### 6. 交互与状态检查
记录每一步的输入、预期、实际、可见反馈和恢复方式。危险或生产相关操作只检查到确认边界,除非用户另行明确授权执行。
### 7. 必要时补充源码、DOM 与 token 证据
仅在视觉或交互现象需要定位时检查:
- DOM 语义、可访问名称、焦点顺序、禁用状态。
- 响应式规则、布局容器、滚动边界。
- Element Plus 组件选用与状态覆盖。
- token、主题变量、单位、时间窗和刷新信息来源。
来源证据只证明实现线索;视觉结论仍需浏览器或截图证据。
### 8. 输出报告
使用 [references/report-and-browser.md](references/report-and-browser.md) 的模板。不要发明问题数量、通过率或已执行步骤。
每条 finding 必须包含:
- `ID`
- 页面名及 URL 或路由
- 区域
- 截图
- 描述
- 为何不美观或不合理
- 影响
- 建议
- 优先级 `P0`–`P3`
- 判断类型:`客观` 或 `主观`
- 验证状态:`VERIFIED_BROWSER`、`VERIFIED_INTERACTION`、`VERIFIED_SOURCE`、`SCREENSHOT_ONLY` 或 `NOT_RUN`
主观判断必须引用项目规范和具体场景理由,不能只写“看起来不好”。同一 finding 可列多个证据,但验证状态按最强且真实完成的证据填写。
## 完成条件
- 已说明页面分类、环境、视口和数据边界。
- 已区分设计评审、功能 E2E 与视觉回归。
- 已引用项目规则和适用的精确公司规范版本。
- 已真实执行的步骤有证据;未执行项明确 `NOT_RUN`。
- 所有 finding 字段完整,主观判断有项目规范和场景理由。
- 未修改 UI、未安装工具、未写生产数据、未绕过登录或权限。
@@ -0,0 +1,130 @@
# Admin Review
适用于工业内部 B 端管理后台。目标是清晰、专业、高效;不以“极简”为由牺牲必要的信息密度、状态辨识和操作效率。
## 先确认
- 角色:值班员、配置人员、审核人员、管理员或只读访客。
- 任务:查询、配置、审核、诊断、批量处理或查看详情。
- 使用频率:高频熟练操作、低频高风险操作或临时排障。
- 数据规模、权限边界、目标视口、语言和主题。
## 页面结构
检查页面是否形成稳定的任务顺序:
1. 标题与必要说明让用户理解当前位置和目标。
2. 搜索/筛选靠近结果,条件、应用方式和重置结果可预测。
3. 页面主操作清晰且数量克制,次操作和危险操作降级。
4. 内容区承载主要信息,不被重复标题、嵌套卡片或装饰挤压。
5. 分页、汇总、结果数和当前筛选状态可理解。
检查标题、搜索、操作、内容四区的对齐、间距、视觉层级和阅读路径。高密度不等于拥挤:应减少重复容器和无效留白,同时保留可扫读的分组与行距。
## 信息架构与点击路径
- 核心任务是否能从当前页面直接开始。
- 高频操作是否被低频设置、说明或危险操作淹没。
- 列表、详情、编辑、版本、历史之间的返回路径是否稳定。
- 面包屑、侧栏、标题和浏览器返回是否表达一致层级。
- 同一任务是否被迫跨越不必要的弹窗、抽屉或独立路由。
- 选择 Dialog、Drawer 或独立路由是否与信息长度和任务连续性匹配。
记录核心任务的点击步数,但不要机械追求最少点击;高风险操作允许增加有意义的确认步骤。
## 表单、表格、弹窗和抽屉
### 表单
- 标签、必填、单位、格式、范围和示例是否明确。
- 字段顺序是否符合用户心智模型,相关字段是否成组。
- 初始值、禁用原因、校验时机和错误定位是否可理解。
- 提交中是否防重复,成功后去向和保存结果是否清楚。
- 长表单是否有分段、锚点、未保存提醒和恢复策略。
### 表格
- 列是否服务于比较与决策;关键列靠前,操作列稳定。
- 数字、时间、单位和状态是否格式一致并便于纵向扫读。
- 排序、筛选、分页、固定列和滚动是否与数据规模匹配。
- 行内操作是否只保留高频动作;批量动作是否明确作用范围。
- 空结果是否区分“无数据”和“筛选无匹配”。
### 弹窗与抽屉
- 弹窗用于短而聚焦的任务;长内容或需要保留上下文时才考虑抽屉。
- 标题、关闭方式、取消/确定、提交中状态和错误反馈一致。
- 遮罩关闭、Esc、焦点回收和未保存内容处理符合风险等级。
- 危险确认说明对象、后果和可恢复性,不使用含糊的“确定吗”。
## 操作层级与反馈
- 每个区域通常只有一个明确主操作。
- 主操作、次操作、链接操作和危险操作的视觉层级一致。
- 禁用操作提供可理解原因;隐藏操作不应造成权限误解。
- 点击后立即出现可见反馈:loading、进度、成功、失败或排队状态。
- 异步操作可追踪,可刷新,可恢复;错误提供下一步而非只显示代码。
- 不用颜色作为唯一状态表达;状态同时有文本、图标或形状。
## Element Plus
若项目采用 Element Plus:
- 优先使用已有 Element Plus 组件和项目封装,不混入第二套组件库。
- 检查按钮、输入、选择器、表格、分页、表单、Dialog、Drawer、Tag、MessageBox 的一致使用。
- 危险操作优先使用项目规定的确认组件。
- 主题、字号、圆角、间距和状态色应来自项目 token/桥接层,而不是页面散落硬编码。
- 检查多语言、暗色、长文案、表格空态和弹层挂载后的实际表现。
引用:
- `standards://frontend/frontend-stack?version=2.1.0`
- `standards://frontend/element-plus?version=1.0.2`
- `standards://frontend/visual-ux?version=2.0.1`
## 状态完整性
至少按适用性检查:
- 初始、加载、局部加载、提交中。
- 有数据、空数据、筛选无匹配。
- 校验错误、接口错误、超时、部分成功。
- 无权限、只读、禁用、资源不存在。
- 离线、重连、数据过期或并发更新。
状态之间切换时检查布局跳动、焦点丢失、重复提交和错误残留。
## 响应式与整体协调
- 在项目目标视口检查,不以桌面截图推断窄屏可用。
- 窄屏时优先保持任务顺序、关键字段和主要操作;次要列可折叠或转详情。
- 检查横向滚动是否可发现,固定列是否遮挡,弹窗是否溢出。
- 字体、间距、边框、圆角、阴影、图标和色彩是否形成统一节奏。
- 装饰不应压过数据、状态和操作;管理后台无需默认追求大留白或营销页气质。
## Watchman 适配
仅当当前项目确实存在以下本地真源时读取并执行,不把 Watchman 业务字段或页面特例写成通用硬规则:
- `D:/FDE/SP/design-system/DESIGN.md`
- `D:/FDE/SP/design-system/PAGE_PATTERNS.md`
- `D:/FDE/SP/design-system/COMPONENTS.md`
- `docs/ui/ELEMENT_MIGRATION.md`
- `docs/current/frontend-ui.md`
- `.cursor/rules/element-admin-ui.mdc`
Watchman 当前主色为 `#0284c7`,覆盖公司视觉规范默认 `#5e6ad2`。页面布局、列表筛选、页脚和模块特例以本地文档为准;不要把这些业务约定扩散到其他项目。
## 最小浏览器矩阵
| 维度 | 最小覆盖 |
| --- | --- |
| 视口 | 项目主桌面视口;一个窄屏或最小支持宽度 |
| 角色 | 典型可编辑角色;只读或受限角色 |
| 数据 | 正常数据;空数据;长文本/大数值 |
| 状态 | 加载;错误;权限不足;提交中 |
| 交互 | 筛选与重置;排序/分页;主操作;危险确认;返回 |
| 输入 | 键盘 Tab/Enter/Esc;鼠标;适用时触控 |
| 主题/语言 | 项目支持的明暗主题;最长目标语言 |
无法执行的组合列入报告 `NOT_RUN`,写明所需环境、数据、账号或测试桩。
@@ -0,0 +1,144 @@
# Dashboard Review
适用于生产监控大屏、指标总览和分析看板。本参考是通用设计评审规则,不依赖任何特定项目业务代码。
## 先区分使用模式
### 无人值守监控
屏幕持续展示,用户从远处快速发现异常。重点检查:
- 当前总体状态是否一眼可辨。
- 异常是否能在背景信息中脱颖而出。
- 更新时间、断连和数据过期是否明显。
- 页面是否可长期运行且不依赖频繁操作。
### 有人交互分析
用户近距离筛选、对比、钻取和解释。重点检查:
- 时间窗、筛选条件和分析上下文是否持续可见。
- 图表是否支持对比、定位和追溯。
- 钻取后能否稳定返回,条件是否保留。
- 弹窗、详情和导航是否与分析路径匹配。
混合场景分别评审,不把远距监控的超大字号机械套到分析工作台。
## 构图与视觉重心
- 首屏是否有明确重心:总体状态、关键异常或主要生产目标。
- KPI、趋势、分布、明细和事件是否形成从概览到解释的层级。
- 网格、对齐、留白和卡片尺寸是否反映信息优先级。
- 左右或上下构图是否失衡;高价值区域是否被装饰或低价值图表占据。
- 关键异常是否位于稳定位置,避免刷新后大幅跳动。
- 不默认使用深色、霓虹、发光边框或“驾驶舱”装饰;主题应由场景、光照、设备和项目规范决定。
## KPI 层级
- KPI 名称、当前值、单位、时间窗和对比基准完整。
- 主 KPI 数量克制;次级指标不与主 KPI 争夺视觉权重。
- 变化量说明方向和基准,避免只显示无语境的百分比。
- 数字精度与决策需要匹配;不展示无意义小数。
- 数字使用稳定宽度或等宽数字,刷新时不造成布局抖动。
## 图表选择与数据诚实
- 趋势用时间序列;构成用适合的比例图;排名用可比较长度;关系图仅在关系本身重要时使用。
- 不用面积、3D、透视、截断坐标轴或双轴制造夸大效果。
- 坐标轴、单位、图例、阈值、采样频率和缺失数据表达完整。
- 颜色类别数量受控,语义稳定;同一状态在不同图表中不换色。
- 数据聚合、平滑和降采样不得隐藏异常;必要时说明方法。
- Tooltip、图例和标签不遮挡关键数据,且键鼠操作可用。
## 时间、刷新与数据新鲜度
- 全局和局部时间窗关系明确。
- 显示最后成功刷新时间、刷新频率和时区。
- 手动刷新、自动刷新、暂停和全屏状态可理解。
- 数据过期、部分源延迟和完全断连有不同表达。
- 刷新不应重置用户筛选、钻取位置或阅读上下文,除非明确说明。
## 状态语义
明确区分:
- 正常
- 异常/告警
- 离线
- 未知
- 数据过期
- 维护或停用(若业务存在)
颜色不得是唯一编码;配合文本、图标、形状、边框或图案。不要把未知或离线显示成正常,也不要把“无数据”自动解释为零。
## 远距可读与装饰克制
- 从预期观看距离检查标题、KPI、告警和关键标签。
- 低对比细线、小号辅助字和密集图例不得承载关键状态。
- 背景纹理、渐变、动态粒子和装饰边框不影响图表读取。
- 动画只用于解释变化或提示异常,避免持续闪烁和无意义流光。
- 大屏不是海报:品牌元素不应挤占持续监控所需空间。
## 目标分辨率
至少在以下视口验证真实布局,而非仅缩放截图:
- `1920 × 1080`
- `2560 × 1440`
检查:
- 信息是否只是等比放大,还是合理利用新增空间。
- 字号、图表密度、边距和弹层是否保持协调。
- 浏览器缩放、系统缩放、全屏和非全屏状态下是否裁切。
- 固定比例设计在不同屏幕上是否出现黑边、溢出或过度拉伸。
若项目声明其他目标屏幕,以项目真源为准,并保留上述两项为适用性建议而非硬性要求。
## 运行状态
检查:
- 进入和退出全屏。
- 自动刷新与手动刷新。
- 单个数据源断连、部分数据失败、整体离线。
- 空数据、零值、缺失值、过载数据和极端值。
- 长时间运行后的内存、动画、定时器和布局稳定性(无运行条件则 `NOT_RUN`)。
- 告警突增时的排序、聚合、去重和视觉过载。
## 交互
- 筛选条件可见、可清除,并说明影响范围。
- 图表钻取对象、时间点和返回路径明确。
- 弹窗不遮挡必须持续观察的状态;关闭后恢复上下文。
- 导航离开前保留或明确丢弃分析状态。
- 交互图表提供键盘或替代访问方式;纯悬停信息不得成为唯一信息。
## 可复用浏览器测试矩阵
| 维度 | 用例 |
| --- | --- |
| 使用模式 | 无人值守监控;有人交互分析 |
| 视口 | 1920×1080;2560×1440;项目指定屏幕 |
| 显示状态 | 正常;告警;离线;未知;数据过期 |
| 数据形态 | 空;零;单点;正常密度;过载;极端值;长标签 |
| 时间 | 默认时间窗;切换时间窗;跨时区;刷新后保留上下文 |
| 连接 | 正常;单源断连;部分失败;整体断连;重连 |
| 操作 | 全屏;刷新;筛选;钻取;弹窗;返回;导航 |
| 输入 | 鼠标;键盘;适用时触控/遥控 |
| 主题环境 | 项目主题;目标光照;浏览器/系统缩放 |
## NOT_RUN 清单
以下项目未执行时逐项标记,不得用推测替代:
- 目标屏幕实机和观看距离。
- 1920×1080、2560×1440 或项目指定视口。
- 长时间运行稳定性。
- 实时刷新、断连、重连和数据过期。
- 告警风暴、过载和极端值。
- 全屏、系统缩放和浏览器缩放。
- 真实角色权限与生产数据表现。
- 键盘、触控或遥控设备。
每项说明阻塞原因、所需环境/数据和建议执行步骤。真实生产数据访问必须另行授权。
@@ -0,0 +1,137 @@
# HMI Review
适用于工业现场状态站、辅助操作终端和设备控制 HMI。本参考为通用评审规则,不依赖任何特定项目业务代码。
## 先分类风险
### 只读状态站
只展示设备、过程和告警状态。重点是远距辨识、状态可信、数据新鲜度和异常定位。
### 辅助操作终端
支持确认、记录、选择配方、发起流程或辅助处置。重点是步骤清晰、权限、误触防护、反馈和恢复。
### 设备控制 HMI
可直接影响设备、产线或工艺。必须先确认授权、仿真/测试环境、安全联锁和停止边界。默认只评审到确认边界,不执行真实控制。
页面含多类能力时按最高风险操作设置保护,但不要让低风险高频任务被无意义确认拖慢。
## 步骤与任务清晰度
- 当前模式、对象、工位、设备和任务上下文持续可见。
- 操作顺序符合现场流程,前置条件和完成条件明确。
- 多步任务显示当前位置、剩余步骤和可返回范围。
- 禁止操作说明原因和解除条件,而不是仅灰掉。
- 关键操作前明确展示作用对象、目标值和预期结果。
## 即时反馈
- 触发后立即显示“已接收、执行中、成功、失败、超时或被联锁拒绝”。
- 区分 UI 已发送、控制系统已接收和设备已达到目标状态。
- 延迟操作显示进度、等待原因和取消边界。
- 页面不得提前显示成功,也不得在通信未知时回退为正常。
- 状态刷新保持稳定,避免数值跳动导致误判。
## 误触防护与危险确认
- 高频安全操作保持直接;低频高风险操作增加明确确认或双动作。
- 触控目标有足够尺寸和间距,避免相邻危险按钮。
- 危险操作不得与常用操作仅靠颜色区分。
- 确认内容包括对象、动作、后果、当前状态和必要权限。
- 长按、滑动确认、双人复核或二次认证仅在风险分析支持时使用。
- 执行中防重复触发;超时后提供可验证的恢复路径。
## 急停与安全联锁边界
- UI 不能替代实体急停、硬件安全回路、安全 PLC 或已认证联锁。
- 不把普通软件按钮标成可等价替代硬件急停。
- UI 可显示急停/联锁状态、原因和恢复指引,但不得暗示绕过。
- 安全联锁拒绝必须清楚、持续且不可被普通提示覆盖。
- 解除联锁、复位和重新启动应按权限与现场规程分离。
发现疑似安全边界不清时按高优先级报告,并要求安全/控制工程负责人复核;不得自行设计控制逻辑。
## 手套、触控、距离与光照
- 在目标屏幕尺寸、观看距离和操作姿态下检查。
- 触控目标和间距适合戴手套操作,边缘和角落目标不难命中。
- 不依赖精细拖拽、窄滚动条、纯悬停或双指手势完成关键任务。
- 强光、暗光、反光和色觉差异下保持关键状态可辨。
- 字号、行高和数字对齐支持快速读取;单位紧邻数值。
- 适用时检查触控反馈、误触撤销和屏幕清洁模式。
## 颜色与状态
- 颜色不是唯一编码;同时使用文本、图标、形状、位置或图案。
- 状态色语义稳定,不因页面或设备变化而改变。
- 正常、运行、停止、等待、维护、异常、告警、离线、未知应按业务真实语义区分。
- 动画和闪烁只用于需要立即注意的状态,并控制频率与范围。
- 未确认告警、已确认告警和已恢复未复位状态不得混为一类。
## 告警可理解性
- 告警包含设备/区域、发生时间、状态、严重度和简明原因。
- 提供现场可执行的下一步或升级路径,不只显示错误码。
- 告警排序兼顾严重度、时间和关联性,避免告警风暴淹没根因。
- 确认告警不等于清除原因;界面明确两者差异。
- 历史、抑制、搁置和维护状态按权限展示并可追溯。
## 恢复、权限与操作日志
- 失败、超时、断连和中断后有安全恢复路径。
- 角色权限与现场职责匹配;登录切换不遗留上一用户敏感状态。
- 高风险操作要求可追溯身份,不使用共享匿名身份代替审计。
- 日志记录谁、何时、在哪个终端、对什么对象、做了什么、结果如何。
- 日志不记录密码、令牌或不必要的敏感生产数据。
- 回退、复位和重试不会重复执行已成功的危险动作。
## 离线与通信延迟
- 显示连接状态、最后更新时间和数据年龄。
- 区分界面离线、控制器离线、单设备离线和部分数据延迟。
- 离线时明确哪些操作不可用,禁止把待发送指令伪装成已执行。
- 重连后验证真实状态,不盲目重放旧命令。
- 通信超时后提供查询状态、人工确认或安全恢复步骤。
## 授权边界
真实设备控制、生产写入、配方下发、参数修改、联锁复位和生产数据访问必须另行明确授权,并限定环境、对象、时间窗和回退方式。默认使用仿真器、测试台或合成数据。
引用安全边界:
- `standards://security/red-line?version=1.1.0`
## 可复用测试矩阵
| 维度 | 用例 |
| --- | --- |
| HMI 类型 | 只读状态站;辅助操作终端;设备控制 HMI |
| 角色 | 未登录;只读;操作员;主管;维护/管理员 |
| 设备状态 | 正常;运行;停止;等待;维护;告警;离线;未知 |
| 命令状态 | 未发起;已接收;执行中;成功;拒绝;失败;超时;结果未知 |
| 通信 | 正常;高延迟;抖动;断连;部分断连;重连 |
| 输入 | 鼠标;裸手触控;手套触控;键盘/物理按键(适用时) |
| 环境 | 目标距离;强光;暗光;反光;噪声环境 |
| 风险 | 普通操作;危险操作;联锁拒绝;重复触发;误触;恢复 |
| 数据 | 正常值;边界值;异常值;陈旧值;缺失值;快速变化 |
| 审计 | 成功;失败;拒绝;超时;用户切换;离线恢复 |
设备控制类用例优先在仿真或测试环境执行,并由设备/安全负责人批准。
## NOT_RUN 清单
未实际验证时逐项标记:
- 目标硬件、屏幕、触控和手套操作。
- 真实观看距离、强光、暗光和反光环境。
- 控制器/设备通信延迟、断连和重连。
- 仿真器或测试台上的命令生命周期。
- 急停、安全 PLC 和联锁状态呈现。
- 告警风暴、确认、恢复和复位。
- 角色权限、重新认证和操作审计。
- 长时间运行与状态刷新稳定性。
- 真实设备控制或生产数据。
每项写明所需授权、负责人、环境、数据和安全前置条件。不得以源码、静态原型或截图替代设备与现场验证。
@@ -0,0 +1,212 @@
# Report and Browser Evidence
规定设计评审的浏览器执行、证据保存和报告格式。证据必须能说明“实际看到了什么”,不得夸大验证范围。
## 浏览器方案
1. 优先复用项目已有 Playwright Test、配置、认证状态、测试数据和启动命令。
2. Cursor 浏览器用于探索、复现、查看可访问树、补截图和 DOM 证据。
3. 不重复安装 Playwright、浏览器、MCP、截图服务或外部 Skill。
4. 不绕登录、权限、验证码或安全确认;需要人工登录时停在该步骤并请用户接管。
5. 不向真实系统写数据;设计评审通常只读。提交、删除、控制或生产写入须另行授权。
## 证据目录建议
优先使用项目已有证据目录。项目无约定时建议:
```text
docs/evidence/ui-review/<date>-<scope>/
screenshots/
traces/
report.md
```
若用户限制可修改路径,不创建证据目录;在报告中记录建议路径和 `NOT_RUN`。
截图命名:
```text
<page>-<viewport>-<state>-<sequence>.png
```
示例:
```text
alarm-list-1920x1080-error-01.png
line-dashboard-2560x1440-disconnected-02.png
hmi-station-1366x768-interlock-03.png
```
文件名使用小写 ASCII、连字符和稳定状态名,不含用户姓名、工号、设备秘密或生产数据。
## 视口与环境记录
每轮记录:
- URL/路由与页面名。
- 环境和构建版本(可获得时)。
- 浏览器与版本。
- viewport、device scale factor、浏览器缩放和系统缩放(可获得时)。
- 主题、语言、角色、数据集和时间窗。
- 是否全屏、触控、远距观看或目标硬件。
不得把浏览器窗口尺寸误写为 viewport;无法确认的字段写 `unknown`。
## 截图要求
- 先截完整上下文,再截问题区域;必要时用标注副本,但保留原图。
- 截图包含能定位页面和状态的信息,不裁掉关键上下文。
- 动态页面等待稳定条件,不用任意固定等待代替状态判断。
- 同一 finding 引用最小充分截图,避免大量重复图片。
- 截图只能证明当时可见结果,不能证明点击、网络请求或业务状态成功。
## 敏感信息遮蔽
截图和报告前检查:
- 密码、令牌、密钥、连接串和环境变量。
- 姓名、手机号、邮箱、工号、个人头像和定位信息。
- 受限资产、客户数据、生产参数和内部主机信息。
- 浏览器地址栏、开发者工具、通知和其他应用窗口中的秘密。
优先使用合成数据和测试环境。必须遮蔽时保留原始证据的受控位置和遮蔽副本,不在仓库保存未经授权的敏感原图。
遵守 `standards://security/red-line?version=1.1.0`。
## 交互检查
对适用流程记录:
1. 前置状态。
2. 输入方式和操作。
3. 预期反馈。
4. 实际反馈。
5. 最终状态与恢复方式。
6. 截图、trace、console、network 或 DOM 证据。
至少考虑:
- Tab、Shift+Tab、Enter、Space、Esc 和焦点回收。
- 点击目标、双击风险、触控目标和禁用原因。
- 弹窗、抽屉、Tooltip、下拉和滚动。
- 加载、提交中、防重复和超时。
- 返回、刷新、前进后退和状态保留。
视觉问题若必须通过交互才能出现,只有实际执行后才能标 `VERIFIED_INTERACTION`。
## 状态覆盖
按页面适用性检查并记录:
- 默认/正常
- loading/提交中
- empty/筛选无匹配
- error/timeout/部分失败
- forbidden/只读/未登录
- offline/disconnected/stale/unknown
- 长文本、大数值、极端值、过载
- 成功后的反馈与恢复
未覆盖状态逐项放入 `NOT_RUN`,不要汇总成含糊的“其他状态未测”。
## 验证状态
| 状态 | 含义 |
| --- | --- |
| `VERIFIED_BROWSER` | 已在目标或可说明差异的真实浏览器环境直接观察 |
| `VERIFIED_INTERACTION` | 已实际执行交互并观察到输入、反馈和结果 |
| `VERIFIED_SOURCE` | 仅由源码、DOM、样式或 token 证据确认实现事实 |
| `SCREENSHOT_ONLY` | 只有静态截图,未验证运行环境与交互 |
| `NOT_RUN` | 未执行;必须说明原因和待执行步骤 |
不要用 `VERIFIED_SOURCE` 宣布视觉效果已通过,不要用 `SCREENSHOT_ONLY` 宣布交互正确。
## 优先级
| 优先级 | 判定 |
| --- | --- |
| `P0` | 可能导致人身/设备安全风险、危险误操作、关键状态严重误导或无法安全恢复 |
| `P1` | 核心任务被阻断、关键告警/权限/数据状态误解,或高频任务存在严重效率风险 |
| `P2` | 明显影响可用性、一致性、信息理解或多状态质量,但有可行绕路 |
| `P3` | 轻微协调、细节、文案或优化建议,不阻断任务 |
优先级基于影响、发生条件和可恢复性,不按视觉显眼程度决定。不要发明问题数量或严重度配额。
## 客观与主观
- `客观`:违反明确项目规则、可测可用性要求、状态事实、安全边界或一致性约束。
- `主观`:对构图、节奏、美观、密度或协调性的专业判断。
主观 finding 必须同时给出:
1. 项目规范、设计真源或明确设计原则。
2. 当前角色、任务、距离、设备或环境理由。
3. 可比较、可复测的改进目标。
不得只写“太丑”“不够高级”“不现代”或“世界级不足”。
## Finding 模板
```markdown
### [ID] [短标题]
- 页面名/URL或路由:
- 区域:
- 截图:
- 描述:
- 为何不美观/不合理:
- 影响:
- 建议:
- 优先级:P0 | P1 | P2 | P3
- 判断类型:客观 | 主观
- 验证状态:VERIFIED_BROWSER | VERIFIED_INTERACTION | VERIFIED_SOURCE | SCREENSHOT_ONLY | NOT_RUN
- 依据:项目规范、公司规范、场景或证据
```
截图不可用时填 `无(原因)`,不能删除字段。
## 报告模板
```markdown
# UI Review — [范围]
## 范围与条件
- 页面/路由:
- 页面分类:admin | dashboard | HMI | mixed
- 角色与核心任务:
- 环境/版本:
- 视口/设备:
- 主题/语言:
- 数据边界:
## 方法与证据
- 设计评审:
- 功能 E2E:
- 视觉回归:
- 浏览器/Playwright:
- 项目真源:
- 公司规范:
## 结论
[只总结已验证的主要风险与优点,不发明数量。]
## Findings
[逐条使用 Finding 模板。]
## NOT_RUN
- [未执行项]:原因;待执行步骤;所需环境/授权。
## 证据索引
- [截图/trace/路由/源码证据]
## 下一步
- [按优先级给出可复测建议;默认不直接改 UI。]
```
## “规则已建立、尚未实测”标准写法
当本轮只建立评审规则、未运行页面时,使用:
> 已建立工业 UI 评审规则与报告结构;本轮未对任何页面执行真实浏览器、交互、功能 E2E 或视觉回归验证。所有页面级结论均为 `NOT_RUN`,不得据此声明页面通过、失败、合规或存在特定数量的问题。待执行步骤:确认目标页面、运行环境、账号与数据边界后,按对应页面类别和目标视口执行浏览器评审并保存证据。
不得把“规则完整”“模板已创建”改写为“页面已评审”。
+1 -1
View File
@@ -1,6 +1,6 @@
---
name: test-strategy
description: Select a task-appropriate validation strategy before coding or validation handoff. Use to recommend evidence, automated tests, manual checks, or NOT_RUN conditions based on task type, change risk, and environment limits without mandating global TDD.
description: Select a Marionettist/Watchman task-slice validation strategy before coding or validation handoff. Use to recommend evidence, automated tests, manual checks, or NOT_RUN conditions based on task type, change risk, and environment limits without mandating global TDD. Not for multi-quarter QA roadmap documents — use qa-test-strategy.
phase: analysis
model_requirement: reasoning
can_edit: false
+14
View File
@@ -0,0 +1,14 @@
.venv
**/__pycache__
**/*.pyc
.git
.task
web/node_modules
**/node_modules
docs/evidence
local-data
.env.local
*.log
.pytest_cache
.mypy_cache
.ruff_cache
+69
View File
@@ -0,0 +1,69 @@
# Copy to .env.dev / .env.local and replace placeholders.
# .env.local is never committed.
# Bootstrap only (local superuser). Prefer system env or .env.local.
WATCHMAN_BOOTSTRAP_DATABASE_URL=postgresql+psycopg://postgres:CHANGE-ME@127.0.0.1:5432/postgres
# App and migrator roles (not the bootstrap superuser)
WATCHMAN_MIGRATOR_PASSWORD=CHANGE-ME
WATCHMAN_APP_PASSWORD=CHANGE-ME
DATABASE_URL=postgresql+psycopg://watchman_app:CHANGE-ME@127.0.0.1:5432/watchman
DATABASE_MIGRATOR_URL=postgresql+psycopg://watchman_migrator:CHANGE-ME@127.0.0.1:5432/watchman
# Server-injected tenant for M01; keep out of committed shared env.
WATCHMAN_TENANT_ID=dev-tenant
# Queue (host processes talk to published RabbitMQ port).
# DEV ONLY: RabbitMQ image default guest/guest — never reuse in non-local brokers.
CELERY_BROKER_URL=amqp://guest:guest@127.0.0.1:56729//
# Compose app profile overrides (gitignored .env.local only)
# DEV ONLY guest/guest for the local compose RabbitMQ service.
CELERY_BROKER_URL_DOCKER=amqp://guest:guest@rabbitmq:5672//
DATABASE_URL_DOCKER=postgresql+psycopg://watchman_app:CHANGE-ME@host.docker.internal:5432/watchman
DATABASE_MIGRATOR_URL_DOCKER=postgresql+psycopg://watchman_migrator:CHANGE-ME@host.docker.internal:5432/watchman
COMPOSE_POSTGRES_PASSWORD=CHANGE-ME
# 4. Security, identity. Real values belong in gitignored .env.local only.
CASDOOR_ENDPOINT=http://CHANGE-ME
CASDOOR_CLIENT_ID=CHANGE-ME
CASDOOR_CLIENT_SECRET=CHANGE-ME
CASDOOR_ORGANIZATION=CHANGE-ME
CASDOOR_APPLICATION=CHANGE-ME
CASDOOR_CERTIFICATE=CHANGE-ME
CASDOOR_ISSUER=http://CHANGE-ME
CASDOOR_AUDIENCE=CHANGE-ME
HXOPS_SSO_ISSUER=https://CHANGE-ME
HXOPS_SSO_AUDIENCE=CHANGE-ME
HXOPS_SSO_PUBLIC_KEY=CHANGE-ME
# Datasource password encryption (Fernet urlsafe base64 key). Generate your own; losing it makes stored passwords unrecoverable.
WATCHMAN_DATASOURCE_KEY=CHANGE-ME
# Datasource probe: per-attempt timeout (seconds, default 5) and attempt cap (1-2, default 2; only timeout/unreachable retry).
WATCHMAN_DATASOURCE_PROBE_TIMEOUT_SECONDS=5
WATCHMAN_DATASOURCE_PROBE_MAX_ATTEMPTS=2
# Scheduled datasource health check (Celery Beat). Off by default. The cron is 5-field Unix
# (minute hour day-of-month month day-of-week), digits with * / , - only; setting both
# day-of-month and day-of-week is rejected. An invalid value means no schedule.
WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED=false
WATCHMAN_DATASOURCE_HEALTHCHECK_CRON="*/5 * * * *"
# M03 S2: isolated probe-test sources (engine connector tests). Real values in .env.local only.
WATCHMAN_TEST_PG_HOST=127.0.0.1
WATCHMAN_TEST_PG_PORT=5432
WATCHMAN_TEST_PG_USER=CHANGE-ME
WATCHMAN_TEST_PG_PASSWORD=CHANGE-ME
WATCHMAN_TEST_PG_DATABASE=CHANGE-ME
WATCHMAN_TEST_MYSQL_HOST=127.0.0.1
WATCHMAN_TEST_MYSQL_PORT=3306
WATCHMAN_TEST_MYSQL_USER=CHANGE-ME
WATCHMAN_TEST_MYSQL_PASSWORD=CHANGE-ME
WATCHMAN_TEST_MYSQL_DATABASE=CHANGE-ME
# SQL Server runs in compose profile source-sqlserver (127.0.0.1 only); user is sa.
# The password must satisfy SQL Server complexity rules.
WATCHMAN_TEST_SQLSERVER_HOST=127.0.0.1
WATCHMAN_TEST_SQLSERVER_PORT=1433
WATCHMAN_TEST_SQLSERVER_USER=sa
WATCHMAN_TEST_SQLSERVER_PASSWORD=CHANGE-ME
WATCHMAN_TEST_SQLSERVER_DATABASE=CHANGE-ME
+19
View File
@@ -0,0 +1,19 @@
# Shared non-secret defaults for all environments.
# Do not put production secrets in this file.
# 1. Environment and service identity
APP_NAME=watchman
ENV_NAME=dev
# 2. Application runtime
API_HOST=127.0.0.1
API_PORT=8000
# 3. Public addresses / network (dev-only ports; never publish to 0.0.0.0)
CONSOLE_HOST=127.0.0.1
CONSOLE_PORT=5173
# 4. Database names / role names (passwords and tenant id stay in .env.local)
WATCHMAN_DATABASE_NAME=watchman
WATCHMAN_MIGRATOR_USER=watchman_migrator
WATCHMAN_APP_USER=watchman_app
+4
View File
@@ -2,7 +2,9 @@
.env
.env.*
!.env.example
!.env.shared
secrets/
*.pem
*.key
*.p12
@@ -30,6 +32,8 @@ Thumbs.db
playwright/.auth/
test-results/
playwright-report/
web/apps/console/playwright-report/
docs/evidence/M01/ui/test-results/
# Raw local artifacts can contain internal data; keep only reviewed summaries
docs/evidence/**/raw/
+3 -3
View File
@@ -1,15 +1,15 @@
profiles:
think:
description: "Deep reasoning, planning, and gate decisions"
default: "openai/gpt-5.5"
default: "gpt-5.6-sol"
temperature: 0.1
build:
description: "Focused coding and implementation from approved task context"
default: "openai/gpt-5.4"
default: "grok-4.7"
temperature: 0.1
review:
description: "Reflective, cautious, nuanced review"
default: "deepseek/deepseek-v4-pro"
default: "grok-4.7"
temperature: 0.0
run:
description: "Fast utility work such as indexing and validation"
+1
View File
@@ -0,0 +1 @@
3.12
@@ -0,0 +1,150 @@
# Task Context Pack
## Task Goal
完成 Watchman M01 基础框架:实现 S1–S7、补齐 critic/review 必改与建议顺带项,并留下可回查证据。
## Knowledge Posture
- Mode: standard
- Maturity: L1
## Current Slice Or Group
当前:review 修复收尾已完成;等待复审结果与用户最终确认。不再扩大 M01 范围。
## Gate Policy
- Recommended: strict
- Selected: autonomous(任务局部)
- finalApprovalRequired: true
- Policy Notes: 分析→编码门禁已过。仓库 `gatePolicy.defaultMode` 保持 balanced(D17)。最终批准仍需用户确认。
## Bugfix Context
不适用(本轮为 review 修复)。
## Requirement Source
`.task/2026-11-17/m01-foundation/requirement.md`
## Implementation Source
`.task/2026-11-17/m01-foundation/implementation-plan.md`
## Involved Modules Or Areas
`services/watchman`、`web/`、`deploy/`、`docs/evidence/M01/`。
## Loaded Context
### Global Rules
AGENTS.md 托管段门禁;sy-standards;密钥不入库。
### Knowledge Map Matches
M01 基础框架。
### Path-Proximity Rules
无模块级 MODULE_RULES。
### Excluded Context
syops 业务代码、M02+、生产部署。
## Loaded Rules
- `standards://api/api-envelope?version=1.1.0`
- `standards://api/error-handling?version=1.1.1`
- `standards://engineering/code-layout?version=1.0.1`
- `standards://engineering/code-comments?version=1.1.1`
- `standards://security/red-line?version=1.1.0`
- `standards://security/env-secrets?version=1.1.1`
- `standards://frontend/frontend-stack?version=2.1.0`
- `standards://frontend/element-plus?version=1.0.2`
- D01、D04、D12–D18
## Loaded Docs
- `docs/tasks/M01.md`
- `docs/decisions.md`
- `docs/runbook.md`
- `docs/evidence/M01/*`
## Execution Mode
- Mode: sequential
- Current Slice Or Group: review-fixup(已实现)
- Parallel Members: 无
- Fallback Order: N/A
- Shared Files: N/A
- Merge Owner: 主 Agent
- Conflict Resolution Rule: 信封与 RLS 语义冻结
- Validation Level: module
## Execution Chain
实现 → 独立 review → 必改/建议修复 → Playwright/pytest → 复审 → 用户最终确认。
## Allowed Modification Scope
- `services/watchman/**`
- `web/**`
- `deploy/**`
- `.env.example`、`.env.shared`
- `docs/tasks/M01.md`、`docs/progress.md`、`docs/runbook.md`、`docs/decisions.md`、`docs/evidence/M01/**`、`docs/handoffs/**`
- `.task/2026-11-17/m01-foundation/**`
- `.gitignore`
## Forbidden Modification Scope
- 提交真实密码
- 写入 `D:\PROJECT\syops`
- 业务模块、Casdoor、vben5、Redis、生产部署
- 未经确认的门禁姿态放宽
- DONE_LOCAL/git commit(除非用户明确要求)
## Key Existing Classes Or Entrypoints
- `python -m watchman api|worker|beat`
- `web/apps/console` Vite 5173
- `/health`、`/platform/*`
## Required Behavior
- 数值信封无额外顶层字段;`/health` 不泄漏机密
- env 分层;启动缺键失败;probe/docs 非生产收口
- FORCE RLS;幂等;调用方不可传租户;commit 后租户重绑
- 前端三态 + 截图证据
## Non-goals
M02 登录、业务规则、真实企微、生产 Compose。
## Implementation Steps
1. (已完成)必改与建议修复。
2. (进行中)独立复审。
3. 用户最终确认后关 M01。
## Validation Commands
- `uv run pytest services/watchman/tests -q`
- `cd web/apps/console && pnpm test:unit && pnpm typecheck && pnpm test:e2e`
## Assumptions
- 本机 Postgres + RabbitMQ Compose 可用。
- `.env.local` 已配置且不入库。
## Risks
- 复审可能再发现残余项。
- 无 commit hash,证据与工作区绑定需靠文件路径与命令输出。
## Stop Conditions
- 复审 FAIL 或用户要求改口径时停止。
- 不自动 DONE_LOCAL/不自动 commit。
@@ -0,0 +1,497 @@
# M01 基础框架 Implementation Plan
## Requirement Source
`.task/2026-11-17/m01-foundation/requirement.md`
## Scope Summary
按已冻结的 M01 需求,顺序建立 uv 与 `web/` 工作区、环境分层、API 信封、带强制 RLS 的两张平台表、Celery 探测进程、管理台薄壳,以及只绑定本机的开发 Compose。不进入业务模块。
## Involved Modules Or Areas
Watchman M01。一个 Python 服务包,API / worker / beat 三个进程。前端是 `web/apps/console` 薄壳。
## Loaded Rules
- Marionettist:本任务 `gatePolicy.selected=autonomous`,`finalApprovalRequired=true`。分析到编码仍须用户确认。`risk_score >= 4` 和 `high-risk` 切片完成后必须停。
- `standards://engineering/code-layout?version=1.0.1`
- `standards://api/api-envelope?version=1.1.0`
- `standards://api/error-handling?version=1.1.1`
- `standards://frontend/frontend-stack?version=2.1.0`
- `standards://frontend/element-plus?version=1.0.2`
- `standards://security/red-line?version=1.1.0`
- `standards://security/env-secrets?version=1.1.1`
- `standards://engineering/code-comments?version=1.1.1`
- `standards://workflow/git-commit?version=1.1.0`
- Watchman D01、D04、D12–D15。
## Loaded Docs
- `docs/tasks/INDEX.md` M01
- `docs/development-plan.md` 技术栈;目录以 D12 为准
- `docs/decisions.md`
- syops 只用于对照,不复制 Flask、Redis worker 或字符串错误码
## Global Forbidden Scope
- `D:\PROJECT\syops` 内的任何写入。
- 业务包:数据源、查询、规则、报警、通知、场景、AI。
- Casdoor 真接入、权限点编码、vben5、Redis。
- 把 API、worker 拆成独立服务或独立数据库。
- 监听 `0.0.0.0`,或把开发端口写进任何非开发配置。
- 真实密钥、生产连接串、修改已合入迁移。
- 为列表分页做协议选择。
## Execution Strategy
- Complexity: complex
- Default Execution: sequential
- Parallel Execution: not-needed
- Fallback Execution: sequential
- Merge Owner: 主 Agent
- Conflict Resolution Rule: 工作区根、锁文件、env 样例和迁移目录由当前切片独占。后一切片不得改前一切片已经冻结的信封字段和 RLS 策略语义。
选择顺序执行,因为根工作区、环境样例和数据库会话会被多个切片碰到。
## Slice Dependency Graph
| Slice | Depends On | Can Run In Parallel With | Fallback Order | Shared Files | Merge Owner | Conflict Risk |
| --- | --- | --- | --- | --- | --- | --- |
| S1 工作区 | 无 | 无 | 1 | 根 `pyproject.toml`、`web/`、`.gitignore` | 主 Agent | high |
| S2 环境分层 | S1 | 无 | 2 | env 样例、`.gitignore` | 主 Agent | high |
| S3 信封 | S1 | 无 | 3 | `services/watchman` | 主 Agent | medium |
| S4 RLS | S2、S3 | 无 | 4 | 迁移、数据库会话 | 主 Agent | high |
| S5 队列 | S2、S4 | 无 | 5 | 同一 Python 包、Compose | 主 Agent | medium |
| S6 薄壳 | S3 | 无 | 6 | `web/` | 主 Agent | medium |
| S7 手册与总验 | S5、S6 | 无 | 7 | `deploy/`、`docs/runbook.md` | 主 Agent | medium |
S6 依赖 S3 的信封,不依赖 S4 的表。仍按上表顺序做,避免和 S5 同时改 Compose。
## Implementation Slices
### Slice 1: 工作区与工具链
#### Goal
建立可安装的 uv 工作区和 pnpm `web/` 工作区,锁定 Python 3.12 候选上的最小依赖。不写业务行为。
#### Allowed Modification Scope
- 根 `pyproject.toml`、`uv.lock`
- `services/watchman/pyproject.toml`
- `services/watchman/src/watchman/` 的空包和进程入口文件
- `web/package.json`、`web/pnpm-workspace.yaml`、`web/pnpm-lock.yaml`
- `web/apps/console` 的空 Vite 应用
- `web/packages/api`、`web/packages/ui-components`、`web/design` 的空包
- `.gitignore` 中与虚拟环境和前端依赖相关的条目
#### Forbidden Scope
- 业务模块、迁移、Compose、页面视觉、密钥文件。
#### Execution
- Mode: sequential
- Depends On: 无
- Can Run With: 无
- Must Not Run With: S2–S7
- Fallback Order: 1
- Shared Files: 根工作区
- Merge Owner: 主 Agent
- Conflict Risk: high
- Gate Class: standard
- Risk Score: 3
- Gate Reasons: new-dependencies
- Validation Level: slice
- Recommended Agent Strategy: 编码模型实现;审查用另一个模型系列
#### Steps
1. 核对 FastAPI、Pydantic v2、SQLAlchemy 2、Alembic、Celery、pytest 与 Python 3.12 的当前兼容版本,把结果写进切片记录。AGPL 依赖不引入。
2. 创建 uv 工作区。只建一个成员:`services/watchman`。入口预留 API、worker、beat,不拆服务。
3. 创建 pnpm 工作区:`web/apps/console`、`web/packages/api`、`web/packages/ui-components`、`web/design`。
4. 生成锁文件。
#### Validation
- `uv lock` 成功。
- `uv run --package watchman python -c "import watchman"` 成功。
- `pnpm install` 在 `web/` 成功,`pnpm -r list` 能看到 console 和两个包。
#### Done Criteria
- 锁文件入库所需的依赖已经固定。
- 还没有健康检查、表和页面行为。
#### Rollback Notes
删除新建的工作区文件和锁文件即可。没有数据库可回滚。
### Slice 2: 环境分层
#### Goal
按公司环境规范提供可提交的无密样例,并让进程从分层 env 读取配置。
#### Allowed Modification Scope
- `.env.shared`
- `.env.example`
- `.gitignore` 的 env 例外
- `services/watchman` 的配置读取模块
- 配置测试
#### Forbidden Scope
- `.env.local`、真实 `.env.dev`、真实密码。
- 监听地址改到非回环。
#### Execution
- Mode: sequential
- Depends On: S1
- Can Run With: 无
- Must Not Run With: S3–S7
- Fallback Order: 2
- Shared Files: `.gitignore`
- Merge Owner: 主 Agent
- Conflict Risk: high
- Gate Class: standard
- Risk Score: 3
- Gate Reasons: secrets-config
- Validation Level: slice
- Recommended Agent Strategy: 编码模型实现
#### Steps
1. `.env.shared` 只放三环境相同且非机密的值,包括开发绑定地址说明。
2. `.env.example` 列出 `.env.dev` 与 `.env.local` 要填的键,值用占位符。
3. 调整忽略规则:提交 `.env.shared` 和 `.env.example`;忽略 `.env.local`、`.env.dev`、`.env.test`、`.env.prod`。
4. 加载顺序实现为:系统环境、`.env.local`、`.env.dev`、`.env.shared`。
5. 开发端口写死为仅开发:API `127.0.0.1:8000`,控制台 `127.0.0.1:5173`,Postgres `127.0.0.1:54329`,RabbitMQ `127.0.0.1:56729`,管理端口 `127.0.0.1:15679`。
#### Validation
- 测试证明 `.env.local` 覆盖 `.env.dev`,`.env.dev` 覆盖 `.env.shared`。
- 仓库检索确认样例不含真实口令、token 或内网账号。
#### Done Criteria
- 缺配置时进程失败并给出键名,不打印其他配置值。
- 开发端口只出现在开发样例和开发 Compose 计划中。
#### Rollback Notes
恢复 `.gitignore` 并删除新的 env 样例和配置模块。
### Slice 3: API 信封与错误
#### Goal
提供健康检查和全局失败信封。路由不手写错误 JSON。
#### Allowed Modification Scope
- `services/watchman/src/watchman/api/`
- `services/watchman/src/watchman/services/` 中的健康服务
- 错误类型、响应构造、请求号中间件
- 对应 pytest
#### Forbidden Scope
- 数据库表、RLS、前端页面、队列任务。
#### Execution
- Mode: sequential
- Depends On: S1
- Can Run With: 无
- Must Not Run With: S4–S7
- Fallback Order: 3
- Shared Files: `services/watchman`
- Merge Owner: 主 Agent
- Conflict Risk: medium
- Gate Class: standard
- Risk Score: 3
- Gate Reasons: public-api-contract
- Validation Level: slice
- Recommended Agent Strategy: 编码模型实现
#### Steps
1. 成功体使用 `success`、`data`、`request_id`。失败体使用 `success=false`、`error`、`request_id`。
2. 错误码只用五段位整数。内部错误对外为 50000。
3. 尊重传入的 `X-Request-Id`;没有则生成。响应头回写同一个值。
4. `GET /health` 返回进程存活,不访问数据库,不返回租户、主机或连接串。
5. 增加一个只用于测试的参数错误路径,确认 40000 由全局处理生成。
#### Validation
- `uv run pytest services/watchman/tests/test_envelope.py`
- 断言成功与 40000、50000 的形状,并断言响应不含 traceback。
#### Done Criteria
- 健康检查和两类失败响应有测试。
- 没有信封例外出口。
#### Rollback Notes
移除 API 包中本切片新增的模块和测试。
### Slice 4: 平台表、租户会话与 RLS
#### Goal
在 PostgreSQL 建立审计事件和运行记录,应用角色被强制 RLS 限制在服务端租户内。
#### Allowed Modification Scope
- `services/watchman/migrations/`
- 数据库会话和租户上下文
- 审计、运行记录的最小写入服务
- RLS 与幂等测试
- 开发 Compose 中仅数据库服务的部分可以在本切片先写出,完整应用服务留到 S7
#### Forbidden Scope
- 报警、查询、场景等业务表。
- 从请求体、查询串或请求头读取租户。
- 用超级用户作为应用连接。
- 修改已经写好的迁移文件;纠正用新迁移。
#### Execution
- Mode: sequential
- Depends On: S2、S3
- Can Run With: 无
- Must Not Run With: S5–S7
- Fallback Order: 4
- Shared Files: 迁移目录、数据库会话
- Merge Owner: 主 Agent
- Conflict Risk: high
- Gate Class: high-risk
- Risk Score: 5
- Gate Reasons: schema, security, rls
- Validation Level: slice
- Recommended Agent Strategy: 独立实现与不同系列审查。本切片结束必须停,即使用户选择了 autonomous。
#### Steps
1. Compose 只启动 PostgreSQL,发布在 `127.0.0.1:54329`。创建迁移角色和应用角色。应用角色不是超级用户,也不是表所有者。
2. 迁移创建审计事件和运行记录。两表都有服务端写入的租户列和幂等键唯一约束。
3. 启用并强制 RLS。策略比较租户列和 `current_setting('app.tenant_id', true)`。
4. 每个应用事务在本地设置 `app.tenant_id`,值只来自服务端配置。
5. 写接口要求 `x-idempotency-key`。重复键返回第一次的结果,不插入第二行。
6. 测试覆盖:未设置租户不可读不可写;其他租户不可见;正确租户可读写;重复键不新增。
#### Validation
- 启动开发 Postgres 后执行迁移。
- `uv run pytest services/watchman/tests/test_rls.py services/watchman/tests/test_idempotency.py`
- 用应用角色手工查询确认没有租户设置时结果为空。
#### Done Criteria
- 空库迁移成功。
- RLS 正反用例通过。
- 健康检查仍然不访问这两张表。
#### Rollback Notes
停掉开发库卷并删除本切片迁移文件。若迁移已被共享环境应用,只能再写一条逆向迁移,不改原文件。
### Slice 5: 队列进程
#### Goal
API 之外的 worker 能连接 RabbitMQ,并注册一个不写业务事实的探测任务。
#### Allowed Modification Scope
- 同一 `services/watchman` 包内的 Celery 入口
- Compose 中的 RabbitMQ 服务,只绑定 `127.0.0.1:56729` 和 `127.0.0.1:15679`
- worker 启动测试
#### Forbidden Scope
- Redis result backend。
- 业务周期任务、报警计数、真实外发。
- 第二个调度框架。
#### Execution
- Mode: sequential
- Depends On: S2、S4
- Can Run With: 无
- Must Not Run With: S6、S7
- Fallback Order: 5
- Shared Files: Python 包、Compose
- Merge Owner: 主 Agent
- Conflict Risk: medium
- Gate Class: standard
- Risk Score: 3
- Gate Reasons: new-infrastructure
- Validation Level: slice
- Recommended Agent Strategy: 编码模型实现
#### Steps
1. Celery broker 指向开发 RabbitMQ。不配置 Redis。
2. 注册一个探测任务,返回静态状态,不写审计表,不增加任何业务次数。
3. beat 进程可以启动,但 M01 不注册业务日程。
#### Validation
- RabbitMQ 容器健康。
- worker 进程启动后能列出探测任务。
- 执行一次探测任务,确认审计表行数不变。
#### Done Criteria
- 三个进程入口都存在,仍然是同一个包。
- 探测任务没有业务副作用。
#### Rollback Notes
停止 RabbitMQ 容器并移除 Celery 入口。不删除 S4 的表。
### Slice 6: 管理台薄壳
#### Goal
本机控制台显示健康检查的加载、成功和失败。四语言目录齐全。不引入后台框架。
#### Allowed Modification Scope
- `web/apps/console`
- `web/packages/api` 的唯一 JSON 客户端
- `web/design/tokens.css` 的最小令牌
- `web/packages/ui-components` 保持空包或只放说明,不放 ProTable
#### Forbidden Scope
- vben5、业务菜单、列表页、第二套组件库。
- 页面内直接 `fetch`。
- 全局 `app.use(ElementPlus)`。
#### Execution
- Mode: sequential
- Depends On: S3
- Can Run With: 无
- Must Not Run With: S7
- Fallback Order: 6
- Shared Files: `web/`
- Merge Owner: 主 Agent
- Conflict Risk: medium
- Gate Class: standard
- Risk Score: 2
- Gate Reasons: none
- Validation Level: slice
- Recommended Agent Strategy: 编码模型实现,并用浏览器核对健康三态
#### Steps
1. 唯一客户端解析信封,失败抛带 `code`、`requestId` 的错误对象。
2. App 根注入一次 Element Plus 语言。页面按需引入用到的组件。
3. 建立 `locales/zh-CN`、`zh-TW`、`en`、`th`。健康文案四份都写上。
4. 页面请求 `/health`,分别呈现加载、成功和失败。
5. 开发服务器只绑 `127.0.0.1:5173`。
#### Validation
- `pnpm --filter console exec vue-tsc --noEmit`
- 浏览器打开本机控制台:API 可用时看到成功;API 停掉时看到失败;请求未完成时看到加载。
- 抽查一种非默认语言,健康文案不是硬编码中文。
#### Done Criteria
- 三态都实际看过,不只看截图。
- 四语言目录和 `errors.json` 骨架存在。
#### Rollback Notes
恢复 `web/apps/console` 到 S1 的空应用,保留工作区结构。
### Slice 7: 开发手册与总验
#### Goal
把 API、worker、beat、前端和两个基础设施服务收成一条开发手册,并跑本模块测试。
#### Allowed Modification Scope
- `deploy/compose.dev.yml`
- `docs/runbook.md`
- 根 README 里指向手册的短节
- `docs/tasks/M01.md` 的证据栏
- `docs/progress.md`
#### Forbidden Scope
- 生产 Compose、域名 443 配置、业务服务。
- 把 `0.0.0.0` 写进 Compose。
#### Execution
- Mode: sequential
- Depends On: S5、S6
- Can Run With: 无
- Must Not Run With: 无
- Fallback Order: 7
- Shared Files: `deploy/`、文档
- Merge Owner: 主 Agent
- Conflict Risk: medium
- Gate Class: standard
- Risk Score: 3
- Gate Reasons: dev-runtime
- Validation Level: final
- Recommended Agent Strategy: 主 Agent 汇总证据;测试由独立执行完成
#### Steps
1. Compose 包含 Postgres、RabbitMQ、API、worker、beat。端口只发布到 127.0.0.1,并在文件头标明仅开发。
2. 手册写明启动、迁移、测试和停止命令。
3. 跑后端测试、前端类型检查,并按 S6 再看一次健康三态。
#### Validation
- `docker compose -f deploy/compose.dev.yml config`
- 手册中的测试命令实际执行并记录退出码。
- 容器未启动时记录未运行,不记通过。
#### Done Criteria
- 手册命令和实际命令一致。
- M01 仍不声称业务模块或真实登录已经完成。
#### Rollback Notes
停止 Compose 并删除开发卷。文档可以回退到本切片之前。
## Parallel Slice Groups
没有并行组。
## Final Validation
- 信封测试、RLS 测试、幂等测试、worker 探测测试通过。
- `vue-tsc` 通过。
- 浏览器确认健康三态。
- `docker compose config` 通过,发布地址都是 127.0.0.1。
## Documentation Update Requirement
- 已在分析阶段记录 D12–D15。
- S1 记录实际锁定的版本,替换 O09 里本模块已经核实的部分。
- S7 更新 `docs/runbook.md`、`docs/progress.md` 和 `docs/tasks/M01.md`。
- 不把实现文件清单写进架构文档。
## Risks
- S4 是高风险切片。autonomous 不能越过它。
- 版本号要在 S1 查官方资料后锁定。计划里故意不预写。
- 分页协议和 vben5 仍延后。
- O08 的模型授权仍未确认。编码开始前要记下实际子 Agent 模型;不能把未执行的审查写成通过。
+43
View File
@@ -0,0 +1,43 @@
# Task Intake Result
## Task Type
feature. Watchman M01,搭建基础框架和开发环境。Tier M:一个已有任务边界的模块,含 API、壳层 UI 和本模块迁移。不是跨模块权限模型或真实外发。
## Current Understanding
用户要求先规划、不编码。范围以 `docs/tasks/INDEX.md` 的 M01 为准:后端/前端骨架、平台库迁移、任务队列与测试环境、错误/审计/运行记录基础和契约。不实现登录、业务模块或真实外发。
已确认技术方向见 `docs/decisions.md` D01:FastAPI、SQLAlchemy/Alembic、PostgreSQL、Celery/RabbitMQ、Vue 3/TS/Vite/Element Plus、Pinia/Router、pytest/Playwright、Docker Compose。不建微服务,不引入 Redis 作为任务结果库。
`D:\PROJECT\syops` 是 Flask + 自建 worker + Redis 的既有项目,Python 3.12,字符串错误码 `DOMAIN.SUBTYPE`,前端为 Vue 3.5、Element Plus、Pinia、vue-i18n、Tailwind 3。可借鉴环境文件分层、请求号和分层异常,不能把 Flask 应用或业务模块搬过来。公司现行信封已改为数值错误码。
## Gate Policy
- config/default: autonomous
- allowTaskOverride: true
- recommended: strict
- selected: autonomous
- reason or override reason: 用户于 2026-11-17 明确选择 autonomous。建议 strict 仍只作参考。
- effective: autonomous
- finalApprovalRequired: true
## Blocking Questions
无。2026-11-17 用户已选:autonomous、公司目录、薄壳、M01 实施 RLS、Compose 只绑本机。
## Non-blocking Assumptions
- 错误码按 `standards://api/api-envelope?version=1.1.0` 使用 40000/41000/42000/43000/50000。不沿用 syops 字符串码。`error-handling?version=1.1.1` 里残留的 `SYSTEM.INTERNAL_ERROR` 与信封冲突,内部错误拟用 50000。
- 四语言目录按 `frontend-stack?version=2.1.0` 建齐。M01 不交付业务列表,因此不锁定「cursor 分页」和 Element Plus 页码分页的冲突。
- 按钮图标按 `element-plus?version=1.0.2` 使用 `@element-plus/icons-vue`。
- 密钥只进 env。样例不含真实值。迁移只新增。
- 正式 Casdoor、业务表和真实发送不在 M01。
## Recommended Next Step
用户回答阻塞问题后,写 M01 实现切片。编码仍须单独确认。
## Suggested Prompt For Next Step
按已选门禁和目录,为 M01 写 implementation slices。只覆盖骨架、契约、迁移、队列和壳层。
@@ -0,0 +1,147 @@
# M01 基础框架 Requirement
## Goal
在隔离的本机开发环境里跑起 Watchman 的模块化单体骨架:统一 API 信封、平台库迁移、租户行级隔离、任务队列进程、空的管理台壳和可重复的测试命令。不交付业务预警功能。
## Background
范围来自 `docs/tasks/INDEX.md` 的 M01,技术方向来自 `docs/decisions.md` D01、D04。2026-11-17 用户确认了目录、前端厚度、RLS 和本机 Compose。公司规范以 sy-standards 当时读到的最新版本为准,篇目见 Source Notes。
`D:\PROJECT\syops` 只作为既有工程参照。它是 Flask、自建 worker 和字符串错误码,不能当作 Watchman 的实现模板。
## In Scope
- uv 工作区和 `web/` pnpm 工作区的空工程。
- 一个 Python 包同时提供 API、worker、beat 三个进程入口。
- FastAPI 健康检查、统一成功/失败信封、请求号、数值错误码。
- 环境变量按 `.env.shared`、`.env.dev`、`.env.local` 分层;机密不入库。
- PostgreSQL 上的审计事件表和运行记录表,启用并强制 RLS。
- 服务端注入租户会话。调用方不能提交 `tenant_id`。
- Celery + RabbitMQ 的空队列进程,不承载业务任务。
- 管理台薄壳:按页使用 Element Plus、Tailwind、四语言目录、一个能看见健康状态的空布局。
- 开发 Compose 只绑定 127.0.0.1。
- 依赖锁文件、迁移和测试命令。
## Out Of Scope
- Casdoor 真登录、权限点和业务授权。留到 M02。
- 数据源、查询、规则、报警、通知、Cron 场景和 AI。
- vben5、ProTable、业务列表和业务菜单。
- Redis、微服务、把 syops 业务代码拷进本仓库。
- 生产部署、对外监听、真实 MES 或企微。
- 在 M01 锁定列表分页协议。
## Current Behavior
仓库只有文档和 Git 初始化。没有 `backend/`、`frontend/`、依赖安装、数据库或容器。
## Required Behavior
- 按开发手册能在本机启动 API、worker 和前端壳。
- `GET` 健康检查返回成功信封,不返回连接串、租户标识或堆栈。
- 失败响应使用数值错误码。参数问题 40000,认证 41000,权限 42000,服务错误 50000。500 响应不包含堆栈或 SQL。
- 每个响应有 `request_id`,并与 `X-Request-Id` 对齐。
- 写操作接受 `x-idempotency-key`。同一键重复提交不产生第二条审计或运行记录。
- 应用数据库角色不是超级用户,也不是表所有者。未设置租户会话时读不到平台业务行,也不能写入。
- 设置了服务端租户后,只能读写该租户的行。
- 队列进程能连上本机 RabbitMQ 并注册一个无业务副作用的探测任务。探测任务不得写业务错误次数。
- 前端壳能显示健康检查成功、失败和加载。文案来自四语言目录。
## User Flow
开发者启动 Compose 和两个进程,打开本机管理台,看到健康状态。没有登录墙,也没有业务功能入口。
## Business Rules
- 仍是一个模块化单体。目录采用公司落位,不拆成多个可独立部署的服务。
- M01 只有一个由服务端配置的开发租户,没有租户管理功能。
- 审计和运行记录是平台基础事实,不是报警、采样或通知。
- 重试探测任务不得被记成业务异常。
## Data Rules
- M01 只建审计事件和运行记录两类平台表,外加迁移框架自身的表。
- 平台表含服务端写入的租户列,并对应用角色启用强制 RLS。
- 时间用 ISO 8601 UTC。
- 迁移只新增,不修改已经合入的迁移文件。
## API Contract
- 线格式以 `standards://api/api-envelope?version=1.1.0` 为准:`success`、`data` 与 `error` 互斥,带 `request_id`。
- `error.code` 使用 40000、41000、42000、43000、50000 段位。M01 不实现配额 43000 的业务。
- 不采用 syops 的 `DOMAIN.SUBTYPE` 字符串码。
- `error-handling?version=1.1.1` 示例里的 `SYSTEM.INTERNAL_ERROR` 与信封冲突。内部错误对外使用 50000。
- 列表分页协议不在本需求冻结。信封要求 cursor,Element Plus 规范要求页码,留到第一个列表模块再决定。
## UI Requirements
- 一个空管理台,按页引入 Element Plus,不全局注册。
- 四语言目录一次建齐:`zh-CN`、`zh-TW`、`en`、`th`。缺翻译回退 `zh-CN`。
- 健康状态有加载、成功、失败。
- 不引入 vben5,不做列表页骨架。
## Compatibility Requirements
- 前端落在 `web/`,后端落在 uv 工作区的一个服务包内,进程入口分开。
- 开发数据库和队列只监听 127.0.0.1。具体端口写在实现计划,并标明只用于开发。
- 新增第三方依赖先看许可证和维护状态。AGPL 不进入核心。
## Error Handling
- 路由不手写错误 JSON。服务层抛语义异常,全局处理成失败信封。
- 前端只有一个 JSON 客户端。页面不直接 `fetch`。
- M01 不登记信封例外出口。
## Permissions And Security
- 不读取、不提交真实密钥。样例值使用占位符。
- 调用方不能伪造租户。
- 健康检查不泄漏基础设施细节。
- 内部端口不对 `0.0.0.0` 发布。
## Assumptions
- Python 以 3.12 为候选,具体次版本和库版本在实现时按官方兼容情况锁定,不在本需求里预写版本号。
- 本机有 Docker,并能拉取 PostgreSQL 和 RabbitMQ 镜像。
- 开发租户标识放在不提交的 env 文件。
## Risks
- RLS 配错会造成要么全表可见,要么应用完全不可写。
- 公司落位规范里的目录例子来自多包平台,直接拆成多个服务会违反 D04。
- 信封 cursor 分页和 Element Plus 页码分页尚未裁决。
- 公司规范服务当前不在 Cursor 的 MCP 命名空间里,本次是经项目配置的 HTTP 端点读取的。
## Acceptance Criteria
- 新环境按手册启动后,健康检查返回成功信封且不含机密。
- 依赖有锁文件。
- 迁移可以向前应用到空库。回滚方式是新增迁移,不改已应用文件。
- RLS 有正反测试:正确租户可见,未设置租户和其他租户不可见。
- 同一幂等键不产生重复审计或运行记录。
- worker 进程可以启动并发现探测任务。
- 前端壳在成功、失败、加载三种状态下行为正确,四语言目录存在。
- 测试命令真实执行。容器或工具缺失时标未运行,不写成通过。
## Deferred Questions
- 第一个业务列表用 cursor 还是页码。
- vben5 在哪个后续模块引入。
- Casdoor 的 issuer、audience 和权限点。属于 M02 和 O10。
- O01 到 O07 的业务口径。不阻塞 M01。
## Source Notes
- 用户 2026-11-17:门禁选 autonomous;目录选公司落位;前端选薄壳;RLS 在 M01 实施;Compose 只绑本机。
- `docs/tasks/INDEX.md` M01。
- `docs/decisions.md` D01、D04。
- `standards://api/api-envelope?version=1.1.0`
- `standards://api/error-handling?version=1.1.1`
- `standards://frontend/frontend-stack?version=2.1.0`
- `standards://frontend/element-plus?version=1.0.2`
- `standards://engineering/code-layout?version=1.0.1`
- `standards://engineering/code-comments?version=1.1.1`
- `standards://security/red-line?version=1.1.0`
- `standards://security/env-secrets?version=1.1.1`
- `standards://workflow/git-commit?version=1.1.0`
@@ -0,0 +1,60 @@
# Critic Review — M01 验收预期审计
模式:acceptance-expectation audit(非 pre-done 收口)。marionettist-reviewer 为 NOT_RUN,本结论只表示「预期是否达成、能否进入 review」,不授权 DONE_LOCAL,不代表 reviewPassed。
## Verdict
PASS_WITH_WARNINGS
M01 预期结果:**大部分达成,部分未验证**。可以开始独立 review;在补齐下列验收缺口前不能关闭 M01。
## 验收条款逐项
| 验收条款 | 结论 | 依据 |
|---|---|---|
| 按手册启动后健康检查返回成功信封且不含机密 | 达成(本机已有环境) | runbook 有完整步骤;test_envelope 断言无 traceback、50000。未做「全新环境」复现 |
| 依赖有锁文件 | 达成 | `uv.lock`、`web/pnpm-lock.yaml` 存在 |
| 迁移可向前应用到空库;回滚靠新增迁移 | 基本达成 | 单一迁移 `20261117_0001`;迁移者角色拥有 schema,应用角色非所有者。空库 upgrade 无独立留证 |
| RLS 正反测试 | 部分达成 | 见 F1 |
| 同一幂等键不重复记录 | 部分达成 | 见 F2 |
| worker 可启动并发现探测任务 | 达成 | 任务注册测试 + 调用方称经 broker 执行且 audit 计数不变 |
| 前端三态行为正确、四语言目录存在 | 部分达成 | 见 F3 |
| 测试命令真实执行 | 达成(按调用方证据) | pytest 10 passed、typecheck、compose build;本次 critic 未重跑 |
## 产品/验收缺口(高信号)
- **F1 S4(high-risk / risk_score 5)RLS 证据不完整。** 已有:未设租户读不到、其他租户读不到、本租户读得到(仅 `audit_events`)。缺:
- 未设租户 **不能写入** 的反向测试(需求 Required Behavior 明确要求)。
- `run_records` 的 RLS 正反测试(仅靠同一迁移循环推断)。
- 应用角色非超级用户/非所有者/NOBYPASSRLS 的显式断言(目前只能从「读不到」间接推出)。
按 risk_score 5,S4 的验证证据应达到需求原文,而不是推断。
- **F2 幂等只测了审计事件。** `run_records` 走同样代码路径但无测试;且现有测试只比对返回 id,没有断言库内行数为 1。需求写的是「不产生第二条审计或运行记录」。
- **F3 前端三态未验证。** `App.vue` 有 loading/success/failure 分支和 i18n 键,但只有 typecheck,没有运行时断言或浏览器截图。这一条是验收条款本身,不只是流程证据。缺翻译回退 `zh-CN` 也未验证。
## 流程缺口(不影响「预期是否写出来」,但阻止关闭)
- 独立模块 review 未执行(`reviewPassed: false`,`criticPassed: false`)。
- 浏览器三态证据未归档;AGENTS 要求 UI 模块有断言+截图。
- `finalApprovalRequired: true`,需用户最终确认。
- M01.md「实施委派」仍写 `8 passed`,与证据段 `10 passed` 不一致,需主 Agent 修正。
- 无 commit;证据需按 AGENTS §9 用差异摘要或文件哈希绑定候选版本。
## 次要提示
- `WATCHMAN_TENANT_ID=dev-tenant` 放在入库的 `.env.shared`。不是密钥,但需求 Assumptions 写的是「放在不提交的 env 文件」。要么移到 `.env.local`,要么在 decisions 记一条偏差。
- `.env.dev` 文件不存在。配置代码会加载它,缺失可接受,但 runbook 最好说明它是可选层。
- `.env.local` 已被 `.env.*` 忽略且未被跟踪,符合要求。
- Compose 宿主端口均绑 127.0.0.1;容器内 `API_HOST: 0.0.0.0` 只在容器网络内,可接受。
## Gate Readiness
- 可以开始独立 review:是。
- review 后可以直接关闭:否。需先补 F1、F2(小型后端测试),补 F3(三态运行时断言或 Playwright+截图),再对受影响部分复审并重跑测试。
## Recommended Builder Action
1. 补 RLS 测试:未设租户插入应失败;`run_records` 读写隔离;查询 `pg_roles` 断言应用角色 `rolsuper=false`、`rolbypassrls=false`,且表所有者不是应用角色。
2. 补幂等测试:`run_records` 重复键;两张表都断言 `count(*) = 1`。
3. 用 Playwright 或组件测试覆盖健康三态(mock 成功、失败、挂起),截图存到 `docs/evidence/` 下非 raw 目录。
4. 修正 M01.md 中 8/10 passed 不一致;决定 `WATCHMAN_TENANT_ID` 的存放位置。
5. 之后再派独立 review(不同模型系列),通过后跑正式测试,再请求最终确认。
@@ -0,0 +1,140 @@
# Reviewer Review — M01 修复复审
模式:fuller two-stage review(沿用 S4 `gateClass: high-risk` / `risk_score: 5`)。
范围:仅复审 `.task/2026-11-17/m01-foundation/reviews/reviewer-m01.md` 的必处理项与已实现的建议项。不重审已通过切片的基线设计。
审查者不改产品代码,不授权 DONE_LOCAL。
## Recommendation
**PASS_WITH_WARNINGS**(复审当时)→ W1 已在复审后立刻收口
六条必处理项均已关闭。复审当时的非阻断残留 W1(`/openapi.json` 在 prod 仍 200)已在同会话补上:`openapi_url=None` + 测试断言 404。
可以进入用户最终确认(finalApproval)。本报告不将 M01 标为 DONE_LOCAL。
---
## 必处理项
| # | 原项 | 结论 |
|---|---|---|
| 1 | 重写配置分层测试 | **关闭** |
| 2 | Playwright 三态证据 | **关闭** |
| 3 | 启动期 `ensure_runtime_config` / `missing_required_keys` | **关闭** |
| 4 | `ENV_NAME` 收口 `/_probe` 与 `/docs` | **关闭**(见残留 W1) |
| 5 | 幂等 `IntegrityError` / 冲突回读 | **关闭** |
| 6 | 回滚 `gatePolicy` / `tier-policy` 漂移 | **关闭** |
无仍开放的必处理项。
### 1. 配置分层
`services/watchman/tests/test_config_layering.py` 用 `tmp_path` 写入三份 env 文件。`.env.local` 的 `API_PORT=8002` / `WATCHMAN_TENANT_ID=local-tenant` 覆盖 dev 与 shared;进程环境 `API_PORT=9000` 覆盖文件。`CHANGE-ME` 与空值进入缺失列表。`ensure_runtime_config` 以 `SystemExit` 退出,消息含键名,不含 `CHANGE-ME` 或 `password`。
`merge_layered_env`(`core/config.py`)只返回 dict,不再写入 `os.environ`。加载顺序是 `.env.shared` → `.env.dev` → `.env.local`,然后进程环境覆盖。
残留:现有断言只锁住「local 为最高文件层」和「进程环境最高」。若有人把 `.env.dev` 与 `.env.shared` 对调、同时保持 `.env.local` 最后,该测试仍会通过。实现顺序是对的,不构成未关闭项。
### 2. Playwright 三态
`web/apps/console/e2e/health.spec.ts` 有 loading→success、failure(含 `50000`)、`?lang=en` 三条用例,截图写入 `docs/evidence/M01/ui/`。本审查查看了四张图,与证据描述一致:
- `health-loading.png`:卡片内「健康检查加载中」
- `health-success.png`:绿色「健康检查成功」与「服务可用: watchman 0.1.0」
- `health-failure.png`:红色告警「服务不可用: 50000: Internal server error」
- `health-success-en.png`:「Health check succeeded」与「Service available: watchman 0.1.0」,无硬编码中文
用例通过 `page.route` 桩掉 `/health`,用来稳定拍出三态。这是 UI 证据,不是对活后端的联调。本审查未重跑 e2e,避免改写这些截图。
### 3. 启动缺键
`__main__.py` 在 api/worker/beat 分支之前调用 `ensure_runtime_config()`。`create_app()` 默认同样调用。必填键为 `DATABASE_URL`、`DATABASE_MIGRATOR_URL`、`WATCHMAN_TENANT_ID`;空串与含 `CHANGE-ME` 的值都算缺失。退出文本只拼接键名。
Compose 的 api/worker/beat 命令是 `python -m watchman`,走这条入口。
### 4. ENV_NAME
`is_non_production` 仅在 `env_name` 为 `dev` 或 `test` 时打开 `docs_url` 与 `/_probe/*`。`test_probe_and_docs_hidden_outside_non_production` 覆盖 prod 下 404。
本审查另起进程实测 `ENV_NAME=prod` 且 `validate_runtime=False`:
- `/docs` 404
- `/redoc` 404
- `/_probe/boom` 404
- `/openapi.json` **200**
`create_app` 只把 `docs_url` 置空,并设置 `redoc_url=None`,没有设置 `openapi_url=None`。见下方 W1。缺省 `env_name` 仍是 `dev`,未设置 `ENV_NAME` 时探针与文档保持开启;`docs/runbook.md` 已写明仅 dev/test 暴露。
### 5. 幂等
`create_audit_event` 与 `create_run_record` 在 `begin_nested()` 内 `flush`,捕获 `IntegrityError` 后按 `(tenant_id, idempotency_key)` 回读首次行;回读仍为空则原样抛出。唯一约束 `uq_audit_events_tenant_idem` / `uq_run_records_tenant_idem` 仍在迁移中。
测试含串行重复、四线程并发同键(`count == 1` 且 id 相同),以及把第一次查询打成未命中以迫使冲突回退。本次 `pytest` 这些用例通过。
### 6. 门禁漂移
工作区相对基线提交未修改 `marionettist.config.yaml` 与 `.marionettist/tier-policy.yml`。当前 `gatePolicy.defaultMode` 为 `balanced`。Tier L 为 `workflowHint: full-marionettist`、`gateHint: prefer-strict`。`docs/decisions.md` D17 记录该回滚不作为 M01 交付。D18 与 Compose 行内注释一致:容器内 `API_HOST=0.0.0.0`,宿主发布仍是 `127.0.0.1:8000:8000`。
`docs/progress.md` 与 `docs/tasks/M01.md` 写的是等待复审/最终确认,没有把 M01 标成 DONE_LOCAL。
---
## 建议项(抽查)
已在代码或证据中对上,不单列缺陷:
- 调用方 `tenant_id` 反向测试:响应与库行均为服务端租户
- Compose `0.0.0.0` 行内标注与 D18
- Tailwind v4(`@tailwindcss/vite` + `@import "tailwindcss"`)、`element-theme.css` 令牌映射、`ElConfigProvider` 随 `zh-CN` / `zh-TW` / `en` / `th` 切换
- 信封去掉顶层 `timestamp`;41000 / 42000(含 `permission_node`)/ HTTP 503 且 `retryable: true` 有断言;500 路径回写 `X-Request-Id`
- `Session.after_begin` 跳过嵌套事务;`test_tenant_rebounds_after_commit` 在同一 session 上两次 `commit()` 后仍能数到两行
- 非 JSON 响应抛 `BusinessError`(50000 + 响应头 request id)
- `mountApp("en")` 断言英文健康文案;四份 `errors.json` 已并入 i18n
- `bootstrap_local_db.py` 说明 `sql.Literal` 密码可能进入 `log_statement=all` 的服务器日志
- Dockerfile `USER watchman`(uid 10001),并在 `uv sync` 后 `chown`
- RLS fixture 按 `tracked_keys` 删除;未设租户的写入用例预期失败并 `rollback`
- `guest:guest` 仅作 Compose 开发缺省,API 服务有 DEV ONLY 注释;Settings 缺省 broker 已改为 `CHANGE-ME`
- `docs/evidence/M01/licenses.md` 的 fastapi 0.163.1、SQLAlchemy 2.0.57、Alembic 1.20.1、Celery 5.7.0、Pydantic 2.14.3 与 `uv.lock` 一致
---
## Stage 1:边界与合规
修复留在 M01 基础框架内:配置、启动、信封、RLS 会话、幂等、控制台健康壳、开发 Compose / Dockerfile、证据与 D17/D18。门禁文件已回到基线,没有把 `observed` / `target` 规则写成当前强制行为。
进度文档没有宣布 DONE_LOCAL。没有新的越权路径:租户仍只来自服务端设置,反向测试锁住了请求体里的 `tenant_id`。
W1 是收口不完整,不是对必处理项的回退。`/_probe` 与 `/docs` 的要求已经满足。
## Stage 2:实现质量
幂等冲突路径有真实数据库测试,不只是串行 check-then-insert。`after_begin` 有 commit 后重绑测试,不是只注册了监听器。信封与生产探针测试和本次抽查一致。
前端三态截图可读,英文态与中文态分开。Tailwind 布局在截图里生效(留白、浅底、单卡片)。
---
## 新发现(非阻断)
### W1(低)生产态仍提供 `/openapi.json`
`services/watchman/src/watchman/api/app.py` 在非 dev/test 时关闭 Swagger 与 ReDoc,未关闭 OpenAPI schema。本次实测 `ENV_NAME=prod` 时 `/openapi.json` 返回 200。schema 描述的是已经挂载的 `/health` 与 `/platform`,不额外泄露连接串。后续若要把文档面一并关掉,需同时设置 `openapi_url=None`。不阻塞本次最终确认。
### W2(低)分层测试没有单独锁住中间层
见必处理项 1 的残留。代码顺序正确。
---
## 本审查执行的验证
- `uv run pytest services/watchman/tests -q` → **23 passed**(1 条 Starlette/`httpx` 弃用警告)
- `web/apps/console`:`pnpm test:unit` → **8 passed**;`pnpm typecheck` → 通过
- `ENV_NAME=prod` 路由抽查:`/docs`、`/redoc`、`/_probe/boom` 为 404,`/openapi.json` 为 200
- 四张 UI 截图已查看
未重跑 `pnpm test:e2e`(会重写 `docs/evidence/M01/ui/`)。未构建镜像,未做空库全新 `alembic upgrade`。工作区仍无 commit,证据没有 git 哈希绑定;这是既有状态,用户未授权提交。
## 最终确认
M01 修复复审没有剩余阻断项。用户可以做 finalApproval。只有用户确认之后,主 Agent 才能考虑 DONE_LOCAL。本审查不授予该状态。
@@ -0,0 +1,215 @@
# Reviewer Review — M01 基础框架模块整体独立审查
模式:fuller two-stage review(含 S4 `gateClass: high-risk` / `risk_score: 5`)。
范围:S1–S7 全部已实现切片 + critic F1–F3 补齐。
审查者与实现者不同模型系列。本报告不授权 DONE_LOCAL。
## Recommendation
**PASS_WITH_WARNINGS**
未发现阻断级边界违规、租户越权或机密入库。RLS 设计是 fail-closed 的,应用角色约束正确,critic 的 F1–F3 已被实测覆盖。
但存在 1 条高信号测试失真(S2-1)和若干规范偏差,关闭 M01 前必须处理「必须修复」清单。
---
## Stage 1:边界与合规
### S1-1(中)S2 的 Done Criteria 未实现:缺配置不会在启动时失败
计划 S2 Done Criteria:「缺配置时进程失败并给出键名,不打印其他配置值。」
`services/watchman/src/watchman/core/config.py:86` 的 `missing_required_keys()` 写出来了,但全仓库无任何调用方(`__main__.py`、`api/app.py`、`jobs/celery_app.py` 都没有)。
同时 `config.py:58-65` 给 `DATABASE_URL` / `DATABASE_MIGRATOR_URL` 配了含 `CHANGE-ME` 的默认值,所以在 `.env.local` 缺失时进程能正常启动,直到第一次连库才在运行期炸,错误信息来自 psycopg 而不是键名。
建议:在 `__main__.py` 三个 role 分支前统一调用 `missing_required_keys([...])`,缺键时 `SystemExit` 并只打印键名;补一条测试。
### S1-2(中)测试专用路由与 `/docs` 无条件注册,`ENV_NAME` 没有被任何代码使用
`services/watchman/src/watchman/api/app.py:75` 与 `:82` 把 `/_probe/validation-error`、`/_probe/boom` 注册进 `create_app()` 本体,没有任何环境开关。`/_probe/boom` 会稳定产生未捕获异常 + 500 + 错误日志,是可被外部触发的噪声/轻量 DoS 面。
`app.py:34` 的 `docs_url="/docs"` 同样无条件开启。
`config.py:55` 已经有 `env_name`,但全仓库只在 `settings_as_public_dict()`(本身也无调用方)里出现过一次。
建议:`if settings.env_name == "dev"` 包住两个 `_probe` 路由与 `docs_url`;让 `ENV_NAME` 成为真正的环境判别位。这是 M01 冻结进程行为的地方,拖到 M02 之后成本更高。
### S1-3(中)前端对公司规范有三处偏差
| 偏差 | 位置 | 规范出处 |
|---|---|---|
| Element Plus locale 写死 `zhCn`,不随 i18n 切换 | `web/apps/console/src/App.vue:34` | `standards://frontend/element-plus?version=1.0.2` §1 明文「禁止写死 `zh-cn`」 |
| 未引入 Tailwind CSS v4,布局改用 `<style scoped>` 手写 | `web/apps/console/package.json`、`App.vue:77-90` | `frontend-stack?version=2.1.0` 裁定 Tailwind v4 为唯一原子样式层;D13 也点名 Tailwind |
| 无 `element-theme.css` 令牌映射,未引暗色变量 | `web/apps/console/src/main.ts:3` 只引了 `element-plus/dist/index.css` | `element-plus` §1「样式引一次」+ §2「变量先行」 |
第三项的后果是:页面背景走了 `tokens.css`,但 `ElCard`/`ElTag`/`ElAlert` 内部仍是 Element 默认配色与字号,和品牌令牌不一致。
注:ProTable / vben5 由 D13 明确延后,不计入偏差;Tailwind 与 locale 同步并未被任何决策延后。
### S1-4(中)UI 视觉验证未执行,M01 据此不能进 DONE_LOCAL
`docs/evidence/M01/health-states.md` 自述「未使用 Playwright 截图」,`state.json` S6 的 `gateReasons` 也记了 `browser-evidence-pending`。
计划 S6 Validation 要求「浏览器打开本机控制台」看三态,且「抽查一种非默认语言,健康文案不是硬编码中文」;AGENTS §5/§10 要求 UI 模块有断言+截图+视觉检查才能关闭。
当前只有 vitest 组件级断言。这不是伪造,证据写得诚实,但验收条款本身未满足。
### S1-5(低)三个文件改动不在本次声明的 allowed scope 内,其中两个放宽了门禁姿态
- `marionettist.config.yaml`:`gatePolicy.defaultMode` 由 `balanced` 改为 `autonomous`
- `.marionettist/tier-policy.yml`:Tier L 的 `workflowHint` 由 `full-marionettist` 降为 `analysis-context`,`gateHint` 由 `prefer-strict` 降为 `default`
- `docs/development-plan.md`:2.1 目录草图标注被 D12 取代(内容本身合理且保留了旧稿)
前两项影响的是后续模块:Tier L 在本仓的定义恰好覆盖「权限模型、生产外发、真实外部系统、部署变更」,也就是 M02 Casdoor 与企微真实发送。`finalApprovalRequired: true` 和 `risk_score >= 4` 的强制停顿仍在,所以不是安全漏洞,但属于需要用户明确点头的流程变更,不应混在 M01 实现里顺带落地。
`docs/progress.md` 与 `docs/handoffs/2026-11-17-002.md` 虽不在本次 allowed 列表,但计划 S7 和 AGENTS §7 要求更新,视为合规。
### S1-6(低)`API_HOST: 0.0.0.0` 写进了 Compose
`deploy/compose.dev.yml:55`。宿主发布仍是 `127.0.0.1:8000:8000`,容器内绑 `0.0.0.0` 是必要的,critic 也已接受运行时行为。
但计划 S7 Forbidden Scope 原文是「不把 `0.0.0.0` 写进 Compose」,红线 #6 要求「dev 演示临时绑 `0.0.0.0` 须显式标注」。文件头只说明了发布端口绑回环,没有就这一行做标注。
建议:在该行加一句行内注释说明「容器内监听,宿主仅回环发布,不得复用到任何部署配置」,并在 `docs/decisions.md` 补一条偏差记录。
### S1-7(低)信封多了标准未定义的顶层 `timestamp`
`services/watchman/src/watchman/core/response.py:24` 与 `:50`。
`standards://api/api-envelope?version=1.1.0` 的线格式只有 `success` / `data`|`error` / `request_id`,本篇自称「信封线格式唯一真源」。
值本身是合法的 ISO-8601 UTC,不影响消费方;但这是要被后续全部模块继承的契约,建议要么确认公司侧允许扩展字段,要么现在去掉。
### S1-8(低)依赖许可证预检无留证
红线 #8 与计划 S1 Step 1 要求新依赖先查许可证(AGPL 不进核心)。
实际锁定的版本与 `docs/decisions.md` O09 的记录完全一致(已核对 `uv.lock`:fastapi 0.163.1 / sqlalchemy 2.0.57 / alembic 1.20.1 / celery 5.7.0 / pydantic 2.14.3),版本记录可信;但没有任何文件记录许可证核查结果。实际依赖无 AGPL,补一行证据即可。
---
## Stage 2:实现质量
### S2-1(高)`test_config_layering.py` 并没有测试分层
`services/watchman/tests/test_config_layering.py`:
- `assert settings.api_host == "127.0.0.1"` 和 `settings.api_port == 8000` 与 `config.py:56-57` 的代码默认值相同,即使所有 env 文件都删掉也会通过
- `assert settings.tenant_id` 同理(默认 `dev-tenant`)
- 参数里的 `tmp_path` 根本没用,没有构造任何临时 env 文件
- 仓库里 `.env.dev` 不存在,所以「`.env.local` 覆盖 `.env.dev`、`.env.dev` 覆盖 `.env.shared`」这条中间层从未被执行过
- 唯一有效断言是 `if .env.local exists: "CHANGE-ME" not in database_url`,依赖本机文件存在,CI 上会静默跳过
计划 S2 Validation 原文是「测试证明 `.env.local` 覆盖 `.env.dev`,`.env.dev` 覆盖 `.env.shared`」。这条验收目前是假阳性。
代码本身(`config.py:29-43`)我逐行读过,优先级顺序是对的,所以这是测试缺陷不是功能缺陷——但它会让后续改动误以为有回归保护。
建议:用 `tmp_path` 造三份 env 文件、把 `_load_layered_env` 的根目录参数化(它已经接受 `root`),对同一个 key 断言三层覆盖关系。
### S2-2(中)幂等是 check-then-insert,并发重复键会返回 50000 而不是首次结果
`services/watchman/src/watchman/services/platform_records.py:40-55`(`run_records` 同构于 `:74-90`):先 `select` 再 `add`,中间没有任何防并发手段。
两个并发同键请求都查不到既有行 → 都 insert → 第二个撞 `uq_*_tenant_idem` → `IntegrityError` → 被兜底 handler 转成 50000。全仓库无 `IntegrityError` 捕获,也无 `ON CONFLICT`(已 grep 确认)。
需求写的是「重复键返回第一次的结果,不插入第二行」。现状只在串行下成立,现有两条幂等测试也都是串行的。
幂等键的全部意义就是防重试/防重发(AGENTS §8「任务重试、重复采样、消息重发不得增加业务错误次数」),这个基础设施会被 M02+ 的报警写入直接继承。
建议:`INSERT ... ON CONFLICT (tenant_id, idempotency_key) DO NOTHING RETURNING`,未返回行时回查;或捕获 `IntegrityError` 后回滚到 savepoint 再回查。
### S2-3(中)租户设置只在请求开始注入一次,`commit()` 之后即失效
`core/db.py:71-81` 的 `get_db_session` 在创建 session 后调用一次 `set_tenant`,而 `set_config(..., true)` 是事务局部的。
`api/routes/platform.py:52` 在路由里 `session.commit()`,该事务结束后 `app.tenant_id` 就没了。当前每个路由只提交一次,所以行为正确;但任何在 commit 之后继续用同一 session 的后续代码都会进入「无租户」事务,读为空、写被拒。
是 fail-closed,不是越权,但对 M02+ 是个安静的陷阱。
建议:用 SQLAlchemy `event.listens_for(Session, "after_begin")` 在每个事务开始时重新注入,而不是依赖「一个请求只提交一次」这个隐式约定。
### S2-4(中)`_load_layered_env` 永久污染 `os.environ`
`core/config.py:38-42`:把文件值 `setdefault` 进 `os.environ`。副作用是 `reload_settings()` 永远拿不到改过的文件值(第二次调用时这些 key 已经在 `os.environ` 里,被当成「进程环境优先」跳过),测试之间也会互相串。
`test_config_layering.py:14` 的 `monkeypatch.delenv` 就是在绕这个问题。
同一函数里 `__import__("os")` 内联了两次(`:40`、`:42`),`missing_required_keys` 里又 `import os`(`:88`)——顶层 import 即可,不符合 `standards://engineering/code-layout`。
建议:返回合并后的 dict 交给 pydantic-settings 消费,不要写 `os.environ`;至少提供一个显式的 `override=True` 路径给测试。
### S2-5(中)信封契约被冻结,但一半错误码没有测试
`core/errors.py` 定义了 40000/41000/42000/50000(503 retryable)五类。测试只覆盖 40000 与 50000。
未覆盖的里面有一条是标准硬性要求:`api-envelope` 规定 42000 必须回显 `permission_node`。`response.error_body` 确实只在非 None 时才放这个字段(`response.py:44-45`),逻辑是对的,但没有任何断言锁住它,M02 接权限时很容易被改掉。
建议:补一组参数化测试,断言 41000 / 42000(含 `permission_node`)/ 503(`retryable: true`)的信封形状。
### S2-6(中)「调用方不可传租户」是 S4 的核心安全不变量,但没有反向测试
`api/routes/platform.py:22-30` 的 `AuditCreateRequest` / `RunCreateRequest` 不含 `tenant_id`,Pydantic v2 默认忽略额外字段,所以外部传 `tenant_id` 确实不生效——但这是靠一个默认行为兜住的,一旦有人加了 `model_config = ConfigDict(extra="allow")` 或改成 `**kwargs` 就会破。
D14 和需求都把这条列为 M01 必须保证的行为,risk_score 5 的切片应该有显式断言。
建议:补一条「POST 带 `tenant_id: other-tenant` → 写入仍落在服务端租户」的测试。
### S2-7(低)500 响应丢失 `X-Request-Id` 响应头
`RequestIdMiddleware`(`api/app.py:20`)是用户中间件,位于 Starlette `ServerErrorMiddleware` 内层。未捕获异常会穿过它上抛,兜底 handler 返回的 `JSONResponse` 因此拿不到 `response.headers[...]` 回写。
body 里的 `request_id` 仍然正确(`request.state` 挂在共享的 scope state 上)。`AppError` 和 `RequestValidationError` 路径不受影响。
计划 S3 Step 3 要求「响应头回写同一个值」,这条在 500 路径上不成立。`test_envelope.py:34` 只断言了 body,没断言头,所以没发现。
### S2-8(低)前端客户端对非 JSON 响应抛裸错误
`web/packages/api/src/index.ts:60` 直接 `await response.json()`。遇到网关返回的 HTML 502 / 空响应时抛 `SyntaxError`,不是带 `code`/`requestId` 的 `BusinessError`,最终在 `health.ts:36` 以 `String(error)` 形式原样显示给用户。
计划 S6 Step 1 要求「失败抛带 `code`、`requestId` 的错误对象」。建议把 `json()` 包进 try,失败时抛 50000 + 头里的 request id(该分支代码已经存在于 `:62-68`,只是够不着)。
### S2-9(低)「四语言」测试实际断言的是回退中文
`web/apps/console/src/App.spec.ts:101-110` 这条用例以 `locale="th"` 挂载,但故意不注入 th 文案(`:29` 有注释说明),断言结果是「显示中文」。它证明的是 fallback 机制,不是四语言可用。
`mountApp` 里加载了 `en` 却没有任何用例用它。所以计划 S6「抽查一种非默认语言,健康文案不是硬编码中文」这条仍未验证。
另外四份 `errors.json` 已建骨架(符合计划),但 `src/i18n.ts` 没有加载它们,目前是悬空文件。
建议:加一条 `mountApp("en")` 并断言出现英文文案的用例,成本极低。
### S2-10(低)`bootstrap_local_db.py` 的 SQL 组装前后不一致,密码会进语句文本
`scripts/bootstrap_local_db.py`:`_upsert_role` 用 `psycopg.sql.Identifier`/`Literal` 正确组装(`:32-39`),但 `main()` 里 `CREATE DATABASE "{db_name}"`(`:75`)和四条 `GRANT ... TO "{user}"`(`:86-92`)是 f-string 拼接。值来自环境变量、风险低,但同一文件两套写法容易被后人照抄错的那套。
另外 `sql.Literal(password)` 会把明文密码放进语句文本,本机 Postgres 若开了 `log_statement=all` 就会落盘到服务端日志(红线 #1「密码绝不入…日志」)。本机开发可接受,建议在脚本 docstring 里显式标注这一限制。
### S2-11(低)死代码与为消除告警而写的占位
- `config.py:86 missing_required_keys`、`config.py:99 settings_as_public_dict`、`db.py:56 session_scope` 三个函数全仓库无调用方(已 grep)
- `api/app.py:88` 的 `_ = success_body` 是为了压 unused import 告警——直接删掉该 import 即可,`app.py` 本身不需要它
### S2-12(低)镜像以 root 运行;RLS 测试不清理数据
`deploy/Dockerfile` 没有 `USER` 指令。仅开发镜像,但加一个非 root 用户成本很低。
`tests/test_rls.py` 每次运行都往本机 `audit_events` / `run_records` 写入若干行且从不清理,长期会让本机库里积累测试数据,也会让「未设租户读不到」这类基于 `count(*) == 0` 的断言在未来更脆。建议用 fixture 在 teardown 里按 `idempotency_key` 前缀删除。
### S2-13(低)`guest:guest` 作为默认值写进了入库文件
`core/config.py:68` 与 `deploy/compose.dev.yml:56/80/102`。是 RabbitMQ 众所周知的开发默认账号,`docs/runbook.md:35` 也已标注「仅开发」,风险实际为零。
但红线 #1 的字面要求是密码不进代码与配置样例,建议改成无默认的必填键或占位符,避免这个写法被后续模块照抄到真实 broker 上。
---
## 做得对、不需要改的部分
- RLS 是 fail-closed 的:`current_setting('app.tenant_id', true)` 未设置时返回 NULL,比较结果为 NULL,读写都被拒;`ENABLE` + `FORCE` 都加了,`USING` 和 `WITH CHECK` 都写了,策略限定 `TO watchman_app`
- 角色分离正确:migrator 拥有 schema,app 角色 `NOSUPERUSER NOCREATEDB NOCREATEROLE NOBYPASSRLS`,`migrations/env.py` 明确走 migrator URL;`test_rls.py:29` 用 `pg_roles` + `pg_tables` 做了显式断言,不是间接推断
- 迁移单一、未被改写,符合红线 #2
- `/health` 只返回 `status`/`app`/`version`,不碰数据库、不回显租户或连接串,并有否定断言
- 兜底 handler 不泄漏堆栈,`test_envelope.py:41` 直接断言异常文本 `boom` 不出现在响应里
- Celery 无 result backend、探测任务无副作用并有计数不变的实测
- `.env.local` 未被跟踪,`.gitignore` 的 `!.env.shared` 例外加得准确,`.env.example` 全部是 `CHANGE-ME` 占位
- `uv.lock` 实际版本与 O09 记录逐项吻合,没有把未核实的版本写进文档
- critic 的 F1–F3 确实补齐了,不是改文档糊弄:未设租户写入失败、`run_records` 正反隔离、`count(*) == 1`、三态运行时断言都能在测试里找到对应代码
- 后端 13 条、前端 7 条测试与证据文档记的数量一致(已按文件逐条核对,未重跑)
---
## 关闭 M01 前必须处理
1. S2-1 —— 重写 `test_config_layering.py`,让它真的覆盖三层优先级
2. S1-4 —— 补浏览器三态证据(截图存 `docs/evidence/M01/` 非 raw 目录),或由用户明确同意以组件测试代替并记一条决策
3. S1-1 —— 启动期必填键校验接上 `missing_required_keys`
4. S1-2 —— `_probe` 路由与 `/docs` 按 `ENV_NAME` 收口
5. S2-2 —— 幂等改为 `ON CONFLICT` 或捕获 `IntegrityError`(这是会被所有业务模块继承的基础设施)
6. S1-5 —— 就 `marionettist.config.yaml` 与 `tier-policy.yml` 的门禁放宽单独向用户确认,不要夹在 M01 里
## 建议但可以排进 M02
S1-3(Tailwind / locale 同步 / element-theme.css)、S1-6、S1-7、S2-3、S2-4、S2-5、S2-6、S2-7、S2-8、S2-9、S2-10 ~ S2-13。
其中 S2-6(租户不可注入的反向测试)建议尽量不要拖——它是 S4 唯一没有测试锁住的安全不变量。
## 残余风险
- S4 是 `risk_score: 5`,但其安全保证目前靠「Pydantic 默认忽略额外字段」这一隐式行为兜底(S2-6),建议即使整体放行也先补这一条
- 本次审查未重跑任何测试命令,全部验证状态采信调用方证据;测试文件内容与声称的用例数一致,但执行结果本身未经本审查独立确认
- 空库全新 `alembic upgrade head` 没有独立留证(critic 也提过),本机库已存在,首次迁移路径未被重复验证
- 没有 commit,证据与候选版本之间缺少 hash 绑定(AGENTS §9)
@@ -0,0 +1,84 @@
{
"taskId": "2026-11-17/m01-foundation",
"type": "feature",
"phase": "finalization",
"status": "in_progress",
"allowedToCode": true,
"currentSlice": "S7",
"gatePolicy": {
"configDefault": "autonomous",
"allowTaskOverride": true,
"recommended": "strict",
"selected": "autonomous",
"reason": "User selected autonomous. Implementation slices S1-S7 complete; finalApprovalRequired remains true.",
"effective": "autonomous",
"finalApprovalRequired": true
},
"slices": [
{
"id": "S1",
"status": "completed",
"gateClass": "standard",
"risk_score": 3,
"gateReasons": ["new-dependencies"]
},
{
"id": "S2",
"status": "completed",
"gateClass": "standard",
"risk_score": 3,
"gateReasons": ["secrets-config"]
},
{
"id": "S3",
"status": "completed",
"gateClass": "standard",
"risk_score": 3,
"gateReasons": ["public-api-contract"]
},
{
"id": "S4",
"status": "completed",
"gateClass": "high-risk",
"risk_score": 5,
"gateReasons": ["schema", "security", "rls", "local-postgres"]
},
{
"id": "S5",
"status": "completed",
"gateClass": "standard",
"risk_score": 3,
"gateReasons": ["new-infrastructure"]
},
{
"id": "S6",
"status": "completed",
"gateClass": "standard",
"risk_score": 2,
"gateReasons": ["thin-shell-landed", "browser-evidence-pending"]
},
{
"id": "S7",
"status": "completed",
"gateClass": "standard",
"risk_score": 3,
"gateReasons": ["dev-runtime"]
}
],
"gates": {
"requirementFrozen": true,
"planApproved": true,
"contextPackReady": true,
"criticPassed": false,
"implementationDone": true,
"reviewPassed": false,
"validationPassed": true
},
"files": {
"intake": ".task/2026-11-17/m01-foundation/intake.md",
"requirement": ".task/2026-11-17/m01-foundation/requirement.md",
"implementationPlan": ".task/2026-11-17/m01-foundation/implementation-plan.md",
"contextPack": ".task/2026-11-17/m01-foundation/context-pack.md"
},
"updatedAt": "2026-11-17T05:20:00Z"
}
+95
View File
@@ -0,0 +1,95 @@
# Task Context Pack
## Task Goal
M02 用 Casdoor 做身份和三个粗角色。密码登录、会话、角色收口、登录页和地址令牌登录已经实现。D20 已确认地址令牌不核对签发应用。用户已确认完成,状态为 DONE_LOCAL。
## Knowledge Posture
- Mode: standard
- Maturity: L1
## Current Slice Or Group
收尾。地址令牌登录已由用户确认做法并实现。不开始下一个业务模块。
## Gate Policy
- Recommended: strict
- Selected: balanced
- finalApprovalRequired: true
- Policy Notes: 认证是 high-risk。O11 已由 D20 确认。标 DONE_LOCAL 仍要用户点头。
## Requirement Source
`.task/2026-11-17/m02-auth/requirement.md`
## Implementation Source
`.task/2026-11-17/m02-auth/implementation-plan.md`。地址令牌是其后按用户指令追加的入口,不在原切片正文里。
## Involved Modules Or Areas
`services/watchman` 的 `watchman.auth` 与 `/auth` 路由;`web/apps/console` 的登录壳。
## Loaded Rules
- `standards://api/api-envelope?version=1.1.0`
- `standards://security/red-line?version=1.1.0`
- `standards://engineering/code-comments?version=1.1.1`
- D14、D19、O10、O11
## Loaded Docs
- `docs/tasks/M02.md`
- `docs/runbook.md` 的登录节
- `docs/decisions.md` 的 D19、O10、O11
- `.task/2026-11-17/m02-auth/reviews/reviewer-m02-token-login.md`
## Allowed Modification Scope
- `services/watchman/src/watchman/auth/`
- `services/watchman/src/watchman/api/routes/auth.py`
- `services/watchman/tests/` 的登录与会话测试
- `web/apps/console` 的登录壳、会话和登录 e2e
- `docs/tasks/M02.md`、`docs/progress.md`、`docs/runbook.md`、`docs/decisions.md`
- 本任务目录下的审查记录和本 context pack
## Forbidden Modification Scope
- 不要再给地址令牌加签发应用校验,D20 已经否掉这条
- `D:\PROJECT\syops` 的任何写入
- 读取、打印或复制 `.env.local`、访问令牌
- 角色表、用户授权表、密码哈希
- 下一个业务模块
## Key Existing Entrypoints
- `POST /auth/login`:密码登录
- `POST /auth/token-login`:地址令牌,后端调用 Casdoor userinfo
- `POST /auth/hxops-entry`:签名断言,必须带 `casdoor_sub`
- `GET /auth/me`、`POST /auth/logout`
## Required Behavior
前端发现 `?token=` 后只提交给后端,并从地址栏去掉。后端不把该令牌写入会话、响应或日志。Casdoor 拒绝为 41000,不可用为 503。通过后的会话令牌是 Watchman 自己的。
## Validation Commands
- `uv run pytest services/watchman/tests -q`
- `pnpm --filter @watchman/console test:unit`
- `pnpm exec playwright test e2e/login.spec.ts`(在 `web/apps/console`)
## Assumptions
- 会话 8 小时。浏览器同时有 HttpOnly cookie 和 sessionStorage 里的 Watchman access token。
- 真实 Casdoor 只在用户明确要求时调用。测试注入替身。
## Risks
- D20:同一 Casdoor 实例上其他应用的有效访问令牌可以换 Watchman 会话。这是已确认行为。
- 地址上的令牌会出现在承接页面的访问日志里。
## Stop Conditions
- M02 已 DONE_LOCAL。不开始下一个模块,除非用户另行指定。
@@ -0,0 +1,398 @@
# M02 统一登录与权限 Implementation Plan
## Requirement Source
`.task/2026-11-17/m02-auth/requirement.md`
## Scope Summary
按已冻结需求接入 Casdoor 身份、三个粗角色和 Watchman 会话,收口 M01 平台写接口,并加上登录壳。不建角色表,不改 syops,不实现业务模块。
## Involved Modules Or Areas
Watchman 认证与现有平台 API、管理台薄壳。Casdoor 仅作为外部身份与角色来源。HXOPS 只作为短时断言的签发方,本仓库实现接收端。
## Loaded Rules
- 本任务 `gatePolicy.selected=balanced`,`finalApprovalRequired=true`。分析到编码仍须用户确认。
- `high-risk`、`boundary-sensitive`、critic 要求、`risk_score >= 4` 的切片完成后必须停。balanced 不能跳过这些停点。
- `standards://api/api-envelope?version=1.1.0`
- `standards://api/error-handling?version=1.1.1`
- `standards://api/permission-nodes?version=1.0.0`
- `standards://security/red-line?version=1.1.0`
- `standards://frontend/frontend-stack?version=2.1.0`
- `standards://frontend/element-plus?version=1.0.1`
- Watchman D01、D12、D13、D14、D19。
## Loaded Docs
- `.task/2026-11-17/m02-auth/requirement.md`
- `docs/tasks/INDEX.md` 的 M02
- `docs/decisions.md`
- syops 认证说明只作对照
## Global Forbidden Scope
- `D:\PROJECT\syops` 的任何写入,包括为了打通入口而改 HXOPS。
- 复制 syops `.env.dev` 的密钥、client id 或 audience 进仓库、文档、测试夹具。
- 用户表、角色表、授权管理页、密码哈希。
- 数据源、查询、规则、报警、通知、场景、AI。
- Redis、vben5、把健康检查改成必须登录。
- 未确认就新增三枚以外的权限点。
## Execution Strategy
- Complexity: complex
- Default Execution: sequential
- Parallel Execution: not-needed
- Fallback Execution: sequential
- Merge Owner: 主 Agent
- Conflict Resolution Rule: 认证切片按 S1 到 S6 的顺序写同一服务包。不并行。
selected `balanced` 对 S1–S5 不自动续跑:这些切片是 `high-risk` 或 `boundary-sensitive`,且要求 critic。S6 虽是 `simple`,也要等 S5 的停点结束之后再开始。
## Slice Dependency Graph
| Slice | Depends On | Can Run In Parallel With | Fallback Order | Shared Files | Merge Owner | Conflict Risk |
| --- | --- | --- | --- | --- | --- | --- |
| S1 令牌校验 | 无 | 无 | 1 | 无 | 主 Agent | low |
| S2 会话与密码登录 | S1 | 无 | 2 | `app.py`、`config.py` | 主 Agent | high |
| S3 角色收口 | S2 | 无 | 3 | 平台路由 | 主 Agent | high |
| S4 HXOPS 断言 | S2、S3 | 无 | 4 | `app.py`、会话 | 主 Agent | high |
| S5 登录壳 | S4 | 无 | 5 | 前端 API 客户端 | 主 Agent | medium |
| S6 文档与示例配置 | S5 | 无 | 6 | 任务卡、runbook、`.env.example` | 主 Agent | low |
## Implementation Slices
### Slice 1: 令牌校验
#### Goal
本地密钥下拒绝坏签名、错误 issuer、错误 audience 和过期令牌。这一步不发 HTTP 登录,不访问真实 Casdoor。
#### Allowed Modification Scope
- `services/watchman/src/watchman/auth/` 中的校验模块
- `services/watchman/tests/` 中对应该校验的测试
#### Forbidden Scope
- 路由、迁移、前端、`.env.local`、syops
#### Execution
- Mode: sequential
- Depends On: 无
- Can Run With: 无
- Must Not Run With: S2–S6
- Fallback Order: 1
- Shared Files: 无
- Merge Owner: 主 Agent
- Conflict Risk: low
- Gate Class: high-risk
- Risk Score: 4
- Gate Reasons: security-logic, critic-required
- Validation Level: slice
- Recommended Agent Strategy: 实现用编码模型;本切片审查用另一系列,并先读冻结需求
#### Steps
1. 实现只接受已验签声明的校验:issuer、audience、有效期、签名。
2. 用测试生成的密钥覆盖四类失败和一类成功。
3. 确认失败结果不能被当成已登录。
#### Validation
`uv run pytest services/watchman/tests -q`
#### Done Criteria
验收标准 1 在单元测试中有对应断言。仓库里没有真实密钥。
#### Rollback Notes
删除新增的 auth 校验模块和测试即可。无迁移。
### Slice 2: 会话与密码登录
#### Goal
用可替换的 Casdoor 替身完成密码登录、当前用户和退出。会话写入服务端,遵守 RLS。未配置真实应用时登录失败为 503,测试不依赖内网 Casdoor。
#### Allowed Modification Scope
- `services/watchman/src/watchman/auth/`
- `services/watchman/src/watchman/api/` 的登录路由和注册
- `services/watchman/src/watchman/core/config.py`
- `services/watchman/src/watchman/models/` 与对应 Alembic 迁移,仅限会话
- `services/watchman/tests/` 的登录与会话测试
- `.env.example` 只加占位键名,值为空或 CHANGE-ME
#### Forbidden Scope
- 前端页面、平台写接口的授权、HXOPS 断言、syops、真实 secret
#### Execution
- Mode: sequential
- Depends On: S1
- Can Run With: 无
- Must Not Run With: S3–S6
- Fallback Order: 2
- Shared Files: `app.py`、`config.py`、迁移目录
- Merge Owner: 主 Agent
- Conflict Risk: high
- Gate Class: high-risk
- Risk Score: 4
- Gate Reasons: security-logic, schema-change, critic-required
- Validation Level: slice
- Recommended Agent Strategy: 实现与审查分属不同模型系列
#### Steps
1. 增加会话存储。字段限于需求中的数据规则。租户只用服务端配置。
2. 密码登录调用可注入的 Casdoor 端口。成功写会话并取回角色;失败 41000;端口不可用或未配置 503。
3. 提供当前用户与退出。退出后会话不可再用于后续切片的平台写接口。
4. 测试断言响应和日志路径不包含密码、secret、Casdoor token。
#### Validation
`uv run pytest services/watchman/tests -q`
#### Done Criteria
验收标准 2、8 的会话部分、9 有自动化证据。健康检查仍匿名可用。
#### Rollback Notes
回滚本切片迁移,并移除登录路由。不改动 S1 的纯校验测试。
### Slice 3: 角色收口与对象检查
#### Goal
平台写接口改为必须是 `watchman-admin`。进入能力与对象 ID 检查按冻结的三枚权限点拒绝。角色快照过期后,Casdoor 不可用则拒绝。
#### Allowed Modification Scope
- `services/watchman/src/watchman/auth/`
- `services/watchman/src/watchman/api/routes/platform.py`
- `services/watchman/tests/` 中权限与对象检查测试
#### Forbidden Scope
- 新的业务表、授权管理接口、前端、syops
#### Execution
- Mode: sequential
- Depends On: S2
- Can Run With: 无
- Must Not Run With: S4–S6
- Fallback Order: 3
- Shared Files: 平台路由、auth 依赖
- Merge Owner: 主 Agent
- Conflict Risk: high
- Gate Class: high-risk
- Risk Score: 4
- Gate Reasons: security-logic, permission-nodes, critic-required
- Validation Level: slice
- Recommended Agent Strategy: 实现与审查分属不同模型系列
#### Steps
1. 为三个权限点接上角色判断。无角色不升成查看者。
2. 平台两个写接口接入 `perm:data:emp:watchman.platform.write`。
3. 对象检查对两个合成 ID 在无授权时都返回 42000,权限点为 `perm:data:emp:watchman.object.read`。不新增公开的对象管理 API。
4. 角色确认超过 5 分钟且替身失败时,返回 503,不放行。
#### Validation
`uv run pytest services/watchman/tests -q`
#### Done Criteria
验收标准 3、4 的服务端部分、5、7 通过。41000 的响应里没有 `permission_node`。
#### Rollback Notes
恢复平台路由的 M01 行为会重新变成匿名可写。回滚时要连同本切片测试一起撤下,并在进度里写明平台写接口重新失去保护。
### Slice 4: HXOPS 短时断言
#### Goal
接收端校验短时断言,建立与密码登录相同的会话。角色只从 Casdoor 端口读取。
#### Allowed Modification Scope
- `services/watchman/src/watchman/auth/`
- `services/watchman/src/watchman/api/` 的断言入口
- `services/watchman/tests/` 的断言测试
#### Forbidden Scope
- 修改 syops、在断言中信任 HXOPS 权限列表、前端以外的业务模块
#### Execution
- Mode: sequential
- Depends On: S2、S3
- Can Run With: 无
- Must Not Run With: S5–S6
- Fallback Order: 4
- Shared Files: `app.py`、会话创建
- Merge Owner: 主 Agent
- Conflict Risk: high
- Gate Class: high-risk
- Risk Score: 4
- Gate Reasons: security-logic, external-identity, critic-required
- Validation Level: slice
- Recommended Agent Strategy: 实现与审查分属不同模型系列
#### Steps
1. 校验断言的签名、issuer、audience、有效期和 Casdoor 身份引用。
2. 缺少该引用,或只用 HXOPS 本地主键冒充时,返回 41000。
3. 通过后调用与密码登录相同的角色读取。断言内的权限字段不写入会话。
#### Validation
`uv run pytest services/watchman/tests -q`
#### Done Criteria
验收标准 6 通过。真实 HXOPS 跳转未配置时,证据里写明未做真实联调。
#### Rollback Notes
移除断言路由。密码登录和平台收口保持可用。
### Slice 5: 登录壳
#### Goal
管理台可以登录、看到无权限、会话失效后离开、退出。本地身份模式有可见标识。
#### Allowed Modification Scope
- `web/apps/console/`
- `web/packages/api/`
- 对应的单元测试与 Playwright
#### Forbidden Scope
- 后端授权规则、vben5、把真实 secret 写进前端环境
#### Execution
- Mode: sequential
- Depends On: S4
- Can Run With: 无
- Must Not Run With: S6
- Fallback Order: 5
- Shared Files: 前端 API 客户端、路由
- Merge Owner: 主 Agent
- Conflict Risk: medium
- Gate Class: boundary-sensitive
- Risk Score: 4
- Gate Reasons: auth-ui, session-boundary, critic-required
- Validation Level: slice
- Recommended Agent Strategy: 实现后用浏览器走登录失败、无权限和退出;审查用另一系列
#### Steps
1. 登录页提交到 S2 的接口。失败展示通用文案。
2. 按当前用户角色进入壳页或无权限页。
3. 退出并确认再访问受保护调用会失败。
4. 本地身份模式显示固定标识。
5. 为 HXOPS 断言准备提交入口,不把断言写进日志或本地长期存储。
#### Validation
- `pnpm test:unit`
- `pnpm test:e2e`
- 浏览器实际走一遍登录失败、无权限和退出。只看截图不算完成。
#### Done Criteria
验收标准 11 有断言和浏览器操作证据。前端包里没有 client secret。
#### Rollback Notes
撤下登录页后,后端会话仍在。进度里要写明界面与接口暂时不一致。
### Slice 6: 文档与示例配置
#### Goal
任务卡、运行说明和示例环境变量与已实现行为一致,并写清真实联调尚未完成的条件。
#### Allowed Modification Scope
- `docs/tasks/M02.md`
- `docs/runbook.md`
- `docs/progress.md`
- `docs/decisions.md`
- `.env.example`
#### Forbidden Scope
- 业务代码、真实密钥、把本地测试写成真实 Casdoor 已通过
#### Execution
- Mode: sequential
- Depends On: S5
- Can Run With: 无
- Must Not Run With: 无
- Fallback Order: 6
- Shared Files: 进度和任务卡
- Merge Owner: 主 Agent
- Conflict Risk: low
- Gate Class: simple
- Risk Score: 2
- Gate Reasons: docs-only
- Validation Level: final
- Recommended Agent Strategy: 主 Agent 直接改文档,并对照验收标准 12
#### Steps
1. 写上 Watchman Application 需要哪些键,值保持占位。
2. 写明真实密码登录和真实 HXOPS 跳转的完成条件。
3. 更新 M02 任务卡证据。没有命令输出就写未运行。
#### Validation
对照需求验收标准逐条看证据路径是否存在。不新跑业务测试,除非文档改动同时改了示例配置的键名。
#### Done Criteria
验收标准 12 在进度和任务卡里有明确状态。示例文件没有真实 secret。
#### Rollback Notes
文档回退不影响已发布的会话行为。
## Parallel Slice Groups
本任务不设并行组。会话、路由注册和权限依赖是同一条链。
## Final Validation
- `uv run pytest services/watchman/tests -q`
- `pnpm test:unit`
- `pnpm test:e2e`
- 浏览器走登录失败、无权限、退出
- 检查响应与日志样本,确认没有密码和 client secret
- 真实 Casdoor 与真实 HXOPS 入口未就绪时保持未完成,不并入上述通过结论
## Documentation Update Requirement
S6 更新运行说明和任务卡。不把本计划扩写成新的架构文档。若实现时发现会话规则和冻结需求不一致,先停下来改需求,再改代码。
## Risks
- S2 的迁移一旦执行,回滚需要明确的 down 步骤。
- S3 之前平台写接口仍匿名可写。不要在 S2 做完时宣称模块已经收口。
- S5 的 `risk_score` 为 4,即使界面工作看起来较小,也不能在 S4 通过后自动开做。
+58
View File
@@ -0,0 +1,58 @@
# Task Intake Result
## Task Type
feature。Tier L(认证、授权、会话;安全敏感,critic 建议保留)。
## Current Understanding
- 用户要求推进 M02(统一登录与权限),先规划并讨论疑问,不编码。
- M01 已 DONE_LOCAL。现有 `/platform/*` 写接口没有登录校验。租户只来自服务端 `WATCHMAN_TENANT_ID`(D14)。
- 冻结文档 15.1:接入 Casdoor,不另建正式账号密码体系;后端校验;无权限不能只靠隐藏按钮。无真实配置时只用显著标识的开发身份,不能当作正式验收。
- O10 仍是 TECH_PENDING:issuer、client、audience、角色和数据范围映射未提供。
- 用户已选:自有登录页 + 后端 password grant,并实现 HXOPS 短时 JWT 接收端。syops 平级服务文档把身份和业务权限分开;HXOPS 角色在本库,不在 Casdoor。
- 公司权限点格式为 `perm:{data|app}:{emp|dept}:{action}`(`standards://api/permission-nodes?version=1.0.0`)。禁止在代码里编造未确认编码。M01 测试夹具 `perm:platform:audit.read` 不符合该格式,不能当成正式权限点。
## Gate Policy
- config/default: balanced
- allowTaskOverride: true
- recommended: strict
- selected: balanced
- reason or override reason: 用户在 2026-11-17 选择 balanced。推荐 strict 仅作建议,不覆盖该选择。
- effective: balanced。分析到编码仍须确认。高风险切片、critic、显式停点不受 balanced 取消。
- finalApprovalRequired: true
## Blocking Questions
已确认:
1. 门禁:balanced。
2. 登录:Watchman 自有登录页,后端 password grant;同时做从 HXOPS 进入的短时 JWT 接收端。
3. 用户倾向授权放在 Casdoor,不在 Watchman 再维护一套角色。syops 现状与此不同,见下方,待用户二选一。
仍待确认:
1. 授权来源按用户倾向(Casdoor 角色,Watchman 只校验)还是按 HXOPS 现状(本库角色表)。
2. Casdoor Application:用户已选新建 Watchman Application。不复用 HXOPS client。密钥只进 `.env.local`。应用未建好前,真实密码登录不能当作通过。
## 已核对的 syops 事实
- HXOPS 把用户和密码同步到 Casdoor。角色、功能权限、权限组在 HXOPS 自己的库里,不在 Casdoor。
- 平级服务 SSO 文档写明:认证只回答“是谁”;平级服务自己管业务权限;SSO JWT 不携带 HXOPS 权限列表。
- `.env.dev` 的 Casdoor 指向内网 `organization_HX`。JWKS 本机可访问(HTTP 200)。回调地址是 HXOPS 前端端口,该 client 属于 HXOPS。密钥不写入本仓库。
## Non-blocking Assumptions
- M02 不实现用户管理后台、组织全量同步、企微发送、场景/数据源业务模块。
- 对象级越权用合成对象 ID 验证检查器;场景、数据源等表留到对应模块。
- 密钥只进 `.env.local`,不进对话、仓库和文档。
- 分析到编码仍需用户明确确认。
## Recommended Next Step
用户回答阻塞问题后,写 `.task/2026-11-17/m02-auth/requirement.md`,再切片。在此之前不编码。
## Suggested Prompt For Next Step
确认门禁、登录方式、授权落点和有无测试应用后,冻结 M02 需求并给出实现切片。
+168
View File
@@ -0,0 +1,168 @@
# M02 统一登录与权限 Requirement
## Goal
Watchman 用 Casdoor 确认“是谁”,用 Casdoor 上的三个粗角色确认“能进到哪一档”。本服务强制校验,不另建账号密码,也不另建角色表或授权管理页。
## Background
- M01 已完成。`POST /platform/audit-events` 与 `POST /platform/run-records` 目前没有登录校验。健康检查保持公开。
- 租户只来自服务端 `WATCHMAN_TENANT_ID`(D14)。调用方不能传租户。
- 用户 2026-11-17 确认:门禁 balanced;自有登录页加后端向 Casdoor 校验密码;同时接收 HXOPS 短时 JWT;授权按 Casdoor 粗角色,不建本库角色;新建 Watchman 自己的 Casdoor Application,不复用 HXOPS client。
- syops 的现状不同:HXOPS 把角色存在自己的库里。本需求不照搬该表结构。平级服务文档仍适用的部分是:认证与授权分开,SSO JWT 不携带 HXOPS 权限,退出只清本服务会话。
- 公司权限点格式为 `perm:{data|app}:{emp|dept}:{action}`(`standards://api/permission-nodes?version=1.0.0`)。Watchman 此前没有已注册编码。下面三枚是本模块冻结的最小清单。
## In Scope
- 用户名和密码在 Watchman 登录页提交。后端用 Watchman Application 向 Casdoor 校验。浏览器不打开 Casdoor 登录页。
- 接收 HXOPS 发来的短时身份断言,校验后建立与密码登录相同的 Watchman 会话。
- 校验签名、issuer、audience、有效期。未验签的内容不能授权。
- 三个 Casdoor 角色:`watchman-admin`、`watchman-operator`、`watchman-viewer`。
- 保护现有平台写接口。未登录与无权限分开。
- 对象 ID 本身不是授权。提供可复用的对象访问检查,并用两个合成 ID 证明未授权时都拒绝。
- 登录、失败、过期、无权限、退出的界面,以及对应自动化测试。
- 配置缺失或真实应用尚未建好时,自动测试用本地签名身份。这种身份必须显著标识,不能当作真实联调通过。
## Out Of Scope
- 用户管理、改密、把用户同步到 Casdoor。继续由 HXOPS 负责。
- 本服务的角色表、授权管理页、按人编辑功能权限。
- 场景、数据源、报警等业务模块,以及“某一行数据属于谁”的正式授权。
- 修改 `D:\PROJECT\syops`,或在 HXOPS 里增加 Watchman 入口。
- 复用 HXOPS 的 client id、client secret 或 audience。
- 浏览器跳转到 Casdoor 授权页作为主登录方式。
- 全局退出、退出 Casdoor、退出 HXOPS。
- 企微登录按钮、企微通知。
- Redis、微服务拆分、vben5。
## Current Behavior
- 平台写接口匿名可调用。
- 没有登录页、会话或 Casdoor 配置。
- 错误信封已能表达 41000 和 42000。42000 在有权限点时回显 `permission_node`。
## Required Behavior
- 健康检查仍不要求登录。
- 平台写接口:无会话返回 41000;有会话但没有 `watchman-admin` 返回 42000,并带权限点 `perm:data:emp:watchman.platform.write`。
- 进入管理台:三个角色之一即可。权限点 `perm:app:emp:watchman.enter`。已登录但没有任何这三个角色时,显示无权限,不显示业务操作。
- 对象检查:权限点 `perm:data:emp:watchman.object.read`。调用方未获该对象授权时,两个不同的合成 ID 都拒绝。知道 ID 不能读到数据。M02 不提供按对象授权的维护功能,默认没有对象级授权。
- 密码错误、断言无效、签名错误、issuer 或 audience 不符、令牌过期:拒绝,不建立会话。
- Casdoor 在需要重新确认角色时不可用:拒绝本次操作,返回可重试的 503。不沿用已经过期的角色缓存。
- 登录响应和日志不包含密码、client secret、Casdoor token。
- 会话里的租户只等于服务端配置。请求或令牌里的租户值不生效。
- 退出只清除 Watchman 会话。
## User Flow
1. 用户打开 Watchman 登录页,输入账号和密码。
2. 后端向 Casdoor 校验。成功则建立本服务会话,并读回该用户在 Watchman Application 上的角色。
3. 有三个角色之一:进入壳页。没有:进入无权限页。
4. 从 HXOPS 进入时,HXOPS 交给 Watchman 一个短时断言。Watchman 校验断言后,再按同一身份向 Casdoor 取 Watchman 角色,然后进入与上面相同的会话。
5. 会话过期或角色缓存过期且无法重新确认:回到登录或拒绝操作。
6. 用户退出:只离开 Watchman。
## Business Rules
- Casdoor 是身份来源,也是这三个角色的分配来源。分配在 Casdoor 控制台完成。
- Watchman 不解释 HXOPS 的角色和功能权限。断言里即使带了那些权限也忽略。
- `watchman-admin` 覆盖处理者和查看者的本模块能力。`watchman-operator` 覆盖查看者的进入能力。本模块里处理者与查看者的差别只保留角色名,供后续模块使用;M02 没有单独的“处理”业务动作。
- 无角色不等于查看者。不默认授予 `watchman-viewer`。
- 本地签名身份只在非生产、且显式开启的测试或开发模式可用。界面必须看得出这不是正式登录。
## Data Rules
- 可以保存会话:身份主体、签发方、显示名、角色快照、角色确认时间、过期时间、服务端租户。
- 不保存密码、密码哈希、client secret、Casdoor access token。
- 不建角色定义表,不建用户授权表。
- 会话上的租户来自服务端配置,并遵守现有 RLS。
- 技术默认,不是业务制度:会话 8 小时;角色快照 5 分钟后必须向 Casdoor 重新确认。
## API Contract
沿用 M01 信封(`standards://api/api-envelope?version=1.1.0`)。
- 登录:提交用户名和密码。成功建立会话。失败 41000。Casdoor 未配置或暂时不可达:503,且可重试。
- 退出:清除本服务会话。
- 当前用户:返回身份和角色名。不返回秘密。
- HXOPS 进入:提交短时断言。校验失败 41000。成功后的会话与密码登录相同。
- 平台写接口按 Required Behavior 保护。
断言必须同时满足:签名有效、issuer 与 audience 符合 Watchman 期望的 HXOPS 入口配置、未过期,并且带有 Casdoor 身份引用。HXOPS 自己的本地用户主键不能冒充该身份。
## UI Requirements
- 登录页使用现有 Element Plus 薄壳,收集用户名和密码,展示失败原因的通用文案。
- 无权限、会话过期、退出后的落点要能区分。
- 本地身份模式有可见标识。
- 不把 Casdoor 跳转作为主路径。
- 界面隐藏按钮不是授权。后端结果为准。
## Compatibility Requirements
- 不改变健康检查的匿名访问。
- 不改变信封形状。41000 不带 `permission_node`。42000 带上面列出的权限点。
- 新的 Casdoor Application 与 HXOPS 共用同一 Casdoor 服务和组织。client 必须分开。
- 真实密码登录和真实 HXOPS 跳转,在 Watchman Application 或 HXOPS 入口配置未就绪时记为未通过,不记为失败的产品逻辑。
## Error Handling
- 登录失败使用统一文案,不把 Casdoor 原文回给浏览器。
- 秘密不进响应、日志和文档。
- 角色刷新失败不降级为放行。
## Permissions And Security
冻结的权限点:
| 编码 | 含义 | 谁可以通过 |
|---|---|---|
| `perm:app:emp:watchman.enter` | 进入管理台 | 三个角色之一 |
| `perm:data:emp:watchman.platform.write` | 写平台审计和运行记录 | 仅 `watchman-admin` |
| `perm:data:emp:watchman.object.read` | 按对象 ID 读取 | M02 默认无人获得;检查必须拒绝未授权 ID |
公司规范要求权限点由代码声明且默认拒绝。本模块只声明这三枚。后续模块新增编码前要再确认,不能沿用 M01 测试里的 `perm:platform:audit.read`。
## Assumptions
- 用户会在同一 Casdoor、组织 `organization_HX` 下新建 Watchman Application,并把 issuer、client、audience、密钥放进不入库的 `.env.local`。
- HXOPS 短时断言的真实签发不在本仓库完成。本模块先把接收和校验做对。
- 8 小时会话和 5 分钟角色缓存是技术默认。
- 处理者角色在 M02 没有独立业务按钮。
## Risks
- 应用未建好时,真实登录无法验收。
- HXOPS 尚未把 Watchman 配成入口时,无感进入只能用测试断言。
- 角色缓存在 5 分钟内不会反映 Casdoor 上的撤销。
- 对象级范围还没做。后面的模块如果只信角色名,会把“能进入系统”误当成“能看每一行”。
## Acceptance Criteria
1. 错误签名、错误 issuer、错误 audience、过期令牌都不能建立会话。
2. 密码登录在 Casdoor 替身成功时建立会话,并带上替身返回的角色;替身失败时不建立会话。
3. 无会话调用平台写接口得到 41000。查看者或处理者调用得到 42000,且 `permission_node` 为 `perm:data:emp:watchman.platform.write`。管理者可以写。
4. 没有任何三个角色的已登录用户不能进入壳页。
5. 两个合成对象 ID 在没有对象授权时都被拒绝。
6. HXOPS 断言缺少 Casdoor 身份、或用 HXOPS 本地主键冒充时,不建立会话。合法断言建立会话后,角色仍以 Casdoor 为准,不采用断言里的 HXOPS 权限。
7. 角色缓存过期且 Casdoor 不可用时,操作被拒绝,而不是继续放行。
8. 退出后再调用平台写接口得到 41000。
9. 日志和接口响应中没有密码和 client secret。
10. 健康检查仍可匿名访问。
11. 登录页能完成失败、成功进入、无权限、退出。本地身份模式有可见标识。
12. 未配置 Watchman Application 时,真实联调单独标为未完成,本地签名测试的通过不替代它。
## Deferred Questions
- 会话 8 小时、角色 5 分钟是否要改成别的数字。
- HXOPS 何时把 Watchman 加为真实入口。
- 后续模块如何把场景、报警的行级范围接到 `perm:data:emp:watchman.object.read`,而仍然不在 Watchman 做角色管理页。
## Source Notes
- 用户确认记录:2026-11-17,门禁 balanced;登录含 HXOPS 接收端;授权用 Casdoor 三档粗角色;新建 Watchman Application。
- `需求冻结文档_V1.1_交接稿.md` 第 15 节。
- `docs/tasks/INDEX.md` 的 M02。
- `docs/decisions.md` 的 D14、O10。O10 的 client 与 audience 仍要等新应用,角色落点已由本需求取代“存在本库”的选项。
- syops:`docs/features/auth/hxops-peer-service-sso.md` 第 14、15 节。只读对照,不复制其用户表和权限表。
- `.env.dev` 只用来确认 Casdoor 地址和组织。密钥不进入本仓库。JWKS 在规划时返回 HTTP 200。
@@ -0,0 +1,6 @@
# Critic — M02 S1(编码前)
- 模型:claude-opus-5-thinking-high
- 子代理:eab6ed43-cf99-4c43-8b71-b813c4101161
- 结论:PASS。无阻断项。
- 开工约束:只加 `pyjwt[crypto]>=2.10,<3`;锁文件只含该库及其传递依赖;不改根 `pyproject.toml`。只允许 RS256,拒绝 `alg: none` 和 HS256 混淆。过期用确定性时间。密钥只在测试内存中生成。做完停在 S2 前。
@@ -0,0 +1,6 @@
# Critic — M02 S2(编码前)
- 模型:claude-opus-5-thinking-high
- 子代理:03d34f4b-94e1-4072-8271-0e89c535dd0c
- 结论:PASS。无阻断项。
- 约束:不新增依赖,不改 `uv.lock`,运行时代码不 import `httpx`。不把 `CASDOOR_*` 放进启动必填项。登录失败 41000,未配置 503 且不建会话。测试注入替身,不读 `.env.local`,不访问网络。Cookie 为 HttpOnly,本地不强制 Secure。会话表走现有 RLS。本切片不保护平台写接口。做完停在 S3 前。
@@ -0,0 +1,4 @@
# Critic — M02 S3(编码前)
- 用户在 2026-11-17 明确要求跳过编程前 critic,并默认 PASS。
- 未另派审查模型做编码前审计。
@@ -0,0 +1,7 @@
# Review — M02 模块整体
- 审查:claude-opus-5-thinking-high,f3455ae9-1f7a-4a5b-9d2e-a030e8e79d32。结论:FAIL。
- 必改:HXOPS 断言在没有 `casdoor_sub` 时会回退到令牌自己的 `sub`,本地用户主键可以冒充 Casdoor 身份。
- 修复:`casdoor_sub` 必须存在,不再回退到 `sub`。`CASDOOR_ISSUER` 未配置时入口返回 503。补了缺少 `casdoor_sub` 的拒绝测试,并去掉对未导入 `pytest` 的调用。
- 复跑:`uv run pytest services/watchman/tests -q` → 54 passed。前端 unit 9 passed。这次没有重跑 Playwright,界面没有改。
- 未做第二次独立复审。HXOPS 真实跳转仍未联调。未标 DONE_LOCAL。
@@ -0,0 +1,7 @@
# Review — M02 S1
- 第一次审查(claude-sonnet-5-5-high,9a4bae12-f271-4fee-9944-d8cdd8fc5740):FAIL。缺 `# GUARD:`;alg none / HS256 测试没有锁住本服务自己的算法限制。
- 修复后复审(gemini-4-hydrogen-high,351c41be-cf86-450f-8490-4ca5cf507b42):PASS。
- 实现(gpt-5.6-terra-medium,6d369019-b392-4f7c-914f-8e83405e8124)。
- 主 Agent 复跑:`uv run pytest services/watchman/tests -q` → 30 passed。
- 未开始 S2。
@@ -0,0 +1,9 @@
# Review — M02 S2
- 编码前 critic(claude-opus-5-thinking-high,03d34f4b-94e1-4072-8271-0e89c535dd0c):PASS。
- 实现(gpt-5.6-terra-medium,a062b19b-2917-44f5-a294-5fb7c63c04b2)。
- 审查(claude-sonnet-5-5-high,bb80f999-7799-4fe8-9a49-225c95d3d25d):PASS_WITH_WARNINGS。无必改项。
- 主 Agent 复跑:`uv run pytest services/watchman/tests -q` → 35 passed。
- 迁移:`uv run alembic -c alembic.ini upgrade head`(在 `services/watchman`)已由实现方执行成功。
- 真实 Casdoor HTTP 按 critic 延后。默认登录端口固定返回 503。
- 未开始 S3。平台写接口仍匿名。
@@ -0,0 +1,8 @@
# Review — M02 地址令牌登录
- 审查:[M02 token login review](e5113ddc-6c2c-4e01-8e00-2381e1b5e072),claude-opus-5-thinking-high。结论:BLOCKED。
- 代码路径与已确认行为一致:前端只发现 `?token=` 并交给 `POST /auth/token-login`;后端只拿该令牌请求 Casdoor userinfo。没有本地白名单,也没有把令牌写进日志、会话或响应。`POST /auth/hxops-entry` 仍要求 `casdoor_sub`,这次 diff 没有改它。
- 审查当时重跑:pytest 58 passed,前端 unit 10 passed,`vue-tsc` 通过。Playwright 4 passed 是主 Agent 在同一工作区重跑的,审查没有再跑。
- 必改不是实现方式,而是口径:`authenticate_bearer` 只证明令牌在这套 Casdoor 上仍然有效,不核对是哪个应用签发的。同一实例里其他应用的访问令牌,只要用户有 Watchman 角色,就能换到 Watchman 会话。签名断言那条路径会核对 issuer 和 audience,这条不会。标 DONE_LOCAL 前要用户选择:只接受指定应用的令牌,或明确接受该 Casdoor 实例上任意仍然有效的访问令牌。见 O11。未替用户做这个决定。
- 审查看到的 `docs/progress.md` 和 `docs/runbook.md` 还是旧的 HXOPS 按钮口径。这两处已在审查之后改成地址令牌。任务记录当时仍停在 S2/S6,已补到当前收尾。
- 2026-11-17 用户确认 D20:接受该 Casdoor 实例上任意仍然有效的访问令牌。审查要求的决定已经落地,没有为此改校验代码。
+15
View File
@@ -0,0 +1,15 @@
{
"taskId": "2026-11-17/m02-auth",
"phase": "done",
"allowedToCode": false,
"gatePolicy": {
"recommended": "strict",
"selected": "balanced",
"effective": "balanced",
"finalApprovalRequired": true
},
"requirement": ".task/2026-11-17/m02-auth/requirement.md",
"implementationPlan": ".task/2026-11-17/m02-auth/implementation-plan.md",
"currentSlice": "done",
"nextGate": "none"
}
@@ -0,0 +1,54 @@
# Task Context Pack
## Task Goal
M03 S8:控制台覆盖 D23 — 保存前草稿测、启用、表单校验、详情熔断参数与状态展示。
## Current Slice Or Group
**S8**(已批准编码);`gateClass: standard`,`risk_score: 3`
## Requirement Source
`.task/2026-11-17/m03-datasource/requirement.md`(D23 UI)
## Implementation Source
`.task/2026-11-17/m03-datasource/implementation-plan.md` Slice 8
## Allowed Modification Scope
- `web/apps/console/src/datasources/**`
- `web/apps/console/locales/**`(四语言)
- `web/apps/console/e2e/**` 数据源相关
- 必要时极薄改动:`router.ts` / `AppShell.vue`(仅若导航文案需要)
## Forbidden Modification Scope
- 后端协议重写/迁移动 S6/S7 语义;口令进 localStorage;企微 UI;巡检 Cron 前端配置页(后端 env 即可)
## Key Entrypoints
- `DatasourceEdit.vue`、`DatasourceList.vue`、`client.ts`、`types.ts`、`payload.ts`
- API:`POST /datasources/test-draft`、`POST .../enable`、PATCH circuit_* 字段、公开 JSON 含 circuit_*
- UI 规则:D22 页脚居中;`docs/current/frontend-ui.md`
- 规范:`standards://frontend/frontend-stack?version=2.1.0`、`standards://frontend/element-plus?version=1.0.2`
## Validation Commands
```
cd web/apps/console && pnpm test:unit && pnpm test:e2e && pnpm typecheck
```
(或 filter `@watchman/console` 从 web/)
## Assumptions
- 草稿测:新建密码必填;编辑密码留空可带 id 用已存密文
- host 仅必填;port 1–65535;熔断默认 300/3/600,详情可编辑
- 停用显示启用;开闸提示 + circuit_open_until
- 列表行:停用可启用;开闸不可已保存测试
## Stop Conditions
- S8 评审后进入模块验收门禁(最终确认前不标 DONE_LOCAL)
@@ -0,0 +1,485 @@
# M03 数据源配置 Implementation Plan
## Requirement Source
`.task/2026-11-17/m03-datasource/requirement.md`
## Scope Summary
第一阶段实现数据库数据源的登记、编辑、停用/启用、草稿与已保存连接测试、每源熔断参数、Cron 周期巡检和空引用占位,覆盖 PostgreSQL、MySQL、SQL Server。凭证加密落在平台库。S1–S5 已完成;本增补为 S6–S8(D23)。
## Involved Modules Or Areas
- 后端服务包 `services/watchman`:模型、迁移、加密、连接器、API、权限。
- 控制台 `web/apps/console`:仅在原型确认后的切片。
- 开发 Compose:仅为 SQL Server 测试追加本机服务,不改平台库定义。
- 不改登录、Casdoor、查询、报警。
## Loaded Rules
- `AGENTS.md` 项目本地段:凭证不入库;主 Agent 不代替实现子 Agent 写业务代码(编码阶段)。
- `.cursor/rules/sy-standards.mdc`:API 信封、错误、权限点、安全红线。
- Marionettist `gatePolicy.selected=autonomous`。`risk_score >= 4`、高风险/边界敏感、以及用户指定的原型确认仍然停。
## Loaded Docs
- `docs/tasks/INDEX.md` M03、交接稿 A-01、`docs/decisions.md` D14/D19、`docs/progress.md`。
- 现有权限:`services/watchman/src/watchman/auth/access.py`。
- 现有模型与信封:`models/platform.py`、`core/errors.py`、`core/response.py`。
## Global Forbidden Scope
- 口令、连接串、加密密钥写入仓库、文档、测试快照、审计 payload、日志。
- `.env.local`、`.cursor/mcp.json`。
- M02 登录流程、已有三枚权限点的语义。
- 查询执行、非数据库来源的可用实现。
- 在原型确认前修改 `web/apps/console` 的数据源页面。
- 生产库、真实 MES、`git reset --hard`、自动 commit。
## Execution Strategy
- Complexity: complex
- Default Execution: sequential
- Parallel Execution: not-needed
- Fallback Execution: sequential
- Merge Owner: 主 Agent
- Conflict Resolution Rule: 后一切片不得改前一切片已冻结的表身份列和权限点字符串;冲突时停下来问用户。
## Slice Dependency Graph
| Slice | Depends On | Can Run In Parallel With | Fallback Order | Shared Files | Merge Owner | Conflict Risk |
| --- | --- | --- | --- | --- | --- | --- |
| S1 模型与密文 | 分析确认 | 无 | 1 | 迁移、模型包 | 主 Agent | medium |
| S2 三种驱动与连接测试 | S1 | 无 | 2 | 连接器包、开发 Compose | 主 Agent | medium |
| S3 API 与权限 | S1、S2 | 无 | 3 | 路由、access.py | 主 Agent | high |
| S4 HTML 原型 | S3 的字段口径;可在 S3 评审通过后立刻做 | 无 | 4 | 仅原型目录 | 主 Agent | low |
| S5 Vue 页面 | S4 用户确认 | 无 | 5 | web/apps/console | 主 Agent | medium |
| S6 启用/草稿测/熔断模型 | S5 | 无 | 6 | 迁移、services、routes | 主 Agent | high |
| S7 Cron 巡检 | S6 | 无 | 7 | worker/beat、settings | 主 Agent | high |
| S8 控制台增补 | S6、S7 | 无 | 8 | web/apps/console | 主 Agent | medium |
## Implementation Slices
### Slice 1: 数据源模型、迁移与凭证密文
#### Goal
平台库能按租户保存数据源元数据和口令密文。种类与引擎可扩展,非数据库种类没有可用行。
#### Allowed Modification Scope
- `services/watchman/src/watchman/models/`
- `services/watchman/migrations/`
- `services/watchman/src/watchman/core/` 中新增的密钥读取与加解密
- `services/watchman/tests/` 中对应该切片的测试
- `.env.example` 只增加占位名,不写真实密钥
#### Forbidden Scope
- API 路由、前端、连接真实源库、Compose 中的 SQL Server。
- 任何真实口令。
#### Execution
- Mode: sequential
- Depends On: 分析到编码的用户确认
- Can Run With: 无
- Must Not Run With: S2、S3
- Fallback Order: 1
- Shared Files: `models/__init__.py`、迁移链
- Merge Owner: 主 Agent
- Conflict Risk: medium
- Gate Class: high-risk
- Risk Score: 4
- Gate Reasons: schema-migration, credential-storage
- Validation Level: slice
- Recommended Agent Strategy: 实现子 Agent 编码;审查用不同模型系列
#### Steps
1. 新增数据源表:租户、名称唯一、种类、引擎、连接字段、密文、启用状态、最近测试类别与时间。启用 RLS,租户来自服务端。
2. 种类枚举保留扩展点;写入约束本阶段只允许 database 加三种引擎。
3. 加解密密钥只从环境变量读取。测试用临时密钥。
4. 单元测试:加密往返、日志/序列化不含明文、错误种类不能入库。
#### Validation
- `uv run pytest` 中本切片新增测试,以及现有平台 RLS 测试仍通过。
- `alembic upgrade head` 在开发库可重复执行到新版本。
#### Done Criteria
- 迁移可升级。密文列不接受明文 API 形态(此切片尚无 API)。
- 测试不包含真实口令。
#### Rollback Notes
- 降级迁移只删除本切片新增表。不改 `audit_events` / `run_records`。
### Slice 2: PostgreSQL、MySQL、SQL Server 连接测试
#### Goal
对已保存的数据库目标做有超时的连接测试,并把结果分成成功、认证失败、超时、不可达、服务端拒绝(`rejected`)。只有有正面证据时才标认证失败。
#### Allowed Modification Scope
- `services/watchman` 内新建的数据源连接器与测试
- `services/watchman` 依赖清单中的三种数据库驱动
- `deploy/compose.dev.yml` 仅增加绑定 127.0.0.1 的 SQL Server 测试服务
- 测试脚本创建隔离库表。口令只进 `.env.local`
#### Forbidden Scope
- 对目标执行 DDL/DML。连通性只用驱动 ping 或 `SELECT 1`。
- 生产库。把容器口令写进 Compose 仓库文件。
- 前端。
#### Execution
- Mode: sequential
- Depends On: S1 评审通过后的用户确认(high-risk 停点)
- Can Run With: 无
- Must Not Run With: S3、S5
- Fallback Order: 2
- Shared Files: 依赖锁文件、compose
- Merge Owner: 主 Agent
- Conflict Risk: medium
- Gate Class: high-risk
- Risk Score: 4
- Gate Reasons: external-connection, new-dependencies, test-infrastructure
- Validation Level: slice
- Recommended Agent Strategy: 实现子 Agent;SQL Server 安装可委派子 Agent,口令不回写到对话摘要以外的仓库文件
#### Steps
1. 定义连接器接口。三种引擎各一实现。其他种类返回“未实现”,且本阶段没有这类数据行。
2. 统一超时和错误分类。日志只记类别和数据源 ID。
3. 用 `.env.local` 连接本地 Postgres、本地 MySQL,并创建专用测试库。
4. Docker 安装 SQL Server,同样创建专用测试库,跑同一组分类测试。
#### Validation
- 三种引擎:正确口令成功;错误口令为认证失败;不可路由或拒绝连接为不可达;超时上限内返回超时类别。
- 断言响应与日志夹具不含口令。
#### Done Criteria
- 三类失败与成功在测试中分开。
- SQL Server 只监听本机。若 Docker 不可用,该引擎标 BLOCKED,不能写成通过。
#### Rollback Notes
- 移除驱动依赖和 Compose 服务。不删除用户原有的本地 Postgres/MySQL 实例。只删除本切片创建的测试库。
### Slice 3: 数据源 API、权限与空引用
#### Goal
提供列表、详情、创建、更新、停用、连接测试和空引用。权限点按需求表强制。
#### Allowed Modification Scope
- `services/watchman/src/watchman/api/`
- `services/watchman/src/watchman/auth/access.py` 只新增三枚数据源权限点及角色判断
- 数据源服务层与 API 测试
- 审计写入处:payload 不含凭证
#### Forbidden Scope
- 改 ENTER / PLATFORM_WRITE / OBJECT_READ 的含义。
- 前端页面。
- 接受调用方传入的租户 ID 或任意连接 URL。
#### Execution
- Mode: sequential
- Depends On: S2 评审通过后的用户确认
- Can Run With: 无
- Must Not Run With: S5
- Fallback Order: 3
- Shared Files: `access.py`、`api/app.py`
- Merge Owner: 主 Agent
- Conflict Risk: high
- Gate Class: boundary-sensitive
- Risk Score: 4
- Gate Reasons: permission-nodes, credential-api, tenant-boundary
- Validation Level: slice
- Recommended Agent Strategy: 实现子 Agent;审查用不同模型系列
#### Steps
1. 按需求实现 API。创建只接受 database 与三种引擎。
2. 接入三角色。无会话 41000,无权限 42000 且带权限点。
3. 详情不返回密文。更新时口令字段缺省表示不替换。
4. 引用返回空 `items`。
5. 停用后测试返回冲突或参数错误中的稳定类别,记录仍可 GET。
#### Validation
- API 测试覆盖权限矩阵、脱敏、停用、非法种类、引用空列表。
- 现有 auth/platform 测试仍通过。
#### Done Criteria
- 验收标准 1、2、4、5、6 的后端部分有测试证据。
- 三枚新权限点字符串与需求表一致。
#### Rollback Notes
- 路由可从应用移除。权限函数删除不得影响原有三枚节点。
### Slice 4: HTML 原型
#### Goal
给出一份可在浏览器打开的静态原型,供用户确认信息架构和状态,然后再写 Vue。
#### Allowed Modification Scope
- `.task/2026-11-17/m03-datasource/prototype/` 下的 HTML/CSS/少量静态脚本
- 原型说明一份,放在同一目录
#### Forbidden Scope
- `web/`、后端、真实口令、真实 API 地址。
#### Execution
- Mode: sequential
- Depends On: S3 完成(字段与状态已稳定)
- Can Run With: 无
- Must Not Run With: S5
- Fallback Order: 4
- Shared Files: 无
- Merge Owner: 主 Agent
- Conflict Risk: low
- Gate Class: standard
- Risk Score: 2
- Gate Reasons: user-required-prototype-approval
- Validation Level: slice
- Recommended Agent Strategy: 委派 subagent 出原型;主 Agent 只检查是否越界
#### Steps
1. 委派 subagent 按需求的用户流程做单页或少量静态页。
2. 覆盖空列表、表单、测试中、成功、认证失败、超时、停用、空引用、查看者/处理者/管理者的按钮差异。
3. 主 Agent 把打开方式交给用户,停止等待确认。
#### Validation
- 本地用浏览器打开原型,核对上述状态都在页面上。不要求接 API。
#### Done Criteria
- 原型文件只在任务目录。
- 明确记录“未确认,禁止开始 S5”。
#### Rollback Notes
- 删除原型目录不影响运行中的服务。
### Slice 5: 控制台数据源页面
#### Goal
在用户确认原型后,把同等流程做到控制台,并接上 S3 的 API。
#### Allowed Modification Scope
- `web/apps/console/src/` 数据源功能、路由入口、i18n
- 对应 vitest 与 Playwright
#### Forbidden Scope
- 在用户确认原型之前开始本切片。
- 后端协议重写。页面不得保存口令到 localStorage。
- 非数据库来源的可用表单。
#### Execution
- Mode: sequential
- Depends On: 用户对 S4 原型的明确确认
- Can Run With: 无
- Must Not Run With: 无
- Fallback Order: 5
- Shared Files: `App.vue` 或现有壳层导航
- Merge Owner: 主 Agent
- Conflict Risk: medium
- Gate Class: standard
- Risk Score: 3
- Gate Reasons: ui-after-prototype
- Validation Level: final
- Recommended Agent Strategy: 实现子 Agent;浏览器验证用 Playwright
#### Steps
1. 按确认后的原型实现列表、表单、测试状态、停用和空引用。
2. 按钮按角色隐藏,同时依赖后端 42000。
3. Playwright 覆盖主路径和“口令不被回填”。
#### Validation
- `pnpm` 下现有前端测试加新用例。
- Playwright 跑通数据源主路径。浏览器里实际点选一遍。
#### Done Criteria
- 验收标准 7 的页面部分有断言和截图路径(截图默认 gitignore)。
- 与原型的差异已记在任务卡,未确认的差异不算完成。
#### Rollback Notes
- 前端改动可单独回退,不影响已发布的 API。
### Slice 6: 启用、草稿测试、熔断账本与 usable
#### Goal
后端支持启用、草稿测试、每源熔断参数与运行态、统一失败记账与 `assert_usable`;已保存测试在停用或开闸时拒绝。
#### Allowed Modification Scope
- `services/watchman` 模型、迁移、datasources 服务/probe、API 路由、settings 读取(探测超时/重试)
- 对应 pytest
#### Forbidden Scope
- 企微发送;场景页;手写 Cron 解析器;自动改 `enabled`;前端大改(留给 S8)
#### Execution
- Mode: sequential
- Depends On: 用户确认本增补进入编码
- Gate Class: high-risk
- Risk Score: 4
- Gate Reasons: schema-migration, circuit-semantics
- Validation Level: slice
#### Steps
1. 迁移:熔断三参数、circuit_state、circuit_opened_at、窗口失败计数/窗口起点(或等价可测结构)。
2. `enable_datasource`;disable/enable 与熔断解耦。
3. `test-draft`:表单探测,不写 last_test,不记账。
4. 已保存测试:停用或开闸拒绝;否则探测并记账/成功清计数(未开闸时)。
5. `assert_usable(enabled && closed)`;导出供后续模块。
6. 更新校验:host 必填即可;熔断参数上下限。
#### Validation
- pytest:启用往返;草稿不落库;开闸拒绝测试;冷却后熄闸;参数持久化。
#### Done Criteria
- 验收 4、6、7、8 的后端部分有测试。
#### Rollback Notes
- 回滚迁移与服务改动;不碰前端。
### Slice 7: Cron 周期巡检
#### Goal
配置开关 + Cron 驱动的批量连通性巡检;失败写 last_test 与审计,不发企微。
#### Allowed Modification Scope
- Celery 任务/beat 调度注册、datasources 巡检服务、`.env.example` 占位、对应测试
- 复用成熟 Cron 库(如 croniter)与现有 Celery Beat,薄适配
#### Forbidden Scope
- 第二套调度引擎;企微;改熔断语义(只调用 S6 记账接口)
#### Execution
- Mode: sequential
- Depends On: S6
- Gate Class: high-risk
- Risk Score: 4
- Gate Reasons: scheduling, production-config
- Validation Level: slice
#### Steps
1. 配置项:`HEALTHCHECK_ENABLED`、`HEALTHCHECK_CRON`(及探测超时/重试若未在 S6 完成)。
2. 任务:枚举启用且未开闸源 → 探测 → 记账/更新 last_test → 失败审计。
3. enabled=false 或 Cron 无效则 no-op。
4. 单测用固定时钟/mock probe,不打真实外网。
#### Validation
- pytest:开关关闭不跑;开闸源跳过;失败写审计无密钥。
#### Done Criteria
- 验收 9 后端有证据。
#### Rollback Notes
- 去掉任务注册与配置项即可。
### Slice 8: 控制台增补(启用/草稿测/校验/熔断配置)
#### Goal
控制台覆盖 D23 交互:保存前测试、启用、表单校验、详情熔断参数与状态展示。
#### Allowed Modification Scope
- `web/apps/console` 数据源页面、client、i18n、vitest、Playwright
#### Forbidden Scope
- 后端协议重写;口令进 localStorage;企微 UI
#### Execution
- Mode: sequential
- Depends On: S6(API);S7 可不阻塞 UI,但巡检无前端配置页(仅后端配置)
- Gate Class: standard
- Risk Score: 3
- Validation Level: final
#### Steps
1. 新建/编辑:草稿测试按钮;保存前可用。
2. 停用行/详情:启用按钮。
3. 详情:熔断三参数表单项;开闸提示与恢复时间。
4. Element Plus 表单规则(host 仅必填)。
5. Playwright/单测覆盖主路径。
#### Validation
- 前端单测 + Playwright;与 S6 API 联调。
#### Done Criteria
- 验收 11;模块可进入整体 review。
#### Rollback Notes
- 前端可单独回退。
## Parallel Slice Groups
无。S6→S7→S8 顺序执行。
## Final Validation
- 后端:`uv run pytest` 全量;迁移到新 head。
- 前端:单测 + Playwright。
- 模块级独立 review 后,用户确认再 DONE_LOCAL。
## Documentation Update Requirement
- D21、D22、D23 已记入 `docs/decisions.md`。
- 熔断/usable 边界若稳定,实现后更新 `docs/current` 与知识地图。
- `docs/progress.md` 每片门禁更新。
## Risks
- S6、S7 为 risk_score 4,autonomous 下每片评审后仍停。
- S8 为 standard/3;S6 通过后可按 autonomous 继续,但仍保留最终验收。
- 熄闸后可能立刻再开闸——按需求接受。
+52
View File
@@ -0,0 +1,52 @@
# Task Intake Result
## Task Type
feature。Tier L(凭证保护、外部连接测试、可扩展数据源边界;跨后端 API/前端/迁移)。
## Current Understanding
- 用户要求推进 M03(数据源配置)。当前 `docs/progress.md`:M02 DONE_LOCAL,无进行中模块。
- 用户本轮范围收窄:第一阶段先做**数据库接入**,同时为其他数据来源(API/消息等)留扩展位;不把非 DB 来源做成首版可运行能力。
- 前端正式开发前,先委托 subagent 产出**可确认的原型 HTML**;用户确认后再写 Vue 页面。
- 冻结文档 A-01:新建/编辑/连接测试/停用/引用查看;凭证后端受控、界面不回显;首版只读数据库采集;源库类型不等于平台库;接口/MQ/视频等暂不强制。
- INDEX M03 完整边界:数据源 API+列表/编辑+连接测试、凭证保护及引用提示。本轮将按用户“分阶段”拆:先 DB 接入骨架与 API,UI 在原型确认后推进。
- O01–O07 与 M03 无硬阻塞;O08 跨系列委派仍开放。
## Gate Policy
- config/default: balanced
- allowTaskOverride: true
- recommended: balanced
- selected: autonomous
- reason or override reason: 用户在 2026-11-17 明确选择 autonomous。推荐 balanced 仅作建议(凭证/外连/迁移偏敏感),不覆盖该选择。
- effective: autonomous
- finalApprovalRequired: true
说明:autonomous 不取消分析→编码门禁、最终验收、`gateClass: high-risk|boundary-sensitive`、critic、显式停点、危险命令,以及 `risk_score >= 4` 的停顿。前端原型 HTML 确认视为编码前/UI 切片前的显式停点。
## Blocking Questions
已由用户在 2026-11-17 确认,并写入需求与 D21:
1. 第一阶段含后端,以及原型确认后的列表/编辑/测试 UI。
2. 现在支持 PostgreSQL、MySQL、SQL Server。SQL Server 用 Docker 测试。允许创建测试库表。口令不写入仓库。
3. 平台库加密字段,API 不回显,日志脱敏。
4. 引用用空列表/占位契约。
## Non-blocking Assumptions
- 源类型用可扩展枚举/策略接口;非 DB 类型 API 可返回“暂不支持”或只存元数据但不提供连接测试实现。
- 连接测试对真实外网/生产库默认 Mock/合成;真实外连另获准。
- 原型 HTML 为静态交互稿,不接真实 API,不作为后端事实。
- 权限点经 sy-standards 检索后落库,禁止编造编码;角色沿用 D19(admin/operator/viewer)。
- 行级数据范围若本模块需要,单独再确认;不默认复制平台 RLS 到外部源库。
- 分析完成并用户确认前不编码;不自动 commit/push。
## Recommended Next Step
用户答复阻塞问题后:写 `requirement.md` → module/workflow 轻量检查 → `implementation-plan.md`(含原型 HTML 独立切片/门禁)→ `context-pack.md`。之后停在分析→编码门禁。
## Suggested Prompt For Next Step
确认阶段边界、首版驱动集合、凭证存放与引用提示深度后,冻结 M03 需求并给出实现切片(DB 优先,前端前先做 HTML 原型)。
@@ -0,0 +1,37 @@
# M03 数据源 · 静态 HTML 原型(S4)
**状态:此原型尚未获批用于 Vue 实现。** 未经维护者确认信息架构与各状态前,不得据此编写 Vue 页面。
## 如何打开
直接用浏览器打开本目录的 `index.html`(双击即可)。单文件,无构建、无 CDN、无网络请求。
## 用途
让维护者确认「数据源」页面的信息架构、角色差异和各状态,之后再用 Vue 3 + Element Plus 实现。视觉按 Element Plus 能还原的克制后台风格设计,采用项目 token(主色 `#5e6ad2`、圆角 8px、基础字号 13.5px)。
## 控件说明
顶部黄色虚线条「原型切换」不属于未来产品,只用于评审。
- **角色**:管理者 / 处理者 / 查看者。
- 只有管理者能进入数据源界面,可以使用新建、保存、停用、测试。
- 处理者和查看者进入后只看到「无法进入数据源」,看不到列表和表单。
- **画面**(仅管理者):
- 空列表:说明还没有数据源,并提供「新建」。
- 列表:名称、引擎、主机、端口、库名、用户名、状态、最近测试、操作;不显示密码或密文。
- 新建:名称、用途说明、引擎(仅 PostgreSQL / MySQL / SQL Server)、主机、端口、库名、用户名、密码。没有「只读意图」。密码框可在输入后点击「查看」。
- 编辑:密码框用固定长度星号占位,不是已保存的密码;聚焦后清空,留空保存则不修改。含连接测试区与引用区。
- **开发注意**:
- 密码框用 Element Plus 的 `el-input`(`type="password"`、`show-password`),不要照着原型自绘。
- 列表页的「新建」放在表格上方。详情页的「返回列表」、保存、测试、停用放在页脚并居中;页脚不在纵向滚动区域内。表格行内操作留在该行。约定见 `docs/current/frontend-ui.md`。
- 测试中 / 测试成功 / 认证失败 / 超时 / 不可达 / 服务端拒绝:结果面板不显示密码。「服务端拒绝」示例为库不存在,不是密码错误。
- 已停用:该行保留在列表,状态「已停用」,「测试」置灰并说明「停用后不能测试」。
- 空引用:「引用」区显示「尚无引用」及空列表,不虚构场景或查询。
- **点「测试」后模拟结果**:选择点击「测试」后(先显示测试中约 1.4 秒)进入哪种结果。
- 列表和编辑页中的「测试」「保存」「停用」只切换本页状态,页面顶部有「原型本地模拟」提示。
## 约束
- 所有数据均为虚构,主机使用保留后缀 `.example.test`;不含真实口令、`.env.local` 中的主机或任何 API 调用。
- 只为信息架构评审;停用后的「启用」、列表分页/筛选、引用的具体内容等未在需求中确认,原型未做。
@@ -0,0 +1,457 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Watchman M03 数据源 · 静态原型(S4)</title>
<style>
:root {
--primary: #5e6ad2;
--primary-soft: #eef0fb;
--text: #1f2328;
--text-2: #59636e;
--muted: #8b949e;
--surface: #ffffff;
--soft: #f6f8fa;
--border: #d0d7de;
--border-2: #eaeef2;
--ok: #1a7f37;
--ok-bg: #e9f6ec;
--warn: #9a6700;
--warn-bg: #fff8e1;
--err: #cf222e;
--err-bg: #fdecee;
--radius: 8px;
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
}
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body { font-family: var(--font); font-size: 13.5px; color: var(--text); background: var(--soft); line-height: 1.55; }
button, input, select, textarea { font: inherit; color: inherit; }
/* ---- prototype toolbar (not part of product) ---- */
.proto {
background: #fffbe6; border-bottom: 1px dashed #d4b106; padding: 8px 16px;
display: flex; flex-wrap: wrap; gap: 8px 20px; align-items: center; font-size: 12.5px;
}
.proto-title { font-weight: 600; color: #7a5b00; }
.proto-group { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.proto-group > .lbl { color: var(--text-2); margin-right: 2px; }
.proto-btn {
border: 1px solid var(--border); background: var(--surface); border-radius: 6px;
padding: 2px 9px; cursor: pointer; font-size: 12.5px;
}
.proto-btn:hover { border-color: var(--primary); color: var(--primary); }
.proto-btn.on { background: var(--primary); border-color: var(--primary); color: #fff; }
.proto-note { flex-basis: 100%; color: #7a5b00; }
.proto select { border: 1px solid var(--border); border-radius: 6px; padding: 2px 6px; background: #fff; font-size: 12.5px; }
/* ---- shell ---- */
.shell { display: flex; height: calc(100vh - var(--proto-h, 96px)); min-height: 520px; }
.side { width: 196px; flex: none; background: var(--surface); border-right: 1px solid var(--border-2); padding: 14px 10px; }
.brand { font-weight: 700; font-size: 16px; padding: 4px 10px 14px; letter-spacing: .3px; }
.nav-item { padding: 7px 10px; border-radius: 6px; color: var(--text-2); }
.nav-item.cur { background: var(--primary-soft); color: var(--primary); font-weight: 600; }
.nav-item.off { color: var(--muted); }
.main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
.top { height: 48px; flex: none; background: var(--surface); border-bottom: 1px solid var(--border-2);
display: flex; align-items: center; justify-content: space-between; padding: 0 20px; }
.pagefoot { flex: none; background: var(--surface); border-top: 1px solid var(--border-2);
display: flex; align-items: center; justify-content: center; gap: 8px; padding: 12px 20px; }
.list-actions { display: flex; justify-content: flex-end; margin-bottom: 12px; }
.crumb { color: var(--text-2); }
.crumb b { color: var(--text); font-weight: 600; }
.who { color: var(--text-2); display: flex; align-items: center; gap: 8px; }
.tag { display: inline-block; padding: 0 8px; border-radius: 10px; font-size: 12px; line-height: 20px; background: var(--primary-soft); color: var(--primary); }
.content { flex: 1; overflow: auto; padding: 20px; }
.local-banner { background: var(--primary-soft); border: 1px solid #d5d9f5; color: #3f49a8; border-radius: var(--radius);
padding: 7px 12px; margin-bottom: 14px; font-size: 12.5px; }
.card { background: var(--surface); border: 1px solid var(--border-2); border-radius: var(--radius); padding: 16px 18px; margin-bottom: 16px; }
.card h3 { margin: 0 0 12px; font-size: 14.5px; }
.btn { border: 1px solid var(--border); background: var(--surface); border-radius: 6px; padding: 5px 14px; cursor: pointer; }
.btn:hover:not(:disabled) { border-color: var(--primary); color: var(--primary); }
.btn.primary { background: var(--primary); border-color: var(--primary); color: #fff; }
.btn.primary:hover:not(:disabled) { background: #4f5bc4; color: #fff; }
.btn.danger { color: var(--err); }
.btn.danger:hover:not(:disabled) { border-color: var(--err); color: var(--err); }
.btn.sm { padding: 1px 8px; font-size: 12.5px; }
.btn:disabled { color: var(--muted); background: var(--soft); cursor: not-allowed; }
.btn.link { border: 0; background: none; color: var(--primary); padding: 1px 6px; }
.btn.link.danger { color: var(--err); }
.btn.link:disabled { color: var(--muted); background: none; }
table { width: 100%; border-collapse: collapse; }
th { text-align: left; font-weight: 600; color: var(--text-2); background: var(--soft); padding: 9px 12px; border-bottom: 1px solid var(--border-2); white-space: nowrap; }
td { padding: 10px 12px; border-bottom: 1px solid var(--border-2); vertical-align: middle; }
tr.hl td { background: #fafbff; }
tr.off td { color: var(--muted); }
.mono { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12.5px; }
.table-wrap { overflow-x: auto; border: 1px solid var(--border-2); border-radius: var(--radius); background: var(--surface); }
.table-wrap table th:first-child, .table-wrap table td:first-child { padding-left: 16px; }
.ops { white-space: nowrap; }
.ops-why { display: block; color: var(--muted); font-size: 12px; padding: 0 6px; }
.status { display: inline-flex; align-items: center; gap: 6px; }
.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ok); }
.status.off .dot { background: var(--muted); }
.last-ok { color: var(--ok); } .last-bad { color: var(--err); } .last-none { color: var(--muted); }
.empty { text-align: center; padding: 56px 20px; background: var(--surface); border: 1px dashed var(--border); border-radius: var(--radius); }
.empty h3 { margin: 0 0 6px; font-size: 15px; }
.empty p { margin: 0 0 14px; color: var(--text-2); }
.empty.sm { padding: 22px 20px; }
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 24px; max-width: 760px; }
.field { display: flex; flex-direction: column; gap: 4px; }
.field.full { grid-column: 1 / -1; }
.field label { color: var(--text-2); font-size: 12.5px; }
.field input[type=text], .field input[type=password], .field input[type=number], .field select, .field textarea {
border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; background: var(--surface); width: 100%; outline: none; }
.field input:focus, .field select:focus, .field textarea:focus { border-color: var(--primary); box-shadow: 0 0 0 2px var(--primary-soft); }
.field input:disabled, .field select:disabled, .field textarea:disabled { background: var(--soft); color: var(--text-2); cursor: not-allowed; }
.pwd { display: flex; gap: 8px; align-items: center; }
.pwd input { flex: 1; }
.hint { color: var(--muted); font-size: 12px; }
.drop-later { color: #7a5b00; }
.form-actions { margin-top: 18px; display: flex; gap: 10px; align-items: center; }
.check { display: flex; align-items: center; gap: 8px; }
.note { border-radius: var(--radius); padding: 8px 12px; font-size: 12.5px; background: var(--soft); border: 1px solid var(--border-2); color: var(--text-2); }
.note.warn { background: var(--warn-bg); border-color: #f1dc9a; color: var(--warn); }
.result { border-radius: var(--radius); padding: 12px 14px; border: 1px solid; margin-top: 12px; }
.result .r-title { font-weight: 600; margin-bottom: 2px; }
.result .r-body { font-size: 13px; }
.result .r-meta { margin-top: 6px; font-size: 12px; opacity: .85; }
.result.ok { background: var(--ok-bg); border-color: #b7e0c2; color: #145c2a; }
.result.bad { background: var(--err-bg); border-color: #f4b8be; color: #8e1a23; }
.result.pend { background: var(--primary-soft); border-color: #d5d9f5; color: #3f49a8; }
.result.warn { background: var(--warn-bg); border-color: #f1dc9a; color: var(--warn); }
.spin { display: inline-block; width: 12px; height: 12px; border: 2px solid #c3c8f0; border-top-color: var(--primary); border-radius: 50%; animation: sp .8s linear infinite; vertical-align: -2px; margin-right: 6px; }
@keyframes sp { to { transform: rotate(360deg); } }
.refs.focus { outline: 2px solid var(--primary-soft); border-color: var(--primary); }
.kv { display: grid; grid-template-columns: 96px 1fr; gap: 4px 12px; font-size: 13px; }
.kv dt { color: var(--muted); } .kv dd { margin: 0; }
</style>
</head>
<body>
<div class="proto" id="proto">
<span class="proto-title">原型切换</span>
<div class="proto-group"><span class="lbl">角色</span><span id="p-roles"></span></div>
<div class="proto-group"><span class="lbl">画面</span><span id="p-screens"></span></div>
<div class="proto-group"><span class="lbl">点「测试」后模拟结果</span><select id="p-sim"></select></div>
<div class="proto-note">此条仅用于评审,不属于未来产品。所有数据均为虚构,页面不发送任何网络请求,不含真实密码或地址。正式版本进行删除</div>
</div>
<div class="shell" id="shell">
<aside class="side">
<div class="brand">Watchman</div>
<div class="nav-item cur" id="nav-ds">数据源</div>
</aside>
<div class="main">
<header class="top">
<div class="crumb" id="crumb">Watchman / <b>数据源</b></div>
<div class="who">当前角色 <span class="tag" id="who-role"></span></div>
</header>
<main class="content" id="view"></main>
<div class="pagefoot" id="pagefoot" hidden></div>
</div>
</div>
<script>
(function () {
'use strict';
var ROLES = { admin: '管理者', handler: '处理者', viewer: '查看者' };
var SCREENS = [
['empty', '空列表'], ['list', '列表'], ['create', '新建'], ['edit', '编辑'],
['testing', '测试中'], ['ok', '测试成功'], ['auth', '认证失败'], ['timeout', '超时'],
['unreachable', '不可达'], ['rejected', '服务端拒绝'], ['disabled', '已停用'], ['noref', '空引用']
];
var SIM = [['ok', '成功'], ['auth', '认证失败'], ['timeout', '超时'], ['unreachable', '不可达'], ['rejected', '服务端拒绝']];
var PORT = { PostgreSQL: 5432, MySQL: 3306, 'SQL Server': 1433 };
// All sample data below is fictional. Hosts use the reserved ".example.test" suffix.
var ROWS = [
{ id: 1, name: '产线工艺库', engine: 'PostgreSQL', host: 'db.example.test', port: 5432, db: 'process_demo', user: 'readonly_demo', on: true, last: ['ok', '2026-11-17 09:12 成功'], desc: '示例:工艺参数只读库(虚构)' },
{ id: 2, name: '设备台账库', engine: 'MySQL', host: 'mysql.example.test', port: 3306, db: 'asset_demo', user: 'readonly_demo', on: true, last: ['bad', '2026-11-16 17:40 认证失败'], desc: '示例:设备台账(虚构)' },
{ id: 3, name: '质检结果库', engine: 'SQL Server', host: 'mssql.example.test', port: 1433, db: 'quality_demo', user: 'readonly_demo', on: true, last: ['none', '尚未测试'], desc: '示例:质检结果(虚构)' },
{ id: 4, name: '历史归档库', engine: 'PostgreSQL', host: 'archive.example.test', port: 5432, db: 'archive_demo', user: 'readonly_demo', on: false, last: ['ok', '2026-11-10 14:03 成功'], desc: '示例:已停用的归档库(虚构)' }
];
var state = { role: 'admin', screen: 'list', sim: 'ok', timer: null, testTarget: 1, from: 'list' };
function $(id) { return document.getElementById(id); }
function isAdmin() { return state.role === 'admin'; }
function row(id) { for (var i = 0; i < ROWS.length; i++) if (ROWS[i].id === id) return ROWS[i]; return ROWS[0]; }
function later(text) { return text + ' <span class="drop-later">正式版本进行删除</span>'; }
/* ---------- prototype toolbar ---------- */
function renderProto() {
var r = '', s = '', k;
for (k in ROLES) r += '<button class="proto-btn' + (state.role === k ? ' on' : '') + '" data-role="' + k + '">' + ROLES[k] + '</button> ';
$('p-roles').innerHTML = r;
SCREENS.forEach(function (x) {
s += '<button class="proto-btn' + (state.screen === x[0] ? ' on' : '') + '" data-screen="' + x[0] + '">' + x[1] + '</button> ';
});
$('p-screens').innerHTML = s;
var o = '';
SIM.forEach(function (x) { o += '<option value="' + x[0] + '"' + (state.sim === x[0] ? ' selected' : '') + '>' + x[1] + '</option>'; });
$('p-sim').innerHTML = o;
$('who-role').textContent = ROLES[state.role];
$('nav-ds').className = 'nav-item' + (isAdmin() ? ' cur' : ' off');
}
/* ---------- pieces ---------- */
function banner() {
return '<div class="local-banner">' + later('原型本地模拟:此页面不会向任何服务发送请求,「测试」「保存」「停用」只会切换本页的演示状态。') + '</div>';
}
function statusCell(r) {
return r.on
? '<span class="status"><span class="dot"></span>启用</span>'
: '<span class="status off"><span class="dot"></span>已停用</span>';
}
function lastCell(r) {
var cls = r.last[0] === 'ok' ? 'last-ok' : r.last[0] === 'bad' ? 'last-bad' : 'last-none';
return '<span class="' + cls + '">' + r.last[1] + '</span>';
}
function opsCell(r) {
var h = '<button class="btn link" data-go="edit" data-id="' + r.id + '">编辑</button>';
if (r.on) h += '<button class="btn link" data-test="' + r.id + '">测试</button>';
else h += '<button class="btn link" disabled title="停用后不能测试">测试</button><span class="ops-why">停用后不能测试</span>';
if (r.on) h += '<button class="btn link danger" data-disable="' + r.id + '">停用</button>';
return h;
}
function listTable(rows, hlId) {
var h = '<div class="table-wrap"><table><thead><tr>' +
'<th>名称</th><th>引擎</th><th>主机</th><th>端口</th><th>库名</th><th>用户名</th><th>状态</th><th>最近测试</th><th>操作</th>' +
'</tr></thead><tbody>';
rows.forEach(function (r) {
h += '<tr class="' + (r.on ? '' : 'off ') + (r.id === hlId ? 'hl' : '') + '">' +
'<td>' + r.name + '</td><td>' + r.engine + '</td><td class="mono">' + r.host + '</td><td class="mono">' + r.port +
'</td><td class="mono">' + r.db + '</td><td class="mono">' + r.user + '</td><td>' + statusCell(r) + '</td><td>' + lastCell(r) +
'</td><td class="ops">' + opsCell(r) + '</td></tr>';
});
return h + '</tbody></table></div>';
}
function setCrumb(leaf) {
var html = 'Watchman / <b>数据源</b>';
if (leaf) html += ' / <b>' + leaf + '</b>';
$('crumb').innerHTML = html;
}
function setFoot(actions) {
var foot = $('pagefoot');
foot.hidden = !actions;
foot.innerHTML = actions || '';
}
/* ---------- screens ---------- */
function vEmpty() {
setCrumb('');
setFoot('');
return banner() + '<div class="list-actions"><button class="btn primary" data-go="create">新建</button></div>' +
'<div class="empty"><h3>还没有数据源</h3><p>管理者可以新建第一个数据源。</p></div>';
}
function vList() {
setCrumb('');
setFoot('');
return banner() + '<div class="list-actions"><button class="btn primary" data-go="create">新建</button></div>' + listTable(ROWS.slice(0, 3), 0);
}
function vDisabled() {
setCrumb('');
setFoot('');
return banner() + '<div class="list-actions"><button class="btn primary" data-go="create">新建</button></div>' + listTable(ROWS, 4) +
'<p class="hint" style="margin-top:10px">' + later('已停用的行保持可见,状态为「已停用」,「测试」按钮置灰,原因:停用后不能测试。') + '</p>';
}
function passwordField(mode) {
var edit = mode === 'edit';
return '<div class="field"><label>密码</label><div class="pwd">' +
'<input type="password" id="f-password" autocomplete="new-password" data-mode="' + mode + '"' +
(edit ? ' data-mask="1" value="••••••••"' : ' value="" placeholder="请输入密码"') + '>' +
'<button type="button" class="btn sm" id="f-reveal" data-reveal>查看</button></div>' +
'<span class="hint">' + later(edit
? '星号是固定占位,不是已保存的密码。聚焦后自动清空;留空保存则不修改。开发时改用 Element Plus 的 el-input,type=password 且 show-password,不要自绘这个框。'
: '开发时改用 Element Plus 的 el-input,type=password 且 show-password,不要自绘这个框。') + '</span></div>';
}
function fieldsHtml(r, mode) {
var v = r || { name: '', desc: '', engine: 'PostgreSQL', host: '', port: 5432, db: '', user: '' };
var eng = '';
['PostgreSQL', 'MySQL', 'SQL Server'].forEach(function (e) { eng += '<option' + (v.engine === e ? ' selected' : '') + '>' + e + '</option>'; });
return '<div class="form-grid">' +
'<div class="field"><label>名称</label><input type="text" value="' + v.name + '"></div>' +
'<div class="field"><label>引擎</label><select id="f-engine">' + eng + '</select>' +
'<span class="hint">' + later('非数据库来源暂不可用。') + '</span></div>' +
'<div class="field full"><label>用途说明</label><textarea rows="2">' + (v.desc || '') + '</textarea></div>' +
'<div class="field"><label>主机</label><input type="text" placeholder="例如 db.example.test" value="' + v.host + '"></div>' +
'<div class="field"><label>端口</label><input type="number" id="f-port" value="' + v.port + '"></div>' +
'<div class="field"><label>库名</label><input type="text" value="' + v.db + '"></div>' +
'<div class="field"><label>用户名</label><input type="text" value="' + v.user + '"></div>' +
passwordField(mode) +
'</div>';
}
function pageActions(r, mode) {
var h = '';
if (isAdmin()) h += '<button class="btn primary" data-save>保存</button>';
if (mode === 'edit') {
if (r.on) h += '<button class="btn" data-test="' + r.id + '">测试</button>';
else h += '<button class="btn" disabled title="停用后不能测试">测试</button>';
if (r.on) h += '<button class="btn danger" data-disable="' + r.id + '">停用</button>';
}
h += '<button class="btn" data-go="list">返回列表</button>';
return h;
}
function vCreate() {
setCrumb('新建');
setFoot(pageActions(null, 'create'));
return banner() + '<div class="card"><h3>连接信息</h3>' + fieldsHtml(null, 'create') + '</div>';
}
var RESULTS = {
ok: ['ok', '测试成功', '已连接并完成只读探测。', '耗时示意 0.4 秒(虚构)'],
auth: ['bad', '认证失败', '服务端不接受该用户名或密码。请核对用户名,并在密码框重新输入后保存。', '这是认证问题,不代表主机或库名有误'],
timeout: ['warn', '超时', '在允许的时间内没有收到服务端响应。可稍后重试,或检查网络与防火墙。', '超时不等于密码错误'],
unreachable: ['bad', '不可达', '无法与目标主机和端口建立连接。请核对主机、端口,以及网络是否放行。', '尚未到达认证步骤'],
rejected: ['bad', '服务端拒绝', '服务端已响应但拒绝了请求,例如库名不存在。这不是密码错误。', '请核对库名或该账号的访问授权']
};
function resultPanel(kind, r) {
if (kind === 'testing') {
return '<div class="result pend"><div class="r-title"><span class="spin"></span>测试中</div>' +
'<div class="r-body">' + later('正在测试「' + r.name + '」(本地模拟,未发出任何请求)…') + '</div></div>';
}
var x = RESULTS[kind];
if (!x) return '';
var cls = x[0];
return '<div class="result ' + cls + '"><div class="r-title">' + x[1] + '</div><div class="r-body">' + x[2] + '</div>' +
'<div class="r-meta">' + later(x[3] + ' · 目标 ' + r.host + ':' + r.port + ' / ' + r.db + ' · 结果面板不显示密码') + '</div></div>';
}
function refsSection(focus) {
return '<div class="card refs' + (focus ? ' focus' : '') + '"><h3>引用</h3>' +
'<div class="empty sm"><p style="margin:0">尚无引用</p></div>' +
'<p class="hint" style="margin:8px 0 0">' + later('此处将列出使用该数据源的对象;当前列表为空。') + '</p></div>';
}
function vEdit(kind) {
var r = row(state.testTarget);
setCrumb('详情');
setFoot(pageActions(r, 'edit'));
var h = banner();
if (!r.on) h += '<div class="note warn" style="margin-bottom:14px">该数据源已停用。停用后不能测试。</div>';
h += '<div class="card"><h3>连接信息</h3>' + fieldsHtml(r, 'edit') + '</div>';
h += '<div class="card"><h3>连接测试</h3>';
if (kind === 'testing' || RESULTS[kind]) h += resultPanel(kind, r);
else h += '<div class="note">' + later('尚未测试。点击上方「测试」可演示测试中与结果(本地模拟)。') + '</div>';
h += '</div>';
h += refsSection(kind === 'noref');
return h;
}
function vDenied() {
setCrumb('');
setFoot('');
return banner() + '<div class="empty"><h3>无法进入数据源</h3><p>只有管理者可以进入数据源界面。</p></div>';
}
function render() {
renderProto();
var s = state.screen, h;
if (!isAdmin()) h = vDenied();
else if (s === 'empty') h = vEmpty();
else if (s === 'list') h = vList();
else if (s === 'create') h = vCreate();
else if (s === 'edit') h = vEdit(null);
else if (s === 'disabled') h = vDisabled();
else if (s === 'noref') h = vEdit('noref');
else h = vEdit(s); // testing / ok / auth / timeout / unreachable / rejected
$('view').innerHTML = h;
sizeShell();
}
function sizeShell() {
var h = $('proto').offsetHeight;
$('shell').style.setProperty('height', 'calc(100vh - ' + h + 'px)');
}
function go(screen) {
if (state.timer) { clearTimeout(state.timer); state.timer = null; }
state.screen = screen;
render();
}
function runTest(id) {
state.testTarget = id;
go('testing');
state.timer = setTimeout(function () { state.timer = null; state.screen = state.sim; render(); }, 1400);
}
/* ---------- events ---------- */
document.addEventListener('click', function (e) {
var t = e.target.closest('button');
if (!t || t.disabled) return;
if (t.hasAttribute('data-reveal')) {
var input = $('f-password');
if (!input || input.getAttribute('data-mask') === '1' || input.value === '') return;
var show = input.type === 'password';
input.type = show ? 'text' : 'password';
t.textContent = show ? '隐藏' : '查看';
return;
}
if (t.hasAttribute('data-role')) { state.role = t.getAttribute('data-role'); render(); return; }
if (t.hasAttribute('data-screen')) { go(t.getAttribute('data-screen')); return; }
if (t.hasAttribute('data-go')) {
if (t.hasAttribute('data-id')) state.testTarget = +t.getAttribute('data-id');
go(t.getAttribute('data-go'));
return;
}
if (t.hasAttribute('data-test')) { runTest(+t.getAttribute('data-test')); return; }
if (t.hasAttribute('data-disable')) { go('disabled'); return; }
if (t.hasAttribute('data-save')) { go('list'); return; }
});
document.addEventListener('focusin', function (e) {
if (e.target.id !== 'f-password' || e.target.getAttribute('data-mask') !== '1') return;
e.target.value = '';
e.target.removeAttribute('data-mask');
});
document.addEventListener('focusout', function (e) {
if (e.target.id !== 'f-password' || e.target.getAttribute('data-mode') !== 'edit') return;
if (e.target.value !== '') return;
e.target.value = '••••••••';
e.target.type = 'password';
e.target.setAttribute('data-mask', '1');
var btn = $('f-reveal');
if (btn) { btn.textContent = '查看'; }
});
document.addEventListener('input', function (e) {
if (e.target.id !== 'f-password') return;
if (e.target.value === '') {
e.target.type = 'password';
var btn = $('f-reveal');
if (btn) btn.textContent = '查看';
}
});
document.addEventListener('change', function (e) {
if (e.target.id === 'p-sim') { state.sim = e.target.value; return; }
if (e.target.id === 'f-engine' && state.screen === 'create') {
$('f-port').value = PORT[e.target.value];
}
});
window.addEventListener('resize', sizeShell);
render();
})();
</script>
</body>
</html>
@@ -0,0 +1,175 @@
# M03 数据源配置(第一阶段)Requirement
## Goal
维护者能登记数据库数据源、编辑、停用与启用、在保存前/后做连接测试,并在详情中配置该源的熔断参数。平台对已保存且已启用的源做可开关的 Cron 周期巡检;连接失败(含认证失败)按该源配置累计,触发熔断后在冷却期内禁止测试与业务使用,冷却结束自动熄闸。凭证只在平台库中以密文保存。API 与日志不回显明文。
## Background
- 模块计划见 `docs/tasks/INDEX.md` 的 M03,需求见交接稿 A-01。
- M01、M02 已 DONE_LOCAL。平台库是 PostgreSQL,带租户 RLS。授权来自 Casdoor 角色(D19);数据源接口仅 `watchman-admin`。
- D21:第一阶段数据库来源 + 加密凭证 + 空引用 + 原型门禁。D22:列表/页脚按钮规则与密码框组件。
- 2026-11-18 用户实测反馈并确认增补:草稿测试、可逆启用、表单校验、Cron 巡检、与停用解耦的熔断、详情页配置熔断参数(D23)。
## In Scope
- 数据源元数据:名称、用途说明、启用状态、来源种类、数据库引擎、主机、端口、库名、最近一次连接测试结果与失败类别、熔断运行态与每源熔断参数。
- 来源种类可扩展。本阶段只接受并实现 `database`。引擎:`postgresql`、`mysql`、`sqlserver`。
- 新建、编辑、停用、启用、按租户列表与详情。停用后仍可查询与再启用;不可测试、不进周期巡检;后续场景配置不可选(本阶段提供稳定“可选源”筛选语义/接口约定)。
- 连接测试:
- **已保存测试**:测持久化配置,更新 `last_test_*`;失败计入该源熔断账。
- **草稿测试**:用当前表单探测,不写 `last_test_*`,不计入熔断;新建密码必填,编辑密码留空则用已存密文。
- 测试类别:成功、认证失败、超时、网络不可达、服务端拒绝。响应与日志不含口令、连接串、密文或驱动原始错误。
- 凭证:平台库加密字段。更新时整段替换。读取接口只返回“是否已配置”。
- 引用查询接口返回空列表和稳定占位结构。
- 周期巡检:后端配置开关 + Cron 表达式;只扫描已启用且未熔断的源;失败更新 `last_test_*`、写审计,本轮不发企微(C2=A)。
- 熔断:与 `enabled` 解耦;参数在数据源详情可配;默认窗口 5 分钟/阈值 3/冷却 10 分钟。
- 单次探测:可配超时;可重试类别仅 timeout/unreachable;auth_failed/rejected 不重试。
- 权限:仅 admin 的数据源读写与测试。
- 控制台页面:上述流程(原型已确认)。
## Out Of Scope
- 查询定义、SQL 执行、采集、映射、报警、企微真实发送、场景页本身。
- HTTP、消息队列、视频等非数据库来源的可用实现。
- 外部密钥管理系统、凭证轮换后台、配置导出、物理删除。
- 证明源库账号只读。
- 真实 MES 或生产库联调。
- 熔断自动改启用状态;半开试探探测(采用纯时间熄闸)。
## Current Behavior
S1–S5 已交付:可登记三种引擎、保存后按 id 测试、仅停用不可启用、无草稿测、无周期巡检、无熔断。本增补在其上扩展。
## Required Behavior
- 有权限用户可登记数据源;保存前可用草稿测试;保存后可用已保存测试。
- 列表和详情看不到口令。编辑留空表示不改凭证。
- 停用/启用可逆。停用:不可测、不巡检、不可被后续场景选中。启用不要求先测通。
- 详情可查看并保存该源熔断三参数;缺省为 300s/3/600s。
- 已保存源上的探测失败与(预留)业务查源失败写入统一失败账;窗口内达阈值则开闸;开闸期内禁止测试、业务使用与巡检;冷却结束自动熄闸。
- 草稿测试不入熔断账。
- 非 database/未知引擎创建失败。引用空数组。跨租户不可见。无会话 41000;非 admin 42000。
## User Flow
1. 管理者打开数据源列表。
2. 新建:填连接信息 → 可先草稿测试 → 保存(默认可为启用)。
3. 详情:编辑连接、配置熔断参数、已保存测试、停用或启用。
4. 停用后仍可打开详情再启用;测试按钮不可用。
5. 熔断中:界面标明状态与预计恢复时间;测试与业务使用被拒。
6. 引用区仍为空状态。
## Business Rules
- 租户内名称唯一。停用不是删除;本阶段无物理删除。
- 连接测试失败不自动改 `enabled`。
- 熔断不改 `enabled`;停用也不清熔断账(再启用后若仍在开闸冷却内则仍不可用,直到熄闸)。
- 周期巡检与手工/草稿测试均不得增加业务报警错误次数。
- 只读意图本阶段不展示、不据此拒绝连接(若列仍在库中可保留但不进表单)。
## Circuit Breaker Rules
| 项 | 口径 |
|---|---|
| 与停用 | 完全解耦。停用是人工配置;熔断是运行态 |
| 记失败 | 已保存源的探测(手工/巡检)及后续业务查源连接失败;类别含 success 以外全部(含 auth_failed) |
| 记成功 | 未开闸时成功清零窗口计数;已开闸时成功不提前熄闸 |
| 开闸 | 滑动窗口内失败次数 ≥ 阈值 |
| 开闸期 | 拒绝已保存测试、拒绝业务取连接、跳过巡检 |
| 熄闸 | `circuit_opened_at + cooldown` 到期后自动 `closed`,不先探测 |
| 参数 | 每源可配:`failure_window_seconds`、`failure_threshold`、`open_cooldown_seconds`;默认 300、3、600;在详情页编辑并随更新保存 |
| 草稿 | 无 id 或不落库的草稿测试不记账 |
后续查询模块必须通过本模块提供的 `assert_usable`/失败记账入口,不得绕过熔断。
## Healthcheck Rules
- 配置(环境/后端配置文件,非每源):`enabled` 布尔 + Cron 表达式。
- `enabled=false` 或非法 Cron:不注册/任务直接返回。
- 候选:`enabled=true` 且电路未开闸。
- 失败:更新 `last_test_*`、写审计;本轮不发企微。
## Data Rules
- 租户由服务端注入,RLS 不变。
- 口令密文列;密钥只来自环境变量。
- 主机、端口、库名、用户名、熔断参数与熔断状态可回显;口令/连接串/密文不可。
- 测试结果:类别、时间、短原因(无驱动原文)。
## API Contract
- 列表、详情、创建、更新、停用、**启用**。
- 已保存测试:`POST .../{id}/test`。
- 草稿测试:`POST .../test-draft`(body 为连接字段;编辑时可带 id 仅用于取已存密码,仍不写 last_test、不记账——若带 id 仅解密密码,熔断仍不记账)。
- 详情/列表返回:`enabled`、`circuit_state`(`closed`|`open`)、`circuit_opened_at`、`circuit_open_until`(可计算)、三熔断参数、`last_test_*`。
- 更新可改三熔断参数(校验:窗口/冷却为正整数合理上限;阈值为 ≥1 整数)。
- 开闸或停用时测试返回明确业务错误(非笼统 500)。
- 可选源列表或列表过滤约定:仅 `enabled && circuit closed`(或提供 `usable=true` 查询参数)供后续场景使用。
- 信封与错误码段不变。
## UI Requirements
- 沿用已确认原型与 D22;本增补在正式页上加:
- 新建/编辑:**测试连接**在保存前可用(草稿);保存后仍可已保存测试。
- 停用后显示**启用**。
- 详情:熔断三参数表单项;熔断中提示。
- 表单校验:名称/引擎/host(仅必填)/port(1–65535)/database/username 必填;密码新建必填、编辑可空;熔断参数数值校验。
- 仅 admin 进入。
## Compatibility Requirements
- 不改 M02 登录与既有三权限点含义。
- 不改审计表既有列语义;数据源变更与巡检失败可写审计,payload 无凭证。
- 查询/场景模块稍后接入 usable 与记账,不在本阶段实现场景页。
## Error Handling
- 类别分离;探测超时有上限。
- 日志脱敏。
- 前端按统一错误信封展示。
## Permissions And Security
| 权限点 | 动作 | 角色 |
|---|---|---|
| `perm:data:emp:watchman.datasource.read` | 列表与详情 | 仅 admin |
| `perm:data:emp:watchman.datasource.write` | 新建、编辑、停用、启用 | 仅 admin |
| `perm:data:emp:watchman.datasource.test` | 已保存测试与草稿测试 | 仅 admin |
- 后端强制。已保存测试只能打已保存主机端口;草稿测试使用提交的主机端口(仅 admin)。
## Assumptions
- 巡检 Cron 使用与平台一致的解析库(成熟库,不手写)。
- 单次探测超时/最大尝试次数可用全局配置;熔断三参数每源配置。
- 业务查源尚未实现时,提供可单测的记账与 `assert_usable` API,供后续模块调用。
## Risks
- 草稿测试扩大出站面:靠 admin 权限约束,无网段白名单。
- 纯时间熄闸后第一次业务调用可能再次失败并迅速重新开闸——可接受。
- Cron 与 Celery Beat 适配需薄封装,避免第二套调度器。
## Acceptance Criteria
1. admin 能创建三种引擎;错误引擎与非 database 被拒。
2. 列表/详情/审计/日志无口令与密文;编辑留空不改口令。
3. 三种隔离库:已保存测试成功;错口令 auth_failed;库不存在 rejected;超时类别正确。
4. 新建/编辑保存前草稿测试可用且不写 last_test、不入熔断账。
5. 仅 admin;非 admin 42000;无会话 41000。
6. 停用后不可测、不巡检;可再启用(无需先测通)。
7. 详情可改熔断三参数并持久化;默认 300/3/600。
8. 窗口内达阈值开闸:测试与 usable 被拒;冷却后自动熄闸。
9. 配置关闭或无效 Cron 时巡检不跑;开启后按 Cron 只扫启用且未熔断源;失败有 last_test 与审计,无企微。
10. 引用仍为空列表。
11. 控制台覆盖启用、草稿测、校验、熔断展示与参数编辑。
## Deferred Questions
- 源库只读探测;内网白名单;非数据库来源字段;引用项字段;企微通知巡检失败。
## Source Notes
- 用户 2026-11-17:D21;2026-11-18:D22;2026-11-18 实测六条反馈;Q1=A、Q2=A、Q3 host 仅必填、Q4 Cron、Q5 熔断与停用解耦且认证计入、Q6 全进本轮;C1 默认参数、C2=A、熔断参数在详情配置 → D23。
- 规范:`standards://api/api-envelope?version=1.1.0`、`standards://api/error-handling?version=1.1.1`、`standards://api/permission-nodes?version=1.0.0`、`standards://security/red-line?version=1.1.0`。
@@ -0,0 +1,11 @@
# M03 S1 Review
- Slice: S1 数据源模型、迁移与凭证密文
- Implementer: Claude Sonnet,[实现 S1](583d05d2-27ef-4bc9-9e40-cfe28866705e)
- Independent review: Gemini,[审查 S1](70b146aa-3bea-43f9-a853-6c5d2fa25448)
- Extra read-only pass: GPT,[代码审查](ef0eaf81-b33c-4e2e-907f-047854093f95)
- Verdict: PASS_WITH_WARNINGS
- Validation reported by implementer: `uv run pytest` in `services/watchman` → 84 passed, exit 0. Alembic upgrade, downgrade to `20261117_0003`, upgrade again, exit 0. Local database left at `20261117_0004`.
- Blockers: none
- Follow-up, not an S1 defect to fix now: `updated_at` does not auto-refresh on UPDATE. Handle in S3 when rows are edited. Do not rewrite the applied migration for this.
- Residual: empty plaintext is not rejected yet (S3). Do not `model_dump()` Settings. Key loss is unrecoverable. Cross-tenant UPDATE/DELETE is covered by the same RLS policy but not a separate test.
@@ -0,0 +1,11 @@
# M03 S2 Review
- Slice: S2 三种数据库连接测试
- Implementer: Claude Sonnet,[实现 S2](577db49f-ed40-4c5e-b538-1916ce389b51)
- First review: GPT,[审查 S2](82d483cc-7add-471f-941d-5991cf93e535),BLOCKED。缺库被标成认证失败。
- Repair and re-review: Gemini,[复审 S2](930b0683-26b7-4ae7-8d0e-63eccfb00f53),PASS_WITH_WARNINGS。
- Validation: `uv run pytest` in `services/watchman` → 134 passed, exit 0. Live wrong password is `auth_failed`. Live missing database is `rejected` for PostgreSQL, MySQL, and SQL Server.
- Blocker closed: `auth_failed` requires positive evidence. Other server rejections use `rejected`.
- Warning carried forward: S3 must expose `rejected` in the API. `updated_at` still does not auto-refresh.
- SQL Server test container: `watchman-dev-sqlserver`, published on 127.0.0.1 only.
- Fernet key and test passwords are in gitignored `.env.local` only.
@@ -0,0 +1,10 @@
# M03 S3 Review
- Slice: S3 数据源 API、权限与空引用
- Implementer: Claude Sonnet,[实现 S3](072e1cac-4f7f-409a-9672-6bd23edaa96c)
- First review: GPT,[审查 S3](b8304f13-65cd-4017-9723-95b0d016babb),BLOCKED。连接参数变更后仍保留旧测试结果。
- Repair and re-review: Gemini,[复审 S3](89b2c565-07c1-421b-b6c4-7f1925a39d6f),PASS_WITH_WARNINGS。
- Validation: `uv run pytest` in `services/watchman` → 175 passed, exit 0. Reviewer re-ran the suite.
- Closed: PATCH clears `last_test_*` when engine, host, port, database, username, or password actually changes.
- Not adopted: `@app_gate` / `permission_nodes` registry / `perm_diff`. This repository has no gateway scanner. Nodes stay as constants, the same way M02 did, and D19 does not add a second registry.
- Residual: a slow probe can write its result back if the row was edited or disabled during the probe. `password: null` keeps the stored secret.
@@ -0,0 +1,8 @@
# M03 S4 Prototype Check
- Slice: S4 static HTML prototype
- Implementer: Claude Sonnet, [原型](6ef382ff-78dc-4167-ae66-a8c204db0d61)
- Files: `.task/2026-11-17/m03-datasource/prototype/index.html` and `README.md`
- Scope: no Vue, no `web/`, no API
- Checked in a browser: list, viewer role (no save/test/disable), rejected state with an empty password field and the note that a missing database is not an authentication failure. The references section is on the detail screen as “尚无引用”.
- Not approved for Vue. S5 stays blocked until the user confirms this prototype.
@@ -0,0 +1,8 @@
# M03 S5 Review
- Slice: console datasource pages, and datasource API checks limited to watchman-admin
- Implementer: Claude Sonnet, [实现 S5](d8c04bbe-bdfe-4d10-b004-2406034e1841)
- Review: GPT, [审查 S5](0413a65a-8cd3-445b-9f42-9e5e2fffab72), PASS_WITH_WARNINGS
- Warning closed after review: principal.py docstrings now say admin-only, matching the checks
- Validation reported: backend pytest 182 passed; console unit 24; typecheck; build; Playwright 17 passed, including 10 datasource specs. APIs in Playwright were mocked.
- Not DONE_LOCAL. The user has not accepted the finished module.
@@ -0,0 +1,30 @@
# Review Result
## Recommendation
PASS_WITH_WARNINGS
## Review Scope
- Task: `2026-11-17/m03-datasource`, slice `S6`
- Routing: Tier L, `gateClass: high-risk`, `risk_score: 4`; two-stage bounded re-review performed after the P1 repair.
- Reviewed the caller-provided S6 repair paths and bounded task artifacts. No forbidden `web/**` or `services/watchman/src/watchman/jobs/**` changes were reviewed.
- Supplied validation evidence: `cd services/watchman && uv run pytest` reported `232 passed, 1 warning`. This reviewer did not rerun the suite.
## Stage 1: Boundary And Compliance Review
- **P1 fixed:** `get_datasource()` now calls `_close_if_cooled_down()` before serialization, and the detail route commits the normalized state. `list_datasources()` likewise normalizes every returned row and its route commits.
- The new regression tests advance past cooldown, verify detail and ordinary-list responses return `closed` with cleared open timestamps, and verify the persisted row is closed.
- The repair remains within allowed S6 service, route, and test scope. No scheduler, frontend, credential, or other forbidden-scope behavior was introduced.
## Stage 2: Implementation Quality Review
- No blocking implementation or regression finding was identified in the bounded re-review.
## Warning
- `services/watchman/src/watchman/services/datasources.py:116-122`: `to_public()` still says an elapsed `circuit_open_until` means “the next usability check closes it.” Detail and list reads now also normalize before serialization, so this wording is stale. It does not affect runtime behavior.
## Residual Risk
- Circuit state changes on reads are intentionally persisted by the detail/list route commits. The supplied full-suite result covers the repaired paths; migration-head verification was not supplied for this re-review.
@@ -0,0 +1,36 @@
# Review Result
## Slice
S7 — Cron periodic datasource health checks
Gate class: `high-risk`; risk score: `4`
## Stage 1: Boundary And Compliance Review
No blocking findings.
- The implementation stays within the approved S7 areas: Celery Beat registration, Cron validation, health-check orchestration, settings, dependency lock, environment example, and focused tests. No `web/**` or migration file was modified for this slice.
- It uses the existing Celery Beat application and `croniter`; no second scheduler was introduced.
- Disabled, invalid-Cron, disabled-source, and open-circuit paths all no-op or skip before probing. The per-source probe rechecks usability, preserving the S6 circuit boundary.
- Failed probes update persisted test outcomes and write a credential-free audit payload. No WeCom send path is present.
- Cron validation explicitly rejects simultaneous restricted DOM/DOW fields, avoiding the known croniter (OR) versus Celery (AND) semantic mismatch. A direct Celery compatibility check also confirmed that unsupported weekday `7` is rejected rather than silently scheduled.
## Stage 2: Implementation Quality Review
No blocking findings.
- The candidate IDs are collected before network I/O and each source is committed independently, avoiding a long database transaction during probes and preventing one source failure from aborting the batch.
- Tests cover switch and invalid-Cron no-ops, enabled-and-closed selection, mid-loop disable, outcome accounting, audit secret hygiene, circuit opening, Beat registration, configuration parsing, and task execution.
## Validation Evidence
- Supplied: `cd services/watchman && uv run pytest` — `262 passed`, including 30 new S7 tests.
- Reviewed runtime compatibility: Celery rejects an unsupported `day_of_week=7`; the adapter treats it as invalid and does not register a schedule.
## Residual Risk
This remains production scheduling/configuration work (`risk_score: 4`). The test evidence is mock-probe based, so an environment-level Beat/worker/RabbitMQ execution check is still appropriate during later integration validation.
## Recommendation
PASS
@@ -0,0 +1,35 @@
# Review Result
## Slice
S8 — 控制台增补(启用/草稿测/校验/熔断配置)
## Scope And Boundary Review
- 已审阅 `web/apps/console/src/datasources/**`、四个 locale 文件、`web/apps/console/e2e/datasources.spec.ts` 和 M03 UI 证据目录;未发现 `services/watchman/**` 的 S8 改动。
- 草稿测试走 `POST /datasources/test-draft`,保存前可用;已保存测试与草稿测试分离。
- 停用/开闸状态禁用已保存测试;停用记录可直接启用,且启用不要求预先测试。
- 详情页展示并提交三个熔断参数;host 仅做非空校验,端口和熔断参数做整数范围校验。
- 编辑密码使用固定掩码,空密码不会出现在更新或草稿测试 payload;页面不使用 localStorage 保存凭证。
- 四种 locale 的 datasource 键由单测比较,未发现键集遗漏。
## Findings
### Warning — S6 契约联调尚无独立证据
`pnpm test:e2e` 的 25 个用例均使用 mocked APIs。实现与当前 S6 路由的 `test-draft`、`enable`、熔断字段和错误详情契约一致,但实施计划要求与 S6 API 联调;现有证据不能证明真实前后端组合运行。模块整体验收前应补充一次针对运行中 S6 API 的最小端到端验证,或明确记录该环境不可用。
## Validation Evidence
- Reported: `pnpm test:unit` — 7 files / 39 tests passed.
- Reported: `pnpm typecheck` — exit 0.
- Reported: `pnpm test:e2e` — 25/25 passed with mocked APIs.
- Reviewer check: scoped frontend diff passes `git diff --check`.
## Knowledge Sync
无需在本切片额外更新知识文档。熔断/usable 边界的稳定性文档同步仍按实施计划在模块验收阶段处理。
## Recommendation
PASS_WITH_WARNINGS
@@ -0,0 +1,23 @@
{
"taskId": "2026-11-17/m03-datasource",
"module": "M03",
"title": "数据源配置模块",
"type": "feature",
"tier": "L",
"phase": "done",
"allowedToCode": false,
"currentSlice": "done",
"proposedNextSlice": null,
"lastGate": "done-local",
"status": "DONE_LOCAL",
"gatePolicy": {
"selected": "autonomous",
"effective": "autonomous",
"finalApprovalRequired": true
},
"notes": [
"User confirmed finish: commit, push, DONE_LOCAL",
"UI polish after S8 acceptance included"
],
"updatedAt": "2026-11-18T04:50:00Z"
}
@@ -0,0 +1,78 @@
# Task Context Pack
## Task Goal
M04:受控查询草稿、不可变版本、只读预览与控制台(A-016~A-020;D24)。
## Current Slice Or Group
分析完成;用户已确认计划并要求执行全部切片。下一编码切片:**S1**。
## Requirement Source
`.task/2026-11-18/m04-queries/requirement.md`
## Implementation Source
`.task/2026-11-18/m04-queries/implementation-plan.md`
## Involved Modules Or Knowledge Areas
- 查询定义/版本;只读执行;M03 数据源 usable/熔断
- 控制台查询 UI(S5)
## Loaded Rules
- `AGENTS.md`;sy-standards(API 信封、错误、权限点、前端、红线、注释)
- Marionettist autonomous;原型确认停点;`risk_score>=4` 片际停
## Loaded Docs
- `docs/tasks/INDEX.md` M04;交接稿 A-02;`docs/decisions.md`;`docs/current/frontend-ui.md`
- M03 `assert_usable`/datasources API
## Allowed Modification Scope
按当前切片:见 implementation-plan 各 Slice Allowed Modification Scope。
## Forbidden Modification Scope
- 秘密入库/入日志;映射/报警/企微/场景正式采集;生产破坏性操作
- S4 确认前改 Vue 查询页
## Key Existing Entrypoints
- `services/watchman/src/watchman/services/datasources.py`:`assert_usable`、`list_references`、失败记账
- `services/watchman/src/watchman/api/routes/datasources.py`
- `services/watchman/src/watchman/auth/access.py`
- `web/apps/console/src/datasources/`(UI 模式参考)
- `.task/2026-11-17/m03-datasource/prototype/`(原型模式参考)
## Gate Policy
- selected / effective: autonomous
- finalApprovalRequired: true
## Validation Commands
```
cd services/watchman && uv run pytest
cd services/watchman && uv run alembic upgrade head
cd web/apps/console && pnpm test:unit && pnpm test:e2e && pnpm typecheck
```
## Assumptions
- 权限点 `watchman.query.*` 仅 admin
- 预览不进报警
- 正式采集留给 M08
## Risks
- SQL 注入与任意标识符;熔断绕过;版本可变回归
## Stop Conditions
- S4→S5:原型未确认
- high-risk/boundary-sensitive/risk>=4 片审未过
- 最终验收前不标 DONE_LOCAL(除非用户明确授权)
@@ -0,0 +1,168 @@
# M04 查询定义与采集 Implementation Plan
## Requirement Source
`.task/2026-11-18/m04-queries/requirement.md`(D24)
## Scope Summary
参数化 SQL 查询草稿、不可变版本发布、只读预览执行与控制台 UI。正式场景采集不在本轮。
## Involved Modules Or Areas
- `services/watchman`:模型、迁移、执行器、API、权限、数据源 references 回填。
- `web/apps/console`:仅 S4 确认后的查询页面。
- 不改 Casdoor 登录语义;不改熔断参数模型本身。
## Loaded Rules
- `AGENTS.md` 项目本地段;`.cursor/rules/sy-standards.mdc`
- Marionettist `gatePolicy.selected=autonomous`
## Loaded Docs
- `docs/tasks/INDEX.md` M04;交接稿 A-02;`docs/decisions.md` D14/D19/D22/D23/D24
- `docs/current/frontend-ui.md`
- M03:`assert_usable`、datasources routes/services
## Global Forbidden Scope
- 口令、连接串、加密密钥、预览全文入仓库/日志/证据。
- `.env.local`、`.cursor/mcp.json`
- 映射/规则/报警/企微/场景 Cron 正式采集
- 原型确认前的 Vue 查询页(S5 起允许)
- 生产库、`git reset --hard`、未授权自动 commit
## Execution Strategy
- Complexity: complex
- Default Execution: sequential
- Parallel Execution: not-needed
- Merge Owner: 主 Agent
## Slice Dependency Graph
| Slice | Depends On | Fallback Order | Gate Class | Risk Score |
| --- | --- | --- | --- | --- |
| S1 模型与版本 | 分析确认 | 1 | high-risk | 4 |
| S2 只读执行器 | S1 | 2 | high-risk | 4 |
| S3 API 与权限 | S1、S2 | 3 | boundary-sensitive | 4 |
| S4 HTML 原型 | S3 字段口径 | 4 | simple | 2 |
| S5 Vue 页面 | S4 用户确认 | 5 | standard | 3 |
| S6 整体验收 | S5 | 6 | boundary-sensitive | 3 |
## Implementation Slices
### Slice 1: 模型、迁移与不可变版本约束
#### Goal
平台库可按租户保存查询草稿与不可变版本;RLS 生效;版本内容更新路径在服务/测试层被拒绝。
#### Allowed Modification Scope
- `services/watchman/src/watchman/models/`
- `services/watchman/migrations/`
- `services/watchman/tests/` 本切片测试
#### Forbidden Scope
- API 路由、执行器真实连源、前端
#### Gate Class / Risk Score
high-risk / 4 — schema-migration
#### Validation
- `uv run pytest` 本切片测试;`alembic upgrade head`
#### Done Criteria
- 表与 RLS 就绪;版本行内容不可被服务辅助函数更新(测试覆盖)
### Slice 2: 只读执行器
#### Goal
对给定 SQL 模板+参数+限制在 usable 数据源上只读执行;空/非法类型/失败三分;绑定防注入。
#### Allowed Modification Scope
- `services/watchman/src/watchman/queries/`(或等价包)
- `services/watchman/src/watchman/services/` 执行相关
- 测试;必要时薄改 datasources 记账调用
#### Forbidden Scope
- 前端;发布 API 完整面
#### Gate Class / Risk Score
high-risk / 4 — device/datasource communication, injection
#### Validation
- 单元/集成:绑定、超时、行数、空结果、类型不匹配、参数含 SQL 片段不注入
### Slice 3: API、权限、引用回填
#### Goal
CRUD/启停/publish/版本/preview/references;四权限点;审计;数据源 references 列查询。
#### Allowed Modification Scope
- `api/routes/`、`auth/access.py`、`services/`、`api/app.py` 注册
- datasources `list_references` 回填
- 测试
#### Gate Class / Risk Score
boundary-sensitive / 4 — permissions, public API
#### Validation
- API 测试:权限拒绝、发布递增、版本只读、预览三分、信封
### Slice 4: HTML 原型
#### Goal
静态原型覆盖列表/编辑/版本/预览/角色门,供确认。
#### Allowed Modification Scope
- `.task/2026-11-18/m04-queries/prototype/` 仅
#### Gate Class / Risk Score
simple / 2
#### Stop
用户确认前不开始 S5。
### Slice 5: Vue 控制台
#### Goal
按确认原型与 D22 实现查询页与 e2e/单测。
#### Allowed Modification Scope
- `web/apps/console/**` 查询相关、导航、四语言、e2e
#### Gate Class / Risk Score
standard / 3
### Slice 6: 模块整体 review 与正式测试
#### Goal
独立 review、修复、pytest/unit/Playwright 证据、主 Agent 验收(DONE_LOCAL 仅用户最终确认后)。
#### Gate Class / Risk Score
boundary-sensitive / 3
+46
View File
@@ -0,0 +1,46 @@
# Task Intake Result
## Task Type
feature。Tier L(只读执行、注入防护、迁移、不可变版本、跨前后端)。
## Current Understanding
- M03 DONE_LOCAL。推进 M04:受控查询定义、参数/输出契约、只读执行、预览与配套 UI(A-016~A-020)。
- 用户确认:参数化 SQL 模板(A);不可变查询版本本轮交付(2b);正式定时/场景采集留给 M08。
- 正式 Vue 前须 HTML 原型确认(与 M03/D21 同模式)。
- 执行须经 M03 `assert_usable`/熔断记账,不得绕过。
## Gate Policy
- config/default: balanced
- allowTaskOverride: true
- recommended: balanced
- selected: autonomous
- reason or override reason: 用户在 Marionettist 入口明确选择 autonomous。
- effective: autonomous
- finalApprovalRequired: true
说明:autonomous 不取消分析→编码门禁、最终验收、`gateClass: high-risk|boundary-sensitive`、critic、显式停点、危险命令,以及 `risk_score >= 4`。HTML 原型确认为 S5 前显式停点。用户于 2026-11-18 确认计划并要求执行全部 todos,视为越过分析→编码门禁。
## Blocking Questions
已关闭:
1. 查询正文 = 参数化 SQL 模板。
2. M04 交付不可变查询版本(publish/只读历史);正式采集留给 M08。
## Non-blocking Assumptions
- 权限仅 `watchman-admin`,权限点 `watchman.query.{read,write,publish,preview}`。
- 预览不进报警/通知。
- 定义/版本 references 先空列表;数据源 references 可回填查询引用。
- 标识符白名单用于不可绑定对象名;不靠 SELECT 前缀。
## Recommended Next Step
编码 S1(模型与迁移)。
## Suggested Prompt For Next Step
按 `implementation-plan.md` Slice 1 实现 query_definitions/query_versions 与 RLS/不可变约束测试。
@@ -0,0 +1,79 @@
# M04 查询定义 · 静态 HTML 原型(S4)
**状态:待维护者确认,确认前不得据此编写 Vue 页面。** 未经确认信息架构、按钮位置与各预览状态,不改正式 Vue 应用,也不动后端。
## 如何打开
直接用浏览器打开本目录的 `index.html`(双击即可)。单文件,无构建、无 CDN、无网络请求。
## 控件说明
顶部黄色虚线条「原型切换」不属于未来产品,只用于评审。
- **角色**:管理者 / 处理者 / 查看者。只有管理者能进入查询界面;处理者和查看者只看到「无法进入查询」(后端对应 42000 并带权限点)。
- **画面**(仅管理者):空列表、列表、新建草稿、编辑草稿、编辑(已停用)、版本只读。
- **预览结果**:未试跑 / 试跑中 / 成功 / 空结果 / 非法类型 / 失败 / 已停用 / 熔断中。点按钮立即展示该结果,并让之后点页脚「试跑预览」得到同一结果(先显示约 1 秒试跑中)。
- **失败子类型**:超时 / 连接失败 / SQL 语法错误(三类分开展示;连接失败注明计入熔断统计)。
- 编辑页中的名称、SQL、参数、输出、标识符、限制可以真的改;「保存草稿」「发布」「停用/启用」只修改本页内存数据,刷新即还原。
## 原型包含
| 画面 | 内容 |
| --- | --- |
| 门禁 | 非管理者看到拒绝页,无列表、无表单 |
| 空列表 | 说明 + 表格上方「新建」 |
| 列表 | 名称、数据源、状态、最新版本、更新时间、行内「打开」「预览」;已停用行「预览」置灰 |
| 新建/编辑草稿 | 名称、用途说明、数据源(已停用的灰显)、SQL 模板(示例 `:line_code`,实时标出未声明参数)、参数 schema(名称/类型/必填/默认值)、输出 schema(名称/类型)、允许标识符(标签)、`timeout_ms`、`max_rows`、状态、试跑预览区、版本列表、引用占位 |
| 版本只读 | 冻结的 SQL、参数、输出、标识符、限制;可试跑;无保存、无发布 |
| 预览结果 | 成功(样例行,示例脱敏列)、空结果、非法类型(契约不符明细)、失败(超时/连接/语法)、已停用、熔断中 |
| 发布 | 页脚「发布」弹出确认;有未保存修改时先提示保存;成功后版本列表新增 vN |
页脚按钮(居中、在滚动区外):
- 新建:返回列表、保存草稿、发布(置灰,需先保存)、试跑预览(置灰,需先保存)。
- 编辑草稿:返回列表、保存草稿、发布、停用/启用、试跑预览。
- 版本只读:返回列表、返回草稿、试跑预览。
- 列表页「新建」在表格上方;行内「打开」「预览」留在行内;版本列表行内「打开」。依据 `docs/current/frontend-ui.md`(D22)。
## 原型不包含
- 真实请求、真实数据源或口令;所有数据虚构,数据源名称无真实地址。
- 结构化表/字段选择器、任意脚本、字段映射、规则、报警、通知、场景定时采集。
- 非数据库数据源、查询物理删除、列表分页/筛选、审计页。
- 引用的具体内容(查询侧恒为「尚无引用」)。
- 服务端上限的真实值(页面里的 30000/1000 仅为示意)。
## 按钮与未来 Vue(Element Plus)对应
| 原型 | Vue 实现 |
| --- | --- |
| 列表「新建」 | `el-button type="primary"`,放在 `el-table` 上方 |
| 列表/版本表 | `el-table`;行内「打开」「预览」用 `el-button link` |
| 状态 | `el-tag` 或 `el-badge`;停用行「预览」`disabled` |
| 表单 | `el-form` + `el-form-item`、`el-input`、`el-input type="textarea"`、`el-select`、`el-input-number` |
| SQL 模板 | `el-input type="textarea"` 等宽字体(如需高亮另行评审,不引入新依赖前先问) |
| 参数/输出 schema | 可编辑 `el-table` + `el-input`/`el-select`/`el-checkbox`;行内删除 |
| 允许标识符 | `el-tag closable` + `el-input` 回车添加 |
| 页脚 | 滚动区外的固定区,`el-button` 居中;保存草稿 `primary`,发布 `plain`,停用 `type="danger" plain`,其余默认 |
| 发布确认 | `ElMessageBox.confirm` |
| 预览结果 | `el-alert`(成功/警告/错误)+ `el-table` 展示样例;试跑中用 `v-loading` |
| 无权限 | 空状态页(`el-empty`);真正权限由后端判定,前端隐藏不算安全控制 |
| 原型切换条、「原型本地模拟」提示、`正式版本进行删除` 标注 | 正式版全部删除 |
视觉 token:主色 `#5e6ad2`、圆角 8px、基础字号 13.5px。
## 请维护者确认
1. 预览使用「已保存草稿」还是「表单当前内容」?原型按已保存草稿,有未保存修改时给提示。
2. 查询停用后:「试跑预览」按钮仍可点并明确拒绝(原型做法),还是直接置灰?停用时「发布」是否允许?原型未限制。
3. 发布入口只在页脚(原型做法),版本区不放第二个发布按钮,是否同意?
4. 输出契约只有名称和类型,敏感列脱敏策略未设字段;原型只用固定示例遮盖 `operator_name`。是否需要「脱敏」列?
5. 标识符白名单的 SQL 占位语法未定;原型只展示允许列表。
6. 版本只读页面包含数据源名,并以 `详情 / 版本 vN` 作为面包屑,是否合适?
7. 预览成功样例固定 3 行;超出 `max_rows` 的截断提示未做。是否需要?
8. 失败子类型中,超时是否计入熔断,以后端口径为准,原型未声明。
## 约束
- 所有数据均为虚构;不含真实口令;不含 API 调用。
- 不改 Vue 应用与后端,不提交 git。
@@ -0,0 +1,842 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Watchman M04 查询定义 · 静态原型(S4)</title>
<style>
:root {
--primary: #5e6ad2;
--primary-soft: #eef0fb;
--text: #1f2328;
--text-2: #59636e;
--muted: #8b949e;
--surface: #ffffff;
--soft: #f6f8fa;
--border: #d0d7de;
--border-2: #eaeef2;
--ok: #1a7f37;
--ok-bg: #e9f6ec;
--warn: #9a6700;
--warn-bg: #fff8e1;
--err: #cf222e;
--err-bg: #fdecee;
--radius: 8px;
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
}
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body { font-family: var(--font); font-size: 13.5px; color: var(--text); background: var(--soft); line-height: 1.55; }
button, input, select, textarea { font: inherit; color: inherit; }
[hidden] { display: none !important; }
/* ---- prototype toolbar (not part of product) ---- */
.proto {
background: #fffbe6; border-bottom: 1px dashed #d4b106; padding: 8px 16px;
display: flex; flex-wrap: wrap; gap: 8px 20px; align-items: center; font-size: 12.5px;
}
.proto-title { font-weight: 600; color: #7a5b00; }
.proto-group { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.proto-group > .lbl { color: var(--text-2); margin-right: 2px; }
.proto-btn {
border: 1px solid var(--border); background: var(--surface); border-radius: 6px;
padding: 2px 9px; cursor: pointer; font-size: 12.5px;
}
.proto-btn:hover { border-color: var(--primary); color: var(--primary); }
.proto-btn.on { background: var(--primary); border-color: var(--primary); color: #fff; }
.proto-note { flex-basis: 100%; color: #7a5b00; }
.proto select { border: 1px solid var(--border); border-radius: 6px; padding: 2px 6px; background: #fff; font-size: 12.5px; }
/* ---- shell ---- */
.shell { display: flex; height: calc(100vh - 120px); min-height: 520px; }
.side { width: 196px; flex: none; background: var(--surface); border-right: 1px solid var(--border-2); padding: 14px 10px; }
.brand { font-weight: 700; font-size: 16px; padding: 4px 10px 14px; letter-spacing: .3px; }
.nav-item { padding: 7px 10px; border-radius: 6px; color: var(--text-2); }
.nav-item.cur { background: var(--primary-soft); color: var(--primary); font-weight: 600; }
.nav-item.off { color: var(--muted); }
.main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
.top { height: 48px; flex: none; background: var(--surface); border-bottom: 1px solid var(--border-2);
display: flex; align-items: center; justify-content: space-between; padding: 0 20px; }
.pagefoot { flex: none; background: var(--surface); border-top: 1px solid var(--border-2);
display: flex; align-items: center; justify-content: center; flex-wrap: wrap; gap: 8px; padding: 12px 20px; }
.list-actions { display: flex; justify-content: flex-end; margin-bottom: 12px; }
.crumb { color: var(--text-2); }
.crumb b { color: var(--text); font-weight: 600; }
.who { color: var(--text-2); display: flex; align-items: center; gap: 8px; }
.tag { display: inline-block; padding: 0 8px; border-radius: 10px; font-size: 12px; line-height: 20px; background: var(--primary-soft); color: var(--primary); }
.tag.grey { background: var(--soft); color: var(--text-2); border: 1px solid var(--border-2); }
.tag.ok { background: var(--ok-bg); color: var(--ok); }
.tag.warn { background: var(--warn-bg); color: var(--warn); }
.content { flex: 1; overflow: auto; padding: 20px; }
.local-banner { background: var(--primary-soft); border: 1px solid #d5d9f5; color: #3f49a8; border-radius: var(--radius);
padding: 7px 12px; margin-bottom: 14px; font-size: 12.5px; }
.flash { border-radius: var(--radius); padding: 8px 12px; margin-bottom: 14px; border: 1px solid; font-size: 13px; }
.flash.ok { background: var(--ok-bg); border-color: #b7e0c2; color: #145c2a; }
.flash.warn { background: var(--warn-bg); border-color: #f1dc9a; color: var(--warn); }
.flash.bad { background: var(--err-bg); border-color: #f4b8be; color: #8e1a23; }
.card { background: var(--surface); border: 1px solid var(--border-2); border-radius: var(--radius); padding: 16px 18px; margin-bottom: 16px; }
.card h3 { margin: 0 0 12px; font-size: 14.5px; display: flex; align-items: center; justify-content: space-between; gap: 10px; }
.card h3 .sub { font-weight: 400; font-size: 12px; color: var(--muted); }
.btn { border: 1px solid var(--border); background: var(--surface); border-radius: 6px; padding: 5px 14px; cursor: pointer; }
.btn:hover:not(:disabled) { border-color: var(--primary); color: var(--primary); }
.btn.primary { background: var(--primary); border-color: var(--primary); color: #fff; }
.btn.primary:hover:not(:disabled) { background: #4f5bc4; color: #fff; }
.btn.outline { border-color: var(--primary); color: var(--primary); }
.btn.danger { color: var(--err); }
.btn.danger:hover:not(:disabled) { border-color: var(--err); color: var(--err); }
.btn.sm { padding: 1px 8px; font-size: 12.5px; }
.btn:disabled { color: var(--muted); background: var(--soft); border-color: var(--border); cursor: not-allowed; }
.btn.link { border: 0; background: none; color: var(--primary); padding: 1px 6px; }
.btn.link.danger { color: var(--err); }
.btn.link:disabled { color: var(--muted); background: none; }
table { width: 100%; border-collapse: collapse; }
th { text-align: left; font-weight: 600; color: var(--text-2); background: var(--soft); padding: 9px 12px; border-bottom: 1px solid var(--border-2); white-space: nowrap; }
td { padding: 10px 12px; border-bottom: 1px solid var(--border-2); vertical-align: middle; }
tr.hl td { background: #fafbff; }
tr.off td { color: var(--muted); }
.mono { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12.5px; }
.table-wrap { overflow-x: auto; border: 1px solid var(--border-2); border-radius: var(--radius); background: var(--surface); }
.table-wrap table th:first-child, .table-wrap table td:first-child { padding-left: 16px; }
.table-wrap.inner table td { padding: 6px 10px; }
.ops { white-space: nowrap; }
.tbl-tools { display: flex; justify-content: flex-end; margin: -4px 0 8px; }
.status { display: inline-flex; align-items: center; gap: 6px; }
.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ok); }
.status.off .dot { background: var(--muted); }
.empty { text-align: center; padding: 56px 20px; background: var(--surface); border: 1px dashed var(--border); border-radius: var(--radius); }
.empty h3 { margin: 0 0 6px; font-size: 15px; }
.empty p { margin: 0 0 14px; color: var(--text-2); }
.empty.sm { padding: 18px 20px; }
.empty.sm p { margin: 0; }
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 24px; max-width: 820px; }
.field { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
.field.full { grid-column: 1 / -1; }
.field > label { color: var(--text-2); font-size: 12.5px; }
.req { color: var(--err); margin-left: 2px; }
input[type=text], input[type=number], select, textarea {
border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; background: var(--surface); width: 100%; outline: none; }
input:focus, select:focus, textarea:focus { border-color: var(--primary); box-shadow: 0 0 0 2px var(--primary-soft); }
input:disabled, select:disabled, textarea:disabled { background: var(--soft); color: var(--text-2); cursor: not-allowed; }
.table-wrap.inner input[type=text], .table-wrap.inner select { padding: 3px 8px; }
textarea.sql { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12.5px; line-height: 1.6; resize: vertical; }
pre.sql { margin: 0; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12.5px; line-height: 1.6;
background: var(--soft); border: 1px solid var(--border-2); border-radius: 6px; padding: 10px 12px; white-space: pre-wrap; }
.hint { color: var(--muted); font-size: 12px; }
.drop-later { color: #7a5b00; }
.check { display: flex; align-items: center; gap: 8px; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-top: 6px; }
.chip { display: inline-flex; align-items: center; gap: 4px; padding: 0 8px; line-height: 22px; border-radius: 4px; font-size: 12px;
border: 1px solid var(--border); background: var(--soft); font-family: ui-monospace, Consolas, monospace; }
.chip.ok { background: var(--ok-bg); border-color: #b7e0c2; color: #145c2a; }
.chip.bad { background: var(--err-bg); border-color: #f4b8be; color: #8e1a23; }
.chip.dim { color: var(--muted); }
.chip button { border: 0; background: none; cursor: pointer; color: var(--muted); padding: 0 2px; }
.chip button:hover { color: var(--err); }
.ident-add { display: flex; gap: 8px; margin-top: 10px; max-width: 420px; }
.note { border-radius: var(--radius); padding: 8px 12px; font-size: 12.5px; background: var(--soft); border: 1px solid var(--border-2); color: var(--text-2); }
.note.warn { background: var(--warn-bg); border-color: #f1dc9a; color: var(--warn); }
.pv-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px 20px; max-width: 820px; margin-bottom: 12px; }
.pv-target { margin-bottom: 10px; color: var(--text-2); font-size: 12.5px; }
.result { border-radius: var(--radius); padding: 12px 14px; border: 1px solid; margin-top: 12px; }
.result .r-title { font-weight: 600; margin-bottom: 2px; }
.result .r-body { font-size: 13px; }
.result .r-meta { margin-top: 6px; font-size: 12px; opacity: .85; }
.result .r-table { margin-top: 10px; background: #fff; color: var(--text); }
.result .r-table td, .result .r-table th { white-space: nowrap; }
.result.ok { background: var(--ok-bg); border-color: #b7e0c2; color: #145c2a; }
.result.bad { background: var(--err-bg); border-color: #f4b8be; color: #8e1a23; }
.result.pend { background: var(--primary-soft); border-color: #d5d9f5; color: #3f49a8; }
.result.warn { background: var(--warn-bg); border-color: #f1dc9a; color: var(--warn); }
.result.grey { background: var(--soft); border-color: var(--border); color: var(--text-2); }
.spin { display: inline-block; width: 12px; height: 12px; border: 2px solid #c3c8f0; border-top-color: var(--primary); border-radius: 50%; animation: sp .8s linear infinite; vertical-align: -2px; margin-right: 6px; }
@keyframes sp { to { transform: rotate(360deg); } }
.focus { outline: 2px solid var(--primary-soft); border-color: var(--primary); }
.kv { display: grid; grid-template-columns: 96px 1fr; gap: 4px 12px; font-size: 13px; }
.kv dt { color: var(--muted); } .kv dd { margin: 0; }
.modal-mask { position: fixed; inset: 0; background: rgba(31,35,40,.4); display: flex; align-items: center; justify-content: center; z-index: 10; }
.modal { background: #fff; border-radius: var(--radius); padding: 18px 20px; width: 400px; max-width: 90vw; box-shadow: 0 8px 28px rgba(0,0,0,.18); }
.modal h3 { margin: 0 0 8px; font-size: 15px; }
.modal p { margin: 0 0 16px; color: var(--text-2); }
.modal .row { display: flex; justify-content: flex-end; gap: 8px; }
</style>
</head>
<body>
<div class="proto" id="proto">
<span class="proto-title">原型切换</span>
<div class="proto-group"><span class="lbl">角色</span><span id="p-roles"></span></div>
<div class="proto-group"><span class="lbl">画面</span><span id="p-screens"></span></div>
<div class="proto-group"><span class="lbl">预览结果</span><span id="p-results"></span></div>
<div class="proto-group" id="p-fsub-wrap"><span class="lbl">失败子类型</span><select id="p-fsub"></select></div>
<div class="proto-note">此条仅用于评审,不属于未来产品。所有数据均为虚构,页面不发送任何网络请求,不含真实密码或地址。点「预览结果」按钮会立即展示该结果,并让页脚「试跑预览」之后得到同一结果。正式版本进行删除</div>
</div>
<div class="shell" id="shell">
<aside class="side">
<div class="brand">Watchman</div>
<div class="nav-item off">数据源</div>
<div class="nav-item cur" id="nav-q">查询</div>
</aside>
<div class="main">
<header class="top">
<div class="crumb" id="crumb">Watchman / <b>查询</b></div>
<div class="who">当前角色 <span class="tag" id="who-role"></span></div>
</header>
<main class="content" id="view"></main>
<div class="pagefoot" id="pagefoot" hidden></div>
</div>
</div>
<div id="modal-root"></div>
<script>
(function () {
'use strict';
var ROLES = { admin: '管理者', handler: '处理者', viewer: '查看者' };
var SCREENS = [
['empty', '空列表'], ['list', '列表'], ['create', '新建草稿'], ['edit', '编辑草稿'], ['editoff', '编辑(已停用)'], ['version', '版本只读']
];
var RESULT_KINDS = [
['none', '未试跑'], ['running', '试跑中'], ['success', '成功'], ['empty', '空结果'], ['illegal_type', '非法类型'],
['failure', '失败'], ['disabled', '已停用'], ['circuit_open', '熔断中']
];
var FSUB = [['timeout', '超时'], ['connection', '连接失败'], ['syntax', 'SQL 语法错误']];
var TYPES = ['string', 'integer', 'number', 'boolean', 'datetime'];
var NOW = '2026-11-18 14:37';
// All sample data below is fictional. Hosts/datasources use reserved ".example.test" naming only.
var DS = [
{ id: 'ds1', name: '产线工艺库', on: true },
{ id: 'ds2', name: '设备台账库', on: true },
{ id: 'ds3', name: '质检结果库', on: true },
{ id: 'ds4', name: '历史归档库', on: false }
];
var SQL1 = 'SELECT lot_no, temperature, operator_name, measured_at\nFROM process_readings\nWHERE line_code = :line_code\n AND measured_at >= :since\n AND temperature >= :min_temp\nORDER BY measured_at DESC';
var SQL1_V2 = 'SELECT lot_no, temperature, measured_at\nFROM process_readings\nWHERE line_code = :line_code\n AND measured_at >= :since';
var SQL1_V1 = 'SELECT lot_no, temperature\nFROM process_readings\nWHERE line_code = :line_code';
var P_LINE = { name: 'line_code', type: 'string', req: true, def: '' };
var P_SINCE = { name: 'since', type: 'datetime', req: false, def: '2026-11-17 00:00:00' };
var P_MIN = { name: 'min_temp', type: 'number', req: false, def: '0' };
function clone(x) { return JSON.parse(JSON.stringify(x)); }
function ver(no, at, sql, params, outputs, idents, timeout, maxRows) {
return { no: no, at: at, by: 'admin.demo', sql: sql, params: clone(params), outputs: clone(outputs), idents: idents.slice(), timeout: timeout, maxRows: maxRows };
}
var QUERIES = [
{ id: 1, name: '产线温度采样', desc: '示例:按产线与时间窗取最近温度读数(虚构)', ds: 'ds1', on: true, updated: '2026-11-18 09:40',
sql: SQL1, params: [P_LINE, P_SINCE, P_MIN],
outputs: [{ name: 'lot_no', type: 'string' }, { name: 'temperature', type: 'number' }, { name: 'operator_name', type: 'string' }, { name: 'measured_at', type: 'datetime' }],
idents: ['process_readings', 'lot_no', 'temperature', 'operator_name', 'measured_at'], timeout: 5000, maxRows: 200, versions: [] },
{ id: 2, name: '设备停机记录', desc: '示例:按设备编码取停机事件(虚构)', ds: 'ds2', on: true, updated: '2026-11-17 16:05',
sql: 'SELECT equipment_code, stop_reason, stopped_at, duration_min\nFROM equipment_downtime\nWHERE equipment_code = :equipment_code\n AND stopped_at >= :since',
params: [{ name: 'equipment_code', type: 'string', req: true, def: '' }, P_SINCE],
outputs: [{ name: 'equipment_code', type: 'string' }, { name: 'stop_reason', type: 'string' }, { name: 'stopped_at', type: 'datetime' }, { name: 'duration_min', type: 'integer' }],
idents: ['equipment_downtime'], timeout: 3000, maxRows: 100, versions: [] },
{ id: 3, name: '质检不良统计', desc: '示例:按批次汇总不良代码,尚未发布(虚构)', ds: 'ds3', on: false, updated: '2026-11-16 11:22',
sql: 'SELECT defect_code, COUNT(*) AS cnt\nFROM qc_results\nWHERE batch_no = :batch_no\nGROUP BY defect_code',
params: [{ name: 'batch_no', type: 'string', req: true, def: '' }],
outputs: [{ name: 'defect_code', type: 'string' }, { name: 'cnt', type: 'integer' }],
idents: ['qc_results'], timeout: 5000, maxRows: 200, versions: [] },
{ id: 4, name: '在制批次清单', desc: '示例:当前在制批次(虚构)', ds: 'ds1', on: true, updated: '2026-11-15 08:50',
sql: 'SELECT lot_no, step_code, started_at\nFROM wip_lots\nWHERE line_code = :line_code',
params: [P_LINE],
outputs: [{ name: 'lot_no', type: 'string' }, { name: 'step_code', type: 'string' }, { name: 'started_at', type: 'datetime' }],
idents: ['wip_lots'], timeout: 5000, maxRows: 500, versions: [] }
];
(function seed() {
var q1 = QUERIES[0], q2 = QUERIES[1], q4 = QUERIES[3];
q1.versions = [
ver(3, '2026-11-18 09:40', SQL1, q1.params, q1.outputs, q1.idents, 5000, 200),
ver(2, '2026-11-14 15:20', SQL1_V2, [P_LINE, P_SINCE], [{ name: 'lot_no', type: 'string' }, { name: 'temperature', type: 'number' }, { name: 'measured_at', type: 'datetime' }], ['process_readings'], 5000, 100),
ver(1, '2026-11-10 10:02', SQL1_V1, [P_LINE], [{ name: 'lot_no', type: 'string' }, { name: 'temperature', type: 'number' }], ['process_readings'], 3000, 50)
];
q2.versions = [ver(1, '2026-11-17 16:05', q2.sql, q2.params, q2.outputs, q2.idents, 3000, 100)];
q4.versions = [
ver(2, '2026-11-15 08:50', q4.sql, q4.params, q4.outputs, q4.idents, 5000, 500),
ver(1, '2026-11-12 13:30', q4.sql, q4.params, q4.outputs.slice(0, 2), q4.idents, 5000, 200)
];
})();
var state = {
role: 'admin', screen: 'list', cur: 1, ver: 3, draft: null, pvals: {}, preview: null,
sim: 'success', fsub: 'timeout', flash: null, dirty: false, modal: false,
focusPreview: false, scrollPreview: false, refocus: null, timer: null, nextId: 5
};
function $(id) { return document.getElementById(id); }
function isAdmin() { return state.role === 'admin'; }
function esc(s) { return String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); }
function later(text) { return text + ' <span class="drop-later">正式版本进行删除</span>'; }
function qById(id) { for (var i = 0; i < QUERIES.length; i++) if (QUERIES[i].id === id) return QUERIES[i]; return QUERIES[0]; }
function curQ() { return qById(state.cur); }
function dsName(id) { for (var i = 0; i < DS.length; i++) if (DS[i].id === id) return DS[i].name; return '—'; }
function verOf(q, no) { for (var i = 0; i < q.versions.length; i++) if (q.versions[i].no === no) return q.versions[i]; return q.versions[0]; }
function latestNo(q) { return q.versions.length ? q.versions[0].no : 0; }
function isCreate() { return state.screen === 'create'; }
function isVersion() { return state.screen === 'version'; }
/* ---------- draft / preview params ---------- */
function blankDraft() {
return { name: '', desc: '', ds: 'ds1', sql: '', params: [], outputs: [], idents: [], timeout: 5000, maxRows: 200 };
}
function loadDraft(id) {
var q = qById(id);
state.draft = { name: q.name, desc: q.desc, ds: q.ds, sql: q.sql, params: clone(q.params), outputs: clone(q.outputs), idents: q.idents.slice(), timeout: q.timeout, maxRows: q.maxRows };
state.dirty = false;
}
function sourceParams() { return isVersion() ? verOf(curQ(), state.ver).params : state.draft.params; }
function initPvals() {
state.pvals = {};
sourceParams().forEach(function (p) { state.pvals[p.name] = p.def || ''; });
}
function setPath(path, val) {
var parts = path.split('.'), o = state, i;
for (i = 0; i < parts.length - 1; i++) o = o[parts[i]];
o[parts[parts.length - 1]] = val;
}
/* ---------- prototype toolbar ---------- */
function screenOn(id) {
var s = state.screen, q = qById(state.cur);
if (id === 'edit') return s === 'edit' && q.on;
if (id === 'editoff') return s === 'edit' && !q.on;
return s === id;
}
function renderProto() {
var r = '', s = '', k, b = '';
for (k in ROLES) r += '<button class="proto-btn' + (state.role === k ? ' on' : '') + '" data-role="' + k + '">' + ROLES[k] + '</button> ';
$('p-roles').innerHTML = r;
SCREENS.forEach(function (x) { s += '<button class="proto-btn' + (screenOn(x[0]) ? ' on' : '') + '" data-screen="' + x[0] + '">' + x[1] + '</button> '; });
$('p-screens').innerHTML = s;
RESULT_KINDS.forEach(function (x) { b += '<button class="proto-btn' + ((state.preview || 'none') === x[0] ? ' on' : '') + '" data-result="' + x[0] + '">' + x[1] + '</button> '; });
$('p-results').innerHTML = b;
var o = '';
FSUB.forEach(function (x) { o += '<option value="' + x[0] + '"' + (state.fsub === x[0] ? ' selected' : '') + '>' + x[1] + '</option>'; });
$('p-fsub').innerHTML = o;
$('who-role').textContent = ROLES[state.role];
$('nav-q').className = 'nav-item' + (isAdmin() ? ' cur' : ' off');
}
/* ---------- shared pieces ---------- */
function banner() {
return '<div class="local-banner">' + later('原型本地模拟:此页面不会向任何服务发送请求,「保存草稿」「发布」「试跑预览」等只会切换本页的演示状态。') + '</div>' +
(state.flash ? '<div class="flash ' + state.flash[0] + '">' + esc(state.flash[1]) + '</div>' : '');
}
function setCrumb(leaf) {
var html = 'Watchman / <b>查询</b>';
if (leaf) html += ' / <b>' + leaf + '</b>';
$('crumb').innerHTML = html;
}
function setFoot(actions) {
var foot = $('pagefoot');
foot.hidden = !actions;
foot.innerHTML = actions || '';
}
function statusCell(q) {
return q.on ? '<span class="status"><span class="dot"></span>启用</span>' : '<span class="status off"><span class="dot"></span>已停用</span>';
}
function verCell(q) { return q.versions.length ? 'v' + latestNo(q) : '<span class="hint">未发布</span>'; }
function listTable(rows) {
var h = '<div class="table-wrap"><table><thead><tr>' +
'<th>名称</th><th>数据源</th><th>状态</th><th>最新版本</th><th>更新时间</th><th>操作</th></tr></thead><tbody>';
rows.forEach(function (q) {
var dsOff = false;
h += '<tr class="' + (q.on ? '' : 'off') + '"><td>' + esc(q.name) + '</td><td>' + esc(dsName(q.ds)) + '</td><td>' + statusCell(q) +
'</td><td class="mono">' + verCell(q) + '</td><td class="mono">' + q.updated + '</td><td class="ops">' +
'<button class="btn link" data-act="open" data-id="' + q.id + '">打开</button>' +
'<button class="btn link"' + (q.on && !dsOff ? ' data-act="preview" data-id="' + q.id + '"' : ' disabled title="已停用,不能预览"') + '>预览</button>' +
'</td></tr>';
});
return h + '</tbody></table></div>';
}
/* ---------- schema editors ---------- */
function typeSelect(path, val, ro) {
var h = '<select data-bind="' + path + '"' + (ro ? ' disabled' : '') + '>';
TYPES.forEach(function (t) { h += '<option' + (t === val ? ' selected' : '') + '>' + t + '</option>'; });
return h + '</select>';
}
function paramsEditor(ps, ro) {
var h = '';
if (!ro) h += '<div class="tbl-tools"><button class="btn sm" data-act="add-param">添加参数</button></div>';
if (!ps.length) return h + '<div class="empty sm"><p>尚未声明参数。SQL 中的 :name 必须在此声明,未声明的参数会被拒绝。</p></div>';
h += '<div class="table-wrap inner"><table><thead><tr><th>参数名</th><th>类型</th><th>必填</th><th>默认值</th>' + (ro ? '' : '<th>操作</th>') + '</tr></thead><tbody>';
ps.forEach(function (p, i) {
var b = 'draft.params.' + i;
if (ro) {
h += '<tr><td class="mono">' + esc(p.name) + '</td><td class="mono">' + p.type + '</td><td>' + (p.req ? '是' : '否') + '</td><td class="mono">' + (p.def === '' ? '<span class="hint">—</span>' : esc(p.def)) + '</td></tr>';
} else {
h += '<tr><td><input type="text" class="mono" data-bind="' + b + '.name" value="' + esc(p.name) + '" placeholder="例如 line_code"></td>' +
'<td>' + typeSelect(b + '.type', p.type) + '</td>' +
'<td><input type="checkbox" data-bind="' + b + '.req"' + (p.req ? ' checked' : '') + '></td>' +
'<td><input type="text" data-bind="' + b + '.def" value="' + esc(p.def) + '" placeholder="可空"></td>' +
'<td class="ops"><button class="btn link danger" data-act="del-param" data-i="' + i + '">删除</button></td></tr>';
}
});
return h + '</tbody></table></div>';
}
function outputsEditor(os, ro) {
var h = '';
if (!ro) h += '<div class="tbl-tools"><button class="btn sm" data-act="add-out">添加输出字段</button></div>';
if (!os.length) return h + '<div class="empty sm"><p>尚未声明输出字段。输出契约用于检查结果类型。</p></div>';
h += '<div class="table-wrap inner"><table><thead><tr><th>字段名</th><th>类型</th>' + (ro ? '' : '<th>操作</th>') + '</tr></thead><tbody>';
os.forEach(function (o, i) {
var b = 'draft.outputs.' + i;
if (ro) h += '<tr><td class="mono">' + esc(o.name) + '</td><td class="mono">' + o.type + '</td></tr>';
else h += '<tr><td><input type="text" class="mono" data-bind="' + b + '.name" value="' + esc(o.name) + '" placeholder="例如 lot_no"></td>' +
'<td>' + typeSelect(b + '.type', o.type) + '</td>' +
'<td class="ops"><button class="btn link danger" data-act="del-out" data-i="' + i + '">删除</button></td></tr>';
});
return h + '</tbody></table></div>';
}
function identsBlock(ids, ro) {
var h = '<div class="chips">';
if (!ids.length) h += '<span class="hint">无(不允许动态标识符)</span>';
ids.forEach(function (t, i) {
h += '<span class="chip">' + esc(t) + (ro ? '' : '<button title="移除" data-act="del-ident" data-i="' + i + '">×</button>') + '</span>';
});
h += '</div>';
if (!ro) h += '<div class="ident-add"><input type="text" id="f-ident-input" placeholder="输入标识符后按回车,例如 process_readings"><button class="btn" data-act="add-ident">添加</button></div>';
h += '<div class="hint" style="margin-top:6px">' + later('标识符(表/字段名)不能作为绑定参数的值;只有这里声明的名称允许出现在 SQL 的标识符位置,留空即不允许。占位语法待维护者确认。') + '</div>';
return h;
}
/* ---------- SQL chips (live) ---------- */
function detectParams(sql) {
var out = [], re = /(^|[^:\w]):([A-Za-z_]\w*)/g, m;
while ((m = re.exec(sql || ''))) if (out.indexOf(m[2]) < 0) out.push(m[2]);
return out;
}
function chipsHtml(sql, params) {
var used = detectParams(sql), declared = params.map(function (p) { return p.name; }), h = '';
if (!used.length) return '<span class="hint">SQL 中尚未使用 :参数。</span>';
h += '<span class="hint">SQL 中的参数:</span>';
used.forEach(function (n) {
h += declared.indexOf(n) >= 0 ? '<span class="chip ok">:' + esc(n) + '</span>' : '<span class="chip bad" title="未在参数 schema 中声明,保存会被拒绝">:' + esc(n) + ' 未声明</span>';
});
declared.forEach(function (n) { if (n && used.indexOf(n) < 0) h += '<span class="chip dim" title="已声明但 SQL 中未使用">' + esc(n) + ' 未使用</span>'; });
return h;
}
function refreshChips() {
var el = $('sql-chips');
if (el && state.draft) el.innerHTML = chipsHtml(state.draft.sql, state.draft.params);
}
/* ---------- preview ---------- */
function pvInputs(ps) {
if (!ps.length) return '<div class="hint" style="margin-bottom:12px">该查询没有声明参数,可直接试跑。</div>';
var h = '<div class="pv-grid">';
ps.forEach(function (p) {
var v = state.pvals[p.name] == null ? '' : state.pvals[p.name], inp;
if (p.type === 'boolean') {
inp = '<select data-bind="pvals.' + p.name + '"><option value=""' + (v === '' ? ' selected' : '') + '>(未填)</option><option value="true"' + (v === 'true' ? ' selected' : '') + '>true</option><option value="false"' + (v === 'false' ? ' selected' : '') + '>false</option></select>';
} else {
inp = '<input type="' + (p.type === 'integer' || p.type === 'number' ? 'number' : 'text') + '" data-bind="pvals.' + p.name + '" value="' + esc(v) + '" placeholder="' + (p.type === 'datetime' ? 'YYYY-MM-DD HH:MM:SS' : '') + '">';
}
h += '<div class="field"><label><span class="mono">' + esc(p.name) + '</span> · ' + p.type + (p.req ? '<span class="req">*</span>' : '') + '</label>' + inp + '</div>';
});
return h + '</div>';
}
function refreshPvParams() {
var el = $('pv-params');
if (el) el.innerHTML = pvInputs(sourceParams());
}
function maskCol(n) { return /operator|person|user/i.test(n); }
function sampleVal(o, i) {
if (maskCol(o.name)) return '张**';
if (o.type === 'integer') return String(i * 3 + 2);
if (o.type === 'number') return (71.2 + i * 0.8).toFixed(1);
if (o.type === 'boolean') return i % 2 ? 'true' : 'false';
if (o.type === 'datetime') return '2026-11-18 08:' + (10 + i * 5) + ':00';
return o.name === 'lot_no' ? 'LOT-100' + i : o.name + '-' + i;
}
function successTable(outs) {
var h = '<div class="table-wrap r-table"><table><thead><tr>';
outs.forEach(function (o) { h += '<th>' + esc(o.name) + (maskCol(o.name) ? ' <span class="tag warn">脱敏</span>' : '') + '</th>'; });
h += '</tr></thead><tbody>';
for (var i = 1; i <= 3; i++) {
h += '<tr>';
outs.forEach(function (o) { h += '<td class="mono">' + esc(sampleVal(o, i)) + '</td>'; });
h += '</tr>';
}
return h + '</tbody></table></div>';
}
function contextInfo() {
var q = curQ();
if (isVersion()) { var v = verOf(q, state.ver); return { outs: v.outputs, timeout: v.timeout, maxRows: v.maxRows, dsId: q.ds, label: '版本 v' + v.no + '(已冻结)' }; }
var d = isCreate() ? state.draft : q; return { outs: d.outputs, timeout: d.timeout, maxRows: d.maxRows, dsId: d.ds, label: '草稿(已保存内容)' };
}
function resultPanel(kind) {
var q = curQ(), c = contextInfo(), dsn = dsName(c.dsId);
var limits = 'timeout_ms=' + c.timeout + ' · max_rows=' + c.maxRows;
var foot = '仅预览:不创建报警、不发送通知、不进入正式运行';
if (kind === 'running') {
return '<div class="result pend"><div class="r-title"><span class="spin"></span>试跑中</div><div class="r-body">' + later('正在试跑「' + esc(q.name) + '」(本地模拟,未发出任何请求)…') + '</div></div>';
}
if (kind === 'success') {
return '<div class="result ok"><div class="r-title">试跑成功</div><div class="r-body">返回 3 行样例,列符合输出契约。标记「脱敏」的列按简单策略遮盖。</div>' +
successTable(c.outs) +
'<div class="r-meta">' + later('耗时示意 0.32 秒(虚构) · ' + limits + ' · 数据源 ' + esc(dsn)) + '<br>' + foot + '</div></div>';
}
if (kind === 'empty') {
return '<div class="result grey"><div class="r-title">空结果</div><div class="r-body">查询已成功执行,但没有符合条件的行。这不是失败,也不是类型错误。</div>' +
'<div class="r-meta">' + later('耗时示意 0.18 秒(虚构) · ' + limits) + '<br>' + foot + '</div></div>';
}
if (kind === 'illegal_type') {
var col = null, i;
for (i = 0; i < c.outs.length; i++) if (c.outs[i].type !== 'string') { col = c.outs[i]; break; }
if (!col) col = c.outs[0] || { name: 'value', type: 'integer' };
var exp = col.type === 'string' ? 'integer' : col.type;
return '<div class="result warn"><div class="r-title">输出类型不匹配</div><div class="r-body">查询已执行,但返回值与输出契约不符,整批结果不视为合法输出。</div>' +
'<div class="table-wrap r-table"><table><thead><tr><th>行</th><th>字段</th><th>契约类型</th><th>实际值(样例)</th></tr></thead><tbody>' +
'<tr><td class="mono">2</td><td class="mono">' + esc(col.name) + '</td><td class="mono">' + exp + '</td><td class="mono">"N/A"(字符串)</td></tr>' +
'<tr><td class="mono">5</td><td class="mono">' + esc(col.name) + '</td><td class="mono">' + exp + '</td><td class="mono">"--"(字符串)</td></tr>' +
'</tbody></table></div>' +
'<div class="r-meta">' + later('共 2 处不匹配(虚构) · ' + limits) + '<br>' + foot + '</div></div>';
}
if (kind === 'failure') {
var f = {
timeout: ['执行超时', '超过 timeout_ms=' + c.timeout + ' 仍未返回,已中止查询。可缩小时间窗或调整限制后重试。', '超时不是 SQL 语法错误,也不是类型不匹配'],
connection: ['连接失败', '无法连接到数据源「' + dsn + '」。', '连接类失败会计入该数据源的熔断统计(与 M03 一致)'],
syntax: ['SQL 语法错误', '源库拒绝了该 SQL:near "FORM"(虚构示例)。请检查 SQL 模板。', '语法错误不属于连接失败,不计入熔断统计']
}[state.fsub];
return '<div class="result bad"><div class="r-title">试跑失败 · ' + f[0] + '</div><div class="r-body">' + esc(f[1]) + '</div>' +
'<div class="r-meta">' + later(f[2] + ' · ' + limits) + '<br>' + foot + '</div></div>';
}
if (kind === 'disabled') {
var body = !q.on ? '查询「' + q.name + '」已停用,不能试跑。请先在页脚「启用」。' : '所绑定的数据源「' + dsn + '」已停用,不能试跑。';
return '<div class="result warn"><div class="r-title">已停用,未执行</div><div class="r-body">' + esc(body) + '</div>' +
'<div class="r-meta">' + later('被拒绝时不会向源库发起任何查询。') + '</div></div>';
}
if (kind === 'circuit_open') {
return '<div class="result bad"><div class="r-title">数据源熔断中,未执行</div><div class="r-body">数据源「' + esc(dsn) + '」当前熔断开闸,不会向源库发起查询。预计恢复时间 2026-11-18 15:10(示意)。</div>' +
'<div class="r-meta">' + later('熔断由数据源侧连续失败触发;此处不绕过熔断。') + '</div></div>';
}
return '<div class="note">' + later('尚未试跑。填写参数后点击页脚「试跑预览」可演示结果(本地模拟)。') + '</div>';
}
function previewCard() {
var ver_ = isVersion(), c = contextInfo();
var h = '<div class="card' + (state.focusPreview ? ' focus' : '') + '" id="pv-card"><h3>试跑预览<span class="sub">仅返回样例,不进入报警</span></h3>';
h += '<div class="pv-target">预览对象:<b>' + c.label + '</b>' + (ver_ ? '' : '') + '</div>';
if (!ver_) h += '<div class="note warn" id="pv-dirty" style="margin-bottom:10px"' + (state.dirty ? '' : ' hidden') + '>' + later('当前有未保存修改;预览使用已保存的草稿,不含这些修改(待确认)。') + '</div>';
h += '<div id="pv-params">' + pvInputs(sourceParams()) + '</div>';
h += '<div id="pv-result">' + resultPanel(state.preview || 'none') + '</div>';
return h + '</div>';
}
/* ---------- versions ---------- */
function versionsCard(q, hlNo) {
var h = '<div class="card"><h3>版本<span class="sub">仅已发布版本;发布请使用页脚「发布」</span></h3>';
if (isCreate()) return h + '<div class="empty sm"><p>保存草稿并发布后,版本会出现在这里。</p></div></div>';
if (!q.versions.length) return h + '<div class="empty sm"><p>尚未发布。发布后会生成 v1,且内容不可再改。</p></div></div>';
h += '<div class="table-wrap"><table><thead><tr><th>版本</th><th>发布时间</th><th>发布人</th><th>数据库限制</th><th>操作</th></tr></thead><tbody>';
q.versions.forEach(function (v, idx) {
h += '<tr class="' + (v.no === hlNo ? 'hl' : '') + '"><td class="mono">v' + v.no + (idx === 0 ? ' <span class="tag ok">最新</span>' : '') + '</td><td class="mono">' + v.at + '</td><td class="mono">' + v.by +
'</td><td class="mono">timeout ' + v.timeout + ' / rows ' + v.maxRows + '</td><td class="ops"><button class="btn link" data-act="openver" data-no="' + v.no + '">打开</button></td></tr>';
});
return h + '</tbody></table></div></div>';
}
/* ---------- footers ---------- */
function footEdit() {
var q = curQ(), create = isCreate(), h = '';
h += '<button class="btn" data-act="list">返回列表</button>';
h += '<button class="btn primary" data-act="save">保存草稿</button>';
h += create ? '<button class="btn" disabled title="请先保存草稿">发布</button>' : '<button class="btn outline" data-act="publish">发布</button>';
if (!create) h += q.on ? '<button class="btn danger" data-act="toggle">停用</button>' : '<button class="btn" data-act="toggle">启用</button>';
h += create ? '<button class="btn" disabled title="请先保存草稿">试跑预览</button>' : '<button class="btn" data-act="run"' + (state.preview === 'running' ? ' disabled' : '') + '>试跑预览</button>';
return h;
}
function footVersion() {
return '<button class="btn" data-act="list">返回列表</button><button class="btn" data-act="draft">返回草稿</button>' +
'<button class="btn" data-act="run"' + (state.preview === 'running' ? ' disabled' : '') + '>试跑预览</button>';
}
/* ---------- screens ---------- */
function vDenied() {
setCrumb(''); setFoot('');
return banner() + '<div class="empty"><h3>无法进入查询</h3><p>只有管理者可以进入查询界面。</p>' +
'<p class="hint" style="margin:0">' + later('后端返回 42000,并带缺失的权限点 perm:data:emp:watchman.query.read。') + '</p></div>';
}
function vEmpty() {
setCrumb(''); setFoot('');
return banner() + '<div class="list-actions"><button class="btn primary" data-act="create">新建</button></div>' +
'<div class="empty"><h3>还没有查询</h3><p>管理者可以新建第一个查询定义:选择数据源,写参数化 SQL,声明参数与输出契约。</p></div>';
}
function vList() {
setCrumb(''); setFoot('');
return banner() + '<div class="list-actions"><button class="btn primary" data-act="create">新建</button></div>' + listTable(QUERIES) +
'<p class="hint" style="margin-top:10px">' + later('已停用的行保持可见,「预览」置灰;「打开」进入草稿详情。分页/筛选未在需求中确认,原型未做。') + '</p>';
}
function basicCard() {
var d = state.draft, q = curQ(), create = isCreate(), dsOpts = '';
DS.forEach(function (x) {
dsOpts += '<option value="' + x.id + '"' + (d.ds === x.id ? ' selected' : '') + (x.on ? '' : ' disabled') + '>' + x.name + (x.on ? '' : '(已停用)') + '</option>';
});
var st = create ? '<span class="hint">新建后默认启用</span>' : statusCell(q) + ' <span class="hint">· 通过页脚「' + (q.on ? '停用' : '启用') + '」切换</span>';
return '<div class="card"><h3>基本信息' + (create ? '<span class="sub">草稿</span>' : '<span class="sub">草稿 · 最新已发布 ' + (q.versions.length ? 'v' + latestNo(q) : '无') + '</span>') + '</h3>' +
'<div class="form-grid">' +
'<div class="field"><label>名称<span class="req">*</span></label><input type="text" data-bind="draft.name" value="' + esc(d.name) + '" placeholder="租户内唯一"></div>' +
'<div class="field"><label>数据源<span class="req">*</span></label><select data-bind="draft.ds">' + dsOpts + '</select>' +
'<span class="hint">' + later('仅可选择可用的数据库数据源;已停用的灰显不可选。') + '</span></div>' +
'<div class="field full"><label>用途说明</label><textarea rows="2" data-bind="draft.desc">' + esc(d.desc) + '</textarea></div>' +
'<div class="field"><label>状态</label><div>' + st + '</div></div>' +
'</div></div>';
}
function sqlCard() {
var d = state.draft;
return '<div class="card"><h3>SQL 模板</h3>' +
'<div class="field"><textarea class="sql" rows="8" data-bind="draft.sql" spellcheck="false" placeholder="SELECT lot_no FROM process_readings WHERE line_code = :line_code">' + esc(d.sql) + '</textarea>' +
'<span class="hint">' + later('使用命名参数,例如 :line_code,值一律参数绑定,不拼接进 SQL。不靠 SELECT 前缀判定安全,是否只读由数据源账户与执行器保证。') + '</span></div>' +
'<div class="chips" id="sql-chips">' + chipsHtml(d.sql, d.params) + '</div></div>';
}
function limitsCard() {
var d = state.draft;
return '<div class="card"><h3>执行限制</h3><div class="form-grid">' +
'<div class="field"><label>timeout_ms<span class="req">*</span></label><input type="number" data-bind="draft.timeout" value="' + esc(d.timeout) + '"></div>' +
'<div class="field"><label>max_rows<span class="req">*</span></label><input type="number" data-bind="draft.maxRows" value="' + esc(d.maxRows) + '"></div>' +
'<div class="field full"><span class="hint">' + later('服务端有上限封顶(示意:timeout_ms ≤ 30000,max_rows ≤ 1000,具体值以后端为准),表单填过大会被拒绝。') + '</span></div>' +
'</div></div>';
}
function vEdit() {
var create = isCreate(), q = curQ(), d = state.draft;
setCrumb(create ? '新建' : '详情');
setFoot(footEdit());
var h = banner();
if (!create && !q.on) h += '<div class="note warn" style="margin-bottom:14px">该查询已停用。仍可查看与编辑草稿,但不能试跑预览;可在页脚「启用」。</div>';
h += basicCard() + sqlCard();
h += '<div class="card"><h3>参数 schema<span class="sub">命名参数 · 未知参数拒绝</span></h3>' + paramsEditor(d.params, false) + '</div>';
h += '<div class="card"><h3>输出 schema<span class="sub">输出契约 · 用于检查结果类型</span></h3>' + outputsEditor(d.outputs, false) + '</div>';
h += '<div class="card"><h3>允许的标识符</h3>' + identsBlock(d.idents, false) + '</div>';
h += limitsCard();
h += previewCard();
h += versionsCard(q, 0);
h += '<div class="card"><h3>引用<span class="sub">场景尚未落地</span></h3><div class="empty sm"><p>尚无引用</p></div></div>';
return h;
}
function vVersion() {
var q = curQ(), v = verOf(q, state.ver);
setCrumb('详情 / 版本 v' + v.no);
setFoot(footVersion());
var h = banner();
h += '<div class="note" style="margin-bottom:14px">版本 v' + v.no + ' 已冻结,内容不可修改。更正需回到草稿修改后发布新版本;这里仍可试跑预览。</div>';
h += '<div class="card"><h3>版本信息<span class="sub"><span class="tag grey">只读</span></span></h3><dl class="kv">' +
'<dt>查询</dt><dd>' + esc(q.name) + '</dd><dt>版本</dt><dd class="mono">v' + v.no + (v.no === latestNo(q) ? ' <span class="tag ok">最新</span>' : '') + '</dd>' +
'<dt>发布时间</dt><dd class="mono">' + v.at + '</dd><dt>发布人</dt><dd class="mono">' + v.by + '</dd><dt>数据源</dt><dd>' + esc(dsName(q.ds)) + '</dd></dl></div>';
h += '<div class="card"><h3>SQL 模板<span class="sub">冻结</span></h3><pre class="sql">' + esc(v.sql) + '</pre></div>';
h += '<div class="card"><h3>参数 schema<span class="sub">冻结</span></h3>' + paramsEditor(v.params, true) + '</div>';
h += '<div class="card"><h3>输出 schema<span class="sub">冻结</span></h3>' + outputsEditor(v.outputs, true) + '</div>';
h += '<div class="card"><h3>允许的标识符<span class="sub">冻结</span></h3>' + identsBlock(v.idents, true) + '</div>';
h += '<div class="card"><h3>执行限制<span class="sub">冻结</span></h3><dl class="kv"><dt>timeout_ms</dt><dd class="mono">' + v.timeout + '</dd><dt>max_rows</dt><dd class="mono">' + v.maxRows + '</dd></dl></div>';
h += previewCard();
h += versionsCard(q, v.no);
return h;
}
/* ---------- modal ---------- */
function renderModal() {
var root = $('modal-root');
if (!state.modal) { root.innerHTML = ''; return; }
var q = curQ(), next = latestNo(q) + 1;
root.innerHTML = '<div class="modal-mask"><div class="modal"><h3>确认发布 v' + next + '?</h3>' +
'<p>将把当前已保存的草稿固化为不可变版本 v' + next + '。发布后不能修改或删除,更正需发布新版本。</p>' +
'<div class="row"><button class="btn" data-act="cancel-pub">取消</button><button class="btn primary" data-act="confirm-pub">确认发布</button></div>' +
'<p class="hint" style="margin:10px 0 0">' + later('未来用 ElMessageBox 确认。') + '</p></div></div>';
}
/* ---------- render / navigation ---------- */
function render(resetScroll) {
renderProto();
var view = $('view'), st = view.scrollTop, s = state.screen, h;
if (!isAdmin()) h = vDenied();
else if (s === 'empty') h = vEmpty();
else if (s === 'list') h = vList();
else if (s === 'create' || s === 'edit') h = vEdit();
else if (s === 'version') h = vVersion();
else h = vList();
view.innerHTML = h;
renderModal();
sizeShell();
view.scrollTop = resetScroll ? 0 : st;
if (state.scrollPreview || state.focusPreview) {
var pc = $('pv-card');
if (pc) pc.scrollIntoView({ block: state.focusPreview ? 'start' : 'nearest' });
state.scrollPreview = false;
}
if (state.refocus) { var f = $(state.refocus); if (f) f.focus(); state.refocus = null; }
}
function sizeShell() {
$('shell').style.setProperty('height', 'calc(100vh - ' + $('proto').offsetHeight + 'px)');
}
function clearTimer() { if (state.timer) { clearTimeout(state.timer); state.timer = null; } }
function go(screen, flash) {
clearTimer();
state.screen = screen;
state.flash = flash || null;
state.preview = null;
state.modal = false;
if (screen === 'create') { state.draft = blankDraft(); state.dirty = false; initPvals(); }
else if (screen === 'edit') { loadDraft(state.cur); initPvals(); }
else if (screen === 'version') { initPvals(); }
render(true);
}
function setFlash(cls, text, keepScroll) { state.flash = [cls, text]; render(!keepScroll); }
/* ---------- actions ---------- */
function validate() {
var d = state.draft, i, names = [];
if (!String(d.name).trim()) return '名称必填。';
for (i = 0; i < QUERIES.length; i++) if (QUERIES[i].name === d.name.trim() && (isCreate() || QUERIES[i].id !== state.cur)) return '租户内名称已存在:' + d.name.trim() + '。';
if (!String(d.sql).trim()) return 'SQL 模板必填。';
for (i = 0; i < d.params.length; i++) {
var n = d.params[i].name;
if (!/^[A-Za-z_]\w*$/.test(n)) return '参数名不合法:' + (n || '(空)') + '。';
if (names.indexOf(n) >= 0) return '参数名重复:' + n + '。';
names.push(n);
}
var used = detectParams(d.sql);
for (i = 0; i < used.length; i++) if (names.indexOf(used[i]) < 0) return 'SQL 含未声明参数 :' + used[i] + ',未知参数会被拒绝。';
for (i = 0; i < d.outputs.length; i++) if (!/^[A-Za-z_]\w*$/.test(d.outputs[i].name)) return '输出字段名不合法:' + (d.outputs[i].name || '(空)') + '。';
var t = Number(d.timeout), r = Number(d.maxRows);
if (!(t >= 1 && t <= 30000)) return 'timeout_ms 需在 1~30000 之间(示意上限)。';
if (!(r >= 1 && r <= 1000)) return 'max_rows 需在 1~1000 之间(示意上限)。';
return null;
}
function doSave() {
var err = validate();
if (err) { setFlash('bad', '无法保存:' + err); return; }
var d = state.draft, q;
if (isCreate()) {
q = { id: state.nextId++, versions: [], on: true };
QUERIES.push(q);
state.cur = q.id;
} else q = curQ();
q.name = d.name.trim(); q.desc = d.desc; q.ds = d.ds; q.sql = d.sql;
q.params = clone(d.params); q.outputs = clone(d.outputs); q.idents = d.idents.slice();
q.timeout = Number(d.timeout); q.maxRows = Number(d.maxRows); q.updated = NOW;
if (state.screen === 'create') { go('edit', ['ok', '草稿已保存(本地模拟)。']); return; }
loadDraft(q.id);
setFlash('ok', '草稿已保存(本地模拟)。');
}
function doPublish() {
if (state.dirty) { setFlash('warn', '有未保存修改,请先保存草稿再发布。'); return; }
var q = curQ();
if (!q.sql || !q.sql.trim()) { setFlash('bad', '无法发布:草稿 SQL 为空。'); return; }
state.modal = true; renderModal();
}
function confirmPublish() {
var q = curQ(), no = latestNo(q) + 1;
q.versions.unshift(ver(no, NOW, q.sql, q.params, q.outputs, q.idents, q.timeout, q.maxRows));
q.updated = NOW;
state.modal = false;
setFlash('ok', '已发布 v' + no + '(本地模拟)。版本内容已冻结,继续修改草稿不影响它。');
}
function runPreview() {
clearTimer();
state.preview = 'running'; state.scrollPreview = true; render();
state.timer = setTimeout(function () {
state.timer = null; state.preview = !curQ().on ? 'disabled' : state.sim; state.scrollPreview = true; render();
}, 1000);
}
function pickResult(kind) {
clearTimer();
if (kind !== 'none' && kind !== 'running') state.sim = kind;
if (state.screen !== 'edit' && state.screen !== 'version') {
if (!isAdmin()) { render(); return; }
state.cur = state.cur || 1; go('edit');
}
state.preview = kind === 'none' ? null : kind;
state.scrollPreview = true; render();
}
/* ---------- events ---------- */
document.addEventListener('click', function (e) {
var t = e.target.closest('button');
if (!t || t.disabled) return;
if (t.hasAttribute('data-role')) { state.role = t.getAttribute('data-role'); render(); return; }
if (t.hasAttribute('data-screen')) {
var sc = t.getAttribute('data-screen');
if (sc === 'edit') { state.cur = state.cur === 3 ? 1 : state.cur; go('edit'); }
else if (sc === 'editoff') { state.cur = 3; go('edit'); }
else if (sc === 'version') { state.cur = state.cur === 3 ? 1 : state.cur; state.ver = latestNo(curQ()); go('version'); }
else go(sc);
return;
}
if (t.hasAttribute('data-result')) { pickResult(t.getAttribute('data-result')); return; }
var act = t.getAttribute('data-act');
if (!act) return;
var i = +t.getAttribute('data-i'), d = state.draft;
switch (act) {
case 'list': go('list'); break;
case 'create': go('create'); break;
case 'open': state.cur = +t.getAttribute('data-id'); go('edit'); break;
case 'preview': state.cur = +t.getAttribute('data-id'); state.focusPreview = true; go('edit'); state.focusPreview = false; break;
case 'draft': go('edit'); break;
case 'openver': state.ver = +t.getAttribute('data-no'); go('version'); break;
case 'save': doSave(); break;
case 'publish': doPublish(); break;
case 'confirm-pub': confirmPublish(); break;
case 'cancel-pub': state.modal = false; renderModal(); break;
case 'toggle': var q = curQ(); q.on = !q.on; q.updated = NOW; state.preview = null; setFlash('ok', q.on ? '已启用(本地模拟)。' : '已停用(本地模拟)。已发布版本不受影响。'); break;
case 'run': runPreview(); break;
case 'add-param': d.params.push({ name: '', type: 'string', req: false, def: '' }); state.dirty = true; render(); break;
case 'del-param': d.params.splice(i, 1); state.dirty = true; initPvalsKeep(); render(); break;
case 'add-out': d.outputs.push({ name: '', type: 'string' }); state.dirty = true; render(); break;
case 'del-out': d.outputs.splice(i, 1); state.dirty = true; render(); break;
case 'del-ident': d.idents.splice(i, 1); state.dirty = true; render(); break;
case 'add-ident': addIdent(); break;
}
});
function initPvalsKeep() {
var old = state.pvals; state.pvals = {};
sourceParams().forEach(function (p) { state.pvals[p.name] = old[p.name] != null ? old[p.name] : (p.def || ''); });
}
function addIdent() {
var el = $('f-ident-input'), v = el ? el.value.trim() : '';
if (!v) return;
if (!/^[A-Za-z_][\w.]*$/.test(v)) { state.refocus = 'f-ident-input'; setFlash('warn', '标识符只能包含字母、数字、下划线和点:' + v, true); return; }
if (state.draft.idents.indexOf(v) < 0) state.draft.idents.push(v);
state.dirty = true; state.refocus = 'f-ident-input'; render();
}
function onBind(e) {
var el = e.target, path = el.getAttribute && el.getAttribute('data-bind');
if (!path) return;
var val = el.type === 'checkbox' ? el.checked : el.value;
setPath(path, val);
if (path.indexOf('draft.') === 0) {
state.dirty = true;
var pd = $('pv-dirty'); if (pd) pd.hidden = false;
if (path === 'draft.sql' || /^draft\.params\./.test(path)) refreshChips();
if (e.type === 'change' && /^draft\.params\./.test(path)) { initPvalsKeep(); refreshPvParams(); }
}
}
document.addEventListener('input', onBind);
document.addEventListener('change', function (e) {
if (e.target.id === 'p-fsub') { state.fsub = e.target.value; if (state.preview === 'failure') render(); return; }
onBind(e);
});
document.addEventListener('keydown', function (e) {
if (e.key === 'Enter' && e.target.id === 'f-ident-input') { e.preventDefault(); addIdent(); }
});
window.addEventListener('resize', sizeShell);
render(true);
})();
</script>
</body>
</html>
+105
View File
@@ -0,0 +1,105 @@
# M04 查询定义与采集 Requirement
## Goal
维护者能在控制台维护受控查询草稿(参数化 SQL、参数 schema、输出契约、执行限制),发布不可变版本,并对草稿或已发布版本做只读预览试跑。预览区分空结果、非法类型与执行失败;不进入报警/通知,也不承担场景定时采集。
## Background
- 模块:`docs/tasks/INDEX.md` M04;覆盖旧细项 A-016~A-020;需求 A-02。
- 前置:M03 DONE_LOCAL。数据源 usable/熔断见 D23;查询执行必须调用 `assert_usable` 与失败记账入口。
- 决策:D14 RLS;D19 三角色;D22 按钮/密码框约定;**D24** 本模块口径(参数化 SQL + 不可变版本 + 预览边界)。
- 门禁:`gatePolicy.selected=autonomous`;Vue 前 HTML 原型确认。
## In Scope
- `query_definitions`:租户内名称唯一;绑定可用数据库数据源;草稿 SQL/参数 schema/输出契约/限制;启停。
- `query_versions`:`publish` 从当前草稿拷贝不可变快照;`(definition_id, version_no)` 唯一;内容禁止改写/删除字段更新。
- 参数:命名参数绑定;未知参数拒绝;类型/必填/默认值校验。
- 标识符:不可作绑定值的表/字段等仅允许白名单(本阶段可先支持固定占位语法或显式允许列表字段,禁止任意拼接)。
- 只读执行器:超时、最大行数;不靠 `SELECT` 前缀判定安全;平台库事务与源库查询分离。
- 预览 API/UI:草稿预览与指定版本预览;空/非法类型/失败三分;样例脱敏;不写正式报警。
- 权限:仅 admin 的 read/write/publish/preview。
- 引用:查询定义/版本 references 返回空列表+稳定占位;数据源 references 可列出引用它的查询(只读提示)。
- 控制台:列表、编辑草稿、发布、版本只读、试跑预览;布局遵守 D22/`docs/current/frontend-ui.md`。
- 审计:创建、更新草稿、启停、发布、预览(预览审计不含结果全文/秘密)。
## Out Of Scope
- 结构化表/字段选择器(非参数化 SQL)。
- 任意脚本、eval、动态拼 SQL 条件串。
- 字段映射、规则判定、报警、企微、场景 Cron 正式采集(M05/M06/M07/M08)。
- 非数据库数据源执行。
- 绕过熔断直连源库。
- 真实 MES/生产库写入;口令或预览全文入库外日志/仓库。
- 查询物理删除(本阶段停用即可)。
## Required Behavior
- 有权限用户可 CRUD 草稿;停用后仍可查看,不可预览执行(或明确拒绝并提示);可再启用。
- `publish` 生成递增 `version_no`;历史版本只读;草稿可继续改,不影响已发布快照。
- 预览前 `assert_usable(datasource)`;源停用或熔断开闸则拒绝预览并记账策略与 M03 业务失败一致(连接类失败计入熔断)。
- 参数含 SQL 片段时仍参数绑定,不形成结构注入。
- 多行/多对象结果可返回;不在本模块串联报警。
- 空结果、输出契约类型不匹配、超时/连接/语法类失败分开展示。
- 跨租户不可见。无会话 41000;非 admin 42000 且带权限点。
## User Flow
1. 管理者打开查询列表。
2. 新建:选数据源、用途、SQL 模板、参数与输出契约、限制 → 保存草稿。
3. 可对草稿试跑预览(填参数)。
4. 发布 → 生成版本;可查看版本列表与只读详情;可对版本试跑。
5. 继续改草稿不影响已发布版本;再次发布得到新版本号。
6. 停用定义后不可作为后续场景候选(约定字段/列表过滤);本阶段场景未落地,提供稳定 `enabled` 语义即可。
## Business Rules
- 租户内 `name` 唯一。无物理删除。
- 版本内容不可变;更正靠新版本。
- 预览不创建报警、不发送通知、不推进正式 run 业务状态机(若写 run_records 须明确 `sample`/试跑标记且默认不做;本轮预览结果仅 API 响应)。
- 最新已发布版本号可空(从未发布)。
- 数据源被引用时,数据源 references 返回查询条目;查询侧 references 仍可空(场景未到)。
## Data Rules
- 租户服务端注入;表启用 RLS。
- SQL/参数/输出/限制可回显给有权限用户;源库口令永不回显。
- 预览响应可含样例行,敏感列按输出契约或简单脱敏策略处理;日志不得落完整结果集或口令。
## API Contract(摘要)
- `GET/POST /queries`,`GET/PATCH /queries/{id}`,`POST .../enable|disable`,`POST .../publish`
- `GET /queries/{id}/versions`,`GET /queries/{id}/versions/{version_no}`
- `POST /queries/{id}/preview`(草稿),`POST /queries/{id}/versions/{version_no}/preview`
- `GET /queries/{id}/references`
- 统一信封;错误码沿用平台约定。
## Permission Nodes
- `perm:data:emp:watchman.query.read`
- `perm:data:emp:watchman.query.write`
- `perm:data:emp:watchman.query.publish`
- `perm:data:emp:watchman.query.preview`
## Acceptance Criteria
- A-016:参数/输出/限制 schema;未知字段拒绝。
- A-017:绑定、只读账户前提(配置层)、超时与行数限制;不靠 SELECT 前缀。
- A-018:空/失败/非法类型分开;样例脱敏。
- A-019:列表与编辑 UI;越权不可保存。
- A-020:试跑预览 UI;不进入正式报警。
- 不可变版本:发布后历史不可改;新发布递增版本号。
- V009/V010/V011 口径的自动化或集成测试有证据。
## Assumptions
- 首版白名单机制:禁止通过参数改写标识符;若 SQL 需动态标识符,仅接受定义时声明的允许标识符集合(可为空=不允许动态标识符)。
- 默认限制:超时与 max_rows 有服务端上限封顶,防止表单填过大。
- 原型确认前不改正式 Vue 查询页;用户确认计划并要求执行全部切片后,S4 产出原型,S5 在原型落地后实现(若原型与冻结 UX 一致则连续推进)。
## Risks And Stop Conditions
- 注入/任意 SQL 风险:执行器与评审必查。
- 迁移/权限/熔断边界:`risk_score>=4` 切片在 autonomous 下仍停片际确认(实现后片审再续)。
- 禁止真实生产库破坏性操作;禁止秘密入库。
@@ -0,0 +1,30 @@
# M04 MUST-FIX Recheck
## Verdict
PASS
## Scope
Bounded recheck of the two MUST-FIX findings in `review-module-m04.md`; this is not a new module-wide review.
## Findings Closed
1. **Immutable query versions — closed.**
- Migration `20261118_0007` revokes `UPDATE`/`DELETE` from `watchman_app` and installs a statement-level `BEFORE UPDATE OR DELETE OR TRUNCATE` rejection trigger.
- The trigger also rejects mutations attempted by the migrator/table-owner, so a later privilege grant cannot bypass the append-only boundary.
- Regression coverage verifies app-role Core and ORM mutation failures, unchanged stored SQL, allowed inserts, and owner-side update/delete/truncate rejection.
2. **SQL Server preview write risk — closed.**
- `run_query` refuses SQL Server immediately after datasource usability checks, before template validation, secret decryption, or any source connection, with `engine_readonly_unsupported`.
- `queries/drivers.py` has no SQL Server runner, so direct `fetch_rows` calls also fail without opening a connection. The M03 connectivity probe remains separate and unchanged.
- Regression coverage exercises SELECT, UPDATE, DELETE, and `EXEC` refusal plus the API outcome and no-connection path.
## Validation
- `uv run pytest tests/test_query_versions.py tests/test_query_execute.py tests/test_query_api.py -q`
- Result: **194 passed**; one pre-existing dependency deprecation warning from Starlette `TestClient`.
## Notes
No new high-severity issue was found in these remediations.
@@ -0,0 +1,46 @@
# M04 Module Review
## Verdict
FAIL
## Must-fix
1. **Published versions are not actually immutable at the persistence boundary** (confidence: 100)
- **Location:** `services/watchman/migrations/versions/20261118_0006_query_definitions.py:42`; `services/watchman/src/watchman/services/query_versions.py:23`; `services/watchman/src/watchman/services/queries.py:385`
- The migration grants `watchman_app` `UPDATE` on `query_versions` and installs no trigger or database rule to reject updates. The only guard is the standalone `forbid_version_content_mutation()` helper, but no production write path calls it. Any present or future application code using a SQLAlchemy session can therefore alter a published SQL snapshot and commit it.
- This violates D24's immutable-published-version requirement despite the absence of an HTTP update route.
- **Fix:** enforce append-only versions at the database boundary (for example, revoke UPDATE/DELETE for the application role, or add an update/delete-rejecting trigger with a narrowly controlled maintenance path). Add an integration test that attempts a direct ORM/Core update and proves it is rejected.
2. **SQL Server previews can execute writes when the saved datasource credentials have write access** (confidence: 98)
- **Location:** `services/watchman/src/watchman/queries/drivers.py:260`
- PostgreSQL and MySQL establish a read-only transaction before executing the submitted template. The SQL Server runner sends the template directly via `cur.execute(sql, params)` and has no equivalent server-side read-only transaction or application gate. `DataSource.read_only_intent` is only stored/displayed and is never checked or verified before execution (`services/watchman/src/watchman/services/datasources.py:303`, `services/watchman/src/watchman/queries/execute.py:151`).
- A single-statement `UPDATE`, `DELETE`, DDL, or an executing stored procedure is accepted by the template parser and will mutate a SQL Server datasource whenever its configured login has write privileges. Parameter binding prevents value injection; it does not make arbitrary SQL read-only. This violates the read-only-preview boundary.
- **Fix:** do not allow SQL Server preview until a server-enforced read-only execution method is available, or require and verify a least-privileged read-only login as an executable precondition. Add a live SQL Server regression test proving a write statement cannot change data.
## Should-fix
None.
## Notes
- Review covered the supplied M04 backend, API/auth, datasource-reference, frontend, tests, migrations, and task/documentation scope.
- The reviewed API routes correctly restrict query operations to `watchman-admin`; parameter values are bound rather than text-spliced; preview outcomes keep empty, illegal-type, and failure distinct; and preview audit payloads omit SQL, parameters, and rows.
- Existing test results were provided by the orchestrator. This review did not re-run them.
## Remediation
Both must-fix findings were addressed (no commit made).
1. **Immutable `query_versions` at the DB boundary** — new migration `20261118_0007_query_versions_immutable`:
- `REVOKE UPDATE, DELETE` on `query_versions` from `watchman_app`; `SELECT, INSERT` re-asserted.
- Statement-level `BEFORE UPDATE OR DELETE OR TRUNCATE` trigger (`trg_query_versions_append_only`) that always raises `restrict_violation` (23001), so it also stops the table owner and any future grant, even when forced RLS hides all rows.
- Downgrade drops trigger and function and restores the 0006 grants (round-trip upgrade/downgrade/upgrade verified locally).
- Tests (`test_query_versions.py`): app-role privilege matrix; Core and ORM UPDATE/DELETE fail with SQLSTATE 42501 and the stored SQL is unchanged; INSERT of a new version still works; the owner (migrator) is rejected by the trigger for UPDATE/DELETE/TRUNCATE.
- Because the app role can no longer delete versions, test cleanup now uses a superuser purge (`tests/_privileged_cleanup.py`, `session_replication_role = replica`); there is no application maintenance path.
2. **SQL Server read-only boundary** — chosen fix: refuse, do not gate on statement text.
- `run_query` returns `failure_kind = engine_readonly_unsupported` (fixed safe message, no details from the driver) for `engine == "sqlserver"` right after `assert_usable`, before validation, secret decryption or any connection. The circuit is untouched.
- `_run_sqlserver` was removed from `queries/drivers.py`, so `fetch_rows` also raises `UnsupportedDataSourceError` for SQL Server: no write path exists even if the guard were bypassed. The M03 probe (`datasources/probe.py`) is unchanged.
- Tests: `run_query` on a sqlserver datasource is refused for SELECT, UPDATE, DELETE and EXEC with no driver/secret access; `fetch_rows("sqlserver")` opens nothing; an API preview test confirms the refusal outcome and a single audit event.
Validation: `uv run pytest` in `services/watchman` — 456 passed. Not covered: a live SQL Server test (none needed, since execution is refused); the frontend has not been checked for display of the new `failure_kind`.
@@ -0,0 +1,32 @@
# M04 Slice S1 Review Note (coder self-check)
Status: implemented; awaiting independent review (not a review verdict).
## Files created
- `services/watchman/src/watchman/models/query.py` — `QueryDefinition`, `QueryVersion`, `VERSION_CONTENT_COLUMNS`
- `services/watchman/migrations/versions/20261118_0006_query_definitions.py` — revises `20261118_0005`
- `services/watchman/src/watchman/services/query_versions.py` — `forbid_version_content_mutation`, `assert_version_immutable`
- `services/watchman/tests/test_query_versions.py` — 28 tests
## Files changed
- `services/watchman/src/watchman/models/__init__.py` — export new models
## Design notes
- `datasource_id` and `definition_id` FKs are `ON DELETE RESTRICT`; extra index `ix_query_definitions_datasource_id`.
- Both tables: ENABLE + FORCE RLS, `tenant_isolation` policy, full CRUD grant to `watchman_app`.
- `query_versions` has no `updated_at`. Immutability is enforced only by the service helper (frozen: content columns plus `tenant_id`, `definition_id`, `version_no`, `published_at`, `published_by`). It is NOT enforced at DB level because UPDATE is granted per the slice spec; direct SQL/ORM writes bypass the helper. Later slices must route all version writes through the service layer. A DB trigger is a possible hardening for the reviewer to consider.
- `latest_published_version_no` is not FK-linked to `query_versions` (set by publish logic in S3).
## Validation
- `uv run alembic upgrade head` — PASS (to `20261118_0006`); downgrade to `0005` then upgrade again — PASS.
- `uv run pytest tests/test_query_versions.py` — 28 passed.
- `uv run pytest` (full) — 290 passed, 1 pre-existing deprecation warning.
- No real passwords; datasource rows use a placeholder ciphertext and synthetic host/user.
## Scope check
- Only `models/`, `migrations/`, `services/query_versions.py` (explicitly requested), `tests/` touched. No API routes, executor, frontend, M03 circuit changes, or git commits.
@@ -0,0 +1,71 @@
# M04 Slice S2 — 只读执行器:实现自检记录
状态:实现完成,待独立 review(本文件是 coder 自检,不是独立审查结论)。未 commit。
## 变更文件
新增:
- `services/watchman/src/watchman/queries/__init__.py`(边界说明、导出)
- `services/watchman/src/watchman/queries/result.py`(`QueryRunResult`、状态/failure_kind 常量)
- `services/watchman/src/watchman/queries/schema.py`(param/output schema 解析、值类型校验)
- `services/watchman/src/watchman/queries/template.py`(模板扫描、`:name` 绑定、`{{ident}}` 白名单、单语句检查)
- `services/watchman/src/watchman/queries/drivers.py`(PG/MySQL/SQL Server 单语句执行与失败分类)
- `services/watchman/src/watchman/queries/execute.py`(`run_query` 编排)
- `services/watchman/tests/test_query_execute.py`
修改(薄改):
- `services/watchman/src/watchman/services/datasources.py`:新增 `build_probe_target(row)`、`record_connection_failure(session, datasource_id, category)`;未改既有函数。
未触碰:路由、前端、`query_definitions` schema/迁移、`.env*`。
## 行为摘要
`run_query` 顺序:`assert_usable` → 限制/schema/参数/标识符校验 → 内存解密 → `commit`(网络调用期间不持有事务)→ 执行(`max_rows+1`)→ 分类。
| 情形 | status | failure_kind |
| --- | --- | --- |
| 有行且符合输出契约 | success | — |
| 0 行 | empty | — |
| 声明列类型不符(details 仅含字段名/期望类型/实际 Python 类型名/首个违规行号,不含值) | illegal_type | — |
| 数据源停用/熔断打开(不连接、不读密钥) | failure | disabled / circuit_open |
| 校验失败(未知参数、缺必填、类型错、`{{x}}` 不在白名单、多语句、非法限制/schema) | failure | validation |
| 连接 auth/timeout/unreachable/rejected | failure | auth_failed / timeout / unreachable / rejected,**记入熔断** |
| 连接中途断开 | failure | unreachable,**记入熔断** |
| 语句超时(PG statement_timeout/MySQL read_timeout) | failure | timeout,**不记熔断** |
| SQL 语法/运行错误 | failure | sql_error(PG 附 SQLSTATE),**不记熔断** |
| 超过 `max_rows` | failure | limit_exceeded(不返回行) |
- 绑定:模板 `:name` → `%(name)s` 由驱动绑定;`::` 转型、字符串/引号标识符/注释/PG `$$` 内的 `:name`、`{{}}` 不当作占位符;无参数时不转义 `%`,有参数时转义为 `%%`。参数值不可能成为标识符(测试覆盖)。
- 白名单:`{{ident}}` 必须在 `allowed_identifiers` 且匹配 `^[A-Za-z_][A-Za-z0-9_]*$`,按引擎加引号(`"x"` / `` `x` `` / `[x]`);空列表=不允许;校验发生在连接之前。
- 只读:PG 用 `BEGIN READ ONLY` + `SET LOCAL statement_timeout`,结束 rollback;MySQL `SET SESSION TRANSACTION READ ONLY` + `START TRANSACTION READ ONLY` + 尽力设置 `MAX_EXECUTION_TIME`;SQL Server 无会话级只读,依赖只读账户(A-017 配置层前提)。不以 `SELECT` 前缀判定安全。额外加了“必须单语句”的结构检查(允许末尾 `;`)。
- 限制:`timeout_ms`/`max_rows` 必须是 ≥1 的 int,超过 `MAX_TIMEOUT_MS`/`MAX_ROWS_LIMIT` 被封顶;其余视为 `validation`。
- 日志:仅记录引擎、数据源 id、状态、行数;不记口令、连接串、参数值、结果集。
## 验证
- `uv run pytest tests/test_query_execute.py`:71 passed(含对 `WATCHMAN_TEST_PG_*` 本地源库的真实执行:绑定防注入、`%` 转义、类型参数、空/illegal_type/sql_error 三分、行数上限、语句超时不记熔断、会话只读(CREATE TABLE 被拒、`transaction_read_only=on`)、错误口令 auth_failed 记账、端口不可达记账)。
- `uv run pytest`(全量):361 passed,无失败。
- 覆盖要求映射:参数含 SQL 片段不改结构(模板测试+fake+live);空/失败/illegal_type 区分;disabled/circuit 拒绝且驱动未被调用;未知参数;`{{ident}}` 不在白名单/空白名单拒绝。
- MySQL 仅用 fake 驱动测试(连接 auth 映射、只读 SET、语法错误、连接丢失 vs read_timeout);SQL Server 未做任何自动化测试(无环境);二者的真实库行为 **NOT_RUN**。
## 设计决定/需要 reviewer 与用户确认的点
1. **`nullish` 语义未在需求中定义**:当前实现为“该列不做类型约束”;另外 SQL `NULL` 对所有声明类型都通过类型检查(认为 NULL 是缺值而非类型错误)。若产品想要“只能为 NULL”或“非 NULL 才算合法”,需改 `schema.check_output_value`。
2. **成功不记账**:按任务说明只对连接类失败调用 `record_probe_outcome`(`update_last_test=False`,不改 `last_test_*`);成功的预览不会重置失败计数。
3. **语句超时不算连接类失败**:慢查询/运行时超时不开闸;连接阶段超时和连接丢失才记入。MySQL `read_timeout` 与连接中途断开在驱动层难区分,按“超时链→timeout(不记);2006/2013 无超时链→unreachable(记)”处理。
4. **`param_schema[].required` 缺省为 true**(更严格);`required=true` 且带 `default` 时,缺参仍拒绝(按字面规则)。`boolean` 严格要求 bool(MySQL tinyint 返回 int 会判 illegal_type);`integer` 不接受 Decimal。
5. **`run_query` 内部 `commit`**:校验失败/连接失败记账后都会 commit,以免熔断计数随调用方丢弃结果而丢失;S3 路由无需再为熔断额外提交,但应知道会话已被提交。
6. `run_query` 对查询类问题**返回** `QueryRunResult`,不抛错;`NotFoundError`(未知数据源)和 `DatasourceSecretUnavailableError` 仍向上抛,由 S3 映射信封。
7. `drivers.py` 复用了 `watchman.datasources.probe` 的私有分类助手(`_classify_after_failure` 等),使连接失败分类与探测一致;若后续希望公开,可在 probe 中提升为公共 API(本片未改 probe)。
8. 结果行中 `Decimal→float`、`bytes→hex`、日期时间→ISO 字符串、其他→`str`;输出契约之外的列原样返回(脱敏策略留给 S3/预览层)。
9. 同名重复列只保留最后一个值(dict)。
## 残余风险
- 只读保证依赖数据库账户权限:PG 事务内用户 SQL 无法在单语句内切回读写,但仍应使用只读账户(配置层)。
- 无参数模板时 psycopg 可能走简单协议;已由“单语句”结构检查约束,但该检查是词法级的,不是完整 SQL 解析。
- SQL Server 路径无自动化证据。
## 文档同步
无设计语义变化需要更新 `docs/`;M04 任务卡进度由主 Agent 更新。
@@ -0,0 +1,82 @@
# M04 Slice S3 — API、权限、引用回填:实现自检记录
状态:实现完成,待独立 review(本文件是 coder 自检,不是独立审查结论)。未 commit。
## 变更文件
新增:
- `services/watchman/src/watchman/services/queries.py`(定义 CRUD、启停、publish、版本读取、预览编排、序列化)
- `services/watchman/src/watchman/api/routes/queries.py`(`/queries` 路由,`extra="forbid"` 请求模型)
- `services/watchman/tests/test_query_api.py`(84 个用例)
修改:
- `auth/access.py`:四个节点常量 + `require_query_read/write/publish/preview`(仅 `watchman-admin`)
- `auth/principal.py`:`require_query_reader/writer/publisher/previewer`;把 `_load_session_roles` 的会话读取抽成 `_load_session`(返回 login_name + roles,行为不变);`require_query_publisher` 返回 login_name 供 `published_by`
- `api/app.py`:注册 `queries.router`
- `services/datasources.py`:`list_references` 回填查询条目 `{type:"query", id, name, enabled}`,按 name 排序,仅本租户
- `api/routes/datasources.py`:仅 references 路由 docstring
未触碰:S1 模型/迁移、`query_versions.py`、`queries/` 执行器包、前端、`.env*`、`docs/`。
## 路由与契约
| 路由 | 权限 | 说明 |
| --- | --- | --- |
| `GET /queries?enabled=` | read | 摘要列表(不含草稿内容) |
| `POST /queries` | write | 创建启用的未发布定义 |
| `GET /queries/{id}` | read | 摘要 + `draft{sql_template,param_schema,output_schema,allowed_identifiers,timeout_ms,max_rows}`,含 `latest_published_version_no` |
| `PATCH /queries/{id}` | write | name/description/datasource_id/草稿六字段;不含 enabled 与任何版本字段 |
| `POST /{id}/disable|enable` | write | |
| `POST /{id}/publish` | publish | 返回完整冻结版本 |
| `GET /{id}/versions`、`/{id}/versions/{n}` | read | 摘要(新→旧)/完整内容 |
| `POST /{id}/preview`、`/{id}/versions/{n}/preview` | preview | body `{params:{}}`(可省略,`extra=forbid`) |
| `GET /{id}/references` | read | `{id, items: []}` |
- 输入字段名用 `sql_template` 等(不带 `draft_`),输出放在 `draft` 对象里,键名相同,便于 GET → PATCH 往返。
- 未知/越权字段(tenant_id、enabled、version_no、published_by、latest_published_version_no、`draft_*`)→ 40000。
- 版本无任何 PATCH/PUT/DELETE/POST 路由(测试断言 404/405);唯一写入门(定义 PATCH)拒绝版本形字段。
- 信封、错误码沿用既有:无会话 41000;非 admin 42000 + `permission_node`;404 用 `NotFoundError`(含跨租户、非法 UUID);重名 409 `duplicate_name`;预览停用 409 `reason=disabled`。
## 行为摘要
- **创建/PATCH 校验**:复用 S2 `parse_param_schema/parse_output_schema/parse_allowed_identifiers`(未知键、重复、非法类型→40000 reason);SQL 模板不得全空白;`timeout_ms/max_rows` 必须是 ≥1 的严格 int(拒绝 bool/0/负数),超过服务端上限按 S2 口径**封顶**(不拒绝);数据源须存在于本租户且 `kind=database`,否则 400(`datasource_not_found`/`datasource_not_database`)。不对 SQL 模板做深度解析(模板问题在预览中以 `failure/validation` 呈现)。
- **publish**:锁定定义行(`FOR UPDATE`)→ 重新校验草稿 → `version_no = (latest or 0)+1` → 只 INSERT 版本行,复制 draft 六字段 → 更新 `latest_published_version_no`;`published_by` = 会话 `login_name`(截断 128)。版本行没有任何更新路径;`UNIQUE(definition_id, version_no)` 兜底并发(映射 409 `version_conflict`)。停用的定义仍可发布。
- **预览**:先断言定义启用(否则 409,不运行、不审计)→ 把草稿/版本内容拷出 ORM 对象(`run_query` 会 commit)→ 调 S2 `run_query`(定义当前绑定的数据源)→ 写审计 → 路由 commit。`QueryRunResult` 映射:
- `success`/`empty`:`columns, rows, row_count, masked_columns`
- `illegal_type`:`columns, details.fields`(仅字段名/类型,无值)
- `failure`:`failure_kind, details`
- 失败的运行是 HTTP 200 的结果(`status=failure`),不是 API 错误。
- **样例脱敏**:输出契约没有敏感标记,采用按列名的简单策略(`password/pwd/secret/token/credential/api_key/private_key/id_card/phone/mobile/email`,大小写不敏感),非 NULL 值替换为 `***`,并返回 `masked_columns`。S2 说明过脱敏留给本层。
- **审计**:`query.create`(id,name,datasource_id)、`query.update`(id,name,**字段名列表**,无 SQL)、`query.enable/disable`(id,name)、`query.publish`(id,name,version_no)、`query.preview`(**仅** id、status,版本预览加 version_no;不含 name、SQL、参数、行、消息)。幂等键由服务端生成。
- **数据源 references**:`{id, items:[{type:"query",id,name,enabled}]}`,随查询改绑/停用实时变化,不含其他租户。查询侧 references 仍恒为空。
- 时间戳序列化统一转 UTC ISO(新写入值与重新读取值时区会不同,否则前后不相等)。
## 验证
- `uv run pytest tests/test_query_api.py`:84 passed
- `uv run pytest`(全量):**445 passed**(S2 后基线 361 + 本片 84),无失败;无需网络或真实源库
- 覆盖:节点字符串与角色规则;12 条路由 × 匿名 41000;12 条路由 × 4 类非 admin 42000 带正确节点且数据未变;create/list/get/patch/enable/disable+`?enabled=` 过滤;创建与 PATCH 的未知字段/空值/非法 schema/限制/数据源校验;重名 409;publish v1→v2、草稿后改不影响 v1、版本列表与详情、published_by、审计;版本不可通过任何端点改;预览成功/空/illegal_type/failure 四种形状(fake `run_query`);脱敏;预览审计无数据;版本预览用冻结内容、草稿预览用草稿;停用定义 409 且不运行不审计;真实 `run_query` 的无网络路径(unknown_param 校验失败、数据源停用);查询 references 为空;数据源 references 列出/改绑/停用/跨租户;跨租户 id 404。
- 未运行:对真实源库的 HTTP 预览成功路径(S2 的 live 测试覆盖执行器本身;本片用 fake)。浏览器/前端:不在本片。
## 设计决定/需要 reviewer 与用户确认的点
1. **输入/输出字段命名**:输入 `sql_template…`,输出 `draft.{…}`;S4 原型与 S5 按此口径。若希望扁平 `draft_*` 需改序列化。
2. **版本不快照 datasource_id**:版本预览使用定义**当前**绑定的数据源。若用户后来改绑数据源,旧版本预览会跑在新数据源上。需求未要求版本冻结数据源(S1 表也没有该列);如需冻结应回到 S1 加列。
3. **停用定义仍可发布**,只拒绝预览。需求仅说停用后不可预览。
4. **数据源停用/熔断**在预览中是 `status=failure, failure_kind=disabled|circuit_open`(S2 语义,HTTP 200),而**查询定义停用**是 409。两者故意不同:前者是运行结果,后者是调用前置条件。
5. **绑定数据源时只要求存在且 `kind=database`**,不要求当前 enabled/熔断闭合(那是运行时状态,由 `assert_usable` 把关)。需求写“可用数据库数据源”,如要求创建时必须 usable 需确认。
6. **脱敏策略是列名正则**,可能漏掉不含关键词的敏感列、误伤含关键词的列;输出契约尚无敏感标记。
7. **PATCH 空 body 为成功空操作**(会写一条 `query.update`,`fields: []`),与数据源 PATCH 一致。
8. `principal.py` 的 `_load_session_roles` 被改写为 `_load_session` 的薄包装(行为不变,数据源/平台测试全绿)。
9. `preview` 失败信息只经 S2 的固定文案/安全 details 透出;若 S2 details 扩展含值需同步检查。
10. 没有写权限节点登记到公司 `standards://api/permission-nodes`(本次 sy-standards 检索未执行;节点串按任务指令原样使用)。
## 残余风险
- 预览会对真实源库执行用户 SQL(只读保证依赖 S2 与只读账户);本片未新增任何绕过 `assert_usable` 的路径。
- 并发 publish 依赖行锁+唯一约束;未写并发测试(测试库单进程)。
- `published_by` 取 `login_name`(非 Casdoor subject);如审计需要稳定主体 id 应改为 subject。
## 文档同步
无设计语义变化需要更新 `docs/`;`docs/progress.md`、M04 任务卡、`knowledge-map` 由主 Agent 更新。
@@ -0,0 +1,16 @@
# Review S4 — HTML prototype
## Status
PASS — static prototype delivered for maintainer UX confirmation.
## Files
- `.task/2026-11-18/m04-queries/prototype/index.html`
- `.task/2026-11-18/m04-queries/prototype/README.md`
## Notes
- Covers gate, empty/list, draft edit, version readonly, preview outcome switcher, publish confirm.
- Follows D22 footer/list button rules and M03 prototype interaction pattern.
- User execute-all-todos authorization (2026-11-18): S5 proceeds using prototype defaults documented in README (preview saved draft; disable allows click-then-reject for preview; name-based masking).
@@ -0,0 +1,26 @@
# Review S5 — Vue queries console
## Status
PASS_WITH_WARNINGS — module landed; unit/typecheck verified in session; e2e evidence pending formal S6 run.
## Scope delivered
- `web/apps/console/src/queries/**` — list/edit/gate/version/preview helpers
- Routes under `/queries` in `router.ts`; nav/crumbs in `AppShell.vue`
- `allowsQueries` admin gate in `session.ts`
- Locales (四语言) + `docs/current/frontend-ui.md` 查询节
- Unit specs: validation/payload/client/errors/locales
- E2E: `web/apps/console/e2e/queries.spec.ts` (mocked API)
## UX defaults locked for S5
- Preview saved draft; dirty form disables preview / prompts save before publish
- Disabled: list preview disabled; detail preview click → 409 explanation
- Masking via API `masked_columns`
## Remaining for S6
- Formal Playwright run + screenshots under `docs/evidence/M04/ui/`
- Independent module review across S1–S5
- Full pytest regression
+32
View File
@@ -0,0 +1,32 @@
{
"taskId": "2026-11-18/m04-queries",
"module": "M04",
"title": "查询定义与采集模块",
"type": "feature",
"tier": "L",
"phase": "final-approval",
"allowedToCode": false,
"currentSlice": "S6-done",
"proposedNextSlice": null,
"lastGate": "module-review-pass-awaiting-final-approval",
"status": "VERIFIED_LOCAL",
"gatePolicy": {
"selected": "autonomous",
"effective": "autonomous",
"recommended": "balanced",
"finalApprovalRequired": true,
"allowTaskOverride": true
},
"validation": {
"pytest": "456 passed",
"consoleUnitQueries": "51 passed",
"e2eQueries": "16 passed",
"evidence": "docs/evidence/M04/ui/"
},
"notes": [
"D24 parameterized SQL + immutable versions; formal collection deferred to M08",
"Module review FAIL then remediations: DB append-only versions; SQL Server preview refused",
"Recheck PASS"
],
"updatedAt": "2026-11-18T07:30:00Z"
}
@@ -0,0 +1,42 @@
# Context Pack — m04-version-activate
## Task goal
去掉查询草稿/发布两步;保存即新版本并生效;支持版本激活(列表+详情)。
## Requirement / plan
- `.task/2026-11-18/m04-version-activate/requirement.md`
- `.task/2026-11-18/m04-version-activate/implementation-plan.md`
- D26 in `docs/decisions.md`
## Allowed modification scope
- `services/watchman/src/watchman/models/query.py`
- `services/watchman/src/watchman/services/queries.py`
- `services/watchman/src/watchman/api/routes/queries.py`
- `services/watchman/migrations/versions/20261118_0008_*.py`
- `services/watchman/tests/test_query_*.py`
- `web/apps/console/src/queries/**`
- `web/apps/console/locales/**`
- `web/apps/console/e2e/queries.spec.ts`
- `docs/decisions.md`, `docs/progress.md`, `docs/tasks/M04.md`, `docs/current/frontend-ui.md`
- `.task/active.json` and this task directory
## Forbidden
- Dropping `draft_*` columns
- New permission node codes
- Scene/cron/alarm modules
- Auto commit/push
## Current approved slice
- All slices S1–S4 completed; phase `finalization`.
- Awaiting user final approval for DONE_LOCAL / optional commit.
## Validation
- query* pytest: 201 passed
- console unit `src/queries`: 52 passed
- e2e `queries.spec.ts`: 16 passed
@@ -0,0 +1,10 @@
# Implementation Plan
| Slice | Content | gateClass | risk_score |
|-------|---------|-----------|------------|
| S1 | migration + save-as-version / activate service | boundary-sensitive | 4 |
| S2 | API reshape | standard | 3 |
| S3 | console UI | standard | 3 |
| S4 | tests + docs | standard | 2 |
gatePolicy.selected=balanced(用户批准整份 plan 后连续执行)。
@@ -0,0 +1,28 @@
# M04 增补:去掉草稿 + 版本激活
## Goal
查询定义不再使用「草稿/发布」两步。保存内容即生成不可变新版本并自动设为当前生效;可激活任一历史版本;列表与详情均可切换。
## Decisions
- D26(1=C,2=A):版本切换=激活 `current_version_no`;保存内容=新版本且自动 current。
- 版本行仍不可变(D24 库级约束保留)。`draft_*` 列本轮保留并镜像 current,对外不暴露 draft。
## In Scope
- `current_version_no` 迁移与回填。
- create → v1 + current;save-as-version;activate;去 publish/draft API 形状。
- 控制台:保存/激活/列表切换版本;文案去草稿/发布。
## Out Of Scope
- 物理删除 `draft_*` 列。
- 场景采集(M08)。
- 新权限点编码。
## Acceptance
- 新建保存即有 v1 且为 current;再保存得 v2 且 current=v2。
- 激活旧版后列表/详情/默认预览跟 current。
- UI 无保存草稿/发布/返回草稿;列表可切换版本。
@@ -0,0 +1,22 @@
{
"taskId": "2026-11-18/m04-version-activate",
"type": "feature",
"phase": "done",
"allowedToCode": false,
"currentSlice": "S4",
"completedSlices": ["S1", "S2", "S3", "S4"],
"status": "DONE_LOCAL",
"validation": {
"pytest_query": "201 passed",
"unit_queries": "52 passed",
"e2e_queries": "16 passed"
},
"gatePolicy": {
"selected": "balanced",
"effective": "balanced",
"recommended": "balanced",
"finalApprovalRequired": true,
"allowTaskOverride": true
},
"updatedAt": "2026-11-18T10:31:00Z"
}
@@ -0,0 +1,39 @@
# Module Boundary Summary
## Module Scope
- Target area: 字段映射与规则判断。新的映射、规则、输入修订和试算,挂在已有查询定义上。
- Related areas: 查询定义与只读预览;控制台页面;管理员角色门禁。
- Cross-area impact: 试算会调用查询当前版本的预览。不改查询正文、版本不可变和 SQL Server 拒绝试跑。报警、场景、通知不在本模块落表。
## Modifiability
- Modifiable: `services/watchman` 中新增的映射/规则/输入代码、新迁移、对应测试;确认原型之后的 `web/apps/console` 新页面;`docs/tasks/M05.md`、`docs/progress.md`、`docs/decisions.md`。
- Restricted areas: 查询执行器只可调用,不可放宽只读和 SQL Server 限制。权限检查沿用服务端角色门禁。
- Forbidden areas: 报警、场景、Cron、企微、原因分析;`.env.local`、`.cursor/mcp.json`;生产库和未授权提交。
## Loaded Context
- `docs/project/knowledge-map.md` 的产品范围、公司规范、控制台界面。
- `docs/current/frontend-ui.md` 由 D25 指向,列表和页脚在实现 UI 时读取。
- 未把 `docs/target/` 当作当前行为。
## Dependency Direction
查询定义和预览结果流向映射。映射的列流向规则。规则试算只读这些列。报警以后读取输入身份,本模块不反向依赖报警。
## Boundary Risks
- 身份修订若写成新输入,会把 M06 的去重做坏。
- 权限点不能在需求里编造后直接当已注册编码。
- 迁移版本号与查询迁移串行,不能并行改 `migrations/versions`。
## Recommended Modification Path
1. 先持久化映射和版本,再写身份修订,再写规则结构,再写纯计算。
2. 接口和权限放在计算可用之后。
3. HTML 原型确认后才写 Vue。
## Uncertainty
- 新权限点的注册表里还没有映射/规则编码。实现该切片时再核对规范,对不上就停。
@@ -0,0 +1,133 @@
# Task Context Pack
## Task Goal
实现 M05:查询上的字段映射、可配置身份、结构化规则,以及正常/异常/未知试算。不创建报警。
## Knowledge Posture
- Mode: standard
- Maturity: L1
## Current Slice Or Group
S6 HTML 原型已给出。S7 未批准,须先确认原型。
## Gate Policy
- Recommended: strict
- Selected: autonomous
- finalApprovalRequired: true
- Policy Notes: 配置默认是 balanced。用户指定 autonomous。该选择不取消分析确认、计划 critic、`risk_score >= 4`、原型确认和最终验收。
## Bugfix Context
本任务不是缺陷修复。
## Requirement Source
`.task/2026-11-18/m05-mapping-rules/requirement.md`
## Implementation Source
`.task/2026-11-18/m05-mapping-rules/implementation-plan.md`
## Involved Modules Or Areas
查询定义(只调用预览)、新建映射与规则、控制台新页面、管理员门禁。
## Loaded Context
### Global Rules
`AGENTS.md` 项目本地段要求一个会话聚焦 M05,主 Agent 不代替独立审查。公司规范篇目在写代码前按切片再查最新版本。
### Knowledge Map Matches
产品范围指向 `docs/progress.md`、`docs/decisions.md`。控制台界面指向 `docs/current/frontend-ui.md`,只在 S7 读取。
### Path-Proximity Rules
目标目录下没有另外的 `MODULE_RULES.md`。
### Excluded Context
未读阶段 B/C 文档,未读 Cron 复用文档。那些属于 M08 及以后。
## Loaded Rules
- `AGENTS.md`
- `.cursor/rules/sy-standards.mdc`
- `.cursor/rules/workflow-rules.mdc`
## Loaded Docs
- `docs/tasks/INDEX.md`
- `docs/decisions.md`(D27)
- `需求冻结文档_V1.1_交接稿.md` 第 5~6 章
- `.task/2026-11-18/m05-mapping-rules/boundary.md`
## Execution Mode
- Mode: sequential
- Current Slice Or Group: S6
- Parallel Members: 无
- Fallback Order: S1 到 S8
- Shared Files: `services/watchman/migrations`、`auth/access.py`
- Merge Owner: 主 Agent
- Conflict Resolution Rule: 迁移和权限串行
- Validation Level: slice
## Execution Chain
计划确认 → 计划 critic → S1 → 审查 → 因 S2 为 risk 4 而停下。后续每片按计划里的 gateClass 和 risk_score 决定是否还要单独确认。
## Allowed Modification Scope
确认 S1 之后,只允许计划中 S1 的路径。当前允许的写入只有任务文档。
## Forbidden Modification Scope
报警、场景、Cron、企微、查询只读边界、原型确认前的 Vue、密钥文件。
## Key Existing Classes Or Entrypoints
- 查询:`services/watchman/src/watchman/api/routes/queries.py`、`services/watchman/src/watchman/services/queries.py`
- 权限:`services/watchman/src/watchman/auth/access.py` 中的 `watchman-admin` 与 `perm:data:emp:watchman.query.*`
- 控制台查询页:`web/apps/console/src/queries/`
## Required Behavior
以 requirement.md 的 Business Rules 和 Acceptance Criteria 为准。结论用正常、异常、未知。不勾身份列时多行取第一行并提示跳过行数。
## Non-goals
报警、场景、原因分析、脚本、SQL Server 试跑。
## Implementation Steps
见实现计划。当前不执行。
## Validation Commands
- 后端:在 `services/watchman` 运行 `uv run pytest`
- 迁移:`alembic upgrade head`
- 前端:在 `web/apps/console` 运行 `pnpm test:unit`
- UI 切片另加 Playwright。未跑的命令记为未运行。
## Assumptions
与 requirement.md 的 Assumptions 相同。其中版本方式、嵌套深度 4、普通试算不落库,用户还没单独点名,但是按 D26 和“试算不产生报警”写下的。
## Risks
第一行依赖结果顺序。身份修订不能变成新业务事件。权限点编码实现时再核对。
## Stop Conditions
- 用户尚未确认本计划。
- S1 前的计划 critic 尚未通过。
- S4 前显式停下,即使 S3 已通过。判定语义不自动开写。
- S7 前必须有原型确认。
- 权限点规范与项目先例冲突时停下。
- 最终 DONE_LOCAL 需要用户确认。
@@ -0,0 +1,508 @@
# M05 字段映射与规则判断 Implementation Plan
## Requirement Source
`.task/2026-11-18/m05-mapping-rules/requirement.md`(D27)
## Scope Summary
查询上的映射与规则、可配置身份、正常/异常/未知试算、原型确认后的控制台。不写报警和场景。
## Involved Modules Or Areas
- `services/watchman`:模型、迁移、映射、身份修订、规则校验、判定函数、API、权限。
- `web/apps/console`:仅 S7,且 S6 原型已确认。
- 查询预览只调用,不改只读边界。
## Loaded Rules
- `AGENTS.md` 项目本地段
- `.cursor/rules/sy-standards.mdc`
- `standards://api/permission-nodes?version=1.0.0`
- `standards://api/api-envelope?version=1.1.0`
- 本任务 `gatePolicy.selected=autonomous`,建议 strict
## Loaded Docs
- `docs/tasks/INDEX.md` M05
- `docs/decisions.md` D05、D22、D24、D25、D26、D27
- `docs/current/frontend-ui.md`(UI 切片再读)
- `.task/2026-11-18/m05-mapping-rules/boundary.md`
## Global Forbidden Scope
- 报警、场景、Cron、企微、原因分析、任意脚本
- 放宽 SQL Server 查询试跑或查询只读限制
- 原型确认前修改 `web/apps/console` 的正式页面
- `.env.local`、`.cursor/mcp.json`、凭证、生产库
- `git reset --hard`、未授权 commit
- 把未知写成报警,或把执行失败写成正常/未知
## Execution Strategy
- Complexity: complex
- Default Execution: sequential
- Parallel Execution: not-needed
- Fallback Execution: sequential
- Merge Owner: 主 Agent
- Conflict Resolution Rule: 迁移目录和权限模块串行;后一片不得改前一片已冻结的结论枚举。
开工前先做一次计划 critic。Tier L 的 reviewLevel 为 critic-required,这里把它写成 S1 之前的显式停点。autonomous 不跳过它,也不跳过 `risk_score >= 4` 和原型确认。
## Slice Dependency Graph
| Slice | Depends On | Can Run In Parallel With | Fallback Order | Shared Files | Merge Owner | Conflict Risk |
| --- | --- | --- | --- | --- | --- | --- |
| S1 映射与版本 | 计划确认且 critic 通过 | 无 | 1 | `services/watchman/migrations` | 主 Agent | high |
| S2 身份与修订 | S1 | 无 | 2 | `services/watchman/migrations` | 主 Agent | high |
| S3 规则结构 | S1 | 无 | 3 | `services/watchman/migrations` | 主 Agent | high |
| S4 判定函数 | S3 | 无 | 4 | 无共享迁移 | 主 Agent | low |
| S5 API 与权限 | S2、S4 | 无 | 5 | `auth/access.py` | 主 Agent | high |
| S6 HTML 原型 | S5 的字段口径 | 无 | 6 | `.task/.../prototype` | 主 Agent | low |
| S7 Vue | S6 用户确认原型 | 无 | 7 | `web/apps/console` | 主 Agent | medium |
| S8 模块审查与测试 | S7 | 无 | 8 | 证据目录 | 主 Agent | low |
## Implementation Slices
### Slice 1: 映射模型与不可变版本
#### Goal
能保存映射:所属查询、选用列、类型、身份勾选、乘数和偏移;保存产生不可变版本并设为当前版本。
#### Allowed Modification Scope
- `services/watchman/src/watchman/models/`
- `services/watchman/src/watchman/services/` 中新建的映射服务
- `services/watchman/migrations/versions/`
- `services/watchman/tests/` 中本切片测试
#### Forbidden Scope
- 规则判定、API 路由、前端、报警表
- 既有查询迁移文件的改写
#### Execution
- Mode: sequential
- Depends On: 分析确认,且计划 critic 通过
- Can Run With: 无
- Must Not Run With: 任何其他迁移切片
- Fallback Order: 1
- Shared Files: `services/watchman/migrations`
- Merge Owner: 主 Agent
- Conflict Risk: high
- Gate Class: high-risk
- Risk Score: 4
- Gate Reasons: database-schema, immutable-version
- Validation Level: slice
- Recommended Agent Strategy: 单人实现后独立审查
#### Steps
1. 映射定义、列配置、不可变版本和当前版本指针。新表都带 `tenant_id`,按 `20261118_0006` 的形式 `ENABLE`/`FORCE ROW LEVEL SECURITY`、建立 `tenant_isolation` 策略,并 `GRANT` 给 `watchman_app`。
2. 保存即新版本。历史版本不可更新、不可删除。数据库层沿用 `20261118_0007`:对版本表 `REVOKE UPDATE, DELETE`,并加语句级 BEFORE UPDATE/DELETE/TRUNCATE 触发器。
3. 列类型只接受数值、文本、布尔、日期时间。身份列为布尔标记。每条映射最多一列可标为观测时间,该标记不代替身份列。换算只存乘数和偏移。日期时间列与比较值用 `timestamptz`;无时区的值在进入比较前即为非法,不按机器本地时区解释。比较归一到 UTC。
4. 对照查询当前版本的输出列;缺失列拒绝保存。
#### Validation
- 在 `services/watchman` 运行 `uv run pytest`,至少包含:跨租户读写被拒;对历史映射版本 `UPDATE` 被拒;对历史映射版本 `DELETE` 被拒。
- `alembic upgrade head` 与对应 downgrade 都在真实 PostgreSQL 上跑通。SQLite 不能代替 FORCE RLS。命令没跑就记未运行,不记通过。
#### Done Criteria
- 验收标准 1 的数据侧成立:多列可保存,类型、身份标记和可选观测时间标记可回读。
- 上述跨租户、UPDATE 被拒、DELETE 被拒三条测试实际通过。
- 版本内容不可改,由数据库拒绝证明,不单靠服务层。
#### Rollback Notes
- 向下迁移先 `DROP POLICY`,再删除触发器,然后删除本切片新增表。不改查询表。downgrade 未在真实 PostgreSQL 跑通时,不得宣称可回滚。
### Slice 2: 输入身份与修订
#### Goal
按 D27 持久化输入。勾选身份列时按列值唯一;不勾时每条映射只有一条输入。值变化追加修订,相同值不追加。
#### Allowed Modification Scope
- S1 已建立的映射服务及其测试
- 新的输入/修订模型与迁移
#### Forbidden Scope
- 报警表、判定枚举的报警副作用、前端
#### Execution
- Mode: sequential
- Depends On: S1
- Can Run With: 无
- Must Not Run With: S3 同时写迁移
- Fallback Order: 2
- Shared Files: `services/watchman/migrations`
- Merge Owner: 主 Agent
- Conflict Risk: high
- Gate Class: high-risk
- Risk Score: 4
- Gate Reasons: input-identity, dedup-contract
- Validation Level: slice
- Recommended Agent Strategy: 单人实现后独立审查
#### Steps
1. 唯一约束落在租户、映射加身份值上,不包含度量值和运行号。
2. 不勾身份列时使用固定的映射级身份。
3. 身份列为空的行拒绝形成输入。
4. 度量变化写修订;相同度量不写新修订。
5. 同一次结果里多行身份值相同:按返回顺序保留第一行,其余计入跳过重复行,不写第二条修订。
6. 输入表和修订表同样带 `tenant_id`,按 S1 启用 FORCE RLS、`tenant_isolation` 和 `watchman_app` 授权,并有跨租户被拒测试。修订行追加后禁止 UPDATE/DELETE,强制方式与映射版本相同。
#### Validation
- `uv run pytest`:多身份、第一行策略的持久化入口、同身份重复行只留第一行、修订、重读
#### Done Criteria
- 验收标准 2、3 的持久化侧成立。
- 测试证明运行号不会把同一身份拆开。
#### Rollback Notes
- 向下迁移先 `DROP POLICY`、再删除修订表触发器,然后删除输入表和修订表。不删除映射定义。downgrade 未在真实 PostgreSQL 跑通时,不得宣称可回滚。
### Slice 3: 规则结构校验
#### Goal
保存结构化条件。非法运算符、过深嵌套、空组、文本上的大小比较,在保存时拒绝。不执行用户代码。
#### Allowed Modification Scope
- 规则模型、迁移、校验服务、测试
#### Forbidden Scope
- 判定真值表实现放在 S4
- 前端、报警
#### Execution
- Mode: sequential
- Depends On: S1
- Can Run With: 无
- Must Not Run With: S2 的迁移文件
- Fallback Order: 3
- Shared Files: `services/watchman/migrations`
- Merge Owner: 主 Agent
- Conflict Risk: high
- Gate Class: high-risk
- Risk Score: 4
- Gate Reasons: database-schema, reject-code-execution
- Validation Level: slice
- Recommended Agent Strategy: 单人实现后独立审查
#### Steps
1. 规则属于映射,保存即不可变版本。规则定义和规则版本表带 `tenant_id`,按 S1 启用 FORCE RLS。规则版本在数据库层禁止 UPDATE/DELETE,方式与映射版本相同,并有 UPDATE 被拒、DELETE 被拒测试。
2. 条件节点只含列引用、白名单运算符、比较值和 AND/OR。日期时间比较值必须带时区,缺时区在保存时拒绝。
3. 深度上限 4。比较值类型须与列类型相容。
#### Validation
- `uv run pytest`:拒绝脚本片段、未知运算符、超深树、错误类型比较
#### Done Criteria
- 非法规则不能保存。
- 合法规则回读与提交结构一致。
#### Rollback Notes
- 向下迁移先 `DROP POLICY`、再删除规则版本触发器,然后删除规则表。不删除映射表和输入表。downgrade 未在真实 PostgreSQL 跑通时,不得宣称可回滚。
### Slice 4: 正常/异常/未知计算
#### Goal
纯函数按冻结真值表计算。缺失与非法都得出未知,但原因不同。换算只使用已配置的乘数和偏移。执行失败不进入这三种结论。
#### Allowed Modification Scope
- 判定与映射转换的纯函数及测试
#### Forbidden Scope
- 写报警、改身份唯一约束、前端
#### Execution
- Mode: sequential
- Depends On: S3
- Can Run With: 无
- Must Not Run With: 无
- Fallback Order: 4
- Shared Files: 无
- Merge Owner: 主 Agent
- Conflict Risk: low
- Gate Class: standard
- Risk Score: 3
- Gate Reasons: judgment-semantics, explicit-stop-before-slice
- Validation Level: slice
- Recommended Agent Strategy: 测试先固定真值表,再写函数
S4 固化判定语义。即便上一片是已批准的 S3,开始 S4 前仍停下确认真值表测试范围。autonomous 不跳过这个显式停点。
#### Steps
1. 固定 AND/OR 和比较边界的测试,用 `normal`/`abnormal`/`unknown` 做断言,展示文案仍是正常、异常、未知。
2. 实现转换:缺失保持缺失;非法不变成 0 或空字符串。
3. 未配置换算的单位差记为非法。
4. 多行且无身份列时,计算只用第一行,并返回跳过行数。
5. 零行返回空结果,不返回正常、未知或执行失败。
6. 至少一条跨时区用例:同一时刻的两个带时区值比较为相等;无时区值记为非法。
7. 当前查询版本已删除映射列时,计算拒绝并指出缺失列,不静默跳过。
#### Validation
- `uv run pytest` 覆盖验收标准 4、5、6 的计算部分
#### Done Criteria
- 真值表测试通过。
- 没有一条测试把执行异常断言成未知。
#### Rollback Notes
- 删除判定函数不影响已写入的映射版本。
### Slice 5: API 与权限
#### Goal
管理员可以维护映射、规则并试算。其他角色被拒绝。普通试算不写正式输入。
#### Allowed Modification Scope
- `services/watchman/src/watchman/api/`
- `services/watchman/src/watchman/auth/access.py` 及对应依赖
- API 测试
#### Forbidden Scope
- 新角色名、前端页面、报警路由
- 未对照权限点规范就发明另一套检查
#### Execution
- Mode: sequential
- Depends On: S2、S4
- Can Run With: 无
- Must Not Run With: 无
- Fallback Order: 5
- Shared Files: `auth/access.py`
- Merge Owner: 主 Agent
- Conflict Risk: high
- Gate Class: high-risk
- Risk Score: 4
- Gate Reasons: permissions, api-contract
- Validation Level: slice
- Recommended Agent Strategy: 先核对 `standards://api/permission-nodes?version=1.0.0`,编码与查询模块先例不一致时停
#### Steps
1. 读写和试算只允许 `watchman-admin`。试算复用既有查询预览执行器,不新写一套只读执行。SQL Server 仍拒绝试跑。预览所用权限点先核对规范:能沿用 `perm:data:emp:watchman.query.preview` 就沿用;要新编码时对不上注册表就停。
2. 信封按 `standards://api/api-envelope?version=1.1.0`。
3. 结论码用 `normal`、`abnormal`、`unknown`。界面只显示正常、异常、未知。不把中文词写成数据库枚举。
4. 试算响应分开:结论、缺失、非法、无法形成身份、采用第一行、同身份重复行被跳过、空结果、映射列在当前查询版本中已不存在、执行失败。
5. 查询预览失败时不返回正常或未知。零行不返回正常。
#### Validation
- `uv run pytest`:管理员成功,操作者与查看者拒绝,试算无报警行
#### Done Criteria
- 验收标准 7 的“试算不产生报警”和验收标准 8 成立。
#### Rollback Notes
- 去掉新路由和权限函数。不改查询权限点的含义。
### Slice 6: HTML 原型
#### Goal
用静态页面把映射、规则和试算走通,供确认后再写 Vue。
#### Allowed Modification Scope
- `.task/2026-11-18/m05-mapping-rules/prototype/`
#### Forbidden Scope
- `web/apps/console` 正式页面
#### Execution
- Mode: sequential
- Depends On: S5 的响应字段
- Can Run With: 无
- Must Not Run With: S7
- Fallback Order: 6
- Shared Files: 无
- Merge Owner: 主 Agent
- Conflict Risk: low
- Gate Class: simple
- Risk Score: 2
- Gate Reasons: prototype-before-vue
- Validation Level: slice
- Recommended Agent Strategy: 主 Agent 给出原型并停下等确认
#### Steps
1. 列表、映射表单、规则条件、预览结果。
2. 按钮位置按 D22、D25 的静态结构摆放。
3. 文案使用正常、异常、未知。
#### Validation
- 人工打开原型,核对多列、身份列可空、第一行提示、三种结论。
#### Done Criteria
- 原型覆盖验收标准 1、2、6 的可见部分。
- 用户确认前不开始 S7。
#### Rollback Notes
- 删除原型目录不影响服务。
### Slice 7: Vue 控制台
#### Goal
按已确认原型做控制台页面,接上 S5 的接口。
#### Allowed Modification Scope
- `web/apps/console/src/` 下新建的映射与规则页面、路由和本模块测试
#### Forbidden Scope
- 未确认原型就改页面
- 查询编辑页的行为改变,除非只增加入口链接
#### Execution
- Mode: sequential
- Depends On: S6 的用户确认
- Can Run With: 无
- Must Not Run With: 无
- Fallback Order: 7
- Shared Files: 控制台路由
- Merge Owner: 主 Agent
- Conflict Risk: medium
- Gate Class: standard
- Risk Score: 3
- Gate Reasons: prototype-confirmed, ui-contract
- Validation Level: slice
- Recommended Agent Strategy: 对照 `standards://frontend/frontend-stack` 与 `standards://frontend/element-plus` 的最新版本
#### Steps
1. 实现前重读 `docs/current/frontend-ui.md`。
2. 列表、编辑、试算。
3. 页面按钮位置按 D22、D25。
#### Validation
- `pnpm test:unit`(`web/apps/console`)
- 浏览器走通保存、重开、试算、非管理员不可写
#### Done Criteria
- 验收标准 1、2、6、7 的界面侧成立。
- 试算结果与接口一致。
#### Rollback Notes
- 撤回新页面和路由入口。不删服务端数据。
### Slice 8: 模块审查与正式测试
#### Goal
对 S1~S7 做一次整体独立审查,并在通过的候选上跑正式测试。
#### Allowed Modification Scope
- 审查指出的切片内缺陷
- `docs/tasks/M05.md`、`docs/progress.md`、`docs/evidence/M05/`
#### Forbidden Scope
- 借修复扩大到报警或场景
- 未重新审查就标 DONE_LOCAL
#### Execution
- Mode: sequential
- Depends On: S7
- Can Run With: 无
- Must Not Run With: 无
- Fallback Order: 8
- Shared Files: 证据目录
- Merge Owner: 主 Agent
- Conflict Risk: low
- Gate Class: boundary-sensitive
- Risk Score: 3
- Gate Reasons: module-acceptance
- Validation Level: final
- Recommended Agent Strategy: 审查用与实现不同的模型系列;审查者默认不改代码
#### Steps
1. 独立审查边界、真值表、身份和权限。
2. 修复后再审,最多三轮,然后停下来问。
3. 正式 pytest、前端单测、Playwright 和截图。
#### Validation
- `uv run pytest`
- `pnpm test:unit`
- Playwright 覆盖映射保存、试算三种结论、第一行提示
#### Done Criteria
- 审查通过,命令实际跑过,证据路径写在 `docs/tasks/M05.md`。
- DONE_LOCAL 仍等用户最终确认。
#### Rollback Notes
- 不回滚已通过的迁移,除非审查认定迁移本身错误。那种情况先停。
## Parallel Slice Groups
无。迁移和权限文件串行。
## Final Validation
- 后端 `uv run pytest`
- 控制台 `pnpm test:unit`
- 映射与试算的 Playwright
- 非管理员拒绝的接口测试
## Documentation Update Requirement
- 实现过程更新 `docs/tasks/M05.md` 与 `docs/progress.md`。
- S8 同步 `docs/tasks/INDEX.md` 里 M05 的 PASS/FAIL/UNKNOWN 措辞,改为正常/异常/未知。M06 里「不改原始 FAIL」改成「不改原始异常判定」,不改变 M06 的范围。
- 行为口径有变时才改 `docs/decisions.md`。
- 不把源码清单写进 `docs/project/knowledge-map.md`。
## Risks
- S2 的第一行策略依赖查询顺序。计划里已写成假设,测试要用有 ORDER BY 的样例,并另有一条记录“无排序时第一行不稳定”。
- S5 的权限点若规范不允许按查询模块先例新增,该切片停止,不改用前端隐藏代替。
@@ -0,0 +1,46 @@
# Task Intake Result
## Task Type
feature。Tier L(新模块、迁移、输入身份、判定语义;后续报警与场景会依赖这份契约)。
## Current Understanding
- M04 已 DONE_LOCAL。本会话推进 M05:字段映射、类型/空值、输入身份、结构化规则、PASS/FAIL/UNKNOWN、样例测试(INDEX;A-021~A-026;冻结稿 A-04、第 6 章)。
- 不做:报警创建/合并(M06)、场景草稿与 Cron(M08)、规则原因分析(M12)、任意脚本、数据质量规则转人工。
- O06 仍 OPEN。已确认的只有 D05:同一输入不重新触发;关闭后新周期或新独立事件可新建。同周期值更正如何改报警,不在本模块自行决定。
- 查询侧已有不可变版本、`current_version_no`、只读预览(PostgreSQL/MySQL)。SQL Server 查询试跑仍不做。
## Gate Policy
- config/default: balanced
- allowTaskOverride: true
- recommended: strict
- selected: autonomous
- reason or override reason: 用户在本任务入口明确指定 autonomous。建议 strict 是因为有迁移、输入身份和判定语义,且 tier-policy 对 Tier L 的 gateHint 为 prefer-strict。建议不覆盖用户选择。
- effective: autonomous
- finalApprovalRequired: true
autonomous 不取消:分析到编码的确认、最终验收、high-risk/boundary-sensitive、需要 critic 的切片、显式停点、危险命令,以及 `risk_score >= 4`。
## Blocking Questions
已关闭(D27)。身份列可配置、可为空;不勾时多行取结果顺序的第一行。日期只是可选身份列。
## Non-blocking Assumptions
- 版本方式沿用 D26:保存即插入不可变版本并设为当前;可激活历史版本。不恢复草稿/发布两步。
- 权限沿用查询模块:仅 `watchman-admin`。公司权限点规范(`standards://api/permission-nodes?version=1.0.0`)要求编码先存在于注册表,禁止编造。现有查询点是项目内 `perm:data:emp:watchman.query.*`,规范目录里没有映射/规则点。编码阶段再按同一项目先例声明,不在本轮把新编码写成已注册事实。
- 正式 Vue 前先确认 HTML 原型(D21/D24 先例)。
- 列表遵循 D25。
- 比较运算符以冻结稿已列的等于、不等于、大于、大于等于、小于、小于等于为上限。不含正则、脚本、窗口和跨事件序列。
- 条件嵌套深度上限暂按 4。空条件组在保存时拒绝。
- 样例试算不创建报警、不发通知、不写正式运行。
## Recommended Next Step
用户确认计划。确认后做计划 critic,通过后再进入 S1。当前不编码。
## Suggested Prompt For Next Step
确认 M05 计划后做计划 critic,通过再实现 S1。不写业务代码,直到计划被确认。
@@ -0,0 +1,294 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Watchman M05 映射与规则 · 静态原型(S6)</title>
<style>
:root {
--primary: #5e6ad2; --primary-soft: #eef0fb; --text: #1f2328; --text-2: #59636e; --muted: #8b949e;
--surface: #ffffff; --soft: #f6f8fa; --border: #d0d7de; --border-2: #eaeef2;
--ok: #1a7f37; --ok-bg: #e9f6ec; --warn: #9a6700; --warn-bg: #fff8e1; --err: #cf222e; --err-bg: #fdecee;
--radius: 8px;
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
}
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body { font-family: var(--font); font-size: 13.5px; color: var(--text); background: var(--soft); line-height: 1.55; }
button, input, select { font: inherit; color: inherit; }
[hidden] { display: none !important; }
.proto { background: #fffbe6; border-bottom: 1px dashed #d4b106; padding: 8px 16px; display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; font-size: 12.5px; }
.proto-title { font-weight: 600; color: #7a5b00; }
.proto-group { display: flex; align-items: center; gap: 6px; }
.proto-btn { border: 1px solid var(--border); background: #fff; border-radius: 6px; padding: 2px 9px; cursor: pointer; }
.proto-btn.on { background: var(--primary); border-color: var(--primary); color: #fff; }
.proto-note { flex-basis: 100%; color: #7a5b00; }
.shell { display: flex; height: calc(100vh - 78px); min-height: 520px; }
.side { width: 196px; flex: none; background: var(--surface); border-right: 1px solid var(--border-2); padding: 14px 10px; display: flex; flex-direction: column; }
.brand { font-weight: 700; font-size: 16px; padding: 4px 10px 14px; }
.nav-item { padding: 7px 10px; border-radius: 6px; color: var(--text-2); }
.nav-item.cur { background: var(--primary-soft); color: var(--primary); font-weight: 600; }
.nav-item.off { color: var(--muted); }
.side .who { margin-top: auto; padding: 10px; color: var(--text-2); font-size: 12.5px; }
.main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
.top { height: 48px; flex: none; background: var(--surface); border-bottom: 1px solid var(--border-2); display: flex; align-items: center; padding: 0 20px; }
.crumb { color: var(--text-2); } .crumb b { color: var(--text); font-weight: 600; }
.content { flex: 1; overflow: auto; padding: 16px 20px; min-height: 0; }
.pagefoot { flex: none; background: var(--surface); border-top: 1px solid var(--border-2); display: flex; align-items: center; justify-content: center; gap: 8px; padding: 12px 20px; }
.listfoot { flex: none; background: var(--surface); border-top: 1px solid var(--border-2); display: flex; justify-content: flex-end; padding: 8px 20px; color: var(--text-2); font-size: 12.5px; }
.tools { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; }
.tools .grow { flex: 1; }
.tools input, .tools select { width: 180px; }
.btn { border: 1px solid var(--border); background: var(--surface); border-radius: 6px; padding: 5px 14px; cursor: pointer; }
.btn.primary { background: var(--primary); border-color: var(--primary); color: #fff; }
.btn.link { border: 0; background: none; color: var(--primary); padding: 1px 6px; }
.btn:disabled { color: var(--muted); background: var(--soft); cursor: not-allowed; }
input, select { border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; background: #fff; width: 100%; }
.card { background: var(--surface); border: 1px solid var(--border-2); border-radius: var(--radius); padding: 16px 18px; margin-bottom: 16px; }
.card h3 { margin: 0 0 12px; font-size: 14.5px; }
table { width: 100%; border-collapse: collapse; }
th { text-align: left; font-weight: 600; color: var(--text-2); background: var(--soft); padding: 9px 12px; border-bottom: 1px solid var(--border-2); }
td { padding: 8px 12px; border-bottom: 1px solid var(--border-2); vertical-align: middle; }
.table-wrap { border: 1px solid var(--border-2); border-radius: var(--radius); background: #fff; overflow: auto; }
.ops { white-space: nowrap; width: 196px; text-align: right; }
.modal-mask { position: fixed; inset: 0; background: rgba(31,35,40,.4); display: flex; align-items: center; justify-content: center; z-index: 20; }
.modal { background: #fff; border-radius: var(--radius); padding: 18px 20px; width: 640px; max-width: 92vw; max-height: 80vh; overflow: auto; }
.modal h3 { margin: 0 0 8px; font-size: 15px; }
.modal .actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 14px; }
.tag { display: inline-block; padding: 0 8px; border-radius: 10px; font-size: 12px; line-height: 20px; }
.tag.abnormal { background: var(--err-bg); color: var(--err); }
.tag.normal { background: var(--ok-bg); color: var(--ok); }
.tag.unknown { background: var(--warn-bg); color: var(--warn); }
.tag.grey { background: var(--soft); color: var(--text-2); border: 1px solid var(--border-2); }
.miss { background: #fff8e1; }
.badcell { background: var(--err-bg); }
.note { border-radius: var(--radius); padding: 8px 12px; font-size: 12.5px; background: var(--soft); border: 1px solid var(--border-2); color: var(--text-2); margin-bottom: 12px; }
.note.warn { background: var(--warn-bg); border-color: #f1dc9a; color: var(--warn); }
.flash { border-radius: var(--radius); padding: 8px 12px; margin-bottom: 12px; background: var(--ok-bg); border: 1px solid #b7e0c2; color: #145c2a; }
.empty { text-align: center; padding: 56px 20px; background: #fff; border: 1px dashed var(--border); border-radius: var(--radius); }
.result { border-radius: var(--radius); padding: 12px 14px; border: 1px solid; margin-top: 12px; }
.result.abnormal { background: var(--err-bg); border-color: #f4b8be; }
.result.normal { background: var(--ok-bg); border-color: #b7e0c2; }
.result.unknown { background: var(--warn-bg); border-color: #f1dc9a; }
.result.empty { background: var(--soft); border-color: var(--border); }
.result.error { background: var(--err-bg); border-color: #f4b8be; }
.hint { color: var(--muted); font-size: 12px; }
.mono { font-family: ui-monospace, Consolas, monospace; font-size: 12.5px; }
</style>
</head>
<body>
<div class="proto">
<span class="proto-title">静态原型 · 不是正式页面</span>
<span class="proto-group"><span>角色</span>
<button class="proto-btn on" data-role="admin">管理员</button>
<button class="proto-btn" data-role="operator">处理者</button>
<button class="proto-btn" data-role="viewer">查看者</button>
</span>
<span class="proto-group"><span>试算样例</span>
<button class="proto-btn on" data-out="abnormal">异常</button>
<button class="proto-btn" data-out="normal">正常</button>
<button class="proto-btn" data-out="missing">未知·缺失</button>
<button class="proto-btn" data-out="invalid">未知·非法</button>
<button class="proto-btn" data-out="empty">空结果</button>
<button class="proto-btn" data-out="error">执行失败</button>
<button class="proto-btn" data-out="first">只用第一行</button>
</span>
<div class="proto-note">映射和判断规则共用一个版本。切换版本时字段和条件一起换。基于某一版编辑后,另存为新版本,旧版本不改。</div>
</div>
<div class="shell">
<aside class="side">
<div class="brand">预警平台</div>
<div class="nav-item off">数据源</div>
<div class="nav-item off">查询</div>
<div class="nav-item cur">映射与规则</div>
<div class="who" id="who">管理员</div>
</aside>
<div class="main">
<div class="top"><div class="crumb" id="crumb">预警平台 / <b>映射与规则</b></div></div>
<div class="content" id="content"></div>
<div class="pagefoot" id="foot" hidden></div>
<div class="listfoot" id="listfoot" hidden>共 1 条</div>
</div>
</div>
<div class="modal-mask" id="mask" hidden>
<div class="modal" id="modal"></div>
</div>
<script>
var state = { view: "list", role: "admin", outcome: "abnormal", flash: "", editing: null, ruleEditing: null };
function col(name, label, type, extra) {
extra = extra || {};
return { name: name, label: label, type: type, identity: !!extra.identity, observe: !!extra.observe, multiply: extra.multiply || "", offset: extra.offset || "" };
}
var versions = [
{ no: 1, columns: [col("temperature", "温度", "number"), col("pressure", "压力", "number")], rules: [{ column: "温度", op: "大于", value: "90" }] },
{ no: 2, columns: [col("temperature", "温度", "number"), col("pressure", "压力", "number"), col("serial", "设备", "string", { identity: true }), col("observed_at", "观测时间", "datetime", { observe: true })], rules: [{ column: "温度", op: "大于", value: "80" }, { column: "压力", op: "大于", value: "10" }] }
];
var current = 2;
var draft = null;
function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]; }); }
function render() {
document.querySelectorAll("[data-role]").forEach(function (b) { b.classList.toggle("on", b.dataset.role === state.role); });
document.querySelectorAll("[data-out]").forEach(function (b) { b.classList.toggle("on", b.dataset.out === state.outcome); });
document.getElementById("who").textContent = { admin: "管理员", operator: "处理者", viewer: "查看者" }[state.role];
var crumb = "预警平台 / <b>映射与规则</b>";
if (state.view === "detail") crumb += " / <b>详情</b>";
if (state.view === "trial") crumb += " / <b>试算</b>";
document.getElementById("crumb").innerHTML = crumb;
var denied = state.role !== "admin";
var foot = document.getElementById("foot");
var listfoot = document.getElementById("listfoot");
foot.hidden = true;
listfoot.hidden = true;
var html = "";
if (denied) {
html = '<div class="empty"><h3>无法进入映射与规则</h3><p>只有管理员可以维护映射、规则和试算。</p></div>';
} else if (state.view === "list") {
listfoot.hidden = false;
html = (state.flash ? '<div class="flash">' + esc(state.flash) + "</div>" : "") +
'<div class="tools"><input id="qname" placeholder="名称" value="炉温"><select><option>全部查询</option><option>当前炉温</option></select>' +
'<button class="btn" id="do-filter">查询</button><button class="btn" id="do-reset">重置</button><span class="grow"></span>' +
'<button class="btn primary" id="go-new">新建</button></div>' +
'<div class="table-wrap"><table><thead><tr><th>名称</th><th>查询</th><th>当前版本</th><th>身份列</th><th class="ops">操作</th></tr></thead><tbody><tr>' +
"<td>炉温与压力</td><td>当前炉温</td><td>v" + current + "</td><td>" + identityText(version(current)) + "</td>" +
'<td class="ops"><button class="btn link" id="go-detail">打开</button><button class="btn link" id="open-switch">切换版本</button><button class="btn link" id="go-trial">试算</button></td></tr></tbody></table></div>';
} else if (state.view === "detail") {
foot.hidden = false;
var base = draft.base;
var next = versions[versions.length - 1].no + 1;
html = '<div class="note">正在基于 v' + base + " 编辑。保存后成为 v" + next + ",并设为当前版本。v" + base + " 不会被修改。</div>" +
'<div class="card"><h3>选用列 <span class="hint">来源 v' + base + " · 当前生效 v" + current + '</span></h3><div class="table-wrap"><table><thead><tr><th>查询列</th><th>类型</th><th>身份</th><th>观测时间</th><th>乘数</th><th>偏移</th></tr></thead><tbody>' +
draft.columns.map(function (c, i) {
return "<tr><td>" + esc(c.label) + " <span class=\"mono\">" + esc(c.name) + "</span></td><td>" + esc(c.type) + "</td>" +
'<td><input type="checkbox" data-id="' + i + '"' + (c.identity ? " checked" : "") + "></td>" +
'<td><input type="checkbox" data-obs="' + i + '"' + (c.observe ? " checked" : "") + (c.type !== "datetime" ? " disabled" : "") + "></td>" +
"<td>" + (c.type === "number" ? '<input data-mul="' + i + '" value="' + esc(c.multiply) + '" placeholder="不换算">' : "—") + "</td>" +
"<td>" + (c.type === "number" ? '<input data-off="' + i + '" value="' + esc(c.offset) + '" placeholder="不换算">' : "—") + "</td></tr>";
}).join("") + "</tbody></table></div></div>" +
'<div class="card"><h3>判断规则 <span class="hint">与字段同属 v' + base + "</span></h3>" +
'<div class="table-wrap"><table><thead><tr><th>列</th><th>比较</th><th>比较值</th></tr></thead><tbody>' +
draft.rules.map(function (row, i) {
return "<tr><td>" + esc(row.column) + '</td><td><select data-op="' + i + '"><option' + (row.op === "大于" ? " selected" : "") + '>大于</option><option' + (row.op === "大于等于" ? " selected" : "") + ">大于等于</option></select></td>" +
'<td><input data-val="' + i + '" value="' + esc(row.value) + '"></td></tr>';
}).join("") + "</tbody></table></div>" +
'<p class="hint">条件描述异常。成立为异常,不成立为正常。这里没有单独的规则版本。</p></div>';
foot.innerHTML = '<button class="btn" id="back-list">返回列表</button><button class="btn" id="open-switch">切换版本</button><button class="btn primary" id="save-map">另存为新版本</button>';
} else {
foot.hidden = false;
html = trialHtml();
foot.innerHTML = '<button class="btn" id="back-list">返回列表</button><button class="btn" id="go-detail">打开当前版本</button>';
}
document.getElementById("content").innerHTML = html;
bind();
}
function trialHtml() {
var o = state.outcome;
if (o === "empty") {
return '<div class="result empty"><b>空结果</b><div>查询没有返回行。这不是正常,也不是未知,也不是执行失败。</div></div>';
}
if (o === "error") {
return '<div class="result error"><b>执行失败</b><div>当前查询版本里已经没有映射列 temperature。没有给出正常、异常或未知。</div></div>';
}
var skip = "";
if (o === "first" || !hasIdentity(version(current))) {
skip = '<div class="note warn">未勾选身份列。本次结果有 3 行,采用第一行,跳过 2 行。换行顺序要靠查询自己排序。</div>';
}
var tempStatus = o === "missing" ? "缺失" : (o === "invalid" ? "非法" : "有效");
var tempVal = o === "missing" ? "—" : (o === "invalid" ? "hot" : (o === "normal" ? "70" : "81.2"));
var code = (o === "missing" || o === "invalid") ? "unknown" : (o === "normal" ? "normal" : "abnormal");
var label = { unknown: "未知", normal: "正常", abnormal: "异常" }[code];
var cls = o === "missing" ? "miss" : (o === "invalid" ? "badcell" : "");
return skip + '<div class="card"><h3>映射结果</h3><div class="table-wrap"><table><thead><tr><th>列</th><th>原始值</th><th>转换后</th><th>字段状态</th></tr></thead><tbody>' +
'<tr class="' + cls + '"><td>温度</td><td class="mono">' + esc(tempVal) + "</td><td class=\"mono\">" + esc(tempVal) + "</td><td>" + tempStatus + "</td></tr>" +
"<tr><td>压力</td><td class=\"mono\">12</td><td class=\"mono\">12</td><td>有效</td></tr></tbody></table></div>" +
'<p class="hint">缺失保持为空,不会变成 0。非法值不会变成空字符串。两者的结论都是未知,但状态不同。</p></div>' +
'<div class="result ' + code + '"><b>' + label + '</b><div>温度大于 80 且压力大于 10。实际温度 ' + esc(tempVal) + ",比较值 80。</div>" +
'<div class="hint">接口码 ' + code + " · 版本 v" + current + " · 观测时间 " + (hasObserve(version(current)) ? "2026-11-18 09:00 +08:00" : "本次试算时间") + "</div></div>";
}
function version(no) { return versions.filter(function (v) { return v.no === no; })[0]; }
function identityText(v) {
var names = v.columns.filter(function (c) { return c.identity; }).map(function (c) { return c.label; });
return names.length ? names.join("、") : "未勾选";
}
function hasIdentity(v) { return v.columns.some(function (c) { return c.identity; }); }
function hasObserve(v) { return v.columns.some(function (c) { return c.observe; }); }
function cloneColumns(list) { return list.map(function (c) { return col(c.name, c.label, c.type, c); }); }
function ruleText(v) { return v.rules.map(function (row) { return row.column + row.op + row.value; }).join(" 且 "); }
function cloneRules(list) { return list.map(function (row) { return { column: row.column, op: row.op, value: row.value }; }); }
function loadMap(no) {
var source = version(no);
draft = { base: no, columns: cloneColumns(source.columns), rules: cloneRules(source.rules) };
state.view = "detail";
closeModal();
render();
}
function closeModal() { document.getElementById("mask").hidden = true; }
function openSwitch() {
var rows = versions.slice().reverse().map(function (v) {
var active = current === v.no;
return "<tr><td>v" + v.no + (active ? ' <span class="tag grey">当前</span>' : "") + "</td><td>" + esc(identityText(v) + " · " + ruleText(v)) + "</td><td class=\"ops\">" +
(active ? "" : '<button class="btn link" data-act="activate" data-no="' + v.no + '">激活</button>') +
'<button class="btn link" data-act="edit" data-no="' + v.no + '">以此编辑</button></td></tr>';
}).join("");
document.getElementById("modal").innerHTML = "<h3>切换版本</h3><p class=\"hint\">一个版本同时包含字段映射和判断规则。激活不产生新版本。以此编辑后另存,字段和条件一起成为新版本。</p>" +
'<div class="table-wrap"><table><thead><tr><th>版本</th><th>内容</th><th class="ops">操作</th></tr></thead><tbody>' + rows + "</tbody></table></div>" +
'<div class="actions"><button class="btn" id="close-modal">关闭</button></div>';
document.getElementById("mask").hidden = false;
document.getElementById("close-modal").onclick = closeModal;
document.getElementById("modal").onclick = function (ev) {
var t = ev.target;
if (!t.dataset || !t.dataset.act) return;
var no = +t.dataset.no;
if (t.dataset.act === "activate") { current = no; state.flash = "已将 v" + no + " 设为当前版本。字段和判断规则一起切换,没有新增版本。"; closeModal(); render(); }
if (t.dataset.act === "edit") loadMap(no);
};
}
function bind() {
var go = function (id, fn) { var n = document.getElementById(id); if (n) n.onclick = fn; };
go("go-detail", function () { state.flash = ""; loadMap(current); });
go("go-new", function () { loadMap(current); });
go("go-trial", function () { state.view = "trial"; render(); });
go("back-list", function () { state.view = "list"; render(); });
go("open-switch", function () { openSwitch(); });
go("save-map", function () {
readDraft();
var no = versions[versions.length - 1].no + 1;
var base = draft.base;
versions.push({ no: no, columns: cloneColumns(draft.columns), rules: cloneRules(draft.rules) });
current = no;
state.view = "list";
state.flash = "已按 v" + base + " 的字段和判断规则另存为 v" + no + ",并设为当前版本。v" + base + " 未改。";
render();
});
go("do-filter", function () { state.flash = "已按名称筛选。输入时不会自动筛选。"; render(); });
go("do-reset", function () { state.flash = ""; render(); });
document.querySelectorAll("[data-id]").forEach(function (box) {
box.onchange = function () { draft.columns[+box.dataset.id].identity = box.checked; };
});
document.querySelectorAll("[data-obs]").forEach(function (box) {
box.onchange = function () {
draft.columns.forEach(function (c, i) { c.observe = i === +box.dataset.obs && box.checked && c.type === "datetime"; });
render();
};
});
}
function readDraft() {
document.querySelectorAll("[data-mul]").forEach(function (input) { draft.columns[+input.dataset.mul].multiply = input.value; });
document.querySelectorAll("[data-off]").forEach(function (input) { draft.columns[+input.dataset.off].offset = input.value; });
document.querySelectorAll("[data-op]").forEach(function (input) { draft.rules[+input.dataset.op].op = input.value; });
document.querySelectorAll("[data-val]").forEach(function (input) { draft.rules[+input.dataset.val].value = input.value; });
}
document.querySelector(".proto").onclick = function (ev) {
var t = ev.target;
if (t.dataset.role) { state.role = t.dataset.role; state.view = "list"; render(); }
if (t.dataset.out) { state.outcome = t.dataset.out; if (state.role === "admin") state.view = "trial"; render(); }
};
render();
</script>
</body>
</html>
@@ -0,0 +1,165 @@
# M05 字段映射与规则判断 Requirement
## Goal
在已有查询定义上维护字段映射和结构化判断规则,并用样例行试算。每行给出正常、异常或未知。本模块不创建报警。
## Background
M04 已交付查询定义、不可变版本和只读预览。冻结稿 A-04、第 6 章和 A-021~A-026 把映射、输入身份和是否异常放在报警之前。D27 收口了本模块的字段和身份口径。O06 里“修订后报警怎么改”仍归 M06。
## In Scope
- 挂在查询定义上的映射:选用结果列、类型、可选身份列、可选数值换算。
- 挂在映射上的规则:结构化条件,AND/OR,样例试算。
- 正常/异常/未知,以及与之分开的字段状态、执行失败。
- 输入身份和值修订的持久化。同一身份不因重读新开一条。
- 管理界面。正式 Vue 之前先确认 HTML 原型。
## Out Of Scope
- 报警创建、合并、关闭后新周期(M06,O06 的报警半边)。
- 场景草稿、发布、Cron(M08)。
- 规则原因分析(M12)和数据质量规则转人工。
- 任意脚本、正则、窗口、跨事件序列、NOT。
- SQL Server 查询试跑。
- 从行内单位文本自动猜换算。
## Current Behavior
查询可以定义、版本化和预览。没有映射、规则、输入身份或判定结果。
## Required Behavior
配置人员选择一条查询,勾选要使用的结果列。每列标明类型。数值列可以配置乘数和偏移。身份列由人勾选,可以不勾,也可以勾多列;日期列只有被勾成身份列时才参与区分。
规则引用这些列。每条条件选择一列、一个已允许的运算符和一个比较值。条件可以按 AND/OR 组合。
试算展示原始列、转换后的值、字段状态,以及正常/异常/未知。同时给出规则的文字说明、实际值、比较值、命中条件、规则版本、观测时间和输入依据。试算不写报警,不发通知。
零行是空结果,不是正常,不是未知,也不是执行失败。单行里的指标为空仍按缺失处理。
## User Flow
1. 从查询进入映射,勾选列、类型、身份列和换算,保存。
2. 在该映射下编写规则,保存。
3. 用贴入的样例,或对该查询当前版本做一次只读预览(仅 PostgreSQL/MySQL),查看映射和判定。
4. 重开已保存的映射和规则,条件与保存时一致。
## Business Rules
业务结论只有三种,界面和接口都使用这些词:
| 结论 | 含义 |
|---|---|
| 正常 | 有效数据已经足以确定异常条件不成立 |
| 异常 | 有效数据已经足以确定异常条件成立 |
| 未知 | 必要数据不足,不能可靠确定 |
执行失败另记,不写成正常、异常或未知。
单条比较:两边都能按声明类型比较,条件成立为异常,不成立为正常。缺值或非法值为未知。
AND:已有一条正常,则整组正常;全部为异常,则整组异常;还没有正常且存在未知,则整组未知。
OR:已有一条异常,则整组异常;全部为正常,则整组正常;还没有异常且存在未知,则整组未知。
字段状态与结论分开:缺失、非法都导致未知,但预览里必须能看出是哪一种。缺失保持为空,不转成 0 或空字符串。
身份:
- 勾了身份列时,这些列的值合起来区分输入。值变化只追加修订,不新开身份。度量值、运行号和整行哈希都不进入身份。
- 不勾身份列时,这条映射本身是唯一输入。结果有多行时采用本次返回顺序的第一行。
- 身份列已勾选但该行身份值为空:该行不能形成身份,不写入输入。
- 同一次结果里多行身份值相同:按返回顺序保留第一行,其余计入跳过的重复行,不在同一次里写多条修订。
未知不创建报警。本模块没有报警写入。空结果也不创建报警,不记成正常。
## Data Rules
- 一条查询可有多条映射。一条映射可有多条规则。
- 映射和判断规则共用同一个不可变版本。切换当前版本时,字段和条件一起切换。可基于某一历史版本编辑字段和条件,保存时另存为一个新版本并设为当前,被打开的历史版本内容不变。判断规则没有单独的版本号。
- 同一身份且度量值无变化:不追加修订。
- 试算样例可以不落成正式输入。正式输入只在明确的保存试算中写入。默认的页面试算不写输入。见 Assumptions。
- 列是否还存在,对照该查询的当前版本。当前版本去掉了已选列时,保存和试算都拒绝,并说明缺哪一列。
- 新表带 `tenant_id`,并按现有业务表启用强制行级安全。映射版本内容在数据库层禁止更新和删除。
- 日期时间列与日期时间比较值使用带时区的时间,比较前归一到 UTC。没有时区的值视为非法,不按机器本地时区猜。
- 每条映射最多把一列标成观测时间。不标时,详情里的观测时间用本次试算时间。观测时间列不自动变成身份列。
## API Contract
对外操作:映射的维护与读取、规则的维护与读取、映射试算、规则试算。响应信封遵循 `standards://api/api-envelope?version=1.1.0`。路径在实现切片里按现有查询路由风格确定,不在本需求里另造一套信封。
试算响应能区分:一行结论、字段缺失、字段非法、无法形成身份、采用了第一行、同身份重复行被跳过、空结果、映射列在当前查询版本中已不存在、执行失败。
结论的存储和接口使用稳定英文码 `normal`、`abnormal`、`unknown`。界面文案固定为正常、异常、未知。不把这三个中文词写成数据库枚举。空结果和执行失败不使用这三个码。
## UI Requirements
- 列表遵循 D25。详情和表单的页面按钮遵循 D22。
- 正式 Vue 前先给出 HTML 原型并经确认。
- 映射页能勾选列、类型、身份列、最多一列观测时间、乘数和偏移。
- 规则页用结构化条件,不用脚本框。
- 预览高亮缺失和非法。采用第一行时写明跳过的行数。
- 判定结果使用正常、异常、未知。
## Compatibility Requirements
- 不改查询版本不可变、只读预览和 SQL Server 不试跑的现有行为。
- 不改已有权限角色名。`watchman-admin` 继续是配置人员角色。
## Error Handling
- 查询预览失败:执行失败,不产生正常或未知。
- 类型对不上、未配置的单位差、无法解析:字段非法,结论未知。
- 系统异常:执行失败。
- 空条件、超过嵌套深度、未知运算符、对文本或布尔使用大小比较:保存时拒绝。
## Permissions And Security
仅 `watchman-admin` 可读取、保存和试算。操作者与查看者不能写,也不能靠隐藏按钮绕过。
权限点编码在实现时按 `standards://api/permission-nodes?version=1.0.0` 声明,并沿用现有 `perm:data:emp:watchman.query.*` 的项目写法。需求不把尚未注册的编码写成已存在事实。
## Assumptions
- 映射和规则的版本方式与 D26 相同。
- 比较类型为数值、文本、布尔、日期时间。数值和日期时间可用等于、不等于、大于、大于等于、小于、小于等于。文本和布尔只有等于、不等于。
- 条件嵌套深度上限为 4。根组算第 1 层,叶子也算一层。空组拒绝。
- 第一行指本次结果集的返回顺序。顺序要稳定,由查询自己写 ORDER BY。
- 换算写在映射上,不读取行里的单位文字。
- 页面上的普通试算不写正式输入;持久修订由单独的保存动作写入。
- 没有标成观测时间的列时,试算说明里的时间用本次试算时间。这条现在写进 Data Rules,因为冻结稿要求详情展示观测时间,而用户已确认日期不是必填。
- 同一次结果中的重复身份保留第一行。这是为了和「第一行」口径一致,S2 之前若要改,先改需求再写代码。
## Risks
- 不勾身份列时,多行只留第一行。查询若没有 ORDER BY,下一次第一行可能变了,修订会记在同一条输入上。
- 身份持久化会被 M06 拿去合并报警。本模块的修订不能被实现成新的业务事件。
- 新权限点若与公司注册表不一致,实现时要停下来核对,不能临时改成只靠前端隐藏。
## Acceptance Criteria
1. 一行中的多列指标可以同时被映射,规则的每条条件能选择其中一列。
2. 不勾身份列时,多行样例只用第一行,并显示跳过行数;勾选身份列后,不同身份值分成不同输入。
3. 同一身份的新度量值追加修订;相同值的重读不新开输入,也不把运行号算进身份。
4. 缺失保持缺失,非法值不变成 0 或空字符串;两者结论都是未知,预览能区分。
5. 未配置换算的单位差为非法。已配置的乘数和偏移按配置生效。
6. AND/OR 符合 Business Rules 中的三值表。执行失败不显示为正常或未知。
7. 保存后再打开,条件一致。试算不产生报警。
8. 非管理员调用写和试算被拒绝。
9. 查询返回零行时结果为空结果,不出现正常、未知或执行失败。
10. 当前查询版本去掉已选列时,试算被拒绝并指出缺失列。
11. 带时区的日期时间按 UTC 比较;没有时区的值记为非法。
## Deferred Questions
- O06:同一身份修订之后,原报警是否更新。M06 再定。
- 普通试算与“保存为正式输入”是否分成两个按钮,若实现时界面放不下,再问一次,不自行改成每次试算都落库。
## Source Notes
- D05、D22、D24、D25、D26、D27。
- `需求冻结文档_V1.1_交接稿.md` A-04、第 6 章。
- `docs/tasks/INDEX.md` M05;`docs/tasks/CHECKLIST-v1.md` A-021~A-026。
- `docs/development-plan.md` 4.2:身份不同于运行号,整行哈希不能用来丢掉跨周期事件。本模块用可配置身份列实现这一点。
@@ -0,0 +1,166 @@
# M05 计划 Critic 审查
- 模式:plan-review(S1 之前的 critic-required 停点)
- 任务:`.task/2026-11-18/m05-mapping-rules`
- 日期:2026-11-18
- 审查范围:requirement.md、implementation-plan.md、context-pack.md、boundary.md、D05/D22/D24/D25/D26/D27、`docs/tasks/INDEX.md` M05、冻结稿 A-04 与第 6 章、`AGENTS.md` 项目本地段;并抽查 `models/query.py`、`auth/access.py`、`migrations/versions/`。
- 本次审查不改任何产品代码、迁移或前端。
## 当前结论(第二轮复审,2026-11-18 晚)
**PASS_WITH_WARNINGS**
**S1 可以开始:是。** 没有剩余阻断项。详见文末「复审(第二轮)」。下面第一轮的 FAIL 结论已被取代,保留作为修订依据。
## 第一轮结论(已取代)
**FAIL**
**S1 可以开始:否。** 需要先按下面「阻断项」修订实现计划(只改 S1 的 Steps/Validation/Rollback 三段即可,不必重做整份计划),修订后再放行 S1。
说明:FAIL 的原因不是需求口径错了。需求与 D27、冻结稿第 6 章在语义上一致;问题集中在 S1 这一片的 schema 契约与验证证据,按现在的写法实现出来的表会违反仓库既有的租户隔离与不可变强制约定,且 S1 的 Done Criteria 没有对应测试。
## 先确认没有问题的部分
- 需求与 D27 一致:映射挂查询、一行多列、身份列可配置可为空、日期列只是可选身份列、不勾身份列时整条映射一条输入并取第一行、同一身份只追加修订、缺失与非法分开但都为未知、系统异常另记、单位只做已配置乘数与偏移、结论用正常/异常/未知。
- 三值真值表与冻结稿 6.1 一致(异常=命中,正常=未命中,未知=信息不足;AND 已有正常即正常,OR 已有异常即异常)。
- 安全底线未被突破:未知不创建报警、技术失败不写成正常或未知、本模块不写报警状态,这三条在需求、boundary.md 与计划的 Global Forbidden Scope 中都有明确表述。S4 的 Done Criteria「没有一条测试把执行异常断言成未知」是有效约束。
- 身份口径完整:运行号与整行哈希都被排除在身份之外,身份列为空的行不写入输入,值变化只追加修订,相同值不追加(S2 Steps 1~4)。
- 权限点没有被编造。需求与计划都只引用既有 `perm:data:emp:watchman.query.*` 写法,把新编码推迟到 S5 并要求先核对规范,与 `auth/access.py` 现状(admin-only 的 datasource/query 节点)一致。已通过 sy-standards 核对版本:`standards://api/permission-nodes` 最新为 1.0.0、`standards://api/api-envelope` 最新为 1.1.0,计划引用的版本号正确。
- 门禁设置正确:S1 为 `gateClass: high-risk` + `risk_score: 4`,计划把「计划 critic 通过」写成 S1 的前置依赖,context-pack 的 Stop Conditions 明确 autonomous 不取消 critic、不取消 `risk_score >= 4` 停顿、不取消原型确认与最终验收。`marionettist.config.yaml` 的 `allowTaskOverride: true`,`.task/active.json` 为 `phase: analysis`、`allowedToCode: false`、`lastGate: plan-confirmed-awaiting-critic`,状态自洽。
- 切片没有混入报警、场景、Cron、企微、原因分析或任意脚本;S6 原型先于 S7 的顺序和停点成立。
- S1 的文件范围是真的:`models/query.py`、`auth/access.py`、`migrations/versions/`(head 为 `20261118_0009`)均存在,S1 Step 4 要对照的「查询当前版本输出列」在 `query_definitions.current_version_no` 与 `query_versions.output_schema` 上确实可取。
## 阻断项(修订后 S1 才能开始)
### B1. S1 的建表步骤漏了 tenant_id 与强制 RLS,会破坏既有租户隔离
证据:`20261117_0004_data_sources.py`、`20261118_0006_query_definitions.py` 对每张业务表都执行 `ENABLE / FORCE ROW LEVEL SECURITY`、建 `tenant_isolation` 策略(`tenant_id = current_setting('app.tenant_id', true)`)并显式 `GRANT` 给 `watchman_app`;`models/query.py` 的两张表都带 `tenant_id`;仓库已有 `tests/test_rls.py`、`tests/test_datasource_rls.py` 守这条线。
问题:S1 的 Steps 只写了「映射定义、列配置、不可变版本和当前版本指针」,完全没有 `tenant_id`、RLS 策略和授权。按计划字面实现出来的映射表将没有任何租户隔离,任何租户只要拿到 id 就能读写别的租户的映射,而且与 ORM 会话设置 `app.tenant_id` 的现有机制不一致。这是安全边界问题,不是风格问题。
要求的最小修订:S1 Steps 增加一条「新表均带 `tenant_id`,按 0006 的 `_enable_rls` 同形式启用 FORCE RLS、建 `tenant_isolation` 策略并授权 `watchman_app`」;Validation 增加一条跨租户读写被拒的测试(可仿 `test_datasource_rls.py`);Rollback Notes 补上「向下迁移同时 DROP POLICY」。
### B2. 「历史版本不可更新、不可删除」没有强制层,也没有对应测试
证据:`20261118_0007_query_versions_immutable.py` 的文件说明已经写明,0006 当时只靠「服务层拒绝」是不够的(那个 Python helper 在写路径上根本没人调用),所以改成 `REVOKE UPDATE, DELETE` + 语句级 BEFORE UPDATE/DELETE/TRUNCATE 触发器两层强制。
问题:S1 的 Step 2 写「保存即新版本。历史版本不可更新、不可删除」,Done Criteria 写「版本内容不可改」,但 Steps 没说在哪一层强制,Validation 只有「`uv run pytest` 覆盖本切片」和「`alembic upgrade head` 对空库可升级」。这正是审查项 7 指出的情况:S1 可以在没有任何一条测试证明不可变的情况下被宣布完成,而且很可能重犯 0007 修掉的那个缺陷。
要求的最小修订:S1 Steps 明确不可变由数据库层强制(沿用 0007 的 REVOKE + 语句级触发器形式);Validation 增加两条具体断言——对历史映射版本执行 UPDATE 被拒、执行 DELETE 被拒;Done Criteria 绑定这两条测试,而不是绑定一句描述。
### B3. 观测时间与时区在 S1 的列配置 schema 里没有位置,决定晚了就要再改一次高风险迁移
证据:冻结稿 4.3 要求输入契约能表达「观测时间/统计周期」,并明确「时区不可依赖执行机器隐式默认值」;6.2 要求判定详情展示「自然语言规则、实际值、比较值、命中条件、版本、观测时间和输入依据」。
问题:S1 的列配置只有「类型、身份布尔标记、乘数与偏移」,没有任何「哪一列是观测时间」的声明位;需求的 Required Behavior 列举试算要展示的内容时也漏了观测时间和输入依据。需求 Assumptions 里有一条「没有观测时间列时用本次试算时间」,但这条不在用户本次确认的五条假设之内,等于是未确认口径。同时,日期时间列与日期时间比较值的时区约定(存 tz-aware 还是裸值、比较时按哪个时区)在需求、S1、S3、S4 里都没有写,冻结稿恰好禁止依赖机器隐式默认。
为什么必须在 S1 之前定:列配置 schema 和日期时间列的存储形态都是 S1 的表结构。这两件事留到 S4/S5 再决定,就要对一张 `risk_score: 4` 的表再加一次迁移。
要求的最小修订(二选一,并把选择写进 requirement 的 Assumptions 与 S1 Steps):
- 在列配置中增加一个可选的「观测时间列」声明,与身份标记并列;或
- 明确记录「本模块不声明观测时间列,判定详情一律使用试算时间」,并作为需要用户点头的口径列出。
无论选哪一种,都要在 S1 Steps 写死日期时间列与日期时间比较值的时区约定(建议统一 tz-aware 存储、比较前归一),并在 S4 的真值表测试里固定一条跨时区用例。
## 非阻断警告(S1 可以带着走,但要在指定切片前落实)
### W1. 空结果(零行)语义缺失 —— S4/S5 之前必须补
冻结稿 4.3 明确「空结果、单行指标为空、源连接失败是不同情况」,且空结果「不自动代表指标为零、业务正常或报警恢复」。requirement 的 Business Rules、Error Handling、Acceptance Criteria,以及 S4 Steps、S5 Step 3 的响应状态列表,都没有「查询返回零行」这一种。不勾身份列时更直接:没有第一行可取。按现状实现,S4 很可能把零行落成「正常」或笼统的「未知」,两种都踩到冻结稿红线。补法:在 requirement 增加一条明确结论与一条验收标准,并把「空结果」加进 S5 的响应状态枚举。
### W2. 「当前版本删掉了已选列」在试算侧没有落片 —— S4/S5 之前补
requirement 的 Data Rules 要求「当前版本去掉了已选列时,映射不能静默继续试算」。S1 Step 4 只覆盖了保存时拒绝,试算时的这条路径没有任何切片负责,S5 Step 3 的响应状态里也没有这一种。请在 S5 的响应状态中增加「映射列在当前查询版本中已不存在」,并在 S4 或 S5 的 Validation 里加一条用例。
### W3. 同一次结果中多行命中同一身份值,行为未定义 —— S2 之前定
S2 Step 1 把唯一约束落在「映射 + 身份值」上,但没说同一次试算里两行身份值相同时怎么办(取第一行?按顺序各写一条修订?拒绝?)。这会直接决定唯一约束冲突时的处理,也会影响 M06 的合并口径。请在 S2 开工前写死,并配一条测试。
### W4. `docs/tasks/INDEX.md` 仍写 PASS/FAIL/UNKNOWN,与 D27 的正常/异常/未知冲突
INDEX(2026-11-17)M05 验收段写的是「PASS/FAIL/UNKNOWN」,M06 还写「不改原始 FAIL」。按冲突顺序,D27(2026-11-18,用户逐项确认)优先,需求用中文三词是对的。但计划的 Documentation Update Requirement 只列了 `docs/tasks/M05.md` 和 `docs/progress.md`,没有列 INDEX。这会让后续审查者拿 INDEX 当权威。请在 S8 的文档同步里加上修订 INDEX 的 M05/M06 措辞。
### W5. 「接口也用正常/异常/未知」要区分枚举码与展示文案 —— S5 决定
D27 的原意是术语统一,不等于要把中文字面量作为线上枚举值或数据库枚举。S5 请对照 `standards://api/api-envelope?version=1.1.0`(最新版,已核)决定是「稳定英文码 + 中文展示文案」还是中文值,并写进 S5 Steps。界面文案保持正常/异常/未知不变。无论选哪种,都不要把三词写死进数据库枚举类型。
### W6. S5 调用查询预览的路径没有写成步骤
requirement 允许试算对当前版本做一次只读预览(仅 PostgreSQL/MySQL),但没有任何切片的 Steps 写「复用既有查询预览执行器」。boundary.md 写了「查询执行器只可调用」,建议把这句落到 S5 Steps 里,并顺带明确预览权限点是沿用 `perm:data:emp:watchman.query.preview` 还是另立——仍然按 B 项原则:核对规范,对不上就停,不编码。
### W7. S1 的 Rollback Notes 不完整,且没有 downgrade 验证
「向下迁移只删除本切片新增表」漏了策略与触发器(0006 的 downgrade 是先 DROP POLICY 再 drop_table)。另外 Validation 只验 `upgrade head`,没有验 downgrade,而 Rollback Notes 却承诺可回滚。建议要么补一条 downgrade 验证,要么如实写明该命令未运行。
### W8. RLS 相关测试需要真实 Postgres,环境不具备时必须记 NOT_RUN
`alembic upgrade head` 与 RLS 用例依赖真实 Postgres(FORCE RLS 在 SQLite 上无意义)。请在 S1 的 Validation 里写明运行环境,命令没真正跑就按 `AGENTS.md` 第 7 条如实记为未运行,不要写成 PASS。
### W9. autonomous 下 S3 → S4 会自动连推,建议对 S4 另设停点(建议性)
S4 是 `standard` + `risk_score: 3`,按 autonomous 规则可以在 S3(risk 4)完成后不经确认直接进入。S4 固化的是本模块的核心语义(三值真值表、缺失与非法的区分、第一行与跳过行数)。考虑到 W1、W2、B3 的时区用例都要在 S4 落地,建议在计划里把 S4 之前也写成显式停点,或要求 S4 先把真值表测试提交给审查。这是建议,不是阻断。
## 放行条件
按 B1、B2、B3 修订 `implementation-plan.md` 的 S1 Steps/Validation/Rollback Notes,并把 B3 选定的观测时间口径与时区约定回写到 `requirement.md` 的 Assumptions(若选「不声明观测时间列」,该条需用户确认)。这些改完之后 S1 即可开始,W1~W9 按各自标注的切片时点处理。
---
# 复审(第二轮)
- 模式:plan-review 复审
- 时间:2026-11-18 晚
- 依据:重新完整读取 `requirement.md`、`implementation-plan.md`、`context-pack.md` 当前内容,未沿用上一轮记忆。
- 结论:**PASS_WITH_WARNINGS**,**S1 可以开始:是**,无剩余阻断项。
## 阻断项核验
**B1(tenant_id 与强制 RLS)已修复。** S1 Step 1 明确「新表都带 `tenant_id`,按 `20261118_0006` 的形式 `ENABLE`/`FORCE ROW LEVEL SECURITY`、建立 `tenant_isolation` 策略,并 `GRANT` 给 `watchman_app`」;Validation 要求跨租户读写被拒的测试;Rollback Notes 要求先 `DROP POLICY`。与 0006 的既有形式一致。
**B2(不可变版本的强制层与证据)已修复。** S1 Step 2 指明沿用 `20261118_0007`:版本表 `REVOKE UPDATE, DELETE` 加语句级 BEFORE UPDATE/DELETE/TRUNCATE 触发器;Validation 列出 `UPDATE` 被拒、`DELETE` 被拒两条测试;Done Criteria 写成「由数据库拒绝证明,不单靠服务层」。这条堵住了上一轮「S1 可以在零证据下宣布完成」的口子。
**B3(观测时间与时区)已修复,且位置正确。** 口径写进了 `requirement.md` 的 Data Rules(每条映射最多一列观测时间、不标时用试算时间、观测时间列不自动变身份列;日期时间用带时区值、比较前归一 UTC、无时区视为非法),不再是未确认假设;Required Behavior 补上了「观测时间和输入依据」,与冻结稿 6.2 的判定详情要求对齐;S1 Step 3 与 Done Criteria 承接了 schema 侧,S4 Step 6 有跨时区与无时区用例,AC11 可验收。
## 非阻断警告核验
W1 空结果(需求 Required Behavior/Business Rules/API Contract/AC9、S4 Step 5、S5 Step 5)、W2 缺列保存与试算双侧拒绝(Data Rules/AC10、S1 Step 4、S4 Step 7、S5 Step 4)、W3 同次重复身份保留第一行(Business Rules、S2 Step 5)、W4 INDEX 措辞归入 S8(Documentation Update Requirement,含 M06「不改原始异常判定」且声明不改 M06 范围)、W5 英文码加中文文案且不建中文数据库枚举(API Contract、S4 Step 1、S5 Step 3)、W6 复用既有查询预览执行器并先核对预览权限点(S5 Step 1)、W7/W8 downgrade 与真实 PostgreSQL 写进 S1 Validation 且未跑记未运行、W9 S4 显式停点(S4 Execution 段与 context-pack Stop Conditions),均已落实。
## 本轮新增的非阻断警告
### R1. S2 新建输入/修订表时没有重复 B1 的 RLS 模式 —— S2 开工前补
S2 的 Allowed Modification Scope 含「新的输入/修订模型与迁移」,Step 1 的唯一约束已包含租户,说明表上会有 `tenant_id`。但 S2 的 Steps 没有写 `ENABLE`/`FORCE ROW LEVEL SECURITY`、`tenant_isolation` 策略与 `GRANT`,Validation 也没有跨租户被拒用例和真实 PostgreSQL 的 upgrade/downgrade 要求。这是与 B1 同一类的问题,只是落在另一片。S2 是独立的 `risk_score: 4` 停点,不影响 S1 开工,但在 S2 批准前必须按 S1 的写法补齐。
### R2. S3 规则版本既没有 RLS 模式,也没有 B2 的不可变强制 —— S3 开工前补
`requirement.md` Data Rules 写「映射和规则各自保存即产生不可变版本」,但数据库层那条只写了「映射版本内容在数据库层禁止更新和删除」,没有覆盖规则版本。对应地,S3 Step 1 只说「保存即不可变版本」,没有 `REVOKE UPDATE, DELETE` 与触发器,也没有 RLS 与 `tenant_id`;S3 Validation 只有四条拒绝非法规则的用例,没有跨租户、`UPDATE` 被拒、`DELETE` 被拒。建议把需求那句改成覆盖映射版本与规则版本,并把 S3 的 Steps/Validation 对齐 S1。
### R3. 规则里配置的无时区日期时间比较值,是保存时拒绝还是运行时非法,没有写死 —— S3 开工前定
S1 Step 3 把「无时区值为非法」同时写给了列和比较值,但比较值由 S3 的规则表存储,S3 Step 3 只要求「比较值类型须与列类型相容」。需求 Error Handling 的保存时拒绝清单里也没有这一项,而 AC11 的措辞偏向运行时字段非法。建议明确:人工配置的比较值在保存时拒绝(配置错误应当早失败),行数据里的无时区值在运行时记为非法、结论未知。两者分开写,避免 S3 与 S4 各写一半。
### R4. S4、S5 的 Validation 行没有跟上新增的步骤和验收标准
S4 Steps 已覆盖空结果、跨时区、缺列三件事,但 Validation 仍写「覆盖验收标准 4、5、6 的计算部分」,没有点名 AC9、AC10、AC11;S5 Steps 4、5 已列出空结果、重复身份跳过、缺列三种响应状态,但 Validation 仍只有「管理员成功,操作者与查看者拒绝,试算无报警行」。按现状,这些新口径有实现而无门禁。建议把 AC9~AC11 和三种新响应状态分别写进 S4、S5 的 Validation。
### R5. 零行时是否写入正式输入,没有写明
「保存试算」会写正式输入,但空结果既不是三种结论也没有行可用。S2 与 S5 都没说零行时不写输入与修订。建议在 S2 加一句「空结果不写输入、不写修订」,避免实现时顺手写一条空身份。
### R6. `context-pack.md` 有三处与修订后的计划/需求不同步 —— S1 开工前刷新
这份文件是实现者直接读的,当前落后于另外两份:
1. Validation Commands 仍写「迁移:`alembic upgrade head`」,没有 S1 已要求的真实 PostgreSQL 与 downgrade。
2. Assumptions 仍写「版本方式、嵌套深度 4、普通试算不落库,用户还没单独点名」,但用户已在 2026-11-18 确认了这几条(含第一行口径与身份值为空的行不形成输入)。保留旧措辞会让后续 Agent 把已确认口径当成待确认。
3. Required Behavior 只提中文三词,没有提 `normal`/`abnormal`/`unknown` 接口码、空结果和观测时间。
这三处都是文档同步,不改变实现方向,但建议在 S1 动工前顺手改掉。
### R7. 两处措辞小问题(可选)
S1 的 Goal 一句仍只列「所属查询、选用列、类型、身份勾选、乘数和偏移」,没带观测时间标记,而 Step 3 与 Done Criteria 都有;另外需求说「结论的存储和接口使用稳定英文码」,但没有任何切片说明结论会被落到哪张表(试算是瞬态,修订存的是度量值)。若本模块实际不持久化结论,建议把「存储」二字改成只约束接口,免得 S2 多建一列。
## 放行结论
S1 可以按现在的 `implementation-plan.md` 开始。R1、R2、R3、R5 必须在对应切片(S2、S3)批准前落实,R4、R6 建议在 S1 动工前后顺手处理,R7 为可选。S2、S3、S5 仍是 `risk_score: 4` 的独立停点,S4 前有显式停点,这些都不因本次 PASS_WITH_WARNINGS 而放宽。
@@ -0,0 +1,24 @@
# S1 Review
- 切片:S1 映射模型与不可变版本
- 审查:独立审查,与实现不是同一模型系列
- 推荐:PASS_WITH_WARNINGS
- 阻断项:无
## 已核对
- 三张新表有 `tenant_id`,并启用强制行级安全。
- 版本表和列配置表由数据库拒绝 UPDATE/DELETE/TRUNCATE。
- 观测时间列最多一列。身份标记和乘数、偏移已保存。
- 保存时会拒绝当前查询版本里不存在的列。
- 没有接口、权限点、报警表或输入修订表。
## 警告
1. 测试只拒绝了版本表的 UPDATE/DELETE,没有对列配置表做同样的拒绝测试。迁移里已经保护了列配置表。
2. 外键只核对 id,不核对租户。与查询模块现有写法相同。服务层按当前租户查找父行。
3. 观测时间列没有限制必须是日期时间类型。需求只写了最多一列。S4 把该列当时间用之前要补上类型限制。
4. 版本指针没有外键,与查询定义的指针方式相同。
5. 声明类型和查询输出类型的比较留到试算,不在 S1。
实现方报告:真实 PostgreSQL 上 `alembic upgrade head`、`downgrade -1` 再升级通过。主 Agent 重跑 `uv run pytest tests/test_mapping_versions.py`:6 passed。审查未重跑测试。
@@ -0,0 +1,26 @@
# S2 Review
- 切片:S2 输入身份与修订
- 审查:独立审查,与实现不是同一模型系列
- 推荐:PASS_WITH_WARNINGS
- 阻断项:无
## 已核对
- 唯一约束是租户、映射、身份键。度量值和运行号不在键里。
- 不勾身份列时使用固定的映射级身份,一批只取第一行。
- 勾了身份列时,同一批里同一身份只保留第一行。
- 值变化追加修订,相同值不追加。
- 两张新表有 `tenant_id` 和强制行级安全。修订行在数据库层拒绝 UPDATE、DELETE、TRUNCATE。
- 没有接口、权限点、报警或规则判定。
## 警告
1. 身份列只有 `None` 或缺失会跳过。空字符串和纯空格仍会建成输入。需求写的是“身份值为空”,空字符串算不算空,留到下次改这段持久化之前确认。
2. 修订表自己的跨租户读写、不勾身份列时的重读、身份值为 `None`,测试里还没有。
3. 个别测试按全表取修订行,库里有别的数据时可能拿错行。
4. 身份键对类型敏感:数值 `1`、字符串 `"1"` 会变成两个身份。
5. 一批里出现不带时区的日期时间时,整批失败。判定阶段才把这种值记为非法。
6. `mappings.py` 模块注释仍写着不做输入持久化,和现在的代码不符。
实现方报告:真实 PostgreSQL 上升级、降一级再升级通过。主 Agent 重跑 `uv run pytest tests/test_mapped_input_revisions.py tests/test_mapping_versions.py`:14 passed。审查未重跑。
@@ -0,0 +1,25 @@
# S3 Review
- 切片:S3 规则结构校验
- 审查:独立审查,与实现不是同一模型系列
- 推荐:PASS_WITH_WARNINGS
- 阻断项:无
## 已核对
- 规则定义和规则版本带 `tenant_id`,并启用强制行级安全。
- 历史规则版本在数据库层拒绝 UPDATE、DELETE、TRUNCATE。
- 条件只接受 AND/OR 组和叶子。叶子只有列、运算符、比较值。
- 文本和布尔拒绝大小比较。日期时间比较值没有时区时,保存即拒绝。
- 深度按根组第 1 层、叶子也算一层,上限 4。空组拒绝。
- 保存时不执行用户代码,也没有正常/异常/未知的计算。
- 没有接口和权限点。
## 警告
1. 运算符如果不是字符串,而是列表或对象,会抛出未处理的类型错误。规则不会保存,但调用方看到的不是校验失败。S5 之前改成先判断类型。
2. 深度计数已按上面的口径写进需求。还缺一条“刚好 4 层可以保存”的测试。
3. 拒绝测试大多只断言抛了校验错误,没有断言原因。布尔列的大小比较、列不在当前映射版本里、组运算符非法,都还没有对应用例。
4. 规则版本没有记下校验时所对照的映射版本。试算前仍要再核对列是否还在。
审查重跑 `uv run pytest tests/test_rule_versions.py`:8 passed。主 Agent 重跑 S1 至 S3 共 22 passed。迁移升级和降级由实现方在真实 PostgreSQL 报告通过,审查未重跑。
@@ -0,0 +1,26 @@
# S4 Review
- 切片:S4 正常/异常/未知计算
- 审查:独立审查,与实现不是同一模型系列
- 推荐:PASS_WITH_WARNINGS(第三次复审)
- 阻断项:无
## 过程
第一次审查为 BLOCKED:真值表覆盖不足,缺列检查只看规则列,比较中的意外错误被写成未知。修复后第二次仍为 BLOCKED:浮点行值乘以 Decimal 乘数会抛错。第三次复审关闭了这个问题。
## 已核对
- 结论码是 `normal`、`abnormal`、`unknown`。零行是 `empty`。缺映射列是 `error`,并给出列名。
- AND/OR 的未知组合、等值边界、缺失和非法的字段状态都有测试。
- 配置了乘数或偏移时,整数和浮点先转成 Decimal 再运算。非有限数值是非法,结论为未知。
- 没有写报警,没有迁移。
## 警告
- 还没有用例证明“配置的比较值非法时会抛出,而不是返回未知”。
- 多行且有身份列时,顶层结论只代表第一行。
- 条件树的运算符若不是 `and`,计算函数会按 OR 处理。保存规则时已经拒绝这种树。
- 函数说明仍写着只检查规则列,代码已经检查全部映射列。
主 Agent 重跑 `uv run pytest tests/test_judgment.py`:12 passed。审查同样重跑 12 passed。
@@ -0,0 +1,26 @@
# S5 Review
- 切片:S5 接口与权限
- 审查:独立审查,与实现不是同一模型系列
- 推荐:PASS_WITH_WARNINGS(复审)
- 阻断项:无
## 过程
第一次审查为 BLOCKED:查询试算没有提交,预览审计会丢;规则版本保存不核对规则是否属于地址里的映射。两处已改,复审通过。
## 已核对
- 权限点是 `perm:data:emp:watchman.mapping.read`、`write`、`trial`,只放行 `watchman-admin`。
- 贴入样例的试算不写正式输入,也不要求查询预览权限。
- 重跑当前查询的试算同时要求映射试算和既有查询预览权限,并调用既有预览。失败时结果是错误,不是正常或未知。预览之后会提交,审计记录保留。
- 规则不属于该映射时,保存版本返回 404。
- 没有新角色,没有报警写入,没有新的 SQL 执行器。
## 警告
- 保存规则版本时先按未加锁的读取核对归属,并发保存同一条规则可能得到 500,唯一约束仍会挡住重复行。
- 规则 id 不是合法 UUID 时,可能是 500 而不是 404。
- 接口测试只有 2 个用例,没有覆盖 SQL Server 拒绝和只读路由的 403。
主 Agent 与审查都重跑了 `uv run pytest tests/test_mapping_api.py`:2 passed。
@@ -0,0 +1,23 @@
# S7 Review
- 切片:S7 正式页面,以及判断规则并入映射版本
- 审查:独立审查
- 推荐:BLOCKED(第三次)
- 已用复查次数:3
## 已成立
- 映射版本上有 `condition_tree`,保存时字段和条件在同一个新版本里。
- 激活只改当前版本号,不新增版本。
- 列表没有「判断规则」按钮。
- 打开已有版本时会读服务端的当前版本,试算提交的是页面上的 JSON 行。
## 仍阻断
新建映射还没有版本。详情页把空的当前版本当成 0 去读取,请求失败后,页面上仍留着写死的列 `n` 和条件 `n eq 1`。这时点「另存为新版本」会把这份占位内容存成 v1。
## 修复后复审
推荐:PASS_WITH_WARNINGS。
新建映射没有版本时,不再请求版本 0。初始字段来自该查询的输出列,页面里不再有占位列 `n`。`seed.spec.ts` 通过。编辑页是否跳过版本加载,还没有组件测试。
@@ -0,0 +1,30 @@
# S8 模块审查
- 推荐:PASS_WITH_WARNINGS(修复后复审)
- 第一次为 BLOCKED:数值字符串比较、粘贴试算不核对查询列、ISO 时间被判非法、条件组重开被清空。
- 修复后复审通过。
## 已核对
- 正常、异常、未知、空结果、执行失败分开。
- 字段和判断条件存在同一个映射版本。激活不新增版本。
- 列表没有「判断规则」按钮。
- 新建映射不请求版本 0,不用占位列 `n`。
- 管理员权限、行级安全和版本不可改仍在。
## 警告
- 比较值留空时,页面会提示保存失败。
- 组合条件用「并且/或者」和一条条条件编辑,不再用 JSON 文本框。
- 列表总数会跟着名称和查询筛选走。
- 试算会显示「采用第一行,跳过 N 行」。
- Playwright 已跑通,截图在 `docs/evidence/M05/ui/`。
- 旧的独立规则版本接口还在,新页面不用它。
- 映射 Playwright:1 passed。截图:trial-normal.png、trial-abnormal.png、trial-unknown.png、trial-first-row.png。
## 测试
- `uv run pytest tests/test_judgment.py tests/test_mapping_api.py tests/test_rule_versions.py tests/test_mapping_versions.py`:28 passed。
- `pnpm test:unit`:95 passed。
- 全量 `uv run pytest`:3 个数据源列表用例失败,失败点是新建记录不在返回的第一页,不是本模块断言。
- Playwright:未运行。
@@ -0,0 +1,35 @@
{
"taskId": "2026-11-18/m05-mapping-rules",
"module": "M05",
"title": "字段映射与规则判断模块",
"type": "feature",
"tier": "L",
"phase": "done",
"allowedToCode": false,
"currentSlice": "S8",
"proposedNextSlice": null,
"lastGate": "user-closed-done-local",
"status": "DONE_LOCAL",
"gatePolicy": {
"selected": "autonomous",
"effective": "autonomous",
"recommended": "strict",
"finalApprovalRequired": true,
"allowTaskOverride": true,
"overrideReason": "用户在任务入口明确指定 autonomous"
},
"gates": {
"requirementFrozen": true,
"planApproved": true,
"contextPackReady": true,
"criticPassed": true,
"implementationDone": true,
"reviewPassed": true,
"validationPassed": true
},
"notes": [
"User confirmed the plan on 2026-11-18 with 继续, including the listed assumptions.",
"Plan critic recheck PASS_WITH_WARNINGS. S1 may start. S2/S3 must repeat RLS; S3 versions must be immutable in the database."
],
"updatedAt": "2026-11-19T02:05:00Z"
}
@@ -0,0 +1,46 @@
# Module Boundary Summary
## Module Scope
- Target area: M06 报警实例、判定关联、人工处理历史、列表/详情 API 与控制台。
- Related areas: M05 输入修订与判定;M01 `RunRecord`/审计;M02 角色与会话;后续 M07/M08/M09 的稳定接口边界。
- Cross-area impact: M06 消费既有异常事实和合成发布快照,不反向修改 M05,也不创建场景、调度、通知或次数策略。
## Modifiability
- Modifiable: `services/watchman` 新增 alarms 模型/服务/路由/迁移/测试;`auth/access.py`、`auth/principal.py` 的已批准报警权限接入;`api/app.py` 路由注册;`web/apps/console` 新增报警页面、路由、四语言、测试;M06 任务与证据文档。
- Restricted areas: M05 模型只可引用,不可改写身份或判定语义;M01 通用审计/运行记录只可复用;共享权限、路由、模型导出与迁移目录必须串行修改。
- Forbidden areas: M07 企微和真实消息;M08 场景/Cron/正式发布实体;M09 次数窗口/升级;可编排工作流引擎;自动恢复;转派/重开/审批;生产库、真实外发、凭证、`.env.local`、`.cursor/mcp.json`、未授权提交。
## Loaded Context
- Rules: `AGENTS.md`、Marionettist workflow、sy-standards workspace rules。
- Docs: 冻结稿第 7、8、10、13、15 章,`docs/decisions.md` D05/D19/D20/D22/D25/D27/D28/D32~D35,`docs/tasks/INDEX.md`、`CHECKLIST-v1.md`、M05 交接、测试计划。
- Standards: `api-envelope?version=1.1.0`、`error-handling?version=1.1.1`、`permission-nodes?version=1.0.0`、`frontend-stack?version=2.1.0`、`element-plus?version=1.0.2`、`code-comments?version=1.1.1`、`security/red-line?version=1.1.0`。
## Dependency Direction
`MappedInputRevision`/正式异常事实 + 合成场景发布快照 → 报警 occurrence → 报警实例 → 追加式处理记录 → API → UI。M07/M09 以后读取报警身份和关闭有效性;M06 不依赖它们的表或执行器。M08 正式发布就绪后按 requirement「M08 收尾备注」替换合成快照路径。
## Boundary Risks
- 正式 occurrence 必须与试算隔离(D35)。
- 合成快照只做最小字段;不得建正式场景表(D35 + M08 收尾)。
- 处理范围来自合成快照声明,禁止默认 operator 全租户(D35)。
- 报警创建/合并、并发接手/关闭需要 PostgreSQL 唯一约束、行锁或乐观并发;SQLite 或纯 Mock 不足以验收。
- 公司权限规范禁止编造权限点;编码与注册方式必须在权限切片先核对。
- 公司信封建议 cursor 分页,但 D25 已确认本项目业务列表使用 `page/page_size`;M06 沿用项目契约。
## Recommended Modification Path
1. 建报警/occurrence/判定引用与历史关联,数据库强制租户隔离和幂等。
2. 建正向状态服务和追加式处理记录,再接后端权限与快照范围。
3. 接只读与命令 API;写命令要求幂等键并返回明确冲突。
4. 原型确认后实现 Vue,最后做模块整体审查、正式测试与视觉证据。
## Uncertainty
- 无阻塞业务不确定性。表名和合并键字段布局可在 S1 按现有模型风格落地,但不得扩大到可编排工作流或 M08 正式场景表。
- 权限点字面值不是可照邻近模块编造的实现细节。S3 必须先对照 `standards://api/permission-nodes?version=1.0.0` 与仓库已有节点;规范和仓库都没有报警权限点时停止并询问。
- 「处理范围」只确认了来源和缺省拒绝。字段布局未冻结,不得写成新的已确认授权模型。
@@ -0,0 +1,159 @@
# Task Context Pack
## Task Goal
实现 M06 报警创建/有限合并、列表/详情、接手、进展、关闭、新周期关联和 UI;不发送真实消息。
## Knowledge Posture
- Mode: `standard`
- Maturity: `L1`
## Current Slice Or Group
无已批准编码片。提议下一片为 S1;requirement 已冻结(D32~D35),等待 plan-review critic 与分析→编码确认;`allowedToCode=false`。
## Gate Policy
- Config Default: `balanced`
- Recommended: `strict`
- Selected / Effective: `autonomous`
- finalApprovalRequired: `true`
- Policy Notes: 用户选择覆盖默认,但不取消分析确认、Tier L critic、`risk_score >= 4`、原型确认和最终批准。
## Requirement Source
`.task/2026-11-19/m06-alarm-center/requirement.md`(已冻结)
## Implementation Source
`.task/2026-11-19/m06-alarm-center/implementation-plan.md`(待 plan critic / 编码前门禁批准)
## Involved Modules Or Areas
M05 输入修订/判定、M01 审计/运行、M02 会话角色、新报警领域、控制台。
## Loaded Context
### Global Rules
- `AGENTS.md`
- `.cursor/rules/workflow-rules.mdc`
- `.cursor/rules/sy-standards.mdc`
- `.cursor/rules/00-repository-rules.mdc`
### Knowledge Map Matches
- 产品范围与进度:`docs/progress.md`、`docs/decisions.md`、冻结稿、INDEX。
- 公司规范与 Marionettist:workflow 与 sy-standards。
- 控制台界面:`docs/current/frontend-ui.md`。
### Path-Proximity Rules
目标源码路径向上只有仓库根 `AGENTS.md`,未发现更近的 `MODULE_RULES.md` 或 `HARNESS_RULES.md`。
### Excluded Context
未加载 M07 企微实现、M08 Cron 复用、M09 次数策略、阶段 B/C 细节;它们不属于当前实现范围。
## Loaded Rules And Standards
- `standards://api/api-envelope?version=1.1.0`
- `standards://api/error-handling?version=1.1.1`
- `standards://api/permission-nodes?version=1.0.0`
- `standards://frontend/frontend-stack?version=2.1.0`
- `standards://frontend/element-plus?version=1.0.2`
- `standards://engineering/code-comments?version=1.1.1`
- `standards://security/red-line?version=1.1.0`
## Loaded Docs
- `需求冻结文档_V1.1_交接稿.md`
- `docs/tasks/INDEX.md`、`docs/tasks/CHECKLIST-v1.md`
- `docs/decisions.md`、`docs/testing-plan.md`
- `docs/current/frontend-ui.md`
- M05 requirement、context、boundary、implementation plan
## Execution Mode
- Mode: sequential
- Current Slice Or Group: none
- Parallel Members: none
- Fallback Order: S1 → S2 → S3 → S4 → S5 → S6
- Shared Files: migrations、model exports、auth、API app、router、locales
- Merge Owner: 主 Agent
- Conflict Resolution Rule: 共享文件和迁移串行;不得覆盖任务开始前的未提交修改。
- Validation Level: analysis only / NOT_RUN
## Execution Chain
正式异常事实 → occurrence 幂等 → 报警创建/有限合并 → 追加式人工状态历史 → API 权限 → 原型 → Vue → 整体 review/正式验证。
## Allowed Modification Scope
当前仅任务文档、`docs/tasks/M06.md`、`docs/progress.md`、`.task/active.json`。编码获批后按 implementation-plan 当前片逐片开放。
## Forbidden Modification Scope
当前禁止所有业务源码。全任务禁止 M07/M08/M09、真实消息、自动恢复、转派/重开/审批、生产库、凭证、未授权提交,以及覆盖既有工作区修改。
## Key Existing Classes Or Entrypoints
- M05:`models/mapping.py` 的 `MappedInput`/`MappedInputRevision`;`services/judgment.py` 的纯 `evaluate_rows`;`api/routes/mappings.py` 仅试算。
- M01:`models/platform.py` 的 `RunRecord`/`AuditEvent`,无场景发布快照。
- 权限:`auth/access.py`、`auth/principal.py`;当前角色存在但对象范围仍未实现。
- API:`api/app.py` 统一 handler/路由注册。
- UI:`web/apps/console/src/router.ts`、`api.ts`、四语言 common/errors。
- Alarm skeleton: 未发现。
## Required Behavior
以已冻结 requirement 与 D32~D35 为准。
## Non-goals
消息发送、场景/Cron、次数/升级、可编排工作流引擎、自动恢复、转派、重开、审批、真实系统联调。
## Implementation Steps
见 implementation-plan;当前不执行。
## Test Strategy
- Commands: 真实 PostgreSQL migration + pytest;前端 unit/typecheck/build;Playwright U06。
- Required Evidence: RLS、幂等、并发创建/接手/关闭、越范围拒绝、试算零报警、V030~V037,以及 V042 的 M06 部分、三视口截图。V038~V041 不属于本模块。
- Allowed NOT_RUN Reasons: 本轮为分析与 plan-review,尚未获批编码候选。D32~D35 已冻结,不得再以口径未定跳过以后的 PostgreSQL、RLS 和并发验证。NOT_RUN 不计 PASS。
## Validation Commands
- `cd services/watchman && uv run alembic upgrade head`
- 隔离 PostgreSQL 上 M06 迁移 downgrade/upgrade
- `cd services/watchman && uv run pytest`
- `cd web/apps/console && pnpm test:unit`
- `cd web/apps/console && pnpm typecheck`
- `cd web/apps/console && pnpm build`
- `cd web/apps/console && pnpm test:e2e -- alarms.spec.ts`
## Assumptions
- 合成数据/Mock 默认;不触达真实 MES 或企微。
- D22/D25 和项目现有 `page/page_size` 契约继续适用。
- 关闭有效性只由报警终态导出,不创建通知/升级任务、意图行或次数窗口。
## Risks
- 正式判定入口缺失,不能复用试算产生副作用。
- 场景快照和数据范围缺失会导致跨模块兼容或横向越权。
- 数据库唯一约束、RLS 和并发必须在 PostgreSQL 验证。
## Stop Conditions
- plan 未批准或 plan-review critic 未通过。
- 分析→编码门禁未获用户明确确认,`allowedToCode=false`。`autonomous` 不得跳过 S1~S3 完成后的停顿,也不得在用户确认原型前开始 S5。
- 权限点无法按 `standards://api/permission-nodes?version=1.0.0` 与仓库已有节点核对时停止,禁止按 `watchman.*` 邻近模式编造。
- M05 `evaluate_rows` 或试算路由写入 occurrence/报警时停止。
- 出现通知/升级意图表、次数窗口读写,或撤回已受理消息的命令时停止。
- 实现滑向可编排工作流或正式场景表时停止并询问。
- S4 原型未确认时禁止 S5。
- 最终 `DONE_LOCAL` 需要用户批准。
@@ -0,0 +1,228 @@
# M06 报警中心与人工处理 Implementation Plan
## Requirement Source
`.task/2026-11-19/m06-alarm-center/requirement.md`(已冻结;D32~D35)。编码前仍需 plan-review critic 与分析→编码用户确认。
## Scope Summary
报警事实与有限合并、正向人工状态机、追加历史、API、原型确认后的控制台;不发送消息,不实现场景/Cron、次数升级或可编排工作流。
## Involved Modules Or Areas
- `services/watchman`:新 alarm 持久化、服务、API、权限、测试。
- `web/apps/console`:新报警列表/详情、路由、四语言、单测/Playwright。
- 复用:M05 输入修订与版本引用;M01 审计/运行契约;M02 会话角色。
## Loaded Rules And Standards
- `AGENTS.md`、Marionettist workflow、workspace rules。
- `standards://api/api-envelope?version=1.1.0`
- `standards://api/error-handling?version=1.1.1`
- `standards://api/permission-nodes?version=1.0.0`
- `standards://frontend/frontend-stack?version=2.1.0`
- `standards://frontend/element-plus?version=1.0.2`
- `standards://engineering/code-comments?version=1.1.1`
- `standards://security/red-line?version=1.1.0`
## Loaded Docs
- `docs/tasks/INDEX.md`、`docs/tasks/CHECKLIST-v1.md`
- `docs/decisions.md`
- `需求冻结文档_V1.1_交接稿.md`
- `docs/current/frontend-ui.md`、`docs/testing-plan.md`
- M05 requirement/context/boundary 及实际 M05 模型、服务、试算路由。
## Global Forbidden Scope
- M07 企微/真实消息、M08 场景/Cron/正式发布实体、M09 次数/升级、可编排工作流引擎。
- 自动恢复、转派、重开、审批、批量关闭。
- 改写 M05 输入/修订/判定事实;把试算当正式异常。
- 编造权限点;用前端隐藏替代后端权限;默认 operator 全租户。
- 改已合入迁移;生产库/真实外发/凭证/`.env.local`/`.cursor/mcp.json`。
- 未授权 Git commit、push 或覆盖任务开始前的工作区修改。
## Execution Strategy
- Complexity: complex / Tier L
- Default Execution: sequential
- Parallel Execution: not-needed
- Fallback Execution: sequential
- Merge Owner: 主 Agent
- Conflict Resolution Rule: 迁移、`auth/access.py`、`auth/principal.py`、`api/app.py`、前端 router/locales 均串行;后片不得改前片冻结的状态与幂等语义。
- Critic: requirement 冻结后、编码前必须 plan-review;高风险片完成 review/validation 后需 pre-done critic;最终仍需 final approval。
- Gate Policy: selected `autonomous`。它不取消分析→编码确认。S1、S2、S3 完成后必须暂停(`high-risk` 或 `boundary-sensitive`,且 `risk_score >= 4`,并要求 critic)。S4 写完原型也不等于可进入 S5,必须先有用户原型确认。只有该确认已经发生,且下一片仍是已批准的 `simple`/`standard`、`risk_score <= 3`、无 critic、无其他停顿条件时,才可能按 autonomous 续行。S6 必须暂停,最终批准仍然必需。
## Slice Dependency Graph
| Slice | Depends On | Can Run In Parallel With | Fallback Order | Shared Files | Merge Owner | Conflict Risk |
|---|---|---|---:|---|---|---|
| S1 报警事实与合并 | D32~D35 已确认、requirement 冻结、plan critic PASS | 无 | 1 | migrations/models exports | 主 Agent | high |
| S2 人工状态与历史 | S1、D32/D33 | 无 | 2 | migrations/auth | 主 Agent | high |
| S3 API 与权限 | S1、S2、权限点核对 | 无 | 3 | auth/app router | 主 Agent | high |
| S4 HTML 原型 | S3 稳定响应契约 | 无 | 4 | task prototype | 主 Agent | low |
| S5 Vue 报警中心 | S4 用户确认 | 无 | 5 | router/locales | 主 Agent | medium |
| S6 模块审查与正式验证 | S1~S5 | 无 | 6 | evidence/progress | 主 Agent | medium |
## Implementation Slices
### S1 报警事实、occurrence、有限合并与新周期关联
- Goal: 用正式异常事实原子创建/关联报警,重复 occurrence 幂等,新独立事件可新建并关联历史。
- Allowed Scope: 新 alarm models/services/migration/tests;必要的模型导出;仅引用 M05/M01。
- Forbidden Scope: 人工处理 API/UI、M07/M08/M09、修改旧迁移。
- Mode: sequential
- Depends On: D32~D35;plan critic PASS;分析→编码确认。
- Gate Class: `high-risk`
- Risk Score: `5`
- Gate Reasons: `database-schema`, `alarm-dedup`, `merge-semantics`, `cross-module-contract`
- Critic: plan-review 前置;片后 pre-done。
- Validation Level: slice
- Steps:
1. 新表启用/强制 RLS,租户由服务端注入。
2. occurrence 稳定幂等键、判定/输入修订/合成快照引用及数据库唯一约束。
3. 报警结构化 merge key、有效范围、新事件历史关联。
4. 使用事务与锁/约束处理并发创建,不按文本合并。
5. PASS/UNKNOWN/执行失败无报警副作用。M05 `evaluate_rows` 与试算路由不得写入 occurrence 或报警。
6. 同周期值更正只追加 M05 修订并保留依据;不改写原始 FAIL,不自动新建报警,不自动重发。
- Validation:
- `cd services/watchman && uv run alembic upgrade head`
- 隔离的真实 PostgreSQL 上做 migration downgrade/upgrade、RLS、并发、重复、新周期、同周期修订,以及试算零报警行。SQLite 或纯 Mock 不能当作本片通过。
- Done Criteria: V030~V033 数据侧通过;重复提交只产生一个 occurrence。D35 最小快照契约已冻结,实施时不得扩成 M08 正式场景表。
- Rollback Notes: 新迁移只新增;已合入后不得改旧迁移,修正用新迁移。
### S2 正向状态机、处理历史与关闭有效性
- Goal: `pending -> processing -> closed`、进展追加、并发保护;落实 D36(关闭后同键不重开但留依据/日志);关闭后未执行意图是否仍有效只由报警终态导出。
- Allowed Scope: 新 alarm handling service/models/migration/tests;修正 S1 `record_formal_failure` 对已关闭同键的行为以符合 D36。主体判断只用当前处理人与既有三角色,不改权限点常量。
- Forbidden Scope: 通知/升级任务表、意图行、次数窗口的读写或清零、撤回已受理消息、直接关闭、转派、重开、自动恢复、可编排工作流。不得注册或编造权限点;本片的主体判断只用当前处理人与既有三角色,权限点字面值留到 S3。
- Mode: sequential
- Depends On: S1;D32/D33/D35/D36。
- Gate Class: `high-risk`
- Risk Score: `5`
- Gate Reasons: `permissions`, `state-machine`, `concurrency`, `terminal-state`
- Critic: 片后 pre-done。
- Validation Level: slice
- Steps:
1. 原子接手并记录唯一当前处理人/接手时间。
2. 追加进展,不更新旧记录。
3. 校验关闭主体、结果、说明,追加终态记录。
4. 并发/重复命令幂等,相同键不同 payload 冲突。
5. 关闭有效性只由终态导出:`closed` 表示绑定该报警的未执行意图应视为失效。不落意图行,不提供撤回,不读写、不清零 M09 次数窗口。
6. D36:已关闭同合并键再来正式异常时,不重开、不新开;追加可追溯依据和审计日志;更新 S1 相关测试。
- Validation: 隔离的真实 PostgreSQL 并发测试覆盖 V034~V037,以及 V042 的 M06 部分(关闭不清零、不建窗口或意图表、新旧报警身份不混淆、无撤回接口);另加 D36 关闭后同键追加依据/日志用例。SQLite 或纯 Mock 不能当作本片通过。V038~V041 不在本片。
- Done Criteria: 无双处理人、无矛盾终态;原始异常和历史不可覆盖;D36 有断言。
- Rollback Notes: 若实现偏离 D33 的三状态和关闭结果枚举,停止,不另加兼容分支。
### S3 报警列表/详情/命令 API 与后端授权
- Goal: 提供分页筛选、详情依据、历史和三类命令,所有读取/操作后端校验。
- Allowed Scope: 新 alarm routes/schemas/dependencies/tests;`auth/access.py`、`auth/principal.py`、`api/app.py` 的最小接入。
- Forbidden Scope: 新角色名、手写错误 JSON、未核对规范的权限点、前端。
- Mode: sequential
- Depends On: S1、S2;`permission-nodes` 核对(范围按 D35)。
- Gate Class: `boundary-sensitive`
- Risk Score: `4`
- Gate Reasons: `api-contract`, `permissions`, `object-scope`, `shared-auth-files`
- Critic: 片后 pre-done。
- Validation Level: slice
- Steps:
1. 先对照 `standards://api/permission-nodes?version=1.0.0` 和仓库已有节点。报警权限点若规范和仓库都不存在,停止并询问,禁止按 `watchman.*` 邻近模式编造。
2. 列表按 D25 后端筛选、排序、`page/page_size`;详情 ID 不得绕过范围。
3. 接手/进展/关闭读取 `x-idempotency-key`,service 抛语义异常。
4. 冲突复用现有 `ConflictError`(HTTP 409,信封码 40000),不新造业务码 409。越权复用 `ForbiddenError`(42000 加权限点)。字段错误走统一信封;新增错误码同步四语言。
- Validation: `cd services/watchman && uv run pytest` 必须打在隔离 PostgreSQL 上,覆盖 admin/operator/viewer、越范围 ID、HTTP 409、幂等和信封。不得用 SQLite 或 Mock 代替授权与租户隔离断言。
- Done Criteria: A-040~A-043 API 侧通过;无范围来源时禁止开放 operator。
- Rollback Notes: 撤回新路由/依赖,不改变既有角色和查询/映射权限。
### S4 HTML 原型确认
- Goal: 在正式 Vue 前确认列表、详情、接手、进展、关闭和冲突反馈。
- Allowed Scope: `.task/2026-11-19/m06-alarm-center/prototype/`
- Forbidden Scope: `web/apps/console` 正式页面。
- Mode: sequential
- Depends On: S3 响应字段稳定。
- Gate Class: `simple`
- Risk Score: `2`
- Gate Reasons: `prototype-before-vue`
- Critic: no;需用户原型确认。
- Validation Level: slice
- Steps: 静态走通 U06;核对 D22/D25、非恢复文案、关闭校验与冲突提示。
- Validation: 浏览器人工检查三个桌面视口。
- Done Criteria: 用户确认原型后才允许 S5。
- Rollback Notes: 删除原型不影响产品。
### S5 Vue 报警中心
- Goal: 实现报警筛选列表、详情依据、处理历史及接手/进展/关闭交互。
- Allowed Scope: `web/apps/console/src/alarms/`、最小 router/nav、四语言、unit/e2e。
- Forbidden Scope: 修改后端业务语义、前端伪造授权、通知/升级页面。
- Mode: sequential
- Depends On: S4 用户确认。
- Gate Class: `standard`
- Risk Score: `3`
- Gate Reasons: `ui-contract`, `confirmed-prototype`, `shared-router-locales`
- Critic: no per-slice;仍纳入 Tier L 最终 pre-done。
- Validation Level: slice
- Steps:
1. Element Plus 具名导入,沿用现有 console 骨架与客户端。
2. 列表加载/空/无匹配/失败/无权;服务端排序分页。
3. 详情展示依据和处理历史;命令 loading、防重复、409 刷新提示。
4. 四语言同步,不把服务端 message 直接展示。
- Validation:
- `cd web/apps/console && pnpm test:unit`
- `cd web/apps/console && pnpm typecheck`
- `cd web/apps/console && pnpm build`
- Playwright U06,1440×900、1280×800、1920×1080。
- Done Criteria: A-044~A-047 UI 侧通过,关闭后无误操作且不显示恢复。
- Rollback Notes: 撤回新页面、路由与文案,不删后端事实。
### S6 模块整体审查、正式验证与收口
- Goal: 对 S1~S5 做独立整体 review、修复复审、正式测试和视觉检查。
- Allowed Scope: 切片内缺陷;M06 任务/证据/进度文档。
- Forbidden Scope: 借修复扩到 M07/M08/M09;未重审重测即标 DONE。
- Mode: sequential
- Depends On: S1~S5。
- Gate Class: `boundary-sensitive`
- Risk Score: `4`
- Gate Reasons: `module-acceptance`, `tier-l`, `final-validation`
- Critic: reviewer 后 pre-done 必须执行。
- Validation Level: final
- Steps:
1. 高风险两阶段 diff review,重点为幂等、合并、并发、权限、RLS 和边界。
2. 修复后复审,最多三次。
3. 正式后端、迁移、前端、Playwright 与截图;记录 Mock/未运行/真实阻塞。
4. 用户最终批准后才标 `DONE_LOCAL`。
- Validation: 下述 Final Validation 全部适用命令。
- Done Criteria: reviewer PASS/PASS_WITH_WARNINGS、pre-done critic PASS、验证证据齐全;最终批准仍必需。
- Rollback Notes: 迁移缺陷先停并用新迁移修正,不做破坏性回滚。
## Parallel Slice Groups
无。迁移、权限、路由和业务语义存在顺序依赖。
## Final Validation
- `cd services/watchman && uv run alembic upgrade head`
- 隔离 PostgreSQL 上 downgrade/upgrade(仅 M06 新迁移范围)
- `cd services/watchman && uv run pytest`
- `cd web/apps/console && pnpm test:unit`
- `cd web/apps/console && pnpm typecheck`
- `cd web/apps/console && pnpm build`
- `cd web/apps/console && pnpm test:e2e -- alarms.spec.ts`
- 专项:V030~V037,以及 V042 的 M06 部分;U06 三视口;跨租户、越范围、重复/并发命令。RLS、唯一约束和并发接手/关闭只认隔离 PostgreSQL,不认 SQLite 或纯 Mock。V038~V041 不在本模块。
## Documentation Update Requirement
- 实施中更新 `docs/tasks/M06.md`、`docs/progress.md` 与 `docs/evidence/M06/summary.md`。
- D32~D35 已由用户确认并写入 `docs/decisions.md`。编码时不得把 O04/O05/O06 重新当成未决问题,也不得改写这些已确认结论。
- S6 正式验证前,把 `docs/testing-plan.md` 的 V033、V042 期望改成 D34、D32 口径。当前 V042 仍写「不预设窗口是否清零」,不能当作 M06 的测试真源。
- 行为/边界意义改变时再评估 current docs 与 knowledge map;仅新增源码不更新 knowledge map。
## Risks
- `planApproved=false`,`allowedToCode=false`。plan-review 通过不等于可以写业务代码,仍须用户明确确认分析→编码。
- D32~D35 已关闭范围、快照和正式异常契约。未声明的处理范围必须拒绝,禁止回退为 operator 全租户。
- M05 只有试算路径。`evaluate_rows` 和试算路由不得产生报警或 occurrence。
@@ -0,0 +1,59 @@
# Task Intake Result
## Task Type
feature。Tier L:M06 是跨数据库、状态机、权限、API 与 UI 的新模块,且 O04/O05/O06 会改变核心业务语义。
## Tier Policy
- Active Source: 项目本地 `.marionettist/tier-policy.yml`,结构有效,未使用 fallback。
- Selected Tier: L
- Description: complex, cross-cutting, boundary-sensitive, or concretely high-risk work。
- Match Rules: 多区域、跨边界、工作流敏感;数据库并发、权限及状态终态具有具体高风险。
- Workflow Hint: `full-marionettist`
- Gate Hint: `prefer-strict`(仅建议)
- Review Level: `critic-required`
- Model Profile Hint: `think`
- minTier / maxTier: `L` / `null`
- Warning: `modelProfileHint` 自动交叉校验仍是 deferred hardening;本仓 `.marionettist/model-profiles.yml` 已存在 `think: gpt-5.6-sol`。
## Current Understanding
- 前置 M05 已 `DONE_LOCAL`。M06 覆盖 P-006、A-037~A-047。
- 范围:报警创建/有限范围合并、列表/详情、接手、进展、关闭、新周期关联和控制台 UI。
- 不做:真实消息、M07 企微、M08 场景/Cron、M09 次数窗口/升级。
- D05 已确认同一输入不重新触发,关闭后新统计周期或独立事件可以新建并关联历史。
- 现有代码没有 alarms 模型、服务、路由或页面。M05 已有 `MappedInputRevision` 与纯试算结论,但没有持久化的正式判定事件。
- M01 只有通用 `RunRecord`/审计记录,没有场景发布快照实体。M06 不能顺手建设 M08。
- 当前权限只按 Casdoor 三角色判断;`require_object_access` 仍默认拒绝,没有“范围内处理者”的数据范围来源。
- 工作区在本任务开始前已有未提交修改;本任务不得覆盖这些修改,也不提交 Git。
## Gate Policy
- config/default: `balanced`
- allowTaskOverride: `true`
- recommended: `strict`(Tier L、迁移、权限、并发状态机和开放业务口径)
- selected: `autonomous`
- reason or override reason: 用户在 M06 入口明确指定。
- effective: `autonomous`
- finalApprovalRequired: `true`
- policy notes: `autonomous` 不取消分析→编码确认、critic、`risk_score >= 4`、业务阻塞、原型确认或最终批准。
## Blocking Questions
1. O04:关闭怎样终结本报警尚未执行的通知/升级意图;已受理消息不可撤回;次数窗口是否继续累计可延后 M09。
2. O05:接手/关闭主体、关闭结果枚举、说明要求,以及“范围内”的授权来源。
3. O06:同周期值更正对原报警及新报警的影响。
4. M01/M08 边界:M06 使用的合成发布快照最小字段与稳定身份尚无现成代码契约。
## Non-blocking Assumptions
- 状态仅允许 `pending -> processing -> closed`;不做直接关闭、转派、重开、审批或自动恢复。
- 人工操作追加记录,不覆盖原始异常判定、输入修订或旧处理记录。
- PostgreSQL、RLS、服务端租户注入、统一信封、四语言与现有 D22/D25 页面布局继续沿用。
- 列表分页沿用项目已确认的 `page/page_size`,不在 M06 改造全仓分页协议。
## Recommended Next Step
先由用户确认 O04/O05/O06、处理范围来源和合成发布快照契约;随后更新 requirement 为冻结状态,运行 Tier L 计划 critic,再请求跨越分析→编码门禁。
@@ -0,0 +1,92 @@
# M06 报警中心 · 静态 HTML 原型(S4)
**状态:待用户确认。确认前不得据此编写 Vue 页面,不得开始 S5。**
## 如何打开
用浏览器直接打开本目录的 `index.html`(双击即可)。单文件,无构建、无 CDN、无接口请求。侧栏 logo 使用仓库里的 `web/apps/console/src/assets/logo.jpg`,用相对路径引用;打不开时只少一张图,页面仍可走查。
路径:`.task/2026-11-19/m06-alarm-center/prototype/index.html`
刷新页面会回到初始样例。走查改过的数据也可以点原型条上的「还原样例」。
## 黄色原型条
顶部黄条不是未来产品,只用于切换角色、主体和画面。正式 Vue 会删掉它。
- **角色**:管理者 / 处理者 / 查看者。查看者能看列表和详情。接手、进展、关闭会提示无权,并带上对应权限点。
- **主体**:`subj-chen`、`subj-lin`、`subj-zhao`,或「无」。无主体时列表为空,文案说明没有处理范围,不是租户里没有报警。
- **画面**:样例、加载中、空列表、加载失败、无权、范围外。无权和范围外不看当前角色,用来确认这两种版式。
- **模拟**:不模拟 / 接手冲突 / 幂等冲突。后两个会让下一次对应操作失败且不写历史。「再次关闭」只在已经打开一条已关闭报警时有意义。
## 主要页面
| 页面 | 内容 |
| --- | --- |
| 列表 | 模块、场景名称、对象、最近发生起止、状态。点「查询」才筛选,「重置」清空再查。没有等级筛选项,也没有等级列。表头排序对应 `sort_by` / `sort_order`,底栏分页对应 `page` / `page_size`(10 / 20 / 50,默认 20)。行内只有「打开」。没有「新建」。 |
| 详情 | 摘要、观测(观测时间 / 计划时间 / 接收时间分列)、判定演示、同周期修订、关闭后依据、处理历史。页脚居中:返回列表、接手、追加进展、关闭。已关闭后页脚只留返回列表。 |
| 接手 | 待处理可接手。已有其他处理人时提示冲突,不改当前处理人。管理者也不能把处理人抢走。 |
| 进展 | 只有当前处理人能写。说明必填,证据引用选填。 |
| 关闭 | 结果只有「已处理 / 误报」,说明必填。待处理不能直接关闭。处理中可由当前处理人或管理者关闭。管理者关闭不替换原来的处理人。 |
| 状态 | 加载中、还没有报警、没有符合条件的报警、加载失败(可重试)、无权、没有找到这条报警、没有处理范围。文案是固定中文,不展示服务端原文。 |
样例是虚构的炉温、气压和尺寸数据。`alm-1003` 已关闭,并且带一条关闭后依据:报警保持已关闭,最近发生和观测次数都不改。页面正文不使用「已恢复」。
## 和 S3 接口的对应
列表筛选对应已有参数:`module_key`、`scenario_name`(包含)、`mapped_input_id`、`status`、`occurred_from` / `occurred_to`(按最近发生)。排序字段与 `alarm_reads._SORT` 一致。对象列不排序,因为接口不能按身份键排序。
详情里的计划时间、规则原文、实际值和比较值**不是**当前接口字段,表格和判定块里写了「演示」。occurrence 接口现有观测时间、接收时间、创建时间。创建时间没有单独做列,避免和计划时间混在一起。
权限点只用 D38 已有四个,没有新编码:
- `perm:data:emp:watchman.alarm.read`
- `perm:data:emp:watchman.alarm.take`
- `perm:data:emp:watchman.alarm.progress`
- `perm:data:emp:watchman.alarm.close`
## 按钮位置
- 列表的「查询 / 重置」在表格上方。分页在底栏右对齐,不放页面操作。报警没有「新建」。
- 行内「打开」留在该行,操作列宽按 1 个链接按钮约 72px。
- 详情的返回、接手、进展、关闭在页脚居中,正文滚动时页脚留在滚动区域外面。
- 关闭和进展用 480px 对话框。说明没填、关闭结果没选,对话框不关。提交中按钮变为「提交中」并不能再点。
约定来自 D22、D25 和 `docs/current/frontend-ui.md`。S5 再用 Element Plus 具名组件实现,不要把本页的原生按钮抄进正式页面。
## 建议走查
1. 默认管理者、`subj-chen`、样例。改筛选条件先不点查询,列表应不变。再点查询、重置。
2. 点「最近发生」切换升降序。底栏仍是分页,不是操作按钮。
3. 打开 `alm-1001`。先点关闭,应提示待处理不能直接关闭。再接手、追加进展(空说明应被拦住)、关闭(不选结果、不填说明应被拦住;选「已处理」并填写后变为已关闭)。页脚不再提供接手和关闭。
4. 切到处理者 `subj-zhao`,打开 `alm-1002`(当前处理人是 `subj-lin`)。接手、进展、关闭都应被拒绝,处理人不变。
5. 切回管理者,打开同一条,关闭对话框应能打开(管理者可以关闭,但不能写进展)。
6. 切到查看者,点接手,应看到无权和 `watchman.alarm.take`。列表本身仍在。
7. 用原型条看加载中、空列表、加载失败、无权、范围外,以及主体「无」。
8. 打开 `alm-1003`,看关闭后依据和三条处理历史。点「再次关闭」,历史条数不应增加。确认页面没有「已恢复」。
## 三个桌面视口请人眼看
本片没有跑 Playwright,也没有在浏览器里把窗口改成这三个尺寸。下面是确认时要看的点。黄条会占高度,判断时看黄条下面的产品区域。
| 视口 | 看什么 |
| --- | --- |
| 1440×900 | 筛选可以换行,但表格和底部分页仍同时可见。详情页脚的按钮居中,正文往下滚时页脚不跟着走。操作列不撑得很宽。 |
| 1280×800 | 黄条换行后,列表底栏和详情页脚仍留在窗口里。筛选换行后表格还看得见表头。表格若放不下,只在表格区域内横向滚动,整页不跟着左右滚。详情事实区仍能读,页脚按钮可以换行,但保持居中。 |
| 1920×1080 | 表格拉开后操作列仍大约 72px。筛选控件保持各自宽度,不拉成整行一条。详情卡片随内容区变宽,页脚仍居中。 |
## 请确认后再做 S5
1. 列表和详情都不放等级。需求原文写过等级,报警行没有这个字段。S5 在有字段来源之前也不做。
2. 计划时间是否只为这次看版式。若 S5 不展示计划时间,详情只保留观测时间和接收时间。
3. 规则原文、实际值、比较值是否留到有接口字段再做。S5 可以先只展示观测、依据和处理历史。
4. 查看者是继续显示接手 / 进展 / 关闭并在点击后提示无权,还是按角色不显示这些按钮。不显示也不代替后端检查。
5. 已关闭后页脚只留「返回列表」。再次关闭的拒绝只在误操作时出现。
6. 三种空状态的文案:还没有报警;没有符合条件的报警;没有处理范围所以看不到报警。
7. 管理者可以关闭他人已接手的报警,不能替换处理人,也不能代写进展。
## 不包含
- `web/apps/console` 正式页面、后端、M07 / M08 / M09。
- 真实请求、等级、转派、重开、审批、通知和次数升级。
- 四语言。原型只有简体中文。
@@ -0,0 +1,910 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Watchman M06 报警中心 · 静态原型(S4)</title>
<style>
:root {
--primary: #5e6ad2; --primary-soft: #eef0fb; --text: #1f2328; --text-2: #59636e; --muted: #8b949e;
--surface: #ffffff; --soft: #f6f8fa; --border: #d0d7de; --border-2: #eaeef2;
--ok: #1a7f37; --ok-bg: #e9f6ec; --warn: #9a6700; --warn-bg: #fff8e1; --err: #cf222e; --err-bg: #fdecee;
--radius: 8px;
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
}
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body { font-family: var(--font); font-size: 13.5px; color: var(--text); background: var(--soft); line-height: 1.55; display: flex; flex-direction: column; }
button, input, select, textarea { font: inherit; color: inherit; }
button { cursor: pointer; }
[hidden] { display: none !important; }
.proto { flex: none; background: #fffbe6; border-bottom: 1px dashed #d4b106; padding: 8px 16px; display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; font-size: 12.5px; }
.proto-title { font-weight: 600; color: #7a5b00; }
.proto-group { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.proto-group .lbl { color: #7a5b00; }
.proto-btn { border: 1px solid var(--border); background: #fff; border-radius: 6px; padding: 2px 9px; }
.proto-btn.on { background: var(--primary); border-color: var(--primary); color: #fff; }
.proto-note { flex-basis: 100%; color: #7a5b00; }
.shell { flex: 1; min-height: 0; display: flex; }
.side { width: 192px; flex: none; background: var(--surface); border-right: 1px solid var(--border-2); padding: 14px 10px; display: flex; flex-direction: column; }
.brand { display: flex; align-items: center; gap: 8px; font-weight: 700; font-size: 16px; padding: 4px 10px 14px; }
.brand img { width: 28px; height: 28px; object-fit: contain; }
.nav-item { padding: 7px 10px; border-radius: 6px; color: var(--text-2); }
.nav-item.cur { background: var(--primary-soft); color: var(--primary); font-weight: 600; }
.side .who { margin-top: auto; border-top: 1px solid var(--border-2); padding: 12px 10px 4px; color: var(--text-2); font-size: 12.5px; }
.side .who .btn { width: 100%; margin-top: 8px; }
.main { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.top { height: 48px; flex: none; background: var(--surface); border-bottom: 1px solid var(--border-2); display: flex; align-items: center; padding: 0 20px; }
.crumb { color: var(--text-2); }
.crumb b { color: var(--text); font-weight: 600; }
.crumb-btn { border: 0; background: none; padding: 0; color: var(--text-2); }
.crumb-btn:hover { color: var(--primary); }
.content.fill { flex: 1; min-height: 0; overflow: hidden; display: flex; flex-direction: column; }
.content.scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px 20px 24px; }
.listpage { flex: 1; min-height: 0; display: flex; flex-direction: column; padding: 16px 20px 0; }
.tools { display: flex; flex-wrap: wrap; align-items: flex-end; gap: 8px; margin-bottom: 8px; }
.field { display: flex; flex-direction: column; gap: 2px; }
.field span { font-size: 12px; color: var(--muted); }
.field input, .field select { height: 32px; }
.field.w-mod select { width: 132px; }
.field.w-name input { width: 160px; }
.field.w-obj select { width: 132px; }
.field.w-time input { width: 178px; }
.field.w-status select { width: 120px; }
.btn { height: 32px; border: 1px solid var(--border); background: var(--surface); border-radius: 6px; padding: 0 14px; }
.btn.primary { background: var(--primary); border-color: var(--primary); color: #fff; }
.btn.link { height: auto; border: 0; background: none; color: var(--primary); padding: 1px 6px; }
.btn.tiny { height: 28px; padding: 0 10px; }
.btn:disabled { color: var(--muted); background: var(--soft); border-color: var(--border-2); cursor: not-allowed; }
.btn.primary:disabled { color: #fff; background: #b9c0ee; border-color: #b9c0ee; }
.applied { margin: 0 0 8px; color: var(--text-2); font-size: 12px; }
.stage { flex: 1; min-height: 0; overflow: auto; background: #fff; border: 1px solid var(--border-2); border-radius: var(--radius); }
.stage.plain { border: 0; background: transparent; display: flex; align-items: center; justify-content: center; }
table { width: 100%; border-collapse: collapse; min-width: 1040px; }
th { text-align: left; font-weight: 600; color: var(--text-2); background: var(--soft); padding: 9px 12px; border-bottom: 1px solid var(--border-2); position: sticky; top: 0; z-index: 1; }
td { padding: 8px 12px; border-bottom: 1px solid var(--border-2); vertical-align: middle; background: #fff; }
.sort { border: 0; background: none; padding: 0; font-weight: 600; color: inherit; }
.sort.on { color: var(--primary); }
.ops { width: 72px; text-align: right; white-space: nowrap; }
.pagefoot, .listfoot { flex: none; background: var(--surface); border-top: 1px solid var(--border-2); }
.pagefoot { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 8px; padding: 12px 20px; }
.listfoot { display: flex; justify-content: flex-end; align-items: center; gap: 8px; padding: 8px 20px; color: var(--text-2); font-size: 12.5px; }
.listfoot select { height: 28px; width: auto; }
.card { background: var(--surface); border: 1px solid var(--border-2); border-radius: var(--radius); padding: 16px 18px; margin-bottom: 16px; }
.card h3 { margin: 0 0 12px; font-size: 14.5px; }
.card table { min-width: 720px; }
.facts { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px 16px; margin: 0; }
.facts div { min-width: 0; }
.facts dt { color: var(--muted); font-size: 12px; }
.facts dd { margin: 2px 0 0; }
.tag { display: inline-block; padding: 0 8px; border-radius: 10px; font-size: 12px; line-height: 20px; }
.tag.pending { background: var(--warn-bg); color: var(--warn); }
.tag.processing { background: var(--primary-soft); color: var(--primary); }
.tag.closed { background: var(--soft); color: var(--text-2); border: 1px solid var(--border-2); }
.tag.ok { background: var(--ok-bg); color: var(--ok); }
.tag.warn { background: var(--warn-bg); color: var(--warn); }
.banner { border-radius: var(--radius); padding: 8px 12px; margin-bottom: 12px; }
.banner.ok { background: var(--ok-bg); border: 1px solid #b7e0c2; color: #145c2a; }
.banner.warn { background: var(--warn-bg); border: 1px solid #f1dc9a; color: var(--warn); }
.banner.err { background: var(--err-bg); border: 1px solid #f4b8be; color: var(--err); }
.empty { text-align: center; padding: 48px 20px; }
.empty h3 { margin: 0 0 6px; font-size: 15px; }
.empty p { margin: 0; color: var(--text-2); }
.hint { color: var(--muted); font-size: 12px; margin: 8px 0 0; }
.mono { font-family: ui-monospace, Consolas, monospace; font-size: 12.5px; }
.judge { margin-top: 10px; padding-top: 10px; border-top: 1px dashed var(--border-2); }
.judge + .judge { border-top: 1px dashed var(--border-2); }
.spin { width: 22px; height: 22px; border: 2px solid var(--border); border-top-color: var(--primary); border-radius: 50%; animation: spin .8s linear infinite; margin: 0 auto 10px; }
@keyframes spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .spin { animation: none; border-top-color: var(--border); } }
.modal-mask { position: fixed; inset: 0; background: rgba(31,35,40,.4); display: flex; align-items: center; justify-content: center; z-index: 20; padding: 16px; }
.modal { background: #fff; border-radius: var(--radius); padding: 18px 20px; width: 480px; max-width: 100%; }
.modal h3 { margin: 0 0 6px; font-size: 15px; }
.modal label { display: block; margin-top: 12px; }
.modal label span { display: block; font-size: 12px; color: var(--text-2); margin-bottom: 4px; }
.modal textarea { width: 100%; min-height: 96px; resize: vertical; }
.modal .choices { display: flex; gap: 16px; margin-top: 4px; }
.modal .result-row > span { display: block; font-size: 12px; color: var(--text-2); margin: 12px 0 4px; }
.modal .choices label { display: flex; align-items: center; gap: 6px; margin: 0; }
.stage.in { border: 0; border-radius: 0; }
.modal .actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; }
.modal .err { color: var(--err); font-size: 12.5px; margin: 8px 0 0; }
input, select, textarea { border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; background: #fff; }
</style>
</head>
<body>
<div class="proto">
<span class="proto-title">静态原型 · 不是正式页面</span>
<span class="proto-group"><span class="lbl">角色</span>
<button type="button" class="proto-btn" data-act="role" data-role="admin">管理者</button>
<button type="button" class="proto-btn" data-act="role" data-role="operator">处理者</button>
<button type="button" class="proto-btn" data-act="role" data-role="viewer">查看者</button>
</span>
<span class="proto-group"><span class="lbl">主体</span>
<button type="button" class="proto-btn" data-act="subject" data-subject="subj-chen">subj-chen</button>
<button type="button" class="proto-btn" data-act="subject" data-subject="subj-lin">subj-lin</button>
<button type="button" class="proto-btn" data-act="subject" data-subject="subj-zhao">subj-zhao</button>
<button type="button" class="proto-btn" data-act="subject" data-subject="">无</button>
</span>
<span class="proto-group"><span class="lbl">画面</span>
<button type="button" class="proto-btn" data-act="screen" data-screen="ready">样例</button>
<button type="button" class="proto-btn" data-act="screen" data-screen="loading">加载中</button>
<button type="button" class="proto-btn" data-act="screen" data-screen="empty">空列表</button>
<button type="button" class="proto-btn" data-act="screen" data-screen="failure">加载失败</button>
<button type="button" class="proto-btn" data-act="screen" data-screen="forbidden">无权</button>
<button type="button" class="proto-btn" data-act="screen" data-screen="missing">范围外</button>
</span>
<span class="proto-group"><span class="lbl">模拟</span>
<button type="button" class="proto-btn" data-act="sim" data-sim="">不模拟</button>
<button type="button" class="proto-btn" data-act="sim" data-sim="claim">处理冲突</button>
<button type="button" class="proto-btn" data-act="sim" data-sim="idem">幂等冲突</button>
<button type="button" class="proto-btn" data-act="reclose">再次关闭</button>
<button type="button" class="proto-btn" data-act="reset-seed">还原样例</button>
</span>
<div class="proto-note">黄色区域只用于走查,正式页面没有。筛选要点「查询」才生效。关闭只表示人工终态。计划时间列是版式演示,当前接口没有这个字段。</div>
</div>
<div class="shell">
<aside class="side">
<div class="brand"><img src="../../../../web/apps/console/src/assets/logo.jpg" alt=""><span>预警平台</span></div>
<div class="nav-item">概览</div>
<div class="nav-item">数据源</div>
<div class="nav-item">查询</div>
<div class="nav-item">映射与规则</div>
<div class="nav-item cur">报警</div>
<div class="who">
<div id="who">已登录:管理者</div>
<div id="who-sub">主体 subj-chen</div>
<button type="button" class="btn" data-act="logout">退出</button>
</div>
</aside>
<div class="main">
<div class="top"><div class="crumb" id="crumb">预警平台 / <b>报警</b></div></div>
<div class="content fill" id="content"></div>
<div class="pagefoot" id="foot" data-testid="alarm-footer" hidden></div>
<div class="listfoot" id="listfoot" data-testid="alarm-pagination" hidden></div>
</div>
</div>
<div class="modal-mask" id="mask" hidden>
<div class="modal" id="modal" role="dialog" aria-modal="true"></div>
</div>
<script>
var NODES = {
read: "perm:data:emp:watchman.alarm.read",
take: "perm:data:emp:watchman.alarm.take",
progress: "perm:data:emp:watchman.alarm.progress",
close: "perm:data:emp:watchman.alarm.close"
};
var MODULES = { furnace: "炉温模块", utility: "公辅模块", quality: "质量模块" };
var OBJECTS = { "mi-furnace-01": "炉-01", "mi-comp-02": "空压-02", "mi-part-09": "零件-09" };
var ROLE_LABEL = { admin: "管理者", operator: "处理者", viewer: "查看者" };
var STATUS_LABEL = { pending: "待处理", processing: "处理中", closed: "已关闭" };
var COMMAND_LABEL = { claim: "处理", progress: "追加进展", close: "关闭" };
function occ(id, observed, planned, received, cycle, rule, actual, expect) {
return {
id: id, observed_at: observed, planned_at: planned, received_at: received, cycle_key: cycle,
mapping_version: "v2", rule_version: "v2",
judgment: { rule: rule, actual: actual, expect: expect, hit: true }
};
}
function ev(seq, command, actor, role, handler, from, to, note, result, evidence, at) {
return {
seq: seq, command: command, actor_subject: actor, actor_role: role, handler_subject: handler,
from_status: from, to_status: to, note: note, close_result: result, evidence_ref: evidence, recorded_at: at
};
}
function blankDraft() {
return { module: "", scenario: "", object: "", status: "", from: "", to: "" };
}
function buildSeed() {
return [
{
id: "alm-1001", module_key: "furnace", scenario_key: "furnace-overtemp", scenario_name: "炉温超限",
mapped_input_id: "mi-furnace-01", status: "pending", current_handler: null, claimed_at: null, closed_at: null,
close_result: null, occurrence_count: 2, first_occurred_at: "2026-11-19T08:00:00+08:00",
last_occurred_at: "2026-11-19T08:15:00+08:00", previous_alarm_id: null, snapshot_version_no: 3,
cycle_key: "2026-11-19-08", event_key: "evt-1001", opened_at: "2026-11-19T08:00:05+08:00",
occurrences: [
occ("occ-1001-1", "2026-11-19T08:00:00+08:00", "2026-11-19T07:55:00+08:00", "2026-11-19T08:00:20+08:00", "2026-11-19-08", "炉温大于 80", "91.2", "80"),
occ("occ-1001-2", "2026-11-19T08:15:00+08:00", "2026-11-19T08:10:00+08:00", "2026-11-19T08:15:18+08:00", "2026-11-19-08", "炉温大于 80", "93.0", "80")
],
revision_evidence: [{ id: "ev-1001-1", occurrence_id: "occ-1001-1", recorded_at: "2026-11-19T08:20:00+08:00", mapping_version: "v2", rule_version: "v2", snapshot_version_no: 3 }],
closed_basis: [],
history: []
},
{
id: "alm-1002", module_key: "utility", scenario_key: "air-pressure", scenario_name: "气压偏低",
mapped_input_id: "mi-comp-02", status: "processing", current_handler: "subj-lin",
claimed_at: "2026-11-19T08:50:00+08:00", closed_at: null, close_result: null, occurrence_count: 1,
first_occurred_at: "2026-11-19T08:40:00+08:00", last_occurred_at: "2026-11-19T08:40:00+08:00",
previous_alarm_id: null, snapshot_version_no: 3, cycle_key: "2026-11-19-08", event_key: "evt-1002",
opened_at: "2026-11-19T08:40:06+08:00",
occurrences: [occ("occ-1002-1", "2026-11-19T08:40:00+08:00", "2026-11-19T08:35:00+08:00", "2026-11-19T08:40:11+08:00", "2026-11-19-08", "气压低于 0.60", "0.42", "0.60")],
revision_evidence: [], closed_basis: [],
history: [ev(1, "claim", "subj-lin", "operator", "subj-lin", "pending", "processing", null, null, null, "2026-11-19T08:50:00+08:00")]
},
{
id: "alm-1003", module_key: "furnace", scenario_key: "furnace-overtemp", scenario_name: "炉温超限",
mapped_input_id: "mi-furnace-01", status: "closed", current_handler: "subj-lin",
claimed_at: "2026-11-18T15:00:00+08:00", closed_at: "2026-11-18T16:30:00+08:00", close_result: "resolved",
occurrence_count: 1, first_occurred_at: "2026-11-18T14:40:00+08:00", last_occurred_at: "2026-11-18T14:40:00+08:00",
previous_alarm_id: null, snapshot_version_no: 3, cycle_key: "2026-11-18-14", event_key: "evt-1003",
opened_at: "2026-11-18T14:40:04+08:00",
occurrences: [occ("occ-1003-1", "2026-11-18T14:40:00+08:00", "2026-11-18T14:35:00+08:00", "2026-11-18T14:40:09+08:00", "2026-11-18-14", "炉温大于 80", "88.4", "80")],
revision_evidence: [],
closed_basis: [{
id: "basis-1003-1", observed_at: "2026-11-19T07:05:00+08:00", received_at: "2026-11-19T07:05:12+08:00",
recorded_at: "2026-11-19T07:05:20+08:00", cycle_key: "2026-11-18-14", event_key: "evt-1003-later"
}],
history: [
ev(1, "claim", "subj-lin", "operator", "subj-lin", "pending", "processing", null, null, null, "2026-11-18T15:00:00+08:00"),
ev(2, "progress", "subj-lin", "operator", "subj-lin", "processing", "processing", "已核对现场读数,仍高于阈值。", null, "rec-temp-118", "2026-11-18T15:40:00+08:00"),
ev(3, "close", "subj-lin", "operator", "subj-lin", "processing", "closed", "现场已完成处置并复核读数。", "resolved", null, "2026-11-18T16:30:00+08:00")
]
},
{
id: "alm-1004", module_key: "quality", scenario_key: "dimension", scenario_name: "尺寸超差",
mapped_input_id: "mi-part-09", status: "closed", current_handler: "subj-zhao",
claimed_at: "2026-11-17T09:10:00+08:00", closed_at: "2026-11-17T09:40:00+08:00", close_result: "false_positive",
occurrence_count: 1, first_occurred_at: "2026-11-17T09:00:00+08:00", last_occurred_at: "2026-11-17T09:00:00+08:00",
previous_alarm_id: null, snapshot_version_no: 2, cycle_key: "2026-11-17-09", event_key: "evt-1004",
opened_at: "2026-11-17T09:00:08+08:00",
occurrences: [occ("occ-1004-1", "2026-11-17T09:00:00+08:00", "2026-11-17T08:55:00+08:00", "2026-11-17T09:00:16+08:00", "2026-11-17-09", "尺寸大于 12.0", "12.4", "12.0")],
revision_evidence: [], closed_basis: [],
history: [
ev(1, "claim", "subj-zhao", "operator", "subj-zhao", "pending", "processing", null, null, null, "2026-11-17T09:10:00+08:00"),
ev(2, "close", "subj-zhao", "operator", "subj-zhao", "processing", "closed", "核对后确认是标定漂移,不是工艺异常。", "false_positive", null, "2026-11-17T09:40:00+08:00")
]
},
{
id: "alm-1005", module_key: "quality", scenario_key: "dimension", scenario_name: "尺寸超差",
mapped_input_id: "mi-part-09", status: "pending", current_handler: null, claimed_at: null, closed_at: null,
close_result: null, occurrence_count: 1, first_occurred_at: "2026-11-19T10:05:00+08:00",
last_occurred_at: "2026-11-19T10:05:00+08:00", previous_alarm_id: null, snapshot_version_no: 3,
cycle_key: "2026-11-19-10", event_key: "evt-1005", opened_at: "2026-11-19T10:05:04+08:00",
occurrences: [occ("occ-1005-1", "2026-11-19T10:05:00+08:00", "2026-11-19T10:00:00+08:00", "2026-11-19T10:05:10+08:00", "2026-11-19-10", "尺寸大于 12.0", "12.8", "12.0")],
revision_evidence: [], closed_basis: [], history: []
},
{
id: "alm-1006", module_key: "furnace", scenario_key: "furnace-overtemp", scenario_name: "炉温超限",
mapped_input_id: "mi-furnace-01", status: "pending", current_handler: null, claimed_at: null, closed_at: null,
close_result: null, occurrence_count: 1, first_occurred_at: "2026-11-19T11:20:00+08:00",
last_occurred_at: "2026-11-19T11:20:00+08:00", previous_alarm_id: "alm-1001", snapshot_version_no: 3,
cycle_key: "2026-11-19-11", event_key: "evt-1006", opened_at: "2026-11-19T11:20:05+08:00",
occurrences: [occ("occ-1006-1", "2026-11-19T11:20:00+08:00", "2026-11-19T11:15:00+08:00", "2026-11-19T11:20:12+08:00", "2026-11-19-11", "炉温大于 80", "90.1", "80")],
revision_evidence: [], closed_basis: [], history: []
}
];
}
var state = {
role: "admin",
subject: "subj-chen",
screen: "ready",
view: "list",
detailId: null,
draft: blankDraft(),
applied: blankDraft(),
sortBy: "last_occurred_at",
sortOrder: "desc",
page: 1,
pageSize: 20,
notice: null,
dialog: null,
simulate: "",
busy: false
};
var alarms = buildSeed();
var submitToken = 0;
function clone(v) { return JSON.parse(JSON.stringify(v)); }
function esc(s) {
return String(s == null ? "" : s).replace(/[&<>"]/g, function (c) {
return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c];
});
}
function wall(iso) { return iso ? String(iso).slice(0, 16) : ""; }
function fmt(iso) {
var w = wall(iso);
if (!w) return "—";
return w.slice(0, 10) + " " + w.slice(11, 16);
}
function nowIso() {
var d = new Date();
var p = function (n) { return String(n).padStart(2, "0"); };
var off = -d.getTimezoneOffset();
var sign = off >= 0 ? "+" : "-";
var abs = Math.abs(off);
return d.getFullYear() + "-" + p(d.getMonth() + 1) + "-" + p(d.getDate()) + "T" + p(d.getHours()) + ":" + p(d.getMinutes()) + ":" + p(d.getSeconds()) + sign + p(Math.floor(abs / 60)) + ":" + p(abs % 60);
}
function findAlarm(id) {
for (var i = 0; i < alarms.length; i++) if (alarms[i].id === id) return alarms[i];
return null;
}
function resultLabel(v) {
if (v === "resolved") return "已处理";
if (v === "false_positive") return "误报";
return "—";
}
function tag(kind, text) { return '<span class="tag ' + kind + '">' + esc(text) + "</span>"; }
function statusTag(alarm) {
var extra = alarm.status === "closed" ? " · " + resultLabel(alarm.close_result) : "";
return tag(alarm.status, STATUS_LABEL[alarm.status] + extra);
}
function opt(value, label, current) {
return '<option value="' + esc(value) + '"' + (value === current ? " selected" : "") + ">" + esc(label) + "</option>";
}
function bannerHtml() {
if (!state.notice) return "";
return '<div class="banner ' + state.notice.tone + '" data-testid="alarm-notice">' + esc(state.notice.text) + "</div>";
}
function syncDraft() {
var ids = ["f-module", "f-scenario", "f-object", "f-status", "f-from", "f-to"];
if (!document.getElementById("f-module")) return;
var keys = ["module", "scenario", "object", "status", "from", "to"];
for (var i = 0; i < ids.length; i++) state.draft[keys[i]] = document.getElementById(ids[i]).value;
}
function appliedActive() {
var a = state.applied;
return !!(a.module || a.scenario.trim() || a.object || a.status || a.from || a.to);
}
function filteredRows() {
var a = state.applied;
var name = a.scenario.trim().toLowerCase();
var rows = alarms.filter(function (row) {
if (a.module && row.module_key !== a.module) return false;
if (name && row.scenario_name.toLowerCase().indexOf(name) === -1) return false;
if (a.object && row.mapped_input_id !== a.object) return false;
if (a.status && row.status !== a.status) return false;
var last = wall(row.last_occurred_at);
if (a.from && last < a.from) return false;
if (a.to && last > a.to) return false;
return true;
});
var key = state.sortBy;
var dir = state.sortOrder === "asc" ? 1 : -1;
rows.sort(function (x, y) {
var av = x[key], bv = y[key];
if (av < bv) return -1 * dir;
if (av > bv) return 1 * dir;
if (x.id < y.id) return -1;
if (x.id > y.id) return 1;
return 0;
});
return rows;
}
function appliedLine() {
var a = state.applied;
var parts = [];
if (a.module) parts.push("模块 " + MODULES[a.module]);
if (a.scenario.trim()) parts.push("场景名称包含「" + a.scenario.trim() + "」");
if (a.object) parts.push("对象 " + OBJECTS[a.object]);
if (a.status) parts.push("状态 " + STATUS_LABEL[a.status]);
if (a.from) parts.push("最近发生不早于 " + a.from.replace("T", " "));
if (a.to) parts.push("最近发生不晚于 " + a.to.replace("T", " "));
var sortName = {
module_key: "模块", scenario_name: "场景", last_occurred_at: "最近发生",
first_occurred_at: "首次发生", occurrence_count: "观测次数", status: "状态"
}[state.sortBy];
var sort = "排序:" + sortName + (state.sortOrder === "asc" ? " 升序" : " 降序");
if (!parts.length) return "已生效筛选:无。改条件不会马上变列表,要点「查询」。 " + sort + "。";
return "已生效筛选:" + parts.join(";") + "。" + sort + "。";
}
function sortHead(key, label) {
var on = state.sortBy === key;
var arrow = on ? (state.sortOrder === "asc" ? " ↑" : " ↓") : "";
return '<th><button type="button" class="sort' + (on ? " on" : "") + '" data-act="sort" data-sort="' + key + '">' + esc(label) + arrow + "</button></th>";
}
function toolsHtml() {
var d = state.draft;
var modules = opt("", "全部", d.module);
for (var key in MODULES) modules += opt(key, MODULES[key], d.module);
var objects = opt("", "全部", d.object);
for (var id in OBJECTS) objects += opt(id, OBJECTS[id], d.object);
var statuses = opt("", "全部", d.status) + opt("pending", "待处理", d.status) + opt("processing", "处理中", d.status) + opt("closed", "已关闭", d.status);
return '<div class="tools" data-testid="alarm-list-toolbar">' +
'<label class="field w-mod"><span>模块</span><select id="f-module">' + modules + "</select></label>" +
'<label class="field w-name"><span>场景</span><input id="f-scenario" placeholder="场景名称" value="' + esc(d.scenario) + '"></label>' +
'<label class="field w-obj"><span>对象</span><select id="f-object">' + objects + "</select></label>" +
'<label class="field w-time"><span>最近发生起</span><input id="f-from" type="datetime-local" value="' + esc(d.from) + '"></label>' +
'<label class="field w-time"><span>最近发生止</span><input id="f-to" type="datetime-local" value="' + esc(d.to) + '"></label>' +
'<label class="field w-status"><span>状态</span><select id="f-status">' + statuses + "</select></label>" +
'<button type="button" class="btn primary" data-act="query" data-testid="alarm-filter-search">查询</button>' +
'<button type="button" class="btn" data-act="reset" data-testid="alarm-filter-reset">重置</button>' +
"</div>";
}
function pagerHtml(total) {
var pages = Math.max(1, Math.ceil(total / state.pageSize));
var prev = state.page > 1 ? state.page - 1 : 1;
var next = state.page < pages ? state.page + 1 : pages;
var nums = "";
for (var i = 1; i <= pages; i++) {
nums += '<button type="button" class="btn tiny' + (i === state.page ? " primary" : "") + '" data-act="page" data-page="' + i + '">' + i + "</button>";
}
var sizes = [10, 20, 50].map(function (n) {
return '<option value="' + n + '"' + (n === state.pageSize ? " selected" : "") + ">" + n + " 条/页</option>";
}).join("");
return '<span>共 ' + total + ' 条</span><select id="page-size" aria-label="每页条数">' + sizes + "</select>" +
'<button type="button" class="btn tiny" data-act="page" data-page="' + prev + '"' + (state.page === 1 ? " disabled" : "") + ">上一页</button>" +
nums +
'<button type="button" class="btn tiny" data-act="page" data-page="' + next + '"' + (state.page === pages ? " disabled" : "") + ">下一页</button>";
}
function centerBox(testId, title, body, extra) {
return '<div class="stage plain"><div class="empty" data-testid="' + testId + '"><h3>' + esc(title) + "</h3><p>" + esc(body) + "</p>" + (extra || "") + "</div></div>";
}
function listHtml() {
var head = bannerHtml() + toolsHtml() + '<p class="applied">' + esc(appliedLine()) + "</p>";
if (state.screen === "loading") {
return head + '<div class="stage plain"><div class="empty" data-testid="alarm-loading"><div class="spin"></div><h3>报警加载中</h3><p>列表还没有出来。</p></div></div>';
}
if (state.screen === "failure") {
return head + centerBox("alarm-load-error", "报警列表暂时无法加载", "可以重试。页面不展示服务端原文。", '<p style="margin-top:12px"><button type="button" class="btn" data-act="retry" data-testid="alarm-retry">重试</button></p>');
}
if (state.screen === "empty") {
return head + centerBox("alarm-empty", "还没有报警", "出现正式异常后会列在这里。");
}
if (!state.subject) {
return head + centerBox("alarm-scope-empty", "当前账号没有处理范围,看不到报警", "这不是系统里没有报警,也不会因此改成查看全部。");
}
var rows = filteredRows();
if (!rows.length) {
return head + centerBox("alarm-filter-empty", "没有符合条件的报警", "重置筛选后可以再看。");
}
var pages = Math.max(1, Math.ceil(rows.length / state.pageSize));
if (state.page > pages) state.page = pages;
var start = (state.page - 1) * state.pageSize;
var pageRows = rows.slice(start, start + state.pageSize);
var body = pageRows.map(function (row) {
return "<tr data-testid=\"alarm-row-" + esc(row.id) + "\"><td>" + esc(MODULES[row.module_key]) + "</td><td>" + esc(row.scenario_name) +
"<div class=\"hint\" style=\"margin:0\">" + esc(row.scenario_key) + "</div></td><td>" + esc(OBJECTS[row.mapped_input_id]) +
"</td><td>" + fmt(row.last_occurred_at) + "</td><td>" + fmt(row.first_occurred_at) + "</td><td>" + row.occurrence_count +
"</td><td>" + statusTag(row) + "</td><td class=\"mono\">" + esc(row.current_handler || "—") +
'</td><td class="ops"><button type="button" class="btn link" data-act="open" data-id="' + esc(row.id) + '">打开</button></td></tr>';
}).join("");
return head + '<div class="stage" data-testid="alarm-table-wrap"><table data-testid="alarm-table"><thead><tr>' +
sortHead("module_key", "模块") + sortHead("scenario_name", "场景") + "<th>对象</th>" +
sortHead("last_occurred_at", "最近发生") + sortHead("first_occurred_at", "首次发生") +
sortHead("occurrence_count", "观测次数") + sortHead("status", "状态") + "<th>当前处理人</th><th class=\"ops\">操作</th>" +
"</tr></thead><tbody>" + body + "</tbody></table></div>";
}
function detailHtml(alarm) {
var prev = alarm.previous_alarm_id
? '<button type="button" class="btn link" data-act="open" data-id="' + esc(alarm.previous_alarm_id) + '">' + esc(alarm.previous_alarm_id) + "</button>"
: "—";
var basisNote = alarm.closed_basis.length
? '<p class="hint">关闭之后又记到一条正式异常。报警仍是已关闭,没有重开,也不表示数值回到正常。最近发生和观测次数都没有因为这条改掉。</p>'
: "";
var occRows = alarm.occurrences.map(function (row) {
return "<tr><td>" + fmt(row.observed_at) + "</td><td>" + fmt(row.planned_at) + "</td><td>" + fmt(row.received_at) +
"</td><td class=\"mono\">" + esc(row.cycle_key) + "</td><td>" + esc(row.mapping_version) + "</td><td>" + esc(row.rule_version) + "</td></tr>";
}).join("");
var judges = alarm.occurrences.map(function (row, index) {
var j = row.judgment;
return '<div class="judge"><b>判定 ' + (index + 1) + "</b> · " + esc(row.id) +
"<div>规则:" + esc(j.rule) + "。实际值 " + esc(j.actual) + ",比较值 " + esc(j.expect) + "," + (j.hit ? "命中" : "未命中") +
"。映射 " + esc(row.mapping_version) + ",规则 " + esc(row.rule_version) + "。</div>" +
'<div class="hint">演示。当前依据接口没有规则原文、实际值和比较值。</div></div>';
}).join("");
var rev = alarm.revision_evidence.length ? alarm.revision_evidence.map(function (row) {
return "<tr><td class=\"mono\">" + esc(row.id) + "</td><td class=\"mono\">" + esc(row.occurrence_id) + "</td><td>" + fmt(row.recorded_at) +
"</td><td>映射 " + esc(row.mapping_version) + " · 规则 " + esc(row.rule_version) + " · 快照 v" + row.snapshot_version_no + "</td></tr>";
}).join("") : '<tr><td colspan="4">没有同周期修订依据。</td></tr>';
var basis = alarm.closed_basis.length ? alarm.closed_basis.map(function (row) {
return "<tr><td>" + fmt(row.observed_at) + "</td><td>" + fmt(row.received_at) + "</td><td>" + fmt(row.recorded_at) +
"</td><td class=\"mono\">" + esc(row.cycle_key) + "</td><td class=\"mono\">" + esc(row.event_key) + "</td></tr>";
}).join("") : '<tr><td colspan="5">没有关闭后依据。</td></tr>';
var hist = alarm.history.length ? alarm.history.map(function (row) {
return "<tr><td>" + row.seq + "</td><td>" + fmt(row.recorded_at) + "</td><td>" + esc(COMMAND_LABEL[row.command]) +
"</td><td class=\"mono\">" + esc(row.actor_subject) + " · " + esc(ROLE_LABEL[row.actor_role] || "") + "</td><td>" + esc(STATUS_LABEL[row.from_status]) + " → " + esc(STATUS_LABEL[row.to_status]) +
"</td><td>" + esc(row.note || "—") + "</td><td>" + (row.close_result ? resultLabel(row.close_result) : "—") +
"</td><td class=\"mono\">" + esc(row.evidence_ref || "—") + "</td></tr>";
}).join("") : '<tr><td colspan="8">还没有人工处理记录。</td></tr>';
var validity = alarm.status === "closed"
? "已关闭。尚未执行的处理意图应失效。这是给后续模块的标记,不是数值回到正常。"
: "尚未关闭。没有关闭有效性。";
return bannerHtml() +
'<div class="card" data-testid="alarm-detail"><h3>' + esc(alarm.scenario_name) + " · " + esc(OBJECTS[alarm.mapped_input_id]) + "</h3>" +
'<dl class="facts">' +
"<div><dt>状态</dt><dd>" + statusTag(alarm) + "</dd></div>" +
"<div><dt>模块</dt><dd>" + esc(MODULES[alarm.module_key]) + " · " + esc(alarm.module_key) + "</dd></div>" +
"<div><dt>场景</dt><dd>" + esc(alarm.scenario_name) + " · " + esc(alarm.scenario_key) + "</dd></div>" +
"<div><dt>对象</dt><dd>" + esc(OBJECTS[alarm.mapped_input_id]) + "</dd></div>" +
"<div><dt>当前处理人</dt><dd class=\"mono\">" + esc(alarm.current_handler || "—") + "</dd></div>" +
"<div><dt>开始处理时间</dt><dd>" + fmt(alarm.claimed_at) + "</dd></div>" +
"<div><dt>关闭时间</dt><dd>" + fmt(alarm.closed_at) + "</dd></div>" +
"<div><dt>关闭结果</dt><dd>" + (alarm.close_result ? resultLabel(alarm.close_result) : "—") + "</dd></div>" +
"<div><dt>观测次数</dt><dd>" + alarm.occurrence_count + "(正式观测条数,不是错误次数)</dd></div>" +
"<div><dt>首次发生</dt><dd>" + fmt(alarm.first_occurred_at) + "</dd></div>" +
"<div><dt>最近发生</dt><dd>" + fmt(alarm.last_occurred_at) + "</dd></div>" +
"<div><dt>关联上一条</dt><dd>" + prev + "</dd></div>" +
"<div><dt>周期 / 事件</dt><dd class=\"mono\">" + esc(alarm.cycle_key) + " · " + esc(alarm.event_key) + "</dd></div>" +
"<div><dt>快照</dt><dd>v" + alarm.snapshot_version_no + "(合成发布快照)</dd></div>" +
"<div><dt>关闭有效性</dt><dd>" + esc(validity) + "</dd></div>" +
"</dl>" + basisNote +
(alarm.previous_alarm_id ? '<p class="hint">这是另一条报警,用 previous_alarm_id 指向较早的一条,不是把旧报警重开。</p>' : "") +
"</div>" +
'<div class="card"><h3>观测</h3><div class="stage in" style="flex:none;max-height:240px"><table><thead><tr><th>观测时间</th><th>计划时间</th><th>接收时间</th><th>周期</th><th>映射版本</th><th>规则版本</th></tr></thead><tbody>' +
occRows + "</tbody></table></div>" +
'<p class="hint">观测时间、计划时间、接收时间分列。计划时间是采集计划时刻的演示值。当前 occurrence 接口有观测时间、接收时间和创建时间,没有计划时间。创建时间没有单独做列。</p>' +
judges + "</div>" +
'<div class="card"><h3>依据</h3><h3 style="font-size:13px">同周期修订</h3><div class="stage in" style="flex:none;max-height:180px"><table><thead><tr><th>依据</th><th>观测</th><th>记下时间</th><th>版本</th></tr></thead><tbody>' +
rev + "</tbody></table></div><p class=\"hint\">同周期更正只追加依据,不改写第一次观测。</p>" +
'<h3 style="font-size:13px;margin-top:14px">关闭后依据</h3><div class="stage in" style="flex:none;max-height:180px"><table><thead><tr><th>观测时间</th><th>接收时间</th><th>记下时间</th><th>周期</th><th>事件</th></tr></thead><tbody>' +
basis + "</tbody></table></div></div>" +
'<div class="card"><h3>处理历史</h3><div class="stage in" style="flex:none;max-height:260px"><table><thead><tr><th>序号</th><th>时间</th><th>操作</th><th>操作人</th><th>状态</th><th>说明</th><th>结果</th><th>证据引用</th></tr></thead><tbody>' +
hist + "</tbody></table></div><p class=\"hint\">历史只追加。关闭结果只有已处理和误报。</p></div>";
}
function footerHtml(alarm) {
if (!alarm || alarm.status === "closed") return '<button type="button" class="btn" data-act="back" data-testid="alarm-back">返回列表</button>';
var claimCls = alarm.status === "pending" ? "btn primary" : "btn";
var closeCls = alarm.status === "processing" ? "btn primary" : "btn";
return '<button type="button" class="btn" data-act="back" data-testid="alarm-back">返回列表</button>' +
'<button type="button" class="' + claimCls + '" data-act="claim" data-testid="alarm-claim">处理</button>' +
'<button type="button" class="btn" data-act="progress" data-testid="alarm-progress">追加进展</button>' +
'<button type="button" class="' + closeCls + '" data-act="close" data-testid="alarm-close">关闭</button>';
}
function render() {
document.querySelectorAll("[data-role]").forEach(function (b) { b.classList.toggle("on", b.getAttribute("data-role") === state.role); });
document.querySelectorAll("[data-subject]").forEach(function (b) { b.classList.toggle("on", b.getAttribute("data-subject") === state.subject); });
document.querySelectorAll("[data-screen]").forEach(function (b) { b.classList.toggle("on", b.getAttribute("data-screen") === state.screen); });
document.querySelectorAll("[data-sim]").forEach(function (b) { b.classList.toggle("on", b.getAttribute("data-sim") === state.simulate); });
document.getElementById("who").textContent = "已登录:" + ROLE_LABEL[state.role];
document.getElementById("who-sub").textContent = state.subject ? ("主体 " + state.subject) : "无处理范围";
var crumb = document.getElementById("crumb");
var content = document.getElementById("content");
var foot = document.getElementById("foot");
var listfoot = document.getElementById("listfoot");
foot.hidden = true;
listfoot.hidden = true;
foot.innerHTML = "";
listfoot.innerHTML = "";
if (!state.dialog) document.getElementById("mask").hidden = true;
var html = "";
var fill = true;
if (state.screen === "forbidden") {
crumb.innerHTML = "预警平台 / <b>报警</b>";
html = '<div class="listpage">' + centerBox("alarm-forbidden", "无法查看报警", "当前账号没有读取权限。需要权限点 " + NODES.read + "。") + "</div>";
} else if (state.screen === "missing") {
fill = false;
crumb.innerHTML = '预警平台 / <button type="button" class="crumb-btn" data-act="back">报警</button> / <b>详情</b>';
html = '<div class="empty" data-testid="alarm-missing"><h3>没有找到这条报警</h3><p>页面不说明它是否存在于范围之外。</p></div>';
foot.hidden = false;
foot.innerHTML = '<button type="button" class="btn" data-act="back">返回列表</button>';
} else if (state.view === "detail") {
var alarm = findAlarm(state.detailId);
fill = false;
crumb.innerHTML = '预警平台 / <button type="button" class="crumb-btn" data-act="back">报警</button> / <b>详情</b>';
if (!alarm) {
html = '<div class="empty"><h3>没有找到这条报警</h3><p>页面不说明它是否存在于范围之外。</p></div>';
foot.hidden = false;
foot.innerHTML = '<button type="button" class="btn" data-act="back">返回列表</button>';
} else {
html = detailHtml(alarm);
foot.hidden = false;
foot.innerHTML = footerHtml(alarm);
}
} else {
crumb.innerHTML = "预警平台 / <b>报警</b>";
html = '<div class="listpage" data-testid="alarm-list">' + listHtml() + "</div>";
if (state.screen === "ready" && state.subject && filteredRows().length) {
listfoot.hidden = false;
listfoot.innerHTML = pagerHtml(filteredRows().length);
}
}
content.className = fill ? "content fill" : "content scroll";
content.innerHTML = html;
}
function gate(command) {
var name = COMMAND_LABEL[command];
if (state.role === "viewer") return { tone: "err", text: "无权" + name + "。需要权限点 " + NODES[command === "claim" ? "take" : command] + "。" };
if (!state.subject) return { tone: "err", text: "没有明确的处理范围,不能" + name + "。" };
return null;
}
function lockUi(btn) {
state.busy = true;
if (btn) btn.textContent = "提交中";
document.querySelectorAll("button, input, select, textarea").forEach(function (node) { node.disabled = true; });
}
function finishLater(btn, apply) {
if (state.busy) return;
var token = ++submitToken;
lockUi(btn);
setTimeout(function () {
if (token !== submitToken) return;
apply();
state.busy = false;
state.dialog = null;
render();
}, 500);
}
function openDialog(kind) {
state.dialog = kind;
var mask = document.getElementById("mask");
var title = kind === "close" ? "关闭报警" : "追加进展";
var extra = kind === "close"
? '<div class="result-row"><span>关闭结果(必填)</span><div class="choices"><label><input type="radio" name="close-result" value="resolved"> 已处理</label><label><input type="radio" name="close-result" value="false_positive"> 误报</label></div></div>'
: "";
document.getElementById("modal").innerHTML = "<h3>" + title + "</h3><p class=\"hint\" style=\"margin-top:0\">说明必填。证据引用选填,不是附件。提交中不能重复点。</p>" +
extra +
'<label><span>说明(必填)</span><textarea id="d-note" maxlength="2000"></textarea></label>' +
'<label><span>证据引用(选填)</span><input id="d-evidence" maxlength="512" placeholder="业务记录引用"></label>' +
'<p class="err" id="d-err" hidden></p><div class="actions"><button type="button" class="btn" data-act="dialog-cancel">取消</button>' +
'<button type="button" class="btn primary" id="d-ok" data-act="dialog-ok">' + (kind === "close" ? "关闭" : "保存") + "</button></div>";
mask.hidden = false;
document.getElementById("d-note").focus();
}
function dialogValues() {
var checked = document.querySelector('input[name="close-result"]:checked');
return {
result: checked ? checked.value : "",
note: document.getElementById("d-note").value.trim(),
evidence: document.getElementById("d-evidence").value.trim()
};
}
function showDialogErr(text) {
var node = document.getElementById("d-err");
node.hidden = false;
node.textContent = text;
}
function currentAlarm() { return findAlarm(state.detailId); }
function pushHistory(alarm, command, from, to, note, result, evidence) {
alarm.history.push(ev(alarm.history.length + 1, command, state.subject, state.role, alarm.current_handler, from, to, note, result, evidence || null, nowIso()));
}
function onClaim(btn) {
var denied = gate("claim");
if (denied) { state.notice = denied; render(); return; }
finishLater(btn, function () {
var alarm = currentAlarm();
if (!alarm) return;
if (state.simulate === "claim") {
state.notice = { tone: "warn", text: "已有处理人,这次处理没有生效。" };
return;
}
if (alarm.status === "closed") {
state.notice = { tone: "warn", text: "已关闭的报警不能再处理。" };
return;
}
if (alarm.status === "processing" && alarm.current_handler === state.subject) {
state.notice = { tone: "ok", text: "你已经是当前处理人,没有新增处理记录。" };
return;
}
if (alarm.status === "processing") {
state.notice = { tone: "warn", text: "已有处理人,这次处理没有生效。当前处理人仍是 " + alarm.current_handler + "。" };
return;
}
var at = nowIso();
alarm.status = "processing";
alarm.current_handler = state.subject;
alarm.claimed_at = at;
pushHistory(alarm, "claim", "pending", "processing", null, null, null);
state.notice = { tone: "ok", text: "已开始处理。状态变为处理中。" };
});
}
function onProgress() {
var denied = gate("progress");
if (denied) { state.notice = denied; render(); return; }
var alarm = currentAlarm();
if (!alarm) return;
if (alarm.status !== "processing") {
state.notice = { tone: "warn", text: "只有处理中的报警可以追加进展。" };
render();
return;
}
if (alarm.current_handler !== state.subject) {
state.notice = { tone: "warn", text: "只有当前处理人可以追加进展。" };
render();
return;
}
openDialog("progress");
}
function onClose() {
var denied = gate("close");
if (denied) { state.notice = denied; render(); return; }
var alarm = currentAlarm();
if (!alarm) return;
if (alarm.status === "pending") {
state.notice = { tone: "warn", text: "待处理不能直接关闭。请先处理。" };
render();
return;
}
if (alarm.status === "closed") {
state.notice = { tone: "warn", text: "已经关闭。不同的结果或说明不会再写一条记录。" };
render();
return;
}
if (alarm.current_handler !== state.subject && state.role !== "admin") {
state.notice = { tone: "warn", text: "只有当前处理人或管理者可以关闭。" };
render();
return;
}
openDialog("close");
}
function submitDialog(btn) {
var values = dialogValues();
if (state.dialog === "close" && !values.result) { showDialogErr("请选择关闭结果。"); return; }
if (!values.note) { showDialogErr("请填写说明。"); return; }
if (values.note.length > 2000) { showDialogErr("说明最长 2000 字。"); return; }
if (values.evidence.length > 512) { showDialogErr("证据引用最长 512 字。"); return; }
var kind = state.dialog;
finishLater(btn, function () {
var alarm = currentAlarm();
if (!alarm) return;
if (state.simulate === "idem") {
state.notice = { tone: "warn", text: "同一个操作标识不能配不同内容,这次没有写入。" };
return;
}
if (kind === "progress") {
if (alarm.status !== "processing" || alarm.current_handler !== state.subject) {
state.notice = { tone: "warn", text: "只有当前处理人可以在处理中追加进展。" };
return;
}
pushHistory(alarm, "progress", "processing", "processing", values.note, null, values.evidence);
state.notice = { tone: "ok", text: "进展已记下。原来的观测没有被改写。" };
return;
}
if (alarm.status !== "processing") {
state.notice = { tone: "warn", text: "当前状态不能关闭。" };
return;
}
if (alarm.current_handler !== state.subject && state.role !== "admin") {
state.notice = { tone: "warn", text: "只有当前处理人或管理者可以关闭。" };
return;
}
var handler = alarm.current_handler;
alarm.status = "closed";
alarm.current_handler = handler;
alarm.closed_at = nowIso();
alarm.close_result = values.result;
pushHistory(alarm, "close", "processing", "closed", values.note, values.result, values.evidence);
state.notice = { tone: "ok", text: "已关闭,结果是" + resultLabel(values.result) + "。观测次数没有变。" };
});
}
function onReclose() {
if (state.view !== "detail") {
state.notice = { tone: "warn", text: "请先打开一条已关闭的报警,再模拟再次关闭。" };
render();
return;
}
var alarm = currentAlarm();
if (!alarm || alarm.status !== "closed") {
state.notice = { tone: "warn", text: "这条还没关闭,不能演示再次关闭。" };
render();
return;
}
var denied = gate("close");
if (denied) { state.notice = denied; render(); return; }
state.notice = { tone: "warn", text: "已经关闭。这次的结果或说明和原来不同,没有再写一条记录。历史条数不变。" };
render();
}
document.addEventListener("click", function (ev) {
var el = ev.target.closest("[data-act]");
if (!el || state.busy) return;
var act = el.getAttribute("data-act");
if (act === "role") {
state.role = el.getAttribute("data-role");
state.dialog = null;
state.notice = null;
render();
return;
}
if (act === "subject") {
syncDraft();
state.subject = el.getAttribute("data-subject");
state.dialog = null;
state.notice = null;
if (!state.subject) state.view = "list";
render();
return;
}
if (act === "screen") {
syncDraft();
state.screen = el.getAttribute("data-screen");
state.view = "list";
state.dialog = null;
state.notice = null;
render();
return;
}
if (act === "sim") { state.simulate = el.getAttribute("data-sim"); render(); return; }
if (act === "reset-seed") {
alarms = buildSeed();
state.draft = blankDraft();
state.applied = blankDraft();
state.page = 1;
state.view = "list";
state.screen = "ready";
state.notice = { tone: "ok", text: "样例已还原。" };
state.dialog = null;
render();
return;
}
if (act === "logout") {
state.notice = { tone: "warn", text: "原型不退出登录。" };
render();
return;
}
if (act === "query") {
if (state.screen !== "ready") return;
syncDraft();
if (state.draft.from && state.draft.to && state.draft.from > state.draft.to) {
state.notice = { tone: "err", text: "开始时间不能晚于结束时间。" };
render();
return;
}
state.applied = clone(state.draft);
state.page = 1;
state.notice = null;
render();
return;
}
if (act === "reset") {
if (state.screen !== "ready") return;
state.draft = blankDraft();
state.applied = blankDraft();
state.page = 1;
state.notice = null;
render();
return;
}
if (act === "retry") { state.screen = "ready"; state.notice = null; render(); return; }
if (act === "sort") {
syncDraft();
var key = el.getAttribute("data-sort");
if (state.sortBy === key) state.sortOrder = state.sortOrder === "asc" ? "desc" : "asc";
else { state.sortBy = key; state.sortOrder = "asc"; }
state.page = 1;
render();
return;
}
if (act === "page") {
syncDraft();
state.page = Number(el.getAttribute("data-page"));
render();
return;
}
if (act === "open") {
syncDraft();
state.view = "detail";
state.detailId = el.getAttribute("data-id");
state.screen = "ready";
state.notice = null;
state.dialog = null;
render();
return;
}
if (act === "back") {
state.view = "list";
state.screen = "ready";
state.dialog = null;
state.notice = null;
render();
return;
}
if (act === "claim") { onClaim(el); return; }
if (act === "progress") { onProgress(); return; }
if (act === "close") { onClose(); return; }
if (act === "dialog-cancel") { state.dialog = null; document.getElementById("mask").hidden = true; return; }
if (act === "dialog-ok") { submitDialog(el); return; }
if (act === "reclose") onReclose();
});
document.addEventListener("input", function (ev) {
if (ev.target.id && ev.target.id.indexOf("f-") === 0) syncDraft();
});
document.addEventListener("change", function (ev) {
if (ev.target.id && ev.target.id.indexOf("f-") === 0) syncDraft();
if (ev.target.id === "page-size") {
state.pageSize = Number(ev.target.value);
state.page = 1;
render();
}
});
document.addEventListener("keydown", function (ev) {
if (ev.key === "Escape" && state.dialog && !state.busy) {
state.dialog = null;
document.getElementById("mask").hidden = true;
}
});
render();
</script>
</body>
</html>
@@ -0,0 +1,164 @@
# M06 报警中心与人工处理 Requirement(已冻结)
> 状态:`FROZEN`。用户于 2026-11-19 确认 D32~D35(原 O04/O05/O06 与范围/快照/正式异常契约)。可编排工作流与 M08 场景收尾已登记后置,不进入本模块实现范围。
## Goal
把正式、有效的异常事实按稳定身份创建或关联到报警,提供可追溯的列表、详情和正向人工处理流程,同时不改写原始异常、不伪称恢复、不发送真实消息。
## Background
M05 已交付映射、输入修订和正常/异常/未知试算。M06 覆盖 P-006、A-037~A-047。M08 场景发布与 Cron、M07 通知、M09 次数升级尚未实现,因此本模块只使用合成发布快照和通知有效性边界,不实现这些后续模块。
## In Scope
- 首次有效异常创建报警;PASS/UNKNOWN/执行失败不默认创建。
- 重复输入/任务重投幂等;持续异常在有限范围内关联 occurrence。
- 新统计周期或独立事件可新建报警,并关联历史报警。
- 报警列表、详情、判定依据和处理历史。
- `待处理 -> 处理中 -> 已关闭`;接手、追加进展、关闭。
- 并发接手、重复命令、并发关闭的明确结果。
- 控制台筛选、详情、接手、进展、关闭与历史 UI。
- 为后续模块提供由报警终态导出的查询语义:已关闭则绑定该报警的未执行通知/升级意图应视为失效。不落意图行,不提供撤回已受理消息的命令,不读写次数窗口,不建立 M07/M09 任务执行器。
## Out Of Scope
- 真实消息、企微通道/目标/模板/发送任务。
- 场景配置、正式发布表、Cron、调度、补跑。
- 次数窗口、阈值、升级目标和超时升级。
- 自动恢复、恢复通知、直接从待处理关闭、转派、重开、审批、批量关闭。
- **可编排人工处理工作流**(状态/转移/指派可配置):已登记后置,MVP 不做。
- AI 自动接手/关闭、附件系统、生产数据联调。
## Current Behavior
- 没有 alarms 模型、迁移、服务、API 或页面。
- M05 `evaluate_rows` 是纯试算;`MappedInputRevision` 可提供稳定输入及修订依据,但没有持久化正式判定事件。
- M01 有租户隔离的 `RunRecord` 与 `AuditEvent`,没有场景发布快照实体。
- M02 有 admin/operator/viewer 角色,但没有报警数据范围授权模型。
## Required Behavior
- 一个正式异常 occurrence 必须引用稳定输入/修订、规则或映射版本、观测时间、接收时间、合成发布快照和幂等身份。
- 报警保留首次/最近发生时间、当前处理状态、当前处理人、关联 occurrence 数、原报警关联及展示快照。
- 同一正式异常重复提交返回同一结果,不新增 occurrence,不重复创建报警。
- occurrence 合并依据结构化键和明确有效范围,禁止按消息文本或“所有历史同类”永久合并。
- 后续 PASS、空结果、UNKNOWN、任务失败或发送失败不得自动关闭、恢复或改写原始异常。
- 所有人工处理记录追加保存,记录操作者、处理人、时间、前后状态、进展、关闭结果、关闭说明与可选证据引用。
## User Flow
1. 有权用户按模块、场景、对象、等级、时间、状态筛选报警。
2. 打开详情查看原始异常依据、关联 occurrence 与完整处理历史。
3. 有权处理者接手后进入“处理中”。
4. 当前处理人追加进展;允许关闭者选择结果并填写说明。
5. 关闭后页面只读显示历史,不显示“已恢复”,新独立事件按 D05 可建立并关联新报警。
## Business Rules
- 已确认 D05:同一输入不重新触发;关闭后新统计周期/新独立事件可新建并关联历史。
- 已确认:状态仅 `pending`、`processing`、`closed`,不做自动恢复;MVP 不做从待处理直接关闭。
- 已确认 D32(O04):关闭使“绑定该报警且尚未执行”的后续通知/升级意图失效;已受理消息不可撤回;M09 次数窗口不因人工关闭自动清零。
- 已确认 D33(O05):范围内 operator/admin 可接手;当前处理人或 admin 可关闭;关闭结果仅 `resolved`(已处理)/`false_positive`(误报);说明必填;不做转派/重开。可编排工作流后置。
- 已确认 D34(O06):同周期值更正追加修订并保留依据,不更新报警原始事实、不自动新建报警、不自动重发;只有明确的新独立事件身份才可新建。
- 已确认 D36:已关闭报警上再次出现同一合并键正式异常时,不新开、不重开;仍追加可追溯记录(依据和/或审计日志),便于追查持续异常。
- 已确认 D37:MVP 接受应用库角色可调用合法状态函数,正式入口靠 API/服务校验;已关闭后相同内容用新幂等键再关闭视为回放成功。
## Data Rules
- 所有业务表带 `tenant_id` 并强制 PostgreSQL RLS;调用方不得传 tenant。
- occurrence 使用数据库唯一约束实现幂等;报警合并和状态转换必须抗并发。
- 原始判定引用、occurrence 和处理历史追加保存,不允许原位覆盖历史事实。
- 已确认 D35:合成发布快照最小契约为稳定 `snapshot_id`、`version_no`、`module_key`、`scenario_key/name`、处理范围,以及映射/规则版本引用;不得创建 M08 正式场景表。
- 新周期关联使用显式 `previous_alarm_id` 或等价历史关系,不用相同文本推断。
- 已确认 D35:正式 occurrence 引用 M05 输入修订+映射/规则版本+合成快照;试算不得触发正式报警。
## M08 收尾备注(不在本模块实现)
正式场景发布(M08)就绪后:
1. 新正式路径改挂真实发布版本 ID/不可变内容,不再用合成快照冒充生产发布。
2. 历史报警与 occurrence 保留创建时的快照展示字段与引用,不回写、不伪称恢复。
3. 处理范围改由场景发布/授权模型提供;合成快照范围仅保留测试与过渡说明。
4. 迁移或兼容映射在 M08/M11 联调任务中验收,不提前在 M06 建正式场景表。
## API Contract
- 只读:列表、详情、occurrence/判定依据、处理历史。
- 命令:接手、追加进展、关闭;命令要求 `x-idempotency-key`。
- 统一信封按 `standards://api/api-envelope?version=1.1.0`;route 不手写失败 JSON,错误由语义异常和全局 handler 处理。
- 并发冲突返回 409 语义错误;权限不足返回 42000 和权限点;UI 不显示服务端原始消息。
- 列表按 D25 使用 `page/page_size`、后端筛选与排序。
## UI Requirements
- 列表遵循 D25:模块/场景/对象/等级/时间/状态筛选,点击查询才请求,服务端排序和分页。
- 详情遵循 D22:正文可滚动,接手/进展/关闭操作在固定居中页脚或合适对话框;操作中防重复提交。
- 使用 Element Plus 与四语言;区分加载、空、无匹配、失败、无权和冲突。
- 不显示“已恢复”;已关闭仅表示人工终态。
- 正式 Vue 前先确认 HTML 原型。
## Compatibility Requirements
- 不改变 M05 输入身份、修订和试算不落报警的语义。
- 不新增 M08 场景/Cron,不新增 M07/M09 执行器。
- 不改变三角色名称、统一信封、RLS 或 D22/D25。
## Error Handling
- 重复幂等命令返回原结果;相同幂等键配不同 payload 必须冲突。
- 两人并发接手只产生一个当前处理人;后到者获得幂等成功或明确冲突,不静默覆盖。
- 重复关闭、非当前处理人关闭、缺结果/说明、非法状态转换均明确拒绝。
- 不存在或越范围的报警不得泄漏详情。
## Permissions And Security
- viewer:仅可读其授权范围内报警。
- operator:范围内可接手、追加进展;关闭仅当前处理人或 admin。
- admin:管理者;仍须后端检查租户与对象范围,不以 ID 即授权。
- 处理范围来源:合成发布快照显式声明(D35);禁止默认 operator 全租户。
- 权限点必须先按 `standards://api/permission-nodes?version=1.0.0` 核对,禁止编造编码。
## Assumptions
- 使用合成数据和本地 PostgreSQL;不访问真实 MES、不发送消息。
- 关闭有效性只由报警终态导出,供后续模块读取;不在本模块建意图或窗口表。
- 证据引用首版可为受控字符串/结构化引用,不做附件上传。这是实现假设,不是新的已确认业务枚举。
- 「处理范围」的字段布局未单独立项。已确认的只有:范围必须写在合成快照上,未声明即拒绝,禁止默认 operator 全租户。编码不得把某一种范围模式写成新的已确认决策。
- 列表保持项目既有页码分页契约。
## Risks
- 合成发布快照若过窄,M08 接入时需要兼容迁移;过宽则越界 M08——已用最小字段+收尾备注约束。
- 处理范围仅靠合成快照,测试必须覆盖越权拒绝。
- 合并键、周期和修订语义错误会造成永久抑制或重复报警。
## Acceptance Criteria
1. 首次正式异常原子创建报警;正常/未知/执行失败不创建;试算不创建。
2. 同一 occurrence 重复提交不新增关联或报警。
3. 合并范围内持续异常只新增依据;范围外/新独立事件可新建并关联历史。
4. 列表和详情可按确认字段筛选、分页、排序,并展示原始依据和人工历史。
5. 正向状态转换、进展追加、关闭结果与说明可追溯,不修改原始异常。
6. 并发接手只有一个当前处理人;并发/重复关闭无矛盾终态。
7. 越权读取和操作由后端拒绝;前端隐藏不作为权限控制。
8. 关闭不显示恢复;后续 PASS/UNKNOWN/失败不自动关闭。
9. D32~D35 的 M06 部分通过:V032~V037,以及 V042 的 M06 部分(关闭不清零、不建窗口或意图表;新旧报警身份不混淆;无撤回已受理消息的接口)。V038~V041 与次数窗口计数仍属 M09,不是本模块通过条件。
10. UI 的 U06 在三个桌面视口有断言、截图和视觉复核。
## Blocking Questions
无。业务阻塞已由 D32~D35 关闭。
## Deferred Questions
- 可编排人工处理工作流(状态机/转移/指派可配置):MVP 后补充。
- M09 次数窗口分组、阈值、跨版本继承及是否与关闭交互的细则(D32 已定「关闭不清零」)。
- M07 已受理消息后的外部展示和失败重试。
- M08 正式场景表替换/映射合成快照的迁移验收(见上方收尾备注)。
## Source Notes
- D05、D19、D20、D22、D25、D27、D28、D32、D33、D34、D35。
- 冻结稿第 7、8、10、13、15 章;T09~T15、T33。
- `docs/tasks/INDEX.md` M06;`CHECKLIST-v1.md` P-006、A-037~A-047。
@@ -0,0 +1,105 @@
# Critic Review
## Verdict
PASS_WITH_WARNINGS
对照调用方的三档结论:通过并带警告,不是 FAIL。业务编码仍未放行。`state.json` 保持 `allowedToCode=false`、`planApproved=false`、`criticPassed=false`;本审查不改状态文件。
## Scope Risks
- 修订前,S2「关闭有效性接口」和验收第 9 条把整条 V042 算进 M06。`docs/testing-plan.md` 的 V042 挂在 A-051,原文仍是「不预设窗口是否清零」。照那条做会把次数窗口和升级意图写进本模块。
- 修订后,M07 企微/真实消息、M08 场景/Cron/正式发布表、M09 次数窗口与升级、可编排工作流都不在切片允许范围内。关闭语义只由报警终态导出:已关闭则未执行意图应视为失效;不落意图行,不提供撤回,不清零窗口。M08 收尾只留在 `requirement.md` 的后置备注。
- D32~D35 的用户确认已写进冻结稿,且没有被改写成额外业务范围。D33 的可编排工作流、D35 的正式场景替换都标明后置、本模块不实现。
## Missing Assumptions
- 「处理范围」只确认了来源和缺省拒绝:必须写在合成快照上,未声明即拒绝,禁止 operator 全租户。字段布局(对象键、角色、主体)没有单独冻结。`requirement.md` 的 Assumptions 已标明这不是新的已确认决策。编码时可以选最小显式结构,不得把它写成已确认授权模型,也不得在缺字段时放行。
- 证据引用用受控字符串、不做附件,仍是实现假设。
- 关闭结果的接口字面值 `resolved`/`false_positive` 是 D33「已处理/误报」的映射,不是另一套已确认枚举。不得再加结果值。
- 仓库和 `standards://api/permission-nodes?version=1.0.0` 正文里都没有报警权限点。现有节点停在 `watchman.mapping.*`。S3 对不上就必须停下来问,这次 plan-review 没有把权限点核对成已通过。
## Requirement Gaps
- 冻结稿与 `docs/decisions.md` D32~D35 一致:关闭使未执行意图失效、已受理不可撤回、次数窗口不因关闭清零且细则归 M09;MVP 接手/关闭主体和结果枚举按 D33,可编排工作流后置;同周期更正只追加修订,不自动新报警、不自动重发;合成快照最小字段、occurrence 引用 M05 修订与版本和快照、试算不报警、M08 收尾备注均在。
- 修订前的缺口是验收第 9 条要求整条 V042 通过,和「次数窗口不属于 M06」冲突。现已收成 V042 的 M06 部分,V038~V041 明确排除。
- `intake.md` 仍把 O04/O05/O06 写成待确认问题。那是冻结前的入口记录,不是当前需求真源。以 `requirement.md` 和 D32~D35 为准。
## Plan Gaps
- 修订前,`implementation-plan.md` 文末仍写「requirement 未冻结」「O04/O05/O06 只有用户确认后才标 CONFIRMED」「范围和快照仍是阻塞」。这和文首、冻结稿、`state.json` 矛盾,会让实现把已确认口径重新打开,或把计划当成不可执行草稿。该段已改成:D32~D35 已确认;`planApproved=false` 只表示还要等用户做分析→编码确认。
- S2 原目标「稳定领域接口」过宽。现改为终态导出,并禁止意图行、窗口读写和撤回命令。同周期更正补进 S1 第 6 步。
- `gateClass` 用词未越出 `simple`/`standard`/`boundary-sensitive`/`high-risk`。S1/S2 为 `high-risk` 且 `risk_score` 5,S3/S6 为 `boundary-sensitive` 且 `risk_score` 4,都要求片后 critic。`risk_score` 只加严、没有把高风险片降成可自动续跑。
- `autonomous` 没有写成可跳过 S1~S3。原摘要漏了「S4 原型确认前不得进 S5」。现已写明:S1~S3 和 S6 必须停;S5 只有在用户确认原型之后,且该片仍是 `standard`、`risk_score` 3、无 critic 时,才可能续行。分析→编码确认和最终批准都不取消。
- S2 的 `gateReasons` 仍含 `permissions`。这里只许做当前处理人/既有三角色判断。权限点字面值留在 S3,对不上就停。
## Context Gaps
- `context-pack.md` 原先把「业务口径未冻结」列为可 NOT_RUN 的理由。口径已经冻结,这条会给以后跳过 PostgreSQL/RLS/并发测试留口。已删。
- 上下文包的允许范围仍是任务文档,`allowedToCode=false`。与 `state.json` 的 `phase=analysis`、`currentSlice=null` 一致。
- 停止条件现已覆盖:跳过 S1~S3 停顿、未确认原型就做 S5、编造权限点、试算写入报警、意图表/次数窗口/撤回命令、可编排工作流和正式场景表。
## Validation Gaps
- S1/S2/S3 和最终验证都要求隔离的真实 PostgreSQL。RLS、唯一约束、并发创建/接手/关闭不接受 SQLite 或纯 Mock。这和 `docs/testing-plan.md` 第 1 节、第 5 节一致。现有测试通过 `settings.database_url` 连 PostgreSQL,计划没有改成内存库。
- 试算隔离已变成硬约束:S1 第 5 步、S1 验证、全局禁止项和 context-pack 停止条件都要求 `evaluate_rows` 与试算路由零报警行。验收第 1 条同样要求试算不创建报警。
- 遗留缺口:`docs/testing-plan.md` 第 89 行 V033 仍写「按 O06 最终口径」,第 98 行 V042 仍写「不预设窗口是否清零」。D34/D32 已经收口。M06 的真源是冻结稿里的 M06 部分,不是这两句旧文案。S6 正式验证前必须改测试计划,否则测试子 Agent 会用旧神谕。
## Boundary Risks
- 权限规范 `standards://api/permission-nodes?version=1.0.0` 禁止编造编码,并要求先确认编码存在。仓库 `auth/access.py` 没有报警节点。`boundary.md` 原先把「权限点字面值」写成可按现有模式落地,等于允许照 `watchman.datasource.read` 新造字面值。该句已收紧为对不上就停。
- 冲突应复用现有 `ConflictError`(HTTP 409,信封码 40000),越权复用 `ForbiddenError`(42000 加权限点)。不得新造业务码 409。这是既有 `core/errors.py` 契约,不是新决定。
- 公司规范示例里的 action 是 kebab-case;本仓库已有节点是 `perm:data:emp:watchman.*`。M06 不得为了贴示例去改旧节点,也不得因此新造报警节点。
## Required Changes
编码前阻断项:无。下列文档已在本审查中改完,实现必须以改后的文本为准。
- `requirement.md`:关闭语义改为终态导出;验收第 9 条只保留 V042 的 M06 部分;处理范围字段布局标成未冻结假设。
- `implementation-plan.md`:删掉「需求未冻结/O04 仍待确认」;写明 autonomous 不能跳过 S1~S3,也不能未经原型确认进入 S5;S1 补上试算隔离和 D34;S2 禁止意图表、窗口和撤回;S3 禁止编造权限点,并复用现有冲突/越权错误。
- `boundary.md`:权限点字面值和处理范围布局不再当成可自由落地的实现细节。
- `context-pack.md`:删掉「口径未冻结」的 NOT_RUN 理由,补上试算、权限点和 M07/M09 停止条件。
S6 前仍要改,但不挡住分析→编码确认:
- `docs/testing-plan.md` 的 V033、V042「Then」列改为 D34、D32 口径。未改之前,不得用该文件的旧句作为 M06 通过标准。
未改业务源码、`state.json`、`docs/decisions.md`、`docs/progress.md`。
## Optional Suggestions
- S3 开始前单独问清报警权限点的既有编码或登记出处。不要等到写路由时才发现规范里没有对应节点。
- `intake.md` 可留作历史。后续切片不要从它重开 O04/O05/O06。
- 合并键的具体列可以在 S1 按「结构化、有限范围、禁止按文本永久合并」落地。不要把选定的列解释成新的已确认业务规则。
## 问题分级
### 阻断
无。
### 高
无未关闭项。下面三项在修订前会阻断编码,现已改入任务文档:
- `implementation-plan.md` 文末把已冻结需求和 D32~D35 写成未确认。
- `requirement.md` 验收第 9 条与 S2 原「领域接口」会把 M09 窗口和 M07 意图卷进来。
- `boundary.md` 允许按邻近模块编造权限点字面值,违反 `standards://api/permission-nodes?version=1.0.0`。
### 中
- `docs/testing-plan.md` V033、V042 的期望仍是决策前的写法。S6 前要改。
- 处理范围的字段布局未冻结。缺省拒绝已经是硬约束,具体模式不是已确认决策。
- 报警权限点尚未核对到存在的编码。S3 预期会停,这次审查没有把它放行。
### 低
- `intake.md` 仍列出 O04/O05/O06 待确认。只作历史,不作为冻结稿。
- `resolved`/`false_positive` 只是 D33 两个中文结果的接口映射。
- 权限规范示例与仓库既有 `watchman.*` 节点写法不同。M06 两边都不要借机发明或批量改写。
## 是否建议进入分析→编码确认
建议。用户可以确认从分析进入编码,并只批准 S1。
这次 PASS_WITH_WARNINGS 本身不是开工许可。`autonomous` 也不提前打开 S1。确认之后仍须在 S1、S2、S3 各自完成并审查后停下;S5 还要先有原型确认;S3 若权限点对不上必须再问;最终 `DONE_LOCAL` 仍要单独批准。
@@ -0,0 +1,96 @@
# Critic Review
## Verdict
PASS_WITH_WARNINGS
上次的 BLOCKED/FAIL(验证日志与 `validation-s6.md` 对不上)解除。对照本轮三档,这不是 FAIL。
可以请用户最终批准 `DONE_LOCAL`。主 Agent 不得自行标 DONE。`gatePolicy.finalApprovalRequired` 仍为 true。`gateClass` 仍是 `boundary-sensitive`,`risk_score` 4 只加严证据,不取消最终批准。选定的 `autonomous` 也不能跳过这次停顿。
请示前把 `docs/progress.md` 和 `docs/tasks/M06.md` 改成「验证日志已核对,等待用户最终批准」。这两处现在仍写「正式验证进行中」和「S5 不得开始 S6」。
本地 `DONE_LOCAL` 可以接受 Mock e2e、合成快照、无真实企微。必须写成本地边界,不能写成阶段联调或真实外发通过。
本审查没有改业务代码,也没有改 `state.json`、`docs/progress.md`、`docs/tasks/M06.md`。
## Scope Risks
`git status --short` 里的报警实现仍停在 M06:`models/alarm.py`、`models/alarm_handling.py`、`services/alarms.py`、`services/alarm_handling.py`、`services/alarm_reads.py`、`api/routes/alarms.py`、迁移 `20261119_0014` 与 `20261119_0015`、`auth/access.py`、`auth/principal.py`、`api/app.py`、`web/apps/console/src/alarms/`、`e2e/alarms.spec.ts`、四语言、`AppShell.vue`、`router.ts`、`docs/evidence/M06/`、`docs/testing-plan.md`。文件名里没有企微、场景发布、Cron、次数窗口或 M07/M08/M09。
同一工作区里还有未纳入本次通过范围的脏文件:`docs/evidence/M02/ui/` 四张登录截图、`docs/agent-workflow.md`、`.cursor/agents/marionettist-builder.md`、`docs/预警平台开发规划_初期开发计划.xlsx`、`web/apps/console/tsconfig.tsbuildinfo`。生成物不要一并提交。
## Missing Assumptions
- 即便获批 `DONE_LOCAL`,边界仍是:Playwright 为页面 Mock;没有真实企微或 MES;处理范围来自合成快照;不发送通知,不建次数窗口。这些必须写进进度,不能写成前后端联调或阶段真实集成通过。
- 验证报告写的是当前 `settings.database_url` 指向的 PostgreSQL,不是另建空库。日志能证明 0015 在这套库上往返,不能写成隔离空库已重建。
- 并发关闭用例仍是终态之后的回放和 `already_closed`,不是两条关闭同时离开 `processing`。新的 `validation-s6.md` 没有把该用例说成已覆盖,也没有重申这句。请示时要带上。
- 0014 本身没有降到前一修订再升回。`0015→0014→0015` 只证明 0015 往返。
## Requirement Gaps
`requirement.md` 仍是冻结稿。验收不把 V038~V041 算进本模块。
`docs/testing-plan.md` 第 89 行、第 98 行已改成 D34、D32。模块审查的中 1(V033 仍是 O06,V042 仍是「不预设窗口是否清零」)就这两句正文而言已经关闭。
残留:V033 末尾仍有「不因 payload hash 改变乱报」,并且没有写出 D34 的「不改写原始 FAIL」。这不把窗口是否清零重新打开,不单独阻断。
## Plan Gaps
S6 要求两阶段审查、正式命令,以及用户最终批准之后才标 `DONE_LOCAL`。`reviews/review-module-m06.md` 的 Recommendation 是 `PASS_WITH_WARNINGS`,无阻断、无高。低 1~低 8 仍不阻断。
`docs/evidence/M06/summary.md` 已存在。其中的 523/195.46s、126 passed、11 passed、0015→0014→0015、current=`20261119_0015 (head)` 与日志一致。13 张 PNG 都在 `docs/evidence/M06/ui/`。
`state.json` 已是 `phase=final-gate`、`status=awaiting-final-approval`、`currentSlice=S6`、S6=`validation_rerun_complete`、`validationPassed=true`、`finalApprovalPassed=false`。`lastGate` 为 `s6-validation-rerun-awaiting-critic-and-final-approval`。
滞后的是项目状态文档,不是命令结果:
- `docs/progress.md` 第 5、9、20 行仍是「S6 进行中/正式验证进行中」。
- `docs/tasks/M06.md` 清单第 25–27 行仍未勾选正式测试、pre-done critic 和最终批准。「当前阻塞」和「证据与结论」仍写 S5 等待片审、不得开始 S6。
## Context Gaps
`gates.criticPassed=true` 是更早的 plan critic,不能代替本份 pre-done。`updatedAt` 为 `2026-11-19T06:45:00Z`。
进度和任务卡还没跟上这份 `state.json`。请示用户时以「等待最终批准」为准,不要沿用任务卡里的「不得开始 S6」。
## Validation Gaps
九份日志都在 `.task/2026-11-19/m06-alarm-center/reviews/validation-logs/`,与 `validation-s6.md` 的结果行一致。本审查只读日志,没有重跑命令。
| 日志 | 与报告是否一致 |
| --- | --- |
| `01-alembic-upgrade-head.log` | 一致。`PostgresqlImpl`;没有 `Running upgrade`(当时已在 head)。PowerShell 把 alembic INFO 收成 NativeCommandError。 |
| `02-alembic-downgrade-0014.log` | 一致。`Running downgrade 20261119_0015 -> 20261119_0014`。 |
| `03-alembic-upgrade-head-after-downgrade.log` | 一致。`Running upgrade 20261119_0014 -> 20261119_0015`。 |
| `04-alembic-current.log` | 一致。`20261119_0015 (head)`。 |
| `05-pytest-full.log` | 一致。进度点 7×72+19=523;末行 `523 passed, 1 warning in 195.46s (0:03:15)`。警告是 StarletteDeprecationWarning。 |
| `06-pnpm-test-unit.log` | 一致。vitest `Test Files 20 passed (20)`,`Tests 126 passed (126)`,Start at 14:38:39。 |
| `07-pnpm-typecheck.log` | 一致到「无报错」。只有 `vue-tsc --noEmit` 和同一类 NativeCommandError,没有 TS 错误行。同轮 `08` 的 `vue-tsc -b && vite build` 已建成,用来支持 typecheck 通过。 |
| `08-pnpm-build.log` | 一致。`✓ built in 7.57s`,并有 chunk 大于 500 kB 的提示。 |
| `09-pnpm-e2e-alarms.log` | 与报告的数字一致,但是摘要文件,不是 Playwright reporter。内容为 `exit_code: 0`、`11 passed (15.7s)`、Mock 说明。`ran_at` 写了 approx。不能从这份文件逐条复核 11 个用例名。 |
01~08 没有单独打印 exit code。成功行以及后续命令仍继续执行,支持报告里的 exit 0。NativeCommandError 是 PowerShell 把 INFO/脚本回显当成错误流,不是迁移或构建失败。
截图目录现存 13 张 PNG,名单与报告相符。报告写明本轮没有重拍,沿用 S5。
## Boundary Risks
Mock e2e、合成快照、无真实企微/MES:按完成定义,本地 `DONE_LOCAL` 可以接受。阶段真实集成另行记录。不得把这 11 个用例、合成快照或「没有外发」写成联调通过或真实发送通过。
非新建空库同样可以接受为本地库证据,只要不写成隔离空库已重建。
应用库角色仍可调用合法的 `alarm_apply_transition`,这是已接受的 D37,不是新的越界。接口授权不能写成已经下沉到数据库。同周期更正和正式失败仍是两条入口。
## Required Changes
1. 可以请用户最终批准 `DONE_LOCAL`。批准权在用户。主 Agent 在用户明确批准前不得把大任务标成 `DONE_LOCAL`。
2. 请示前或请示正文里更新 `docs/progress.md` 和 `docs/tasks/M06.md`:S5 片审已通过;S6 模块审查为 PASS_WITH_WARNINGS;正式验证日志已与 `validation-s6.md` 核对;当前等待用户最终批准。删掉「S5 待片审/不得开始 S6」。不要提前写 `DONE_LOCAL`。
3. 请示里写明本地边界:Mock 页面、合成快照、无真实企微/MES、非新建空库、截图沿用 S5、0014 未降到前一修订、并发关闭不是「processing 上双关闭」。
4. 不改业务代码。低 1~低 8 仍不是收口必改。不要补等级筛选、计划时间、M07/M08/M09 或可编排工作流。
## Optional Suggestions
- 若要去掉 e2e 证据等级差,把 Playwright 原始 reporter 贴进 `09-pnpm-e2e-alarms.log`。当前摘要与报告一致,不因此维持 FAIL。
- 把 V033 收成完整 D34:只追加修订/依据,不改写原始 FAIL,不自动新建报警,不自动重发。删掉 payload hash 半句。
- M02 截图、流程文档、规划 xlsx 和 `tsconfig.tsbuildinfo` 与 M06 收口分开处理。
@@ -0,0 +1,58 @@
# S1 实现记录
S1 编码完成,等待独立片审。模块不是 DONE。不得自动开始 S2。
规范:`standards://security/red-line?version=1.1.0`(租户 RLS、迁移只新增、不写入密钥);`standards://engineering/code-comments?version=1.1.1`。本片没有对外 API,未改信封或权限点。
## 改动文件
- `services/watchman/src/watchman/models/alarm.py`
- `services/watchman/src/watchman/models/__init__.py`
- `services/watchman/src/watchman/services/alarms.py`
- `services/watchman/migrations/versions/20261119_0014_alarm_facts.py`
- `services/watchman/tests/test_alarm_occurrences.py`
- `docs/tasks/M06.md`
- `.task/2026-11-19/m06-alarm-center/state.json`
未改:`evaluate_rows`、试算路由、旧迁移、auth、API 路由、前端、M07/M08/M09。
## 行为
- 三张新表 `alarms`、`alarm_occurrences`、`alarm_revision_evidence` 强制 PostgreSQL RLS。`tenant_id` 只取服务端设置。
- 正式 occurrence 引用 M05 输入修订、映射版本、规则版本,以及合成快照的 `snapshot_id`、`version_no`、`module_key`、`scenario_key`、`scenario_name` 和处理范围。没有正式场景表。
- 同一正式身份重复提交只保留一个 occurrence。并发插入由事务咨询锁和唯一约束兜底。
- 合并键是租户、模块、场景、映射输入、周期、独立事件。展示名称和数值正文不参与合并。
- 新周期或新事件新建报警,并用 `previous_alarm_id` 指向同一模块、场景、输入下最近一条报警。
- 已关闭的同一合并键不再追加 occurrence,也不另开报警。关闭动作本身不在本片。
- 同周期更正走 `append_same_cycle_revision`:只追加依据,不改原始 FAIL 修订,不新建报警。没有已有报警时拒绝并零写入。
- `apply_monitored_outcome` 对 PASS、UNKNOWN、空结果、执行失败和试算直接返回,不插入。
处理范围使用了最小显式结构:`principals` 里至少有一个具体 `subject`。这是实现假设,不是新的已确认授权模型。缺范围、`all_tenant`、仅角色、或 `*` 都会拒绝。
## 验证
工作目录:`services/watchman`。数据库是当前配置的 PostgreSQL,不是另建的空库。仓库里没有单独的迁移隔离测试模式。
| 命令 | 结果 |
| --- | --- |
| `uv run alembic upgrade head` | 通过。`20261118_0013 -> 20261119_0014` |
| `uv run alembic downgrade 20261118_0013` 后 `uv run alembic upgrade head` | 通过。结束后 `uv run alembic current` 为 `20261119_0014 (head)` |
| `uv run pytest tests/test_alarm_occurrences.py tests/test_judgment.py -q --tb=line` | 通过。`22 passed in 5.63s` |
`test_alarm_occurrences.py` 覆盖幂等、并发重放、范围内合并、新事件/新周期关联、关闭后同周期不重开、同周期修订不新开报警、缺范围零写入、occurrence 不可改写、RLS,以及试算/非异常零写入。`test_judgment.py` 用来确认 `evaluate_rows` 仍然通过。
未跑:全量 `uv run pytest`、前端检查、Playwright。这些留到后续片或 S6,本片不算被它们挡住。
## 风险
- 合并键和范围 JSON 是 S1 落地选择。片审不要把它写成新的已确认业务规则。
- 持续异常和同周期更正是两个入口。报警仍开放时,`record_formal_failure` 的新观测会再挂一条 occurrence;更正必须调用 `append_same_cycle_revision`。后续正式判定如果只走前一个入口,D34 不会自动生效。
- `previous_alarm_id` 只保存同一模块、场景、输入的最近一条,不是完整历史图。
- 关闭状态的抑制已经写在事实服务里,但没有接手/关闭 API。S2 才能产生生产上的 `closed`。
- 处理范围尚未接到授权判断。S3 不能把这组 JSON 当成已核对的权限点。
- `context-pack.md` 仍写着分析阶段和 `allowedToCode=false`。以 `state.json` 和本次授权为准。
- `docs/progress.md` 本片没有改。开工前工作区里已有无关改动,未纳入本片。
## 建议下一步
派独立片审,只审 S1。通过前不要开始 S2。
@@ -0,0 +1,60 @@
# S2 实现记录
S2 编码完成,等待独立片审。模块不是 DONE。不得自动开始 S3。本片是 `high-risk`,`risk_score` 5。
规范:`standards://security/red-line?version=1.1.0`(租户 RLS、迁移只新增、不写入密钥);`standards://engineering/code-comments?version=1.1.1`。本片没有对外 API,未改信封,未注册或编造权限点。
## 改动文件
- `services/watchman/src/watchman/models/alarm.py`
- `services/watchman/src/watchman/models/alarm_handling.py`
- `services/watchman/src/watchman/models/__init__.py`
- `services/watchman/src/watchman/services/alarms.py`
- `services/watchman/src/watchman/services/alarm_handling.py`
- `services/watchman/migrations/versions/20261119_0015_alarm_handling.py`
- `services/watchman/tests/test_alarm_occurrences.py`
- `services/watchman/tests/test_alarm_handling.py`
- `docs/tasks/M06.md`
- `.task/2026-11-19/m06-alarm-center/state.json`
未改:`20261119_0014`、`auth/access.py`、API 路由、前端、M07/M08/M09。工作区里已有的无关改动(进度、决策、M02 截图、builder 说明)没有纳入本片。
## 行为
- 状态只走 `pending -> processing -> closed`。待处理不能直接关闭,不能转派,不能重开。
- 接手后只有一个当前处理人。同一处理人再次接手不追加第二段历史;另一个主体得到 `already_claimed`。
- 进展只追加。旧进展和原始 FAIL 修订不被改写。
- 关闭只允许当前处理人或范围内 admin。结果只有 `resolved` / `false_positive`,说明必填,并追加一条终态记录。
- 命令按 `x-idempotency-key` 去重。同一键、同一 payload 返回原事件;同一键、不同 payload 冲突。
- `close_validity` 只读终态:`closed` 表示绑定该报警的未执行意图应视为失效。不写意图行,不撤回,不读写次数窗口。
- D36:已关闭的同一合并键再来正式异常时,不重开、不新开报警、不追加 occurrence。追加 `alarm_closed_basis`,并写 `alarm.continued_after_close` 审计。重放不重复写。
- `watchman_app` 不能 UPDATE 报警的状态、处理人和关闭列。合法迁移只经 `alarm_apply_transition`。触发器仍拒绝从待处理直接关闭和反向迁移。处理历史、命令键和关闭依据都是只追加。
- 主体判断用当前处理人,以及既有 `watchman-admin` / `watchman-operator` / `watchman-viewer`。越范围与不存在都是 NotFound。viewer 是 Forbidden,且 `permission_node` 为空。
处理范围仍按合成快照里的具名 `subject` 匹配。角色条目本身不授权。这是 S1 已有的实现假设,不是新的已确认授权模型。
## 验证
工作目录:`services/watchman`。数据库是当前配置的 PostgreSQL,不是另建的空库。
| 命令 | 结果 |
| --- | --- |
| `uv run alembic downgrade 20261119_0014` 后 `uv run alembic upgrade head` | 通过。结束后 head 为 `20261119_0015` |
| `uv run pytest tests/test_alarm_occurrences.py tests/test_alarm_handling.py tests/test_judgment.py --tb=short -q` | 通过。`30 passed in 10.13s` |
覆盖接手、进展、关闭、重复键、并发接手、并发关闭、直接改状态、关闭有效性、PASS/UNKNOWN/失败不恢复,以及 D36 的依据和审计。`test_judgment.py` 用来确认试算入口仍然不写报警。
未跑:全量 `uv run pytest`、前端检查、Playwright。这些留到后续片或 S6,本片不算被它们挡住。
## 风险
- 具名 subject 匹配不是新的权限模型。S3 不能把它写成已核对的权限点,也不能编造报警权限点。
- `close_validity` 和历史读取只受租户 RLS 约束。对象范围仍要由 S3 在路由层检查。
- `alarm_apply_transition` 对 `watchman_app` 可执行,所以持有该数据库角色的人可以走出一条合法状态边,绕过 Python 里的处理人判断。普通 `UPDATE` 改不了状态列。幂等和主体判断在服务层。
- D34 的同周期更正和 D36 的关闭后持续异常仍是两个入口。开放中的报警继续走 `record_formal_failure` 追加 occurrence。
- 关闭依据指向原始 occurrence,不增加 `occurrence_count`,也不改 `last_occurred_at`。
- `context-pack.md` 仍停在分析阶段。以 `state.json` 为准。`docs/progress.md` 本片没有改。
## 建议下一步
派独立片审,只审 S2。通过前不要开始 S3。
@@ -0,0 +1,69 @@
# S3 实现记录
S3 编码完成,等待独立片审。模块不是 DONE。不得自动开始 S4。本片是 `boundary-sensitive`,`risk_score` 4,并且要求 critic。
规范:`standards://api/api-envelope?version=1.1.0`、`standards://api/error-handling?version=1.1.1`、`standards://api/permission-nodes?version=1.0.0`、`standards://security/red-line?version=1.1.0`、`standards://engineering/code-comments?version=1.1.1`。
权限点只使用已批准的 D38,没有另造编码。没有新错误码,因此没有改四语言 `errors.json`。列表分页继续用项目已确认的 `page/page_size`(D25),没有改成规范正文里的 cursor。
## 改动文件
- `services/watchman/src/watchman/api/routes/alarms.py`
- `services/watchman/src/watchman/services/alarm_reads.py`
- `services/watchman/src/watchman/api/app.py`
- `services/watchman/src/watchman/auth/access.py`
- `services/watchman/src/watchman/auth/principal.py`
- `services/watchman/tests/test_alarm_api.py`
- `docs/tasks/M06.md`
- `.task/2026-11-19/m06-alarm-center/state.json`
- `.task/active.json`
未改:前端、HTML 原型、迁移、`alarm_handling.py` 的状态机、M07/M08/M09。工作区里已有的无关改动(进度、决策、M02 截图、builder 说明、规划表)没有纳入本片。
## 行为
- 只读:`GET /alarms`、`GET /alarms/{id}`、`/occurrences`、`/evidence`、`/history`、`/close-validity`。
- 列表筛选只在调用方传入时生效:`module_key`、`scenario_key`、`scenario_name`、`status`、`mapped_input_id`、`occurred_from`、`occurred_to`。排序和 `page/page_size` 在 SQL 里执行。
- 命令:`POST /alarms/{id}/claim|progress|close`。必须带 `x-idempotency-key`。超过 128 字符返回 40000,不截断后写入。
- 命令复用 S2 的 `claim_alarm`、`append_progress`、`close_alarm`。同一键回放原事件。相同幂等键配不同内容返回 409,信封码 40000。
- D37:已关闭后,同一主体用新幂等键再提交完全相同的结果、说明和证据,返回 200,`replayed=true`,不新开终态。
- 授权分三层:既有三角色、D38 权限点、合成快照里的具名 `subject`。角色条目本身不授权。没有 subject 时列表为空,命令返回 42000,不开放成全租户。
- 不存在和越范围的 ID 都是 404,信封码 40000,`reason=not_found`。不先暴露记录是否存在。
- viewer 读得到范围内报警,接手/进展/关闭是 403,信封码 42000,并带回对应权限点。
- 未登录是 401/41000。冲突走现有 `ConflictError`,不手写失败 JSON。
- 关闭有效性先做范围检查,再调用已有的 `close_validity`。响应里不出现“已恢复”。
- 报警模型没有等级字段。本片没有加等级筛选,也没有为它建列。
D38 字面值:
- `perm:data:emp:watchman.alarm.read`
- `perm:data:emp:watchman.alarm.take`
- `perm:data:emp:watchman.alarm.progress`
- `perm:data:emp:watchman.alarm.close`
## 验证
工作目录:`services/watchman`。数据库是当前配置的 PostgreSQL,不是另建的空库。
| 命令 | 结果 |
| --- | --- |
| `uv run pytest tests/test_alarm_api.py --tb=short -q` | 通过。`6 passed, 1 warning in 6.56s` |
| `uv run pytest --tb=line -q` | 通过。`523 passed, 1 warning in 193.25s` |
全量结果包含新的 alarm API 用例,以及既有 S1/S2 报警测试。覆盖 admin/operator/viewer、越范围 ID、401、403+权限点、409、幂等回放、超长幂等键、D37 同内容再关闭,以及试算不出现在列表里。警告是 Starlette 对 httpx 的弃用提示。
未跑:前端 unit、typecheck、build、Playwright。这些留到 S4/S5/S6。
## 风险
- `alarm_apply_transition` 仍可由 `watchman_app` 执行。API 没有把它当授权边界。收紧需要新迁移,本片没有改 `0014`/`0015`。
- 范围匹配仍是合成快照里的具名 subject。这是 S1 的实现假设,不是新的授权模型。
- 处理服务对直接调用仍会把超长幂等键截到 128。HTTP 入口在调用前拒绝。
- `close_validity` 本身只按租户过滤。路由先确认可见,再调用它。
- 列表没有等级筛选,因为报警行上没有等级列。若原型需要等级,要另开范围,不要在 S4 里假造一个空筛选项当已实现。
- 没有新错误码。四语言 `errors.json` 仍只有 40000/41000/42000/50000。冲突原因在 `error.details.reason`,界面文案留给 S5。
- `context-pack.md` 仍停在分析阶段。以 `state.json` 为准。`docs/progress.md` 本片没有改。
## 建议下一步
派独立片审,只审 S3。通过前不要开始 S4。
@@ -0,0 +1,55 @@
# S4 实现记录
S4 只写了报警中心的静态 HTML 原型,用来确认列表、详情、接手、进展、关闭和冲突反馈。正式 Vue 没有开始。模块不是 DONE。用户确认原型之前不得开始 S5。
本片是 `gateClass: simple`,`risk_score` 2,不要求 critic。门禁原因是 `prototype-before-vue`。
规范:已读 `standards://frontend/element-plus?version=1.0.2`。`standards://frontend/frontend-stack?version=2.1.0` 做了检索定位,没有逐段对照选型正文。静态页使用与该规范一致的主色 `#5e6ad2`、字号 13.5px、圆角 8px、控件高 32px。没有引入第二套组件库,也没有把原生控件写进 `web/apps/console`。S5 必须按 Element Plus 具名导入实现,不能照抄本页按钮。
权限点没有新增,仍是 D38 四个已有编码。没有改 API、错误码或四语言文案。
## 改动文件
- `.task/2026-11-19/m06-alarm-center/prototype/index.html`
- `.task/2026-11-19/m06-alarm-center/prototype/README.md`
- `.task/2026-11-19/m06-alarm-center/reviews/impl-s4.md`
- `.task/2026-11-19/m06-alarm-center/state.json`
- `docs/tasks/M06.md`
未改:`web/apps/console`、后端、迁移、M07/M08/M09、`docs/progress.md`、`.task/active.json`。
## 行为
- 列表筛选是草稿。点「查询」才生效,「重置」清空并重新出列表。条件是模块、场景名称、对象、最近发生起止、状态。没有等级筛选项,也没有等级列。
- 表头排序对应 S3 的 `sort_by` / `sort_order`,先排序再分页,不是只排当前页。对象列和操作列不排序。分页用 `page` / `page_size`,可选 10 / 20 / 50,默认 20,放在列表底栏右侧。
- 列表没有「新建」。查询和重置在表格上方。行内只有「打开」,操作列宽约 72px。
- 详情正文可滚动。返回、接手、追加进展、关闭在页脚居中,不在滚动区域内。已关闭后页脚只留返回。
- 观测表把观测时间、计划时间、接收时间分成三列。计划时间、规则原文、实际值和比较值标明是演示。S3 的 occurrence 没有计划时间,依据接口也没有规则原文。
- 关闭结果只有已处理(`resolved`)和误报(`false_positive`),说明必填。待处理不能直接关闭。空说明或未选结果时对话框不提交。
- 他人已接手时,接手提示冲突且不改处理人。非当前处理人不能写进展。关闭只允许当前处理人或管理者。管理者关闭不替换处理人。
- 查看者能看列表和详情。三个命令提示无权,并写出对应权限点,不展示服务端英文原文。
- 无主体时列表为空,并说明没有处理范围。另有「还没有报警」「没有符合条件的报警」「加载中」「加载失败」「无权」「没有找到这条报警」。
- 样例 `alm-1003` 展示关闭后依据。文案说明报警仍是已关闭,最近发生和观测次数不变。页面正文没有「已恢复」。
- 提交中按钮变为「提交中」并禁止再点。相同幂等冲突和再次关闭都不新增历史。
## 验证
| 检查 | 结果 |
| --- | --- |
| `node --check` 抽取后的页面脚本 | 通过 |
| 脚本走查:查询不即时生效、无匹配、排序、接手、关闭必填、已关闭页脚、冲突、无权、空/失败/加载/范围外、关闭后依据,且正文无「已恢复」 | 通过。这是 Node 里模拟点击,不是浏览器。 |
| 1440×900、1280×800、1920×1080 人眼检查 | `NOT_RUN`。检查要点写在原型 README。 |
| Playwright、前端 unit / typecheck / build | `NOT_RUN`。留给 S5 / S6。 |
| pytest | `NOT_RUN`。本片没有改后端。 |
## 风险
- 计划时间和判定原文若被看成已有接口,S5 会做出没有字段的列。原型已标明演示。确认前不要实现这两块。
- 需求里的等级筛选仍然没有数据来源。本片按 S3 审查结论不放空筛选项。
- 查看者是否显示三个命令按钮,还要用户定。隐藏按钮不能当作授权。
- `.task/active.json` 仍是开工 S4 时的指针(`allowedToCode=true`,`currentSlice=S4`)。以本目录 `state.json` 为准:S4 编码已完成,等用户确认,不能开始 S5。
- `docs/progress.md` 本片没有改。进度仍应由主 Agent 写入。
## 建议下一步
请用户按 README 打开原型并确认。确认前保持 S5 不开始。
Loaded 100 of 456 files, more files were not shown because too many files have changed in this diff. Show more