feat(alarms): 完成 M06 报警中心与人工处理
落地正式异常创建/合并、三状态人工处置与控制台,关闭 M06 DONE_LOCAL(含 D40 认领文案「处理」)。 Co-authored-by: Cursor <cursoragent@cursor.com>
No files matched your search
@@ -1,7 +1,7 @@
|
|||||||
---
|
---
|
||||||
name: marionettist-builder
|
name: marionettist-builder
|
||||||
description: Orchestrates the full repository Marionettist flow from analysis to slice coding and review
|
description: Orchestrates the full repository Marionettist flow from analysis to slice coding and review
|
||||||
model: gpt-5.6-sol
|
model: grok-4.7
|
||||||
---
|
---
|
||||||
|
|
||||||
You are the local Marionettist build orchestrator.
|
You are the local Marionettist build orchestrator.
|
||||||
|
|||||||
@@ -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 { "&": "&", "<": "<", ">": ">", '"': """ }[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 不开始。
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# S5 实现记录
|
||||||
|
|
||||||
|
S5 编码完成,等待独立片审。模块不是 DONE。不得开始 S6。S6 是 `boundary-sensitive`,`risk_score` 4,并且要求 critic。
|
||||||
|
|
||||||
|
规范:`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`。
|
||||||
|
|
||||||
|
D39 覆盖了需求稿里的等级筛选。页面没有等级筛选项,也没有等级列。详情只使用 S3 已有字段:观测时间、接收时间、依据、处理历史等。没有计划时间、规则原文、实际值或比较值。
|
||||||
|
|
||||||
|
## 改动文件
|
||||||
|
|
||||||
|
- `web/apps/console/src/alarms/`:列表、详情、客户端、按钮可见性、错误文案、筛选参数。
|
||||||
|
- `web/apps/console/src/router.ts`、`web/apps/console/src/AppShell.vue`:报警路由和侧栏入口。
|
||||||
|
- `web/apps/console/locales/{zh-CN,zh-TW,en,th}/common.json`
|
||||||
|
- `web/apps/console/e2e/alarms.spec.ts`
|
||||||
|
- `docs/evidence/M06/ui/`:Playwright 截图。
|
||||||
|
- `docs/tasks/M06.md`、`docs/progress.md`、本记录、`state.json`。
|
||||||
|
|
||||||
|
未改:后端业务语义、权限点、迁移、M07/M08/M09。没有 commit。工作区里早于本片的后端和文档改动没有纳入本片。
|
||||||
|
|
||||||
|
控制台目前没有 ProTable。本片沿用查询列表的 Element Plus 具名组件和同一套列表骨架,没有新造一套控件,也没有在 `main.ts` 全量注册 Element。
|
||||||
|
|
||||||
|
## 行为
|
||||||
|
|
||||||
|
- 列表筛选在点「查询」后才请求。参数只有接口已有的 `module_key`、`scenario_name`、`mapped_input_id`、`status`、`occurred_from`、`occurred_to`,加上 `sort_by`、`sort_order`、`page`、`page_size`。对象列是 `identity_key`,不排序,因为接口不能按它排序。
|
||||||
|
- 三种空状态:还没有报警;没有符合条件的报警;会话没有处理主体时说明看不到报警。没有主体时即使响应里有行,也不把它们画出来。
|
||||||
|
- 加载失败可重试。统一信封的 `message` 不进界面。409 用 `details.reason` 的固定文案,并重新拉详情。
|
||||||
|
- viewer 的页脚只有返回。待处理只给接手。处理中的当前处理人可以写进展和关闭。管理者可以关闭别人正在处理的报警,不能接手抢走处理人,也不能代写进展。已关闭后页脚只留返回。
|
||||||
|
- 关闭和进展用 480px 对话框。说明或关闭结果没填时对话框不关。同一份内容重试沿用同一个 `x-idempotency-key`。
|
||||||
|
- 关闭后依据的说明是「报警保持关闭」。四语言文案都不含「已恢复」。
|
||||||
|
- 按钮隐藏不是授权。命令仍由后端检查。
|
||||||
|
|
||||||
|
## 验证
|
||||||
|
|
||||||
|
工作目录:`web/apps/console`。Playwright 拦截的是浏览器里的 `/alarms`,没有打真实后端。
|
||||||
|
|
||||||
|
| 命令 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| `pnpm test:unit` | 通过。`126 passed`(20 files) |
|
||||||
|
| `pnpm typecheck` | 通过 |
|
||||||
|
| `pnpm build` | 通过。Vite 仍提示主包超过 500 kB,这是现有控制台的体积提示 |
|
||||||
|
| `pnpm test:e2e -- e2e/alarms.spec.ts` | 通过。`11 passed` |
|
||||||
|
|
||||||
|
截图在 `docs/evidence/M06/ui/`:
|
||||||
|
|
||||||
|
- 列表与详情:`U06-list-1440x900.png`、`U06-list-1280x800.png`、`U06-list-1920x1080.png`、`U06-detail-1440x900.png`、`U06-detail-1280x800.png`、`U06-detail-1920x1080.png`
|
||||||
|
- 状态:`U06-empty-1440x900.png`、`U06-no-match-1440x900.png`、`U06-no-scope-1440x900.png`、`U06-load-failed-1440x900.png`、`U06-viewer-1440x900.png`、`U06-conflict-1440x900.png`、`U06-closed-1440x900.png`
|
||||||
|
|
||||||
|
三视口断言了列表分页和详情页脚留在窗口内,并且页面本身不出现横向滚动。已关闭页脚只有返回。
|
||||||
|
|
||||||
|
未跑:真实后端联调、全量 pytest、模块级 S6 审查。这些留给 S6。
|
||||||
|
|
||||||
|
## 风险
|
||||||
|
|
||||||
|
- 共享 `requestJson` 没有把信封上的 `permission_node` 放进 `BusinessError`。页面在 403 时展示的是这次操作对应的 D38 权限点,不是服务端原文。
|
||||||
|
- 对象筛选提交的是 `mapped_input_id`。列表上看到的是 `identity_key`。不是 UUID 的输入会在本地拦住,不会把服务端句子显示出来。
|
||||||
|
- 没有处理范围的判断来自会话 `subject` 是否为空。真实接口在没有主体时返回空页。前端用这个空页配「没有处理范围」,避免写成「租户里没有报警」。
|
||||||
|
- Playwright 是 Mock。它不能代替 S6 的真实权限、并发和数据库验证。
|
||||||
|
- `vue-tsc -b` 会写出未跟踪的 `web/apps/console/tsconfig.tsbuildinfo`。它不是功能文件。
|
||||||
|
|
||||||
|
## 建议下一步
|
||||||
|
|
||||||
|
派独立片审,只审 S5。通过前不要开始 S6,也不要标模块 DONE。
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
# M06 整模块审查(S6)
|
||||||
|
|
||||||
|
- 任务:`.task/2026-11-19/m06-alarm-center/`
|
||||||
|
- 范围:S1~S5 合在一起,对照冻结 `requirement.md`、`implementation-plan.md`、`boundary.md`、D32~D39,以及 A-037~A-047
|
||||||
|
- 审查方式:Tier L、`gateClass: boundary-sensitive`、`risk_score: 4`、要求 critic。按两段审查(边界与合规,然后实现质量)。本审查不改业务代码,也不复跑测试。
|
||||||
|
- 片审基线:S1~S3、S5 均为 `PASS_WITH_WARNINGS`;S4 为用户确认的原型(D39)。本报告不把已关闭的片审中项重新打开,除非合在一起之后仍然影响模块验收。
|
||||||
|
|
||||||
|
## Recommendation
|
||||||
|
|
||||||
|
PASS_WITH_WARNINGS
|
||||||
|
|
||||||
|
这不是 FAIL。没有阻断项,也没有高严重度代码缺陷。模块仍不得标 `DONE_LOCAL`:测试计划里的 V033/V042 还是旧口径,本审查没有复跑正式验证,S6 的 pre-done critic 和用户最终批准都还没发生。
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
S1~S5 合起来覆盖了报警事实、有限合并、新周期关联、三状态人工处理、列表/详情/命令 API、合成快照范围,以及控制台列表和详情。关闭有效性是从 `closed` 读出来的标志,没有意图行、次数窗口、通知执行器、场景发布表或可编排工作流。
|
||||||
|
|
||||||
|
D32~D39 的已确认口径在代码里是一致的。D36 替换了 S1 里「关闭后同键不落库」。D37 接受了两件当时的中项:应用库角色可以调用合法状态函数;已关闭后相同内容、新幂等键再关闭视为回放。D38 只有四个已登记权限点。D39 明确不做等级筛选和等级列,也不展示计划时间。
|
||||||
|
|
||||||
|
试算入口不写报警。读取和命令都先过角色和权限点,再按快照里的具名 subject 收范围;没有 subject 时列表是空页,命令是 403。越范围和不存在的 ID 都是 404。页面不出现「已恢复」。
|
||||||
|
|
||||||
|
已知的对象筛选和 Mock 端到端测试都不阻断 DONE。前者不要靠新增查询参数来修。后者只能当页面证据,不能当成前后端联调通过。
|
||||||
|
|
||||||
|
## Stage 1:边界与合规
|
||||||
|
|
||||||
|
### 范围
|
||||||
|
|
||||||
|
停在本模块允许的边上:
|
||||||
|
|
||||||
|
- 事实与合并:`models/alarm.py`、`services/alarms.py`、迁移 `20261119_0014`
|
||||||
|
- 处理与关闭有效性:`models/alarm_handling.py`、`services/alarm_handling.py`、迁移 `20261119_0015`
|
||||||
|
- API:`api/routes/alarms.py`、`services/alarm_reads.py`,以及 `auth/access.py`、`auth/principal.py` 里的四个报警节点
|
||||||
|
- 控制台:`web/apps/console/src/alarms/`、`e2e/alarms.spec.ts`
|
||||||
|
- 路由只多挂了 `alarms.router`(`api/app.py`)
|
||||||
|
|
||||||
|
没有滑进这些禁止区域:
|
||||||
|
|
||||||
|
- M07:没有企微、通道、模板、发送任务,也没有撤回已受理消息的命令
|
||||||
|
- M08:没有场景表、Cron、正式发布实体。快照字段落在报警和 occurrence 行上
|
||||||
|
- M09:没有次数窗口、阈值、升级目标。`close_validity` 只读 `status == closed`,不读写窗口
|
||||||
|
- 可编排工作流:状态只有 `pending -> processing -> closed`,没有可配置转移或指派
|
||||||
|
- 自动恢复、待处理直接关闭、转派、重开、审批、批量关闭
|
||||||
|
|
||||||
|
`GET /alarms/{id}/close-validity` 是冻结稿允许的终态查询语义,给后续模块读「未执行意图应失效」。它不落意图行。
|
||||||
|
|
||||||
|
### 规格
|
||||||
|
|
||||||
|
| 验收 | 结论 |
|
||||||
|
| --- | --- |
|
||||||
|
| 1 首次正式异常创建;正常/未知/失败/试算不创建 | 满足。`apply_monitored_outcome` 只在 `source=formal` 且 `code=abnormal` 时写入。`evaluate_rows` 与映射路由不引用报警服务 |
|
||||||
|
| 2 同一 occurrence 重放不新增 | 满足。正式身份唯一约束,重放返回原行 |
|
||||||
|
| 3 范围内只加依据;范围外/新身份可新建并关联 | 满足。合并键是租户、模块、场景、映射输入、`cycle_key`、`event_key`。新报警写 `previous_alarm_id` |
|
||||||
|
| 4 列表/详情筛选、分页、排序、依据和历史 | 满足,等级除外。等级由 D39 明确拿掉。对象筛选用 `mapped_input_id`,见低 1 |
|
||||||
|
| 5 正向转换、进展、关闭可追溯,不改原始异常 | 满足。处理事件追加。occurrence 更新被触发器拒绝 |
|
||||||
|
| 6 并发接手一个处理人;关闭无矛盾终态 | 接手满足。关闭的库约束和行锁能保住单一终态。测试没有在 `processing` 上并发两次关闭,见低 4 |
|
||||||
|
| 7 越权由后端拒绝 | 满足。viewer 三条命令是 403 加对应节点。范围外是 404。前端隐藏按钮不是授权 |
|
||||||
|
| 8 不显示恢复;后续 PASS/UNKNOWN/失败不自动关闭 | 满足。状态只有待处理、处理中、已关闭。关闭结果只有 `resolved`/`false_positive` |
|
||||||
|
| 9 D32~D35 的 M06 部分,含 V042 的「不清零、不建窗口、不混淆身份、无撤回」 | 行为满足。`docs/testing-plan.md` 的 V033/V042 仍是旧文案,不能当验收真源。见中 1 |
|
||||||
|
| 10 U06 三视口断言、截图、视觉复核 | 页面证据在。`e2e/alarms.spec.ts` 覆盖 1440×900、1280×800、1920×1080。`docs/evidence/M06/ui/` 有 13 张截图。接口是 Mock。见低 2 |
|
||||||
|
|
||||||
|
A-037~A-043 有对应的服务和 API 测试名(V030~V037 的行为,不是测试计划旧句子)。A-044~A-047 落在控制台:模块、场景名、时间、状态筛选;详情里的观测时间和接收时间、occurrence、修订依据、关闭后依据、处理历史;接手冲突、进展、关闭后只留返回。清单里 A-045 的「计划时间」按 D39 不做,接口也没有这个字段。
|
||||||
|
|
||||||
|
### D32~D39
|
||||||
|
|
||||||
|
| 决定 | 落地 |
|
||||||
|
| --- | --- |
|
||||||
|
| D32 | `close_validity`:已关闭则 `unexecuted_intents_should_invalidate=true`,否则 false。不插入意图,不撤回,不清窗口 |
|
||||||
|
| D33 | 范围内 operator/admin 可接手。进展只给当前处理人。关闭给当前处理人或范围内 admin。结果仅已处理/误报,说明必填。待处理关闭返回 `illegal_transition`。无转派、重开 |
|
||||||
|
| D34 | `append_same_cycle_revision` 只追加修订依据,不新建报警,不改原 occurrence。正式失败入口不会自动改走这条。见低 7 |
|
||||||
|
| D35 | 快照最小字段在事实行上。缺范围、仅角色、`all_tenant`、subject `*` 都在写入前拒绝。试算不产生报警。没有场景表 |
|
||||||
|
| D36 | 已关闭的同一合并键不新开、不重开、不追加 occurrence。追加 `alarm_closed_basis` 和 `alarm.continued_after_close` 审计。新周期另开一条并指回旧报警 |
|
||||||
|
| D37 | 状态列只经 `alarm_apply_transition`。函数 `GRANT EXECUTE` 给 `watchman_app`,`PUBLIC` 无执行权。已关闭后同一主体、相同结果/说明/证据、新幂等键返回 `replayed=true`,历史仍是一条 `close`。不同内容是 `already_closed` |
|
||||||
|
| D38 | 仅 `perm:data:emp:watchman.alarm.read`、`.take`、`.progress`、`.close`。`access.py` 禁止在这里再编节点 |
|
||||||
|
| D39 | 无等级筛选和等级列。详情只用接口已有字段。viewer 看不到接手/进展/关闭。已关闭页脚只返回。三种空状态分开。admin 可关闭他人报警,不能抢走处理人,也不能代写进展 |
|
||||||
|
|
||||||
|
D39 是比冻结稿「用户流程里含等级」更晚的确认,等级筛选不算验收缺口。不要在收口时把等级筛选项补回去。
|
||||||
|
|
||||||
|
### 规则与验证合规
|
||||||
|
|
||||||
|
- 没有把 `observed`/`target` 规则写成当前硬约束。
|
||||||
|
- 公司信封仍由语义异常和全局处理。路由不手写失败 JSON。列表仍是 D25 的 `page`/`page_size`,不是规范正文里的 cursor。
|
||||||
|
- 权限点用的是用户已登记的 D38,不是邻近模块编出来的编码。
|
||||||
|
- 各片实现记录里的 pytest、前端 unit、typecheck、build、alarms e2e 与用例内容对得上。本审查没有复跑,那些数字不能写成 S6 的通过证据。
|
||||||
|
- `risk_score: 4` 没有被各片较低的 `gateClass` 抵消。选定的 `autonomous` 到 S6 必须停。本结论也不授权标 DONE。
|
||||||
|
|
||||||
|
## Stage 2:实现质量
|
||||||
|
|
||||||
|
### 试算、合并、关闭
|
||||||
|
|
||||||
|
`record_formal_failure` 在 `confirmed_abnormal is not True` 时直接返回。`apply_monitored_outcome` 把 trial、normal、unknown、empty、error 挡在任何插入之前。映射试算路由不调用报警服务。
|
||||||
|
|
||||||
|
同一正式身份(修订、映射版本、规则版本、快照、周期、事件、观测时间)重复提交返回原 occurrence。开放中的同键新观测走追加。已关闭则写依据和审计。咨询锁按租户、模块、场景、映射输入串行,处理路径用同一把锁,再 `SELECT FOR UPDATE`。
|
||||||
|
|
||||||
|
同周期更正是另一个函数。没有报警时它拒绝写入,不会顺手开一条报警。原始 occurrence 的修订号不能原位改。
|
||||||
|
|
||||||
|
### 状态机、幂等、并发
|
||||||
|
|
||||||
|
插入必须是未接手的 `pending`。普通 `UPDATE` 改不了状态、处理人、接手时间、关闭时间和关闭结果;`watchman_app` 的表级 UPDATE 已收回,只留 `occurrence_count`、`last_occurred_at`、`updated_at`。`pending -> closed` 被触发器拒绝。
|
||||||
|
|
||||||
|
接手:第二个不同主体得到 `already_claimed`,不覆盖当前处理人。同一幂等键重放原事件。关闭保留原处理人,所以 admin 关闭不会把处理人改成自己。进展只追加事件,不改状态列。
|
||||||
|
|
||||||
|
命令幂等键在租户内唯一,摘要含报警 ID、命令、主体和角色。同一键配不同内容是 `idempotency_payload_mismatch`。API 拒绝空键和超过 128 的键。D37 的相同内容新键只再挂一条命令,不新开终态事件。
|
||||||
|
|
||||||
|
### 授权、RLS、页面
|
||||||
|
|
||||||
|
读权限是既有三角色,未知角色 403,节点为 read。接手、进展、关闭是 operator 或 admin,viewer 带对应节点 403。角色条目本身不授权。范围来自快照 `principals` 里 `kind=subject` 的值。主体为空时列表 `total=0`,命令 403。响应不带 `tenant_id` 和 `handling_scope`。
|
||||||
|
|
||||||
|
`20261119_0014` 与 `0015` 对报警、occurrence、依据、处理事件、命令、关闭依据启用并 FORCE RLS,策略是 `tenant_id = current_setting('app.tenant_id')`,面向 `watchman_app`。调用方不能传 tenant。定义者函数另有一条仅表所有者的租户策略,避免 FORCE RLS 下更新 0 行。
|
||||||
|
|
||||||
|
页面查询在点「查询」之后才把筛选送出,输入时不筛选。首次进入会拉未筛选的第一页,这和 D25「禁止输入即筛」一致。排序和分页走服务端。403 文案用本次操作对应的 D38 节点,不直出服务端 `message`。四语言报警文案的单测禁掉「已恢复」。
|
||||||
|
|
||||||
|
## Findings
|
||||||
|
|
||||||
|
无阻断。无高。
|
||||||
|
|
||||||
|
### 中 1:V033/V042 仍是决定之前的句子
|
||||||
|
|
||||||
|
- Location: `docs/testing-plan.md` 第 89 行、第 98 行。实现计划「Documentation Update Requirement」要求在 S6 正式验证前改这两句。
|
||||||
|
- 现在的句子:V033 是「按 O06 最终口径,不因 payload hash 改变乱报」。V042 是「严格按 O04 最终决定执行;不预设窗口是否清零」。
|
||||||
|
- 已确认口径:V033 应按 D34,同周期更正只追加修订和依据,不改原始 FAIL,不自动新建报警,不自动重发。V042 的 M06 部分应按 D32:关闭不清零次数窗口,不建窗口表或意图表,旧报警和新报警的身份不混淆,没有撤回已受理消息的接口。V038~V041 仍不属于 M06。
|
||||||
|
- Risk: 拿旧文案当测试真源时,会把「窗口是否清零」继续当成未决,也可能用 payload hash 去衡量 D34。
|
||||||
|
- Required Fix: 标 `DONE_LOCAL` 之前必须改这两句。这是文档,不是业务代码。改完再跑正式验证。不要把 V038~V041 写进 M06 的通过条件。
|
||||||
|
|
||||||
|
### 低 1:对象筛选用映射编号,列表显示身份键
|
||||||
|
|
||||||
|
- Location: `alarm_reads.search_alarms` 的 `mapped_input_id`;`AlarmList.vue` 对象列 `identity_key`;`filters.ts` 只接受 UUID。文案是「对象编号」。
|
||||||
|
- Risk: 列上是类似 `furnace-01` 的身份键。筛选框不接受这个值,页面也不展示那个 UUID。按看到的对象去查,请求发不出去。
|
||||||
|
- Required Fix: 不阻断 DONE。不要为了好填而加 `identity_key` 查询参数或改后端。若改文案,要写明填的是映射对象编号,不是表上的身份键。
|
||||||
|
|
||||||
|
### 低 2:alarms 端到端测试是页面 Mock
|
||||||
|
|
||||||
|
- Location: `web/apps/console/e2e/alarms.spec.ts` 拦截 `/alarms` 和 `/auth/me`。截图在 `docs/evidence/M06/ui/`。
|
||||||
|
- Risk: 它能证明文案、按钮、查询参数和三个桌面视口里分页、页脚还在视口内。它不能证明真实权限、快照范围、并发、数据库幂等或 RLS。加载失败图证明的是页面不渲染 Mock 放进 `message` 的内容。
|
||||||
|
- Required Fix: 不阻断 DONE。证据里必须写明这是 Mock。模块行为验收以隔离 PostgreSQL 上的后端测试为准。不得把这 11 个用例写成前后端联调通过。
|
||||||
|
|
||||||
|
### 低 3:切换报警后,未成功的幂等键还留着
|
||||||
|
|
||||||
|
- Location: `AlarmDetail.vue` 的 `claimHold`、`progressHold`、`closeHold`。加载和路由 ID 变化时没有清掉。
|
||||||
|
- Risk: 上一笔失败后,点到关联的另一条报警再提交同一段说明,会沿用旧键。服务端按租户查键,摘要里有报警 ID,返回 `idempotency_payload_mismatch`,不会写到另一条上。改一个字会换新键。离开详情后组件销毁,键消失。
|
||||||
|
- Required Fix: 不阻断。若修,在报警 ID 变化时清掉三份 hold。
|
||||||
|
|
||||||
|
### 低 4:并发关闭用例是在终态之后重放
|
||||||
|
|
||||||
|
- Location: `test_alarm_handling.py` 的 `test_concurrent_claim_and_close_have_one_outcome`。
|
||||||
|
- Risk: 两人同时接手是真并发,结果是一个处理人。关闭那段先顺序提交了一次关闭,再并发提交「相同说明」和「不同说明」。这覆盖的是 D37 回放和 `already_closed`,不是两条关闭同时从 `processing` 出发。代码路径有咨询锁和 `FOR UPDATE`,触发器也不允许多个终态。
|
||||||
|
- Required Fix: 不阻断。正式验证不要把这个用例说成「处理中双关闭」已覆盖。若补测试,应在 `processing` 上并发两次关闭。
|
||||||
|
|
||||||
|
### 低 5:完整性错误的恢复会丢掉原异常
|
||||||
|
|
||||||
|
- Location: `alarm_handling._recover_command`。找不到命令行时使用不带对象的 `raise`。
|
||||||
|
- Risk: 这个 `raise` 不在 `except` 帧里,会变成 `RuntimeError: No active exception to reraise`。同一幂等键的正常竞争能找到对方已提交的命令。只有约束失败但又没有命令行时才会踩中。
|
||||||
|
- Required Fix: 不阻断。
|
||||||
|
|
||||||
|
### 低 6:范围内、非当前处理人的关闭没有单独的 HTTP 断言
|
||||||
|
|
||||||
|
- Location: 服务层 `test_claim_and_close_authorization` 断言了 operator 关闭他人报警是 `not_current_handler`。API 用例覆盖了 viewer 关闭 403、他人进展 409、admin 在范围内关闭且处理人不变。
|
||||||
|
- Risk: HTTP 上「范围内另一名 operator 关闭」没有单独打到。路由先查范围再进同一个服务函数,缺口是用例,不是另一套授权。
|
||||||
|
- Required Fix: 不阻断。
|
||||||
|
|
||||||
|
### 低 7:D34 不会从正式失败入口自动分流
|
||||||
|
|
||||||
|
- Location: `record_formal_failure` 与 `append_same_cycle_revision`。
|
||||||
|
- Risk: 同周期、同事件、新修订若走正式失败入口,会追加 occurrence,而不是只写修订依据。更正必须显式调用更正函数。当前没有 M08 运行时把两者接混。S1 已接受双入口,后续接线仍要显式选择。
|
||||||
|
- Required Fix: 不阻断。不要在 M06 收口时把两个函数合成一个自动判断。
|
||||||
|
|
||||||
|
### 低 8:RLS 负向断言偏重 alarms 表
|
||||||
|
|
||||||
|
- Location: `test_alarm_rls_is_forced_and_tenant_scoped`。未设置租户时 `alarms` 计数为 0,其他租户读不到该报警,无租户插入失败。
|
||||||
|
- Risk: occurrence、依据、处理事件、命令、关闭依据同样 FORCE RLS,但负向用例没有逐表做跨租户读。策略写法与报警表相同。
|
||||||
|
- Required Fix: 不阻断。正式验证若补,只加读断言,不要放宽策略。
|
||||||
|
|
||||||
|
其余残留,都不阻断:
|
||||||
|
|
||||||
|
- 服务层把超长幂等键截成 128。HTTP 入口已经拒绝超长,截断只影响直接调用服务的路径。
|
||||||
|
- 幂等摘要包含角色集合。同一主体若两次请求的角色不同,同一键会冲突。这符合「不同内容必须冲突」。
|
||||||
|
- 数据库的范围检查只拒绝空范围和 `all_tenant`。具名 subject 由服务拒绝角色条目、星号和全租户。这是冻结稿允许的:字段布局未单独立项,缺省必须拒绝。
|
||||||
|
- D37 已接受:`watchman_app` 可以自己调用合法的 `alarm_apply_transition`,函数不看处理范围,也不看是不是当前处理人。正式入口的主体判断在 API 和服务里。不要把它写成「数据库已完成授权」。
|
||||||
|
- 幂等身份含 `observed_at`。正式入口必须复用源观测时间,否则同一次异常会被当成另一条 occurrence。
|
||||||
|
- 任务卡和 `state.json` 仍写着 S5 待审、不得开始 S6。那是本审查开始前的指针。主 Agent 收口时更新,本审查不改。
|
||||||
|
|
||||||
|
## 已知项是否阻断 DONE
|
||||||
|
|
||||||
|
| 项 | 是否阻断 DONE |
|
||||||
|
| --- | --- |
|
||||||
|
| 对象筛选用 `mapped_input_id`,显示用 `identity_key` | 否。保持低优先级。不要为收口改 API |
|
||||||
|
| Playwright Mock | 否,只要证据写明是页面 Mock,并且隔离 PostgreSQL 上的后端测试单独通过。只用 Mock 宣布模块通过则不行 |
|
||||||
|
| V033/V042 旧文案 | 阻断 DONE,不阻断本审查结论。先改文档,再按新口径记录验证 |
|
||||||
|
| 本审查未复跑测试 | 阻断 DONE。各片声称不能代替 S6 正式验证记录 |
|
||||||
|
|
||||||
|
## 证据缺口与正式验证
|
||||||
|
|
||||||
|
本审查没有执行下面任何命令。S1~S5 实现记录里的通过次数只说明当时跑过,不能抄成 S6 证据。RLS、唯一约束和并发只认隔离 PostgreSQL,不认 SQLite,也不认浏览器 Mock。
|
||||||
|
|
||||||
|
标 DONE 前建议在隔离空库上按这个顺序做,并记下命令、库和结果。迁移缺陷用新迁移修正,不做破坏性回滚。
|
||||||
|
|
||||||
|
1. 后端迁移到当前版本
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd D:\PROJECT\watchman\services\watchman
|
||||||
|
uv run alembic upgrade head
|
||||||
|
```
|
||||||
|
|
||||||
|
2. 只对 M06 两条迁移做一次降级再升级:`20261119_0015` 然后 `20261119_0014`,再 `upgrade head`。不要动更早的迁移,不要删卷。
|
||||||
|
|
||||||
|
3. 后端全量
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd D:\PROJECT\watchman\services\watchman
|
||||||
|
uv run pytest
|
||||||
|
```
|
||||||
|
|
||||||
|
其中应能看到报警事实、处理、API 三组用例,包括试算不写报警、跨租户、越范围、409、幂等、D37 同内容再关闭、并发接手。跑完后写明:并发关闭用例没有覆盖「两条关闭同时离开 processing」。
|
||||||
|
|
||||||
|
4. 前端
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd D:\PROJECT\watchman\web\apps\console
|
||||||
|
pnpm test:unit
|
||||||
|
pnpm typecheck
|
||||||
|
pnpm build
|
||||||
|
pnpm test:e2e -- e2e/alarms.spec.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
5. 专项记录,不另建 M09 用例:
|
||||||
|
|
||||||
|
- V030~V037 的行为,按代码和冻结稿,不按测试计划旧句
|
||||||
|
- V033 按 D34,V042 只记 M06 部分:关闭不清零、不建窗口或意图表、新旧报警身份不混淆、无撤回接口
|
||||||
|
- V038~V041 不在本模块
|
||||||
|
- U06 三视口:断言加 `docs/evidence/M06/ui/` 截图。写明 API 为 Mock
|
||||||
|
- 跨租户、越范围、重复命令、并发接手
|
||||||
|
|
||||||
|
验证之后若改了代码、配置或依赖,受影响部分要再审查再测。通过记录本身也不等于 `DONE_LOCAL`,还要 pre-done critic 和用户最终批准。
|
||||||
|
|
||||||
|
## 标 DONE 之前必须做的事
|
||||||
|
|
||||||
|
必须做:
|
||||||
|
|
||||||
|
1. 把 `docs/testing-plan.md` 的 V033、V042 改成 D34、D32 口径。
|
||||||
|
2. 按上一节在隔离 PostgreSQL 上实跑,并留下可回查的结果。Mock e2e 单独标明。
|
||||||
|
3. S6 pre-done critic。
|
||||||
|
4. 用户最终批准后,主 Agent 才能把大任务标为 `DONE_LOCAL`。
|
||||||
|
|
||||||
|
不必在标 DONE 前改业务代码。低 1~低 8 都不是必须修复项。不要借收口去补等级筛选、计划时间、M07/M08/M09 或可编排工作流。
|
||||||
|
|
||||||
|
## 残留风险
|
||||||
|
|
||||||
|
- 合成快照和具名 subject 是过渡授权。M08 替换正式发布时要做兼容,M06 不建场景表是对的。
|
||||||
|
- 应用库角色仍可调用合法状态函数。这是 D37,不是未修的漏洞,但也不能当成接口授权已经下沉到数据库。
|
||||||
|
- 同周期更正和正式失败是两条入口。以后的运行时接线必须显式选择。
|
||||||
|
- 顾问锁按映射输入串行,不按周期拆。这是为了保住 `previous_alarm_id`,高并发时同一对象的不同周期会互相等待。
|
||||||
|
|
||||||
|
## 本审查没有做的事
|
||||||
|
|
||||||
|
- 没有改业务代码、测试、任务状态或 `docs/progress.md`。
|
||||||
|
- 没有复跑 pytest、alembic、前端命令,也没有逐张重看截图。
|
||||||
|
- 没有代替 pre-done critic,也没有把模块标成 DONE。
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
# Boundary Review Result
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
S1 报警事实、occurrence、有限合并与新周期关联的实现留在本片内。三张新表、领域服务和 PostgreSQL 测试没有滑入接手/关闭 API、前端、M07/M08/M09 或可编排工作流。试算与非异常路径不写报警,M05 `evaluate_rows` 与试算路由未被改写。幂等、有限合并、`previous_alarm_id` 和 D34 追加依据在服务层和测试里是实打实的断言。
|
||||||
|
|
||||||
|
结论是 **PASS_WITH_WARNINGS**。没有阻断项,因此不是 FAIL。S1 仍是 `gateClass: high-risk`、`risk_score: 5`。即使本片通过,也不能自动开始 S2;主 Agent 应先向用户确认,并带上下面两条中等问题的产品语义。
|
||||||
|
|
||||||
|
本审查没有改业务代码,也没有复跑 alembic 或 pytest。验证证据来自 `reviews/impl-s1.md` 的自述,加上对测试源码的核对。用例库存与「22 passed」一致:`test_alarm_occurrences.py` 10 个,`test_judgment.py` 12 个(含参数化)。
|
||||||
|
|
||||||
|
## Changed Scope
|
||||||
|
|
||||||
|
按 S1 行为审阅的文件:
|
||||||
|
|
||||||
|
- `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`(新,`down_revision=20261118_0013`)
|
||||||
|
- `services/watchman/tests/test_alarm_occurrences.py`(新)
|
||||||
|
- `docs/tasks/M06.md`
|
||||||
|
- `.task/2026-11-19/m06-alarm-center/state.json`
|
||||||
|
- `.task/2026-11-19/m06-alarm-center/reviews/impl-s1.md`
|
||||||
|
|
||||||
|
`models/__init__.py` 的 diff 只有 `Alarm`、`AlarmOccurrence`、`AlarmRevisionEvidence` 的导入和 `__all__`。`judgment.py`、试算路由、旧迁移、auth、API app、前端不在本片 diff 里。
|
||||||
|
|
||||||
|
工作区里还有不属于本片行为的未提交改动,不应算进 S1,也不应在提交 S1 时顺手打包:`.cursor/agents/marionettist-builder.md`、`docs/agent-workflow.md`(builder 模型改为 grok-4.7)、`docs/decisions.md`(D31 改写,以及 D32~D35 / O04~O06 收口)、`docs/progress.md`、M02 截图、`docs/预警平台开发规划_初期开发计划.xlsx`。`docs/decisions.md` 的 D32~D35 与冻结稿一致,没有把可编排工作流或 M08 收尾写成当前实现。
|
||||||
|
|
||||||
|
## Review Dimensions
|
||||||
|
|
||||||
|
- Boundary / Spec / Scope / Rules / Validation: 通过,带警告。范围、RLS、租户注入、试算隔离和 D34 的专用入口符合已冻结口径。验证没有在隔离空库上独立复跑。
|
||||||
|
- Code Quality / Maintainability / Implementation / Test Quality: 通过,带警告。测试断言的是行数、身份、状态和异常,不是空调用。关闭后的抑制语义和双入口需要在 S2 前讲清楚。
|
||||||
|
|
||||||
|
### Stage 1:边界与合规
|
||||||
|
|
||||||
|
本片允许范围是新的 alarm 模型、服务、迁移、测试和必要的模型导出,只引用 M05/M01。实际业务代码符合这个范围。
|
||||||
|
|
||||||
|
- 没有报警路由、接手、关闭、进展、权限点、Vue、企微、Cron、次数窗口或意图表。
|
||||||
|
- 状态列 `pending/processing/closed` 和 `current_handler` 提前放在表上,服务只插入 `pending`。测试为了 V032 直接把行改成 `closed`。这是后续状态机的表结构,不是 S2 API。
|
||||||
|
- 合成快照是行上的字段,没有场景发布表。`snapshot_id` 无外键。
|
||||||
|
- `handling_scope` 的 `principals` 布局在代码注释和 `impl-s1.md` 里写明是实现假设,没有写成新的已确认授权模型。
|
||||||
|
- 合并列在 `alarms.py` 标成 S1 落地选择,没有升格成新决策。
|
||||||
|
- D32~D35 在 `docs/decisions.md` 中标为用户确认,与冻结稿一致。没有把 `observed` / `target` 规则改写成 `hard`。
|
||||||
|
- `docs/testing-plan.md` 第 89 行 V033 仍写「按 O06 最终口径」。critic 已要求留到 S6 再改。S1 测试按 D34 断言,没有拿这句旧文案当通过标准。
|
||||||
|
|
||||||
|
试算隔离:
|
||||||
|
|
||||||
|
- `apply_monitored_outcome` 在 `source != "formal"`、`outcome != "result"` 或 `code != "abnormal"` 时直接返回,不插入。
|
||||||
|
- `record_formal_failure` 在 `confirmed_abnormal is not True` 时返回,默认参数是 `False`。
|
||||||
|
- `test_trial_and_non_fail_outcomes_write_nothing` 覆盖 normal、unknown、empty、error、trial,并断言 `evaluate_rows` 之后计数仍是 `(0, 0, 0)`。
|
||||||
|
- 同一测试用源码检查确认 `judgment` 和 mappings 路由没有引用 `watchman.services.alarms`。`judgment.py` 不在本片 diff 中。
|
||||||
|
|
||||||
|
### Stage 2:实现与测试
|
||||||
|
|
||||||
|
幂等键是租户、输入修订、映射版本、规则版本、`snapshot_id`、周期、事件、`observed_at`。`received_at`、展示名和数值正文不在键里。同一对象重放返回同一 occurrence,并发重放断言只有一行。同一合并键、更晚的 `observed_at` 会再挂一条 occurrence,不新开报警;`scenario_name` 改了也不拆报警。新 `event_key` 或新 `cycle_key` 新建报警,并用 `previous_alarm_id` 指向同一模块、场景、输入下按 `opened_at` 最近的一条。不同 `scenario_key` 不串历史。
|
||||||
|
|
||||||
|
D34 的 `append_same_cycle_revision` 在没有对应报警时抛 `ConflictError` 且回滚后行数不变;有报警时只追加 `alarm_revision_evidence`,原始 occurrence 的修订 id 不变,重放不新增依据。数据库触发器拒绝更新 occurrence。
|
||||||
|
|
||||||
|
RLS 与现有迁移同一模式:`ENABLE` + `FORCE`,策略 `tenant_isolation` 只比较 `current_setting('app.tenant_id', true)`,租户列只从 `get_settings().tenant_id` 写入。并发创建用事务咨询锁 `pg_advisory_xact_lock(hashtextextended(...))`,唯一约束作兜底。
|
||||||
|
|
||||||
|
## Violations
|
||||||
|
|
||||||
|
无阻断项。没有改禁止文件,没有旧迁移回写,没有把试算接进报警,也没有把范围 JSON 写成已确认权限模型。
|
||||||
|
|
||||||
|
## 问题
|
||||||
|
|
||||||
|
### 中 1:关闭后的同键新观测不落库
|
||||||
|
|
||||||
|
- File: `services/watchman/src/watchman/services/alarms.py`(`record_formal_failure` 在约 489–491 行对 `status == closed` 返回 `suppressed=True`);测试 `services/watchman/tests/test_alarm_occurrences.py` 约 487–517 行
|
||||||
|
- Rule: V032 要求关闭后旧输入不重报,新周期可以新建并关联历史。冻结稿同时要求合并范围内的持续异常留下依据。
|
||||||
|
- Risk: 已关闭的同一 `cycle_key` + `event_key` 上,即使修订 id 和 `observed_at` 都变了,也不会插入 occurrence。报警不重开,这一点和 V032 一致;正式事实本身也被丢掉。S2 一旦沿用这个入口,关闭后的持续异常没有可追溯依据。
|
||||||
|
- Required Fix: 本片可以保持该行为,但进入 S2 前要向用户确认:关闭后的同键新观测是「抑制且不落库」,还是「不新开报警、仍追加依据」。不要把它写成已经确认的新业务规则。
|
||||||
|
|
||||||
|
### 中 2:D34 不会从正式失败入口自动生效
|
||||||
|
|
||||||
|
- File: `services/watchman/src/watchman/services/alarms.py`(`record_formal_failure` 约 456 行;`append_same_cycle_revision` 约 522 行);`reviews/impl-s1.md` 风险节
|
||||||
|
- Rule: D34。同周期值更正只追加修订和依据,不改写原始 FAIL,不自动新建报警。
|
||||||
|
- Risk: 两个入口是分开的。报警仍开放时,把更正修订送进 `record_formal_failure` 会再挂一条 occurrence,并增加 `occurrence_count`,不会走证据表。当前没有生产判定管道调用它们,所以本片没有写错测试所覆盖的路径。以后的正式判定如果只接前一个入口,D34 会落空。
|
||||||
|
- Required Fix: S2 及以后的正式判定接线必须显式选择入口。本片不必合并这两个函数。
|
||||||
|
|
||||||
|
### 中 3:库表不约束状态迁移,待处理可以直接写成已关闭
|
||||||
|
|
||||||
|
- File: `services/watchman/migrations/versions/20261119_0014_alarm_facts.py` 约 117 行,`ck_alarms_status` 只限制三个字符串;`alarm_occurrences` / `alarm_revision_evidence` 有追加触发器,`alarms` 没有
|
||||||
|
- Rule: D33 禁止从待处理直接关闭。该流转属于 S2,不是本片的 API。
|
||||||
|
- Risk: `watchman_app` 对 `alarms` 仍有 UPDATE。S1 测试自己就把 `pending` 改成 `closed`。S2 不能假设数据库会拦住直接关闭、双处理人或覆盖历史。
|
||||||
|
- Required Fix: S2 在服务层做正向流转。若需要数据库兜底,用新迁移,不要改 `20261119_0014`。
|
||||||
|
|
||||||
|
### 低 1:任务文档互相不一致
|
||||||
|
|
||||||
|
- File: `.task/active.json` 仍是 `phase=coding`、`nextCommand=implement S1`(`updatedAt` 03:02Z);`.task/2026-11-19/m06-alarm-center/state.json` 已是 `awaiting-review`(03:30Z);`context-pack.md` 仍写「无已批准编码片」和 `allowedToCode=false`;`docs/progress.md` 的 M06 行仍写「S1 测试待跑」
|
||||||
|
- Rule: 进度以 `docs/progress.md` 为准,当前片以任务状态为准。实现说明承认 context-pack 过期,并说本片没有改 progress。工作区里的 progress 实际已改到 M06,但停在编码开始时的句子。
|
||||||
|
- Risk: 下一轮若只读 `active.json` 或 progress,会把 S1 当成还没写完,或把已跑过的针对性测试当成没跑。
|
||||||
|
- Required Fix: 由主 Agent 在不覆盖无关 diff 的前提下,把指针和进度改成「S1 片审 PASS_WITH_WARNINGS,等待用户确认后才开 S2」。本审查不改这些状态文件。
|
||||||
|
|
||||||
|
### 低 2:数据库范围检查比服务层宽
|
||||||
|
|
||||||
|
- File: 迁移与 `alarm.py` 的 `_SCOPE_SQL` 只要求 `principals` 数组至少一项,且不能出现 `all_tenant` 键。服务层 `_require_scope`(`alarms.py` 约 151–181 行)另外拒绝仅角色、`*`、`all`、`tenant`
|
||||||
|
- Rule: D35 禁止默认 operator 全租户;缺范围必须拒绝。字段布局本身未冻结。
|
||||||
|
- Risk: 绕过领域服务的插入可以写下仅角色的范围。本片唯一写入路径会拒绝,测试覆盖了空范围、仅角色、`all_tenant` 和 `*`。
|
||||||
|
- Required Fix: 不在本片把某种 JSON 形状补成已确认模型。S3 不能把库里的这段 JSON 当成已核对权限点。
|
||||||
|
|
||||||
|
### 低 3:RLS 负向断言偏弱,occurrence / evidence 没有单独的跨租户读
|
||||||
|
|
||||||
|
- File: `services/watchman/tests/test_alarm_occurrences.py` 约 647–727 行
|
||||||
|
- Rule: 新表必须强制 RLS。
|
||||||
|
- Risk: 无租户 GUC 时 `count(*) = 0` 没有先在正确租户下读回刚提交的那一行,单看这条不能区分「被 RLS 挡住」和「没写上」。同文件其他测试能在租户会话里读回报警。无 GUC 的插入会失败。三张表都断言了 `relrowsecurity`、`relforcerowsecurity` 和 `tenant_isolation`,且表主人不是 `watchman_app`。跨租户不可见只查了 `alarms`。
|
||||||
|
- Required Fix: 不阻断本片。后续片若改 RLS,先读回再断言不可见,并覆盖 occurrence 与 evidence。
|
||||||
|
|
||||||
|
### 低 4:幂等身份包含 `observed_at`
|
||||||
|
|
||||||
|
- File: `alarm.py` 唯一约束 `uq_alarm_occurrences_formal_identity`;`FormalFailure` 注释写明重放身份包含 `observed_at`
|
||||||
|
- Rule: 同一正式异常重投不得再插入。持续异常在合并范围内应追加依据。
|
||||||
|
- Risk: 调用方若每次用「现在」充当观测时间,同一次业务失败会在同一报警下多挂 occurrence。`received_at` 变化不会拆身份。这和「持续异常追加、精确重放不追加」一致,但是正式判定入口的契约,不是已经隐含的任务级幂等。
|
||||||
|
- Required Fix: 以后的正式入口必须复用源观测时间。不必改本片键,除非用户把幂等定义成不含观测时间。
|
||||||
|
|
||||||
|
### 低 5:验证库不是计划里的隔离空库,本审查未复跑
|
||||||
|
|
||||||
|
- File: `reviews/impl-s1.md` 验证表;计划 S1 Validation 要求隔离的真实 PostgreSQL
|
||||||
|
- Rule: SQLite 或纯 Mock 不能算本片通过。
|
||||||
|
- Risk: 自述是在当前配置的 PostgreSQL 上 `upgrade`、`downgrade` 到 `20261118_0013` 再 `upgrade`,以及 22 个 pytest 通过。用例确实连 PostgreSQL(RLS、触发器、咨询锁),不是内存库。downgrade 跑在共享库上有误伤风险,但这次新表是本迁移才创建的。本审查没有重跑命令,不能把自述改写成独立复测通过。
|
||||||
|
- Required Fix: 不要求本片重跑全量 pytest 或 Playwright。提交或 S6 前保留可回查的命令输出。
|
||||||
|
|
||||||
|
## Warnings
|
||||||
|
|
||||||
|
见上面的中、低问题。另外:
|
||||||
|
|
||||||
|
- `previous_alarm_id` 只指向同一模块、场景、输入下最近打开的一条,不是完整历史图。实现说明已经写明。新事件测试断言了这条链;不同场景断言不串链。
|
||||||
|
- 同键重放若处理范围不同,返回第一条,不报冲突。「相同幂等键、不同 payload 必须冲突」写在命令语义里,属于 S2/S3,本片按首写为准。
|
||||||
|
- 咨询锁按租户、模块、场景、输入串行,不按周期拆锁。这能保住 `previous_alarm_id` 链。S2 的关闭必须使用同一把锁,否则关闭与追加会交错。`_find_alarm` 没有 `FOR UPDATE`。
|
||||||
|
|
||||||
|
## Missing Validation
|
||||||
|
|
||||||
|
- 本审查未执行 `alembic` 或 pytest。
|
||||||
|
- 未在单独的空库上复核 downgrade。
|
||||||
|
- 未跑全量 pytest、前端或 Playwright。这些按计划不属于 S1 通过条件。
|
||||||
|
- 没有「已有报警之后,PASS/UNKNOWN/失败不改状态」的回归。当前 `apply_monitored_outcome` 在写入前返回,代码路径做不到改状态;测试只证明了从空库出发不插入。
|
||||||
|
- 没有并发「两个不同观测合并到同一报警」或「两个新周期抢 `previous_alarm_id`」的测试。同身份并发重放有测试。
|
||||||
|
|
||||||
|
## Parallel Group Check
|
||||||
|
|
||||||
|
- Applicable: 否。S1 是顺序片。
|
||||||
|
- Shared Files: 模型导出和新迁移。旧迁移、auth、API app、router 未改。
|
||||||
|
- Merge Owner: 主 Agent
|
||||||
|
- Fallback Order: 不适用
|
||||||
|
- Group Validation: 不适用
|
||||||
|
- Issues: 无并行合并问题
|
||||||
|
|
||||||
|
## Marionettist Gate Check
|
||||||
|
|
||||||
|
- 分析到编码:`state.json` 与 `docs/tasks/M06.md` 记录用户已确认,且只批准 S1。`context-pack.md` 没有同步,见低 1。
|
||||||
|
- 本片编码后进入片审,符合「同一片编码后直接审查」。
|
||||||
|
- `gatePolicy.selected` 为 `autonomous`,但不能跳过 `high-risk` 且 `risk_score` 5 的片间停顿。S2 同样是 `high-risk`、`risk_score` 5、需要 critic。
|
||||||
|
- 本审查不把 `reviewPassed` 写成 true,也不改 `allowedToCode`。
|
||||||
|
|
||||||
|
## Documentation Sync Needed
|
||||||
|
|
||||||
|
- 主 Agent 更新 `docs/progress.md`、`.task/active.json`,并在下次编码前修正 `context-pack.md` 的阶段和 `allowedToCode`。不要在本片把 `principals` 布局或合并列补进 `docs/decisions.md` 当成新确认决策。
|
||||||
|
- `docs/project/knowledge-map.md` 不需要因这三张表更新。设计含义没有超出已冻结的 M06 报警事实。
|
||||||
|
- `docs/testing-plan.md` 的 V033/V042 旧句仍留到 S6,按 critic 的意见处理。
|
||||||
|
|
||||||
|
## 能否进入 S2
|
||||||
|
|
||||||
|
不能自动进入。建议主 Agent 把本报告交给用户,确认中 1 的关闭抑制语义后,再单独批准 S2。用户确认前保持 `proposedNextSlice=S2`、`allowedToCode` 不扩展到 S2。
|
||||||
|
|
||||||
|
## Final Recommendation
|
||||||
|
|
||||||
|
PASS_WITH_WARNINGS
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
# Boundary Review Result
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
S2 正向状态机、追加历史、关闭有效性和 D36 留在本片内。新的处理表、迁移 `20261119_0015` 和领域服务没有滑入报警 API、前端、权限点、M07/M08/M09 或可编排工作流。状态只走 `pending -> processing -> closed`。关闭结果只有 `resolved` / `false_positive`,说明必填。已关闭的同一合并键不再重开、不再追加 occurrence,会追加 `alarm_closed_basis` 和 `alarm.continued_after_close` 审计。普通 `UPDATE` 改不了状态列,从待处理直接关闭也会被触发器拒绝。
|
||||||
|
|
||||||
|
结论是 **PASS_WITH_WARNINGS**。没有阻断项,因此不是 FAIL。S2 仍是 `gateClass: high-risk`、`risk_score: 5`,并且要求 critic。即使本片通过,也不能自动开始 S3。
|
||||||
|
|
||||||
|
本审查没有改业务代码,也没有复跑 alembic 或 pytest。验证证据来自 `reviews/impl-s2.md` 的自述,加上对迁移、服务和测试源码的核对。用例库存与「30 passed」的拆分一致:`test_alarm_occurrences.py` 10 个,`test_alarm_handling.py` 8 个,`test_judgment.py` 12 个(含参数化 4 + 5)。终端记录里没有找到这次命令的输出。
|
||||||
|
|
||||||
|
## Changed Scope
|
||||||
|
|
||||||
|
按 S2 行为审阅的文件:
|
||||||
|
|
||||||
|
- `services/watchman/src/watchman/models/alarm.py`(关闭列、状态检查约束;S1 事实表仍在)
|
||||||
|
- `services/watchman/src/watchman/models/alarm_handling.py`(新)
|
||||||
|
- `services/watchman/src/watchman/models/__init__.py`(增加三个处理模型导出;报警事实模型仍是未提交的 S1 导出)
|
||||||
|
- `services/watchman/src/watchman/services/alarms.py`(D36 关闭依据和审计;开放中的合并仍追加 occurrence)
|
||||||
|
- `services/watchman/src/watchman/services/alarm_handling.py`(新)
|
||||||
|
- `services/watchman/migrations/versions/20261119_0015_alarm_handling.py`(新,`down_revision=20261119_0014`)
|
||||||
|
- `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`
|
||||||
|
- `.task/2026-11-19/m06-alarm-center/reviews/impl-s2.md`
|
||||||
|
|
||||||
|
`20261119_0014` 仍只建事实表,没有 `alarm_apply_transition` 或处理表。`auth/access.py`、`api/app.py`、试算路由和 `test_judgment.py` 不在本片 diff 里。`api/app.py` 仍然只挂健康检查、认证、平台、数据源、查询和映射。
|
||||||
|
|
||||||
|
工作区里还有不属于本片行为的未提交改动,不应算进 S2,也不应在提交 S2 时顺手打包:`.cursor/agents/marionettist-builder.md`、`docs/agent-workflow.md`、`docs/decisions.md`、`docs/progress.md`、`.task/active.json`、M02 截图、`docs/预警平台开发规划_初期开发计划.xlsx`。`docs/decisions.md` 里的 D36 与冻结稿一致,没有把可编排工作流写成当前实现。
|
||||||
|
|
||||||
|
## Review Dimensions
|
||||||
|
|
||||||
|
- Boundary / Spec / Scope / Rules / Validation: 通过,带警告。范围、三状态、D33 关闭主体/结果/说明、D32 终态导出和 D36 依据加审计符合已冻结口径。验证没有在隔离空库上独立复跑。
|
||||||
|
- Code Quality / Maintainability / Implementation / Test Quality: 通过,带警告。测试断言的是状态、历史行、依据行、审计条数和数据库异常,不是空调用。应用角色仍可调用合法迁移函数;已关闭后的相同内容再次关闭被实现成回放成功。
|
||||||
|
|
||||||
|
`risk_score: 5` 没有被拿来放宽审查。本报告走两阶段,并且不把 `autonomous` 当成可以跳过片间停顿的理由。
|
||||||
|
|
||||||
|
### Stage 1:边界与合规
|
||||||
|
|
||||||
|
本片允许范围是新的 handling 模型、服务、迁移、测试,以及为 D36 修正 `record_formal_failure`。主体判断只用当前处理人和既有三角色。实际业务代码符合这个范围。
|
||||||
|
|
||||||
|
- 没有报警路由、Vue、权限点注册、企微、Cron、次数窗口、意图表或撤回命令。
|
||||||
|
- `close_validity` 只读 `alarms.status`。`closed` 时 `unexecuted_intents_should_invalidate` 为真。它不插入意图,不读写窗口。
|
||||||
|
- 关闭结果只有 `resolved` / `false_positive`。服务、检查约束和事件形状一致。`recovered` 在测试里被拒绝。
|
||||||
|
- 待处理关闭被服务拒绝(`illegal_transition`)。触发器同样拒绝 `pending -> closed` 和反向迁移。
|
||||||
|
- 接手后第二个主体得到 `already_claimed`。转派、重开、自动恢复没有入口。已关闭后再接手被拒绝。
|
||||||
|
- viewer 走 `ForbiddenError`,`permission_node` 为空。越范围、仅角色条目、不存在的报警都是 `NotFoundError`。
|
||||||
|
- 具名 `subject` 匹配仍标成 S1 的实现假设,没有写成新的已确认授权模型。角色条目本身不授权。
|
||||||
|
- D32~D36 没有被改写成额外模块。没有把 `observed` / `target` 规则升成当前硬约束。
|
||||||
|
- 开放中的同键新观测仍走 `_attach`,增加 occurrence。D34 仍是 `append_same_cycle_revision`,不并进正式失败入口。
|
||||||
|
|
||||||
|
S1 的关闭抑制被 D36 替换,而不是被删掉事实:同一 `cycle_key` + `event_key` 在 `closed` 时不新建报警、不改 `occurrence_count`,新周期仍用 `previous_alarm_id` 关联。`0014` 没有被回写。
|
||||||
|
|
||||||
|
### Stage 2:实现与测试
|
||||||
|
|
||||||
|
接手、进展、关闭都先拿与事实写入相同的咨询锁(租户、模块、场景、输入),再 `SELECT … FOR UPDATE`。进展只插入新事件,并只改 `updated_at`。旧进展和原始 occurrence 的修订 id 没有更新入口。历史、命令键和关闭依据表只有 `SELECT, INSERT`,另有语句级触发器拒绝 UPDATE / DELETE / TRUNCATE。
|
||||||
|
|
||||||
|
幂等键是租户内唯一。同一键、同一 payload 回放原事件;同一键、不同 payload 返回 `idempotency_payload_mismatch`。并发两个不同主体接手的测试要求结果恰好是一个 `ok` 和一个 `already_claimed`,并且只有一条 claim 事件。同一 claim 键的并发测试要求两个会话得到同一个 `event_id`。
|
||||||
|
|
||||||
|
D36 在 `record_formal_failure` 里于咨询锁之后判断。已有 occurrence 身份仍直接返回,不另写依据。已关闭且身份是新的正式异常时写 `alarm_closed_basis`,指向最早的 occurrence,并调用既有 `create_audit_event`。重放先查依据行,找到就返回,不再写第二笔审计。`test_closed_cycle_does_not_reopen_and_new_cycle_links` 断言了:不新开、不追加 occurrence、依据只一行、审计动作恰好 1 条、新周期另开一条 `pending` 并指回旧报警。`test_close_validity_is_derived_without_intent_rows` 另外从 `apply_monitored_outcome` 走了关闭后的正式异常,并断言 PASS / UNKNOWN / error 不改关闭状态。
|
||||||
|
|
||||||
|
状态列保护有两层。`0015` 收回 `watchman_app` 对 `alarms` 的表级 UPDATE,只留下 `occurrence_count`、`last_occurred_at`、`updated_at`。行级触发器在 `app.alarm_transition` 不是 `service` 时拒绝状态、处理人和关闭列变化;插入也必须是未接手的 `pending`。合法写入只经过 `SECURITY DEFINER` 的 `alarm_apply_transition`。测试把 ORM 的 `status = closed` 和函数里的 `pending -> closed` 都断言为数据库异常,关闭后状态仍是 `pending`。
|
||||||
|
|
||||||
|
M05 试算入口没有被改。`apply_monitored_outcome` 仍在非 `formal` / 非异常时直接返回。`test_judgment.py` 不在本片改动里,参数化之后仍是 12 个用例。
|
||||||
|
|
||||||
|
## Violations
|
||||||
|
|
||||||
|
无阻断项。没有改禁止文件,没有旧迁移回写,没有编造权限点,没有意图表、窗口表或可编排工作流。
|
||||||
|
|
||||||
|
## 问题
|
||||||
|
|
||||||
|
### 中 1:应用角色可以直接走出合法状态边
|
||||||
|
|
||||||
|
- File: `services/watchman/migrations/versions/20261119_0015_alarm_handling.py` 约 200–251 行;`services/watchman/src/watchman/services/alarm_handling.py` 约 322–354 行;测试 `test_direct_status_update_cannot_skip_the_service` 约 482–503 行
|
||||||
|
- Rule: D33 的接手和关闭主体在服务层判断。普通 UPDATE 不得绕过状态机。
|
||||||
|
- Risk: 触发器和列权限挡住了普通 `UPDATE`,也挡住了 `pending -> closed`。`alarm_apply_transition` 仍 `GRANT EXECUTE` 给 `watchman_app`。持有该角色的会话可以自己把待处理改成处理中、再改成已关闭,只要边是合法的。函数不看处理范围,也不看是不是当前处理人。幂等和主体判断只在 Python 里。实现说明已经写了这一点,测试还断言了 `watchman_app` 有执行权、`PUBLIC` 没有。
|
||||||
|
- Required Fix: 不阻断本片。S3 不能把这个函数当成授权边界。若以后要收紧,用新迁移限制调用方,不要改 `0014`。
|
||||||
|
|
||||||
|
### 中 2:已关闭后,相同内容的新关闭键会回放成功
|
||||||
|
|
||||||
|
- File: `services/watchman/src/watchman/services/alarm_handling.py` 约 647–658 行;测试 `test_concurrent_claim_and_close_have_one_outcome` 约 375–409 行
|
||||||
|
- Rule: 冻结稿错误处理写明,重复幂等命令返回原结果;相同幂等键配不同 payload 必须冲突;重复关闭要明确拒绝。验收要求的是无矛盾终态。
|
||||||
|
- Risk: 同一幂等键的回放是对的,不同说明会得到 `already_closed`。但报警已经关闭之后,同一主体用新的幂等键再提交完全相同的结果、说明和证据时,服务把原关闭事件绑到新命令上,并返回 `replayed=True`,而不是拒绝。终态仍然只有一条关闭事件,处理人不会被改掉。测试把这条「ok」写成了预期。S3 如果原样映射成成功响应,就和「重复关闭明确拒绝」不一致。
|
||||||
|
- Required Fix: 不阻断本片,因为没有第二套终态。开 S3 前要让用户选一条:相同内容的再次关闭继续回放成功,或改成 `already_closed` 并改测试。不要在 API 里同时写成两种契约。
|
||||||
|
|
||||||
|
### 低 1:完整性错误的恢复会丢掉原异常
|
||||||
|
|
||||||
|
- File: `services/watchman/src/watchman/services/alarm_handling.py` 约 314–319 行,由约 399、537、609、711 行的 `except IntegrityError` 调用
|
||||||
|
- Rule: 冲突应返回明确的完整性或幂等错误。
|
||||||
|
- Risk: `_recover_command` 在找不到命令行时使用不带对象的 `raise`。这个 `raise` 不在 `except` 栈帧里,会变成 `RuntimeError: No active exception to reraise`,原来的 `IntegrityError` 丢失。同一幂等键的正常竞争能找到对方已提交的命令,现有并发测试走的是那条。只有约束失败但又没有命令行时才会踩中。
|
||||||
|
- Required Fix: 不阻断。下次碰到这个函数时改成显式重新抛出原来的异常。不必为这一条单独开修复片。
|
||||||
|
|
||||||
|
### 低 2:并发关闭测试是在终态之后重放
|
||||||
|
|
||||||
|
- File: `services/watchman/tests/test_alarm_handling.py` 约 341–420 行
|
||||||
|
- Rule: 计划要求并发关闭在真实 PostgreSQL 上只有一个终态。
|
||||||
|
- Risk: 两个接手者的并发是从 `pending` 真的抢行锁。两个关闭线程开始时,报警已经提交为 `closed`。这条测试证明了重复关闭不会多出事件,没有证明两个 `processing -> closed` 同时提交时的行锁。服务在改状态前确有 `FOR UPDATE`,和已测的接手锁是同一条路径。
|
||||||
|
- Required Fix: 不阻断。S6 或后续补一条从 `processing` 出发的双关闭即可。
|
||||||
|
|
||||||
|
### 低 3:幂等键超长时被悄悄截断
|
||||||
|
|
||||||
|
- File: `services/watchman/src/watchman/services/alarm_handling.py` 约 98–105 行
|
||||||
|
- Rule: 相同键相同 payload 回放,不同 payload 冲突。
|
||||||
|
- Risk: 超过 128 个字符的键被截断后入库,而不是拒绝。两个只在第 129 个字符之后不同的键会合成同一个键。调用方如果总是传短键,不会碰到。
|
||||||
|
- Required Fix: 不阻断。S3 读 `x-idempotency-key` 时,超长应返回字段错误,不要截断。
|
||||||
|
|
||||||
|
### 低 4:任务指针互相不一致
|
||||||
|
|
||||||
|
- File: `.task/active.json` 仍是 `phase=coding`、`allowedToCode=true`、`nextCommand=implement S2 then auto-review`(`updatedAt` 03:48Z);`.task/2026-11-19/m06-alarm-center/state.json` 已是 `review` / `coding_done_awaiting_review` / `allowedToCode=false`(04:25Z);`context-pack.md` 仍停在分析阶段;`docs/progress.md` 的 M06 行仍写「S2 进行中」「S2 待跑」
|
||||||
|
- Rule: 进度以 `docs/progress.md` 为准,当前片以任务状态为准。实现说明承认 context-pack 过期,并说本片没有改 progress。
|
||||||
|
- Risk: 下一轮若只读 `active.json` 或 progress,会把 S2 当成还在写,或把已声称跑过的测试当成没跑,甚至在片审期间继续编码。
|
||||||
|
- Required Fix: 由主 Agent 在不覆盖无关 diff 的前提下,把指针和进度改成「S2 片审 PASS_WITH_WARNINGS,等待用户确认后才开 S3」。本审查不改这些状态文件。
|
||||||
|
|
||||||
|
### 低 5:验证库不是计划里的隔离空库,本审查未复跑
|
||||||
|
|
||||||
|
- File: `reviews/impl-s2.md` 验证表;计划 S2 Validation 要求隔离的真实 PostgreSQL
|
||||||
|
- Rule: SQLite 或纯 Mock 不能算本片通过。
|
||||||
|
- Risk: 自述是在当前配置的 PostgreSQL 上从 `0015` 降到 `0014` 再升回,以及 30 个 pytest 通过。用例确实使用 RLS、触发器、咨询锁和 `ThreadPoolExecutor`,不是内存库。降级跑在共享库上有误伤风险;这次新增的是处理表和报警上的列与触发器。本审查没有重跑命令,终端里也没有「30 passed」的输出,不能把自述改写成独立复测通过。用例个数和文件拆分与 30 相符。
|
||||||
|
- Required Fix: 不要求本片重跑全量 pytest 或 Playwright。提交或 S6 前保留可回查的命令输出。
|
||||||
|
|
||||||
|
## Warnings
|
||||||
|
|
||||||
|
见上面的中、低问题。另外:
|
||||||
|
|
||||||
|
- `close_validity` 和历史读取只按租户 RLS 过滤,不按快照范围过滤。这和实现说明一致。S3 路由必须再查范围,不能把服务函数当成已经授权的读接口。
|
||||||
|
- 范围内 admin 可以关闭别人接手的报警,但不能追加进展。测试覆盖了 admin 关闭和 admin 被拒绝记进展。这和「当前处理人追加进展、当前处理人或 admin 关闭」一致。
|
||||||
|
- 同一处理人用新键再次接手会绑到第一条 claim,不追加第二段历史。代码在 `claim_alarm` 约 488–495 行。实现说明写了,测试没有单独断言这条。
|
||||||
|
- D36 断言了一次新观测及其重放。第二条不同 `observed_at` 会因正式身份唯一键再插入一行依据和一笔审计;代码如此,测试没再走一遍。
|
||||||
|
- 精确重放已经存在的 occurrence 会在关闭判断之前返回,不另写依据。这是同一次事实的重投,不是关闭后的新观测。
|
||||||
|
- 关闭依据指向最早一条 occurrence,不增加 `occurrence_count`,也不改 `last_occurred_at`。测试断言了计数和原始修订 id。
|
||||||
|
- `alarm.py` 里状态常量上方仍有一句「留给后续处理片」的旧注释。类文档已经改成状态只能走迁移函数。不影响行为。
|
||||||
|
- 数据库范围检查仍然比服务层宽。这是 S1 的低项,本片没有把它收成新的权限模型。
|
||||||
|
|
||||||
|
## Missing Validation
|
||||||
|
|
||||||
|
- 本审查未执行 `alembic` 或 pytest。
|
||||||
|
- 未在单独的空库上复核 `0014 ↔ 0015`。
|
||||||
|
- 未跑全量 pytest、前端或 Playwright。这些按计划不属于 S2 通过条件。
|
||||||
|
- 没有从 `processing` 同时提交两次关闭的测试。见低 2。
|
||||||
|
- 没有查询 `information_schema.column_privileges` 来单独证明状态列无 UPDATE。迁移代码有列级授权,直接改状态的测试会失败,但失败原因可能是触发器,也可能是列权限。
|
||||||
|
- 处理历史、命令和关闭依据没有单独的跨租户读回断言。RLS 测试检查了六张表的 `FORCE RLS` 和 `tenant_isolation` 策略,负向不可见仍主要落在 `alarms`。
|
||||||
|
- 关闭命令本身的「同一键、不同说明」没有单独用例;进展和接手有。关闭走的是同一个 `_start` 哈希。
|
||||||
|
|
||||||
|
## Parallel Group Check
|
||||||
|
|
||||||
|
- Applicable: 否。S2 是顺序片。
|
||||||
|
- Shared Files: 模型导出、`alarms.py`、新迁移。旧迁移、auth、API app、router 未改。
|
||||||
|
- Merge Owner: 主 Agent
|
||||||
|
- Fallback Order: 不适用
|
||||||
|
- Group Validation: 不适用
|
||||||
|
- Issues: 无并行合并问题
|
||||||
|
|
||||||
|
## Marionettist Gate Check
|
||||||
|
|
||||||
|
- 分析到编码:`state.json` 与 `docs/tasks/M06.md` 记录用户已确认 D36 并只批准 S2。`active.json` 没有同步到片审,见低 4。
|
||||||
|
- 本片编码后进入片审,符合「同一片编码后直接审查」。
|
||||||
|
- `gatePolicy.selected` 为 `autonomous`,但不能跳过 `high-risk` 且 `risk_score` 5 的片间停顿。S3 是 `boundary-sensitive`、`risk_score` 4,并且要求 critic。两条都要停。
|
||||||
|
- 最终批准仍然必需。本片通过不等于模块 DONE。
|
||||||
|
|
||||||
|
## Documentation Sync Needed
|
||||||
|
|
||||||
|
- 不需要因为本片新增了处理表就改架构文档。状态机和 D36 的行为已经写在冻结稿和 `docs/decisions.md`。
|
||||||
|
- `docs/testing-plan.md` 的 V033 / V042 旧文案仍按计划留到 S6,本片没有拿它们当通过标准。
|
||||||
|
- 主 Agent 应更新 `docs/progress.md`、`.task/active.json` 和 context-pack 指针。见低 4。不要在同一次提交里打包无关的 builder、决策和 M02 截图改动,除非那些改动单独确认过。
|
||||||
|
|
||||||
|
## 能否进入 S3
|
||||||
|
|
||||||
|
不能自动进入。建议主 Agent 把本报告交给用户。用户确认后才能开 S3。
|
||||||
|
|
||||||
|
确认时带上两条中等问题:
|
||||||
|
|
||||||
|
1. `watchman_app` 可以调用合法的 `alarm_apply_transition`,绕过 Python 里的处理人判断。S3 的授权必须留在路由和服务里。
|
||||||
|
2. 已关闭后,相同内容的新幂等键目前回放成功。若用户要求重复关闭必须报错,先改 S2 再开 S3。若接受「相同内容回放、不同内容冲突」,S3 按这个语义写 API,不要再另做一套。
|
||||||
|
|
||||||
|
用户确认前保持 `proposedNextSlice=S3`、`allowedToCode` 不扩展到 S3。
|
||||||
|
|
||||||
|
## Final Recommendation
|
||||||
|
|
||||||
|
PASS_WITH_WARNINGS
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
# Boundary Review Result
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
S3 把报警列表、详情、依据、历史、关闭有效性和接手/进展/关闭留在本片。读取和命令先过既有三角色与 D38 四个权限点,再按合成快照里的具名 `subject` 收范围。没有 subject 时列表是空页,命令是 403/42000,没有放开成全租户。不存在和越范围的 ID 都是 404,信封码 40000,`reason=not_found`。冲突走现有 `ConflictError`(HTTP 409,信封码 40000)。幂等键超过 128 在 HTTP 入口拒绝。D37 的相同内容、新幂等键再关闭返回 200,`replayed=true`,不新开终态。
|
||||||
|
|
||||||
|
结论是 **PASS_WITH_WARNINGS**。没有阻断项,因此不是 FAIL。S3 是 `gateClass: boundary-sensitive`、`risk_score: 4`,并且要求 critic。`risk_score` 只加严,没有把本片降成可自动续行。即使本片通过,也不能自动开始 S4。
|
||||||
|
|
||||||
|
本审查没有改业务代码,也没有复跑 pytest。验证证据来自 `reviews/impl-s3.md` 的自述,加上对路由、只读服务、授权接入和 `tests/test_alarm_api.py` 的核对。该文件有 6 个测试函数,与「6 passed」的数量一致。终端记录里没有这次命令的输出。
|
||||||
|
|
||||||
|
## Changed Scope
|
||||||
|
|
||||||
|
按 S3 行为审阅的文件:
|
||||||
|
|
||||||
|
- `services/watchman/src/watchman/api/routes/alarms.py`(新)
|
||||||
|
- `services/watchman/src/watchman/services/alarm_reads.py`(新)
|
||||||
|
- `services/watchman/src/watchman/api/app.py`(只挂上 `alarms.router`)
|
||||||
|
- `services/watchman/src/watchman/auth/access.py`(四个 D38 常量及角色判断)
|
||||||
|
- `services/watchman/src/watchman/auth/principal.py`(会话主体加四个报警依赖;`_load_session` 的三处调用都已按三元组解开)
|
||||||
|
- `services/watchman/tests/test_alarm_api.py`(新)
|
||||||
|
- `docs/tasks/M06.md`
|
||||||
|
- `.task/2026-11-19/m06-alarm-center/state.json`
|
||||||
|
- `.task/2026-11-19/m06-alarm-center/reviews/impl-s3.md`
|
||||||
|
- `.task/active.json`(指针停在 S3 片审,`allowedToCode` 为 false)
|
||||||
|
|
||||||
|
未纳入本片、也不应在提交 S3 时打包的工作区改动:`.cursor/agents/marionettist-builder.md`、`docs/agent-workflow.md`、`docs/decisions.md`、`docs/progress.md`、M02 截图、`docs/预警平台开发规划_初期开发计划.xlsx`。`models/__init__.py` 的报警模型导出、`20261119_0014`、`20261119_0015`、事实服务和处理服务属于已审过的 S1/S2,本片没有改这些迁移。
|
||||||
|
|
||||||
|
没有前端、HTML 原型、`web/apps/console`、企微、Cron、次数窗口或意图表写入。
|
||||||
|
|
||||||
|
## Review Dimensions
|
||||||
|
|
||||||
|
- Boundary / Spec / Scope / Rules / Validation: 通过,带警告。D38 四个字面值、D25 的页码分页与服务端排序、D35 的具名 subject、D37 的同内容再关闭,都落在已确认口径里。路由没有手写失败 JSON。验证没有在本审查里复跑。
|
||||||
|
- Code Quality / Maintainability / Implementation / Test Quality: 通过,带警告。admin/operator/viewer、越范围、401、403 加权限点、409、幂等回放、超长幂等键和试算不进列表都有断言。等级筛选缺的是数据列,不是漏接一个已有字段。
|
||||||
|
|
||||||
|
`risk_score: 4` 没有被拿来放宽审查。本报告走两阶段,并且不把 `autonomous` 当成可以跳过片间停顿的理由。
|
||||||
|
|
||||||
|
### Stage 1:边界与合规
|
||||||
|
|
||||||
|
允许范围是报警路由、只读服务、测试,以及对 `auth/access.py`、`auth/principal.py`、`api/app.py` 的最小接入。实际业务代码符合这个范围。没有新角色名,没有新错误码,没有改四语言 `errors.json`,没有改 `0014`/`0015`。
|
||||||
|
|
||||||
|
权限点只有这四个,与 D38 和 `tests/test_alarm_api.py` 里的 `D38_NODES` 一致:
|
||||||
|
|
||||||
|
- `perm:data:emp:watchman.alarm.read`
|
||||||
|
- `perm:data:emp:watchman.alarm.take`
|
||||||
|
- `perm:data:emp:watchman.alarm.progress`
|
||||||
|
- `perm:data:emp:watchman.alarm.close`
|
||||||
|
|
||||||
|
公司规范篇目里原先没有报警节点。本片用的是用户已登记的 D38,不是按邻近 `watchman.*` 再编一组。`access.py` 里有明确注释,禁止在这里再加报警权限点。viewer 读得到范围内报警;接手、进展、关闭对 viewer 是 403,信封码 42000,并带回对应节点。未知角色 `watchman-alarm` 不能读。
|
||||||
|
|
||||||
|
列表在调用方传入时筛选 `module_key`、`scenario_key`、`scenario_name`、`status`、`mapped_input_id`、`occurred_from`、`occurred_to`。排序和 `page`/`page_size` 在 SQL 里执行。详情、occurrence、依据、历史、关闭有效性都先走同一套可见性判断。范围子句只认 `principals` 里 `kind=subject` 的值;测试快照里同时放了 `kind=role` 的 operator,范围外的 operator 仍然 404。空白 subject 的列表 `total=0`,接手是 42000。
|
||||||
|
|
||||||
|
命令要求 `x-idempotency-key`。空键和超过 128 字符的键是 400/40000,不截断后写入。同一键回放原事件。进展在同一键配不同说明时是 409,`reason=idempotency_payload_mismatch`。待处理直接关闭是 `illegal_transition`。他人接手是 `already_claimed`。非当前处理人追加进展是 `not_current_handler`。不同关闭内容是 `already_closed`。这些都复用 `ConflictError`,信封码仍是 40000,响应里没有 `permission_node`。成功响应走 `success_body`。`RequestValidationError` 仍由 `app.py` 里既有处理器收成 40000。`tenant_id` 不能从查询或命令体传入,多出来的字段会被拒绝。
|
||||||
|
|
||||||
|
关闭有效性先 `_visible`,再调用已有的 `close_validity`。响应字段是 `unexecuted_intents_should_invalidate`,正文里没有「已恢复」。试算异常不会出现在按 `mapped_input_id` 过滤的列表里。
|
||||||
|
|
||||||
|
D37 已按用户确认的口径接到 API:已关闭后,同一主体用新幂等键再提交完全相同的结果和说明,返回 200,`replayed=true`,历史仍是一条 `close`。不同结果走 `already_closed`。这和 S2 片审留下的选择一致,没有在 API 里并存两套契约。
|
||||||
|
|
||||||
|
任务状态停在 `coding_done_awaiting_review`,`currentSlice=S3`,`allowedToCode=false`,`nextCommand` 写明不要开始 S4。M06 任务卡没有把模块标成 DONE。
|
||||||
|
|
||||||
|
### Stage 2:实现质量
|
||||||
|
|
||||||
|
路由在调用 `claim_alarm`、`append_progress`、`close_alarm` 之前先做可见性检查,服务层的 `_authorize` 会再查一次 subject。回放发生在服务的 `_start` 里、`_authorize` 之前;HTTP 路径已经先 404 了越范围 ID,测试也把「同一幂等键打到不可见 ID」固定成 404,避免用冲突响应泄漏记录是否存在。可见的另一条报警若复用同一键,摘要里带了 `alarm_id`,会落到 409。这条可见复用没有单独的 HTTP 用例,服务摘要包含报警 ID,不构成第二套终态。
|
||||||
|
|
||||||
|
`_load_session` 从二元组改成 `(subject, login_name, roles)` 后,原有 `_load_session_roles` 和 `require_query_publisher` 都按新顺序取角色或登录名。会话依赖仍从服务端设置注入 `tenant_id`。
|
||||||
|
|
||||||
|
列表没有等级参数。`Alarm` 及相邻模型都没有 severity、priority、grade 或 level 列。本片允许范围也不包括新迁移。见下方「等级筛选」。
|
||||||
|
|
||||||
|
测试用 `alarm_db` 的 `settings.database_url`,夹具要求 PostgreSQL。授权断言打在真实会话和快照范围上,Casdoor 目录被换成「一旦刷新角色就失败」的替身,避免用旧角色缓存蒙混。这不等于用 Mock 代替租户隔离。
|
||||||
|
|
||||||
|
## Findings
|
||||||
|
|
||||||
|
无高、无中。下面两项不阻断本片。
|
||||||
|
|
||||||
|
### 低 1:需求里的等级筛选在本片没有对应列
|
||||||
|
|
||||||
|
- Location: `services/watchman/src/watchman/services/alarm_reads.py` 的 `search_alarms`;`services/watchman/src/watchman/models/alarm.py` 的 `Alarm` 列。
|
||||||
|
- Rule: 冻结稿写明有权用户可按模块、场景、对象、等级、时间和状态筛选。S3 计划要求的是 D25 的服务端筛选、排序和 `page/page_size`,并禁止为了权限或契约去改已落地的事实表。
|
||||||
|
- Risk: API 能筛模块、场景、对象(`mapped_input_id`)、状态和 `last_occurred_at` 时间窗,不能筛等级。模型里也没有可以 join 的等级列。若 S4 放一个等级下拉,它不会有后端行为。
|
||||||
|
- Required Fix: 不阻断。本片不建等级列是对的。S4/S5 不要用空筛选项假装已经实现。模块验收第 4 条里的「等级」仍未关闭;要做的话另开范围,并先有字段来源。
|
||||||
|
|
||||||
|
### 低 2:非当前处理人的 operator 关闭没有单独的 HTTP 断言
|
||||||
|
|
||||||
|
- Location: `services/watchman/tests/test_alarm_api.py` 的 `test_commands_conflict_idempotency_and_same_content_replay`、`test_admin_can_close_and_cannot_read_outside_scope`。
|
||||||
|
- Rule: operator 可在范围内接手和追加进展;关闭仅当前处理人或 admin。
|
||||||
|
- Risk: 进展的 `not_current_handler`、admin 关闭并保持原处理人,都有 HTTP 断言。另一名 operator 直接 `POST /close` 没有单独用例。路由把同一 `HandlingActor` 交给 `close_alarm`,服务在处理人不是自己且角色不是 admin 时返回 `not_current_handler`。漏测的是 API 接线,不是另一套关闭规则。
|
||||||
|
- Required Fix: 不阻断。若补测试,加一条即可,不必改状态机。
|
||||||
|
|
||||||
|
## 等级筛选
|
||||||
|
|
||||||
|
可以接受。报警行没有等级字段,仓库模型里也没有现成的等级列。S3 若加筛选参数或新列,就会变成没有数据来源的契约,或滑进新迁移。时间筛选使用 `last_occurred_at`,和「最近一次发生」一致,不需要另造等级才能完成本片的分页和排序。
|
||||||
|
|
||||||
|
## 残留风险
|
||||||
|
|
||||||
|
- `alarm_apply_transition` 仍可由 `watchman_app` 执行。S3 没有把它当成授权边界,也没有改旧迁移。这是 S2 已接受的残留。
|
||||||
|
- 处理服务对直接调用仍把超长幂等键截到 128。HTTP 入口在调用前拒绝,并有用例。
|
||||||
|
- `close_validity` 本身只按租户过滤。路由先确认可见再调用。
|
||||||
|
- 范围匹配仍是合成快照里的具名 subject。角色条目不授权。这是 S1 的实现假设,不是新的授权模型。
|
||||||
|
- `context-pack.md` 仍停在分析阶段。`docs/progress.md` 不在本片声明改动里,工作区里那份修改也不应算作 S3。门禁后由主 Agent 更新进度,不要把模块标 DONE。
|
||||||
|
- 本审查没有复跑 `uv run pytest tests/test_alarm_api.py` 或全量 `pytest`。实现记录写的是 6 passed 与 523 passed。用例内容与这个数量、以及 admin/operator/viewer、越权、409、幂等、D37 的声称一致,但命令输出不是本审查重新执行的结果。
|
||||||
|
|
||||||
|
## 能否进入 S4
|
||||||
|
|
||||||
|
不能自动进入。S3 的 `gateClass` 是 `boundary-sensitive`,`risk_score` 是 4,并且要求 critic。`gatePolicy.selected=autonomous` 只允许续行已批准的 `simple` 或 `standard` 且 `risk_score <= 3`、无 critic、无其他停顿的下一片。本片两条都不满足。
|
||||||
|
|
||||||
|
用户确认本片审查结论之后,可以开 S4。S4 仍是 HTML 原型,不是 Vue。确认前保持 `proposedNextSlice=S4`、`allowedToCode` 不扩展到 S4。低项不要求先改代码。等级筛选不要塞进 S4 的原型里当成已实现能力。
|
||||||
|
|
||||||
|
## Recommendation
|
||||||
|
|
||||||
|
PASS_WITH_WARNINGS
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
# Boundary Review Result
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
S5 只做了控制台报警列表、详情和接手/进展/关闭。按钮是否出现由角色、主体和状态决定,命令仍交给已有 API。没有改后端语义,没有在前端伪造授权,没有通知、升级或 M07 页面。
|
||||||
|
|
||||||
|
结论是 **PASS_WITH_WARNINGS**。没有高、中问题,因此不是 FAIL。S5 本身是 `gateClass: standard`、`risk_score: 3`,不要求本片 critic。这不把下一片降级。S6 仍是 `boundary-sensitive`、`risk_score: 4`,并且要求 critic。即使用户确认本片,也不能自动进入 S6。模块不是 DONE。
|
||||||
|
|
||||||
|
本审查没有改业务代码,也没有复跑 unit、typecheck、build 或 Playwright。验证证据来自 `reviews/impl-s5.md`、`e2e/alarms.spec.ts` 的用例结构,以及 `docs/evidence/M06/ui/` 里已有截图。
|
||||||
|
|
||||||
|
## Changed Scope
|
||||||
|
|
||||||
|
按 S5 审阅的文件:
|
||||||
|
|
||||||
|
- `web/apps/console/src/alarms/`(列表、详情、客户端、可见性、错误文案、筛选)
|
||||||
|
- `web/apps/console/src/router.ts`(两条报警路由)
|
||||||
|
- `web/apps/console/src/AppShell.vue`(侧栏和面包屑)
|
||||||
|
- `web/apps/console/locales/{zh-CN,zh-TW,en,th}/common.json`(`nav.alarms` 与 `alarm` 段)
|
||||||
|
- `web/apps/console/e2e/alarms.spec.ts`
|
||||||
|
- `docs/evidence/M06/ui/`(13 张截图)
|
||||||
|
- `docs/tasks/M06.md`、`docs/progress.md`
|
||||||
|
- `.task/2026-11-19/m06-alarm-center/reviews/impl-s5.md`
|
||||||
|
- `.task/2026-11-19/m06-alarm-center/state.json`
|
||||||
|
- `.task/active.json`(指针停在 S5 片审,`allowedToCode` 为 false)
|
||||||
|
|
||||||
|
路由和壳层的 diff 只有报警入口。四份语言文件各增加约 167 行,没有改其它模块的文案。
|
||||||
|
|
||||||
|
工作区里早于本片的后端、迁移、`docs/decisions.md`、M02 截图和其它文档没有纳入本片,也没有在这次审查里重审。`docs/evidence/M06/summary.md` 仍不存在,留给 S6 收口,不作为本片阻断。
|
||||||
|
|
||||||
|
## Review Dimensions
|
||||||
|
|
||||||
|
- Boundary / Spec / Scope / Rules / Validation: 通过,带警告。D39 六条、D22 详情页脚、D25 的查询后筛选和服务端排序分页都落在页面上。验证没有在本审查里复跑。Playwright 打的是页面 Mock。
|
||||||
|
- Code Quality / Maintainability / Implementation / Test Quality: 通过,带警告。可见性、空状态、幂等键复用、不展示服务端 `message` 都有单测。e2e 有 11 个用例,和声称的 `11 passed` 条数一致。
|
||||||
|
|
||||||
|
`risk_score: 3` 没有被拿来跳过 D39 和授权边界。S6 的 `risk_score: 4` 也没有被本片的 `standard` 抵消。
|
||||||
|
|
||||||
|
### Stage 1:边界与合规
|
||||||
|
|
||||||
|
允许范围是报警页、最小路由和导航、四语言、unit/e2e,以及任务状态文档。实际改动符合这个范围。没有新权限点,没有改 `access.py`,没有改报警路由或处理服务。
|
||||||
|
|
||||||
|
D39:
|
||||||
|
|
||||||
|
1. 无等级。筛选和列都没有等级。单测断言查询串不含 `severity` / `level`。e2e 断言没有「等级」列和筛选项。
|
||||||
|
2. 只展示接口已有字段。详情没有计划时间、规则原文、实际值、比较值。观测列是观测时间、接收时间、周期、事件。关闭后依据的说明是「报警保持关闭」。对象筛选的缺口见下方低 1,不是多造了一个等级或计划时间。
|
||||||
|
3. viewer 隐藏接手、进展、关闭。`watchman-viewer` 以及非 admin/operator 得到全部隐藏。e2e 和 `U06-viewer-1440x900.png` 的页脚只有「返回列表」。
|
||||||
|
4. 已关闭页脚只有返回。模板在 `status !== 'closed'` 时才渲染命令,可见性函数对 `closed` 也返回全隐。e2e 和关闭截图一致。
|
||||||
|
5. 三种空状态分开:「还没有报警」「没有符合条件的报警」「没有处理范围,所以看不到报警」。没有主体时,即使 Mock 返回了行,也不画表。
|
||||||
|
6. admin 可以关闭他人正在处理的报警。处理中且处理人不是自己时,只有关闭,没有接手,也没有追加进展。关闭请求体只有结果、说明和可选证据引用,没有 `current_handler`。e2e 关闭后处理人仍是 `subj-lin`。待处理不能直接关闭,和「不做从待处理直接关闭」一致。
|
||||||
|
|
||||||
|
不显示「已恢复」。四语言 `alarm` 文案被单测禁掉「已恢复」「已恢復」「recovered」。状态是待处理、处理中、已关闭。关闭结果只有已处理、误报。
|
||||||
|
|
||||||
|
不直出服务端 `message`。`describeAlarmError` 只用 `details.reason` 的固定文案、已知信封码,或本次操作对应的 D38 节点。`U06-load-failed-1440x900.png` 显示的是「服务错误 (50000)」,不是 Mock 放进 `message` 的那串秘密。409 截图是「这条报警已经有处理人,不能再接手」和「页面已按最新状态刷新」。
|
||||||
|
|
||||||
|
D22:详情正文在 `alarm-scroll` 里滚动,页脚是滚动区外面的居中条。`U06-detail-1280x800.png` 滚到底后,页脚仍是「返回列表」。列表的查询/重置在表格上方,行内只有「打开」。分页在列表底栏,不是详情页脚按钮。
|
||||||
|
|
||||||
|
D25:输入不立即请求。e2e 在点「查询」之前列表请求数保持 1。排序列是 `sortable="custom"`,对象列不排序。分页使用现有的 10/20/50。场景名交给已有的 `scenario_name` 包含匹配,本片没有在浏览器里再筛一遍。
|
||||||
|
|
||||||
|
防重复和 409:同一份进展或关闭内容复用同一个 `x-idempotency-key`。请求进行中按钮进入 loading,对话框不能点遮罩关掉。说明或关闭结果没过校验时对话框不关。409 用固定原因文案,关掉对话框并重新拉详情。幂等键跨报警残留见低 2。
|
||||||
|
|
||||||
|
授权:页面没有写角色头,也没有在客户端把 viewer 改成 admin。隐藏按钮不是放行。权限点字面值与 D38 相同,只用于 403 文案。共享 `requestJson` 仍不把信封上的 `permission_node` 放进 `BusinessError`;页面展示的是这次按钮对应的节点。这是已知限制,不是新的伪造节点。
|
||||||
|
|
||||||
|
S6/M07:报警页没有通知、升级、企微或次数窗口。任务卡和 `state.json` 仍写明不得开始 S6,不得标 DONE。`allowedToCode` 为 false。
|
||||||
|
|
||||||
|
### Stage 2:实现质量
|
||||||
|
|
||||||
|
Element Plus 是具名导入,没有在 `main.ts` 全量注册。列表和详情沿用控制台的表格、分页和壳层高度,详情页脚因此能留在滚动区外。
|
||||||
|
|
||||||
|
命令可见性与 D33 一致:范围内 operator/admin 可接手待处理;处理中只有当前处理人能写进展;关闭是当前处理人或 admin;已关闭不再给命令。主体为空、只含空白或含换行时不给命令,这和读取接口把这种会话当成没有主体是同一口径。
|
||||||
|
|
||||||
|
错误文案覆盖了接手冲突、非当前处理人、非法状态、已关闭、幂等键不匹配和缺键。未知 `reason` 不会把原文贴出来。
|
||||||
|
|
||||||
|
单测覆盖可见性、三种空状态、筛选参数、幂等键复用和错误文案。e2e 覆盖查询后筛选、排序、接手到关闭、校验不关对话框、viewer、admin 关闭他人、409、无主体、无报警、加载失败,以及 1440×900、1280×800、1920×1080 的分页和页脚。截图是这些用例写出来的,内容与上述状态一致。`U06-closed-1440x900.png` 是同一条用例里先保存进展再关闭之后拍的,画面上还留着「进展已保存」。状态和页脚已经是已关闭、只返回。
|
||||||
|
|
||||||
|
## Findings
|
||||||
|
|
||||||
|
无高、无中。下面两项不阻断本片。
|
||||||
|
|
||||||
|
### 低 1:对象筛选要的是映射编号,列表上看到的是身份键
|
||||||
|
|
||||||
|
- Location: `web/apps/console/src/alarms/filters.ts` 的 `alarmFilterIssue`;`AlarmList.vue` 的对象列和「对象编号」输入。
|
||||||
|
- Rule: D39 要求只使用接口已有字段。列表查询参数里的对象是 `mapped_input_id`。列表和详情展示的对象是 `identity_key`。
|
||||||
|
- Risk: 列上的值类似 `furnace-01`。同一列名下的筛选框不接受这个值,本地提示「对象编号需要是完整的编号」,而且页面上不显示那个 UUID。用户按看到的对象去查,请求发不出去。这不是等级或计划时间,接口也没有按身份键筛选的参数。
|
||||||
|
- Required Fix: 不阻断。不要为了好填而新增查询参数或改后端。若后续改文案,应说明要填的是映射对象编号,不是表上的身份键。
|
||||||
|
|
||||||
|
### 低 2:切换报警后,未成功的幂等键还留着
|
||||||
|
|
||||||
|
- Location: `web/apps/console/src/alarms/AlarmDetail.vue` 的 `claimHold`、`progressHold`、`closeHold`。`load()` 和 `route.params.id` 的 watch 都没有清掉它们。
|
||||||
|
- Rule: 同一份内容重试应沿用同一个键。S3 的幂等记录按租户加键查找,摘要里包含报警 ID。另一条可见报警复用同一键会得到 `idempotency_payload_mismatch`,不会改写那一条。
|
||||||
|
- Risk: 请求已经失败、键还留在当前详情实例里时,用户点「关联的上一条报警」再提交同一段说明,会沿用上一笔键。服务端返回 409,页面显示固定的「同一个提交编号被用在了不同的内容上」。数据不会被写到另一条报警上。改一个字会换新键。离开详情页后组件销毁,键也消失。
|
||||||
|
- Required Fix: 不阻断。若要修,在报警 ID 变化时清掉三份 hold 即可。
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
声称与用例对得上,但本审查没有复跑:
|
||||||
|
|
||||||
|
| 声称 | 审查里看到的内容 |
|
||||||
|
| --- | --- |
|
||||||
|
| `pnpm test:unit`:126 passed | 未复跑。报警单测覆盖可见性、空状态、筛选、客户端和四语言。总条数没有在本审查里重新点数。 |
|
||||||
|
| `pnpm typecheck`、`pnpm build` 通过 | 未复跑。`web/apps/console/tsconfig.tsbuildinfo` 是 typecheck 留下的未跟踪文件,不是功能改动。 |
|
||||||
|
| `pnpm test:e2e -- e2e/alarms.spec.ts`:11 passed | 未复跑。文件里是 8 个具名用例加 3 个视口,共 11 个。 |
|
||||||
|
| 截图在 `docs/evidence/M06/ui/` | 13 张都在。抽看了列表、三种空状态、加载失败、viewer、409、关闭,以及 1280 详情。 |
|
||||||
|
|
||||||
|
Mock 局限:Playwright 拦截的是浏览器里的 `/alarms` 和 `/auth/me`。它能证明页面文案、按钮和请求参数,不能证明真实权限、快照范围、并发接手、数据库幂等或 RLS。加载失败图证明的是页面不渲染 Mock 的 `message`,不是真实 500 的线上文案。这些留给 S6,并且 S6 不能只用这套 Mock 宣布模块通过。
|
||||||
|
|
||||||
|
## S6
|
||||||
|
|
||||||
|
可以在用户明确确认后开始 S6。不能自动续行。
|
||||||
|
|
||||||
|
S6 的冻结门禁是 `gateClass: boundary-sensitive`、`risk_score: 4`、`criticRequired: true`。选定的 `autonomous` 到这里必须停。本片 `standard` / `risk_score: 3` 只说明 S5 自己不是高风险片,不能把 S6 变成已批准的下一小步。
|
||||||
|
|
||||||
|
开始 S6 时仍要做模块级审查和正式验证,包括隔离 PostgreSQL 上的后端、迁移和并发。本片通过也不等于 `DONE_LOCAL`。
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# M06 S6 Formal Validation
|
||||||
|
|
||||||
|
主 Agent 于 2026-11-19 在当前配置的 PostgreSQL/本机 console 上重跑并落盘日志。
|
||||||
|
产品代码未改。不宣称 DONE_LOCAL。
|
||||||
|
|
||||||
|
## Environment Bounds
|
||||||
|
|
||||||
|
- DB:当前 `settings.database_url` 指向的 PostgreSQL(非新建空库)。
|
||||||
|
- e2e:Playwright Mock 页面路径;**不是**真实后端联调。
|
||||||
|
- 无真实企微/MES;合成发布快照。
|
||||||
|
- 截图沿用 S5 已有 `docs/evidence/M06/ui/`(本轮 e2e 通过;未强制重拍每一张)。
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
日志目录:`.task/2026-11-19/m06-alarm-center/reviews/validation-logs/`
|
||||||
|
|
||||||
|
| # | cwd | 命令 | exit | 结果 | 日志 |
|
||||||
|
|---|-----|------|------|------|------|
|
||||||
|
| 1 | `services/watchman` | `uv run alembic upgrade head` | 0 | PASS | `01-alembic-upgrade-head.log` |
|
||||||
|
| 2a | 同上 | `uv run alembic downgrade 20261119_0014` | 0 | PASS(0015→0014) | `02-alembic-downgrade-0014.log` |
|
||||||
|
| 2b | 同上 | `uv run alembic upgrade head` | 0 | PASS(0014→0015) | `03-alembic-upgrade-head-after-downgrade.log` |
|
||||||
|
| 2c | 同上 | `uv run alembic current` | 0 | `20261119_0015 (head)` | `04-alembic-current.log` |
|
||||||
|
| 3 | 同上 | `uv run pytest --tb=line -q` | 0 | **523 passed**, 1 warning, **195.46s** | `05-pytest-full.log` |
|
||||||
|
| 4 | `web/apps/console` | `pnpm test:unit` | 0 | **126 passed** (20 files) | `06-pnpm-test-unit.log` |
|
||||||
|
| 5 | 同上 | `pnpm typecheck` | 0 | PASS | `07-pnpm-typecheck.log` |
|
||||||
|
| 6 | 同上 | `pnpm build` | 0 | PASS(chunk>500kB 提示) | `08-pnpm-build.log` |
|
||||||
|
| 7 | 同上 | `pnpm test:e2e -- e2e/alarms.spec.ts` | 0 | **11 passed (15.7s)** | `09-pnpm-e2e-alarms.log` |
|
||||||
|
|
||||||
|
## Screenshots
|
||||||
|
|
||||||
|
`docs/evidence/M06/ui/` 现存 13 张 PNG:list/detail 三视口、empty、no-match、no-scope、load-failed、viewer、conflict、closed。
|
||||||
|
|
||||||
|
## Docs Sync
|
||||||
|
|
||||||
|
- `docs/testing-plan.md` V033/V042 已改为 D34/D32 口径(主 Agent 在 S6 中更新)。
|
||||||
|
|
||||||
|
## Verdict
|
||||||
|
|
||||||
|
自动化命令 **9/9 PASS**(含 alembic current)。
|
||||||
|
ALL PASS = **是**。
|
||||||
|
BOUNDARIES:Mock e2e、合成快照、无真实外发——本地验收边界,不是阶段联调通过。
|
||||||
|
|
||||||
|
建议:pre-done critic 复核本文件与日志后,请用户最终批准 `DONE_LOCAL`。
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
{
|
||||||
|
"taskId": "2026-11-19/m06-alarm-center",
|
||||||
|
"module": "M06",
|
||||||
|
"title": "报警中心与人工处理模块",
|
||||||
|
"type": "feature",
|
||||||
|
"tier": "L",
|
||||||
|
"phase": "done",
|
||||||
|
"status": "done_local",
|
||||||
|
"allowedToCode": false,
|
||||||
|
"currentSlice": "S6",
|
||||||
|
"proposedNextSlice": null,
|
||||||
|
"lastGate": "user-closed-done-local",
|
||||||
|
"gatePolicy": {
|
||||||
|
"recommended": "strict",
|
||||||
|
"selected": "autonomous",
|
||||||
|
"effective": "autonomous",
|
||||||
|
"reason": "用户指定 autonomous;最终批准已由用户确认",
|
||||||
|
"finalApprovalRequired": true,
|
||||||
|
"allowTaskOverride": true
|
||||||
|
},
|
||||||
|
"confirmedDecisions": ["D32", "D33", "D34", "D35", "D36", "D37", "D38", "D39", "D40"],
|
||||||
|
"deferredNotes": [
|
||||||
|
"orchestrable-handling-workflow-post-mvp",
|
||||||
|
"m08-replace-synthetic-snapshot"
|
||||||
|
],
|
||||||
|
"slices": [
|
||||||
|
{"id": "S1", "status": "review_pass_with_warnings", "gateClass": "high-risk", "risk_score": 5},
|
||||||
|
{"id": "S2", "status": "review_pass_with_warnings", "gateClass": "high-risk", "risk_score": 5},
|
||||||
|
{"id": "S3", "status": "review_pass_with_warnings", "gateClass": "boundary-sensitive", "risk_score": 4},
|
||||||
|
{"id": "S4", "status": "user_confirmed", "gateClass": "simple", "risk_score": 2},
|
||||||
|
{"id": "S5", "status": "review_pass_with_warnings", "gateClass": "standard", "risk_score": 3},
|
||||||
|
{"id": "S6", "status": "done_local", "gateClass": "boundary-sensitive", "risk_score": 4}
|
||||||
|
],
|
||||||
|
"gates": {
|
||||||
|
"requirementFrozen": true,
|
||||||
|
"planApproved": true,
|
||||||
|
"contextPackReady": true,
|
||||||
|
"criticPassed": true,
|
||||||
|
"moduleReviewPassed": true,
|
||||||
|
"moduleReviewResult": "PASS_WITH_WARNINGS",
|
||||||
|
"implementationDone": true,
|
||||||
|
"reviewPassed": true,
|
||||||
|
"validationPassed": true,
|
||||||
|
"validationEvidence": ".task/2026-11-19/m06-alarm-center/reviews/validation-s6.md",
|
||||||
|
"finalApprovalPassed": true
|
||||||
|
},
|
||||||
|
"blockers": [],
|
||||||
|
"updatedAt": "2026-11-19T07:25:00Z"
|
||||||
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
{
|
{
|
||||||
"taskId": "2026-11-18/m05-mapping-rules",
|
"taskId": "2026-11-19/m06-alarm-center",
|
||||||
"type": "feature",
|
"type": "feature",
|
||||||
"phase": "done",
|
"phase": "done",
|
||||||
"allowedToCode": false,
|
"allowedToCode": false,
|
||||||
"currentSlice": "S8",
|
"currentSlice": "S6",
|
||||||
"lastGate": "user-closed-done-local",
|
"lastGate": "user-closed-done-local",
|
||||||
"nextCommand": "none",
|
"nextCommand": "none",
|
||||||
"gatePolicy": {
|
"gatePolicy": {
|
||||||
@@ -13,5 +13,5 @@
|
|||||||
"finalApprovalRequired": true,
|
"finalApprovalRequired": true,
|
||||||
"allowTaskOverride": true
|
"allowTaskOverride": true
|
||||||
},
|
},
|
||||||
"updatedAt": "2026-11-19T02:05:00Z"
|
"updatedAt": "2026-11-19T07:25:00Z"
|
||||||
}
|
}
|
||||||
@@ -20,7 +20,7 @@
|
|||||||
|
|
||||||
| 角色 | 选择标准 | 当前真实模型 ID |
|
| 角色 | 选择标准 | 当前真实模型 ID |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 主 Agent/编排 | 用户指定;`marionettist-builder` | `gpt-5.6-sol` |
|
| 主 Agent/编排 | 用户指定;`marionettist-builder` | `grok-4.7` |
|
||||||
| 需求冻结/任务切片 | 用户指定 GPT Sol;`think` profile、`marionettist-planner` | `gpt-5.6-sol` |
|
| 需求冻结/任务切片 | 用户指定 GPT Sol;`think` profile、`marionettist-planner` | `gpt-5.6-sol` |
|
||||||
| 实现 | 用户指定;`marionettist-coder`、`build` profile | `grok-4.7` |
|
| 实现 | 用户指定;`marionettist-coder`、`build` profile | `grok-4.7` |
|
||||||
| Reviewer | 用户指定;片审/diff 审查 | `grok-4.7` |
|
| Reviewer | 用户指定;片审/diff 审查 | `grok-4.7` |
|
||||||
|
|||||||
@@ -36,20 +36,29 @@
|
|||||||
| D28 | M05 映射与判断规则共用一个版本,不给规则单独编号。历史版本不可改;可切换当前版本,字段和条件一起换;可基于某一历史版本编辑,保存时另存为新版本并设为当前。列表不单设「判断规则」入口,规则在映射详情里一起编辑 | 2026-11-18 用户在原型上明确:规则与映射同版,并去掉列表上的判断规则按钮 |
|
| D28 | M05 映射与判断规则共用一个版本,不给规则单独编号。历史版本不可改;可切换当前版本,字段和条件一起换;可基于某一历史版本编辑,保存时另存为新版本并设为当前。列表不单设「判断规则」入口,规则在映射详情里一起编辑 | 2026-11-18 用户在原型上明确:规则与映射同版,并去掉列表上的判断规则按钮 |
|
||||||
| D29 | review/`marionettist-reviewer` 与 critic/`marionettist-critic` 均使用 `grok-4.7`(agent frontmatter 与 review profile 已写入) | 2026-11-19 用户先要求 Cursor 模型,后改为双方均用 grok-4.7 |
|
| D29 | review/`marionettist-reviewer` 与 critic/`marionettist-critic` 均使用 `grok-4.7`(agent frontmatter 与 review profile 已写入) | 2026-11-19 用户先要求 Cursor 模型,后改为双方均用 grok-4.7 |
|
||||||
| D30 | 需求冻结与任务切片设计使用 GPT Sol:`think` profile 与 `marionettist-planner` 均为 `gpt-5.6-sol`(覆盖 `requirement-freezer`/`implementation-slicer` 的 reasoning 映射) | 2026-11-19 用户要求 |
|
| D30 | 需求冻结与任务切片设计使用 GPT Sol:`think` profile 与 `marionettist-planner` 均为 `gpt-5.6-sol`(覆盖 `requirement-freezer`/`implementation-slicer` 的 reasoning 映射) | 2026-11-19 用户要求 |
|
||||||
| D31 | `marionettist-builder` 使用 `gpt-5.6-sol`;`marionettist-coder` 与 `build` profile 使用 `grok-4.7` | 2026-11-19 用户要求 |
|
| D31 | `marionettist-builder`、`marionettist-coder` 与 `build` profile 均使用 `grok-4.7` | 2026-11-19 用户要求;同日 builder 由 Sol 改为 Grok |
|
||||||
|
| D32 | M06 关闭语义(原 O04):关闭使绑定该报警且尚未执行的通知/升级意图失效;已受理消息不可撤回;次数窗口不因人工关闭清零(窗口/阈值细节仍归 M09) | 2026-11-19 用户确认「按建议」 |
|
||||||
|
| D33 | M06 接手/关闭 MVP(原 O05):范围内 operator/admin 可接手;当前处理人或 admin 可关闭;关闭结果仅「已处理/误报」,说明必填;不做转派/重开/从待处理直接关闭。**后置(已登记、本模块不实现)**:人工处理要做成可编排工作流;MVP 先固定三状态正向流转 | 2026-11-19 用户确认建议,并要求先记录可编排工作流、不发散 |
|
||||||
|
| D34 | M06 同周期更正(原 O06):同周期值更正只追加修订与依据,不改写原始 FAIL,不自动新建报警,不自动重发;仅新独立事件/新统计周期可新建并关联历史 | 2026-11-19 用户确认「按建议」 |
|
||||||
|
| D35 | M06 范围/合成快照/正式异常:处理范围由合成发布快照显式声明,禁止默认 operator 全租户;快照最小字段含 `snapshot_id`、`version_no`、`module_key`、`scenario_key/name`、处理范围;occurrence 引用 M05 输入修订+映射/规则版本+合成快照,试算不得产生正式报警。**M08 收尾**:正式场景发布就绪后,新路径改挂真实发布版本;历史报警保留创建时快照/映射,不回写伪造恢复;停止用合成快照冒充生产发布 | 2026-11-19 用户确认建议,并要求备注场景收尾 |
|
||||||
|
| D36 | 已关闭报警上再次出现同一合并键正式异常:不新开报警、不重开旧报警;仍追加可追溯记录(依据/审计日志),便于追查「关了之后仍持续异常」 | 2026-11-19 用户在 S1 片门禁选择 B,并要求日志记录;批准 S2 |
|
||||||
|
| D37 | S2 片审中项收口:MVP 接受应用库角色仍可调用合法状态函数,正式入口靠 API/服务校验拦住;已关闭后相同内容用新幂等键再关闭视为回放成功,不强制报「重复关闭」 | 2026-11-19 用户确认 1A、2A |
|
||||||
|
| D38 | M06 报警权限点(本仓库登记,沿用既有 `watchman.*` 模式):`perm:data:emp:watchman.alarm.read`、`.take`、`.progress`、`.close` | 2026-11-19 用户批准并开工 S3 |
|
||||||
|
| D39 | M06 S4 原型确认并批准 S5:不做等级筛选/列;S5 只展示接口已有字段;viewer 隐藏接手/进展/关闭按钮;已关闭页脚仅返回;保留三种空状态;admin 可关闭他人报警但不可抢走处理人或代写进展 | 2026-11-19 用户确认 1–6 并批准 S5 |
|
||||||
|
| D40 | M06 认领动作界面文案:按钮与历史动作由「接手」改为「处理」;成功提示用「已开始处理」,避免与关闭结果「已处理」混淆;字段「接手时间」改为「开始处理时间」。API/权限点仍为 `claim`/`watchman.alarm.take`,语义不变 | 2026-11-19 用户要求改得更正式 |
|
||||||
|
|
||||||
## 冻结前/相关模块实现前必须确认
|
## 冻结前/相关模块实现前必须确认
|
||||||
|
|
||||||
下表保留旧细项编号用于历史定位;当前阻塞单位按映射为:O01/O07→M08,O02/O03→M09,O04→M06/M09,O05→M06,O06→M05/M06,O08→M01及所有委派,O09→M01/M07/M08/M13,O10→M02。O11 已由 D20 确认。旧依赖不是当前大任务流程。
|
下表保留旧细项编号用于历史定位;当前阻塞单位按映射为:O01/O07→M08,O02/O03→M09,O04/O05/O06 已由 D32~D35 关闭(M09 仍管次数窗口细节),O08→M01及所有委派,O09→M01/M07/M08/M13,O10→M02。O11 已由 D20 确认。旧依赖不是当前大任务流程。
|
||||||
|
|
||||||
| ID | 状态 | 问题 | 建议供选择,非默认已批准 | 阻塞 |
|
| ID | 状态 | 问题 | 建议供选择,非默认已批准 | 阻塞 |
|
||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| O01 | OPEN | Cron 方言、日期和星期组合语义、场景时区 | 建议 5 字段 Unix 分钟级,不支持秒/年/Quartz 特殊符号;DOM/DOW 按标准 Unix OR;显式 IANA 时区,项目可选 Asia/Shanghai。后端唯一解析,所有时区策略测试 | P-004、A-030~A-034 |
|
| O01 | OPEN | Cron 方言、日期和星期组合语义、场景时区 | 建议 5 字段 Unix 分钟级,不支持秒/年/Quartz 特殊符号;DOM/DOW 按标准 Unix OR;显式 IANA 时区,项目可选 Asia/Shanghai。后端唯一解析,所有时区策略测试 | P-004、A-030~A-034 |
|
||||||
| O02 | OPEN | 次数按什么分组、什么窗口、何时重置? | 只计去重后的独立 FAIL 输入。建议阶段 A 先固定日/周/月等窗口;窗口内按场景+对象+异常类别累计,跨周期或规则配置版本如何继承需确认;不把 Cron 每次执行直接算新错误 | P-005、A-048~A-054 |
|
| O02 | OPEN | 次数按什么分组、什么窗口、何时重置? | 只计去重后的独立 FAIL 输入。建议阶段 A 先固定日/周/月等窗口;窗口内按场景+对象+异常类别累计,跨周期或规则配置版本如何继承需确认;不把 Cron 每次执行直接算新错误 | P-005、A-048~A-054 |
|
||||||
| O03 | OPEN | 每一级阈值是累加接收人还是替换?一次越过多级如何发? | 用户举例甲→甲乙→甲乙丙,建议显式配置每级最终目标;默认执行最高新命中级或逐级分别执行需用户选择;达到阈值触发,每级每窗口一次 | P-005、A-050~A-054 |
|
| O03 | OPEN | 每一级阈值是累加接收人还是替换?一次越过多级如何发? | 用户举例甲→甲乙→甲乙丙,建议显式配置每级最终目标;默认执行最高新命中级或逐级分别执行需用户选择;达到阈值触发,每级每窗口一次 | P-005、A-050~A-054 |
|
||||||
| O04 | OPEN | 已关闭后新事件继续计入窗口吗?关闭时尚未发送的通知怎么办? | 建议关闭终结该报警未执行意图,新事件可新建但窗口次数不被人工关闭清零;任务必须绑定新报警身份;已受理消息不能撤回 | P-006、A-043、A-049、A-051 |
|
| O04 | CONFIRMED | 见 D32。关闭终结该报警未执行意图;已受理不可撤回;窗口不因关闭清零 | 用户确认建议 | P-006、A-043、A-049、A-051 |
|
||||||
| O05 | OPEN | 接手/关闭权限及关闭结果枚举 | 建议范围内处理者可接手,当前处理人或管理者可关闭,结果“已处理/误报”,说明必填;不做转派/重开 | P-006、A-041~A-043 |
|
| O05 | CONFIRMED | 见 D33。MVP 固定接手/关闭权限与结果枚举;可编排工作流后置 | 用户确认建议并登记后置 | P-006、A-041~A-043 |
|
||||||
| O06 | OPEN | 同周期值更正是否更新原报警、是否允许新报警? | 同一输入身份重读不重报已确认;“版本变更”不能随意当新业务事件。建议保留修订记录,不自动重发,实际规则需批准 | P-006、A-023、A-039 |
|
| O06 | CONFIRMED | 见 D34。同周期更正只追加修订,不自动新报警/重发 | 用户确认建议 | P-006、A-023、A-039 |
|
||||||
| O07 | OPEN | 停机漏跑、跨周期任务重叠、启停及改 Cron 后的旧任务 | 建议每场景不并发推进进度,逾期运行有界跳过/显式补跑且不自动补发历史消息;用户需确认具体业务行为 | P-004、A-033~A-036 |
|
| O07 | OPEN | 停机漏跑、跨周期任务重叠、启停及改 Cron 后的旧任务 | 建议每场景不并发推进进度,逾期运行有界跳过/显式补跑且不自动补发历史消息;用户需确认具体业务行为 | P-004、A-033~A-036 |
|
||||||
| O08 | OPEN | Cursor/Grok 等实际服务商能处理哪些项目资料?能否跨系列子 Agent? | 先确认交接文档、未来源码、合成数据和截图授权;默认不读取原会议或 MES 原始资料,不发真实凭证。用可用模型目录填写角色映射,不能默认已获所有服务商授权 | 所有实际模型委派 |
|
| O08 | OPEN | Cursor/Grok 等实际服务商能处理哪些项目资料?能否跨系列子 Agent? | 先确认交接文档、未来源码、合成数据和截图授权;默认不读取原会议或 MES 原始资料,不发真实凭证。用可用模型目录填写角色映射,不能默认已获所有服务商授权 | 所有实际模型委派 |
|
||||||
| O09 | TECH_PENDING | Python/Node/依赖版本,Cron 解析器和编辑组件,AI SDK,企微库 | M01 已锁定:Python 3.12.16(uv)、FastAPI 0.163、SQLAlchemy 2.0.57、Alembic 1.20、Celery 5.7、Pydantic 2.14、Vue 3.5 / Element Plus 2.x / Vite 7 / pnpm 12。其余(Cron/AI/企微)仍待后续模块 | P-002、P-004、A-056、B-001 |
|
| O09 | TECH_PENDING | Python/Node/依赖版本,Cron 解析器和编辑组件,AI SDK,企微库 | M01 已锁定:Python 3.12.16(uv)、FastAPI 0.163、SQLAlchemy 2.0.57、Alembic 1.20、Celery 5.7、Pydantic 2.14、Vue 3.5 / Element Plus 2.x / Vite 7 / pnpm 12。其余(Cron/AI/企微)仍待后续模块 | P-002、P-004、A-056、B-001 |
|
||||||
|
|||||||
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 52 KiB |
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 45 KiB |
@@ -0,0 +1,36 @@
|
|||||||
|
# M06 证据摘要
|
||||||
|
|
||||||
|
## 范围
|
||||||
|
|
||||||
|
报警中心与人工处理(A-037~A-047;D32~D39)。合成快照;无真实企微/MES。
|
||||||
|
|
||||||
|
## 自动化(S6 重跑,可回查日志)
|
||||||
|
|
||||||
|
路径:`.task/2026-11-19/m06-alarm-center/reviews/validation-logs/`
|
||||||
|
|
||||||
|
- Alembic:`upgrade head`;`0015 → 0014 → 0015`;current = `20261119_0015 (head)`
|
||||||
|
- `uv run pytest`:523 passed,195.46s(PostgreSQL)
|
||||||
|
- console `pnpm test:unit`:126 passed
|
||||||
|
- `pnpm typecheck`/`pnpm build`:PASS
|
||||||
|
- `pnpm test:e2e -- e2e/alarms.spec.ts`:11 passed(Mock 页面;含三桌面视口)
|
||||||
|
|
||||||
|
详见 `.task/2026-11-19/m06-alarm-center/reviews/validation-s6.md`。
|
||||||
|
|
||||||
|
## UI 截图
|
||||||
|
|
||||||
|
目录:`docs/evidence/M06/ui/`(13 PNG)
|
||||||
|
|
||||||
|
- 列表/详情:1440×900、1280×800、1920×1080
|
||||||
|
- empty/no-match/no-scope/load-failed/viewer/conflict/closed
|
||||||
|
|
||||||
|
## 审查
|
||||||
|
|
||||||
|
- 片审 S1~S5:均为 PASS_WITH_WARNINGS
|
||||||
|
- 模块审查:`reviews/review-module-m06.md` PASS_WITH_WARNINGS
|
||||||
|
- plan critic/S6 pre-done:见 task `reviews/`
|
||||||
|
|
||||||
|
## 明确非宣称
|
||||||
|
|
||||||
|
- 非真实企微发送、非真实 MES、非空库隔离环境
|
||||||
|
- Playwright 非真实 API 联调
|
||||||
|
- 未授权 Git commit/push 前,候选版本以工作区 diff 为准
|
||||||
|
After Width: | Height: | Size: 52 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 52 KiB |
|
After Width: | Height: | Size: 64 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 45 KiB |
@@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
## 当前快照
|
## 当前快照
|
||||||
|
|
||||||
- 当前阶段:M05 **DONE_LOCAL**。
|
- 当前阶段:M06 **DONE_LOCAL**。
|
||||||
- 当前大任务:M05 已关闭。下一步是 M06,尚未开工。
|
- 当前大任务:M06 已关闭。下一步是 M07,尚未开工。
|
||||||
- 用户授权:D21–D28。本任务 `gatePolicy.selected=autonomous`。用户已确认收口并要求提交、推送。
|
- 用户授权:D32–D40。本任务 `gatePolicy.selected=autonomous`。用户已确认最终批准、提交并推送。
|
||||||
- Git:候选提交见下方台账。
|
- Git:候选提交见下方台账(绑定提交后更新)。
|
||||||
- 下一步:M06 开工前另确认。
|
- 下一步:M07 开工前另确认。
|
||||||
|
|
||||||
## 大任务状态
|
## 大任务状态
|
||||||
|
|
||||||
@@ -17,9 +17,11 @@
|
|||||||
| M03 数据源配置 | DONE_LOCAL | 实现 Claude Sonnet;审查 GPT | `e6d37d1` | S1–S8 片审通过;用户联调收尾 | pytest 262+;console unit 39;datasources e2e 18;证据 `docs/evidence/M03/ui/` | 已完成 |
|
| M03 数据源配置 | DONE_LOCAL | 实现 Claude Sonnet;审查 GPT | `e6d37d1` | S1–S8 片审通过;用户联调收尾 | pytest 262+;console unit 39;datasources e2e 18;证据 `docs/evidence/M03/ui/` | 已完成 |
|
||||||
| M04 查询定义与采集 | DONE_LOCAL | 主 Agent 编排;D26 激活切片已实现 | `21cc721` | 模块复审 PASS;D26 回归 pytest/e2e | query* pytest 201;queries unit 52;e2e queries 16;`docs/evidence/M04/ui/` | 已完成 |
|
| M04 查询定义与采集 | DONE_LOCAL | 主 Agent 编排;D26 激活切片已实现 | `21cc721` | 模块复审 PASS;D26 回归 pytest/e2e | query* pytest 201;queries unit 52;e2e queries 16;`docs/evidence/M04/ui/` | 已完成 |
|
||||||
| M05 字段映射与规则判断 | DONE_LOCAL | 主 Agent 收尾 | `2527097` | S8 PASS_WITH_WARNINGS | 映射 pytest;console 单测;Playwright 1;查询试算已在浏览器看过;证据 `docs/evidence/M05/ui/` | 已完成 |
|
| M05 字段映射与规则判断 | DONE_LOCAL | 主 Agent 收尾 | `2527097` | S8 PASS_WITH_WARNINGS | 映射 pytest;console 单测;Playwright 1;查询试算已在浏览器看过;证据 `docs/evidence/M05/ui/` | 已完成 |
|
||||||
|
| M06 报警中心与人工处理 | DONE_LOCAL | 主 Agent 收尾;审查/critic `grok-4.7` | 待绑定 | 模块+pre-done 均为 PASS_WITH_WARNINGS | pytest 523;unit 126;e2e 11;截图 `docs/evidence/M06/` | 已完成(本地边界) |
|
||||||
|
|
||||||
## 当前阻塞
|
## 当前阻塞
|
||||||
|
|
||||||
- O08:跨系列子 Agent 授权仍开放。
|
- O08:跨系列子 Agent 授权仍开放。
|
||||||
- O01–O07:业务口径,不阻塞 M04 已冻结范围(D24/D26)。
|
- O01/O02/O03/O07:仍分别留待 M08/M09。
|
||||||
|
- M06 后置(不阻塞 MVP):可编排人工处理工作流;M08 正式发布替换合成快照。
|
||||||
- M04:SQL Server 查询试跑本轮明确不做(无服务端只读会话);连接测试仍可用。`draft_*` 列本轮保留镜像、未物理删除。
|
- M04:SQL Server 查询试跑本轮明确不做(无服务端只读会话);连接测试仍可用。`draft_*` 列本轮保留镜像、未物理删除。
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
| M03 | 数据源配置模块 | M02 | 数据源 API+列表/编辑+连接测试、凭证保护及引用提示 |
|
| M03 | 数据源配置模块 | M02 | 数据源 API+列表/编辑+连接测试、凭证保护及引用提示 |
|
||||||
| M04 | 查询定义与采集模块 | M03 | 受控查询、参数与输出契约、只读执行、预览和配套界面;不开放任意脚本 |
|
| M04 | 查询定义与采集模块 | M03 | 受控查询、参数与输出契约、只读执行、预览和配套界面;不开放任意脚本 |
|
||||||
| M05 | 字段映射与规则判断模块 | M04 | 映射预览、类型/空值、输入身份、结构化规则编辑、正常/异常/未知、测试 |
|
| M05 | 字段映射与规则判断模块 | M04 | 映射预览、类型/空值、输入身份、结构化规则编辑、正常/异常/未知、测试 |
|
||||||
| M06 | 报警中心与人工处理模块 | M05 | 报警创建/合并、详情/列表、接手、进展、关闭、新周期规则与 UI;不发送真实消息 |
|
| M06 | 报警中心与人工处理模块 | M05 | 报警创建/合并、详情/列表、处理、进展、关闭、新周期规则与 UI;不发送真实消息 |
|
||||||
| M07 | 企业微信通知模块 | M06 | 应用和机器人、目标/模板、多目标任务、试发、结果和失败重试、完整 UI |
|
| M07 | 企业微信通知模块 | M06 | 应用和机器人、目标/模板、多目标任务、试发、结果和失败重试、完整 UI |
|
||||||
| M08 | 场景配置与 Cron 调度模块 | M05、M07 | 组合场景、草稿/发布/启停、开源 Cron 编辑/解析/定时触发、样例运行;基础正式链可验证 |
|
| M08 | 场景配置与 Cron 调度模块 | M05、M07 | 组合场景、草稿/发布/启停、开源 Cron 编辑/解析/定时触发、样例运行;基础正式链可验证 |
|
||||||
| M09 | 次数统计与分层通知模块 | M06、M07、M08;次数口径已定 | 计数窗口、阈值及步骤、升级意图、配置预览与记录;不做时间升级 |
|
| M09 | 次数统计与分层通知模块 | M06、M07、M08;次数口径已定 | 计数窗口、阈值及步骤、升级意图、配置预览与记录;不做时间升级 |
|
||||||
@@ -58,7 +58,7 @@ M01 基础框架中包含最小授权接口契约,正式登录在 M02;不允
|
|||||||
|
|
||||||
### M06 报警中心与人工处理
|
### M06 报警中心与人工处理
|
||||||
|
|
||||||
- 内部分解示例:报警模型与合并 → 状态服务及权限 → 处理历史 → API/列表/详情 → 接手/关闭 UI → 并发和新周期测试。
|
- 内部分解示例:报警模型与合并 → 状态服务及权限 → 处理历史 → API/列表/详情 → 处理/关闭 UI → 并发和新周期测试。
|
||||||
- 验收:待处理→处理中→已关闭;关闭有结果说明;不改原始 FAIL,不伪称恢复;重复事件不重复报,新周期可关联新报警。
|
- 验收:待处理→处理中→已关闭;关闭有结果说明;不改原始 FAIL,不伪称恢复;重复事件不重复报,新周期可关联新报警。
|
||||||
- 依赖场景发布版本时用 M01 契约中的合成发布快照,不在此顺手实现 M08;整体发布链在 M08/M11 联调。
|
- 依赖场景发布版本时用 M01 契约中的合成发布快照,不在此顺手实现 M08;整体发布链在 M08/M11 联调。
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# M06 报警中心与人工处理模块
|
||||||
|
|
||||||
|
一个会话聚焦本模块。当前状态:**DONE_LOCAL**(用户最终批准;本地边界,非真实企微/MES 联调)。
|
||||||
|
|
||||||
|
## 内部步骤
|
||||||
|
|
||||||
|
- [x] Intake:Tier L,初始化 task artifacts,记录 `gatePolicy.selected=autonomous`。
|
||||||
|
- [x] 检查冻结稿、M05 交接、现有代码、权限与公司规范。
|
||||||
|
- [x] 形成待冻结 requirement、边界摘要、条件切片和 context-pack。
|
||||||
|
- [x] 用户确认 O04/O05/O06、处理范围、合成快照/正式判定契约(D32~D35);可编排工作流与 M08 收尾已登记后置。
|
||||||
|
- [x] 冻结 requirement。
|
||||||
|
- [x] 运行 Tier L plan-review critic(`PASS_WITH_WARNINGS`;报告 `reviews/critic-plan.md`)。
|
||||||
|
- [x] 用户确认分析→编码门禁(「继续」);仅执行 S1。
|
||||||
|
- [x] S1 报警事实、occurrence、有限合并与新周期关联;片审 PASS_WITH_WARNINGS(`reviews/impl-s1.md`、`reviews/review-s1.md`)。
|
||||||
|
- [x] 用户确认关闭后同键新观测=D36(不重开,追加依据/日志),并批准 S2。
|
||||||
|
- [x] S2 正向状态机、处理历史与关闭有效性(含 D36 修正);片审 PASS_WITH_WARNINGS(`reviews/impl-s2.md`、`reviews/review-s2.md`)。
|
||||||
|
- [x] 用户确认 S2 中等问题(D37=1A/2A);批准权限点 D38 并开工 S3。
|
||||||
|
- [x] S3 报警 API 与后端授权;片审 PASS_WITH_WARNINGS(`reviews/impl-s3.md`、`reviews/review-s3.md`)。
|
||||||
|
- [x] 用户批准开工 S4(「继续」)。
|
||||||
|
- [x] S4 HTML 原型已写在 `.task/2026-11-19/m06-alarm-center/prototype/`(`reviews/impl-s4.md`)。
|
||||||
|
- [x] 用户确认原型(D39)并批准 S5。
|
||||||
|
- [x] S5 Vue 报警中心;片审 PASS_WITH_WARNINGS(`reviews/impl-s5.md`、`reviews/review-s5.md`)。
|
||||||
|
- [x] 用户批准开工 S6。
|
||||||
|
- [x] S6 模块整体独立 review:PASS_WITH_WARNINGS(`reviews/review-module-m06.md`)。
|
||||||
|
- [x] S6 正式验证重跑并落盘(`reviews/validation-s6.md`、`reviews/validation-logs/`);testing-plan V033/V042 已改 D34/D32。
|
||||||
|
- [x] S6 pre-done critic:PASS_WITH_WARNINGS(`reviews/critic-s6-pre-done.md`)。
|
||||||
|
- [x] 用户最终批准并标 `DONE_LOCAL`(提交/推送按用户指令执行)。
|
||||||
|
|
||||||
|
## 目标与边界
|
||||||
|
|
||||||
|
- 阶段/需求编号:阶段 A;P-006;A-037~A-047;T09~T15、T33;V030~V037、V042;U06。
|
||||||
|
- 依赖及当前状态:M05 `DONE_LOCAL`。S1~S6 已完成;控制台认领文案按 D40 为「处理」。M05 试算仍不写报警。
|
||||||
|
- 已确认决策:D05、D19/D20、D22/D25、D27/D28、D32、D33、D34、D35、D36、D37、D38、D39、D40。
|
||||||
|
- 模块可验收行为:正式异常创建/有限合并;重复不重复报;新独立事件可关联新报警;待处理→处理中→已关闭;关闭结果和说明可查;不改原始异常,不伪称恢复。
|
||||||
|
- 明确不做:真实消息、M07 企微、M08 场景/Cron、M09 次数/升级、可编排工作流引擎、自动恢复、转派、重开、审批。
|
||||||
|
- 后置备注:人工处理可编排工作流(D33);M08 正式发布替换合成快照路径(D35/requirement 收尾备注)。
|
||||||
|
- 输入/输出契约及失败语义:正式异常必须和 M05 试算隔离;命令幂等;并发冲突明确;统一 API 信封。
|
||||||
|
- 权限、事务、唯一约束和幂等键:后端按三角色、D38 四个权限点和合成快照 subject 范围校验。RLS、数据库唯一约束和 PostgreSQL 测试均为必需。没有新增权限点,也没有新错误码。
|
||||||
|
|
||||||
|
## 当前阻塞
|
||||||
|
|
||||||
|
无。模块已 `DONE_LOCAL`。后置项见决策 D33/D35,不在本模块继续实现。
|
||||||
|
|
||||||
|
## 实施委派
|
||||||
|
|
||||||
|
- Builder/规划:`gpt-5.6-sol`(分析轮);编排后续按 D31 为 `grok-4.7`。
|
||||||
|
- 实现/审查/critic:`grok-4.7`;S1~S6 已完成。
|
||||||
|
- 测试/浏览器:pytest 523;console unit 126;alarms e2e 11(Mock);证据 `docs/evidence/M06/`;正式验证日志见 `reviews/validation-logs/`。
|
||||||
|
- 公共契约或迁移:`20261119_0014`、`20261119_0015`。没有新错误码。权限点见 D38。
|
||||||
|
|
||||||
|
## 模块验收
|
||||||
|
|
||||||
|
- 正常:首次正式异常创建;范围内持续异常关联;处理、进展、关闭后历史可查。
|
||||||
|
- 边界:新周期/独立事件新建并关联;同周期更正按 D34;PASS/UNKNOWN/失败不自动关闭或恢复。
|
||||||
|
- 故障/权限/重复:重复 occurrence/命令幂等;并发处理/关闭无覆盖;越范围 ID 拒绝;无前端权限旁路。
|
||||||
|
- 回归范围:M05 输入身份/修订/试算不写报警;M02 会话;统一信封与 RLS。
|
||||||
|
- UI:U06;1440×900、1280×800、1920×1080;断言、截图和视觉检查。
|
||||||
|
|
||||||
|
## 证据与结论
|
||||||
|
|
||||||
|
- 分析 artifacts:`.task/2026-11-19/m06-alarm-center/`。
|
||||||
|
- S1 实现证据:`.task/2026-11-19/m06-alarm-center/reviews/impl-s1.md`。
|
||||||
|
- S2 实现证据:`.task/2026-11-19/m06-alarm-center/reviews/impl-s2.md`。
|
||||||
|
- S3 实现证据:`.task/2026-11-19/m06-alarm-center/reviews/impl-s3.md`。片审:`reviews/review-s3.md`(`PASS_WITH_WARNINGS`)。
|
||||||
|
- S3 `cd services/watchman && uv run pytest --tb=line -q`:`523 passed, 1 warning in 193.25s`。数据库是当前配置的 PostgreSQL,不是另建的空库。警告来自 Starlette 对 httpx 的弃用提示。
|
||||||
|
- S4 原型:`.task/2026-11-19/m06-alarm-center/prototype/index.html` 与 `README.md`。实现记录:`reviews/impl-s4.md`。
|
||||||
|
- S5 实现证据:`.task/2026-11-19/m06-alarm-center/reviews/impl-s5.md`。截图:`docs/evidence/M06/ui/`。
|
||||||
|
- S5 `cd web/apps/console && pnpm test:unit`:`126 passed`。
|
||||||
|
- S5 `pnpm typecheck` 与 `pnpm build`:通过。build 仍有既有的大包体积提示。
|
||||||
|
- S5 `pnpm test:e2e -- e2e/alarms.spec.ts`:`11 passed`。视口 1440×900、1280×800、1920×1080。接口为 Playwright Mock。
|
||||||
|
- S6 模块审查:`reviews/review-module-m06.md`(PASS_WITH_WARNINGS)。
|
||||||
|
- S6 正式验证:`reviews/validation-s6.md`、`reviews/validation-logs/`。
|
||||||
|
- S6 pre-done critic:`reviews/critic-s6-pre-done.md`(PASS_WITH_WARNINGS)。
|
||||||
|
- 最终状态:`DONE_LOCAL`。下一步 M07 另开任务。
|
||||||
@@ -86,7 +86,7 @@ Cron 用例验证“动态配置、正确触发、停用和防重”等业务结
|
|||||||
| V030 | 首次 FAIL;PASS/UNKNOWN 作为对照 | FAIL 报警,对照不默认报警 | A-037 |
|
| V030 | 首次 FAIL;PASS/UNKNOWN 作为对照 | FAIL 报警,对照不默认报警 | A-037 |
|
||||||
| V031 | 同合并范围持续 FAIL,之后跨范围 | 范围内关联,范围外可新建,历史依据留存 | A-038 |
|
| V031 | 同合并范围持续 FAIL,之后跨范围 | 范围内关联,范围外可新建,历史依据留存 | A-038 |
|
||||||
| V032 | 关闭后旧输入重投、新周期新事件到达 | 旧不重报,新可新建并关联历史 | A-039 |
|
| V032 | 关闭后旧输入重投、新周期新事件到达 | 旧不重报,新可新建并关联历史 | A-039 |
|
||||||
| V033 | 同周期源值更正 | 按 O06 最终口径,不因 payload hash 改变乱报 | A-039 |
|
| V033 | 同周期源值更正 | 按 D34:只追加修订/依据,不自动新建报警、不自动重发;不因 payload hash 改变乱报 | A-039 |
|
||||||
| V034 | 两人同时接手/重复接手 | 唯一处理人,后到返回冲突或幂等结果 | A-041 |
|
| V034 | 两人同时接手/重复接手 | 唯一处理人,后到返回冲突或幂等结果 | A-041 |
|
||||||
| V035 | 追加进展后再查询 | 原文、操作者、时间不可覆盖 | A-042 |
|
| V035 | 追加进展后再查询 | 原文、操作者、时间不可覆盖 | A-042 |
|
||||||
| V036 | 非处理人关闭、缺结果或依据、并发关闭 | 按权限拒绝/提示,只有一个合法终态 | A-043 |
|
| V036 | 非处理人关闭、缺结果或依据、并发关闭 | 按权限拒绝/提示,只有一个合法终态 | A-043 |
|
||||||
@@ -95,7 +95,7 @@ Cron 用例验证“动态配置、正确触发、停用和防重”等业务结
|
|||||||
| V039 | 两个独立事件并发达到阈值 | 不丢计数,恰好一个同级意图 | A-049、A-050 |
|
| V039 | 两个独立事件并发达到阈值 | 不丢计数,恰好一个同级意图 | A-049、A-050 |
|
||||||
| V040 | N-1、N、N+1 次及一次越过多级 | 达到阈值、跳级/逐级按 O03,每级不重复 | A-050 |
|
| V040 | N-1、N、N+1 次及一次越过多级 | 达到阈值、跳级/逐级按 O03,每级不重复 | A-050 |
|
||||||
| V041 | 固定或滑动窗口边界、规则版本变更 | 按批准口径,分组不混、重置有依据 | A-049 |
|
| V041 | 固定或滑动窗口边界、规则版本变更 | 按批准口径,分组不混、重置有依据 | A-049 |
|
||||||
| V042 | 关闭旧报警后窗口内有新事件 | 严格按 O04 最终决定执行;不预设窗口是否清零,旧报警和新报警的任务身份不能混淆 | A-051 |
|
| V042 | 关闭旧报警后窗口内有新事件 | M06 部分按 D32:关闭使绑定旧报警的未执行意图失效;已受理不可撤回;次数窗口不因关闭清零(窗口细则归 M09)。旧报警与新报警身份不得混淆。V038~V041/完整次数升级不在 M06 | A-051 |
|
||||||
| V043 | 未满足次数条件但无人响应很久 | 不触发后置的时间升级 | A-050 |
|
| V043 | 未满足次数条件但无人响应很久 | 不触发后置的时间升级 | A-050 |
|
||||||
| V044 | 预览模拟重复/独立事件序列 | 计数和预计目标清晰,绝无真实发送 | A-053 |
|
| V044 | 预览模拟重复/独立事件序列 | 计数和预计目标清晰,绝无真实发送 | A-053 |
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,226 @@
|
|||||||
|
"""Create tenant-scoped alarm facts, occurrences, and revision evidence.
|
||||||
|
|
||||||
|
Revision ID: 20261119_0014
|
||||||
|
Revises: 20261118_0013
|
||||||
|
Create Date: 2026-11-19
|
||||||
|
|
||||||
|
Synthetic snapshot columns are stored on the fact rows. This migration does not
|
||||||
|
create a scenario publish table.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "20261119_0014"
|
||||||
|
down_revision: Union[str, None] = "20261118_0013"
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
APP_ROLE = "watchman_app"
|
||||||
|
ALARMS = "alarms"
|
||||||
|
OCCURRENCES = "alarm_occurrences"
|
||||||
|
EVIDENCE = "alarm_revision_evidence"
|
||||||
|
OCCURRENCE_FUNCTION = "alarm_occurrences_reject_mutation"
|
||||||
|
OCCURRENCE_TRIGGER = "trg_alarm_occurrences_append_only"
|
||||||
|
EVIDENCE_FUNCTION = "alarm_revision_evidence_reject_mutation"
|
||||||
|
EVIDENCE_TRIGGER = "trg_alarm_revision_evidence_append_only"
|
||||||
|
|
||||||
|
# Same minimal scope guard as the ORM. Subject-level contents are enforced by
|
||||||
|
# the domain service; this check only blocks an empty or all-tenant blob.
|
||||||
|
_SCOPE_SQL = (
|
||||||
|
"jsonb_typeof(handling_scope) = 'object' "
|
||||||
|
"AND NOT jsonb_exists(handling_scope, 'all_tenant') "
|
||||||
|
"AND jsonb_typeof(handling_scope -> 'principals') = 'array' "
|
||||||
|
"AND jsonb_array_length(handling_scope -> 'principals') >= 1"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _enable_rls(table: str) -> None:
|
||||||
|
op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")
|
||||||
|
op.execute(f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY")
|
||||||
|
op.execute(
|
||||||
|
f"""
|
||||||
|
CREATE POLICY tenant_isolation ON {table}
|
||||||
|
FOR ALL
|
||||||
|
TO {APP_ROLE}
|
||||||
|
USING (tenant_id = current_setting('app.tenant_id', true))
|
||||||
|
WITH CHECK (tenant_id = current_setting('app.tenant_id', true))
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
op.execute(f"GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE {table} TO {APP_ROLE}")
|
||||||
|
|
||||||
|
|
||||||
|
def _append_only(table: str, function: str, trigger: str, message: str) -> None:
|
||||||
|
op.execute(f"REVOKE UPDATE, DELETE ON TABLE {table} FROM {APP_ROLE}")
|
||||||
|
op.execute(f"GRANT SELECT, INSERT ON TABLE {table} TO {APP_ROLE}")
|
||||||
|
op.execute(
|
||||||
|
f"""
|
||||||
|
CREATE FUNCTION {function}() RETURNS trigger
|
||||||
|
LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
RAISE EXCEPTION '{message}'
|
||||||
|
USING ERRCODE = 'restrict_violation';
|
||||||
|
END;
|
||||||
|
$$
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
op.execute(
|
||||||
|
f"""
|
||||||
|
CREATE TRIGGER {trigger}
|
||||||
|
BEFORE UPDATE OR DELETE OR TRUNCATE ON {table}
|
||||||
|
FOR EACH STATEMENT EXECUTE FUNCTION {function}()
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
ALARMS,
|
||||||
|
sa.Column("id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), primary_key=True),
|
||||||
|
sa.Column("tenant_id", sa.String(length=64), nullable=False),
|
||||||
|
sa.Column("status", sa.String(length=16), server_default=sa.text("'pending'"), nullable=False),
|
||||||
|
sa.Column("current_handler", sa.String(length=128), nullable=True),
|
||||||
|
sa.Column("occurrence_count", sa.Integer(), server_default=sa.text("1"), nullable=False),
|
||||||
|
sa.Column("first_occurred_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("last_occurred_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("previous_alarm_id", postgresql.UUID(as_uuid=True), nullable=True),
|
||||||
|
sa.Column("mapped_input_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("mapped_inputs.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("mapping_definition_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("mapping_definitions.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("mapping_version_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("mapping_versions.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("rule_definition_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("rule_definitions.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("rule_version_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("rule_versions.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("snapshot_id", postgresql.UUID(as_uuid=True), nullable=False),
|
||||||
|
sa.Column("snapshot_version_no", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("module_key", sa.String(length=128), nullable=False),
|
||||||
|
sa.Column("scenario_key", sa.String(length=128), nullable=False),
|
||||||
|
sa.Column("scenario_name", sa.String(length=256), nullable=False),
|
||||||
|
sa.Column("handling_scope", postgresql.JSONB(), nullable=False),
|
||||||
|
sa.Column("cycle_key", sa.String(length=128), nullable=False),
|
||||||
|
sa.Column("event_key", sa.String(length=128), nullable=False),
|
||||||
|
sa.Column("opened_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(["previous_alarm_id"], ["alarms.id"], ondelete="RESTRICT"),
|
||||||
|
sa.UniqueConstraint(
|
||||||
|
"tenant_id",
|
||||||
|
"module_key",
|
||||||
|
"scenario_key",
|
||||||
|
"mapped_input_id",
|
||||||
|
"cycle_key",
|
||||||
|
"event_key",
|
||||||
|
name="uq_alarms_structured_merge_key",
|
||||||
|
),
|
||||||
|
sa.CheckConstraint("status IN ('pending', 'processing', 'closed')", name="ck_alarms_status"),
|
||||||
|
sa.CheckConstraint("occurrence_count >= 1", name="ck_alarms_occurrence_count"),
|
||||||
|
sa.CheckConstraint("snapshot_version_no >= 1", name="ck_alarms_snapshot_version"),
|
||||||
|
sa.CheckConstraint("char_length(btrim(module_key)) > 0", name="ck_alarms_module_key"),
|
||||||
|
sa.CheckConstraint("char_length(btrim(scenario_key)) > 0", name="ck_alarms_scenario_key"),
|
||||||
|
sa.CheckConstraint("char_length(btrim(scenario_name)) > 0", name="ck_alarms_scenario_name"),
|
||||||
|
sa.CheckConstraint("char_length(btrim(cycle_key)) > 0", name="ck_alarms_cycle_key"),
|
||||||
|
sa.CheckConstraint("char_length(btrim(event_key)) > 0", name="ck_alarms_event_key"),
|
||||||
|
sa.CheckConstraint("last_occurred_at >= first_occurred_at", name="ck_alarms_occurred_order"),
|
||||||
|
sa.CheckConstraint("previous_alarm_id IS NULL OR previous_alarm_id <> id", name="ck_alarms_previous_not_self"),
|
||||||
|
sa.CheckConstraint(_SCOPE_SQL, name="ck_alarms_handling_scope"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_alarms_previous_alarm_id", ALARMS, ["previous_alarm_id"])
|
||||||
|
op.create_index(
|
||||||
|
"ix_alarms_subject_opened",
|
||||||
|
ALARMS,
|
||||||
|
["tenant_id", "module_key", "scenario_key", "mapped_input_id", "opened_at"],
|
||||||
|
)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
OCCURRENCES,
|
||||||
|
sa.Column("id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), primary_key=True),
|
||||||
|
sa.Column("tenant_id", sa.String(length=64), nullable=False),
|
||||||
|
sa.Column("alarm_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("alarms.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("mapped_input_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("mapped_inputs.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("mapped_input_revision_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("mapped_input_revisions.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("mapping_definition_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("mapping_definitions.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("mapping_version_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("mapping_versions.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("rule_definition_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("rule_definitions.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("rule_version_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("rule_versions.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("snapshot_id", postgresql.UUID(as_uuid=True), nullable=False),
|
||||||
|
sa.Column("snapshot_version_no", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("module_key", sa.String(length=128), nullable=False),
|
||||||
|
sa.Column("scenario_key", sa.String(length=128), nullable=False),
|
||||||
|
sa.Column("scenario_name", sa.String(length=256), nullable=False),
|
||||||
|
sa.Column("handling_scope", postgresql.JSONB(), nullable=False),
|
||||||
|
sa.Column("cycle_key", sa.String(length=128), nullable=False),
|
||||||
|
sa.Column("event_key", sa.String(length=128), nullable=False),
|
||||||
|
sa.Column("observed_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("received_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.UniqueConstraint(
|
||||||
|
"tenant_id",
|
||||||
|
"mapped_input_revision_id",
|
||||||
|
"mapping_version_id",
|
||||||
|
"rule_version_id",
|
||||||
|
"snapshot_id",
|
||||||
|
"cycle_key",
|
||||||
|
"event_key",
|
||||||
|
"observed_at",
|
||||||
|
name="uq_alarm_occurrences_formal_identity",
|
||||||
|
),
|
||||||
|
sa.CheckConstraint("snapshot_version_no >= 1", name="ck_alarm_occurrences_snapshot_version"),
|
||||||
|
sa.CheckConstraint("char_length(btrim(module_key)) > 0", name="ck_alarm_occurrences_module_key"),
|
||||||
|
sa.CheckConstraint("char_length(btrim(scenario_key)) > 0", name="ck_alarm_occurrences_scenario_key"),
|
||||||
|
sa.CheckConstraint("char_length(btrim(scenario_name)) > 0", name="ck_alarm_occurrences_scenario_name"),
|
||||||
|
sa.CheckConstraint("char_length(btrim(cycle_key)) > 0", name="ck_alarm_occurrences_cycle_key"),
|
||||||
|
sa.CheckConstraint("char_length(btrim(event_key)) > 0", name="ck_alarm_occurrences_event_key"),
|
||||||
|
sa.CheckConstraint(_SCOPE_SQL, name="ck_alarm_occurrences_handling_scope"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_alarm_occurrences_alarm_id", OCCURRENCES, ["alarm_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
EVIDENCE,
|
||||||
|
sa.Column("id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), primary_key=True),
|
||||||
|
sa.Column("tenant_id", sa.String(length=64), nullable=False),
|
||||||
|
sa.Column("alarm_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("alarms.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("occurrence_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("alarm_occurrences.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("mapped_input_revision_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("mapped_input_revisions.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("mapping_version_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("mapping_versions.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("rule_version_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("rule_versions.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("snapshot_id", postgresql.UUID(as_uuid=True), nullable=False),
|
||||||
|
sa.Column("snapshot_version_no", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("received_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("recorded_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.UniqueConstraint("alarm_id", "mapped_input_revision_id", name="uq_alarm_revision_evidence_alarm_revision"),
|
||||||
|
sa.CheckConstraint("snapshot_version_no >= 1", name="ck_alarm_revision_evidence_snapshot_version"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_alarm_revision_evidence_alarm_id", EVIDENCE, ["alarm_id"])
|
||||||
|
|
||||||
|
for table in (ALARMS, OCCURRENCES, EVIDENCE):
|
||||||
|
_enable_rls(table)
|
||||||
|
_append_only(
|
||||||
|
OCCURRENCES,
|
||||||
|
OCCURRENCE_FUNCTION,
|
||||||
|
OCCURRENCE_TRIGGER,
|
||||||
|
"alarm_occurrences is append-only: formal facts are immutable",
|
||||||
|
)
|
||||||
|
_append_only(
|
||||||
|
EVIDENCE,
|
||||||
|
EVIDENCE_FUNCTION,
|
||||||
|
EVIDENCE_TRIGGER,
|
||||||
|
"alarm_revision_evidence is append-only: correction basis is immutable",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
for table in (EVIDENCE, OCCURRENCES, ALARMS):
|
||||||
|
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {table}")
|
||||||
|
op.execute(f"DROP TRIGGER IF EXISTS {EVIDENCE_TRIGGER} ON {EVIDENCE}")
|
||||||
|
op.execute(f"DROP TRIGGER IF EXISTS {OCCURRENCE_TRIGGER} ON {OCCURRENCES}")
|
||||||
|
op.execute(f"DROP FUNCTION IF EXISTS {EVIDENCE_FUNCTION}()")
|
||||||
|
op.execute(f"DROP FUNCTION IF EXISTS {OCCURRENCE_FUNCTION}()")
|
||||||
|
op.drop_index("ix_alarm_revision_evidence_alarm_id", table_name=EVIDENCE)
|
||||||
|
op.drop_table(EVIDENCE)
|
||||||
|
op.drop_index("ix_alarm_occurrences_alarm_id", table_name=OCCURRENCES)
|
||||||
|
op.drop_table(OCCURRENCES)
|
||||||
|
op.drop_index("ix_alarms_subject_opened", table_name=ALARMS)
|
||||||
|
op.drop_index("ix_alarms_previous_alarm_id", table_name=ALARMS)
|
||||||
|
op.drop_table(ALARMS)
|
||||||
@@ -0,0 +1,425 @@
|
|||||||
|
"""Add alarm handling history and stop direct status updates.
|
||||||
|
|
||||||
|
Revision ID: 20261119_0015
|
||||||
|
Revises: 20261119_0014
|
||||||
|
Create Date: 2026-11-19
|
||||||
|
|
||||||
|
0014 stays unchanged. Status, handler, and close columns are no longer updated
|
||||||
|
by a plain UPDATE from the application role. The handling service calls
|
||||||
|
alarm_apply_transition, which is the only writer of those columns.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "20261119_0015"
|
||||||
|
down_revision: Union[str, None] = "20261119_0014"
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
APP_ROLE = "watchman_app"
|
||||||
|
ALARMS = "alarms"
|
||||||
|
EVENTS = "alarm_handling_events"
|
||||||
|
COMMANDS = "alarm_handling_commands"
|
||||||
|
BASIS = "alarm_closed_basis"
|
||||||
|
GUARD_FUNCTION = "alarms_guard_status"
|
||||||
|
GUARD_TRIGGER = "trg_alarms_status_guard"
|
||||||
|
TRANSITION_FUNCTION = "alarm_apply_transition"
|
||||||
|
|
||||||
|
_EVENT_SHAPE = """
|
||||||
|
(
|
||||||
|
command = 'claim'
|
||||||
|
AND from_status = 'pending'
|
||||||
|
AND to_status = 'processing'
|
||||||
|
AND note IS NULL
|
||||||
|
AND close_result IS NULL
|
||||||
|
AND evidence_ref IS NULL
|
||||||
|
) OR (
|
||||||
|
command = 'progress'
|
||||||
|
AND from_status = 'processing'
|
||||||
|
AND to_status = 'processing'
|
||||||
|
AND note IS NOT NULL
|
||||||
|
AND char_length(btrim(note)) > 0
|
||||||
|
AND close_result IS NULL
|
||||||
|
) OR (
|
||||||
|
command = 'close'
|
||||||
|
AND from_status = 'processing'
|
||||||
|
AND to_status = 'closed'
|
||||||
|
AND note IS NOT NULL
|
||||||
|
AND char_length(btrim(note)) > 0
|
||||||
|
AND close_result IN ('resolved', 'false_positive')
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _enable_rls_insert_only(table: str) -> None:
|
||||||
|
op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")
|
||||||
|
op.execute(f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY")
|
||||||
|
op.execute(
|
||||||
|
f"""
|
||||||
|
CREATE POLICY tenant_isolation ON {table}
|
||||||
|
FOR ALL
|
||||||
|
TO {APP_ROLE}
|
||||||
|
USING (tenant_id = current_setting('app.tenant_id', true))
|
||||||
|
WITH CHECK (tenant_id = current_setting('app.tenant_id', true))
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
op.execute(f"GRANT SELECT, INSERT ON TABLE {table} TO {APP_ROLE}")
|
||||||
|
|
||||||
|
|
||||||
|
def _append_only(table: str, function: str, trigger: str, message: str) -> None:
|
||||||
|
op.execute(
|
||||||
|
f"""
|
||||||
|
CREATE FUNCTION {function}() RETURNS trigger
|
||||||
|
LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
RAISE EXCEPTION '{message}'
|
||||||
|
USING ERRCODE = 'restrict_violation';
|
||||||
|
END;
|
||||||
|
$$
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
op.execute(
|
||||||
|
f"""
|
||||||
|
CREATE TRIGGER {trigger}
|
||||||
|
BEFORE UPDATE OR DELETE OR TRUNCATE ON {table}
|
||||||
|
FOR EACH STATEMENT EXECUTE FUNCTION {function}()
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column(ALARMS, sa.Column("claimed_at", sa.DateTime(timezone=True), nullable=True))
|
||||||
|
op.add_column(ALARMS, sa.Column("closed_at", sa.DateTime(timezone=True), nullable=True))
|
||||||
|
op.add_column(ALARMS, sa.Column("close_result", sa.String(length=32), nullable=True))
|
||||||
|
op.create_check_constraint(
|
||||||
|
"ck_alarms_close_result",
|
||||||
|
ALARMS,
|
||||||
|
"close_result IS NULL OR close_result IN ('resolved', 'false_positive')",
|
||||||
|
)
|
||||||
|
op.create_check_constraint(
|
||||||
|
"ck_alarms_pending_unassigned",
|
||||||
|
ALARMS,
|
||||||
|
"status <> 'pending' OR current_handler IS NULL",
|
||||||
|
)
|
||||||
|
op.create_check_constraint(
|
||||||
|
"ck_alarms_processing_handler",
|
||||||
|
ALARMS,
|
||||||
|
"status <> 'processing' OR current_handler IS NOT NULL",
|
||||||
|
)
|
||||||
|
|
||||||
|
# GUARD: table-level UPDATE would let a caller skip the handling service.
|
||||||
|
op.execute(f"REVOKE UPDATE ON TABLE {ALARMS} FROM {APP_ROLE}")
|
||||||
|
op.execute(
|
||||||
|
f"GRANT UPDATE (occurrence_count, last_occurred_at, updated_at) ON TABLE {ALARMS} TO {APP_ROLE}"
|
||||||
|
)
|
||||||
|
|
||||||
|
op.execute(
|
||||||
|
f"""
|
||||||
|
CREATE FUNCTION {GUARD_FUNCTION}() RETURNS trigger
|
||||||
|
LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP = 'INSERT' THEN
|
||||||
|
IF NEW.status IS DISTINCT FROM 'pending'
|
||||||
|
OR NEW.current_handler IS NOT NULL
|
||||||
|
OR NEW.claimed_at IS NOT NULL
|
||||||
|
OR NEW.closed_at IS NOT NULL
|
||||||
|
OR NEW.close_result IS NOT NULL THEN
|
||||||
|
RAISE EXCEPTION 'alarms are inserted as pending; status changes only through the handling service'
|
||||||
|
USING ERRCODE = 'restrict_violation';
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
IF NEW.status IS NOT DISTINCT FROM OLD.status
|
||||||
|
AND NEW.current_handler IS NOT DISTINCT FROM OLD.current_handler
|
||||||
|
AND NEW.claimed_at IS NOT DISTINCT FROM OLD.claimed_at
|
||||||
|
AND NEW.closed_at IS NOT DISTINCT FROM OLD.closed_at
|
||||||
|
AND NEW.close_result IS NOT DISTINCT FROM OLD.close_result THEN
|
||||||
|
RETURN NEW;
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
IF current_setting('app.alarm_transition', true) IS DISTINCT FROM 'service' THEN
|
||||||
|
RAISE EXCEPTION 'alarm status transitions only through the handling service'
|
||||||
|
USING ERRCODE = 'restrict_violation';
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
IF NEW.current_handler IS DISTINCT FROM OLD.current_handler
|
||||||
|
AND NOT (OLD.status = 'pending' AND NEW.status = 'processing') THEN
|
||||||
|
RAISE EXCEPTION 'alarm handler changes only when a pending alarm is claimed'
|
||||||
|
USING ERRCODE = 'restrict_violation';
|
||||||
|
END IF;
|
||||||
|
IF NEW.claimed_at IS DISTINCT FROM OLD.claimed_at
|
||||||
|
AND NOT (OLD.status = 'pending' AND NEW.status = 'processing') THEN
|
||||||
|
RAISE EXCEPTION 'claimed_at is set only when a pending alarm is claimed'
|
||||||
|
USING ERRCODE = 'restrict_violation';
|
||||||
|
END IF;
|
||||||
|
IF OLD.status = 'pending' AND NEW.status = 'processing' THEN
|
||||||
|
IF NEW.current_handler IS NULL OR btrim(NEW.current_handler) = ''
|
||||||
|
OR NEW.claimed_at IS NULL
|
||||||
|
OR NEW.closed_at IS NOT NULL
|
||||||
|
OR NEW.close_result IS NOT NULL THEN
|
||||||
|
RAISE EXCEPTION 'a claim must record one handler and no close result'
|
||||||
|
USING ERRCODE = 'restrict_violation';
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END IF;
|
||||||
|
IF OLD.status = 'processing' AND NEW.status = 'closed' THEN
|
||||||
|
IF NEW.current_handler IS DISTINCT FROM OLD.current_handler
|
||||||
|
OR NEW.claimed_at IS DISTINCT FROM OLD.claimed_at
|
||||||
|
OR NEW.close_result IS NULL
|
||||||
|
OR NEW.close_result NOT IN ('resolved', 'false_positive')
|
||||||
|
OR NEW.closed_at IS NULL
|
||||||
|
OR (NEW.claimed_at IS NOT NULL AND NEW.closed_at < NEW.claimed_at) THEN
|
||||||
|
RAISE EXCEPTION 'a close must keep the handler and record one final result'
|
||||||
|
USING ERRCODE = 'restrict_violation';
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
RAISE EXCEPTION 'alarm status only moves pending to processing to closed'
|
||||||
|
USING ERRCODE = 'restrict_violation';
|
||||||
|
END;
|
||||||
|
$$
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
op.execute(
|
||||||
|
f"""
|
||||||
|
CREATE TRIGGER {GUARD_TRIGGER}
|
||||||
|
BEFORE INSERT OR UPDATE ON {ALARMS}
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION {GUARD_FUNCTION}()
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
# GUARD: owner bypasses RLS, so the tenant predicate is mandatory.
|
||||||
|
op.execute(
|
||||||
|
f"""
|
||||||
|
CREATE FUNCTION {TRANSITION_FUNCTION}(
|
||||||
|
p_alarm_id uuid,
|
||||||
|
p_status text,
|
||||||
|
p_handler text,
|
||||||
|
p_claimed_at timestamptz,
|
||||||
|
p_closed_at timestamptz,
|
||||||
|
p_close_result text
|
||||||
|
) RETURNS void
|
||||||
|
LANGUAGE plpgsql
|
||||||
|
SECURITY DEFINER
|
||||||
|
SET search_path = public
|
||||||
|
AS $$
|
||||||
|
BEGIN
|
||||||
|
IF current_setting('app.tenant_id', true) IS NULL
|
||||||
|
OR btrim(current_setting('app.tenant_id', true)) = '' THEN
|
||||||
|
RAISE EXCEPTION 'tenant is required'
|
||||||
|
USING ERRCODE = 'insufficient_privilege';
|
||||||
|
END IF;
|
||||||
|
PERFORM set_config('app.alarm_transition', 'service', true);
|
||||||
|
UPDATE {ALARMS}
|
||||||
|
SET status = p_status,
|
||||||
|
current_handler = p_handler,
|
||||||
|
claimed_at = CASE
|
||||||
|
WHEN p_status = 'processing' AND status = 'pending' THEN p_claimed_at
|
||||||
|
ELSE claimed_at
|
||||||
|
END,
|
||||||
|
closed_at = CASE
|
||||||
|
WHEN p_status = 'closed' THEN p_closed_at
|
||||||
|
ELSE closed_at
|
||||||
|
END,
|
||||||
|
close_result = CASE
|
||||||
|
WHEN p_status = 'closed' THEN p_close_result
|
||||||
|
ELSE close_result
|
||||||
|
END,
|
||||||
|
updated_at = now()
|
||||||
|
WHERE id = p_alarm_id
|
||||||
|
AND tenant_id = current_setting('app.tenant_id', true);
|
||||||
|
IF NOT FOUND THEN
|
||||||
|
RAISE EXCEPTION 'alarm not found for tenant'
|
||||||
|
USING ERRCODE = 'no_data_found';
|
||||||
|
END IF;
|
||||||
|
PERFORM set_config('app.alarm_transition', '', true);
|
||||||
|
END;
|
||||||
|
$$
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
op.execute(f"REVOKE ALL ON FUNCTION {TRANSITION_FUNCTION}(uuid, text, text, timestamptz, timestamptz, text) FROM PUBLIC")
|
||||||
|
op.execute(
|
||||||
|
f"GRANT EXECUTE ON FUNCTION {TRANSITION_FUNCTION}(uuid, text, text, timestamptz, timestamptz, text) TO {APP_ROLE}"
|
||||||
|
)
|
||||||
|
# FORCE RLS applies to the table owner, and the existing policy targets only
|
||||||
|
# watchman_app. The definer function would otherwise update zero rows.
|
||||||
|
op.execute(
|
||||||
|
"""
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
owner_name text;
|
||||||
|
BEGIN
|
||||||
|
SELECT pg_get_userbyid(c.relowner) INTO owner_name
|
||||||
|
FROM pg_class c
|
||||||
|
JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||||
|
WHERE n.nspname = 'public' AND c.relname = 'alarms';
|
||||||
|
EXECUTE format(
|
||||||
|
'CREATE POLICY tenant_isolation_definer ON alarms FOR ALL TO %I '
|
||||||
|
'USING (tenant_id = current_setting(''app.tenant_id'', true)) '
|
||||||
|
'WITH CHECK (tenant_id = current_setting(''app.tenant_id'', true))',
|
||||||
|
owner_name
|
||||||
|
);
|
||||||
|
END $$;
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
EVENTS,
|
||||||
|
sa.Column("id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), primary_key=True),
|
||||||
|
sa.Column("seq", sa.BigInteger(), sa.Identity(), nullable=False),
|
||||||
|
sa.Column("tenant_id", sa.String(length=64), nullable=False),
|
||||||
|
sa.Column("alarm_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("alarms.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column("command", sa.String(length=16), nullable=False),
|
||||||
|
sa.Column("actor_subject", sa.String(length=128), nullable=False),
|
||||||
|
sa.Column("actor_role", sa.String(length=64), nullable=False),
|
||||||
|
sa.Column("handler_subject", sa.String(length=128), nullable=False),
|
||||||
|
sa.Column("from_status", sa.String(length=16), nullable=False),
|
||||||
|
sa.Column("to_status", sa.String(length=16), nullable=False),
|
||||||
|
sa.Column("note", sa.String(length=2000), nullable=True),
|
||||||
|
sa.Column("close_result", sa.String(length=32), nullable=True),
|
||||||
|
sa.Column("evidence_ref", sa.String(length=512), nullable=True),
|
||||||
|
sa.Column("recorded_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.CheckConstraint("command IN ('claim', 'progress', 'close')", name="ck_alarm_handling_events_command"),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"from_status IN ('pending', 'processing', 'closed')",
|
||||||
|
name="ck_alarm_handling_events_from_status",
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"to_status IN ('pending', 'processing', 'closed')",
|
||||||
|
name="ck_alarm_handling_events_to_status",
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"actor_role IN ('watchman-admin', 'watchman-operator')",
|
||||||
|
name="ck_alarm_handling_events_actor_role",
|
||||||
|
),
|
||||||
|
sa.CheckConstraint("char_length(btrim(actor_subject)) > 0", name="ck_alarm_handling_events_actor"),
|
||||||
|
sa.CheckConstraint("char_length(btrim(handler_subject)) > 0", name="ck_alarm_handling_events_handler"),
|
||||||
|
sa.CheckConstraint(_EVENT_SHAPE, name="ck_alarm_handling_events_shape"),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"evidence_ref IS NULL OR char_length(btrim(evidence_ref)) > 0",
|
||||||
|
name="ck_alarm_handling_events_evidence_ref",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
op.create_index("ix_alarm_handling_events_alarm_id", EVENTS, ["alarm_id", "seq"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
COMMANDS,
|
||||||
|
sa.Column("id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), primary_key=True),
|
||||||
|
sa.Column("tenant_id", sa.String(length=64), nullable=False),
|
||||||
|
sa.Column("alarm_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("alarms.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"event_id",
|
||||||
|
postgresql.UUID(as_uuid=True),
|
||||||
|
sa.ForeignKey("alarm_handling_events.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("command", sa.String(length=16), nullable=False),
|
||||||
|
sa.Column("idempotency_key", sa.String(length=128), nullable=False),
|
||||||
|
sa.Column("payload_hash", sa.String(length=64), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.UniqueConstraint("tenant_id", "idempotency_key", name="uq_alarm_handling_commands_idem"),
|
||||||
|
sa.CheckConstraint("command IN ('claim', 'progress', 'close')", name="ck_alarm_handling_commands_command"),
|
||||||
|
sa.CheckConstraint("char_length(btrim(idempotency_key)) > 0", name="ck_alarm_handling_commands_key"),
|
||||||
|
sa.CheckConstraint("payload_hash ~ '^[0-9a-f]{64}$'", name="ck_alarm_handling_commands_hash"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_alarm_handling_commands_alarm_id", COMMANDS, ["alarm_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
BASIS,
|
||||||
|
sa.Column("id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), primary_key=True),
|
||||||
|
sa.Column("tenant_id", sa.String(length=64), nullable=False),
|
||||||
|
sa.Column("alarm_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("alarms.id", ondelete="RESTRICT"), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"original_occurrence_id",
|
||||||
|
postgresql.UUID(as_uuid=True),
|
||||||
|
sa.ForeignKey("alarm_occurrences.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"mapped_input_revision_id",
|
||||||
|
postgresql.UUID(as_uuid=True),
|
||||||
|
sa.ForeignKey("mapped_input_revisions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"mapping_version_id",
|
||||||
|
postgresql.UUID(as_uuid=True),
|
||||||
|
sa.ForeignKey("mapping_versions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"rule_version_id",
|
||||||
|
postgresql.UUID(as_uuid=True),
|
||||||
|
sa.ForeignKey("rule_versions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("snapshot_id", postgresql.UUID(as_uuid=True), nullable=False),
|
||||||
|
sa.Column("snapshot_version_no", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("cycle_key", sa.String(length=128), nullable=False),
|
||||||
|
sa.Column("event_key", sa.String(length=128), nullable=False),
|
||||||
|
sa.Column("observed_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("received_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("recorded_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.UniqueConstraint(
|
||||||
|
"tenant_id",
|
||||||
|
"mapped_input_revision_id",
|
||||||
|
"mapping_version_id",
|
||||||
|
"rule_version_id",
|
||||||
|
"snapshot_id",
|
||||||
|
"cycle_key",
|
||||||
|
"event_key",
|
||||||
|
"observed_at",
|
||||||
|
name="uq_alarm_closed_basis_formal_identity",
|
||||||
|
),
|
||||||
|
sa.CheckConstraint("snapshot_version_no >= 1", name="ck_alarm_closed_basis_snapshot_version"),
|
||||||
|
sa.CheckConstraint("char_length(btrim(cycle_key)) > 0", name="ck_alarm_closed_basis_cycle_key"),
|
||||||
|
sa.CheckConstraint("char_length(btrim(event_key)) > 0", name="ck_alarm_closed_basis_event_key"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_alarm_closed_basis_alarm_id", BASIS, ["alarm_id"])
|
||||||
|
|
||||||
|
for table in (EVENTS, COMMANDS, BASIS):
|
||||||
|
_enable_rls_insert_only(table)
|
||||||
|
_append_only(EVENTS, "alarm_handling_events_reject_mutation", "trg_alarm_handling_events_append_only", "alarm_handling_events is append-only")
|
||||||
|
_append_only(COMMANDS, "alarm_handling_commands_reject_mutation", "trg_alarm_handling_commands_append_only", "alarm_handling_commands is append-only")
|
||||||
|
_append_only(BASIS, "alarm_closed_basis_reject_mutation", "trg_alarm_closed_basis_append_only", "alarm_closed_basis is append-only")
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
for table, function, trigger in (
|
||||||
|
(BASIS, "alarm_closed_basis_reject_mutation", "trg_alarm_closed_basis_append_only"),
|
||||||
|
(COMMANDS, "alarm_handling_commands_reject_mutation", "trg_alarm_handling_commands_append_only"),
|
||||||
|
(EVENTS, "alarm_handling_events_reject_mutation", "trg_alarm_handling_events_append_only"),
|
||||||
|
):
|
||||||
|
op.execute(f"DROP TRIGGER IF EXISTS {trigger} ON {table}")
|
||||||
|
op.execute(f"DROP FUNCTION IF EXISTS {function}()")
|
||||||
|
for table in (BASIS, COMMANDS, EVENTS):
|
||||||
|
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {table}")
|
||||||
|
op.drop_index("ix_alarm_closed_basis_alarm_id", table_name=BASIS)
|
||||||
|
op.drop_table(BASIS)
|
||||||
|
op.drop_index("ix_alarm_handling_commands_alarm_id", table_name=COMMANDS)
|
||||||
|
op.drop_table(COMMANDS)
|
||||||
|
op.drop_index("ix_alarm_handling_events_alarm_id", table_name=EVENTS)
|
||||||
|
op.drop_table(EVENTS)
|
||||||
|
|
||||||
|
op.execute("DROP POLICY IF EXISTS tenant_isolation_definer ON alarms")
|
||||||
|
op.execute(
|
||||||
|
f"DROP FUNCTION IF EXISTS {TRANSITION_FUNCTION}(uuid, text, text, timestamptz, timestamptz, text)"
|
||||||
|
)
|
||||||
|
op.execute(f"DROP TRIGGER IF EXISTS {GUARD_TRIGGER} ON {ALARMS}")
|
||||||
|
op.execute(f"DROP FUNCTION IF EXISTS {GUARD_FUNCTION}()")
|
||||||
|
op.execute(f"REVOKE UPDATE (occurrence_count, last_occurred_at, updated_at) ON TABLE {ALARMS} FROM {APP_ROLE}")
|
||||||
|
op.execute(f"GRANT UPDATE ON TABLE {ALARMS} TO {APP_ROLE}")
|
||||||
|
op.drop_constraint("ck_alarms_processing_handler", ALARMS, type_="check")
|
||||||
|
op.drop_constraint("ck_alarms_pending_unassigned", ALARMS, type_="check")
|
||||||
|
op.drop_constraint("ck_alarms_close_result", ALARMS, type_="check")
|
||||||
|
op.drop_column(ALARMS, "close_result")
|
||||||
|
op.drop_column(ALARMS, "closed_at")
|
||||||
|
op.drop_column(ALARMS, "claimed_at")
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
"""Seed a few synthetic M06 alarms for local console demos.
|
||||||
|
|
||||||
|
Why: the Playwright demo used route mocks; the real DB starts empty, so the
|
||||||
|
logged-in console shows no rows. This script creates formal failures under a
|
||||||
|
synthetic mapping graph and puts the caller's Casdoor subject into the snapshot
|
||||||
|
handling scope so the list is visible.
|
||||||
|
Boundary: local/dev only; does not send notifications or create M08 scenarios.
|
||||||
|
Depends on alarm services, mappings, and the configured PostgreSQL tenant.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
from sqlalchemy import create_engine, select
|
||||||
|
from sqlalchemy.orm import Session, sessionmaker
|
||||||
|
|
||||||
|
from watchman.core.config import get_settings, reload_settings
|
||||||
|
from watchman.core.db import reset_engine, set_tenant
|
||||||
|
from watchman.models.auth_session import AuthSession
|
||||||
|
from watchman.models.datasource import DataSource
|
||||||
|
from watchman.models.mapping import MappedInput, MappedInputRevision
|
||||||
|
from watchman.models.query import QueryDefinition, QueryVersion
|
||||||
|
from watchman.services.alarms import FormalFailure, SyntheticPublishSnapshot, record_formal_failure
|
||||||
|
from watchman.services.mappings import create_mapping, persist_mapped_rows, save_mapping_version
|
||||||
|
from watchman.services.rules import create_rule, save_rule_version
|
||||||
|
|
||||||
|
FAKE_CIPHERTEXT = "gAAAA-demo-placeholder-ciphertext-not-a-secret"
|
||||||
|
|
||||||
|
|
||||||
|
def _is_test_login(login: str) -> bool:
|
||||||
|
return (
|
||||||
|
login in {"worker", "idem-admin"}
|
||||||
|
or login.startswith("worker-")
|
||||||
|
or login.startswith("idem-")
|
||||||
|
or login.startswith("Alarm")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _recent_subjects(session: Session, limit: int = 20) -> list[tuple[str, str]]:
|
||||||
|
rows = session.scalars(select(AuthSession).order_by(AuthSession.expires_at.desc()).limit(300)).all()
|
||||||
|
seen: dict[str, str] = {}
|
||||||
|
for row in rows:
|
||||||
|
login = (row.login_name or "").strip()
|
||||||
|
subject = (row.subject or "").strip()
|
||||||
|
if not subject or _is_test_login(login):
|
||||||
|
continue
|
||||||
|
seen.setdefault(subject, login or subject)
|
||||||
|
if len(seen) >= limit:
|
||||||
|
break
|
||||||
|
return list(seen.items())
|
||||||
|
|
||||||
|
|
||||||
|
def _build_graph(session: Session, tenant_id: str, label: str) -> tuple[uuid.UUID, uuid.UUID, uuid.UUID]:
|
||||||
|
serial = f"DEMO-{uuid.uuid4().hex[:8]}"
|
||||||
|
datasource = DataSource(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
name=f"demo-alarm-ds-{uuid.uuid4().hex[:8]}",
|
||||||
|
kind="database",
|
||||||
|
engine="postgresql",
|
||||||
|
host="127.0.0.1",
|
||||||
|
port=5432,
|
||||||
|
database_name="synthetic",
|
||||||
|
username="synthetic_user",
|
||||||
|
secret_ciphertext=FAKE_CIPHERTEXT,
|
||||||
|
)
|
||||||
|
session.add(datasource)
|
||||||
|
session.flush()
|
||||||
|
query = QueryDefinition(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
name=f"demo-alarm-query-{label}-{uuid.uuid4().hex[:6]}",
|
||||||
|
datasource_id=datasource.id,
|
||||||
|
draft_sql_template="SELECT 1",
|
||||||
|
current_version_no=1,
|
||||||
|
latest_published_version_no=1,
|
||||||
|
)
|
||||||
|
session.add(query)
|
||||||
|
session.flush()
|
||||||
|
session.add(
|
||||||
|
QueryVersion(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
definition_id=query.id,
|
||||||
|
version_no=1,
|
||||||
|
sql_template="SELECT 1",
|
||||||
|
param_schema=[],
|
||||||
|
output_schema=[
|
||||||
|
{"name": "serial", "type": "string"},
|
||||||
|
{"name": "temperature", "type": "number"},
|
||||||
|
],
|
||||||
|
allowed_identifiers=[],
|
||||||
|
timeout_ms=10000,
|
||||||
|
max_rows=100,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
session.flush()
|
||||||
|
definition = create_mapping(session, query_definition_id=str(query.id))
|
||||||
|
mapping_version = save_mapping_version(
|
||||||
|
session,
|
||||||
|
str(definition.id),
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"source_column_name": "serial",
|
||||||
|
"value_type": "string",
|
||||||
|
"is_identity": True,
|
||||||
|
"is_observation_time": False,
|
||||||
|
"numeric_multiply": None,
|
||||||
|
"numeric_offset": None,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source_column_name": "temperature",
|
||||||
|
"value_type": "number",
|
||||||
|
"is_identity": False,
|
||||||
|
"is_observation_time": False,
|
||||||
|
"numeric_multiply": None,
|
||||||
|
"numeric_offset": None,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
persist_mapped_rows(session, str(definition.id), [{"serial": serial, "temperature": 88}])
|
||||||
|
mapped = session.scalar(
|
||||||
|
select(MappedInput).where(MappedInput.mapping_definition_id == definition.id)
|
||||||
|
)
|
||||||
|
if mapped is None:
|
||||||
|
raise RuntimeError("mapped input missing after persist")
|
||||||
|
revision = session.scalar(
|
||||||
|
select(MappedInputRevision)
|
||||||
|
.where(MappedInputRevision.input_id == mapped.id)
|
||||||
|
.order_by(MappedInputRevision.revision_no.desc())
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
if revision is None:
|
||||||
|
raise RuntimeError("mapped revision missing after persist")
|
||||||
|
rule = create_rule(session, mapping_definition_id=str(definition.id))
|
||||||
|
rule_version = save_rule_version(
|
||||||
|
session,
|
||||||
|
str(rule.id),
|
||||||
|
{"column": "temperature", "operator": "gt", "value": 80},
|
||||||
|
)
|
||||||
|
return mapping_version.id, rule_version.id, revision.id
|
||||||
|
|
||||||
|
|
||||||
|
def seed(subjects: list[str]) -> list[str]:
|
||||||
|
reload_settings()
|
||||||
|
reset_engine()
|
||||||
|
settings = get_settings()
|
||||||
|
engine = create_engine(settings.database_url, pool_pre_ping=True)
|
||||||
|
factory = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False)
|
||||||
|
session = factory()
|
||||||
|
created: list[str] = []
|
||||||
|
try:
|
||||||
|
set_tenant(session, settings.tenant_id)
|
||||||
|
cases = [
|
||||||
|
("furnace", "furnace-overtemp", "炉温超限", "cycle-demo-a", "event-overheat"),
|
||||||
|
("utility", "air-pressure", "气压偏低", "cycle-demo-b", "event-pressure"),
|
||||||
|
("quality", "dimension", "尺寸超差", "cycle-demo-c", "event-dimension"),
|
||||||
|
]
|
||||||
|
base = datetime.now(timezone.utc) - timedelta(hours=2)
|
||||||
|
for index, (module_key, scenario_key, scenario_name, cycle_key, event_key) in enumerate(cases):
|
||||||
|
mapping_version_id, rule_version_id, revision_id = _build_graph(
|
||||||
|
session, settings.tenant_id, scenario_key
|
||||||
|
)
|
||||||
|
observed = base + timedelta(minutes=15 * index)
|
||||||
|
result = record_formal_failure(
|
||||||
|
session,
|
||||||
|
FormalFailure(
|
||||||
|
mapped_input_revision_id=revision_id,
|
||||||
|
snapshot=SyntheticPublishSnapshot(
|
||||||
|
snapshot_id=uuid.uuid4(),
|
||||||
|
version_no=1,
|
||||||
|
module_key=module_key,
|
||||||
|
scenario_key=scenario_key,
|
||||||
|
scenario_name=scenario_name,
|
||||||
|
handling_scope={
|
||||||
|
"principals": [
|
||||||
|
{"kind": "subject", "value": subject} for subject in subjects
|
||||||
|
],
|
||||||
|
},
|
||||||
|
mapping_version_id=mapping_version_id,
|
||||||
|
rule_version_id=rule_version_id,
|
||||||
|
),
|
||||||
|
observed_at=observed,
|
||||||
|
received_at=observed + timedelta(seconds=5),
|
||||||
|
cycle_key=cycle_key,
|
||||||
|
event_key=event_key,
|
||||||
|
),
|
||||||
|
confirmed_abnormal=True,
|
||||||
|
)
|
||||||
|
if result is None or result.alarm_id is None:
|
||||||
|
raise RuntimeError(f"failed to create alarm for {scenario_key}")
|
||||||
|
created.append(str(result.alarm_id))
|
||||||
|
session.commit()
|
||||||
|
return created
|
||||||
|
except Exception:
|
||||||
|
session.rollback()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
parser = argparse.ArgumentParser(description="Seed local demo alarms visible to named subjects.")
|
||||||
|
parser.add_argument(
|
||||||
|
"--subject",
|
||||||
|
action="append",
|
||||||
|
default=[],
|
||||||
|
help="Casdoor subject that should see the alarms. Repeatable.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--from-sessions",
|
||||||
|
action="store_true",
|
||||||
|
help="Also include recent non-test auth_session subjects.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--list-sessions",
|
||||||
|
action="store_true",
|
||||||
|
help="Only list recent non-test sessions, then exit.",
|
||||||
|
)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
reload_settings()
|
||||||
|
reset_engine()
|
||||||
|
settings = get_settings()
|
||||||
|
engine = create_engine(settings.database_url, pool_pre_ping=True)
|
||||||
|
session = sessionmaker(bind=engine)()
|
||||||
|
subjects: list[str] = []
|
||||||
|
try:
|
||||||
|
set_tenant(session, settings.tenant_id)
|
||||||
|
found = _recent_subjects(session)
|
||||||
|
print("recent non-test sessions:")
|
||||||
|
if not found:
|
||||||
|
print(" (none)")
|
||||||
|
for subject, login in found:
|
||||||
|
print(f" subject={subject} login={login}")
|
||||||
|
if args.list_sessions:
|
||||||
|
return
|
||||||
|
if args.from_sessions:
|
||||||
|
subjects.extend(subject for subject, _login in found)
|
||||||
|
subjects.extend(args.subject)
|
||||||
|
cleaned: list[str] = []
|
||||||
|
for item in subjects:
|
||||||
|
value = item.strip()
|
||||||
|
if value and value not in cleaned:
|
||||||
|
cleaned.append(value)
|
||||||
|
if not cleaned:
|
||||||
|
print(
|
||||||
|
"No subjects provided. Log into the console once, then re-run with "
|
||||||
|
"--from-sessions, or pass --subject <casdoor-sub>."
|
||||||
|
)
|
||||||
|
raise SystemExit(2)
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
alarm_ids = seed(cleaned)
|
||||||
|
print(f"seeded {len(alarm_ids)} alarms for subjects: {cleaned}")
|
||||||
|
for alarm_id in alarm_ids:
|
||||||
|
print(f" alarm_id={alarm_id}")
|
||||||
|
print("Refresh http://127.0.0.1:5173/#/alarms and click 查询.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"""FastAPI application factory.
|
"""FastAPI application factory.
|
||||||
|
|
||||||
Registers envelope middleware and global exception handlers.
|
Registers envelope middleware, global exception handlers, and the HTTP routers.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -10,7 +10,7 @@ from fastapi.exceptions import RequestValidationError
|
|||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
from starlette.middleware.base import BaseHTTPMiddleware
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
|
|
||||||
from watchman.api.routes import auth, datasources, health, mappings, platform, queries
|
from watchman.api.routes import alarms, auth, datasources, health, mappings, platform, queries
|
||||||
from watchman.core.config import ensure_runtime_config, get_settings, is_non_production
|
from watchman.core.config import ensure_runtime_config, get_settings, is_non_production
|
||||||
from watchman.core.errors import AppError, ValidationError
|
from watchman.core.errors import AppError, ValidationError
|
||||||
from watchman.core.request_id import REQUEST_ID_HEADER, resolve_request_id
|
from watchman.core.request_id import REQUEST_ID_HEADER, resolve_request_id
|
||||||
@@ -80,6 +80,7 @@ def create_app(*, validate_runtime: bool = True) -> FastAPI:
|
|||||||
app.include_router(datasources.router)
|
app.include_router(datasources.router)
|
||||||
app.include_router(queries.router)
|
app.include_router(queries.router)
|
||||||
app.include_router(mappings.router)
|
app.include_router(mappings.router)
|
||||||
|
app.include_router(alarms.router)
|
||||||
|
|
||||||
@app.exception_handler(AppError)
|
@app.exception_handler(AppError)
|
||||||
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
|
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
|
||||||
|
|||||||
@@ -0,0 +1,300 @@
|
|||||||
|
"""Alarm list, detail, and handling command routes.
|
||||||
|
|
||||||
|
Why: the console needs scoped reads and three idempotent commands without a
|
||||||
|
frontend permission bypass. Filters are applied only when the client sends them.
|
||||||
|
Boundary: checks the approved alarm nodes, then snapshot subject scope. It does
|
||||||
|
not hand-write error JSON, invent a role, or accept tenant_id from the caller.
|
||||||
|
Depends on alarm reads and the handling service.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Annotated, Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Header, Request
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field, StringConstraints
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from watchman.auth.access import ALARM_CLOSE_NODE, ALARM_PROGRESS_NODE, ALARM_TAKE_NODE
|
||||||
|
from watchman.auth.principal import (
|
||||||
|
AlarmCaller,
|
||||||
|
require_alarm_closer,
|
||||||
|
require_alarm_progress_writer,
|
||||||
|
require_alarm_reader,
|
||||||
|
require_alarm_taker,
|
||||||
|
)
|
||||||
|
from watchman.core.db import get_db_session
|
||||||
|
from watchman.core.errors import ForbiddenError, ValidationError
|
||||||
|
from watchman.core.response import success_body
|
||||||
|
from watchman.services import alarm_reads
|
||||||
|
from watchman.services.alarm_handling import (
|
||||||
|
HandlingActor,
|
||||||
|
HandlingResult,
|
||||||
|
append_progress,
|
||||||
|
claim_alarm,
|
||||||
|
close_alarm,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/alarms", tags=["alarms"])
|
||||||
|
|
||||||
|
# GUARD: reject an over-long key here. The handling service truncates at 128.
|
||||||
|
_IDEMPOTENCY_KEY_MAX = 128
|
||||||
|
Note = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=2000)]
|
||||||
|
EvidenceRef = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=512)]
|
||||||
|
|
||||||
|
|
||||||
|
class EmptyBody(BaseModel):
|
||||||
|
"""Claim has no business fields. Unknown fields, including tenant_id, are rejected."""
|
||||||
|
|
||||||
|
model_config = ConfigDict(extra="forbid")
|
||||||
|
|
||||||
|
|
||||||
|
class ProgressBody(BaseModel):
|
||||||
|
"""One appended note. It cannot carry a status or a handler."""
|
||||||
|
|
||||||
|
model_config = ConfigDict(extra="forbid")
|
||||||
|
|
||||||
|
note: Note
|
||||||
|
evidence_ref: EvidenceRef | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class CloseBody(BaseModel):
|
||||||
|
"""Close result and required note. Status is not accepted from the client."""
|
||||||
|
|
||||||
|
model_config = ConfigDict(extra="forbid")
|
||||||
|
|
||||||
|
result: str = Field(pattern="^(resolved|false_positive)$")
|
||||||
|
note: Note
|
||||||
|
evidence_ref: EvidenceRef | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def _ok(request: Request, data: Any) -> JSONResponse:
|
||||||
|
return JSONResponse(content=success_body(data, request_id=request.state.request_id))
|
||||||
|
|
||||||
|
|
||||||
|
def _command_key(value: str | None) -> str:
|
||||||
|
"""Require x-idempotency-key and refuse a value the column would truncate."""
|
||||||
|
if value is None or not value.strip():
|
||||||
|
raise ValidationError(
|
||||||
|
"x-idempotency-key is required",
|
||||||
|
details={"field": "x-idempotency-key", "reason": "idempotency_key_required"},
|
||||||
|
)
|
||||||
|
cleaned = value.strip()
|
||||||
|
if len(cleaned) > _IDEMPOTENCY_KEY_MAX:
|
||||||
|
raise ValidationError(
|
||||||
|
"x-idempotency-key is too long",
|
||||||
|
details={
|
||||||
|
"field": "x-idempotency-key",
|
||||||
|
"reason": "idempotency_key_too_long",
|
||||||
|
"max": _IDEMPOTENCY_KEY_MAX,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
|
def _actor(caller: AlarmCaller, node: str) -> HandlingActor:
|
||||||
|
"""Build the handling actor only when the session has an explicit subject.
|
||||||
|
|
||||||
|
A blank subject is not an operator-wide grant. The role check already ran.
|
||||||
|
"""
|
||||||
|
subject = alarm_reads.scope_subject(caller.subject)
|
||||||
|
if subject is None:
|
||||||
|
raise ForbiddenError(
|
||||||
|
"Alarm handling requires an explicit snapshot subject",
|
||||||
|
permission_node=node,
|
||||||
|
)
|
||||||
|
return HandlingActor(subject=subject, roles=caller.roles)
|
||||||
|
|
||||||
|
|
||||||
|
def _command_data(result: HandlingResult) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"alarm_id": str(result.alarm_id),
|
||||||
|
"event_id": str(result.event_id),
|
||||||
|
"command": result.command,
|
||||||
|
"status": result.status,
|
||||||
|
"current_handler": result.current_handler,
|
||||||
|
"close_result": result.close_result,
|
||||||
|
"replayed": result.replayed,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _reader_subject(caller: AlarmCaller) -> str | None:
|
||||||
|
return alarm_reads.scope_subject(caller.subject)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_command_id(alarm_id: str) -> uuid.UUID:
|
||||||
|
"""Parse an id that visibility already accepted, so the service receives a UUID."""
|
||||||
|
return uuid.UUID(alarm_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def list_alarms(
|
||||||
|
request: Request,
|
||||||
|
module_key: str | None = None,
|
||||||
|
scenario_key: str | None = None,
|
||||||
|
scenario_name: str | None = None,
|
||||||
|
status: str | None = None,
|
||||||
|
mapped_input_id: str | None = None,
|
||||||
|
occurred_from: datetime | None = None,
|
||||||
|
occurred_to: datetime | None = None,
|
||||||
|
sort_by: str = "last_occurred_at",
|
||||||
|
sort_order: str = "desc",
|
||||||
|
page: int = 1,
|
||||||
|
page_size: int = 20,
|
||||||
|
caller: AlarmCaller = Depends(require_alarm_reader),
|
||||||
|
session: Session = Depends(get_db_session),
|
||||||
|
) -> JSONResponse:
|
||||||
|
"""List alarms inside the caller's snapshot subjects. Sort and page in SQL."""
|
||||||
|
# GUARD: do not read a tenant_id query parameter. Scope comes from the session subject.
|
||||||
|
result = alarm_reads.search_alarms(
|
||||||
|
session,
|
||||||
|
subject=_reader_subject(caller),
|
||||||
|
module_key=module_key,
|
||||||
|
scenario_key=scenario_key,
|
||||||
|
scenario_name=scenario_name,
|
||||||
|
status=status,
|
||||||
|
mapped_input_id=mapped_input_id,
|
||||||
|
occurred_from=occurred_from,
|
||||||
|
occurred_to=occurred_to,
|
||||||
|
sort_by=sort_by,
|
||||||
|
sort_order=sort_order,
|
||||||
|
page=page,
|
||||||
|
page_size=page_size,
|
||||||
|
)
|
||||||
|
return _ok(request, result)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{alarm_id}")
|
||||||
|
def get_alarm(
|
||||||
|
request: Request,
|
||||||
|
alarm_id: str,
|
||||||
|
caller: AlarmCaller = Depends(require_alarm_reader),
|
||||||
|
session: Session = Depends(get_db_session),
|
||||||
|
) -> JSONResponse:
|
||||||
|
"""Return one alarm. An id outside the snapshot scope is not found."""
|
||||||
|
return _ok(request, alarm_reads.get_alarm(session, alarm_id, _reader_subject(caller)))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{alarm_id}/occurrences")
|
||||||
|
def get_alarm_occurrences(
|
||||||
|
request: Request,
|
||||||
|
alarm_id: str,
|
||||||
|
caller: AlarmCaller = Depends(require_alarm_reader),
|
||||||
|
session: Session = Depends(get_db_session),
|
||||||
|
) -> JSONResponse:
|
||||||
|
"""Return formal occurrences for one visible alarm."""
|
||||||
|
return _ok(request, alarm_reads.list_occurrences(session, alarm_id, _reader_subject(caller)))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{alarm_id}/evidence")
|
||||||
|
def get_alarm_evidence(
|
||||||
|
request: Request,
|
||||||
|
alarm_id: str,
|
||||||
|
caller: AlarmCaller = Depends(require_alarm_reader),
|
||||||
|
session: Session = Depends(get_db_session),
|
||||||
|
) -> JSONResponse:
|
||||||
|
"""Return revision evidence and closed-repeat basis. Neither means recovered."""
|
||||||
|
return _ok(request, alarm_reads.list_evidence(session, alarm_id, _reader_subject(caller)))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{alarm_id}/history")
|
||||||
|
def get_alarm_history(
|
||||||
|
request: Request,
|
||||||
|
alarm_id: str,
|
||||||
|
caller: AlarmCaller = Depends(require_alarm_reader),
|
||||||
|
session: Session = Depends(get_db_session),
|
||||||
|
) -> JSONResponse:
|
||||||
|
"""Return append-only handling history for one visible alarm."""
|
||||||
|
return _ok(request, alarm_reads.list_history(session, alarm_id, _reader_subject(caller)))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{alarm_id}/close-validity")
|
||||||
|
def get_alarm_close_validity(
|
||||||
|
request: Request,
|
||||||
|
alarm_id: str,
|
||||||
|
caller: AlarmCaller = Depends(require_alarm_reader),
|
||||||
|
session: Session = Depends(get_db_session),
|
||||||
|
) -> JSONResponse:
|
||||||
|
"""Return the derived close flag after the scope check."""
|
||||||
|
return _ok(
|
||||||
|
request,
|
||||||
|
alarm_reads.read_close_validity(session, alarm_id, _reader_subject(caller)),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{alarm_id}/claim")
|
||||||
|
def post_claim(
|
||||||
|
request: Request,
|
||||||
|
alarm_id: str,
|
||||||
|
body: EmptyBody | None = None,
|
||||||
|
caller: AlarmCaller = Depends(require_alarm_taker),
|
||||||
|
session: Session = Depends(get_db_session),
|
||||||
|
x_idempotency_key: str | None = Header(default=None, alias="x-idempotency-key"),
|
||||||
|
) -> JSONResponse:
|
||||||
|
"""Claim one in-scope pending alarm. A repeated key returns the original event."""
|
||||||
|
del body
|
||||||
|
actor = _actor(caller, ALARM_TAKE_NODE)
|
||||||
|
alarm_reads.get_alarm(session, alarm_id, actor.subject)
|
||||||
|
result = claim_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=_parse_command_id(alarm_id),
|
||||||
|
actor=actor,
|
||||||
|
idempotency_key=_command_key(x_idempotency_key),
|
||||||
|
)
|
||||||
|
data = _command_data(result)
|
||||||
|
session.commit()
|
||||||
|
return _ok(request, data)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{alarm_id}/progress")
|
||||||
|
def post_progress(
|
||||||
|
request: Request,
|
||||||
|
alarm_id: str,
|
||||||
|
body: ProgressBody,
|
||||||
|
caller: AlarmCaller = Depends(require_alarm_progress_writer),
|
||||||
|
session: Session = Depends(get_db_session),
|
||||||
|
x_idempotency_key: str | None = Header(default=None, alias="x-idempotency-key"),
|
||||||
|
) -> JSONResponse:
|
||||||
|
"""Append one progress note for the current handler."""
|
||||||
|
actor = _actor(caller, ALARM_PROGRESS_NODE)
|
||||||
|
alarm_reads.get_alarm(session, alarm_id, actor.subject)
|
||||||
|
result = append_progress(
|
||||||
|
session,
|
||||||
|
alarm_id=_parse_command_id(alarm_id),
|
||||||
|
actor=actor,
|
||||||
|
note=body.note,
|
||||||
|
evidence_ref=body.evidence_ref,
|
||||||
|
idempotency_key=_command_key(x_idempotency_key),
|
||||||
|
)
|
||||||
|
data = _command_data(result)
|
||||||
|
session.commit()
|
||||||
|
return _ok(request, data)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{alarm_id}/close")
|
||||||
|
def post_close(
|
||||||
|
request: Request,
|
||||||
|
alarm_id: str,
|
||||||
|
body: CloseBody,
|
||||||
|
caller: AlarmCaller = Depends(require_alarm_closer),
|
||||||
|
session: Session = Depends(get_db_session),
|
||||||
|
x_idempotency_key: str | None = Header(default=None, alias="x-idempotency-key"),
|
||||||
|
) -> JSONResponse:
|
||||||
|
"""Close as resolved or false_positive. Same content with a new key replays (D37)."""
|
||||||
|
actor = _actor(caller, ALARM_CLOSE_NODE)
|
||||||
|
alarm_reads.get_alarm(session, alarm_id, actor.subject)
|
||||||
|
result = close_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=_parse_command_id(alarm_id),
|
||||||
|
actor=actor,
|
||||||
|
result=body.result,
|
||||||
|
note=body.note,
|
||||||
|
evidence_ref=body.evidence_ref,
|
||||||
|
idempotency_key=_command_key(x_idempotency_key),
|
||||||
|
)
|
||||||
|
data = _command_data(result)
|
||||||
|
session.commit()
|
||||||
|
return _ok(request, data)
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
"""Role checks for the Watchman permission nodes.
|
"""Role checks for the Watchman permission nodes.
|
||||||
|
|
||||||
Decides enter, platform write, object read, and the three datasource nodes (read,
|
Decides enter, platform write, object read, datasource, query, mapping, and the
|
||||||
write, test) and the four query nodes (read, write, publish, preview) from Casdoor role names.
|
four approved alarm nodes from the existing Casdoor role names.
|
||||||
Depends on semantic errors only; it does not call Casdoor or open a session.
|
Depends on semantic errors only; it does not call Casdoor or open a session.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -25,6 +25,12 @@ MAPPING_READ_NODE = "perm:data:emp:watchman.mapping.read"
|
|||||||
MAPPING_WRITE_NODE = "perm:data:emp:watchman.mapping.write"
|
MAPPING_WRITE_NODE = "perm:data:emp:watchman.mapping.write"
|
||||||
MAPPING_TRIAL_NODE = "perm:data:emp:watchman.mapping.trial"
|
MAPPING_TRIAL_NODE = "perm:data:emp:watchman.mapping.trial"
|
||||||
|
|
||||||
|
# GUARD: these four literals are D38. Do not add another alarm permission node here.
|
||||||
|
ALARM_READ_NODE = "perm:data:emp:watchman.alarm.read"
|
||||||
|
ALARM_TAKE_NODE = "perm:data:emp:watchman.alarm.take"
|
||||||
|
ALARM_PROGRESS_NODE = "perm:data:emp:watchman.alarm.progress"
|
||||||
|
ALARM_CLOSE_NODE = "perm:data:emp:watchman.alarm.close"
|
||||||
|
|
||||||
ROLE_ADMIN = "watchman-admin"
|
ROLE_ADMIN = "watchman-admin"
|
||||||
ROLE_OPERATOR = "watchman-operator"
|
ROLE_OPERATOR = "watchman-operator"
|
||||||
ROLE_VIEWER = "watchman-viewer"
|
ROLE_VIEWER = "watchman-viewer"
|
||||||
@@ -115,6 +121,43 @@ def require_mapping_trial(role_names: list[str]) -> None:
|
|||||||
raise ForbiddenError(permission_node=MAPPING_TRIAL_NODE)
|
raise ForbiddenError(permission_node=MAPPING_TRIAL_NODE)
|
||||||
|
|
||||||
|
|
||||||
|
def require_alarm_read(role_names: list[str]) -> None:
|
||||||
|
"""Allow alarm reads for the three existing roles.
|
||||||
|
|
||||||
|
Viewer, operator, and admin may read. An empty or unknown role list is
|
||||||
|
denied with the alarm read node. Snapshot scope is a separate check.
|
||||||
|
"""
|
||||||
|
if not ENTER_ROLES.intersection(role_names):
|
||||||
|
raise ForbiddenError(permission_node=ALARM_READ_NODE)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_alarm_handler(role_names: list[str], node: str) -> None:
|
||||||
|
"""Allow a handling command for operator or admin, and name the missing node.
|
||||||
|
|
||||||
|
Viewer stays read-only. This does not grant a snapshot scope or a new role.
|
||||||
|
"""
|
||||||
|
if ROLE_ADMIN not in role_names and ROLE_OPERATOR not in role_names:
|
||||||
|
raise ForbiddenError(permission_node=node)
|
||||||
|
|
||||||
|
|
||||||
|
def require_alarm_take(role_names: list[str]) -> None:
|
||||||
|
"""Allow claim only for operator or admin."""
|
||||||
|
_require_alarm_handler(role_names, ALARM_TAKE_NODE)
|
||||||
|
|
||||||
|
|
||||||
|
def require_alarm_progress(role_names: list[str]) -> None:
|
||||||
|
"""Allow a progress note only for operator or admin."""
|
||||||
|
_require_alarm_handler(role_names, ALARM_PROGRESS_NODE)
|
||||||
|
|
||||||
|
|
||||||
|
def require_alarm_close(role_names: list[str]) -> None:
|
||||||
|
"""Allow a close attempt only for operator or admin.
|
||||||
|
|
||||||
|
The current-handler rule is enforced by the handling service, not here.
|
||||||
|
"""
|
||||||
|
_require_alarm_handler(role_names, ALARM_CLOSE_NODE)
|
||||||
|
|
||||||
|
|
||||||
def require_object_access(role_names: list[str], object_id: str) -> None:
|
def require_object_access(role_names: list[str], object_id: str) -> None:
|
||||||
"""Reject every object id until a later module grants row access.
|
"""Reject every object id until a later module grants row access.
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
"""Reload Casdoor roles for a login name without keeping a user token.
|
"""Reload Casdoor roles for a login name without keeping a user token.
|
||||||
|
|
||||||
Uses the application client to read one user. Tests replace the transport.
|
Uses the application client to read one user. Tests replace the transport.
|
||||||
|
Session gates for datasource, query, mapping, and alarm actions live here too.
|
||||||
Depends on settings and the shared HTTP transport used by password login.
|
Depends on settings and the shared HTTP transport used by password login.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import base64
|
import base64
|
||||||
|
from dataclasses import dataclass
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from typing import Protocol
|
from typing import Protocol
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
@@ -15,6 +17,10 @@ from fastapi import Cookie, Depends, Request
|
|||||||
|
|
||||||
from watchman.auth.casdoor import DefaultCasdoorPort, UrllibCasdoorHttpTransport
|
from watchman.auth.casdoor import DefaultCasdoorPort, UrllibCasdoorHttpTransport
|
||||||
from watchman.auth.access import (
|
from watchman.auth.access import (
|
||||||
|
require_alarm_close,
|
||||||
|
require_alarm_progress,
|
||||||
|
require_alarm_read,
|
||||||
|
require_alarm_take,
|
||||||
require_datasource_read,
|
require_datasource_read,
|
||||||
require_datasource_test,
|
require_datasource_test,
|
||||||
require_datasource_write,
|
require_datasource_write,
|
||||||
@@ -136,8 +142,8 @@ def _load_session(
|
|||||||
session_token: str | None,
|
session_token: str | None,
|
||||||
sessions: SessionStore,
|
sessions: SessionStore,
|
||||||
directory: RoleDirectory,
|
directory: RoleDirectory,
|
||||||
) -> tuple[str, list[str]]:
|
) -> tuple[str, str, list[str]]:
|
||||||
"""Return (login_name, fresh role names) for the caller's session, or raise 41000 / 503.
|
"""Return (subject, login_name, fresh roles) or raise 41000 / 503.
|
||||||
|
|
||||||
Same session and freshness rules as require_platform_writer: a stale snapshot is
|
Same session and freshness rules as require_platform_writer: a stale snapshot is
|
||||||
reloaded from Casdoor and, if that fails, the old roles are not used.
|
reloaded from Casdoor and, if that fails, the old roles are not used.
|
||||||
@@ -153,7 +159,7 @@ def _load_session(
|
|||||||
if now - row.role_checked_at >= ROLE_FRESHNESS:
|
if now - row.role_checked_at >= ROLE_FRESHNESS:
|
||||||
roles = directory.lookup_roles(login_name=row.login_name)
|
roles = directory.lookup_roles(login_name=row.login_name)
|
||||||
sessions.update_roles(token_hash=row.token_hash, role_names=roles, now=now)
|
sessions.update_roles(token_hash=row.token_hash, role_names=roles, now=now)
|
||||||
return row.login_name, roles
|
return row.subject, row.login_name, roles
|
||||||
|
|
||||||
|
|
||||||
def _load_session_roles(
|
def _load_session_roles(
|
||||||
@@ -163,7 +169,7 @@ def _load_session_roles(
|
|||||||
directory: RoleDirectory,
|
directory: RoleDirectory,
|
||||||
) -> list[str]:
|
) -> list[str]:
|
||||||
"""Return fresh role names for the caller's session, or raise 41000 / 503."""
|
"""Return fresh role names for the caller's session, or raise 41000 / 503."""
|
||||||
return _load_session(request, session_token, sessions, directory)[1]
|
return _load_session(request, session_token, sessions, directory)[2]
|
||||||
|
|
||||||
|
|
||||||
def require_datasource_reader(
|
def require_datasource_reader(
|
||||||
@@ -223,7 +229,7 @@ def require_query_publisher(
|
|||||||
directory: RoleDirectory = Depends(get_role_directory),
|
directory: RoleDirectory = Depends(get_role_directory),
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Reject a publish unless the session is admin; return the login name to record."""
|
"""Reject a publish unless the session is admin; return the login name to record."""
|
||||||
login_name, roles = _load_session(request, session_token, sessions, directory)
|
_subject, login_name, roles = _load_session(request, session_token, sessions, directory)
|
||||||
require_query_publish(roles)
|
require_query_publish(roles)
|
||||||
return login_name
|
return login_name
|
||||||
|
|
||||||
@@ -260,3 +266,77 @@ def require_mapping_trialer(
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""Reject mapping trials unless the session is watchman-admin."""
|
"""Reject mapping trials unless the session is watchman-admin."""
|
||||||
require_mapping_trial(_load_session_roles(request, session_token, sessions, directory))
|
require_mapping_trial(_load_session_roles(request, session_token, sessions, directory))
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class AlarmCaller:
|
||||||
|
"""Session identity for an alarm route.
|
||||||
|
|
||||||
|
`subject` is the snapshot scope key. `roles` are the existing three names
|
||||||
|
after a fresh load. This object does not by itself grant a row.
|
||||||
|
"""
|
||||||
|
|
||||||
|
subject: str
|
||||||
|
roles: tuple[str, ...]
|
||||||
|
|
||||||
|
|
||||||
|
def _alarm_caller(
|
||||||
|
request: Request,
|
||||||
|
session_token: str | None,
|
||||||
|
sessions: SessionStore,
|
||||||
|
directory: RoleDirectory,
|
||||||
|
) -> AlarmCaller:
|
||||||
|
"""Load the session subject and roles. A missing session is 41000, not an empty scope."""
|
||||||
|
subject, _login_name, roles = _load_session(request, session_token, sessions, directory)
|
||||||
|
return AlarmCaller(subject=subject, roles=tuple(roles))
|
||||||
|
|
||||||
|
|
||||||
|
def require_alarm_reader(
|
||||||
|
request: Request,
|
||||||
|
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
|
||||||
|
sessions: SessionStore = Depends(get_session_store),
|
||||||
|
directory: RoleDirectory = Depends(get_role_directory),
|
||||||
|
) -> AlarmCaller:
|
||||||
|
"""Reject alarm reads unless the session holds one of the three existing roles."""
|
||||||
|
caller = _alarm_caller(request, session_token, sessions, directory)
|
||||||
|
require_alarm_read(list(caller.roles))
|
||||||
|
return caller
|
||||||
|
|
||||||
|
|
||||||
|
def require_alarm_taker(
|
||||||
|
request: Request,
|
||||||
|
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
|
||||||
|
sessions: SessionStore = Depends(get_session_store),
|
||||||
|
directory: RoleDirectory = Depends(get_role_directory),
|
||||||
|
) -> AlarmCaller:
|
||||||
|
"""Reject a claim unless the session is operator or admin."""
|
||||||
|
caller = _alarm_caller(request, session_token, sessions, directory)
|
||||||
|
require_alarm_take(list(caller.roles))
|
||||||
|
return caller
|
||||||
|
|
||||||
|
|
||||||
|
def require_alarm_progress_writer(
|
||||||
|
request: Request,
|
||||||
|
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
|
||||||
|
sessions: SessionStore = Depends(get_session_store),
|
||||||
|
directory: RoleDirectory = Depends(get_role_directory),
|
||||||
|
) -> AlarmCaller:
|
||||||
|
"""Reject a progress note unless the session is operator or admin."""
|
||||||
|
caller = _alarm_caller(request, session_token, sessions, directory)
|
||||||
|
require_alarm_progress(list(caller.roles))
|
||||||
|
return caller
|
||||||
|
|
||||||
|
|
||||||
|
def require_alarm_closer(
|
||||||
|
request: Request,
|
||||||
|
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
|
||||||
|
sessions: SessionStore = Depends(get_session_store),
|
||||||
|
directory: RoleDirectory = Depends(get_role_directory),
|
||||||
|
) -> AlarmCaller:
|
||||||
|
"""Reject a close attempt unless the session is operator or admin.
|
||||||
|
|
||||||
|
Being in this dependency does not make the caller the current handler.
|
||||||
|
"""
|
||||||
|
caller = _alarm_caller(request, session_token, sessions, directory)
|
||||||
|
require_alarm_close(list(caller.roles))
|
||||||
|
return caller
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
"""SQLAlchemy models for the Watchman service package."""
|
"""SQLAlchemy models for the Watchman service package."""
|
||||||
|
|
||||||
|
from watchman.models.alarm import Alarm, AlarmOccurrence, AlarmRevisionEvidence
|
||||||
|
from watchman.models.alarm_handling import AlarmClosedBasis, AlarmHandlingCommand, AlarmHandlingEvent
|
||||||
from watchman.models.auth_session import AuthSession
|
from watchman.models.auth_session import AuthSession
|
||||||
from watchman.models.datasource import DataSource
|
from watchman.models.datasource import DataSource
|
||||||
from watchman.models.mapping import MappingColumnConfig, MappingDefinition, MappingVersion
|
from watchman.models.mapping import MappingColumnConfig, MappingDefinition, MappingVersion
|
||||||
@@ -7,6 +9,12 @@ from watchman.models.platform import AuditEvent, RunRecord
|
|||||||
from watchman.models.query import QueryDefinition, QueryVersion
|
from watchman.models.query import QueryDefinition, QueryVersion
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
|
"Alarm",
|
||||||
|
"AlarmClosedBasis",
|
||||||
|
"AlarmHandlingCommand",
|
||||||
|
"AlarmHandlingEvent",
|
||||||
|
"AlarmOccurrence",
|
||||||
|
"AlarmRevisionEvidence",
|
||||||
"AuthSession",
|
"AuthSession",
|
||||||
"AuditEvent",
|
"AuditEvent",
|
||||||
"DataSource",
|
"DataSource",
|
||||||
|
|||||||
@@ -0,0 +1,325 @@
|
|||||||
|
"""Tenant-scoped alarm facts, formal occurrences, and same-cycle revision evidence.
|
||||||
|
|
||||||
|
Boundary: stores fact rows and the current handling projection. Claim, progress,
|
||||||
|
and close decisions live in the handling service; this module does not notify
|
||||||
|
or count escalation windows. Depends on M05 inputs, mapping versions, and rule versions.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import (
|
||||||
|
CheckConstraint,
|
||||||
|
DateTime,
|
||||||
|
ForeignKey,
|
||||||
|
Index,
|
||||||
|
Integer,
|
||||||
|
String,
|
||||||
|
UniqueConstraint,
|
||||||
|
func,
|
||||||
|
text,
|
||||||
|
)
|
||||||
|
from sqlalchemy.dialects.postgresql import JSONB, UUID
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from watchman.models.base import Base
|
||||||
|
|
||||||
|
# Status values are stored for the later handling slice. S1 only inserts pending.
|
||||||
|
ALARM_STATUS_PENDING = "pending"
|
||||||
|
ALARM_STATUS_PROCESSING = "processing"
|
||||||
|
ALARM_STATUS_CLOSED = "closed"
|
||||||
|
ALARM_STATUSES = (
|
||||||
|
ALARM_STATUS_PENDING,
|
||||||
|
ALARM_STATUS_PROCESSING,
|
||||||
|
ALARM_STATUS_CLOSED,
|
||||||
|
)
|
||||||
|
|
||||||
|
# D33 close results. These two literals are the whole set.
|
||||||
|
ALARM_CLOSE_RESOLVED = "resolved"
|
||||||
|
ALARM_CLOSE_FALSE_POSITIVE = "false_positive"
|
||||||
|
ALARM_CLOSE_RESULTS = (
|
||||||
|
ALARM_CLOSE_RESOLVED,
|
||||||
|
ALARM_CLOSE_FALSE_POSITIVE,
|
||||||
|
)
|
||||||
|
|
||||||
|
# GUARD: handling scope must name at least one subject. This layout is an
|
||||||
|
# implementation assumption, not a new confirmed authorization model.
|
||||||
|
_SCOPE_SQL = (
|
||||||
|
"jsonb_typeof(handling_scope) = 'object' "
|
||||||
|
"AND NOT jsonb_exists(handling_scope, 'all_tenant') "
|
||||||
|
"AND jsonb_typeof(handling_scope -> 'principals') = 'array' "
|
||||||
|
"AND jsonb_array_length(handling_scope -> 'principals') >= 1"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Alarm(Base):
|
||||||
|
"""One bounded alarm for a structured subject, cycle, and independent event.
|
||||||
|
|
||||||
|
Mutable for occurrence counters, last-seen time, and the handling projection.
|
||||||
|
Status, handler, and close columns move only through the handling transition
|
||||||
|
function; a direct update is rejected. Merge identity is the structured key,
|
||||||
|
never message text. Writers must hold the subject advisory lock.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "alarms"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint(
|
||||||
|
"tenant_id",
|
||||||
|
"module_key",
|
||||||
|
"scenario_key",
|
||||||
|
"mapped_input_id",
|
||||||
|
"cycle_key",
|
||||||
|
"event_key",
|
||||||
|
name="uq_alarms_structured_merge_key",
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"status IN ('pending', 'processing', 'closed')",
|
||||||
|
name="ck_alarms_status",
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"close_result IS NULL OR close_result IN ('resolved', 'false_positive')",
|
||||||
|
name="ck_alarms_close_result",
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"status <> 'pending' OR current_handler IS NULL",
|
||||||
|
name="ck_alarms_pending_unassigned",
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"status <> 'processing' OR current_handler IS NOT NULL",
|
||||||
|
name="ck_alarms_processing_handler",
|
||||||
|
),
|
||||||
|
CheckConstraint("occurrence_count >= 1", name="ck_alarms_occurrence_count"),
|
||||||
|
CheckConstraint("snapshot_version_no >= 1", name="ck_alarms_snapshot_version"),
|
||||||
|
CheckConstraint("char_length(btrim(module_key)) > 0", name="ck_alarms_module_key"),
|
||||||
|
CheckConstraint("char_length(btrim(scenario_key)) > 0", name="ck_alarms_scenario_key"),
|
||||||
|
CheckConstraint("char_length(btrim(scenario_name)) > 0", name="ck_alarms_scenario_name"),
|
||||||
|
CheckConstraint("char_length(btrim(cycle_key)) > 0", name="ck_alarms_cycle_key"),
|
||||||
|
CheckConstraint("char_length(btrim(event_key)) > 0", name="ck_alarms_event_key"),
|
||||||
|
CheckConstraint("last_occurred_at >= first_occurred_at", name="ck_alarms_occurred_order"),
|
||||||
|
CheckConstraint(
|
||||||
|
"previous_alarm_id IS NULL OR previous_alarm_id <> id",
|
||||||
|
name="ck_alarms_previous_not_self",
|
||||||
|
),
|
||||||
|
CheckConstraint(_SCOPE_SQL, name="ck_alarms_handling_scope"),
|
||||||
|
Index("ix_alarms_previous_alarm_id", "previous_alarm_id"),
|
||||||
|
Index(
|
||||||
|
"ix_alarms_subject_opened",
|
||||||
|
"tenant_id",
|
||||||
|
"module_key",
|
||||||
|
"scenario_key",
|
||||||
|
"mapped_input_id",
|
||||||
|
"opened_at",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||||
|
)
|
||||||
|
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
status: Mapped[str] = mapped_column(
|
||||||
|
String(16), nullable=False, server_default=text("'pending'")
|
||||||
|
)
|
||||||
|
current_handler: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||||
|
claimed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
|
closed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
|
close_result: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||||
|
occurrence_count: Mapped[int] = mapped_column(
|
||||||
|
Integer, nullable=False, server_default=text("1")
|
||||||
|
)
|
||||||
|
first_occurred_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||||
|
last_occurred_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||||
|
previous_alarm_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("alarms.id", ondelete="RESTRICT"),
|
||||||
|
nullable=True,
|
||||||
|
)
|
||||||
|
mapped_input_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("mapped_inputs.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
mapping_definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("mapping_definitions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
mapping_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("mapping_versions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
rule_definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("rule_definitions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
rule_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("rule_versions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
snapshot_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
|
||||||
|
snapshot_version_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
|
module_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
scenario_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
scenario_name: Mapped[str] = mapped_column(String(256), nullable=False)
|
||||||
|
handling_scope: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False)
|
||||||
|
cycle_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
event_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
opened_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||||
|
)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AlarmOccurrence(Base):
|
||||||
|
"""One formal abnormal fact. Replays of the same identity return this row.
|
||||||
|
|
||||||
|
Append-only: the cited input revision is the original FAIL and must not be
|
||||||
|
rewritten when a later same-cycle correction arrives. Not safe to update.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "alarm_occurrences"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint(
|
||||||
|
"tenant_id",
|
||||||
|
"mapped_input_revision_id",
|
||||||
|
"mapping_version_id",
|
||||||
|
"rule_version_id",
|
||||||
|
"snapshot_id",
|
||||||
|
"cycle_key",
|
||||||
|
"event_key",
|
||||||
|
"observed_at",
|
||||||
|
name="uq_alarm_occurrences_formal_identity",
|
||||||
|
),
|
||||||
|
CheckConstraint("snapshot_version_no >= 1", name="ck_alarm_occurrences_snapshot_version"),
|
||||||
|
CheckConstraint("char_length(btrim(module_key)) > 0", name="ck_alarm_occurrences_module_key"),
|
||||||
|
CheckConstraint(
|
||||||
|
"char_length(btrim(scenario_key)) > 0",
|
||||||
|
name="ck_alarm_occurrences_scenario_key",
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"char_length(btrim(scenario_name)) > 0",
|
||||||
|
name="ck_alarm_occurrences_scenario_name",
|
||||||
|
),
|
||||||
|
CheckConstraint("char_length(btrim(cycle_key)) > 0", name="ck_alarm_occurrences_cycle_key"),
|
||||||
|
CheckConstraint("char_length(btrim(event_key)) > 0", name="ck_alarm_occurrences_event_key"),
|
||||||
|
CheckConstraint(_SCOPE_SQL, name="ck_alarm_occurrences_handling_scope"),
|
||||||
|
Index("ix_alarm_occurrences_alarm_id", "alarm_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||||
|
)
|
||||||
|
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
alarm_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("alarms.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
mapped_input_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("mapped_inputs.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
mapped_input_revision_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("mapped_input_revisions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
mapping_definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("mapping_definitions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
mapping_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("mapping_versions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
rule_definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("rule_definitions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
rule_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("rule_versions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
snapshot_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
|
||||||
|
snapshot_version_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
|
module_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
scenario_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
scenario_name: Mapped[str] = mapped_column(String(256), nullable=False)
|
||||||
|
handling_scope: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False)
|
||||||
|
cycle_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
event_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
observed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||||
|
received_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AlarmRevisionEvidence(Base):
|
||||||
|
"""Append-only same-cycle correction basis. It never opens an alarm.
|
||||||
|
|
||||||
|
Points at a later M05 revision while the original occurrence keeps the
|
||||||
|
first FAIL revision. Not safe to update or delete.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "alarm_revision_evidence"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint(
|
||||||
|
"alarm_id",
|
||||||
|
"mapped_input_revision_id",
|
||||||
|
name="uq_alarm_revision_evidence_alarm_revision",
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"snapshot_version_no >= 1",
|
||||||
|
name="ck_alarm_revision_evidence_snapshot_version",
|
||||||
|
),
|
||||||
|
Index("ix_alarm_revision_evidence_alarm_id", "alarm_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||||
|
)
|
||||||
|
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
alarm_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("alarms.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
occurrence_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("alarm_occurrences.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
mapped_input_revision_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("mapped_input_revisions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
mapping_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("mapping_versions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
rule_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("rule_versions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
snapshot_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
|
||||||
|
snapshot_version_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
|
received_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||||
|
recorded_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||||
|
)
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
"""Append-only alarm handling history, command keys, and closed-repeat basis.
|
||||||
|
|
||||||
|
Boundary: stores what the handling service and the closed-repeat path append.
|
||||||
|
It does not decide who may claim or close, and it does not store intents or
|
||||||
|
escalation windows. Depends on alarm facts and the server tenant.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import BigInteger, CheckConstraint, DateTime, ForeignKey, Identity, Index, Integer, String, UniqueConstraint, func, text
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from watchman.models.base import Base
|
||||||
|
|
||||||
|
HANDLING_CLAIM = "claim"
|
||||||
|
HANDLING_PROGRESS = "progress"
|
||||||
|
HANDLING_CLOSE = "close"
|
||||||
|
HANDLING_COMMANDS = (
|
||||||
|
HANDLING_CLAIM,
|
||||||
|
HANDLING_PROGRESS,
|
||||||
|
HANDLING_CLOSE,
|
||||||
|
)
|
||||||
|
|
||||||
|
_COMMAND_SHAPE = """
|
||||||
|
(
|
||||||
|
command = 'claim'
|
||||||
|
AND from_status = 'pending'
|
||||||
|
AND to_status = 'processing'
|
||||||
|
AND note IS NULL
|
||||||
|
AND close_result IS NULL
|
||||||
|
AND evidence_ref IS NULL
|
||||||
|
) OR (
|
||||||
|
command = 'progress'
|
||||||
|
AND from_status = 'processing'
|
||||||
|
AND to_status = 'processing'
|
||||||
|
AND note IS NOT NULL
|
||||||
|
AND char_length(btrim(note)) > 0
|
||||||
|
AND close_result IS NULL
|
||||||
|
) OR (
|
||||||
|
command = 'close'
|
||||||
|
AND from_status = 'processing'
|
||||||
|
AND to_status = 'closed'
|
||||||
|
AND note IS NOT NULL
|
||||||
|
AND char_length(btrim(note)) > 0
|
||||||
|
AND close_result IN ('resolved', 'false_positive')
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class AlarmHandlingEvent(Base):
|
||||||
|
"""One handling step. Later steps are new rows; this row is not edited.
|
||||||
|
|
||||||
|
`seq` is the append order. Recorded time can tie, so readers order by `seq`.
|
||||||
|
Not safe to update or delete. The alarm projection is a separate write.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "alarm_handling_events"
|
||||||
|
__table_args__ = (
|
||||||
|
CheckConstraint(
|
||||||
|
"command IN ('claim', 'progress', 'close')",
|
||||||
|
name="ck_alarm_handling_events_command",
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"from_status IN ('pending', 'processing', 'closed')",
|
||||||
|
name="ck_alarm_handling_events_from_status",
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"to_status IN ('pending', 'processing', 'closed')",
|
||||||
|
name="ck_alarm_handling_events_to_status",
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"actor_role IN ('watchman-admin', 'watchman-operator')",
|
||||||
|
name="ck_alarm_handling_events_actor_role",
|
||||||
|
),
|
||||||
|
CheckConstraint("char_length(btrim(actor_subject)) > 0", name="ck_alarm_handling_events_actor"),
|
||||||
|
CheckConstraint("char_length(btrim(handler_subject)) > 0", name="ck_alarm_handling_events_handler"),
|
||||||
|
CheckConstraint(_COMMAND_SHAPE, name="ck_alarm_handling_events_shape"),
|
||||||
|
CheckConstraint(
|
||||||
|
"evidence_ref IS NULL OR char_length(btrim(evidence_ref)) > 0",
|
||||||
|
name="ck_alarm_handling_events_evidence_ref",
|
||||||
|
),
|
||||||
|
Index("ix_alarm_handling_events_alarm_id", "alarm_id", "seq"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||||
|
)
|
||||||
|
seq: Mapped[int] = mapped_column(BigInteger, Identity(), nullable=False)
|
||||||
|
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
alarm_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("alarms.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
command: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||||
|
actor_subject: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
actor_role: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
handler_subject: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
from_status: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||||
|
to_status: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||||
|
note: Mapped[str | None] = mapped_column(String(2000), nullable=True)
|
||||||
|
close_result: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||||
|
evidence_ref: Mapped[str | None] = mapped_column(String(512), nullable=True)
|
||||||
|
recorded_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AlarmHandlingCommand(Base):
|
||||||
|
"""Idempotency record for one accepted handling command.
|
||||||
|
|
||||||
|
The same key with a different payload hash is a conflict, not a second
|
||||||
|
effect. Not safe to update or delete.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "alarm_handling_commands"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("tenant_id", "idempotency_key", name="uq_alarm_handling_commands_idem"),
|
||||||
|
CheckConstraint(
|
||||||
|
"command IN ('claim', 'progress', 'close')",
|
||||||
|
name="ck_alarm_handling_commands_command",
|
||||||
|
),
|
||||||
|
CheckConstraint("char_length(btrim(idempotency_key)) > 0", name="ck_alarm_handling_commands_key"),
|
||||||
|
CheckConstraint("payload_hash ~ '^[0-9a-f]{64}$'", name="ck_alarm_handling_commands_hash"),
|
||||||
|
Index("ix_alarm_handling_commands_alarm_id", "alarm_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||||
|
)
|
||||||
|
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
alarm_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("alarms.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
event_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("alarm_handling_events.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
command: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||||
|
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
payload_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AlarmClosedBasis(Base):
|
||||||
|
"""Trace of a formal failure that arrived after the merge key was closed.
|
||||||
|
|
||||||
|
It does not open an alarm, reopen the closed one, or replace the original
|
||||||
|
FAIL occurrence. Not safe to update or delete.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "alarm_closed_basis"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint(
|
||||||
|
"tenant_id",
|
||||||
|
"mapped_input_revision_id",
|
||||||
|
"mapping_version_id",
|
||||||
|
"rule_version_id",
|
||||||
|
"snapshot_id",
|
||||||
|
"cycle_key",
|
||||||
|
"event_key",
|
||||||
|
"observed_at",
|
||||||
|
name="uq_alarm_closed_basis_formal_identity",
|
||||||
|
),
|
||||||
|
CheckConstraint("snapshot_version_no >= 1", name="ck_alarm_closed_basis_snapshot_version"),
|
||||||
|
CheckConstraint("char_length(btrim(cycle_key)) > 0", name="ck_alarm_closed_basis_cycle_key"),
|
||||||
|
CheckConstraint("char_length(btrim(event_key)) > 0", name="ck_alarm_closed_basis_event_key"),
|
||||||
|
Index("ix_alarm_closed_basis_alarm_id", "alarm_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||||
|
)
|
||||||
|
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
alarm_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("alarms.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
original_occurrence_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("alarm_occurrences.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
mapped_input_revision_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("mapped_input_revisions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
mapping_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("mapping_versions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
rule_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("rule_versions.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
snapshot_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
|
||||||
|
snapshot_version_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
|
cycle_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
event_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
observed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||||
|
received_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||||
|
recorded_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||||
|
)
|
||||||
@@ -0,0 +1,733 @@
|
|||||||
|
"""Forward-only alarm handling: claim, progress, and close.
|
||||||
|
|
||||||
|
Boundary: one current handler, append-only history, and a close-validity read.
|
||||||
|
It does not register permission nodes, open routes, write intents, retract
|
||||||
|
messages, or touch escalation windows. Depends on alarm facts and the server tenant.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import select, text
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from watchman.auth.access import ROLE_ADMIN, ROLE_OPERATOR
|
||||||
|
from watchman.core.config import get_settings
|
||||||
|
from watchman.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||||
|
from watchman.models.alarm import (
|
||||||
|
ALARM_CLOSE_RESULTS,
|
||||||
|
ALARM_STATUS_CLOSED,
|
||||||
|
ALARM_STATUS_PENDING,
|
||||||
|
ALARM_STATUS_PROCESSING,
|
||||||
|
Alarm,
|
||||||
|
)
|
||||||
|
from watchman.models.alarm_handling import (
|
||||||
|
HANDLING_CLAIM,
|
||||||
|
HANDLING_CLOSE,
|
||||||
|
HANDLING_PROGRESS,
|
||||||
|
AlarmHandlingCommand,
|
||||||
|
AlarmHandlingEvent,
|
||||||
|
)
|
||||||
|
from watchman.services.alarms import lock_alarm_subject
|
||||||
|
|
||||||
|
# GUARD: status columns are not assigned here. alarm_apply_transition is the writer.
|
||||||
|
# GUARD: do not invent a permission node. Actor checks use the current handler and the three roles.
|
||||||
|
_NOTE_MAX = 2000
|
||||||
|
_REF_MAX = 512
|
||||||
|
_SUBJECT_MAX = 128
|
||||||
|
_TRANSITION_SQL = """
|
||||||
|
SELECT alarm_apply_transition(
|
||||||
|
:alarm_id, :status, :handler, :claimed_at, :closed_at, :close_result
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class HandlingActor:
|
||||||
|
"""Who is acting. `subject` must match a scope subject; roles are the three existing names."""
|
||||||
|
|
||||||
|
subject: str
|
||||||
|
roles: tuple[str, ...]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class HandlingResult:
|
||||||
|
"""The handling event this command created or replayed.
|
||||||
|
|
||||||
|
`status` and `close_result` come from that event, which is the original
|
||||||
|
command outcome. A later command does not rewrite this result.
|
||||||
|
"""
|
||||||
|
|
||||||
|
alarm_id: uuid.UUID
|
||||||
|
event_id: uuid.UUID
|
||||||
|
command: str
|
||||||
|
status: str
|
||||||
|
current_handler: str | None
|
||||||
|
close_result: str | None
|
||||||
|
replayed: bool
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class CloseValidity:
|
||||||
|
"""Whether unexecuted intents bound to this alarm should be treated as invalid.
|
||||||
|
|
||||||
|
Derived from the terminal status. This is not an intent row and not a window.
|
||||||
|
"""
|
||||||
|
|
||||||
|
alarm_id: uuid.UUID
|
||||||
|
status: str
|
||||||
|
unexecuted_intents_should_invalidate: bool
|
||||||
|
|
||||||
|
|
||||||
|
def _tenant_id() -> str:
|
||||||
|
# GUARD: tenant_id comes only from server settings, never from the caller.
|
||||||
|
return get_settings().tenant_id
|
||||||
|
|
||||||
|
|
||||||
|
def _now() -> datetime:
|
||||||
|
return datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_key(idempotency_key: str | None) -> str:
|
||||||
|
"""Require the command key. The same key with another payload conflicts later."""
|
||||||
|
if idempotency_key is None or not str(idempotency_key).strip():
|
||||||
|
raise ValidationError(
|
||||||
|
"x-idempotency-key is required",
|
||||||
|
details={"field": "x-idempotency-key", "reason": "idempotency_key_required"},
|
||||||
|
)
|
||||||
|
return str(idempotency_key).strip()[:128]
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_actor(actor: HandlingActor) -> HandlingActor:
|
||||||
|
"""Canonicalize the actor so the idempotency hash does not depend on role order."""
|
||||||
|
if not isinstance(actor, HandlingActor) or not isinstance(actor.subject, str):
|
||||||
|
raise ValidationError("Invalid alarm actor", details={"reason": "actor_invalid", "field": "actor"})
|
||||||
|
subject = actor.subject.strip()
|
||||||
|
if not subject or len(subject) > _SUBJECT_MAX or any(char in subject for char in "\r\n\x00"):
|
||||||
|
raise ValidationError(
|
||||||
|
"Invalid alarm actor",
|
||||||
|
details={"reason": "actor_subject_invalid", "field": "actor"},
|
||||||
|
)
|
||||||
|
if isinstance(actor.roles, str) or not isinstance(actor.roles, tuple):
|
||||||
|
raise ValidationError(
|
||||||
|
"Invalid alarm actor",
|
||||||
|
details={"reason": "actor_role_invalid", "field": "actor"},
|
||||||
|
)
|
||||||
|
cleaned: list[str] = []
|
||||||
|
for role in actor.roles:
|
||||||
|
if not isinstance(role, str):
|
||||||
|
raise ValidationError(
|
||||||
|
"Invalid alarm actor",
|
||||||
|
details={"reason": "actor_role_invalid", "field": "actor"},
|
||||||
|
)
|
||||||
|
value = role.strip()
|
||||||
|
if not value or len(value) > 64 or any(char in value for char in "\r\n\x00"):
|
||||||
|
raise ValidationError(
|
||||||
|
"Invalid alarm actor",
|
||||||
|
details={"reason": "actor_role_invalid", "field": "actor"},
|
||||||
|
)
|
||||||
|
cleaned.append(value)
|
||||||
|
return HandlingActor(subject=subject, roles=tuple(sorted(set(cleaned))))
|
||||||
|
|
||||||
|
|
||||||
|
def _deciding_role(actor: HandlingActor) -> str:
|
||||||
|
"""Pick admin over operator. Viewer and unknown roles cannot handle.
|
||||||
|
|
||||||
|
Raises ForbiddenError with no permission node. S3 must not treat that as a
|
||||||
|
registered alarm permission.
|
||||||
|
"""
|
||||||
|
if ROLE_ADMIN in actor.roles:
|
||||||
|
return ROLE_ADMIN
|
||||||
|
if ROLE_OPERATOR in actor.roles:
|
||||||
|
return ROLE_OPERATOR
|
||||||
|
raise ForbiddenError("Alarm handling is limited to operator and admin")
|
||||||
|
|
||||||
|
|
||||||
|
def _require_note(value: object, reason: str) -> str:
|
||||||
|
if not isinstance(value, str):
|
||||||
|
raise ValidationError("A handling note is required", details={"reason": reason, "field": "note"})
|
||||||
|
cleaned = value.strip()
|
||||||
|
if not cleaned:
|
||||||
|
raise ValidationError("A handling note is required", details={"reason": reason, "field": "note"})
|
||||||
|
if len(cleaned) > _NOTE_MAX or "\x00" in cleaned:
|
||||||
|
raise ValidationError("A handling note is invalid", details={"reason": "note_invalid", "field": "note"})
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
|
def _require_ref(value: object) -> str | None:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
if not isinstance(value, str):
|
||||||
|
raise ValidationError(
|
||||||
|
"Evidence reference is invalid",
|
||||||
|
details={"reason": "evidence_ref_invalid", "field": "evidence_ref"},
|
||||||
|
)
|
||||||
|
cleaned = value.strip()
|
||||||
|
if not cleaned:
|
||||||
|
return None
|
||||||
|
if len(cleaned) > _REF_MAX or "\x00" in cleaned:
|
||||||
|
raise ValidationError(
|
||||||
|
"Evidence reference is invalid",
|
||||||
|
details={"reason": "evidence_ref_invalid", "field": "evidence_ref"},
|
||||||
|
)
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
|
def _require_result(value: object) -> str:
|
||||||
|
if not isinstance(value, str) or value.strip() not in ALARM_CLOSE_RESULTS:
|
||||||
|
raise ValidationError(
|
||||||
|
"Close result must be resolved or false_positive",
|
||||||
|
details={"reason": "close_result_invalid", "field": "result"},
|
||||||
|
)
|
||||||
|
return value.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _payload_hash(payload: dict[str, Any]) -> str:
|
||||||
|
encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
|
||||||
|
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def _command_payload(
|
||||||
|
command: str,
|
||||||
|
alarm_id: uuid.UUID,
|
||||||
|
actor: HandlingActor,
|
||||||
|
*,
|
||||||
|
note: str | None = None,
|
||||||
|
close_result: str | None = None,
|
||||||
|
evidence_ref: str | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
payload: dict[str, Any] = {
|
||||||
|
"alarm_id": str(alarm_id),
|
||||||
|
"command": command,
|
||||||
|
"roles": list(actor.roles),
|
||||||
|
"subject": actor.subject,
|
||||||
|
}
|
||||||
|
if command != HANDLING_CLAIM:
|
||||||
|
payload["evidence_ref"] = evidence_ref
|
||||||
|
payload["note"] = note
|
||||||
|
if command == HANDLING_CLOSE:
|
||||||
|
payload["close_result"] = close_result
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def _subject_in_scope(alarm: Alarm, subject: str) -> bool:
|
||||||
|
"""Match a named subject on the snapshot. A role entry alone does not grant handling.
|
||||||
|
|
||||||
|
NOTE(ai): this subject match is the same implementation assumption as the fact
|
||||||
|
scope guard. It is not a new confirmed authorization model.
|
||||||
|
"""
|
||||||
|
scope = alarm.handling_scope
|
||||||
|
if not isinstance(scope, dict):
|
||||||
|
return False
|
||||||
|
principals = scope.get("principals")
|
||||||
|
if not isinstance(principals, list):
|
||||||
|
return False
|
||||||
|
return any(
|
||||||
|
isinstance(item, dict) and item.get("kind") == "subject" and item.get("value") == subject
|
||||||
|
for item in principals
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _lock_alarm(session: Session, alarm_id: uuid.UUID) -> Alarm:
|
||||||
|
"""Lock the subject, then the alarm row, in the same order as fact writes."""
|
||||||
|
if not isinstance(alarm_id, uuid.UUID):
|
||||||
|
raise NotFoundError("Alarm not found")
|
||||||
|
tenant_id = _tenant_id()
|
||||||
|
alarm = session.get(Alarm, alarm_id)
|
||||||
|
if alarm is None or alarm.tenant_id != tenant_id:
|
||||||
|
raise NotFoundError("Alarm not found")
|
||||||
|
lock_alarm_subject(
|
||||||
|
session,
|
||||||
|
module_key=alarm.module_key,
|
||||||
|
scenario_key=alarm.scenario_key,
|
||||||
|
mapped_input_id=alarm.mapped_input_id,
|
||||||
|
)
|
||||||
|
locked = session.scalar(
|
||||||
|
select(Alarm)
|
||||||
|
.where(Alarm.id == alarm_id, Alarm.tenant_id == tenant_id)
|
||||||
|
.with_for_update()
|
||||||
|
.execution_options(populate_existing=True)
|
||||||
|
)
|
||||||
|
if locked is None:
|
||||||
|
raise NotFoundError("Alarm not found")
|
||||||
|
return locked
|
||||||
|
|
||||||
|
|
||||||
|
def _find_command(session: Session, key: str) -> AlarmHandlingCommand | None:
|
||||||
|
return session.scalar(
|
||||||
|
select(AlarmHandlingCommand)
|
||||||
|
.where(
|
||||||
|
AlarmHandlingCommand.tenant_id == _tenant_id(),
|
||||||
|
AlarmHandlingCommand.idempotency_key == key,
|
||||||
|
)
|
||||||
|
.execution_options(populate_existing=True)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _first_event(session: Session, alarm_id: uuid.UUID, command: str) -> AlarmHandlingEvent | None:
|
||||||
|
return session.scalar(
|
||||||
|
select(AlarmHandlingEvent)
|
||||||
|
.where(
|
||||||
|
AlarmHandlingEvent.tenant_id == _tenant_id(),
|
||||||
|
AlarmHandlingEvent.alarm_id == alarm_id,
|
||||||
|
AlarmHandlingEvent.command == command,
|
||||||
|
)
|
||||||
|
.order_by(AlarmHandlingEvent.seq.asc())
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _result_from_event(event: AlarmHandlingEvent, *, replayed: bool) -> HandlingResult:
|
||||||
|
return HandlingResult(
|
||||||
|
alarm_id=event.alarm_id,
|
||||||
|
event_id=event.id,
|
||||||
|
command=event.command,
|
||||||
|
status=event.to_status,
|
||||||
|
current_handler=event.handler_subject,
|
||||||
|
close_result=event.close_result,
|
||||||
|
replayed=replayed,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _replay(session: Session, existing: AlarmHandlingCommand, digest: str) -> HandlingResult:
|
||||||
|
if existing.payload_hash != digest:
|
||||||
|
raise ConflictError(
|
||||||
|
"Idempotency key was already used with a different payload",
|
||||||
|
details={"reason": "idempotency_payload_mismatch"},
|
||||||
|
)
|
||||||
|
event = session.get(AlarmHandlingEvent, existing.event_id)
|
||||||
|
if event is None or event.tenant_id != _tenant_id():
|
||||||
|
raise ConflictError(
|
||||||
|
"Handling history for this command is missing",
|
||||||
|
details={"reason": "handling_history_missing"},
|
||||||
|
)
|
||||||
|
return _result_from_event(event, replayed=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _recover_command(session: Session, key: str, digest: str) -> HandlingResult:
|
||||||
|
session.expire_all()
|
||||||
|
existing = _find_command(session, key)
|
||||||
|
if existing is None:
|
||||||
|
raise
|
||||||
|
return _replay(session, existing, digest)
|
||||||
|
|
||||||
|
|
||||||
|
def _authorize(alarm: Alarm, actor: HandlingActor) -> str:
|
||||||
|
if not _subject_in_scope(alarm, actor.subject):
|
||||||
|
raise NotFoundError("Alarm not found")
|
||||||
|
return _deciding_role(actor)
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_transition(
|
||||||
|
session: Session,
|
||||||
|
alarm: Alarm,
|
||||||
|
*,
|
||||||
|
status: str,
|
||||||
|
handler: str,
|
||||||
|
claimed_at: datetime | None,
|
||||||
|
closed_at: datetime | None,
|
||||||
|
close_result: str | None,
|
||||||
|
) -> None:
|
||||||
|
"""Move the projection through the database function, then reload it.
|
||||||
|
|
||||||
|
The ORM must not emit an UPDATE of status, handler, or close columns.
|
||||||
|
"""
|
||||||
|
session.execute(
|
||||||
|
text(_TRANSITION_SQL),
|
||||||
|
{
|
||||||
|
"alarm_id": alarm.id,
|
||||||
|
"status": status,
|
||||||
|
"handler": handler,
|
||||||
|
"claimed_at": claimed_at,
|
||||||
|
"closed_at": closed_at,
|
||||||
|
"close_result": close_result,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
session.expire(alarm)
|
||||||
|
session.refresh(alarm)
|
||||||
|
|
||||||
|
|
||||||
|
def _insert_command(
|
||||||
|
session: Session,
|
||||||
|
*,
|
||||||
|
alarm_id: uuid.UUID,
|
||||||
|
event_id: uuid.UUID,
|
||||||
|
command: str,
|
||||||
|
key: str,
|
||||||
|
digest: str,
|
||||||
|
) -> None:
|
||||||
|
session.add(
|
||||||
|
AlarmHandlingCommand(
|
||||||
|
tenant_id=_tenant_id(),
|
||||||
|
alarm_id=alarm_id,
|
||||||
|
event_id=event_id,
|
||||||
|
command=command,
|
||||||
|
idempotency_key=key,
|
||||||
|
payload_hash=digest,
|
||||||
|
created_at=_now(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
session.flush()
|
||||||
|
|
||||||
|
|
||||||
|
def _bind_existing(
|
||||||
|
session: Session,
|
||||||
|
event: AlarmHandlingEvent,
|
||||||
|
*,
|
||||||
|
command: str,
|
||||||
|
key: str,
|
||||||
|
digest: str,
|
||||||
|
) -> HandlingResult:
|
||||||
|
"""Point a new key at an existing event without a second history row."""
|
||||||
|
try:
|
||||||
|
with session.begin_nested():
|
||||||
|
_insert_command(
|
||||||
|
session,
|
||||||
|
alarm_id=event.alarm_id,
|
||||||
|
event_id=event.id,
|
||||||
|
command=command,
|
||||||
|
key=key,
|
||||||
|
digest=digest,
|
||||||
|
)
|
||||||
|
except IntegrityError:
|
||||||
|
return _recover_command(session, key, digest)
|
||||||
|
return _result_from_event(event, replayed=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _new_event(
|
||||||
|
alarm: Alarm,
|
||||||
|
*,
|
||||||
|
command: str,
|
||||||
|
actor: HandlingActor,
|
||||||
|
role: str,
|
||||||
|
handler_subject: str,
|
||||||
|
from_status: str,
|
||||||
|
to_status: str,
|
||||||
|
note: str | None,
|
||||||
|
close_result: str | None,
|
||||||
|
evidence_ref: str | None,
|
||||||
|
) -> AlarmHandlingEvent:
|
||||||
|
return AlarmHandlingEvent(
|
||||||
|
tenant_id=_tenant_id(),
|
||||||
|
alarm_id=alarm.id,
|
||||||
|
command=command,
|
||||||
|
actor_subject=actor.subject,
|
||||||
|
actor_role=role,
|
||||||
|
handler_subject=handler_subject,
|
||||||
|
from_status=from_status,
|
||||||
|
to_status=to_status,
|
||||||
|
note=note,
|
||||||
|
close_result=close_result,
|
||||||
|
evidence_ref=evidence_ref,
|
||||||
|
recorded_at=_now(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _start(
|
||||||
|
session: Session,
|
||||||
|
*,
|
||||||
|
alarm_id: uuid.UUID,
|
||||||
|
actor: HandlingActor,
|
||||||
|
idempotency_key: str | None,
|
||||||
|
command: str,
|
||||||
|
note: str | None = None,
|
||||||
|
close_result: str | None = None,
|
||||||
|
evidence_ref: str | None = None,
|
||||||
|
) -> tuple[HandlingResult | None, Alarm, HandlingActor, str, str]:
|
||||||
|
key = _require_key(idempotency_key)
|
||||||
|
normalized = _normalize_actor(actor)
|
||||||
|
digest = _payload_hash(
|
||||||
|
_command_payload(
|
||||||
|
command,
|
||||||
|
alarm_id,
|
||||||
|
normalized,
|
||||||
|
note=note,
|
||||||
|
close_result=close_result,
|
||||||
|
evidence_ref=evidence_ref,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
alarm = _lock_alarm(session, alarm_id)
|
||||||
|
existing = _find_command(session, key)
|
||||||
|
if existing is not None:
|
||||||
|
return _replay(session, existing, digest), alarm, normalized, key, digest
|
||||||
|
return None, alarm, normalized, key, digest
|
||||||
|
|
||||||
|
|
||||||
|
def claim_alarm(
|
||||||
|
session: Session,
|
||||||
|
*,
|
||||||
|
alarm_id: uuid.UUID,
|
||||||
|
actor: HandlingActor,
|
||||||
|
idempotency_key: str | None,
|
||||||
|
) -> HandlingResult:
|
||||||
|
"""Claim a pending alarm for one in-scope operator or admin.
|
||||||
|
|
||||||
|
A second claim by the same handler replays the original event. A different
|
||||||
|
handler gets a conflict and does not replace the current one. Closed alarms
|
||||||
|
are not reopened. The same idempotency key with a different actor conflicts.
|
||||||
|
Raises NotFoundError when the alarm is missing or outside the snapshot
|
||||||
|
subjects, and ForbiddenError when the actor is not an operator or admin.
|
||||||
|
"""
|
||||||
|
replay, alarm, normalized, key, digest = _start(
|
||||||
|
session,
|
||||||
|
alarm_id=alarm_id,
|
||||||
|
actor=actor,
|
||||||
|
idempotency_key=idempotency_key,
|
||||||
|
command=HANDLING_CLAIM,
|
||||||
|
)
|
||||||
|
if replay is not None:
|
||||||
|
return replay
|
||||||
|
role = _authorize(alarm, normalized)
|
||||||
|
if alarm.status == ALARM_STATUS_PROCESSING and alarm.current_handler == normalized.subject:
|
||||||
|
event = _first_event(session, alarm.id, HANDLING_CLAIM)
|
||||||
|
if event is None:
|
||||||
|
raise ConflictError(
|
||||||
|
"Claim history is missing",
|
||||||
|
details={"reason": "handling_history_missing"},
|
||||||
|
)
|
||||||
|
return _bind_existing(session, event, command=HANDLING_CLAIM, key=key, digest=digest)
|
||||||
|
if alarm.status == ALARM_STATUS_PROCESSING:
|
||||||
|
raise ConflictError("Alarm already has a handler", details={"reason": "already_claimed"})
|
||||||
|
if alarm.status != ALARM_STATUS_PENDING:
|
||||||
|
raise ConflictError(
|
||||||
|
"Alarm cannot be claimed from this status",
|
||||||
|
details={"reason": "illegal_transition"},
|
||||||
|
)
|
||||||
|
claimed_at = _now()
|
||||||
|
event = _new_event(
|
||||||
|
alarm,
|
||||||
|
command=HANDLING_CLAIM,
|
||||||
|
actor=normalized,
|
||||||
|
role=role,
|
||||||
|
handler_subject=normalized.subject,
|
||||||
|
from_status=ALARM_STATUS_PENDING,
|
||||||
|
to_status=ALARM_STATUS_PROCESSING,
|
||||||
|
note=None,
|
||||||
|
close_result=None,
|
||||||
|
evidence_ref=None,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with session.begin_nested():
|
||||||
|
_apply_transition(
|
||||||
|
session,
|
||||||
|
alarm,
|
||||||
|
status=ALARM_STATUS_PROCESSING,
|
||||||
|
handler=normalized.subject,
|
||||||
|
claimed_at=claimed_at,
|
||||||
|
closed_at=None,
|
||||||
|
close_result=None,
|
||||||
|
)
|
||||||
|
session.add(event)
|
||||||
|
session.flush()
|
||||||
|
_insert_command(
|
||||||
|
session,
|
||||||
|
alarm_id=alarm.id,
|
||||||
|
event_id=event.id,
|
||||||
|
command=HANDLING_CLAIM,
|
||||||
|
key=key,
|
||||||
|
digest=digest,
|
||||||
|
)
|
||||||
|
except IntegrityError:
|
||||||
|
return _recover_command(session, key, digest)
|
||||||
|
return _result_from_event(event, replayed=False)
|
||||||
|
|
||||||
|
|
||||||
|
def append_progress(
|
||||||
|
session: Session,
|
||||||
|
*,
|
||||||
|
alarm_id: uuid.UUID,
|
||||||
|
actor: HandlingActor,
|
||||||
|
note: str,
|
||||||
|
idempotency_key: str | None,
|
||||||
|
evidence_ref: str | None = None,
|
||||||
|
) -> HandlingResult:
|
||||||
|
"""Append one progress note without changing older notes or the original FAIL.
|
||||||
|
|
||||||
|
Only the current handler can append, and only while the alarm is processing.
|
||||||
|
A repeated key returns the same event. A repeated key with another note
|
||||||
|
conflicts. Raises the same not-found and forbidden errors as claim, or
|
||||||
|
ConflictError when the status or handler does not allow a note.
|
||||||
|
"""
|
||||||
|
cleaned = _require_note(note, "progress_note_required")
|
||||||
|
reference = _require_ref(evidence_ref)
|
||||||
|
replay, alarm, normalized, key, digest = _start(
|
||||||
|
session,
|
||||||
|
alarm_id=alarm_id,
|
||||||
|
actor=actor,
|
||||||
|
idempotency_key=idempotency_key,
|
||||||
|
command=HANDLING_PROGRESS,
|
||||||
|
note=cleaned,
|
||||||
|
evidence_ref=reference,
|
||||||
|
)
|
||||||
|
if replay is not None:
|
||||||
|
return replay
|
||||||
|
role = _authorize(alarm, normalized)
|
||||||
|
if alarm.status != ALARM_STATUS_PROCESSING:
|
||||||
|
raise ConflictError(
|
||||||
|
"Progress can be added only while the alarm is processing",
|
||||||
|
details={"reason": "illegal_transition"},
|
||||||
|
)
|
||||||
|
if alarm.current_handler != normalized.subject:
|
||||||
|
raise ConflictError(
|
||||||
|
"Only the current handler can append progress",
|
||||||
|
details={"reason": "not_current_handler"},
|
||||||
|
)
|
||||||
|
handler = alarm.current_handler
|
||||||
|
assert handler is not None
|
||||||
|
event = _new_event(
|
||||||
|
alarm,
|
||||||
|
command=HANDLING_PROGRESS,
|
||||||
|
actor=normalized,
|
||||||
|
role=role,
|
||||||
|
handler_subject=handler,
|
||||||
|
from_status=ALARM_STATUS_PROCESSING,
|
||||||
|
to_status=ALARM_STATUS_PROCESSING,
|
||||||
|
note=cleaned,
|
||||||
|
close_result=None,
|
||||||
|
evidence_ref=reference,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with session.begin_nested():
|
||||||
|
alarm.updated_at = _now()
|
||||||
|
session.add(event)
|
||||||
|
session.flush()
|
||||||
|
_insert_command(
|
||||||
|
session,
|
||||||
|
alarm_id=alarm.id,
|
||||||
|
event_id=event.id,
|
||||||
|
command=HANDLING_PROGRESS,
|
||||||
|
key=key,
|
||||||
|
digest=digest,
|
||||||
|
)
|
||||||
|
except IntegrityError:
|
||||||
|
return _recover_command(session, key, digest)
|
||||||
|
return _result_from_event(event, replayed=False)
|
||||||
|
|
||||||
|
|
||||||
|
def close_alarm(
|
||||||
|
session: Session,
|
||||||
|
*,
|
||||||
|
alarm_id: uuid.UUID,
|
||||||
|
actor: HandlingActor,
|
||||||
|
result: str,
|
||||||
|
note: str,
|
||||||
|
idempotency_key: str | None,
|
||||||
|
evidence_ref: str | None = None,
|
||||||
|
) -> HandlingResult:
|
||||||
|
"""Close a processing alarm as resolved or false_positive.
|
||||||
|
|
||||||
|
The current handler or an in-scope admin may close. Pending alarms cannot
|
||||||
|
be closed, and a closed alarm is not reopened. The note is required. An
|
||||||
|
exact repeat returns the terminal event; a different result or note conflicts.
|
||||||
|
Raises NotFoundError, ForbiddenError, ValidationError, or ConflictError.
|
||||||
|
"""
|
||||||
|
close_result = _require_result(result)
|
||||||
|
cleaned = _require_note(note, "close_note_required")
|
||||||
|
reference = _require_ref(evidence_ref)
|
||||||
|
replay, alarm, normalized, key, digest = _start(
|
||||||
|
session,
|
||||||
|
alarm_id=alarm_id,
|
||||||
|
actor=actor,
|
||||||
|
idempotency_key=idempotency_key,
|
||||||
|
command=HANDLING_CLOSE,
|
||||||
|
note=cleaned,
|
||||||
|
close_result=close_result,
|
||||||
|
evidence_ref=reference,
|
||||||
|
)
|
||||||
|
if replay is not None:
|
||||||
|
return replay
|
||||||
|
role = _authorize(alarm, normalized)
|
||||||
|
if alarm.status == ALARM_STATUS_CLOSED:
|
||||||
|
terminal = _first_event(session, alarm.id, HANDLING_CLOSE)
|
||||||
|
same_terminal = (
|
||||||
|
terminal is not None
|
||||||
|
and terminal.actor_subject == normalized.subject
|
||||||
|
and terminal.close_result == close_result
|
||||||
|
and terminal.note == cleaned
|
||||||
|
and terminal.evidence_ref == reference
|
||||||
|
)
|
||||||
|
if same_terminal and terminal is not None:
|
||||||
|
return _bind_existing(session, terminal, command=HANDLING_CLOSE, key=key, digest=digest)
|
||||||
|
raise ConflictError("Alarm is already closed", details={"reason": "already_closed"})
|
||||||
|
if alarm.status != ALARM_STATUS_PROCESSING:
|
||||||
|
raise ConflictError(
|
||||||
|
"Alarm cannot be closed from this status",
|
||||||
|
details={"reason": "illegal_transition"},
|
||||||
|
)
|
||||||
|
if alarm.current_handler != normalized.subject and role != ROLE_ADMIN:
|
||||||
|
raise ConflictError(
|
||||||
|
"Only the current handler or an admin can close this alarm",
|
||||||
|
details={"reason": "not_current_handler"},
|
||||||
|
)
|
||||||
|
handler = alarm.current_handler
|
||||||
|
if handler is None or alarm.claimed_at is None:
|
||||||
|
raise ConflictError(
|
||||||
|
"Processing alarm has no claim",
|
||||||
|
details={"reason": "handling_history_missing"},
|
||||||
|
)
|
||||||
|
closed_at = _now()
|
||||||
|
if closed_at < alarm.claimed_at:
|
||||||
|
closed_at = alarm.claimed_at
|
||||||
|
event = _new_event(
|
||||||
|
alarm,
|
||||||
|
command=HANDLING_CLOSE,
|
||||||
|
actor=normalized,
|
||||||
|
role=role,
|
||||||
|
handler_subject=handler,
|
||||||
|
from_status=ALARM_STATUS_PROCESSING,
|
||||||
|
to_status=ALARM_STATUS_CLOSED,
|
||||||
|
note=cleaned,
|
||||||
|
close_result=close_result,
|
||||||
|
evidence_ref=reference,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with session.begin_nested():
|
||||||
|
_apply_transition(
|
||||||
|
session,
|
||||||
|
alarm,
|
||||||
|
status=ALARM_STATUS_CLOSED,
|
||||||
|
handler=handler,
|
||||||
|
claimed_at=alarm.claimed_at,
|
||||||
|
closed_at=closed_at,
|
||||||
|
close_result=close_result,
|
||||||
|
)
|
||||||
|
session.add(event)
|
||||||
|
session.flush()
|
||||||
|
_insert_command(
|
||||||
|
session,
|
||||||
|
alarm_id=alarm.id,
|
||||||
|
event_id=event.id,
|
||||||
|
command=HANDLING_CLOSE,
|
||||||
|
key=key,
|
||||||
|
digest=digest,
|
||||||
|
)
|
||||||
|
except IntegrityError:
|
||||||
|
return _recover_command(session, key, digest)
|
||||||
|
return _result_from_event(event, replayed=False)
|
||||||
|
|
||||||
|
|
||||||
|
def close_validity(session: Session, alarm_id: uuid.UUID) -> CloseValidity:
|
||||||
|
"""Report whether unexecuted intents for this alarm should be treated as invalid.
|
||||||
|
|
||||||
|
D32 is a read of ``closed``. This does not insert an intent, retract an
|
||||||
|
accepted message, or read or clear an escalation window.
|
||||||
|
Raises NotFoundError when the server tenant cannot see the alarm.
|
||||||
|
"""
|
||||||
|
# GUARD: do not write intent, notification, or window rows from this read.
|
||||||
|
if not isinstance(alarm_id, uuid.UUID):
|
||||||
|
raise NotFoundError("Alarm not found")
|
||||||
|
alarm = session.get(Alarm, alarm_id)
|
||||||
|
if alarm is None or alarm.tenant_id != _tenant_id():
|
||||||
|
raise NotFoundError("Alarm not found")
|
||||||
|
return CloseValidity(
|
||||||
|
alarm_id=alarm.id,
|
||||||
|
status=alarm.status,
|
||||||
|
unexecuted_intents_should_invalidate=alarm.status == ALARM_STATUS_CLOSED,
|
||||||
|
)
|
||||||
@@ -0,0 +1,403 @@
|
|||||||
|
"""Scoped alarm reads for the list, detail, basis, history, and close-validity APIs.
|
||||||
|
|
||||||
|
Boundary: returns alarms whose synthetic snapshot names the caller as a subject.
|
||||||
|
It does not claim, close, notify, or treat a role entry as a tenant-wide grant.
|
||||||
|
Depends on alarm facts, handling history, and the server tenant.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import asc, desc, func, select, text
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from watchman.core.config import get_settings
|
||||||
|
from watchman.core.errors import NotFoundError, ValidationError
|
||||||
|
from watchman.models.alarm import ALARM_STATUSES, Alarm, AlarmOccurrence, AlarmRevisionEvidence
|
||||||
|
from watchman.models.alarm_handling import AlarmClosedBasis, AlarmHandlingEvent
|
||||||
|
from watchman.models.mapping import MappedInput
|
||||||
|
from watchman.services.alarm_handling import close_validity
|
||||||
|
|
||||||
|
# NOTE(ai): subject match follows the S1 snapshot layout. It is not a new auth model.
|
||||||
|
# GUARD: a missing subject must yield no rows. Do not drop this clause for admin or operator.
|
||||||
|
_PAGE_SIZE_MAX = 100
|
||||||
|
_KEY_MAX = 128
|
||||||
|
_NAME_MAX = 256
|
||||||
|
_SORT = {
|
||||||
|
"opened_at": Alarm.opened_at,
|
||||||
|
"updated_at": Alarm.updated_at,
|
||||||
|
"first_occurred_at": Alarm.first_occurred_at,
|
||||||
|
"last_occurred_at": Alarm.last_occurred_at,
|
||||||
|
"status": Alarm.status,
|
||||||
|
"module_key": Alarm.module_key,
|
||||||
|
"scenario_key": Alarm.scenario_key,
|
||||||
|
"scenario_name": Alarm.scenario_name,
|
||||||
|
"occurrence_count": Alarm.occurrence_count,
|
||||||
|
}
|
||||||
|
_SORT_DEFAULT = "last_occurred_at"
|
||||||
|
|
||||||
|
|
||||||
|
def scope_subject(value: str | None) -> str | None:
|
||||||
|
"""Return a snapshot subject, or None when the session has none.
|
||||||
|
|
||||||
|
None means the caller has no scope source. Callers must not replace that
|
||||||
|
with every alarm in the tenant. Length is not trimmed.
|
||||||
|
"""
|
||||||
|
if not isinstance(value, str):
|
||||||
|
return None
|
||||||
|
cleaned = value.strip()
|
||||||
|
if not cleaned or any(char in cleaned for char in "\r\n\x00"):
|
||||||
|
return None
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
|
def _tenant_id() -> str:
|
||||||
|
# GUARD: tenant_id comes only from server settings, never from the caller.
|
||||||
|
return get_settings().tenant_id
|
||||||
|
|
||||||
|
|
||||||
|
def _isoformat(value: datetime | None) -> str | None:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
return value.astimezone(timezone.utc).isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_alarm_id(alarm_id: str) -> uuid.UUID:
|
||||||
|
try:
|
||||||
|
return uuid.UUID(alarm_id)
|
||||||
|
except (TypeError, ValueError, AttributeError) as exc:
|
||||||
|
raise NotFoundError("Alarm not found") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _scope_clause(subject: str) -> Any:
|
||||||
|
"""Match a named subject. A role entry in the same array does not qualify."""
|
||||||
|
return text(
|
||||||
|
"EXISTS (SELECT 1 FROM jsonb_array_elements(alarms.handling_scope -> 'principals') AS elem "
|
||||||
|
"WHERE elem ->> 'kind' = 'subject' AND elem ->> 'value' = :scope_subject)"
|
||||||
|
).bindparams(scope_subject=subject)
|
||||||
|
|
||||||
|
|
||||||
|
def _aware(value: datetime | None, field: str) -> datetime | None:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
if value.tzinfo is None or value.utcoffset() is None:
|
||||||
|
raise ValidationError(
|
||||||
|
"Time filters must be timezone-aware",
|
||||||
|
details={"field": field, "reason": "timestamp_timezone_required"},
|
||||||
|
)
|
||||||
|
return value.astimezone(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def _bounded(value: str | None, field: str, limit: int) -> str | None:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
cleaned = value.strip()
|
||||||
|
if not cleaned:
|
||||||
|
return None
|
||||||
|
if len(cleaned) > limit:
|
||||||
|
raise ValidationError("Filter is too long", details={"field": field, "max": limit})
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
|
def _visible(session: Session, alarm_id: str, subject: str | None) -> tuple[Alarm, str]:
|
||||||
|
"""Load one alarm the subject may see, or raise NotFound for missing and out-of-scope ids."""
|
||||||
|
if subject is None:
|
||||||
|
raise NotFoundError("Alarm not found")
|
||||||
|
parsed = _parse_alarm_id(alarm_id)
|
||||||
|
row = session.execute(
|
||||||
|
select(Alarm, MappedInput.identity_key)
|
||||||
|
.join(MappedInput, MappedInput.id == Alarm.mapped_input_id)
|
||||||
|
.where(
|
||||||
|
Alarm.id == parsed,
|
||||||
|
Alarm.tenant_id == _tenant_id(),
|
||||||
|
MappedInput.tenant_id == _tenant_id(),
|
||||||
|
_scope_clause(subject),
|
||||||
|
)
|
||||||
|
).one_or_none()
|
||||||
|
if row is None:
|
||||||
|
raise NotFoundError("Alarm not found")
|
||||||
|
alarm, identity_key = row
|
||||||
|
return alarm, identity_key
|
||||||
|
|
||||||
|
|
||||||
|
def alarm_public(alarm: Alarm, identity_key: str) -> dict[str, Any]:
|
||||||
|
"""Public alarm projection. Scope principals and tenant id stay off the payload."""
|
||||||
|
return {
|
||||||
|
"id": str(alarm.id),
|
||||||
|
"status": alarm.status,
|
||||||
|
"current_handler": alarm.current_handler,
|
||||||
|
"claimed_at": _isoformat(alarm.claimed_at),
|
||||||
|
"closed_at": _isoformat(alarm.closed_at),
|
||||||
|
"close_result": alarm.close_result,
|
||||||
|
"occurrence_count": alarm.occurrence_count,
|
||||||
|
"first_occurred_at": _isoformat(alarm.first_occurred_at),
|
||||||
|
"last_occurred_at": _isoformat(alarm.last_occurred_at),
|
||||||
|
"previous_alarm_id": str(alarm.previous_alarm_id) if alarm.previous_alarm_id else None,
|
||||||
|
"mapped_input_id": str(alarm.mapped_input_id),
|
||||||
|
"identity_key": identity_key,
|
||||||
|
"module_key": alarm.module_key,
|
||||||
|
"scenario_key": alarm.scenario_key,
|
||||||
|
"scenario_name": alarm.scenario_name,
|
||||||
|
"snapshot_id": str(alarm.snapshot_id),
|
||||||
|
"snapshot_version_no": alarm.snapshot_version_no,
|
||||||
|
"cycle_key": alarm.cycle_key,
|
||||||
|
"event_key": alarm.event_key,
|
||||||
|
"opened_at": _isoformat(alarm.opened_at),
|
||||||
|
"updated_at": _isoformat(alarm.updated_at),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def search_alarms(
|
||||||
|
session: Session,
|
||||||
|
*,
|
||||||
|
subject: str | None,
|
||||||
|
module_key: str | None = None,
|
||||||
|
scenario_key: str | None = None,
|
||||||
|
scenario_name: str | None = None,
|
||||||
|
status: str | None = None,
|
||||||
|
mapped_input_id: str | None = None,
|
||||||
|
occurred_from: datetime | None = None,
|
||||||
|
occurred_to: datetime | None = None,
|
||||||
|
sort_by: str = _SORT_DEFAULT,
|
||||||
|
sort_order: str = "desc",
|
||||||
|
page: int = 1,
|
||||||
|
page_size: int = 20,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Filter, sort, and page alarms in SQL for the caller's snapshot subjects.
|
||||||
|
|
||||||
|
Filters apply only when the client sends them. A caller with no subject
|
||||||
|
gets an empty page even if the tenant has alarms.
|
||||||
|
"""
|
||||||
|
if sort_by not in _SORT:
|
||||||
|
raise ValidationError(
|
||||||
|
"Invalid sort_by",
|
||||||
|
details={"field": "sort_by", "allowed": sorted(_SORT)},
|
||||||
|
)
|
||||||
|
if sort_order not in ("asc", "desc"):
|
||||||
|
raise ValidationError(
|
||||||
|
"Invalid sort_order",
|
||||||
|
details={"field": "sort_order", "allowed": ["asc", "desc"]},
|
||||||
|
)
|
||||||
|
if page < 1:
|
||||||
|
raise ValidationError("Invalid page", details={"field": "page"})
|
||||||
|
if page_size < 1 or page_size > _PAGE_SIZE_MAX:
|
||||||
|
raise ValidationError(
|
||||||
|
"Invalid page_size",
|
||||||
|
details={"field": "page_size", "min": 1, "max": _PAGE_SIZE_MAX},
|
||||||
|
)
|
||||||
|
module = _bounded(module_key, "module_key", _KEY_MAX)
|
||||||
|
scenario = _bounded(scenario_key, "scenario_key", _KEY_MAX)
|
||||||
|
name = _bounded(scenario_name, "scenario_name", _NAME_MAX)
|
||||||
|
started = _aware(occurred_from, "occurred_from")
|
||||||
|
ended = _aware(occurred_to, "occurred_to")
|
||||||
|
if started is not None and ended is not None and started > ended:
|
||||||
|
raise ValidationError(
|
||||||
|
"occurred_from is after occurred_to",
|
||||||
|
details={"field": "occurred_from"},
|
||||||
|
)
|
||||||
|
status_value = _bounded(status, "status", 16)
|
||||||
|
if status_value is not None and status_value not in ALARM_STATUSES:
|
||||||
|
raise ValidationError(
|
||||||
|
"Invalid status",
|
||||||
|
details={"field": "status", "allowed": list(ALARM_STATUSES)},
|
||||||
|
)
|
||||||
|
object_id: uuid.UUID | None = None
|
||||||
|
if mapped_input_id is not None and mapped_input_id.strip():
|
||||||
|
try:
|
||||||
|
object_id = uuid.UUID(mapped_input_id.strip())
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValidationError(
|
||||||
|
"Invalid mapped_input_id",
|
||||||
|
details={"field": "mapped_input_id"},
|
||||||
|
) from exc
|
||||||
|
if subject is None:
|
||||||
|
return {"items": [], "total": 0, "page": page, "page_size": page_size}
|
||||||
|
|
||||||
|
filters = [
|
||||||
|
Alarm.tenant_id == _tenant_id(),
|
||||||
|
MappedInput.tenant_id == _tenant_id(),
|
||||||
|
_scope_clause(subject),
|
||||||
|
]
|
||||||
|
if module is not None:
|
||||||
|
filters.append(Alarm.module_key == module)
|
||||||
|
if scenario is not None:
|
||||||
|
filters.append(Alarm.scenario_key == scenario)
|
||||||
|
if name is not None:
|
||||||
|
filters.append(Alarm.scenario_name.ilike(f"%{name}%"))
|
||||||
|
if status_value is not None:
|
||||||
|
filters.append(Alarm.status == status_value)
|
||||||
|
if object_id is not None:
|
||||||
|
filters.append(Alarm.mapped_input_id == object_id)
|
||||||
|
if started is not None:
|
||||||
|
filters.append(Alarm.last_occurred_at >= started)
|
||||||
|
if ended is not None:
|
||||||
|
filters.append(Alarm.last_occurred_at <= ended)
|
||||||
|
|
||||||
|
joined = select(Alarm).join(MappedInput, MappedInput.id == Alarm.mapped_input_id).where(*filters)
|
||||||
|
total = int(session.scalar(select(func.count()).select_from(joined.subquery())) or 0)
|
||||||
|
order_col = _SORT[sort_by]
|
||||||
|
order_expr = asc(order_col) if sort_order == "asc" else desc(order_col)
|
||||||
|
rows = session.execute(
|
||||||
|
select(Alarm, MappedInput.identity_key)
|
||||||
|
.join(MappedInput, MappedInput.id == Alarm.mapped_input_id)
|
||||||
|
.where(*filters)
|
||||||
|
.order_by(order_expr, asc(Alarm.id))
|
||||||
|
.offset((page - 1) * page_size)
|
||||||
|
.limit(page_size)
|
||||||
|
).all()
|
||||||
|
return {
|
||||||
|
"items": [alarm_public(alarm, identity_key) for alarm, identity_key in rows],
|
||||||
|
"total": total,
|
||||||
|
"page": page,
|
||||||
|
"page_size": page_size,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_alarm(session: Session, alarm_id: str, subject: str | None) -> dict[str, Any]:
|
||||||
|
"""Return one in-scope alarm. Missing and out-of-scope ids are both not found."""
|
||||||
|
alarm, identity_key = _visible(session, alarm_id, subject)
|
||||||
|
return alarm_public(alarm, identity_key)
|
||||||
|
|
||||||
|
|
||||||
|
def list_occurrences(session: Session, alarm_id: str, subject: str | None) -> dict[str, Any]:
|
||||||
|
"""Return formal occurrences for one visible alarm, oldest observation first."""
|
||||||
|
alarm, _identity = _visible(session, alarm_id, subject)
|
||||||
|
rows = session.scalars(
|
||||||
|
select(AlarmOccurrence)
|
||||||
|
.where(
|
||||||
|
AlarmOccurrence.alarm_id == alarm.id,
|
||||||
|
AlarmOccurrence.tenant_id == _tenant_id(),
|
||||||
|
)
|
||||||
|
.order_by(AlarmOccurrence.observed_at.asc(), AlarmOccurrence.id.asc())
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"alarm_id": str(alarm.id),
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"id": str(row.id),
|
||||||
|
"mapped_input_revision_id": str(row.mapped_input_revision_id),
|
||||||
|
"mapping_version_id": str(row.mapping_version_id),
|
||||||
|
"rule_version_id": str(row.rule_version_id),
|
||||||
|
"snapshot_id": str(row.snapshot_id),
|
||||||
|
"snapshot_version_no": row.snapshot_version_no,
|
||||||
|
"module_key": row.module_key,
|
||||||
|
"scenario_key": row.scenario_key,
|
||||||
|
"scenario_name": row.scenario_name,
|
||||||
|
"cycle_key": row.cycle_key,
|
||||||
|
"event_key": row.event_key,
|
||||||
|
"observed_at": _isoformat(row.observed_at),
|
||||||
|
"received_at": _isoformat(row.received_at),
|
||||||
|
"created_at": _isoformat(row.created_at),
|
||||||
|
}
|
||||||
|
for row in rows
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def list_evidence(session: Session, alarm_id: str, subject: str | None) -> dict[str, Any]:
|
||||||
|
"""Return same-cycle revision evidence and closed-repeat basis for one visible alarm.
|
||||||
|
|
||||||
|
Closed basis is a trace of a later formal failure. It is not a recovery.
|
||||||
|
"""
|
||||||
|
alarm, _identity = _visible(session, alarm_id, subject)
|
||||||
|
revisions = session.scalars(
|
||||||
|
select(AlarmRevisionEvidence)
|
||||||
|
.where(
|
||||||
|
AlarmRevisionEvidence.alarm_id == alarm.id,
|
||||||
|
AlarmRevisionEvidence.tenant_id == _tenant_id(),
|
||||||
|
)
|
||||||
|
.order_by(AlarmRevisionEvidence.recorded_at.asc(), AlarmRevisionEvidence.id.asc())
|
||||||
|
)
|
||||||
|
basis_rows = session.scalars(
|
||||||
|
select(AlarmClosedBasis)
|
||||||
|
.where(
|
||||||
|
AlarmClosedBasis.alarm_id == alarm.id,
|
||||||
|
AlarmClosedBasis.tenant_id == _tenant_id(),
|
||||||
|
)
|
||||||
|
.order_by(AlarmClosedBasis.recorded_at.asc(), AlarmClosedBasis.id.asc())
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"alarm_id": str(alarm.id),
|
||||||
|
"revision_evidence": [
|
||||||
|
{
|
||||||
|
"id": str(row.id),
|
||||||
|
"occurrence_id": str(row.occurrence_id),
|
||||||
|
"mapped_input_revision_id": str(row.mapped_input_revision_id),
|
||||||
|
"mapping_version_id": str(row.mapping_version_id),
|
||||||
|
"rule_version_id": str(row.rule_version_id),
|
||||||
|
"snapshot_id": str(row.snapshot_id),
|
||||||
|
"snapshot_version_no": row.snapshot_version_no,
|
||||||
|
"received_at": _isoformat(row.received_at),
|
||||||
|
"recorded_at": _isoformat(row.recorded_at),
|
||||||
|
}
|
||||||
|
for row in revisions
|
||||||
|
],
|
||||||
|
"closed_basis": [
|
||||||
|
{
|
||||||
|
"id": str(row.id),
|
||||||
|
"original_occurrence_id": str(row.original_occurrence_id),
|
||||||
|
"mapped_input_revision_id": str(row.mapped_input_revision_id),
|
||||||
|
"mapping_version_id": str(row.mapping_version_id),
|
||||||
|
"rule_version_id": str(row.rule_version_id),
|
||||||
|
"snapshot_id": str(row.snapshot_id),
|
||||||
|
"snapshot_version_no": row.snapshot_version_no,
|
||||||
|
"cycle_key": row.cycle_key,
|
||||||
|
"event_key": row.event_key,
|
||||||
|
"observed_at": _isoformat(row.observed_at),
|
||||||
|
"received_at": _isoformat(row.received_at),
|
||||||
|
"recorded_at": _isoformat(row.recorded_at),
|
||||||
|
}
|
||||||
|
for row in basis_rows
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def list_history(session: Session, alarm_id: str, subject: str | None) -> dict[str, Any]:
|
||||||
|
"""Return append-only handling events for one visible alarm, in seq order."""
|
||||||
|
alarm, _identity = _visible(session, alarm_id, subject)
|
||||||
|
rows = session.scalars(
|
||||||
|
select(AlarmHandlingEvent)
|
||||||
|
.where(
|
||||||
|
AlarmHandlingEvent.alarm_id == alarm.id,
|
||||||
|
AlarmHandlingEvent.tenant_id == _tenant_id(),
|
||||||
|
)
|
||||||
|
.order_by(AlarmHandlingEvent.seq.asc())
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"alarm_id": str(alarm.id),
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"id": str(row.id),
|
||||||
|
"seq": row.seq,
|
||||||
|
"command": row.command,
|
||||||
|
"actor_subject": row.actor_subject,
|
||||||
|
"actor_role": row.actor_role,
|
||||||
|
"handler_subject": row.handler_subject,
|
||||||
|
"from_status": row.from_status,
|
||||||
|
"to_status": row.to_status,
|
||||||
|
"note": row.note,
|
||||||
|
"close_result": row.close_result,
|
||||||
|
"evidence_ref": row.evidence_ref,
|
||||||
|
"recorded_at": _isoformat(row.recorded_at),
|
||||||
|
}
|
||||||
|
for row in rows
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def read_close_validity(session: Session, alarm_id: str, subject: str | None) -> dict[str, Any]:
|
||||||
|
"""Return the derived close flag after the snapshot scope check.
|
||||||
|
|
||||||
|
The domain function does not apply scope, so this read must not call it
|
||||||
|
for an id the subject cannot see.
|
||||||
|
"""
|
||||||
|
alarm, _identity = _visible(session, alarm_id, subject)
|
||||||
|
validity = close_validity(session, alarm.id)
|
||||||
|
return {
|
||||||
|
"alarm_id": str(validity.alarm_id),
|
||||||
|
"status": validity.status,
|
||||||
|
"unexecuted_intents_should_invalidate": validity.unexecuted_intents_should_invalidate,
|
||||||
|
}
|
||||||
@@ -0,0 +1,733 @@
|
|||||||
|
"""Formal alarm facts: idempotent occurrences and bounded structured merge.
|
||||||
|
|
||||||
|
Boundary: records facts and a closed-repeat basis. Claim, progress, and close
|
||||||
|
live in the handling service. No notifications, trial writes, or caller tenants.
|
||||||
|
Depends on M05 revisions, mapping versions, rule versions, and the server tenant.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import uuid
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import select, text
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from watchman.core.config import get_settings
|
||||||
|
from watchman.core.errors import ConflictError, NotFoundError, ValidationError
|
||||||
|
from watchman.models.alarm import (
|
||||||
|
ALARM_STATUS_CLOSED,
|
||||||
|
ALARM_STATUS_PENDING,
|
||||||
|
Alarm,
|
||||||
|
AlarmOccurrence,
|
||||||
|
AlarmRevisionEvidence,
|
||||||
|
)
|
||||||
|
from watchman.models.alarm_handling import AlarmClosedBasis
|
||||||
|
from watchman.services.platform_records import create_audit_event
|
||||||
|
from watchman.models.mapping import (
|
||||||
|
MappedInput,
|
||||||
|
MappedInputRevision,
|
||||||
|
RuleDefinition,
|
||||||
|
RuleVersion,
|
||||||
|
)
|
||||||
|
|
||||||
|
# NOTE(ai): merge columns are an S1 implementation choice, not a new confirmed rule.
|
||||||
|
# GUARD: do not merge on message text, payload hash, or an unbounded history of a label.
|
||||||
|
# GUARD: a closed merge key stays closed. Continued failures append basis and an audit row.
|
||||||
|
CLOSED_REPEAT_ACTION = "alarm.continued_after_close"
|
||||||
|
_KEY_MAX = 128
|
||||||
|
_NAME_MAX = 256
|
||||||
|
_SUBJECT_KINDS = frozenset({"role", "subject"})
|
||||||
|
_REJECTED_SUBJECTS = frozenset({"*", "all", "tenant", "all_tenant"})
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class SyntheticPublishSnapshot:
|
||||||
|
"""Minimal synthetic publish context carried on a formal fact.
|
||||||
|
|
||||||
|
`handling_scope` must declare an explicit subject. There is no scenario table.
|
||||||
|
"""
|
||||||
|
|
||||||
|
snapshot_id: uuid.UUID
|
||||||
|
version_no: int
|
||||||
|
module_key: str
|
||||||
|
scenario_key: str
|
||||||
|
scenario_name: str
|
||||||
|
handling_scope: dict[str, Any]
|
||||||
|
mapping_version_id: uuid.UUID
|
||||||
|
rule_version_id: uuid.UUID
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class FormalFailure:
|
||||||
|
"""One confirmed abnormal observation. Replay identity includes `observed_at`."""
|
||||||
|
|
||||||
|
mapped_input_revision_id: uuid.UUID
|
||||||
|
snapshot: SyntheticPublishSnapshot
|
||||||
|
observed_at: datetime
|
||||||
|
received_at: datetime
|
||||||
|
cycle_key: str
|
||||||
|
event_key: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class SameCycleCorrection:
|
||||||
|
"""A later revision inside an existing cycle. It must not open an alarm."""
|
||||||
|
|
||||||
|
mapped_input_revision_id: uuid.UUID
|
||||||
|
snapshot: SyntheticPublishSnapshot
|
||||||
|
cycle_key: str
|
||||||
|
event_key: str
|
||||||
|
received_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class AlarmFactResult:
|
||||||
|
"""What the fact write did. Flags stay false on replay and on non-fail outcomes."""
|
||||||
|
|
||||||
|
alarm_id: uuid.UUID
|
||||||
|
occurrence_id: uuid.UUID | None
|
||||||
|
evidence_id: uuid.UUID | None
|
||||||
|
created_alarm: bool
|
||||||
|
created_occurrence: bool
|
||||||
|
created_evidence: bool
|
||||||
|
suppressed: bool
|
||||||
|
basis_id: uuid.UUID | None = None
|
||||||
|
created_basis: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class _Resolved:
|
||||||
|
revision: MappedInputRevision
|
||||||
|
mapped_input: MappedInput
|
||||||
|
rule_version: RuleVersion
|
||||||
|
rule_definition: RuleDefinition
|
||||||
|
snapshot: SyntheticPublishSnapshot
|
||||||
|
observed_at: datetime | None
|
||||||
|
received_at: datetime
|
||||||
|
cycle_key: str
|
||||||
|
event_key: str
|
||||||
|
|
||||||
|
|
||||||
|
def _tenant_id() -> str:
|
||||||
|
# GUARD: tenant_id comes only from server settings, never from the caller.
|
||||||
|
return get_settings().tenant_id
|
||||||
|
|
||||||
|
|
||||||
|
def _now() -> datetime:
|
||||||
|
return datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def _fail(reason: str, field: str | None = None) -> ValidationError:
|
||||||
|
details: dict[str, Any] = {"reason": reason}
|
||||||
|
if field is not None:
|
||||||
|
details["field"] = field
|
||||||
|
return ValidationError("Invalid alarm fact", details=details)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_uuid(value: object, field: str) -> uuid.UUID:
|
||||||
|
if not isinstance(value, uuid.UUID):
|
||||||
|
raise _fail("snapshot_field_invalid", field)
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _require_version(value: object) -> int:
|
||||||
|
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
|
||||||
|
raise _fail("snapshot_field_invalid", "version_no")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _require_key(value: object, field: str, limit: int) -> str:
|
||||||
|
if not isinstance(value, str):
|
||||||
|
raise _fail("snapshot_field_invalid", field)
|
||||||
|
cleaned = value.strip()
|
||||||
|
if not cleaned or len(cleaned) > limit or any(char in cleaned for char in "\r\n"):
|
||||||
|
raise _fail("merge_key_not_text", field)
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
|
def _require_aware(value: object, field: str) -> datetime:
|
||||||
|
if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None:
|
||||||
|
raise _fail("timestamp_timezone_required", field)
|
||||||
|
return value.astimezone(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_scope(scope: object) -> dict[str, Any]:
|
||||||
|
"""Reject a missing scope and any all-tenant operator default.
|
||||||
|
|
||||||
|
A subject entry is required so a role name alone cannot cover the tenant.
|
||||||
|
That requirement is an implementation assumption, not a confirmed auth model.
|
||||||
|
"""
|
||||||
|
if not isinstance(scope, dict) or "all_tenant" in scope:
|
||||||
|
reason = (
|
||||||
|
"snapshot_scope_rejects_all_tenant"
|
||||||
|
if isinstance(scope, dict) and "all_tenant" in scope
|
||||||
|
else "snapshot_scope_missing"
|
||||||
|
)
|
||||||
|
raise _fail(reason, "handling_scope")
|
||||||
|
principals = scope.get("principals")
|
||||||
|
if not isinstance(principals, list) or not principals:
|
||||||
|
raise _fail("snapshot_scope_missing", "handling_scope")
|
||||||
|
normalized: list[dict[str, str]] = []
|
||||||
|
for item in principals:
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
raise _fail("snapshot_scope_missing", "handling_scope")
|
||||||
|
kind = item.get("kind")
|
||||||
|
raw_value = item.get("value")
|
||||||
|
if kind not in _SUBJECT_KINDS or not isinstance(raw_value, str):
|
||||||
|
raise _fail("snapshot_scope_missing", "handling_scope")
|
||||||
|
cleaned = raw_value.strip()
|
||||||
|
if not cleaned or cleaned.casefold() in _REJECTED_SUBJECTS:
|
||||||
|
raise _fail("snapshot_scope_rejects_all_tenant", "handling_scope")
|
||||||
|
normalized.append({"kind": kind, "value": cleaned})
|
||||||
|
if not any(item["kind"] == "subject" for item in normalized):
|
||||||
|
raise _fail("snapshot_scope_rejects_all_tenant", "handling_scope")
|
||||||
|
return {"principals": normalized}
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_snapshot(snapshot: SyntheticPublishSnapshot) -> SyntheticPublishSnapshot:
|
||||||
|
if not isinstance(snapshot, SyntheticPublishSnapshot):
|
||||||
|
raise _fail("snapshot_field_invalid", "snapshot")
|
||||||
|
return SyntheticPublishSnapshot(
|
||||||
|
snapshot_id=_require_uuid(snapshot.snapshot_id, "snapshot_id"),
|
||||||
|
version_no=_require_version(snapshot.version_no),
|
||||||
|
module_key=_require_key(snapshot.module_key, "module_key", _KEY_MAX),
|
||||||
|
scenario_key=_require_key(snapshot.scenario_key, "scenario_key", _KEY_MAX),
|
||||||
|
scenario_name=_require_key(snapshot.scenario_name, "scenario_name", _NAME_MAX),
|
||||||
|
handling_scope=_require_scope(snapshot.handling_scope),
|
||||||
|
mapping_version_id=_require_uuid(snapshot.mapping_version_id, "mapping_version_id"),
|
||||||
|
rule_version_id=_require_uuid(snapshot.rule_version_id, "rule_version_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _load_refs(
|
||||||
|
session: Session,
|
||||||
|
*,
|
||||||
|
revision_id: uuid.UUID,
|
||||||
|
snapshot: SyntheticPublishSnapshot,
|
||||||
|
cycle_key: str,
|
||||||
|
event_key: str,
|
||||||
|
received_at: datetime,
|
||||||
|
observed_at: datetime | None,
|
||||||
|
) -> _Resolved:
|
||||||
|
"""Load the M05 revision and rule cited by the snapshot, or refuse the write."""
|
||||||
|
if not isinstance(revision_id, uuid.UUID):
|
||||||
|
raise NotFoundError("Mapped input revision not found")
|
||||||
|
normalized = _normalize_snapshot(snapshot)
|
||||||
|
cycle = _require_key(cycle_key, "cycle_key", _KEY_MAX)
|
||||||
|
event = _require_key(event_key, "event_key", _KEY_MAX)
|
||||||
|
received = _require_aware(received_at, "received_at")
|
||||||
|
observed = _require_aware(observed_at, "observed_at") if observed_at is not None else None
|
||||||
|
tenant_id = _tenant_id()
|
||||||
|
revision = session.scalar(
|
||||||
|
select(MappedInputRevision).where(
|
||||||
|
MappedInputRevision.id == revision_id,
|
||||||
|
MappedInputRevision.tenant_id == tenant_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if revision is None:
|
||||||
|
raise NotFoundError("Mapped input revision not found")
|
||||||
|
if revision.mapping_version_id != normalized.mapping_version_id:
|
||||||
|
raise _fail("snapshot_version_mismatch", "mapping_version_id")
|
||||||
|
mapped_input = session.scalar(
|
||||||
|
select(MappedInput).where(
|
||||||
|
MappedInput.id == revision.input_id,
|
||||||
|
MappedInput.tenant_id == tenant_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if mapped_input is None:
|
||||||
|
raise NotFoundError("Mapped input not found")
|
||||||
|
rule_version = session.scalar(
|
||||||
|
select(RuleVersion).where(
|
||||||
|
RuleVersion.id == normalized.rule_version_id,
|
||||||
|
RuleVersion.tenant_id == tenant_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if rule_version is None:
|
||||||
|
raise NotFoundError("Rule version not found")
|
||||||
|
rule_definition = session.scalar(
|
||||||
|
select(RuleDefinition).where(
|
||||||
|
RuleDefinition.id == rule_version.definition_id,
|
||||||
|
RuleDefinition.tenant_id == tenant_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if rule_definition is None or rule_definition.mapping_definition_id != mapped_input.mapping_definition_id:
|
||||||
|
raise _fail("rule_mapping_mismatch", "rule_version_id")
|
||||||
|
return _Resolved(
|
||||||
|
revision=revision,
|
||||||
|
mapped_input=mapped_input,
|
||||||
|
rule_version=rule_version,
|
||||||
|
rule_definition=rule_definition,
|
||||||
|
snapshot=normalized,
|
||||||
|
observed_at=observed,
|
||||||
|
received_at=received,
|
||||||
|
cycle_key=cycle,
|
||||||
|
event_key=event,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def lock_alarm_subject(
|
||||||
|
session: Session,
|
||||||
|
*,
|
||||||
|
module_key: str,
|
||||||
|
scenario_key: str,
|
||||||
|
mapped_input_id: uuid.UUID,
|
||||||
|
) -> None:
|
||||||
|
"""Hold the subject advisory lock until this transaction ends.
|
||||||
|
|
||||||
|
Fact writes and handling transitions share this token so a close cannot
|
||||||
|
interleave with a merge. Callers take it before SELECT FOR UPDATE.
|
||||||
|
The token is tenant, module, scenario, and mapped input, not the cycle.
|
||||||
|
"""
|
||||||
|
token = "|".join((_tenant_id(), module_key, scenario_key, str(mapped_input_id)))
|
||||||
|
session.execute(
|
||||||
|
text("SELECT pg_advisory_xact_lock(hashtextextended(:token, 0))"),
|
||||||
|
{"token": token},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _lock_subject(session: Session, refs: _Resolved) -> None:
|
||||||
|
"""Serialize create/merge for one scenario subject until this transaction ends."""
|
||||||
|
lock_alarm_subject(
|
||||||
|
session,
|
||||||
|
module_key=refs.snapshot.module_key,
|
||||||
|
scenario_key=refs.snapshot.scenario_key,
|
||||||
|
mapped_input_id=refs.mapped_input.id,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _find_occurrence(session: Session, refs: _Resolved) -> AlarmOccurrence | None:
|
||||||
|
assert refs.observed_at is not None
|
||||||
|
return session.scalar(
|
||||||
|
select(AlarmOccurrence)
|
||||||
|
.where(
|
||||||
|
AlarmOccurrence.tenant_id == _tenant_id(),
|
||||||
|
AlarmOccurrence.mapped_input_revision_id == refs.revision.id,
|
||||||
|
AlarmOccurrence.mapping_version_id == refs.snapshot.mapping_version_id,
|
||||||
|
AlarmOccurrence.rule_version_id == refs.rule_version.id,
|
||||||
|
AlarmOccurrence.snapshot_id == refs.snapshot.snapshot_id,
|
||||||
|
AlarmOccurrence.cycle_key == refs.cycle_key,
|
||||||
|
AlarmOccurrence.event_key == refs.event_key,
|
||||||
|
AlarmOccurrence.observed_at == refs.observed_at,
|
||||||
|
)
|
||||||
|
.execution_options(populate_existing=True)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _find_alarm(session: Session, refs: _Resolved) -> Alarm | None:
|
||||||
|
snapshot = refs.snapshot
|
||||||
|
return session.scalar(
|
||||||
|
select(Alarm)
|
||||||
|
.where(
|
||||||
|
Alarm.tenant_id == _tenant_id(),
|
||||||
|
Alarm.module_key == snapshot.module_key,
|
||||||
|
Alarm.scenario_key == snapshot.scenario_key,
|
||||||
|
Alarm.mapped_input_id == refs.mapped_input.id,
|
||||||
|
Alarm.cycle_key == refs.cycle_key,
|
||||||
|
Alarm.event_key == refs.event_key,
|
||||||
|
)
|
||||||
|
.execution_options(populate_existing=True)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _latest_alarm(session: Session, refs: _Resolved) -> Alarm | None:
|
||||||
|
snapshot = refs.snapshot
|
||||||
|
return session.scalar(
|
||||||
|
select(Alarm)
|
||||||
|
.where(
|
||||||
|
Alarm.tenant_id == _tenant_id(),
|
||||||
|
Alarm.module_key == snapshot.module_key,
|
||||||
|
Alarm.scenario_key == snapshot.scenario_key,
|
||||||
|
Alarm.mapped_input_id == refs.mapped_input.id,
|
||||||
|
)
|
||||||
|
.order_by(Alarm.opened_at.desc(), Alarm.id.desc())
|
||||||
|
.limit(1)
|
||||||
|
.with_for_update()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _original_occurrence(session: Session, alarm_id: uuid.UUID) -> AlarmOccurrence | None:
|
||||||
|
return session.scalar(
|
||||||
|
select(AlarmOccurrence)
|
||||||
|
.where(
|
||||||
|
AlarmOccurrence.tenant_id == _tenant_id(),
|
||||||
|
AlarmOccurrence.alarm_id == alarm_id,
|
||||||
|
)
|
||||||
|
.order_by(AlarmOccurrence.created_at.asc(), AlarmOccurrence.id.asc())
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _find_evidence(session: Session, alarm_id: uuid.UUID, revision_id: uuid.UUID) -> AlarmRevisionEvidence | None:
|
||||||
|
return session.scalar(
|
||||||
|
select(AlarmRevisionEvidence)
|
||||||
|
.where(
|
||||||
|
AlarmRevisionEvidence.tenant_id == _tenant_id(),
|
||||||
|
AlarmRevisionEvidence.alarm_id == alarm_id,
|
||||||
|
AlarmRevisionEvidence.mapped_input_revision_id == revision_id,
|
||||||
|
)
|
||||||
|
.execution_options(populate_existing=True)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _result(
|
||||||
|
*,
|
||||||
|
alarm_id: uuid.UUID,
|
||||||
|
occurrence_id: uuid.UUID | None = None,
|
||||||
|
evidence_id: uuid.UUID | None = None,
|
||||||
|
created_alarm: bool = False,
|
||||||
|
created_occurrence: bool = False,
|
||||||
|
created_evidence: bool = False,
|
||||||
|
suppressed: bool = False,
|
||||||
|
basis_id: uuid.UUID | None = None,
|
||||||
|
created_basis: bool = False,
|
||||||
|
) -> AlarmFactResult:
|
||||||
|
return AlarmFactResult(
|
||||||
|
alarm_id=alarm_id,
|
||||||
|
occurrence_id=occurrence_id,
|
||||||
|
evidence_id=evidence_id,
|
||||||
|
created_alarm=created_alarm,
|
||||||
|
created_occurrence=created_occurrence,
|
||||||
|
created_evidence=created_evidence,
|
||||||
|
suppressed=suppressed,
|
||||||
|
basis_id=basis_id,
|
||||||
|
created_basis=created_basis,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _new_alarm(refs: _Resolved, previous: Alarm | None) -> Alarm:
|
||||||
|
assert refs.observed_at is not None
|
||||||
|
snapshot = refs.snapshot
|
||||||
|
return Alarm(
|
||||||
|
tenant_id=_tenant_id(),
|
||||||
|
status=ALARM_STATUS_PENDING,
|
||||||
|
current_handler=None,
|
||||||
|
occurrence_count=1,
|
||||||
|
first_occurred_at=refs.observed_at,
|
||||||
|
last_occurred_at=refs.observed_at,
|
||||||
|
previous_alarm_id=None if previous is None else previous.id,
|
||||||
|
mapped_input_id=refs.mapped_input.id,
|
||||||
|
mapping_definition_id=refs.mapped_input.mapping_definition_id,
|
||||||
|
mapping_version_id=refs.revision.mapping_version_id,
|
||||||
|
rule_definition_id=refs.rule_definition.id,
|
||||||
|
rule_version_id=refs.rule_version.id,
|
||||||
|
snapshot_id=snapshot.snapshot_id,
|
||||||
|
snapshot_version_no=snapshot.version_no,
|
||||||
|
module_key=snapshot.module_key,
|
||||||
|
scenario_key=snapshot.scenario_key,
|
||||||
|
scenario_name=snapshot.scenario_name,
|
||||||
|
handling_scope=snapshot.handling_scope,
|
||||||
|
cycle_key=refs.cycle_key,
|
||||||
|
event_key=refs.event_key,
|
||||||
|
opened_at=_now(),
|
||||||
|
updated_at=_now(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _new_occurrence(refs: _Resolved, alarm_id: uuid.UUID) -> AlarmOccurrence:
|
||||||
|
assert refs.observed_at is not None
|
||||||
|
snapshot = refs.snapshot
|
||||||
|
return AlarmOccurrence(
|
||||||
|
tenant_id=_tenant_id(),
|
||||||
|
alarm_id=alarm_id,
|
||||||
|
mapped_input_id=refs.mapped_input.id,
|
||||||
|
mapped_input_revision_id=refs.revision.id,
|
||||||
|
mapping_definition_id=refs.mapped_input.mapping_definition_id,
|
||||||
|
mapping_version_id=refs.revision.mapping_version_id,
|
||||||
|
rule_definition_id=refs.rule_definition.id,
|
||||||
|
rule_version_id=refs.rule_version.id,
|
||||||
|
snapshot_id=snapshot.snapshot_id,
|
||||||
|
snapshot_version_no=snapshot.version_no,
|
||||||
|
module_key=snapshot.module_key,
|
||||||
|
scenario_key=snapshot.scenario_key,
|
||||||
|
scenario_name=snapshot.scenario_name,
|
||||||
|
handling_scope=snapshot.handling_scope,
|
||||||
|
cycle_key=refs.cycle_key,
|
||||||
|
event_key=refs.event_key,
|
||||||
|
observed_at=refs.observed_at,
|
||||||
|
received_at=refs.received_at,
|
||||||
|
created_at=_now(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _attach(session: Session, alarm: Alarm, refs: _Resolved) -> AlarmFactResult:
|
||||||
|
"""Add one occurrence to an open alarm without changing its original snapshot."""
|
||||||
|
occurrence = _new_occurrence(refs, alarm.id)
|
||||||
|
try:
|
||||||
|
with session.begin_nested():
|
||||||
|
session.add(occurrence)
|
||||||
|
alarm.occurrence_count += 1
|
||||||
|
assert refs.observed_at is not None
|
||||||
|
if refs.observed_at > alarm.last_occurred_at:
|
||||||
|
alarm.last_occurred_at = refs.observed_at
|
||||||
|
alarm.updated_at = _now()
|
||||||
|
session.flush()
|
||||||
|
except IntegrityError:
|
||||||
|
session.expire_all()
|
||||||
|
existing = _find_occurrence(session, refs)
|
||||||
|
if existing is None:
|
||||||
|
raise
|
||||||
|
return _result(alarm_id=existing.alarm_id, occurrence_id=existing.id)
|
||||||
|
return _result(
|
||||||
|
alarm_id=alarm.id,
|
||||||
|
occurrence_id=occurrence.id,
|
||||||
|
created_occurrence=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _find_closed_basis(session: Session, refs: _Resolved) -> AlarmClosedBasis | None:
|
||||||
|
assert refs.observed_at is not None
|
||||||
|
return session.scalar(
|
||||||
|
select(AlarmClosedBasis)
|
||||||
|
.where(
|
||||||
|
AlarmClosedBasis.tenant_id == _tenant_id(),
|
||||||
|
AlarmClosedBasis.mapped_input_revision_id == refs.revision.id,
|
||||||
|
AlarmClosedBasis.mapping_version_id == refs.snapshot.mapping_version_id,
|
||||||
|
AlarmClosedBasis.rule_version_id == refs.rule_version.id,
|
||||||
|
AlarmClosedBasis.snapshot_id == refs.snapshot.snapshot_id,
|
||||||
|
AlarmClosedBasis.cycle_key == refs.cycle_key,
|
||||||
|
AlarmClosedBasis.event_key == refs.event_key,
|
||||||
|
AlarmClosedBasis.observed_at == refs.observed_at,
|
||||||
|
)
|
||||||
|
.execution_options(populate_existing=True)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _closed_audit_key(alarm_id: uuid.UUID, refs: _Resolved) -> str:
|
||||||
|
assert refs.observed_at is not None
|
||||||
|
identity = "|".join(
|
||||||
|
(
|
||||||
|
str(alarm_id),
|
||||||
|
str(refs.revision.id),
|
||||||
|
str(refs.snapshot.mapping_version_id),
|
||||||
|
str(refs.rule_version.id),
|
||||||
|
str(refs.snapshot.snapshot_id),
|
||||||
|
refs.cycle_key,
|
||||||
|
refs.event_key,
|
||||||
|
refs.observed_at.isoformat(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
digest = hashlib.sha256(identity.encode("utf-8")).hexdigest()
|
||||||
|
return f"{CLOSED_REPEAT_ACTION}:{digest}"[:128]
|
||||||
|
|
||||||
|
|
||||||
|
def _record_closed_basis(session: Session, alarm: Alarm, refs: _Resolved) -> AlarmFactResult:
|
||||||
|
"""Append a trace for a formal failure on an already closed merge key.
|
||||||
|
|
||||||
|
Does not reopen the alarm, open another one, or change the original FAIL.
|
||||||
|
A replay of the same formal identity returns the existing basis and does
|
||||||
|
not write a second audit row. Raises ConflictError when the closed alarm
|
||||||
|
has no original occurrence to point at.
|
||||||
|
"""
|
||||||
|
# GUARD: closed merge keys stay closed. Do not insert an occurrence here.
|
||||||
|
assert refs.observed_at is not None
|
||||||
|
alarm_id = alarm.id
|
||||||
|
existing = _find_closed_basis(session, refs)
|
||||||
|
if existing is not None:
|
||||||
|
return _result(alarm_id=alarm_id, basis_id=existing.id, suppressed=True)
|
||||||
|
anchor = _original_occurrence(session, alarm_id)
|
||||||
|
if anchor is None:
|
||||||
|
raise ConflictError(
|
||||||
|
"Closed alarm has no original fact",
|
||||||
|
details={"reason": "closed_basis_without_occurrence"},
|
||||||
|
)
|
||||||
|
basis = AlarmClosedBasis(
|
||||||
|
tenant_id=_tenant_id(),
|
||||||
|
alarm_id=alarm_id,
|
||||||
|
original_occurrence_id=anchor.id,
|
||||||
|
mapped_input_revision_id=refs.revision.id,
|
||||||
|
mapping_version_id=refs.snapshot.mapping_version_id,
|
||||||
|
rule_version_id=refs.rule_version.id,
|
||||||
|
snapshot_id=refs.snapshot.snapshot_id,
|
||||||
|
snapshot_version_no=refs.snapshot.version_no,
|
||||||
|
cycle_key=refs.cycle_key,
|
||||||
|
event_key=refs.event_key,
|
||||||
|
observed_at=refs.observed_at,
|
||||||
|
received_at=refs.received_at,
|
||||||
|
recorded_at=_now(),
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with session.begin_nested():
|
||||||
|
session.add(basis)
|
||||||
|
session.flush()
|
||||||
|
except IntegrityError:
|
||||||
|
session.expire_all()
|
||||||
|
existing = _find_closed_basis(session, refs)
|
||||||
|
if existing is None:
|
||||||
|
raise
|
||||||
|
return _result(alarm_id=alarm_id, basis_id=existing.id, suppressed=True)
|
||||||
|
create_audit_event(
|
||||||
|
session,
|
||||||
|
action=CLOSED_REPEAT_ACTION,
|
||||||
|
payload={
|
||||||
|
"alarm_id": str(alarm_id),
|
||||||
|
"basis_id": str(basis.id),
|
||||||
|
"original_occurrence_id": str(anchor.id),
|
||||||
|
"mapped_input_revision_id": str(refs.revision.id),
|
||||||
|
"cycle_key": refs.cycle_key,
|
||||||
|
"event_key": refs.event_key,
|
||||||
|
"observed_at": refs.observed_at.isoformat(),
|
||||||
|
"reason": "closed_merge_key",
|
||||||
|
},
|
||||||
|
idempotency_key=_closed_audit_key(alarm_id, refs),
|
||||||
|
)
|
||||||
|
return _result(alarm_id=alarm_id, basis_id=basis.id, created_basis=True, suppressed=True)
|
||||||
|
|
||||||
|
|
||||||
|
def record_formal_failure(
|
||||||
|
session: Session,
|
||||||
|
failure: FormalFailure,
|
||||||
|
*,
|
||||||
|
confirmed_abnormal: bool = False,
|
||||||
|
) -> AlarmFactResult | None:
|
||||||
|
"""Create or reuse one formal FAIL occurrence and its bounded alarm.
|
||||||
|
|
||||||
|
Input is an already confirmed abnormal fact. `confirmed_abnormal` must be
|
||||||
|
true; otherwise the call writes nothing. Output is the existing row on
|
||||||
|
replay, a closed-key basis, or the row just inserted.
|
||||||
|
Raises NotFoundError or ValidationError before any insert when the
|
||||||
|
revision, rule, or snapshot does not hang together. A closed merge key
|
||||||
|
does not reopen or open another alarm; it appends a basis and an audit row.
|
||||||
|
"""
|
||||||
|
# GUARD: PASS / UNKNOWN / failure / trial must not reach this with True.
|
||||||
|
if confirmed_abnormal is not True:
|
||||||
|
return None
|
||||||
|
if not isinstance(failure, FormalFailure):
|
||||||
|
raise _fail("snapshot_field_invalid", "failure")
|
||||||
|
refs = _load_refs(
|
||||||
|
session,
|
||||||
|
revision_id=failure.mapped_input_revision_id,
|
||||||
|
snapshot=failure.snapshot,
|
||||||
|
cycle_key=failure.cycle_key,
|
||||||
|
event_key=failure.event_key,
|
||||||
|
received_at=failure.received_at,
|
||||||
|
observed_at=failure.observed_at,
|
||||||
|
)
|
||||||
|
_lock_subject(session, refs)
|
||||||
|
existing = _find_occurrence(session, refs)
|
||||||
|
if existing is not None:
|
||||||
|
return _result(alarm_id=existing.alarm_id, occurrence_id=existing.id)
|
||||||
|
alarm = _find_alarm(session, refs)
|
||||||
|
if alarm is not None and alarm.status == ALARM_STATUS_CLOSED:
|
||||||
|
return _record_closed_basis(session, alarm, refs)
|
||||||
|
if alarm is None:
|
||||||
|
previous = _latest_alarm(session, refs)
|
||||||
|
alarm = _new_alarm(refs, previous)
|
||||||
|
try:
|
||||||
|
with session.begin_nested():
|
||||||
|
session.add(alarm)
|
||||||
|
session.flush()
|
||||||
|
occurrence = _new_occurrence(refs, alarm.id)
|
||||||
|
session.add(occurrence)
|
||||||
|
session.flush()
|
||||||
|
except IntegrityError:
|
||||||
|
session.expire_all()
|
||||||
|
raced = _find_occurrence(session, refs)
|
||||||
|
if raced is not None:
|
||||||
|
return _result(alarm_id=raced.alarm_id, occurrence_id=raced.id)
|
||||||
|
alarm = _find_alarm(session, refs)
|
||||||
|
if alarm is None:
|
||||||
|
raise
|
||||||
|
if alarm.status == ALARM_STATUS_CLOSED:
|
||||||
|
return _record_closed_basis(session, alarm, refs)
|
||||||
|
return _attach(session, alarm, refs)
|
||||||
|
return _result(
|
||||||
|
alarm_id=alarm.id,
|
||||||
|
occurrence_id=occurrence.id,
|
||||||
|
created_alarm=True,
|
||||||
|
created_occurrence=True,
|
||||||
|
)
|
||||||
|
return _attach(session, alarm, refs)
|
||||||
|
|
||||||
|
|
||||||
|
def append_same_cycle_revision(session: Session, correction: SameCycleCorrection) -> AlarmFactResult:
|
||||||
|
"""Append a same-cycle revision without a new alarm or a rewritten FAIL.
|
||||||
|
|
||||||
|
Requires an alarm already opened for that structured key. A missing alarm
|
||||||
|
raises ConflictError and writes nothing. Replaying the original revision
|
||||||
|
or the same correction returns the existing basis.
|
||||||
|
"""
|
||||||
|
if not isinstance(correction, SameCycleCorrection):
|
||||||
|
raise _fail("snapshot_field_invalid", "correction")
|
||||||
|
refs = _load_refs(
|
||||||
|
session,
|
||||||
|
revision_id=correction.mapped_input_revision_id,
|
||||||
|
snapshot=correction.snapshot,
|
||||||
|
cycle_key=correction.cycle_key,
|
||||||
|
event_key=correction.event_key,
|
||||||
|
received_at=correction.received_at,
|
||||||
|
observed_at=None,
|
||||||
|
)
|
||||||
|
_lock_subject(session, refs)
|
||||||
|
alarm = _find_alarm(session, refs)
|
||||||
|
if alarm is None:
|
||||||
|
raise ConflictError(
|
||||||
|
"Same-cycle correction does not open an alarm",
|
||||||
|
details={"reason": "correction_without_alarm"},
|
||||||
|
)
|
||||||
|
anchor = _original_occurrence(session, alarm.id)
|
||||||
|
if anchor is None:
|
||||||
|
raise ConflictError(
|
||||||
|
"Same-cycle correction has no original fact",
|
||||||
|
details={"reason": "correction_without_occurrence"},
|
||||||
|
)
|
||||||
|
if refs.revision.id == anchor.mapped_input_revision_id:
|
||||||
|
return _result(alarm_id=alarm.id, occurrence_id=anchor.id)
|
||||||
|
existing = _find_evidence(session, alarm.id, refs.revision.id)
|
||||||
|
if existing is not None:
|
||||||
|
return _result(alarm_id=alarm.id, occurrence_id=anchor.id, evidence_id=existing.id)
|
||||||
|
evidence = AlarmRevisionEvidence(
|
||||||
|
tenant_id=_tenant_id(),
|
||||||
|
alarm_id=alarm.id,
|
||||||
|
occurrence_id=anchor.id,
|
||||||
|
mapped_input_revision_id=refs.revision.id,
|
||||||
|
mapping_version_id=refs.revision.mapping_version_id,
|
||||||
|
rule_version_id=refs.rule_version.id,
|
||||||
|
snapshot_id=refs.snapshot.snapshot_id,
|
||||||
|
snapshot_version_no=refs.snapshot.version_no,
|
||||||
|
received_at=refs.received_at,
|
||||||
|
recorded_at=_now(),
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with session.begin_nested():
|
||||||
|
session.add(evidence)
|
||||||
|
session.flush()
|
||||||
|
except IntegrityError:
|
||||||
|
session.expire_all()
|
||||||
|
existing = _find_evidence(session, alarm.id, refs.revision.id)
|
||||||
|
if existing is None:
|
||||||
|
raise
|
||||||
|
return _result(alarm_id=alarm.id, occurrence_id=anchor.id, evidence_id=existing.id)
|
||||||
|
return _result(
|
||||||
|
alarm_id=alarm.id,
|
||||||
|
occurrence_id=anchor.id,
|
||||||
|
evidence_id=evidence.id,
|
||||||
|
created_evidence=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def apply_monitored_outcome(
|
||||||
|
session: Session,
|
||||||
|
*,
|
||||||
|
source: str,
|
||||||
|
outcome: str,
|
||||||
|
code: str | None = None,
|
||||||
|
failure: FormalFailure | None = None,
|
||||||
|
) -> AlarmFactResult | None:
|
||||||
|
"""Record a fact only for a formal abnormal result. Every other outcome is a no-op.
|
||||||
|
|
||||||
|
`source` must be ``formal``. Trial runs, normal, unknown, empty, and error
|
||||||
|
results return None before any alarm read that could insert. A formal
|
||||||
|
abnormal result without a failure payload raises ValidationError and still
|
||||||
|
does not insert.
|
||||||
|
"""
|
||||||
|
# GUARD: trial and non-abnormal outcomes have zero alarm side effects.
|
||||||
|
if source != "formal" or outcome != "result" or code != "abnormal":
|
||||||
|
return None
|
||||||
|
if failure is None:
|
||||||
|
raise _fail("formal_failure_required", "failure")
|
||||||
|
return record_formal_failure(session, failure, confirmed_abnormal=True)
|
||||||
@@ -0,0 +1,610 @@
|
|||||||
|
"""S3 alarm API authorization on PostgreSQL.
|
||||||
|
|
||||||
|
Why: list, detail, and the three commands must enforce the D38 nodes plus
|
||||||
|
snapshot subject scope, and conflicts must stay on the existing envelope.
|
||||||
|
Boundary: does not cover the Vue console, a new role, or a new error code.
|
||||||
|
Depends on S1 facts, S2 handling, and the session cookie.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from sqlalchemy import delete
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from test_alarm_occurrences import ( # type: ignore[attr-defined]
|
||||||
|
OBSERVED,
|
||||||
|
RECEIVED,
|
||||||
|
alarm_db,
|
||||||
|
_build,
|
||||||
|
_revise,
|
||||||
|
_snapshot,
|
||||||
|
)
|
||||||
|
from watchman.api.app import create_app
|
||||||
|
from watchman.auth.access import (
|
||||||
|
ALARM_CLOSE_NODE,
|
||||||
|
ALARM_PROGRESS_NODE,
|
||||||
|
ALARM_READ_NODE,
|
||||||
|
ALARM_TAKE_NODE,
|
||||||
|
ENTER_ROLES,
|
||||||
|
ROLE_ADMIN,
|
||||||
|
ROLE_OPERATOR,
|
||||||
|
ROLE_VIEWER,
|
||||||
|
require_alarm_close,
|
||||||
|
require_alarm_progress,
|
||||||
|
require_alarm_read,
|
||||||
|
require_alarm_take,
|
||||||
|
)
|
||||||
|
from watchman.auth.principal import get_role_directory
|
||||||
|
from watchman.auth.sessions import SESSION_COOKIE_NAME, hash_cookie_token, issue_cookie_token
|
||||||
|
from watchman.core.config import reload_settings
|
||||||
|
from watchman.core.db import reset_engine, set_tenant
|
||||||
|
from watchman.core.errors import ForbiddenError
|
||||||
|
from watchman.models.auth_session import AuthSession
|
||||||
|
from watchman.services.alarms import (
|
||||||
|
FormalFailure,
|
||||||
|
SameCycleCorrection,
|
||||||
|
append_same_cycle_revision,
|
||||||
|
apply_monitored_outcome,
|
||||||
|
)
|
||||||
|
|
||||||
|
OP = "op-line"
|
||||||
|
OTHER_OP = "op-other"
|
||||||
|
ADMIN = "admin-line"
|
||||||
|
OUTSIDER = "outside-line"
|
||||||
|
D38_NODES = (
|
||||||
|
"perm:data:emp:watchman.alarm.read",
|
||||||
|
"perm:data:emp:watchman.alarm.take",
|
||||||
|
"perm:data:emp:watchman.alarm.progress",
|
||||||
|
"perm:data:emp:watchman.alarm.close",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def alarm_api(alarm_db): # type: ignore[no-untyped-def]
|
||||||
|
"""Reuse the alarm database fixture and delete only this test's sessions."""
|
||||||
|
factory, registry, settings = alarm_db
|
||||||
|
tokens: list[str] = []
|
||||||
|
yield factory, registry, settings, tokens
|
||||||
|
session = factory()
|
||||||
|
try:
|
||||||
|
set_tenant(session, settings.tenant_id)
|
||||||
|
if tokens:
|
||||||
|
session.execute(
|
||||||
|
delete(AuthSession).where(
|
||||||
|
AuthSession.token_hash.in_([hash_cookie_token(token) for token in tokens])
|
||||||
|
)
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_alarm_nodes_stay_on_the_approved_d38_literals() -> None:
|
||||||
|
"""D38 is the only alarm permission set, and the three role names stay put."""
|
||||||
|
assert (ALARM_READ_NODE, ALARM_TAKE_NODE, ALARM_PROGRESS_NODE, ALARM_CLOSE_NODE) == D38_NODES
|
||||||
|
assert ENTER_ROLES == frozenset({ROLE_ADMIN, ROLE_OPERATOR, ROLE_VIEWER})
|
||||||
|
require_alarm_read([ROLE_VIEWER])
|
||||||
|
require_alarm_take([ROLE_OPERATOR])
|
||||||
|
require_alarm_progress([ROLE_ADMIN])
|
||||||
|
require_alarm_close([ROLE_ADMIN, ROLE_VIEWER])
|
||||||
|
with pytest.raises(ForbiddenError) as denied:
|
||||||
|
require_alarm_take([ROLE_VIEWER])
|
||||||
|
assert denied.value.code == 42000
|
||||||
|
assert denied.value.permission_node == ALARM_TAKE_NODE
|
||||||
|
with pytest.raises(ForbiddenError) as unknown:
|
||||||
|
require_alarm_read(["watchman-alarm"])
|
||||||
|
assert unknown.value.permission_node == ALARM_READ_NODE
|
||||||
|
|
||||||
|
|
||||||
|
def test_reads_honor_role_and_snapshot_scope(alarm_api) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""A-040: in-scope roles can read; an outside id and a missing cookie cannot."""
|
||||||
|
factory, registry, settings, tokens = alarm_api
|
||||||
|
visible, hidden = _open_pair(factory, registry, settings)
|
||||||
|
viewer = _client(factory, settings, tokens, roles=[ROLE_VIEWER], subject=OP)
|
||||||
|
outsider = _client(factory, settings, tokens, roles=[ROLE_OPERATOR], subject=OUTSIDER)
|
||||||
|
blank = _client(factory, settings, tokens, roles=[ROLE_OPERATOR], subject=" ")
|
||||||
|
unknown = _client(factory, settings, tokens, roles=["watchman-alarm"], subject=OP)
|
||||||
|
anon = _client(factory, settings, tokens, roles=None, subject=OP)
|
||||||
|
|
||||||
|
listed = viewer.get("/alarms")
|
||||||
|
assert listed.status_code == 200, listed.text
|
||||||
|
body = listed.json()
|
||||||
|
assert body["success"] is True
|
||||||
|
assert body["request_id"]
|
||||||
|
ids = {item["id"] for item in body["data"]["items"]}
|
||||||
|
assert visible in ids
|
||||||
|
assert hidden not in ids
|
||||||
|
assert "tenant_id" not in body["data"]["items"][0]
|
||||||
|
assert "handling_scope" not in body["data"]["items"][0]
|
||||||
|
assert "recovered" not in body["data"]["items"][0]
|
||||||
|
|
||||||
|
detail = viewer.get(f"/alarms/{visible}")
|
||||||
|
assert detail.status_code == 200, detail.text
|
||||||
|
assert detail.json()["data"]["id"] == visible
|
||||||
|
assert detail.json()["data"]["status"] == "pending"
|
||||||
|
|
||||||
|
hidden_detail = viewer.get(f"/alarms/{hidden}")
|
||||||
|
_assert_not_found(hidden_detail)
|
||||||
|
_assert_not_found(viewer.get(f"/alarms/{uuid.uuid4()}"))
|
||||||
|
_assert_not_found(viewer.get("/alarms/not-a-uuid"))
|
||||||
|
_assert_not_found(outsider.get(f"/alarms/{visible}"))
|
||||||
|
_assert_not_found(outsider.get(f"/alarms/{visible}/occurrences"))
|
||||||
|
_assert_not_found(outsider.get(f"/alarms/{visible}/history"))
|
||||||
|
_assert_not_found(outsider.get(f"/alarms/{visible}/close-validity"))
|
||||||
|
|
||||||
|
claim = viewer.post(f"/alarms/{visible}/claim", headers=_key("viewer-claim"))
|
||||||
|
_assert_forbidden(claim, ALARM_TAKE_NODE)
|
||||||
|
_assert_forbidden(
|
||||||
|
viewer.post(
|
||||||
|
f"/alarms/{visible}/progress",
|
||||||
|
json={"note": "no"},
|
||||||
|
headers=_key("viewer-progress"),
|
||||||
|
),
|
||||||
|
ALARM_PROGRESS_NODE,
|
||||||
|
)
|
||||||
|
_assert_forbidden(
|
||||||
|
viewer.post(
|
||||||
|
f"/alarms/{visible}/close",
|
||||||
|
json={"result": "resolved", "note": "no"},
|
||||||
|
headers=_key("viewer-close"),
|
||||||
|
),
|
||||||
|
ALARM_CLOSE_NODE,
|
||||||
|
)
|
||||||
|
|
||||||
|
blank_list = blank.get("/alarms")
|
||||||
|
assert blank_list.status_code == 200, blank_list.text
|
||||||
|
assert blank_list.json()["data"]["total"] == 0
|
||||||
|
_assert_forbidden(blank.post(f"/alarms/{visible}/claim", headers=_key("blank")), ALARM_TAKE_NODE)
|
||||||
|
_assert_forbidden(unknown.get("/alarms"), ALARM_READ_NODE)
|
||||||
|
anon_response = anon.get("/alarms")
|
||||||
|
assert anon_response.status_code == 401
|
||||||
|
assert anon_response.json()["success"] is False
|
||||||
|
assert anon_response.json()["error"]["code"] == 41000
|
||||||
|
|
||||||
|
|
||||||
|
def test_commands_conflict_idempotency_and_same_content_replay(alarm_api) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""A-041–A-043: one handler, 409 conflicts, and D37 same-content close replay."""
|
||||||
|
factory, registry, settings, tokens = alarm_api
|
||||||
|
alarm_id, built, snapshot = _open_one(factory, registry, settings, subjects=(OP, OTHER_OP, ADMIN))
|
||||||
|
operator = _client(factory, settings, tokens, roles=[ROLE_OPERATOR], subject=OP)
|
||||||
|
other = _client(factory, settings, tokens, roles=[ROLE_OPERATOR], subject=OTHER_OP)
|
||||||
|
admin = _client(factory, settings, tokens, roles=[ROLE_ADMIN], subject=ADMIN)
|
||||||
|
|
||||||
|
early = operator.post(
|
||||||
|
f"/alarms/{alarm_id}/close",
|
||||||
|
json={"result": "resolved", "note": "too early"},
|
||||||
|
headers=_key("early-close"),
|
||||||
|
)
|
||||||
|
_assert_conflict(early, "illegal_transition")
|
||||||
|
assert operator.get(f"/alarms/{alarm_id}").json()["data"]["status"] == "pending"
|
||||||
|
|
||||||
|
missing = operator.post(f"/alarms/{alarm_id}/claim")
|
||||||
|
assert missing.status_code == 400
|
||||||
|
assert missing.json()["error"]["code"] == 40000
|
||||||
|
assert missing.json()["error"]["details"]["reason"] == "idempotency_key_required"
|
||||||
|
|
||||||
|
long_key = "k" * 129
|
||||||
|
too_long = operator.post(f"/alarms/{alarm_id}/claim", headers={"x-idempotency-key": long_key})
|
||||||
|
assert too_long.status_code == 400, too_long.text
|
||||||
|
assert too_long.json()["error"]["code"] == 40000
|
||||||
|
assert too_long.json()["error"]["details"]["reason"] == "idempotency_key_too_long"
|
||||||
|
assert operator.get(f"/alarms/{alarm_id}").json()["data"]["status"] == "pending"
|
||||||
|
|
||||||
|
extra = operator.post(
|
||||||
|
f"/alarms/{alarm_id}/claim",
|
||||||
|
json={"tenant_id": "other"},
|
||||||
|
headers=_key("extra"),
|
||||||
|
)
|
||||||
|
assert extra.status_code == 400
|
||||||
|
assert extra.json()["error"]["code"] == 40000
|
||||||
|
|
||||||
|
claim_key = _key("claim")
|
||||||
|
request_id = f"req-{uuid.uuid4().hex}"
|
||||||
|
claimed = operator.post(
|
||||||
|
f"/alarms/{alarm_id}/claim",
|
||||||
|
headers={**claim_key, "X-Request-Id": request_id},
|
||||||
|
)
|
||||||
|
assert claimed.status_code == 200, claimed.text
|
||||||
|
assert claimed.headers["X-Request-Id"] == request_id
|
||||||
|
assert claimed.json()["request_id"] == request_id
|
||||||
|
claim_data = claimed.json()["data"]
|
||||||
|
assert claim_data["replayed"] is False
|
||||||
|
assert claim_data["status"] == "processing"
|
||||||
|
assert claim_data["current_handler"] == OP
|
||||||
|
replay = operator.post(f"/alarms/{alarm_id}/claim", headers=claim_key)
|
||||||
|
assert replay.status_code == 200, replay.text
|
||||||
|
assert replay.json()["data"]["replayed"] is True
|
||||||
|
assert replay.json()["data"]["event_id"] == claim_data["event_id"]
|
||||||
|
mismatch = operator.post(
|
||||||
|
f"/alarms/{uuid.uuid4()}/claim",
|
||||||
|
headers=claim_key,
|
||||||
|
)
|
||||||
|
# The key's payload includes the original alarm id, so another path conflicts
|
||||||
|
# only after scope. This id is not visible, so it stays not found.
|
||||||
|
_assert_not_found(mismatch)
|
||||||
|
changed = operator.post(f"/alarms/{alarm_id}/claim", json={"note": "different"}, headers=claim_key)
|
||||||
|
assert changed.status_code == 400
|
||||||
|
|
||||||
|
stolen = other.post(f"/alarms/{alarm_id}/claim", headers=_key("steal"))
|
||||||
|
_assert_conflict(stolen, "already_claimed")
|
||||||
|
assert operator.get(f"/alarms/{alarm_id}").json()["data"]["current_handler"] == OP
|
||||||
|
|
||||||
|
progress_key = _key("progress")
|
||||||
|
progress = operator.post(
|
||||||
|
f"/alarms/{alarm_id}/progress",
|
||||||
|
json={"note": "checked the line", "evidence_ref": "note-1"},
|
||||||
|
headers=progress_key,
|
||||||
|
)
|
||||||
|
assert progress.status_code == 200, progress.text
|
||||||
|
assert progress.json()["data"]["replayed"] is False
|
||||||
|
again = operator.post(
|
||||||
|
f"/alarms/{alarm_id}/progress",
|
||||||
|
json={"note": "checked the line", "evidence_ref": "note-1"},
|
||||||
|
headers=progress_key,
|
||||||
|
)
|
||||||
|
assert again.json()["data"]["event_id"] == progress.json()["data"]["event_id"]
|
||||||
|
assert again.json()["data"]["replayed"] is True
|
||||||
|
other_note = operator.post(
|
||||||
|
f"/alarms/{alarm_id}/progress",
|
||||||
|
json={"note": "a different note"},
|
||||||
|
headers=progress_key,
|
||||||
|
)
|
||||||
|
_assert_conflict(other_note, "idempotency_payload_mismatch")
|
||||||
|
not_handler = other.post(
|
||||||
|
f"/alarms/{alarm_id}/progress",
|
||||||
|
json={"note": "not mine"},
|
||||||
|
headers=_key("other-progress"),
|
||||||
|
)
|
||||||
|
_assert_conflict(not_handler, "not_current_handler")
|
||||||
|
|
||||||
|
close_key = _key("close")
|
||||||
|
closed = operator.post(
|
||||||
|
f"/alarms/{alarm_id}/close",
|
||||||
|
json={"result": "resolved", "note": "line is stable"},
|
||||||
|
headers=close_key,
|
||||||
|
)
|
||||||
|
assert closed.status_code == 200, closed.text
|
||||||
|
assert closed.json()["data"]["status"] == "closed"
|
||||||
|
assert closed.json()["data"]["close_result"] == "resolved"
|
||||||
|
assert closed.json()["data"]["replayed"] is False
|
||||||
|
same_key = operator.post(
|
||||||
|
f"/alarms/{alarm_id}/close",
|
||||||
|
json={"result": "resolved", "note": "line is stable"},
|
||||||
|
headers=close_key,
|
||||||
|
)
|
||||||
|
assert same_key.json()["data"]["replayed"] is True
|
||||||
|
assert same_key.json()["data"]["event_id"] == closed.json()["data"]["event_id"]
|
||||||
|
same_content = operator.post(
|
||||||
|
f"/alarms/{alarm_id}/close",
|
||||||
|
json={"result": "resolved", "note": "line is stable"},
|
||||||
|
headers=_key("close-again"),
|
||||||
|
)
|
||||||
|
assert same_content.status_code == 200, same_content.text
|
||||||
|
assert same_content.json()["data"]["replayed"] is True
|
||||||
|
assert same_content.json()["data"]["event_id"] == closed.json()["data"]["event_id"]
|
||||||
|
different = operator.post(
|
||||||
|
f"/alarms/{alarm_id}/close",
|
||||||
|
json={"result": "false_positive", "note": "line is stable"},
|
||||||
|
headers=_key("close-other"),
|
||||||
|
)
|
||||||
|
_assert_conflict(different, "already_closed")
|
||||||
|
|
||||||
|
history = operator.get(f"/alarms/{alarm_id}/history")
|
||||||
|
assert history.status_code == 200, history.text
|
||||||
|
commands = [item["command"] for item in history.json()["data"]["items"]]
|
||||||
|
assert commands == ["claim", "progress", "close"]
|
||||||
|
assert history.json()["data"]["items"][1]["note"] == "checked the line"
|
||||||
|
validity = operator.get(f"/alarms/{alarm_id}/close-validity")
|
||||||
|
assert validity.json()["data"]["unexecuted_intents_should_invalidate"] is True
|
||||||
|
occurrences = operator.get(f"/alarms/{alarm_id}/occurrences")
|
||||||
|
assert len(occurrences.json()["data"]["items"]) == 1
|
||||||
|
assert occurrences.json()["data"]["items"][0]["mapped_input_revision_id"] == str(built.revision_id)
|
||||||
|
|
||||||
|
revision_id = _revise(factory, settings.tenant_id, built, 90)
|
||||||
|
_append_evidence(factory, settings.tenant_id, built, snapshot, revision_id)
|
||||||
|
evidence = operator.get(f"/alarms/{alarm_id}/evidence")
|
||||||
|
assert evidence.status_code == 200, evidence.text
|
||||||
|
assert len(evidence.json()["data"]["revision_evidence"]) == 1
|
||||||
|
assert evidence.json()["data"]["closed_basis"] == []
|
||||||
|
assert "recovered" not in evidence.text
|
||||||
|
|
||||||
|
# Admin is in scope but is not the handler; the service still allows the close.
|
||||||
|
# This alarm is already closed, so a different note conflicts rather than reopening.
|
||||||
|
admin_close = admin.post(
|
||||||
|
f"/alarms/{alarm_id}/close",
|
||||||
|
json={"result": "resolved", "note": "admin review"},
|
||||||
|
headers=_key("admin-close"),
|
||||||
|
)
|
||||||
|
_assert_conflict(admin_close, "already_closed")
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_can_close_and_cannot_read_outside_scope(alarm_api) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""Admin still needs a snapshot subject. ID alone is not authorization."""
|
||||||
|
factory, registry, settings, tokens = alarm_api
|
||||||
|
alarm_id, _built, _snapshot_value = _open_one(
|
||||||
|
factory, registry, settings, subjects=(OP, ADMIN)
|
||||||
|
)
|
||||||
|
hidden, _built_hidden, _hidden_snapshot = _open_one(
|
||||||
|
factory, registry, settings, subjects=(OUTSIDER,), scenario_key="hidden-temp"
|
||||||
|
)
|
||||||
|
operator = _client(factory, settings, tokens, roles=[ROLE_OPERATOR], subject=OP)
|
||||||
|
admin = _client(factory, settings, tokens, roles=[ROLE_ADMIN], subject=ADMIN)
|
||||||
|
assert operator.post(f"/alarms/{alarm_id}/claim", headers=_key("op-claim")).status_code == 200
|
||||||
|
closed = admin.post(
|
||||||
|
f"/alarms/{alarm_id}/close",
|
||||||
|
json={"result": "false_positive", "note": "admin closed it"},
|
||||||
|
headers=_key("admin-close"),
|
||||||
|
)
|
||||||
|
assert closed.status_code == 200, closed.text
|
||||||
|
assert closed.json()["data"]["close_result"] == "false_positive"
|
||||||
|
assert closed.json()["data"]["current_handler"] == OP
|
||||||
|
_assert_not_found(admin.get(f"/alarms/{hidden}"))
|
||||||
|
_assert_not_found(admin.post(f"/alarms/{hidden}/claim", headers=_key("admin-hidden")))
|
||||||
|
listed = admin.get("/alarms")
|
||||||
|
ids = {item["id"] for item in listed.json()["data"]["items"]}
|
||||||
|
assert alarm_id in ids
|
||||||
|
assert hidden not in ids
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_filters_sort_and_pages_in_sql(alarm_api) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""D25: filters apply when sent, and sort plus page run on the server."""
|
||||||
|
factory, registry, settings, tokens = alarm_api
|
||||||
|
marker = uuid.uuid4().hex[:8]
|
||||||
|
early, _built, _snap = _open_one(
|
||||||
|
factory,
|
||||||
|
registry,
|
||||||
|
settings,
|
||||||
|
subjects=(OP,),
|
||||||
|
module_key=f"alpha-{marker}",
|
||||||
|
scenario_key=f"a-line-{marker}",
|
||||||
|
scenario_name=f"Alpha {marker}",
|
||||||
|
event_key="event-early",
|
||||||
|
observed_at=OBSERVED,
|
||||||
|
)
|
||||||
|
late, _late_built, _late_snap = _open_one(
|
||||||
|
factory,
|
||||||
|
registry,
|
||||||
|
settings,
|
||||||
|
subjects=(OP,),
|
||||||
|
module_key=f"beta-{marker}",
|
||||||
|
scenario_key=f"b-line-{marker}",
|
||||||
|
scenario_name=f"Beta {marker}",
|
||||||
|
event_key="event-late",
|
||||||
|
observed_at=OBSERVED + timedelta(hours=2),
|
||||||
|
)
|
||||||
|
client = _client(factory, settings, tokens, roles=[ROLE_VIEWER], subject=OP)
|
||||||
|
both = client.get("/alarms", params={"scenario_name": marker})
|
||||||
|
assert both.json()["data"]["total"] == 2
|
||||||
|
alpha = client.get("/alarms", params={"module_key": f"alpha-{marker}"})
|
||||||
|
assert [item["id"] for item in alpha.json()["data"]["items"]] == [early]
|
||||||
|
named = client.get("/alarms", params={"scenario_name": f"Beta {marker}"})
|
||||||
|
assert [item["id"] for item in named.json()["data"]["items"]] == [late]
|
||||||
|
window = client.get(
|
||||||
|
"/alarms",
|
||||||
|
params={
|
||||||
|
"scenario_name": marker,
|
||||||
|
"occurred_from": (OBSERVED + timedelta(hours=1)).isoformat(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert [item["id"] for item in window.json()["data"]["items"]] == [late]
|
||||||
|
page = client.get(
|
||||||
|
"/alarms",
|
||||||
|
params={
|
||||||
|
"scenario_name": marker,
|
||||||
|
"sort_by": "scenario_key",
|
||||||
|
"sort_order": "asc",
|
||||||
|
"page": 1,
|
||||||
|
"page_size": 1,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert page.status_code == 200, page.text
|
||||||
|
assert page.json()["data"]["page_size"] == 1
|
||||||
|
assert page.json()["data"]["total"] == 2
|
||||||
|
assert page.json()["data"]["items"][0]["id"] == early
|
||||||
|
second = client.get(
|
||||||
|
"/alarms",
|
||||||
|
params={
|
||||||
|
"scenario_name": marker,
|
||||||
|
"sort_by": "scenario_key",
|
||||||
|
"sort_order": "asc",
|
||||||
|
"page": 2,
|
||||||
|
"page_size": 1,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert second.json()["data"]["items"][0]["id"] == late
|
||||||
|
bad_sort = client.get("/alarms", params={"sort_by": "tenant_id"})
|
||||||
|
assert bad_sort.status_code == 400
|
||||||
|
assert bad_sort.json()["error"]["code"] == 40000
|
||||||
|
naive = client.get("/alarms", params={"occurred_from": "2026-11-19T01:00:00"})
|
||||||
|
assert naive.status_code == 400
|
||||||
|
assert naive.json()["error"]["details"]["reason"] == "timestamp_timezone_required"
|
||||||
|
|
||||||
|
|
||||||
|
def test_trial_outcome_does_not_create_a_listed_alarm(alarm_api) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""S1 regression: a trial abnormal result still adds nothing the API can list."""
|
||||||
|
factory, registry, settings, tokens = alarm_api
|
||||||
|
built = _build(factory, registry, settings.tenant_id)
|
||||||
|
session = _open_session(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
result = apply_monitored_outcome(
|
||||||
|
session,
|
||||||
|
source="trial",
|
||||||
|
outcome="result",
|
||||||
|
code="abnormal",
|
||||||
|
failure=_failure(built, _scope_snapshot(built, (OP,))),
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
assert result is None
|
||||||
|
client = _client(factory, settings, tokens, roles=[ROLE_ADMIN], subject=OP)
|
||||||
|
listed = client.get("/alarms", params={"mapped_input_id": str(built.input_id)})
|
||||||
|
assert listed.status_code == 200, listed.text
|
||||||
|
assert listed.json()["data"]["items"] == []
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_forbidden(response, node: str) -> None: # type: ignore[no-untyped-def]
|
||||||
|
assert response.status_code == 403, response.text
|
||||||
|
body = response.json()
|
||||||
|
assert body["success"] is False
|
||||||
|
assert body["error"]["code"] == 42000
|
||||||
|
assert body["error"]["permission_node"] == node
|
||||||
|
assert "data" not in body
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_not_found(response) -> None: # type: ignore[no-untyped-def]
|
||||||
|
assert response.status_code == 404, response.text
|
||||||
|
body = response.json()
|
||||||
|
assert body["success"] is False
|
||||||
|
assert body["error"]["code"] == 40000
|
||||||
|
assert body["error"]["details"]["reason"] == "not_found"
|
||||||
|
assert "permission_node" not in body["error"]
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_conflict(response, reason: str) -> None: # type: ignore[no-untyped-def]
|
||||||
|
assert response.status_code == 409, response.text
|
||||||
|
body = response.json()
|
||||||
|
assert body["success"] is False
|
||||||
|
assert body["error"]["code"] == 40000
|
||||||
|
assert body["error"]["details"]["reason"] == reason
|
||||||
|
assert "permission_node" not in body["error"]
|
||||||
|
assert body["request_id"]
|
||||||
|
|
||||||
|
|
||||||
|
def _key(prefix: str) -> dict[str, str]:
|
||||||
|
return {"x-idempotency-key": f"{prefix}-{uuid.uuid4().hex}"}
|
||||||
|
|
||||||
|
|
||||||
|
class _NoDirectory:
|
||||||
|
def lookup_roles(self, *, login_name: str) -> list[str]:
|
||||||
|
raise AssertionError("a fresh session must not reload roles")
|
||||||
|
|
||||||
|
|
||||||
|
def _client(factory, settings, tokens: list[str], *, roles: list[str] | None, subject: str) -> TestClient: # type: ignore[no-untyped-def]
|
||||||
|
reload_settings()
|
||||||
|
reset_engine()
|
||||||
|
app = create_app()
|
||||||
|
app.dependency_overrides[get_role_directory] = lambda: _NoDirectory()
|
||||||
|
client = TestClient(app)
|
||||||
|
if roles is not None:
|
||||||
|
client.cookies.set(SESSION_COOKIE_NAME, _seed(factory, settings, tokens, roles, subject))
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
def _seed(factory, settings, tokens: list[str], roles: list[str], subject: str) -> str: # type: ignore[no-untyped-def]
|
||||||
|
token = issue_cookie_token()
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
session = factory()
|
||||||
|
try:
|
||||||
|
set_tenant(session, settings.tenant_id)
|
||||||
|
session.add(
|
||||||
|
AuthSession(
|
||||||
|
token_hash=hash_cookie_token(token),
|
||||||
|
subject=subject,
|
||||||
|
issuer="https://casdoor.test",
|
||||||
|
display_name="Alarm Worker",
|
||||||
|
login_name=f"worker-{uuid.uuid4().hex[:8]}",
|
||||||
|
role_snapshot=list(roles),
|
||||||
|
role_checked_at=now,
|
||||||
|
expires_at=now + timedelta(hours=1),
|
||||||
|
tenant_id=settings.tenant_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
tokens.append(token)
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def _open_session(factory, tenant_id: str) -> Session: # type: ignore[no-untyped-def]
|
||||||
|
session = factory()
|
||||||
|
set_tenant(session, tenant_id)
|
||||||
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
def _scope_snapshot(built, subjects: tuple[str, ...], **overrides: object): # type: ignore[no-untyped-def]
|
||||||
|
scope = {
|
||||||
|
"principals": [{"kind": "subject", "value": subject} for subject in subjects]
|
||||||
|
+ [{"kind": "role", "value": ROLE_OPERATOR}]
|
||||||
|
}
|
||||||
|
return _snapshot(built, handling_scope=scope, **overrides)
|
||||||
|
|
||||||
|
|
||||||
|
def _failure(built, snapshot, **overrides: object) -> FormalFailure: # type: ignore[no-untyped-def]
|
||||||
|
values = {
|
||||||
|
"mapped_input_revision_id": built.revision_id,
|
||||||
|
"snapshot": snapshot,
|
||||||
|
"observed_at": OBSERVED,
|
||||||
|
"received_at": RECEIVED,
|
||||||
|
"cycle_key": "cycle-2026-11",
|
||||||
|
"event_key": "event-overheat",
|
||||||
|
}
|
||||||
|
values.update(overrides)
|
||||||
|
return FormalFailure(**values) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
|
||||||
|
def _open_one(factory, registry, settings, *, subjects: tuple[str, ...], **overrides: object): # type: ignore[no-untyped-def]
|
||||||
|
built = _build(factory, registry, settings.tenant_id)
|
||||||
|
snapshot_overrides = {
|
||||||
|
key: overrides.pop(key)
|
||||||
|
for key in ("module_key", "scenario_key", "scenario_name")
|
||||||
|
if key in overrides
|
||||||
|
}
|
||||||
|
snapshot = _scope_snapshot(built, subjects, **snapshot_overrides)
|
||||||
|
session = _open_session(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
created = apply_monitored_outcome(
|
||||||
|
session,
|
||||||
|
source="formal",
|
||||||
|
outcome="result",
|
||||||
|
code="abnormal",
|
||||||
|
failure=_failure(built, snapshot, **overrides),
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
except Exception:
|
||||||
|
session.rollback()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
assert created is not None and created.alarm_id is not None
|
||||||
|
return str(created.alarm_id), built, snapshot
|
||||||
|
|
||||||
|
|
||||||
|
def _open_pair(factory, registry, settings): # type: ignore[no-untyped-def]
|
||||||
|
visible, _built, _snapshot_value = _open_one(factory, registry, settings, subjects=(OP, ADMIN))
|
||||||
|
hidden, _hidden_built, _hidden_snapshot = _open_one(
|
||||||
|
factory,
|
||||||
|
registry,
|
||||||
|
settings,
|
||||||
|
subjects=(OUTSIDER,),
|
||||||
|
scenario_key="other-temp",
|
||||||
|
event_key="event-hidden",
|
||||||
|
)
|
||||||
|
return visible, hidden
|
||||||
|
|
||||||
|
|
||||||
|
def _append_evidence(factory, tenant_id: str, built, snapshot, revision_id: uuid.UUID) -> None: # type: ignore[no-untyped-def]
|
||||||
|
session = _open_session(factory, tenant_id)
|
||||||
|
try:
|
||||||
|
append_same_cycle_revision(
|
||||||
|
session,
|
||||||
|
SameCycleCorrection(
|
||||||
|
mapped_input_revision_id=revision_id,
|
||||||
|
snapshot=snapshot,
|
||||||
|
cycle_key="cycle-2026-11",
|
||||||
|
event_key="event-overheat",
|
||||||
|
received_at=RECEIVED + timedelta(minutes=5),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
except Exception:
|
||||||
|
session.rollback()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
@@ -0,0 +1,643 @@
|
|||||||
|
"""S2 forward handling, close validity, and direct-status rejection on PostgreSQL.
|
||||||
|
|
||||||
|
Boundary: covers claim, progress, close, idempotency, and the derived close flag.
|
||||||
|
Does not cover alarm routes, permission-node registration, or a frontend.
|
||||||
|
Depends on S1 facts and the handling transition function.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy import func, select, text
|
||||||
|
from sqlalchemy.exc import DBAPIError
|
||||||
|
|
||||||
|
from _privileged_cleanup import _superuser_engine
|
||||||
|
from test_alarm_occurrences import ( # type: ignore[attr-defined]
|
||||||
|
OBSERVED,
|
||||||
|
RECEIVED,
|
||||||
|
alarm_db,
|
||||||
|
_build,
|
||||||
|
_failure,
|
||||||
|
_open,
|
||||||
|
_revise,
|
||||||
|
_snapshot,
|
||||||
|
)
|
||||||
|
from watchman.auth.access import ROLE_ADMIN, ROLE_OPERATOR, ROLE_VIEWER
|
||||||
|
from watchman.core.db import set_tenant
|
||||||
|
from watchman.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||||
|
from watchman.models.alarm import Alarm, AlarmOccurrence
|
||||||
|
from watchman.models.alarm_handling import AlarmClosedBasis, AlarmHandlingCommand, AlarmHandlingEvent
|
||||||
|
from watchman.services.alarm_handling import (
|
||||||
|
HandlingActor,
|
||||||
|
append_progress,
|
||||||
|
claim_alarm,
|
||||||
|
close_alarm,
|
||||||
|
close_validity,
|
||||||
|
)
|
||||||
|
from watchman.services.alarms import apply_monitored_outcome
|
||||||
|
|
||||||
|
SCOPE = {
|
||||||
|
"principals": [
|
||||||
|
{"kind": "subject", "value": "line-a"},
|
||||||
|
{"kind": "subject", "value": "line-b"},
|
||||||
|
{"kind": "subject", "value": "line-admin"},
|
||||||
|
{"kind": "role", "value": "watchman-operator"},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _operator(subject: str = "line-a") -> HandlingActor:
|
||||||
|
return HandlingActor(subject=subject, roles=(ROLE_OPERATOR,))
|
||||||
|
|
||||||
|
|
||||||
|
def _admin() -> HandlingActor:
|
||||||
|
return HandlingActor(subject="line-admin", roles=(ROLE_ADMIN,))
|
||||||
|
|
||||||
|
|
||||||
|
def _key(prefix: str) -> str:
|
||||||
|
return f"{prefix}-{uuid.uuid4()}"
|
||||||
|
|
||||||
|
|
||||||
|
def _events(session, alarm_id: uuid.UUID) -> list[AlarmHandlingEvent]: # type: ignore[no-untyped-def]
|
||||||
|
return list(
|
||||||
|
session.scalars(
|
||||||
|
select(AlarmHandlingEvent)
|
||||||
|
.where(AlarmHandlingEvent.alarm_id == alarm_id)
|
||||||
|
.order_by(AlarmHandlingEvent.seq.asc())
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _opened(alarm_db): # type: ignore[no-untyped-def]
|
||||||
|
"""Create one pending alarm whose scope names the handling subjects."""
|
||||||
|
factory, registry, settings = alarm_db
|
||||||
|
built = _build(factory, registry, settings.tenant_id)
|
||||||
|
session = _open(factory, settings.tenant_id)
|
||||||
|
created = None
|
||||||
|
try:
|
||||||
|
created = apply_monitored_outcome(
|
||||||
|
session,
|
||||||
|
source="formal",
|
||||||
|
outcome="result",
|
||||||
|
code="abnormal",
|
||||||
|
failure=_failure(built, _snapshot(built, handling_scope=SCOPE)),
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
except Exception:
|
||||||
|
session.rollback()
|
||||||
|
session.close()
|
||||||
|
raise
|
||||||
|
assert created is not None and created.occurrence_id is not None
|
||||||
|
return factory, settings, built, session, created
|
||||||
|
|
||||||
|
|
||||||
|
def test_forward_handling_keeps_history_and_original_fact(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""V034–V036: pending becomes processing then closed, and older notes stay put."""
|
||||||
|
_factory, settings, built, session, created = _opened(alarm_db)
|
||||||
|
try:
|
||||||
|
actor = _operator()
|
||||||
|
with pytest.raises(ConflictError) as pending_close:
|
||||||
|
close_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=actor,
|
||||||
|
result="resolved",
|
||||||
|
note="too early",
|
||||||
|
idempotency_key=_key("early"),
|
||||||
|
)
|
||||||
|
assert pending_close.value.details["reason"] == "illegal_transition"
|
||||||
|
session.rollback()
|
||||||
|
set_tenant(session, settings.tenant_id)
|
||||||
|
|
||||||
|
claim = claim_alarm(session, alarm_id=created.alarm_id, actor=actor, idempotency_key=_key("claim"))
|
||||||
|
session.commit()
|
||||||
|
first = append_progress(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=actor,
|
||||||
|
note="checked the sensor",
|
||||||
|
idempotency_key=_key("note-1"),
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
second = append_progress(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=actor,
|
||||||
|
note="replaced the probe",
|
||||||
|
evidence_ref="bench-log-1",
|
||||||
|
idempotency_key=_key("note-2"),
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
closed = close_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=actor,
|
||||||
|
result="false_positive",
|
||||||
|
note="probe drift",
|
||||||
|
idempotency_key=_key("close"),
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
|
||||||
|
alarm = session.get(Alarm, created.alarm_id)
|
||||||
|
occurrence = session.get(AlarmOccurrence, created.occurrence_id)
|
||||||
|
history = _events(session, created.alarm_id)
|
||||||
|
kept_first = session.get(AlarmHandlingEvent, first.event_id)
|
||||||
|
kept_second = session.get(AlarmHandlingEvent, second.event_id)
|
||||||
|
assert alarm is not None and occurrence is not None
|
||||||
|
assert kept_first is not None and kept_second is not None
|
||||||
|
assert claim.replayed is False and claim.status == "processing"
|
||||||
|
assert alarm.status == "closed"
|
||||||
|
assert alarm.current_handler == "line-a"
|
||||||
|
assert alarm.close_result == "false_positive"
|
||||||
|
assert alarm.claimed_at is not None and alarm.closed_at is not None
|
||||||
|
assert occurrence.mapped_input_revision_id == built.revision_id
|
||||||
|
assert alarm.occurrence_count == 1
|
||||||
|
details = [(item.command, item.note, item.recorded_at.isoformat()) for item in history]
|
||||||
|
assert [item[0] for item in details] == ["claim", "progress", "progress", "close"], details
|
||||||
|
assert kept_first.note == "checked the sensor"
|
||||||
|
assert kept_first.actor_subject == "line-a"
|
||||||
|
assert kept_first.command == "progress"
|
||||||
|
assert kept_second.note == "replaced the probe"
|
||||||
|
assert kept_second.evidence_ref == "bench-log-1"
|
||||||
|
assert kept_first.recorded_at <= kept_second.recorded_at
|
||||||
|
assert closed.close_result == "false_positive"
|
||||||
|
assert closed.event_id == history[-1].id
|
||||||
|
with pytest.raises(ConflictError) as reopen:
|
||||||
|
claim_alarm(session, alarm_id=created.alarm_id, actor=actor, idempotency_key=_key("reopen"))
|
||||||
|
assert reopen.value.details["reason"] == "illegal_transition"
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_claim_and_close_authorization(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""V036: viewer, outsider, and a non-handler operator are rejected; admin may close."""
|
||||||
|
_factory, settings, _built, session, created = _opened(alarm_db)
|
||||||
|
try:
|
||||||
|
with pytest.raises(ForbiddenError) as viewer:
|
||||||
|
claim_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=HandlingActor(subject="line-a", roles=(ROLE_VIEWER,)),
|
||||||
|
idempotency_key=_key("viewer"),
|
||||||
|
)
|
||||||
|
assert viewer.value.permission_node is None
|
||||||
|
with pytest.raises(NotFoundError):
|
||||||
|
claim_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=_operator("line-other"),
|
||||||
|
idempotency_key=_key("outsider"),
|
||||||
|
)
|
||||||
|
with pytest.raises(NotFoundError):
|
||||||
|
claim_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=_operator("watchman-operator"),
|
||||||
|
idempotency_key=_key("role-only"),
|
||||||
|
)
|
||||||
|
with pytest.raises(NotFoundError):
|
||||||
|
claim_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=uuid.uuid4(),
|
||||||
|
actor=_operator(),
|
||||||
|
idempotency_key=_key("missing"),
|
||||||
|
)
|
||||||
|
session.rollback()
|
||||||
|
set_tenant(session, settings.tenant_id)
|
||||||
|
claim_alarm(session, alarm_id=created.alarm_id, actor=_operator(), idempotency_key=_key("claim"))
|
||||||
|
session.commit()
|
||||||
|
with pytest.raises(ConflictError) as rival:
|
||||||
|
append_progress(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=_admin(),
|
||||||
|
note="admin is not the handler",
|
||||||
|
idempotency_key=_key("admin-note"),
|
||||||
|
)
|
||||||
|
assert rival.value.details["reason"] == "not_current_handler"
|
||||||
|
with pytest.raises(ConflictError) as other:
|
||||||
|
close_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=_operator("line-b"),
|
||||||
|
result="resolved",
|
||||||
|
note="not mine",
|
||||||
|
idempotency_key=_key("other-close"),
|
||||||
|
)
|
||||||
|
assert other.value.details["reason"] == "not_current_handler"
|
||||||
|
with pytest.raises(ValidationError) as missing_note:
|
||||||
|
close_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=_admin(),
|
||||||
|
result="resolved",
|
||||||
|
note=" ",
|
||||||
|
idempotency_key=_key("blank"),
|
||||||
|
)
|
||||||
|
assert missing_note.value.details["reason"] == "close_note_required"
|
||||||
|
with pytest.raises(ValidationError) as bad_result:
|
||||||
|
close_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=_admin(),
|
||||||
|
result="recovered",
|
||||||
|
note="not a result",
|
||||||
|
idempotency_key=_key("bad-result"),
|
||||||
|
)
|
||||||
|
assert bad_result.value.details["reason"] == "close_result_invalid"
|
||||||
|
session.rollback()
|
||||||
|
set_tenant(session, settings.tenant_id)
|
||||||
|
closed = close_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=_admin(),
|
||||||
|
result="resolved",
|
||||||
|
note="admin closed it",
|
||||||
|
idempotency_key=_key("admin-close"),
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
alarm = session.get(Alarm, created.alarm_id)
|
||||||
|
assert alarm is not None
|
||||||
|
assert closed.status == "closed"
|
||||||
|
assert alarm.current_handler == "line-a"
|
||||||
|
assert alarm.close_result == "resolved"
|
||||||
|
terminal = _events(session, created.alarm_id)[-1]
|
||||||
|
assert terminal.actor_subject == "line-admin"
|
||||||
|
assert terminal.actor_role == ROLE_ADMIN
|
||||||
|
assert terminal.handler_subject == "line-a"
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_command_idempotency_replays_or_conflicts(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""The same key returns the original event; the same key with another payload conflicts."""
|
||||||
|
_factory, _settings, _built, session, created = _opened(alarm_db)
|
||||||
|
try:
|
||||||
|
actor = _operator()
|
||||||
|
key = _key("claim")
|
||||||
|
with pytest.raises(ValidationError) as missing:
|
||||||
|
claim_alarm(session, alarm_id=created.alarm_id, actor=actor, idempotency_key=" ")
|
||||||
|
assert missing.value.details["field"] == "x-idempotency-key"
|
||||||
|
first = claim_alarm(session, alarm_id=created.alarm_id, actor=actor, idempotency_key=key)
|
||||||
|
session.commit()
|
||||||
|
second = claim_alarm(session, alarm_id=created.alarm_id, actor=actor, idempotency_key=key)
|
||||||
|
session.commit()
|
||||||
|
assert second.replayed is True
|
||||||
|
assert second.event_id == first.event_id
|
||||||
|
with pytest.raises(ConflictError) as changed:
|
||||||
|
claim_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=_operator("line-b"),
|
||||||
|
idempotency_key=key,
|
||||||
|
)
|
||||||
|
assert changed.value.details["reason"] == "idempotency_payload_mismatch"
|
||||||
|
session.rollback()
|
||||||
|
note_key = _key("note")
|
||||||
|
append_progress(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=actor,
|
||||||
|
note="first wording",
|
||||||
|
idempotency_key=note_key,
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
replayed = append_progress(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=actor,
|
||||||
|
note="first wording",
|
||||||
|
idempotency_key=note_key,
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
assert replayed.replayed is True
|
||||||
|
with pytest.raises(ConflictError) as other_note:
|
||||||
|
append_progress(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=actor,
|
||||||
|
note="different wording",
|
||||||
|
idempotency_key=note_key,
|
||||||
|
)
|
||||||
|
assert other_note.value.details["reason"] == "idempotency_payload_mismatch"
|
||||||
|
session.rollback()
|
||||||
|
assert len(_events(session, created.alarm_id)) == 2
|
||||||
|
assert int(
|
||||||
|
session.scalar(
|
||||||
|
select(func.count()).select_from(AlarmHandlingCommand).where(
|
||||||
|
AlarmHandlingCommand.alarm_id == created.alarm_id
|
||||||
|
)
|
||||||
|
)
|
||||||
|
or 0
|
||||||
|
) == 2
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_concurrent_claim_and_close_have_one_outcome(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""V034 / V036: two claimers leave one handler, and two closes leave one terminal event."""
|
||||||
|
factory, settings, _built, session, created = _opened(alarm_db)
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
def _claim(subject: str, key: str) -> str:
|
||||||
|
local = _open(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
claim_alarm(
|
||||||
|
local,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=_operator(subject),
|
||||||
|
idempotency_key=key,
|
||||||
|
)
|
||||||
|
local.commit()
|
||||||
|
return "ok"
|
||||||
|
except ConflictError as exc:
|
||||||
|
local.rollback()
|
||||||
|
return str(exc.details["reason"])
|
||||||
|
finally:
|
||||||
|
local.close()
|
||||||
|
|
||||||
|
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||||
|
outcomes = list(pool.map(lambda subject: _claim(subject, _key("race")), ("line-a", "line-b")))
|
||||||
|
assert sorted(outcomes) == ["already_claimed", "ok"]
|
||||||
|
check = _open(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
alarm = check.get(Alarm, created.alarm_id)
|
||||||
|
assert alarm is not None
|
||||||
|
assert alarm.status == "processing"
|
||||||
|
assert alarm.current_handler in {"line-a", "line-b"}
|
||||||
|
assert len(_events(check, created.alarm_id)) == 1
|
||||||
|
winner = alarm.current_handler
|
||||||
|
assert winner is not None
|
||||||
|
close_alarm(
|
||||||
|
check,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=_operator(winner),
|
||||||
|
result="resolved",
|
||||||
|
note="shared close",
|
||||||
|
idempotency_key=_key("seed-close"),
|
||||||
|
)
|
||||||
|
check.commit()
|
||||||
|
finally:
|
||||||
|
check.close()
|
||||||
|
|
||||||
|
def _close(note: str) -> str:
|
||||||
|
local = _open(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
close_alarm(
|
||||||
|
local,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=_operator(winner),
|
||||||
|
result="resolved",
|
||||||
|
note=note,
|
||||||
|
idempotency_key=_key("close-race"),
|
||||||
|
)
|
||||||
|
local.commit()
|
||||||
|
return "ok"
|
||||||
|
except ConflictError as exc:
|
||||||
|
local.rollback()
|
||||||
|
return str(exc.details["reason"])
|
||||||
|
finally:
|
||||||
|
local.close()
|
||||||
|
|
||||||
|
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||||
|
close_outcomes = list(pool.map(_close, ("shared close", "a different ending")))
|
||||||
|
assert "ok" in close_outcomes
|
||||||
|
assert "already_closed" in close_outcomes
|
||||||
|
final = _open(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
alarm = final.get(Alarm, created.alarm_id)
|
||||||
|
closes = [item for item in _events(final, created.alarm_id) if item.command == "close"]
|
||||||
|
assert alarm is not None
|
||||||
|
assert alarm.status == "closed"
|
||||||
|
assert alarm.close_result == "resolved"
|
||||||
|
assert len(closes) == 1
|
||||||
|
assert closes[0].note == "shared close"
|
||||||
|
finally:
|
||||||
|
final.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_repeated_claim_key_is_safe_under_concurrency(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""Two deliveries of one claim key create one event."""
|
||||||
|
factory, settings, _built, session, created = _opened(alarm_db)
|
||||||
|
session.close()
|
||||||
|
key = _key("same")
|
||||||
|
|
||||||
|
def _once() -> uuid.UUID:
|
||||||
|
local = _open(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
result = claim_alarm(
|
||||||
|
local,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=_operator(),
|
||||||
|
idempotency_key=key,
|
||||||
|
)
|
||||||
|
local.commit()
|
||||||
|
return result.event_id
|
||||||
|
finally:
|
||||||
|
local.close()
|
||||||
|
|
||||||
|
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||||
|
ids = list(pool.map(lambda _index: _once(), range(2)))
|
||||||
|
assert ids[0] == ids[1]
|
||||||
|
check = _open(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
assert len(_events(check, created.alarm_id)) == 1
|
||||||
|
finally:
|
||||||
|
check.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_direct_status_update_cannot_skip_the_service(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""A plain UPDATE cannot close a pending alarm, and a skipped edge is rejected too."""
|
||||||
|
_factory, settings, _built, session, created = _opened(alarm_db)
|
||||||
|
try:
|
||||||
|
alarm = session.get(Alarm, created.alarm_id)
|
||||||
|
assert alarm is not None
|
||||||
|
alarm.status = "closed"
|
||||||
|
with pytest.raises(DBAPIError):
|
||||||
|
session.commit()
|
||||||
|
session.rollback()
|
||||||
|
set_tenant(session, settings.tenant_id)
|
||||||
|
with pytest.raises(DBAPIError):
|
||||||
|
session.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
SELECT alarm_apply_transition(
|
||||||
|
:alarm_id, 'closed', 'line-a', now(), now(), 'resolved'
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
),
|
||||||
|
{"alarm_id": created.alarm_id},
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
session.rollback()
|
||||||
|
set_tenant(session, settings.tenant_id)
|
||||||
|
kept = session.get(Alarm, created.alarm_id)
|
||||||
|
assert kept is not None
|
||||||
|
assert kept.status == "pending"
|
||||||
|
assert kept.current_handler is None
|
||||||
|
engine = _superuser_engine()
|
||||||
|
try:
|
||||||
|
with engine.connect() as conn:
|
||||||
|
definer = conn.execute(
|
||||||
|
text("SELECT prosecdef FROM pg_proc WHERE proname = 'alarm_apply_transition'")
|
||||||
|
).scalar_one()
|
||||||
|
assert definer is True
|
||||||
|
grantees = set(
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
SELECT grantee FROM information_schema.routine_privileges
|
||||||
|
WHERE routine_schema = 'public'
|
||||||
|
AND routine_name = 'alarm_apply_transition'
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
).scalars()
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
|
assert "watchman_app" in grantees
|
||||||
|
assert "PUBLIC" not in grantees
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_close_validity_is_derived_without_intent_rows(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""V037 / V042: closing invalidates unexecuted intents by status only, and PASS does not reopen."""
|
||||||
|
factory, settings, built, session, created = _opened(alarm_db)
|
||||||
|
try:
|
||||||
|
open_validity = close_validity(session, created.alarm_id)
|
||||||
|
assert open_validity.unexecuted_intents_should_invalidate is False
|
||||||
|
actor = _operator()
|
||||||
|
claim_alarm(session, alarm_id=created.alarm_id, actor=actor, idempotency_key=_key("claim"))
|
||||||
|
close_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=actor,
|
||||||
|
result="resolved",
|
||||||
|
note="done",
|
||||||
|
idempotency_key=_key("close"),
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
validity = close_validity(session, created.alarm_id)
|
||||||
|
assert validity.status == "closed"
|
||||||
|
assert validity.unexecuted_intents_should_invalidate is True
|
||||||
|
failure = _failure(built, _snapshot(built, handling_scope=SCOPE))
|
||||||
|
for source, outcome, code in (
|
||||||
|
("formal", "result", "normal"),
|
||||||
|
("formal", "result", "unknown"),
|
||||||
|
("formal", "error", None),
|
||||||
|
):
|
||||||
|
assert apply_monitored_outcome(
|
||||||
|
session, source=source, outcome=outcome, code=code, failure=failure
|
||||||
|
) is None
|
||||||
|
session.commit()
|
||||||
|
alarm = session.get(Alarm, created.alarm_id)
|
||||||
|
occurrence = session.get(AlarmOccurrence, created.occurrence_id)
|
||||||
|
assert alarm is not None and occurrence is not None
|
||||||
|
assert alarm.status == "closed"
|
||||||
|
assert alarm.close_result == "resolved"
|
||||||
|
assert occurrence.mapped_input_revision_id == built.revision_id
|
||||||
|
revised = _revise(factory, settings.tenant_id, built, 70)
|
||||||
|
continued = apply_monitored_outcome(
|
||||||
|
session,
|
||||||
|
source="formal",
|
||||||
|
outcome="result",
|
||||||
|
code="abnormal",
|
||||||
|
failure=_failure(
|
||||||
|
built,
|
||||||
|
_snapshot(built, handling_scope=SCOPE),
|
||||||
|
revision_id=revised,
|
||||||
|
observed_at=OBSERVED + timedelta(minutes=3),
|
||||||
|
received_at=RECEIVED + timedelta(minutes=3),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
assert continued is not None and continued.created_basis is True
|
||||||
|
assert continued.created_alarm is False
|
||||||
|
basis = session.get(AlarmClosedBasis, continued.basis_id)
|
||||||
|
assert basis is not None
|
||||||
|
assert basis.original_occurrence_id == created.occurrence_id
|
||||||
|
assert basis.mapped_input_revision_id == revised
|
||||||
|
assert alarm.occurrence_count == 1
|
||||||
|
engine = _superuser_engine()
|
||||||
|
try:
|
||||||
|
with engine.connect() as conn:
|
||||||
|
names = list(
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
SELECT tablename FROM pg_tables
|
||||||
|
WHERE schemaname = 'public'
|
||||||
|
AND (
|
||||||
|
tablename ILIKE '%intent%'
|
||||||
|
OR tablename ILIKE '%window%'
|
||||||
|
OR tablename ILIKE '%escalat%'
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
).scalars()
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
|
assert names == []
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_handling_and_basis_rows_are_append_only(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""History, command keys, and closed basis reject update and delete."""
|
||||||
|
factory, settings, built, session, created = _opened(alarm_db)
|
||||||
|
try:
|
||||||
|
actor = _operator()
|
||||||
|
claim_alarm(session, alarm_id=created.alarm_id, actor=actor, idempotency_key=_key("claim"))
|
||||||
|
close_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=created.alarm_id,
|
||||||
|
actor=actor,
|
||||||
|
result="resolved",
|
||||||
|
note="closed",
|
||||||
|
idempotency_key=_key("close"),
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
revised = _revise(factory, settings.tenant_id, built, 70)
|
||||||
|
recorded = apply_monitored_outcome(
|
||||||
|
session,
|
||||||
|
source="formal",
|
||||||
|
outcome="result",
|
||||||
|
code="abnormal",
|
||||||
|
failure=_failure(
|
||||||
|
built,
|
||||||
|
_snapshot(built, handling_scope=SCOPE),
|
||||||
|
revision_id=revised,
|
||||||
|
observed_at=OBSERVED + timedelta(minutes=4),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
assert recorded is not None and recorded.basis_id is not None
|
||||||
|
event = _events(session, created.alarm_id)[0]
|
||||||
|
event.note = "rewritten"
|
||||||
|
with pytest.raises(DBAPIError):
|
||||||
|
session.commit()
|
||||||
|
session.rollback()
|
||||||
|
set_tenant(session, settings.tenant_id)
|
||||||
|
command = session.scalar(
|
||||||
|
select(AlarmHandlingCommand).where(AlarmHandlingCommand.alarm_id == created.alarm_id)
|
||||||
|
)
|
||||||
|
assert command is not None
|
||||||
|
session.delete(command)
|
||||||
|
with pytest.raises(DBAPIError):
|
||||||
|
session.commit()
|
||||||
|
session.rollback()
|
||||||
|
set_tenant(session, settings.tenant_id)
|
||||||
|
basis = session.get(AlarmClosedBasis, recorded.basis_id)
|
||||||
|
assert basis is not None
|
||||||
|
basis.event_key = "rewritten"
|
||||||
|
with pytest.raises(DBAPIError):
|
||||||
|
session.commit()
|
||||||
|
session.rollback()
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
@@ -0,0 +1,797 @@
|
|||||||
|
"""S1 formal alarm facts on PostgreSQL.
|
||||||
|
|
||||||
|
Boundary: covers idempotent occurrences, bounded merge, new-cycle links, same-cycle
|
||||||
|
corrections, closed-repeat basis, trial isolation, and RLS. The closed-cycle case
|
||||||
|
closes through the handling service. Does not cover alarm APIs.
|
||||||
|
Depends on M05 mappings, revisions, and rule versions.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import inspect
|
||||||
|
import uuid
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy import create_engine, func, select, text
|
||||||
|
from sqlalchemy.exc import DBAPIError
|
||||||
|
from sqlalchemy.orm import Session, sessionmaker
|
||||||
|
|
||||||
|
from _privileged_cleanup import _superuser_engine, purge_query_rows
|
||||||
|
from watchman.api.routes import mappings as mapping_routes
|
||||||
|
from watchman.core.config import get_settings, reload_settings
|
||||||
|
from watchman.core.db import _ensure_after_begin_listener, reset_engine, set_tenant
|
||||||
|
from watchman.core.errors import ConflictError, ValidationError
|
||||||
|
from watchman.models.alarm import Alarm, AlarmOccurrence, AlarmRevisionEvidence
|
||||||
|
from watchman.models.platform import AuditEvent
|
||||||
|
from watchman.services.alarm_handling import HandlingActor, claim_alarm, close_alarm
|
||||||
|
from watchman.services.alarms import CLOSED_REPEAT_ACTION
|
||||||
|
from watchman.models.datasource import DataSource
|
||||||
|
from watchman.models.mapping import MappedInput, MappedInputRevision, MappingDefinition
|
||||||
|
from watchman.models.query import QueryDefinition, QueryVersion
|
||||||
|
from watchman.services import judgment
|
||||||
|
from watchman.services.alarms import (
|
||||||
|
FormalFailure,
|
||||||
|
SameCycleCorrection,
|
||||||
|
SyntheticPublishSnapshot,
|
||||||
|
append_same_cycle_revision,
|
||||||
|
apply_monitored_outcome,
|
||||||
|
record_formal_failure,
|
||||||
|
)
|
||||||
|
from watchman.services.mappings import create_mapping, persist_mapped_rows, save_mapping_version
|
||||||
|
from watchman.services.rules import create_rule, save_rule_version
|
||||||
|
|
||||||
|
FAKE_CIPHERTEXT = "gAAAA-test-placeholder-ciphertext"
|
||||||
|
SCOPE = {"principals": [{"kind": "subject", "value": "line-a"}]}
|
||||||
|
OBSERVED = datetime(2026, 11, 19, 1, 0, tzinfo=timezone.utc)
|
||||||
|
RECEIVED = datetime(2026, 11, 19, 1, 0, 5, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class _Built:
|
||||||
|
mapping_definition_id: uuid.UUID
|
||||||
|
mapping_version_id: uuid.UUID
|
||||||
|
rule_definition_id: uuid.UUID
|
||||||
|
rule_version_id: uuid.UUID
|
||||||
|
input_id: uuid.UUID
|
||||||
|
revision_id: uuid.UUID
|
||||||
|
serial: str
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def alarm_db():
|
||||||
|
"""Open a tenant-scoped session factory and remove only this test's rows."""
|
||||||
|
reload_settings()
|
||||||
|
reset_engine()
|
||||||
|
_ensure_after_begin_listener()
|
||||||
|
settings = get_settings()
|
||||||
|
engine = create_engine(settings.database_url, pool_pre_ping=True)
|
||||||
|
factory = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False)
|
||||||
|
datasource_ids: list[uuid.UUID] = []
|
||||||
|
yield factory, datasource_ids, settings
|
||||||
|
try:
|
||||||
|
for datasource_id in datasource_ids:
|
||||||
|
_purge_graph(datasource_id)
|
||||||
|
purge_query_rows(datasource_id=datasource_id)
|
||||||
|
_delete_datasource(datasource_id)
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
|
reset_engine()
|
||||||
|
|
||||||
|
|
||||||
|
def _purge_graph(datasource_id: uuid.UUID) -> None:
|
||||||
|
"""Delete alarm and mapping rows for one synthetic datasource as superuser."""
|
||||||
|
engine = _superuser_engine()
|
||||||
|
try:
|
||||||
|
with engine.begin() as conn:
|
||||||
|
conn.execute(text("SET LOCAL session_replication_role = replica"))
|
||||||
|
params = {"datasource_id": str(datasource_id)}
|
||||||
|
definitions = (
|
||||||
|
"SELECT id FROM mapping_definitions WHERE query_definition_id IN "
|
||||||
|
"(SELECT id FROM query_definitions WHERE datasource_id = :datasource_id)"
|
||||||
|
)
|
||||||
|
inputs = f"SELECT id FROM mapped_inputs WHERE mapping_definition_id IN ({definitions})"
|
||||||
|
alarms = f"SELECT id FROM alarms WHERE mapped_input_id IN ({inputs})"
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
"DELETE FROM audit_events WHERE action = :action "
|
||||||
|
f"AND payload->>'alarm_id' IN (SELECT id::text FROM alarms WHERE id IN ({alarms}))"
|
||||||
|
),
|
||||||
|
{**params, "action": "alarm.continued_after_close"},
|
||||||
|
)
|
||||||
|
conn.execute(text(f"DELETE FROM alarm_handling_commands WHERE alarm_id IN ({alarms})"), params)
|
||||||
|
conn.execute(text(f"DELETE FROM alarm_handling_events WHERE alarm_id IN ({alarms})"), params)
|
||||||
|
conn.execute(text(f"DELETE FROM alarm_closed_basis WHERE alarm_id IN ({alarms})"), params)
|
||||||
|
conn.execute(text(f"DELETE FROM alarm_revision_evidence WHERE alarm_id IN ({alarms})"), params)
|
||||||
|
conn.execute(text(f"DELETE FROM alarm_occurrences WHERE alarm_id IN ({alarms})"), params)
|
||||||
|
conn.execute(text(f"UPDATE alarms SET previous_alarm_id = NULL WHERE id IN ({alarms})"), params)
|
||||||
|
conn.execute(text(f"DELETE FROM alarms WHERE id IN ({alarms})"), params)
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
"DELETE FROM rule_versions WHERE definition_id IN "
|
||||||
|
f"(SELECT id FROM rule_definitions WHERE mapping_definition_id IN ({definitions}))"
|
||||||
|
),
|
||||||
|
params,
|
||||||
|
)
|
||||||
|
conn.execute(text(f"DELETE FROM rule_definitions WHERE mapping_definition_id IN ({definitions})"), params)
|
||||||
|
conn.execute(text(f"DELETE FROM mapped_input_revisions WHERE input_id IN ({inputs})"), params)
|
||||||
|
conn.execute(text(f"DELETE FROM mapped_inputs WHERE mapping_definition_id IN ({definitions})"), params)
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
"DELETE FROM mapping_column_configs WHERE mapping_version_id IN "
|
||||||
|
f"(SELECT id FROM mapping_versions WHERE definition_id IN ({definitions}))"
|
||||||
|
),
|
||||||
|
params,
|
||||||
|
)
|
||||||
|
conn.execute(text(f"DELETE FROM mapping_versions WHERE definition_id IN ({definitions})"), params)
|
||||||
|
conn.execute(text(f"DELETE FROM mapping_definitions WHERE id IN ({definitions})"), params)
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def _delete_datasource(datasource_id: uuid.UUID) -> None:
|
||||||
|
engine = _superuser_engine()
|
||||||
|
try:
|
||||||
|
with engine.begin() as conn:
|
||||||
|
conn.execute(text("DELETE FROM data_sources WHERE id = :id"), {"id": str(datasource_id)})
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def _build(factory, registry: list[uuid.UUID], tenant_id: str) -> _Built: # type: ignore[no-untyped-def]
|
||||||
|
"""Create one mapped input revision and one rule version under the server tenant."""
|
||||||
|
session: Session = factory()
|
||||||
|
try:
|
||||||
|
set_tenant(session, tenant_id)
|
||||||
|
serial = f"SN-{uuid.uuid4().hex[:12]}"
|
||||||
|
datasource = DataSource(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
name=f"alarm-ds-{uuid.uuid4().hex[:12]}",
|
||||||
|
kind="database",
|
||||||
|
engine="postgresql",
|
||||||
|
host="127.0.0.1",
|
||||||
|
port=5432,
|
||||||
|
database_name="synthetic",
|
||||||
|
username="synthetic_user",
|
||||||
|
secret_ciphertext=FAKE_CIPHERTEXT,
|
||||||
|
)
|
||||||
|
session.add(datasource)
|
||||||
|
session.flush()
|
||||||
|
registry.append(datasource.id)
|
||||||
|
query = QueryDefinition(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
name=f"alarm-query-{uuid.uuid4().hex[:12]}",
|
||||||
|
datasource_id=datasource.id,
|
||||||
|
draft_sql_template="SELECT 1",
|
||||||
|
current_version_no=1,
|
||||||
|
latest_published_version_no=1,
|
||||||
|
)
|
||||||
|
session.add(query)
|
||||||
|
session.flush()
|
||||||
|
session.add(
|
||||||
|
QueryVersion(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
definition_id=query.id,
|
||||||
|
version_no=1,
|
||||||
|
sql_template="SELECT 1",
|
||||||
|
param_schema=[],
|
||||||
|
output_schema=[
|
||||||
|
{"name": "serial", "type": "string"},
|
||||||
|
{"name": "temperature", "type": "number"},
|
||||||
|
],
|
||||||
|
allowed_identifiers=[],
|
||||||
|
timeout_ms=10000,
|
||||||
|
max_rows=100,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
definition: MappingDefinition = create_mapping(session, query_definition_id=str(query.id))
|
||||||
|
mapping_version = save_mapping_version(
|
||||||
|
session,
|
||||||
|
str(definition.id),
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"source_column_name": "serial",
|
||||||
|
"value_type": "string",
|
||||||
|
"is_identity": True,
|
||||||
|
"is_observation_time": False,
|
||||||
|
"numeric_multiply": None,
|
||||||
|
"numeric_offset": None,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source_column_name": "temperature",
|
||||||
|
"value_type": "number",
|
||||||
|
"is_identity": False,
|
||||||
|
"is_observation_time": False,
|
||||||
|
"numeric_multiply": None,
|
||||||
|
"numeric_offset": None,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
persist_mapped_rows(
|
||||||
|
session,
|
||||||
|
str(definition.id),
|
||||||
|
[{"serial": serial, "temperature": 80}],
|
||||||
|
)
|
||||||
|
rule = create_rule(session, mapping_definition_id=str(definition.id))
|
||||||
|
rule_version = save_rule_version(
|
||||||
|
session,
|
||||||
|
str(rule.id),
|
||||||
|
{"column": "temperature", "operator": "gt", "value": 100},
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
mapped = session.scalar(
|
||||||
|
select(MappedInput).where(MappedInput.mapping_definition_id == definition.id)
|
||||||
|
)
|
||||||
|
assert mapped is not None
|
||||||
|
revision = session.scalar(
|
||||||
|
select(MappedInputRevision).where(MappedInputRevision.input_id == mapped.id)
|
||||||
|
)
|
||||||
|
assert revision is not None
|
||||||
|
return _Built(
|
||||||
|
mapping_definition_id=definition.id,
|
||||||
|
mapping_version_id=mapping_version.id,
|
||||||
|
rule_definition_id=rule.id,
|
||||||
|
rule_version_id=rule_version.id,
|
||||||
|
input_id=mapped.id,
|
||||||
|
revision_id=revision.id,
|
||||||
|
serial=serial,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _revise(factory, tenant_id: str, built: _Built, temperature: int) -> uuid.UUID: # type: ignore[no-untyped-def]
|
||||||
|
"""Append one M05 value revision and return its id. Does not touch alarms."""
|
||||||
|
session: Session = factory()
|
||||||
|
try:
|
||||||
|
set_tenant(session, tenant_id)
|
||||||
|
persist_mapped_rows(
|
||||||
|
session,
|
||||||
|
str(built.mapping_definition_id),
|
||||||
|
[{"serial": built.serial, "temperature": temperature}],
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
revision_id = session.scalar(
|
||||||
|
select(MappedInputRevision.id)
|
||||||
|
.where(MappedInputRevision.input_id == built.input_id)
|
||||||
|
.order_by(MappedInputRevision.revision_no.desc())
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
assert isinstance(revision_id, uuid.UUID)
|
||||||
|
return revision_id
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _snapshot(built: _Built, **overrides: object) -> SyntheticPublishSnapshot:
|
||||||
|
values: dict[str, object] = {
|
||||||
|
"snapshot_id": uuid.uuid4(),
|
||||||
|
"version_no": 1,
|
||||||
|
"module_key": "pack",
|
||||||
|
"scenario_key": "pack-temp",
|
||||||
|
"scenario_name": "Pack temperature",
|
||||||
|
"handling_scope": SCOPE,
|
||||||
|
"mapping_version_id": built.mapping_version_id,
|
||||||
|
"rule_version_id": built.rule_version_id,
|
||||||
|
}
|
||||||
|
values.update(overrides)
|
||||||
|
return SyntheticPublishSnapshot(**values) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
|
||||||
|
def _failure(
|
||||||
|
built: _Built,
|
||||||
|
snapshot: SyntheticPublishSnapshot,
|
||||||
|
*,
|
||||||
|
revision_id: uuid.UUID | None = None,
|
||||||
|
observed_at: datetime = OBSERVED,
|
||||||
|
received_at: datetime = RECEIVED,
|
||||||
|
cycle_key: str = "cycle-2026-11",
|
||||||
|
event_key: str = "event-overheat",
|
||||||
|
) -> FormalFailure:
|
||||||
|
return FormalFailure(
|
||||||
|
mapped_input_revision_id=revision_id or built.revision_id,
|
||||||
|
snapshot=snapshot,
|
||||||
|
observed_at=observed_at,
|
||||||
|
received_at=received_at,
|
||||||
|
cycle_key=cycle_key,
|
||||||
|
event_key=event_key,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _counts(session: Session, input_id: uuid.UUID) -> tuple[int, int, int]:
|
||||||
|
alarms = int(
|
||||||
|
session.scalar(select(func.count()).select_from(Alarm).where(Alarm.mapped_input_id == input_id)) or 0
|
||||||
|
)
|
||||||
|
occurrences = int(
|
||||||
|
session.scalar(
|
||||||
|
select(func.count()).select_from(AlarmOccurrence).where(AlarmOccurrence.mapped_input_id == input_id)
|
||||||
|
)
|
||||||
|
or 0
|
||||||
|
)
|
||||||
|
evidence = int(
|
||||||
|
session.scalar(
|
||||||
|
select(func.count())
|
||||||
|
.select_from(AlarmRevisionEvidence)
|
||||||
|
.where(AlarmRevisionEvidence.alarm_id.in_(select(Alarm.id).where(Alarm.mapped_input_id == input_id)))
|
||||||
|
)
|
||||||
|
or 0
|
||||||
|
)
|
||||||
|
return alarms, occurrences, evidence
|
||||||
|
|
||||||
|
|
||||||
|
def _open(factory, tenant_id: str) -> Session: # type: ignore[no-untyped-def]
|
||||||
|
session: Session = factory()
|
||||||
|
set_tenant(session, tenant_id)
|
||||||
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
def test_alarm_tables_have_no_message_merge_column() -> None:
|
||||||
|
"""V031: merge identity is structured columns, not message text."""
|
||||||
|
forbidden = {"message", "body", "title", "text", "payload", "payload_hash"}
|
||||||
|
assert forbidden.isdisjoint(Alarm.__table__.columns.keys())
|
||||||
|
assert forbidden.isdisjoint(AlarmOccurrence.__table__.columns.keys())
|
||||||
|
assert "uq_alarms_structured_merge_key" in {item.name for item in Alarm.__table__.constraints}
|
||||||
|
|
||||||
|
|
||||||
|
def test_trial_and_non_fail_outcomes_write_nothing(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""V030: PASS, UNKNOWN, empty, error, and trial evaluation create no alarm rows."""
|
||||||
|
factory, registry, settings = alarm_db
|
||||||
|
built = _build(factory, registry, settings.tenant_id)
|
||||||
|
failure = _failure(built, _snapshot(built))
|
||||||
|
session = _open(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
assert _counts(session, built.input_id) == (0, 0, 0)
|
||||||
|
assert record_formal_failure(session, failure, confirmed_abnormal=False) is None
|
||||||
|
cases = (
|
||||||
|
("formal", "result", "normal"),
|
||||||
|
("formal", "result", "unknown"),
|
||||||
|
("formal", "empty", None),
|
||||||
|
("formal", "error", None),
|
||||||
|
("trial", "result", "abnormal"),
|
||||||
|
)
|
||||||
|
for source, outcome, code in cases:
|
||||||
|
assert apply_monitored_outcome(
|
||||||
|
session, source=source, outcome=outcome, code=code, failure=failure
|
||||||
|
) is None
|
||||||
|
judgment.evaluate_rows(
|
||||||
|
[{"temperature": 200}],
|
||||||
|
[_Column()],
|
||||||
|
{"column": "temperature", "operator": "gt", "value": 100},
|
||||||
|
["temperature"],
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
assert _counts(session, built.input_id) == (0, 0, 0)
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
judgment_source = inspect.getsource(judgment)
|
||||||
|
route_source = inspect.getsource(mapping_routes)
|
||||||
|
assert "watchman.services.alarms" not in judgment_source
|
||||||
|
assert "record_formal_failure" not in judgment_source
|
||||||
|
assert "watchman.services.alarms" not in route_source
|
||||||
|
|
||||||
|
|
||||||
|
def test_repeated_formal_failure_is_one_occurrence(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""V030: the first formal FAIL opens one alarm, and a replay does not add another."""
|
||||||
|
factory, registry, settings = alarm_db
|
||||||
|
built = _build(factory, registry, settings.tenant_id)
|
||||||
|
failure = _failure(built, _snapshot(built))
|
||||||
|
session = _open(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
first = record_formal_failure(session, failure, confirmed_abnormal=True)
|
||||||
|
session.commit()
|
||||||
|
second = record_formal_failure(session, failure, confirmed_abnormal=True)
|
||||||
|
session.commit()
|
||||||
|
assert first is not None and second is not None
|
||||||
|
assert first.created_alarm is True
|
||||||
|
assert first.created_occurrence is True
|
||||||
|
assert second.created_alarm is False
|
||||||
|
assert second.created_occurrence is False
|
||||||
|
assert second.alarm_id == first.alarm_id
|
||||||
|
assert second.occurrence_id == first.occurrence_id
|
||||||
|
assert _counts(session, built.input_id) == (1, 1, 0)
|
||||||
|
alarm = session.get(Alarm, first.alarm_id)
|
||||||
|
assert alarm is not None
|
||||||
|
assert alarm.status == "pending"
|
||||||
|
assert alarm.current_handler is None
|
||||||
|
assert alarm.previous_alarm_id is None
|
||||||
|
assert alarm.tenant_id == settings.tenant_id
|
||||||
|
assert alarm.handling_scope["principals"][0]["value"] == "line-a"
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_concurrent_replay_keeps_one_occurrence(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""The formal identity constraint keeps one occurrence when two transactions race."""
|
||||||
|
factory, registry, settings = alarm_db
|
||||||
|
built = _build(factory, registry, settings.tenant_id)
|
||||||
|
failure = _failure(built, _snapshot(built))
|
||||||
|
|
||||||
|
def _once() -> uuid.UUID:
|
||||||
|
session = _open(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
result = record_formal_failure(session, failure, confirmed_abnormal=True)
|
||||||
|
session.commit()
|
||||||
|
assert result is not None and result.occurrence_id is not None
|
||||||
|
return result.occurrence_id
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||||
|
ids = list(pool.map(lambda _index: _once(), range(2)))
|
||||||
|
assert ids[0] == ids[1]
|
||||||
|
session = _open(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
assert _counts(session, built.input_id) == (1, 1, 0)
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_merge_range_and_new_event_link(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""V031: the same structured key adds an occurrence; a new event links history."""
|
||||||
|
factory, registry, settings = alarm_db
|
||||||
|
built = _build(factory, registry, settings.tenant_id)
|
||||||
|
snapshot = _snapshot(built)
|
||||||
|
session = _open(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
first = record_formal_failure(
|
||||||
|
session, _failure(built, snapshot), confirmed_abnormal=True
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
renamed = _snapshot(
|
||||||
|
built,
|
||||||
|
snapshot_id=snapshot.snapshot_id,
|
||||||
|
scenario_name="Pack temperature renamed",
|
||||||
|
)
|
||||||
|
second = record_formal_failure(
|
||||||
|
session,
|
||||||
|
_failure(
|
||||||
|
built,
|
||||||
|
renamed,
|
||||||
|
observed_at=OBSERVED + timedelta(minutes=5),
|
||||||
|
received_at=RECEIVED + timedelta(minutes=5),
|
||||||
|
),
|
||||||
|
confirmed_abnormal=True,
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
other_event = record_formal_failure(
|
||||||
|
session,
|
||||||
|
_failure(
|
||||||
|
built,
|
||||||
|
snapshot,
|
||||||
|
observed_at=OBSERVED + timedelta(minutes=10),
|
||||||
|
event_key="event-independent",
|
||||||
|
),
|
||||||
|
confirmed_abnormal=True,
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
other_scenario = record_formal_failure(
|
||||||
|
session,
|
||||||
|
_failure(
|
||||||
|
built,
|
||||||
|
_snapshot(built, scenario_key="pack-pressure", scenario_name="Pack pressure"),
|
||||||
|
observed_at=OBSERVED,
|
||||||
|
event_key="event-independent",
|
||||||
|
),
|
||||||
|
confirmed_abnormal=True,
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
assert first is not None and second is not None
|
||||||
|
assert other_event is not None and other_scenario is not None
|
||||||
|
assert second.alarm_id == first.alarm_id
|
||||||
|
assert second.created_alarm is False
|
||||||
|
assert second.created_occurrence is True
|
||||||
|
assert other_event.created_alarm is True
|
||||||
|
assert other_event.alarm_id != first.alarm_id
|
||||||
|
linked = session.get(Alarm, other_event.alarm_id)
|
||||||
|
original = session.get(Alarm, first.alarm_id)
|
||||||
|
separate = session.get(Alarm, other_scenario.alarm_id)
|
||||||
|
assert linked is not None and original is not None and separate is not None
|
||||||
|
assert linked.previous_alarm_id == first.alarm_id
|
||||||
|
assert original.scenario_name == "Pack temperature"
|
||||||
|
assert original.occurrence_count == 2
|
||||||
|
assert separate.previous_alarm_id is None
|
||||||
|
assert _counts(session, built.input_id) == (3, 4, 0)
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_closed_cycle_does_not_reopen_and_new_cycle_links(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""V032 / D36: a closed cycle keeps its alarm, records basis and audit, and a new cycle links."""
|
||||||
|
factory, registry, settings = alarm_db
|
||||||
|
built = _build(factory, registry, settings.tenant_id)
|
||||||
|
snapshot = _snapshot(built)
|
||||||
|
session = _open(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
first = record_formal_failure(session, _failure(built, snapshot), confirmed_abnormal=True)
|
||||||
|
session.commit()
|
||||||
|
assert first is not None and first.occurrence_id is not None
|
||||||
|
actor = HandlingActor(subject="line-a", roles=("watchman-operator",))
|
||||||
|
claim_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=first.alarm_id,
|
||||||
|
actor=actor,
|
||||||
|
idempotency_key=f"claim-{uuid.uuid4()}",
|
||||||
|
)
|
||||||
|
close_alarm(
|
||||||
|
session,
|
||||||
|
alarm_id=first.alarm_id,
|
||||||
|
actor=actor,
|
||||||
|
result="resolved",
|
||||||
|
note="stop the open cycle",
|
||||||
|
idempotency_key=f"close-{uuid.uuid4()}",
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
revised = _revise(factory, settings.tenant_id, built, 70)
|
||||||
|
continued = _failure(
|
||||||
|
built,
|
||||||
|
snapshot,
|
||||||
|
revision_id=revised,
|
||||||
|
observed_at=OBSERVED + timedelta(minutes=1),
|
||||||
|
)
|
||||||
|
suppressed = record_formal_failure(session, continued, confirmed_abnormal=True)
|
||||||
|
session.commit()
|
||||||
|
assert suppressed is not None
|
||||||
|
assert suppressed.alarm_id == first.alarm_id
|
||||||
|
assert suppressed.suppressed is True
|
||||||
|
assert suppressed.created_alarm is False
|
||||||
|
assert suppressed.created_occurrence is False
|
||||||
|
assert suppressed.created_basis is True
|
||||||
|
assert suppressed.basis_id is not None
|
||||||
|
replayed = record_formal_failure(session, continued, confirmed_abnormal=True)
|
||||||
|
session.commit()
|
||||||
|
assert replayed is not None
|
||||||
|
assert replayed.created_basis is False
|
||||||
|
assert replayed.basis_id == suppressed.basis_id
|
||||||
|
closed = session.get(Alarm, first.alarm_id)
|
||||||
|
occurrence = session.get(AlarmOccurrence, first.occurrence_id)
|
||||||
|
assert closed is not None and occurrence is not None
|
||||||
|
assert closed.status == "closed"
|
||||||
|
assert closed.occurrence_count == 1
|
||||||
|
assert occurrence.mapped_input_revision_id == built.revision_id
|
||||||
|
audit_count = session.scalar(
|
||||||
|
select(func.count())
|
||||||
|
.select_from(AuditEvent)
|
||||||
|
.where(
|
||||||
|
AuditEvent.action == CLOSED_REPEAT_ACTION,
|
||||||
|
AuditEvent.payload["alarm_id"].astext == str(first.alarm_id),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assert int(audit_count or 0) == 1
|
||||||
|
assert _counts(session, built.input_id) == (1, 1, 0)
|
||||||
|
nxt = record_formal_failure(
|
||||||
|
session,
|
||||||
|
_failure(built, snapshot, revision_id=revised, cycle_key="cycle-2026-12"),
|
||||||
|
confirmed_abnormal=True,
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
assert nxt is not None and nxt.created_alarm is True
|
||||||
|
linked = session.get(Alarm, nxt.alarm_id)
|
||||||
|
kept = session.get(Alarm, first.alarm_id)
|
||||||
|
assert linked is not None and kept is not None
|
||||||
|
assert linked.previous_alarm_id == first.alarm_id
|
||||||
|
assert linked.status == "pending"
|
||||||
|
assert linked.id != kept.id
|
||||||
|
assert kept.status == "closed"
|
||||||
|
assert kept.occurrence_count == 1
|
||||||
|
assert _counts(session, built.input_id) == (2, 2, 0)
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_same_cycle_correction_appends_evidence_only(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""V033 / D34: a same-cycle value correction keeps the original FAIL and adds no alarm."""
|
||||||
|
factory, registry, settings = alarm_db
|
||||||
|
built = _build(factory, registry, settings.tenant_id)
|
||||||
|
snapshot = _snapshot(built)
|
||||||
|
session = _open(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
first = record_formal_failure(session, _failure(built, snapshot), confirmed_abnormal=True)
|
||||||
|
session.commit()
|
||||||
|
assert first is not None and first.occurrence_id is not None
|
||||||
|
revised = _revise(factory, settings.tenant_id, built, 70)
|
||||||
|
correction = SameCycleCorrection(
|
||||||
|
mapped_input_revision_id=revised,
|
||||||
|
snapshot=snapshot,
|
||||||
|
cycle_key="cycle-2026-11",
|
||||||
|
event_key="event-overheat",
|
||||||
|
received_at=RECEIVED + timedelta(minutes=2),
|
||||||
|
)
|
||||||
|
appended = append_same_cycle_revision(session, correction)
|
||||||
|
session.commit()
|
||||||
|
replayed = append_same_cycle_revision(session, correction)
|
||||||
|
session.commit()
|
||||||
|
occurrence = session.get(AlarmOccurrence, first.occurrence_id)
|
||||||
|
alarm = session.get(Alarm, first.alarm_id)
|
||||||
|
assert occurrence is not None and alarm is not None
|
||||||
|
assert occurrence.mapped_input_revision_id == built.revision_id
|
||||||
|
assert alarm.occurrence_count == 1
|
||||||
|
assert alarm.status == "pending"
|
||||||
|
assert appended.created_evidence is True
|
||||||
|
assert appended.created_alarm is False
|
||||||
|
assert replayed.created_evidence is False
|
||||||
|
assert replayed.evidence_id == appended.evidence_id
|
||||||
|
assert _counts(session, built.input_id) == (1, 1, 1)
|
||||||
|
with pytest.raises(ConflictError) as caught:
|
||||||
|
append_same_cycle_revision(
|
||||||
|
session,
|
||||||
|
SameCycleCorrection(
|
||||||
|
mapped_input_revision_id=revised,
|
||||||
|
snapshot=snapshot,
|
||||||
|
cycle_key="cycle-missing",
|
||||||
|
event_key="event-overheat",
|
||||||
|
received_at=RECEIVED,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assert caught.value.details["reason"] == "correction_without_alarm"
|
||||||
|
session.rollback()
|
||||||
|
assert _counts(session, built.input_id) == (1, 1, 1)
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_scope_and_version_mismatch_write_nothing(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""D35: an undeclared or all-tenant scope, and a mismatched snapshot, do not insert."""
|
||||||
|
factory, registry, settings = alarm_db
|
||||||
|
built = _build(factory, registry, settings.tenant_id)
|
||||||
|
session = _open(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
rejected = (
|
||||||
|
({}, "snapshot_scope_missing"),
|
||||||
|
({"principals": [{"kind": "role", "value": "operator"}]}, "snapshot_scope_rejects_all_tenant"),
|
||||||
|
(
|
||||||
|
{"all_tenant": True, "principals": [{"kind": "subject", "value": "line-a"}]},
|
||||||
|
"snapshot_scope_rejects_all_tenant",
|
||||||
|
),
|
||||||
|
({"principals": [{"kind": "subject", "value": "*"}]}, "snapshot_scope_rejects_all_tenant"),
|
||||||
|
)
|
||||||
|
for scope, reason in rejected:
|
||||||
|
with pytest.raises(ValidationError) as caught:
|
||||||
|
record_formal_failure(
|
||||||
|
session,
|
||||||
|
_failure(built, _snapshot(built, handling_scope=scope)),
|
||||||
|
confirmed_abnormal=True,
|
||||||
|
)
|
||||||
|
assert caught.value.details["reason"] == reason
|
||||||
|
with pytest.raises(ValidationError) as mismatched:
|
||||||
|
record_formal_failure(
|
||||||
|
session,
|
||||||
|
_failure(built, _snapshot(built, mapping_version_id=uuid.uuid4())),
|
||||||
|
confirmed_abnormal=True,
|
||||||
|
)
|
||||||
|
assert mismatched.value.details["reason"] == "snapshot_version_mismatch"
|
||||||
|
session.rollback()
|
||||||
|
assert _counts(session, built.input_id) == (0, 0, 0)
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_occurrence_fact_cannot_be_rewritten(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""D34: the original occurrence revision is immutable at the database."""
|
||||||
|
factory, registry, settings = alarm_db
|
||||||
|
built = _build(factory, registry, settings.tenant_id)
|
||||||
|
session = _open(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
first = record_formal_failure(
|
||||||
|
session, _failure(built, _snapshot(built)), confirmed_abnormal=True
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
assert first is not None and first.occurrence_id is not None
|
||||||
|
revised = _revise(factory, settings.tenant_id, built, 70)
|
||||||
|
occurrence = session.get(AlarmOccurrence, first.occurrence_id)
|
||||||
|
assert occurrence is not None
|
||||||
|
occurrence.mapped_input_revision_id = revised
|
||||||
|
with pytest.raises(DBAPIError):
|
||||||
|
session.commit()
|
||||||
|
session.rollback()
|
||||||
|
set_tenant(session, settings.tenant_id)
|
||||||
|
kept = session.get(AlarmOccurrence, first.occurrence_id)
|
||||||
|
assert kept is not None
|
||||||
|
assert kept.mapped_input_revision_id == built.revision_id
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_alarm_rls_is_forced_and_tenant_scoped(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||||
|
"""Alarm facts are invisible without the server tenant and to any other tenant."""
|
||||||
|
factory, registry, settings = alarm_db
|
||||||
|
built = _build(factory, registry, settings.tenant_id)
|
||||||
|
session = _open(factory, settings.tenant_id)
|
||||||
|
try:
|
||||||
|
first = record_formal_failure(
|
||||||
|
session, _failure(built, _snapshot(built)), confirmed_abnormal=True
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
assert first is not None
|
||||||
|
alarm_id = first.alarm_id
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
bare: Session = factory()
|
||||||
|
try:
|
||||||
|
visible = bare.execute(text("SELECT count(*) FROM alarms")).scalar_one()
|
||||||
|
assert visible == 0
|
||||||
|
bare.add(
|
||||||
|
Alarm(
|
||||||
|
tenant_id=settings.tenant_id,
|
||||||
|
status="pending",
|
||||||
|
occurrence_count=1,
|
||||||
|
first_occurred_at=OBSERVED,
|
||||||
|
last_occurred_at=OBSERVED,
|
||||||
|
mapped_input_id=built.input_id,
|
||||||
|
mapping_definition_id=built.mapping_definition_id,
|
||||||
|
mapping_version_id=built.mapping_version_id,
|
||||||
|
rule_definition_id=built.rule_definition_id,
|
||||||
|
rule_version_id=built.rule_version_id,
|
||||||
|
snapshot_id=uuid.uuid4(),
|
||||||
|
snapshot_version_no=1,
|
||||||
|
module_key="pack",
|
||||||
|
scenario_key="pack-temp",
|
||||||
|
scenario_name="Pack temperature",
|
||||||
|
handling_scope=SCOPE,
|
||||||
|
cycle_key="cycle-bare",
|
||||||
|
event_key="event-bare",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
with pytest.raises(DBAPIError):
|
||||||
|
bare.commit()
|
||||||
|
bare.rollback()
|
||||||
|
finally:
|
||||||
|
bare.close()
|
||||||
|
|
||||||
|
other = _open(factory, "other-tenant")
|
||||||
|
try:
|
||||||
|
seen = other.scalar(select(func.count()).select_from(Alarm).where(Alarm.id == alarm_id))
|
||||||
|
assert int(seen or 0) == 0
|
||||||
|
finally:
|
||||||
|
other.close()
|
||||||
|
|
||||||
|
engine = create_engine(settings.database_url, pool_pre_ping=True)
|
||||||
|
try:
|
||||||
|
with engine.connect() as conn:
|
||||||
|
for table in (
|
||||||
|
"alarms",
|
||||||
|
"alarm_occurrences",
|
||||||
|
"alarm_revision_evidence",
|
||||||
|
"alarm_handling_events",
|
||||||
|
"alarm_handling_commands",
|
||||||
|
"alarm_closed_basis",
|
||||||
|
):
|
||||||
|
flags = conn.execute(
|
||||||
|
text(
|
||||||
|
"SELECT c.relrowsecurity, c.relforcerowsecurity, t.tableowner "
|
||||||
|
"FROM pg_class c "
|
||||||
|
"JOIN pg_namespace n ON n.oid = c.relnamespace "
|
||||||
|
"JOIN pg_tables t ON t.tablename = c.relname AND t.schemaname = n.nspname "
|
||||||
|
"WHERE n.nspname = 'public' AND c.relname = :table"
|
||||||
|
),
|
||||||
|
{"table": table},
|
||||||
|
).one()
|
||||||
|
assert flags.relrowsecurity is True
|
||||||
|
assert flags.relforcerowsecurity is True
|
||||||
|
assert flags.tableowner != "watchman_app"
|
||||||
|
policies = set(
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
"SELECT policyname FROM pg_policies "
|
||||||
|
"WHERE schemaname = 'public' AND tablename = :table"
|
||||||
|
),
|
||||||
|
{"table": table},
|
||||||
|
).scalars()
|
||||||
|
)
|
||||||
|
assert "tenant_isolation" in policies
|
||||||
|
assert policies <= {"tenant_isolation", "tenant_isolation_definer"}
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
class _Column:
|
||||||
|
"""Minimal mapping column for the pure judgment call."""
|
||||||
|
|
||||||
|
source_column_name = "temperature"
|
||||||
|
value_type = "number"
|
||||||
|
is_identity = False
|
||||||
|
numeric_multiply = None
|
||||||
|
numeric_offset = None
|
||||||
@@ -0,0 +1,375 @@
|
|||||||
|
/**
|
||||||
|
* Demo walkthrough screenshots for M06. Route-mocked so Casdoor is not required.
|
||||||
|
* Output: docs/evidence/M06/demo/
|
||||||
|
*/
|
||||||
|
import { expect, test, type Page, type Route } from "@playwright/test";
|
||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const demoDir = path.resolve(
|
||||||
|
path.dirname(fileURLToPath(import.meta.url)),
|
||||||
|
"../../../../docs/evidence/M06/demo",
|
||||||
|
);
|
||||||
|
fs.mkdirSync(demoDir, { recursive: true });
|
||||||
|
|
||||||
|
const SUBJECT = "demo-operator";
|
||||||
|
const OTHER = "demo-lin";
|
||||||
|
const PENDING = "11111111-1111-4111-8111-111111111111";
|
||||||
|
const PROCESSING = "22222222-2222-4222-8222-222222222222";
|
||||||
|
const CLOSED = "33333333-3333-4333-8333-333333333333";
|
||||||
|
const OBJECT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||||
|
|
||||||
|
type Alarm = {
|
||||||
|
id: string;
|
||||||
|
status: string;
|
||||||
|
current_handler: string | null;
|
||||||
|
claimed_at: string | null;
|
||||||
|
closed_at: string | null;
|
||||||
|
close_result: string | null;
|
||||||
|
occurrence_count: number;
|
||||||
|
first_occurred_at: string;
|
||||||
|
last_occurred_at: string;
|
||||||
|
previous_alarm_id: string | null;
|
||||||
|
mapped_input_id: string;
|
||||||
|
identity_key: string;
|
||||||
|
module_key: string;
|
||||||
|
scenario_key: string;
|
||||||
|
scenario_name: string;
|
||||||
|
snapshot_id: string;
|
||||||
|
snapshot_version_no: number;
|
||||||
|
cycle_key: string;
|
||||||
|
event_key: string;
|
||||||
|
opened_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type HistoryItem = {
|
||||||
|
id: string;
|
||||||
|
seq: number;
|
||||||
|
command: string;
|
||||||
|
actor_subject: string;
|
||||||
|
actor_role: string;
|
||||||
|
handler_subject: string;
|
||||||
|
from_status: string;
|
||||||
|
to_status: string;
|
||||||
|
note: string | null;
|
||||||
|
close_result: string | null;
|
||||||
|
evidence_ref: string | null;
|
||||||
|
recorded_at: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Mock = {
|
||||||
|
alarms: Alarm[];
|
||||||
|
history: Record<string, HistoryItem[]>;
|
||||||
|
};
|
||||||
|
|
||||||
|
function ok(data: unknown): string {
|
||||||
|
return JSON.stringify({ success: true, data, request_id: "demo-alarm" });
|
||||||
|
}
|
||||||
|
|
||||||
|
function seedAlarm(overrides: Partial<Alarm> & Pick<Alarm, "id" | "status" | "scenario_name">): Alarm {
|
||||||
|
return {
|
||||||
|
current_handler: null,
|
||||||
|
claimed_at: null,
|
||||||
|
closed_at: null,
|
||||||
|
close_result: null,
|
||||||
|
occurrence_count: 1,
|
||||||
|
first_occurred_at: "2026-11-19T01:00:00.000Z",
|
||||||
|
last_occurred_at: "2026-11-19T02:00:00.000Z",
|
||||||
|
previous_alarm_id: null,
|
||||||
|
mapped_input_id: OBJECT,
|
||||||
|
identity_key: "furnace-01",
|
||||||
|
module_key: "furnace",
|
||||||
|
scenario_key: "furnace-overtemp",
|
||||||
|
snapshot_id: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
|
||||||
|
snapshot_version_no: 3,
|
||||||
|
cycle_key: "cycle-1",
|
||||||
|
event_key: "event-1",
|
||||||
|
opened_at: "2026-11-19T01:00:00.000Z",
|
||||||
|
updated_at: "2026-11-19T02:00:00.000Z",
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function seedAlarms(): Alarm[] {
|
||||||
|
return [
|
||||||
|
seedAlarm({ id: PENDING, status: "pending", scenario_name: "炉温超限", identity_key: "furnace-01" }),
|
||||||
|
seedAlarm({
|
||||||
|
id: PROCESSING,
|
||||||
|
status: "processing",
|
||||||
|
scenario_name: "气压偏低",
|
||||||
|
identity_key: "comp-02",
|
||||||
|
module_key: "utility",
|
||||||
|
scenario_key: "air-pressure",
|
||||||
|
current_handler: OTHER,
|
||||||
|
claimed_at: "2026-11-19T01:30:00.000Z",
|
||||||
|
mapped_input_id: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
|
||||||
|
}),
|
||||||
|
seedAlarm({
|
||||||
|
id: CLOSED,
|
||||||
|
status: "closed",
|
||||||
|
scenario_name: "尺寸超差",
|
||||||
|
identity_key: "part-09",
|
||||||
|
module_key: "quality",
|
||||||
|
scenario_key: "dimension",
|
||||||
|
current_handler: OTHER,
|
||||||
|
claimed_at: "2026-11-19T01:10:00.000Z",
|
||||||
|
closed_at: "2026-11-19T03:00:00.000Z",
|
||||||
|
close_result: "resolved",
|
||||||
|
occurrence_count: 2,
|
||||||
|
mapped_input_id: "dddddddd-dddd-4ddd-8ddd-dddddddddddd",
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function signIn(page: Page, roles: string[]): Promise<void> {
|
||||||
|
await page.route(
|
||||||
|
(url) => url.pathname === "/auth/me",
|
||||||
|
async (route) => {
|
||||||
|
await route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: "application/json",
|
||||||
|
body: ok({ subject: SUBJECT, display_name: "演示操作员", roles }),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function pushHistory(
|
||||||
|
mock: Mock,
|
||||||
|
alarm: Alarm,
|
||||||
|
command: string,
|
||||||
|
note: string | null,
|
||||||
|
result: string | null = null,
|
||||||
|
): void {
|
||||||
|
const items = mock.history[alarm.id] ?? [];
|
||||||
|
items.push({
|
||||||
|
id: `h-${items.length + 1}`,
|
||||||
|
seq: items.length + 1,
|
||||||
|
command,
|
||||||
|
actor_subject: SUBJECT,
|
||||||
|
actor_role: "watchman-operator",
|
||||||
|
handler_subject: alarm.current_handler ?? SUBJECT,
|
||||||
|
from_status: command === "claim" ? "pending" : "processing",
|
||||||
|
to_status: command === "close" ? "closed" : "processing",
|
||||||
|
note,
|
||||||
|
close_result: result,
|
||||||
|
evidence_ref: null,
|
||||||
|
recorded_at: "2026-11-19T05:00:00.000Z",
|
||||||
|
});
|
||||||
|
mock.history[alarm.id] = items;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function mockAlarms(page: Page): Promise<Mock> {
|
||||||
|
const mock: Mock = {
|
||||||
|
alarms: seedAlarms(),
|
||||||
|
history: {
|
||||||
|
[CLOSED]: [
|
||||||
|
{
|
||||||
|
id: "h1",
|
||||||
|
seq: 1,
|
||||||
|
command: "claim",
|
||||||
|
actor_subject: OTHER,
|
||||||
|
actor_role: "watchman-operator",
|
||||||
|
handler_subject: OTHER,
|
||||||
|
from_status: "pending",
|
||||||
|
to_status: "processing",
|
||||||
|
note: null,
|
||||||
|
close_result: null,
|
||||||
|
evidence_ref: null,
|
||||||
|
recorded_at: "2026-11-19T01:10:00.000Z",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "h2",
|
||||||
|
seq: 2,
|
||||||
|
command: "close",
|
||||||
|
actor_subject: OTHER,
|
||||||
|
actor_role: "watchman-operator",
|
||||||
|
handler_subject: OTHER,
|
||||||
|
from_status: "processing",
|
||||||
|
to_status: "closed",
|
||||||
|
note: "已核对量具并复测通过",
|
||||||
|
close_result: "resolved",
|
||||||
|
evidence_ref: null,
|
||||||
|
recorded_at: "2026-11-19T03:00:00.000Z",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const matcher = (url: URL) =>
|
||||||
|
/^\/alarms(\/[^/]+(\/(occurrences|evidence|history|claim|progress|close))?)?$/.test(url.pathname);
|
||||||
|
|
||||||
|
await page.route(matcher, async (route: Route) => {
|
||||||
|
const request = route.request();
|
||||||
|
const url = new URL(request.url());
|
||||||
|
const method = request.method();
|
||||||
|
const parts = url.pathname.split("/").filter(Boolean);
|
||||||
|
const json = (status: number, text: string) =>
|
||||||
|
route.fulfill({ status, contentType: "application/json", body: text });
|
||||||
|
|
||||||
|
if (parts.length === 1 && method === "GET") {
|
||||||
|
return json(
|
||||||
|
200,
|
||||||
|
ok({ items: mock.alarms, total: mock.alarms.length, page: 1, page_size: 20 }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = parts[1];
|
||||||
|
const alarm = mock.alarms.find((item) => item.id === id);
|
||||||
|
if (!alarm) {
|
||||||
|
return json(404, ok(null));
|
||||||
|
}
|
||||||
|
if (parts.length === 2 && method === "GET") {
|
||||||
|
return json(200, ok(alarm));
|
||||||
|
}
|
||||||
|
const action = parts[2];
|
||||||
|
if (method === "GET" && action === "occurrences") {
|
||||||
|
return json(
|
||||||
|
200,
|
||||||
|
ok({
|
||||||
|
alarm_id: id,
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: `${id}-occ-0`,
|
||||||
|
mapped_input_revision_id: OBJECT,
|
||||||
|
mapping_version_id: OBJECT,
|
||||||
|
rule_version_id: OBJECT,
|
||||||
|
snapshot_id: alarm.snapshot_id,
|
||||||
|
snapshot_version_no: alarm.snapshot_version_no,
|
||||||
|
module_key: alarm.module_key,
|
||||||
|
scenario_key: alarm.scenario_key,
|
||||||
|
scenario_name: alarm.scenario_name,
|
||||||
|
cycle_key: alarm.cycle_key,
|
||||||
|
event_key: alarm.event_key,
|
||||||
|
observed_at: alarm.first_occurred_at,
|
||||||
|
received_at: alarm.first_occurred_at,
|
||||||
|
created_at: alarm.opened_at,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (method === "GET" && action === "evidence") {
|
||||||
|
return json(200, ok({ alarm_id: id, revision_evidence: [], closed_basis: [] }));
|
||||||
|
}
|
||||||
|
if (method === "GET" && action === "history") {
|
||||||
|
return json(200, ok({ alarm_id: id, items: mock.history[id] ?? [] }));
|
||||||
|
}
|
||||||
|
if (method === "POST" && action === "claim") {
|
||||||
|
alarm.status = "processing";
|
||||||
|
alarm.current_handler = SUBJECT;
|
||||||
|
alarm.claimed_at = "2026-11-19T02:10:00.000Z";
|
||||||
|
pushHistory(mock, alarm, "claim", null);
|
||||||
|
return json(
|
||||||
|
200,
|
||||||
|
ok({
|
||||||
|
alarm_id: id,
|
||||||
|
event_id: "evt-1",
|
||||||
|
command: "claim",
|
||||||
|
status: alarm.status,
|
||||||
|
current_handler: alarm.current_handler,
|
||||||
|
close_result: null,
|
||||||
|
replayed: false,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (method === "POST" && action === "progress") {
|
||||||
|
const body = request.postDataJSON() as { note?: string };
|
||||||
|
pushHistory(mock, alarm, "progress", body.note ?? null);
|
||||||
|
return json(
|
||||||
|
200,
|
||||||
|
ok({
|
||||||
|
alarm_id: id,
|
||||||
|
event_id: "evt-2",
|
||||||
|
command: "progress",
|
||||||
|
status: alarm.status,
|
||||||
|
current_handler: alarm.current_handler,
|
||||||
|
close_result: null,
|
||||||
|
replayed: false,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (method === "POST" && action === "close") {
|
||||||
|
const body = request.postDataJSON() as { result?: string; note?: string };
|
||||||
|
alarm.status = "closed";
|
||||||
|
alarm.close_result = body.result ?? "resolved";
|
||||||
|
alarm.closed_at = "2026-11-19T05:00:00.000Z";
|
||||||
|
pushHistory(mock, alarm, "close", body.note ?? null, alarm.close_result);
|
||||||
|
return json(
|
||||||
|
200,
|
||||||
|
ok({
|
||||||
|
alarm_id: id,
|
||||||
|
event_id: "evt-3",
|
||||||
|
command: "close",
|
||||||
|
status: alarm.status,
|
||||||
|
current_handler: alarm.current_handler,
|
||||||
|
close_result: alarm.close_result,
|
||||||
|
replayed: false,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return json(404, ok(null));
|
||||||
|
});
|
||||||
|
|
||||||
|
return mock;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function shot(page: Page, name: string): Promise<void> {
|
||||||
|
await page.screenshot({ path: path.join(demoDir, name), fullPage: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
test.describe("alarm center demo", () => {
|
||||||
|
test("walk through list, claim, progress, close, history, viewer", async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1440, height: 900 });
|
||||||
|
await signIn(page, ["watchman-operator"]);
|
||||||
|
await mockAlarms(page);
|
||||||
|
|
||||||
|
await page.goto("/#/alarms");
|
||||||
|
await expect(page.getByTestId("alarm-table")).toBeVisible();
|
||||||
|
await expect(page.getByTestId("alarm-table")).toContainText("炉温超限");
|
||||||
|
await expect(page.getByTestId("alarm-table")).toContainText("气压偏低");
|
||||||
|
await expect(page.getByTestId("alarm-table")).toContainText("尺寸超差");
|
||||||
|
await shot(page, "01-list-three-alarms.png");
|
||||||
|
|
||||||
|
await page.getByTestId(`alarm-row-${PENDING}`).getByTestId("alarm-open").click();
|
||||||
|
await expect(page.getByTestId("alarm-detail-status")).toContainText("待处理");
|
||||||
|
await shot(page, "02-detail-pending.png");
|
||||||
|
|
||||||
|
await page.getByTestId("footer-claim").click();
|
||||||
|
await expect(page.getByTestId("alarm-detail-status")).toContainText("处理中");
|
||||||
|
await shot(page, "03-after-claim.png");
|
||||||
|
|
||||||
|
await page.getByTestId("footer-progress").click();
|
||||||
|
await page.getByTestId("progress-note").locator("textarea").fill("已到现场核对温度曲线");
|
||||||
|
await page.getByTestId("progress-submit").click();
|
||||||
|
await expect(page.getByTestId("alarm-history")).toContainText("已到现场核对温度曲线");
|
||||||
|
await shot(page, "04-after-progress.png");
|
||||||
|
|
||||||
|
await page.getByTestId("footer-close").click();
|
||||||
|
await page.getByTestId("close-result").click();
|
||||||
|
await page.getByRole("option", { name: "已处理" }).click();
|
||||||
|
await page.getByTestId("close-note").locator("textarea").fill("调整冷却参数后恢复正常");
|
||||||
|
await page.getByTestId("close-submit").click();
|
||||||
|
await expect(page.getByTestId("alarm-detail-status")).toContainText("已关闭");
|
||||||
|
await shot(page, "05-after-close.png");
|
||||||
|
|
||||||
|
await page.goto(`/#/alarms/${CLOSED}`);
|
||||||
|
await expect(page.getByTestId("alarm-history")).toContainText("已核对量具并复测通过");
|
||||||
|
await shot(page, "06-closed-history.png");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("viewer sees detail without handling buttons", async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1440, height: 900 });
|
||||||
|
await signIn(page, ["watchman-viewer"]);
|
||||||
|
await mockAlarms(page);
|
||||||
|
await page.goto(`/#/alarms/${PENDING}`);
|
||||||
|
await expect(page.getByTestId("alarm-detail")).toBeVisible();
|
||||||
|
await expect(page.getByTestId("footer-back")).toBeVisible();
|
||||||
|
await expect(page.getByTestId("footer-claim")).toHaveCount(0);
|
||||||
|
await expect(page.getByTestId("footer-progress")).toHaveCount(0);
|
||||||
|
await expect(page.getByTestId("footer-close")).toHaveCount(0);
|
||||||
|
await shot(page, "07-viewer-no-actions.png");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,596 @@
|
|||||||
|
/**
|
||||||
|
* U06 alarm center. The API is mocked. Copy must not echo a server message,
|
||||||
|
* and the three desktop viewports keep the list pager and detail footer in view.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { expect, test, type Page, type Route } from "@playwright/test";
|
||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const evidenceDir = path.resolve(
|
||||||
|
path.dirname(fileURLToPath(import.meta.url)),
|
||||||
|
"../../../../docs/evidence/M06/ui",
|
||||||
|
);
|
||||||
|
fs.mkdirSync(evidenceDir, { recursive: true });
|
||||||
|
|
||||||
|
const SERVER_SECRET = "HANDLER_STOLEN_SECRET sql password leaked";
|
||||||
|
const SUBJECT = "subj-chen";
|
||||||
|
const OTHER = "subj-lin";
|
||||||
|
const PENDING = "11111111-1111-4111-8111-111111111111";
|
||||||
|
const PROCESSING = "22222222-2222-4222-8222-222222222222";
|
||||||
|
const CLOSED = "33333333-3333-4333-8333-333333333333";
|
||||||
|
const OBJECT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||||
|
|
||||||
|
type Alarm = {
|
||||||
|
id: string;
|
||||||
|
status: string;
|
||||||
|
current_handler: string | null;
|
||||||
|
claimed_at: string | null;
|
||||||
|
closed_at: string | null;
|
||||||
|
close_result: string | null;
|
||||||
|
occurrence_count: number;
|
||||||
|
first_occurred_at: string;
|
||||||
|
last_occurred_at: string;
|
||||||
|
previous_alarm_id: string | null;
|
||||||
|
mapped_input_id: string;
|
||||||
|
identity_key: string;
|
||||||
|
module_key: string;
|
||||||
|
scenario_key: string;
|
||||||
|
scenario_name: string;
|
||||||
|
snapshot_id: string;
|
||||||
|
snapshot_version_no: number;
|
||||||
|
cycle_key: string;
|
||||||
|
event_key: string;
|
||||||
|
opened_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type HistoryItem = {
|
||||||
|
id: string;
|
||||||
|
seq: number;
|
||||||
|
command: string;
|
||||||
|
actor_subject: string;
|
||||||
|
actor_role: string;
|
||||||
|
handler_subject: string;
|
||||||
|
from_status: string;
|
||||||
|
to_status: string;
|
||||||
|
note: string | null;
|
||||||
|
close_result: string | null;
|
||||||
|
evidence_ref: string | null;
|
||||||
|
recorded_at: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Mock = {
|
||||||
|
alarms: Alarm[];
|
||||||
|
history: Record<string, HistoryItem[]>;
|
||||||
|
requests: { method: string; pathname: string; search: string; key: string | null }[];
|
||||||
|
claimConflict: boolean;
|
||||||
|
listStatus: number;
|
||||||
|
listFailuresLeft: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
function ok(data: unknown): string {
|
||||||
|
return JSON.stringify({ success: true, data, request_id: "pw-alarm" });
|
||||||
|
}
|
||||||
|
|
||||||
|
function fail(code: number, message: string, details: Record<string, unknown> = {}): string {
|
||||||
|
return JSON.stringify({
|
||||||
|
success: false,
|
||||||
|
error: { code, message, details, retryable: false },
|
||||||
|
request_id: "pw-alarm",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function seedAlarm(overrides: Partial<Alarm> & Pick<Alarm, "id" | "status" | "scenario_name">): Alarm {
|
||||||
|
return {
|
||||||
|
current_handler: null,
|
||||||
|
claimed_at: null,
|
||||||
|
closed_at: null,
|
||||||
|
close_result: null,
|
||||||
|
occurrence_count: 1,
|
||||||
|
first_occurred_at: "2026-11-18T01:00:00.000Z",
|
||||||
|
last_occurred_at: "2026-11-18T02:00:00.000Z",
|
||||||
|
previous_alarm_id: null,
|
||||||
|
mapped_input_id: OBJECT,
|
||||||
|
identity_key: "furnace-01",
|
||||||
|
module_key: "furnace",
|
||||||
|
scenario_key: "furnace-overtemp",
|
||||||
|
snapshot_id: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
|
||||||
|
snapshot_version_no: 3,
|
||||||
|
cycle_key: "cycle-1",
|
||||||
|
event_key: "event-1",
|
||||||
|
opened_at: "2026-11-18T01:00:00.000Z",
|
||||||
|
updated_at: "2026-11-18T02:00:00.000Z",
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function seedAlarms(): Alarm[] {
|
||||||
|
return [
|
||||||
|
seedAlarm({ id: PENDING, status: "pending", scenario_name: "炉温超限", identity_key: "furnace-01" }),
|
||||||
|
seedAlarm({
|
||||||
|
id: PROCESSING,
|
||||||
|
status: "processing",
|
||||||
|
scenario_name: "气压偏低",
|
||||||
|
identity_key: "comp-02",
|
||||||
|
module_key: "utility",
|
||||||
|
scenario_key: "air-pressure",
|
||||||
|
current_handler: OTHER,
|
||||||
|
claimed_at: "2026-11-18T01:30:00.000Z",
|
||||||
|
mapped_input_id: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
|
||||||
|
}),
|
||||||
|
seedAlarm({
|
||||||
|
id: CLOSED,
|
||||||
|
status: "closed",
|
||||||
|
scenario_name: "尺寸超差",
|
||||||
|
identity_key: "part-09",
|
||||||
|
module_key: "quality",
|
||||||
|
scenario_key: "dimension",
|
||||||
|
current_handler: OTHER,
|
||||||
|
claimed_at: "2026-11-18T01:10:00.000Z",
|
||||||
|
closed_at: "2026-11-18T03:00:00.000Z",
|
||||||
|
close_result: "resolved",
|
||||||
|
occurrence_count: 2,
|
||||||
|
mapped_input_id: "dddddddd-dddd-4ddd-8ddd-dddddddddddd",
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function occurrence(alarm: Alarm, index: number) {
|
||||||
|
return {
|
||||||
|
id: `${alarm.id}-occ-${index}`,
|
||||||
|
mapped_input_revision_id: OBJECT,
|
||||||
|
mapping_version_id: OBJECT,
|
||||||
|
rule_version_id: OBJECT,
|
||||||
|
snapshot_id: alarm.snapshot_id,
|
||||||
|
snapshot_version_no: alarm.snapshot_version_no,
|
||||||
|
module_key: alarm.module_key,
|
||||||
|
scenario_key: alarm.scenario_key,
|
||||||
|
scenario_name: alarm.scenario_name,
|
||||||
|
cycle_key: alarm.cycle_key,
|
||||||
|
event_key: `${alarm.event_key}-${index}`,
|
||||||
|
observed_at: "2026-11-18T01:00:00.000Z",
|
||||||
|
received_at: "2026-11-18T01:05:00.000Z",
|
||||||
|
created_at: "2026-11-18T01:06:00.000Z",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function signIn(page: Page, roles: string[], subject = SUBJECT): Promise<void> {
|
||||||
|
await page.route(
|
||||||
|
(url) => url.pathname === "/auth/me",
|
||||||
|
async (route) => {
|
||||||
|
await route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: "application/json",
|
||||||
|
body: ok({ subject, display_name: "Chen", roles }),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function mockAlarms(
|
||||||
|
page: Page,
|
||||||
|
options: { alarms?: Alarm[]; claimConflict?: boolean; listFailuresLeft?: number } = {},
|
||||||
|
): Promise<Mock> {
|
||||||
|
const mock: Mock = {
|
||||||
|
alarms: options.alarms ?? seedAlarms(),
|
||||||
|
history: {
|
||||||
|
[CLOSED]: [
|
||||||
|
{
|
||||||
|
id: "h1",
|
||||||
|
seq: 1,
|
||||||
|
command: "claim",
|
||||||
|
actor_subject: OTHER,
|
||||||
|
actor_role: "watchman-operator",
|
||||||
|
handler_subject: OTHER,
|
||||||
|
from_status: "pending",
|
||||||
|
to_status: "processing",
|
||||||
|
note: null,
|
||||||
|
close_result: null,
|
||||||
|
evidence_ref: null,
|
||||||
|
recorded_at: "2026-11-18T01:10:00.000Z",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "h2",
|
||||||
|
seq: 2,
|
||||||
|
command: "close",
|
||||||
|
actor_subject: OTHER,
|
||||||
|
actor_role: "watchman-operator",
|
||||||
|
handler_subject: OTHER,
|
||||||
|
from_status: "processing",
|
||||||
|
to_status: "closed",
|
||||||
|
note: "已核对尺寸",
|
||||||
|
close_result: "resolved",
|
||||||
|
evidence_ref: "lot-100",
|
||||||
|
recorded_at: "2026-11-18T03:00:00.000Z",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
requests: [],
|
||||||
|
claimConflict: options.claimConflict ?? false,
|
||||||
|
listStatus: 200,
|
||||||
|
listFailuresLeft: options.listFailuresLeft ?? 0,
|
||||||
|
};
|
||||||
|
const matcher = (url: URL) =>
|
||||||
|
/^\/alarms(\/[^/]+(\/(occurrences|evidence|history|claim|progress|close))?)?$/.test(url.pathname);
|
||||||
|
await page.route(matcher, async (route: Route) => {
|
||||||
|
const request = route.request();
|
||||||
|
const url = new URL(request.url());
|
||||||
|
const method = request.method();
|
||||||
|
const key = request.headers()["x-idempotency-key"] ?? null;
|
||||||
|
mock.requests.push({ method, pathname: url.pathname, search: url.search, key });
|
||||||
|
const json = (status: number, text: string) =>
|
||||||
|
route.fulfill({ status, contentType: "application/json", body: text });
|
||||||
|
const parts = url.pathname.split("/").filter(Boolean);
|
||||||
|
if (parts.length === 1 && method === "GET") {
|
||||||
|
if (mock.listFailuresLeft > 0) {
|
||||||
|
mock.listFailuresLeft -= 1;
|
||||||
|
return json(500, fail(50000, SERVER_SECRET));
|
||||||
|
}
|
||||||
|
return json(200, ok(listBody(mock, url)));
|
||||||
|
}
|
||||||
|
const id = parts[1];
|
||||||
|
const alarm = mock.alarms.find((item) => item.id === id);
|
||||||
|
if (!alarm) {
|
||||||
|
return json(404, fail(40000, SERVER_SECRET, { reason: "not_found" }));
|
||||||
|
}
|
||||||
|
if (parts.length === 2 && method === "GET") {
|
||||||
|
return json(200, ok(alarm));
|
||||||
|
}
|
||||||
|
const action = parts[2];
|
||||||
|
if (method === "GET" && action === "occurrences") {
|
||||||
|
const count = alarm.id === CLOSED ? 4 : 1;
|
||||||
|
return json(200, ok({ alarm_id: id, items: Array.from({ length: count }, (_v, index) => occurrence(alarm, index)) }));
|
||||||
|
}
|
||||||
|
if (method === "GET" && action === "evidence") {
|
||||||
|
return json(
|
||||||
|
200,
|
||||||
|
ok({
|
||||||
|
alarm_id: id,
|
||||||
|
revision_evidence:
|
||||||
|
alarm.id === CLOSED
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
id: "rev-1",
|
||||||
|
occurrence_id: `${id}-occ-0`,
|
||||||
|
mapped_input_revision_id: OBJECT,
|
||||||
|
mapping_version_id: OBJECT,
|
||||||
|
rule_version_id: OBJECT,
|
||||||
|
snapshot_id: alarm.snapshot_id,
|
||||||
|
snapshot_version_no: 3,
|
||||||
|
received_at: "2026-11-18T01:05:00.000Z",
|
||||||
|
recorded_at: "2026-11-18T01:06:00.000Z",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [],
|
||||||
|
closed_basis:
|
||||||
|
alarm.id === CLOSED
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
id: "basis-1",
|
||||||
|
original_occurrence_id: `${id}-occ-0`,
|
||||||
|
mapped_input_revision_id: OBJECT,
|
||||||
|
mapping_version_id: OBJECT,
|
||||||
|
rule_version_id: OBJECT,
|
||||||
|
snapshot_id: alarm.snapshot_id,
|
||||||
|
snapshot_version_no: 4,
|
||||||
|
cycle_key: alarm.cycle_key,
|
||||||
|
event_key: alarm.event_key,
|
||||||
|
observed_at: "2026-11-18T04:00:00.000Z",
|
||||||
|
received_at: "2026-11-18T04:01:00.000Z",
|
||||||
|
recorded_at: "2026-11-18T04:02:00.000Z",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (method === "GET" && action === "history") {
|
||||||
|
return json(200, ok({ alarm_id: id, items: mock.history[id] ?? [] }));
|
||||||
|
}
|
||||||
|
if (method === "POST" && action === "claim") {
|
||||||
|
if (mock.claimConflict) {
|
||||||
|
alarm.status = "processing";
|
||||||
|
alarm.current_handler = OTHER;
|
||||||
|
return json(409, fail(40000, SERVER_SECRET, { reason: "already_claimed" }));
|
||||||
|
}
|
||||||
|
alarm.status = "processing";
|
||||||
|
alarm.current_handler = SUBJECT;
|
||||||
|
alarm.claimed_at = "2026-11-18T02:10:00.000Z";
|
||||||
|
pushHistory(mock, alarm, "claim", null, null);
|
||||||
|
return json(200, ok(commandBody(alarm, "claim")));
|
||||||
|
}
|
||||||
|
if (method === "POST" && action === "progress") {
|
||||||
|
const body = request.postDataJSON() as { note?: string; evidence_ref?: string };
|
||||||
|
pushHistory(mock, alarm, "progress", body.note ?? null, body.evidence_ref ?? null);
|
||||||
|
return json(200, ok(commandBody(alarm, "progress")));
|
||||||
|
}
|
||||||
|
if (method === "POST" && action === "close") {
|
||||||
|
const body = request.postDataJSON() as { result?: string; note?: string; evidence_ref?: string };
|
||||||
|
alarm.status = "closed";
|
||||||
|
alarm.close_result = body.result ?? "resolved";
|
||||||
|
alarm.closed_at = "2026-11-18T05:00:00.000Z";
|
||||||
|
pushHistory(mock, alarm, "close", body.note ?? null, body.evidence_ref ?? null, alarm.close_result);
|
||||||
|
return json(200, ok(commandBody(alarm, "close")));
|
||||||
|
}
|
||||||
|
return json(404, fail(40000, SERVER_SECRET, { reason: "not_found" }));
|
||||||
|
});
|
||||||
|
return mock;
|
||||||
|
}
|
||||||
|
|
||||||
|
function pushHistory(
|
||||||
|
mock: Mock,
|
||||||
|
alarm: Alarm,
|
||||||
|
command: string,
|
||||||
|
note: string | null,
|
||||||
|
evidence: string | null,
|
||||||
|
result: string | null = null,
|
||||||
|
): void {
|
||||||
|
const items = mock.history[alarm.id] ?? [];
|
||||||
|
items.push({
|
||||||
|
id: `h-${items.length + 1}`,
|
||||||
|
seq: items.length + 1,
|
||||||
|
command,
|
||||||
|
actor_subject: SUBJECT,
|
||||||
|
actor_role: "watchman-operator",
|
||||||
|
handler_subject: alarm.current_handler ?? SUBJECT,
|
||||||
|
from_status: command === "claim" ? "pending" : "processing",
|
||||||
|
to_status: command === "close" ? "closed" : "processing",
|
||||||
|
note,
|
||||||
|
close_result: result,
|
||||||
|
evidence_ref: evidence,
|
||||||
|
recorded_at: "2026-11-18T05:00:00.000Z",
|
||||||
|
});
|
||||||
|
mock.history[alarm.id] = items;
|
||||||
|
}
|
||||||
|
|
||||||
|
function commandBody(alarm: Alarm, command: string) {
|
||||||
|
return {
|
||||||
|
alarm_id: alarm.id,
|
||||||
|
event_id: "evt-1",
|
||||||
|
command,
|
||||||
|
status: alarm.status,
|
||||||
|
current_handler: alarm.current_handler,
|
||||||
|
close_result: alarm.close_result,
|
||||||
|
replayed: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function listBody(mock: Mock, url: URL) {
|
||||||
|
let rows = [...mock.alarms];
|
||||||
|
const moduleKey = url.searchParams.get("module_key");
|
||||||
|
const scenario = (url.searchParams.get("scenario_name") ?? "").trim().toLowerCase();
|
||||||
|
const status = url.searchParams.get("status");
|
||||||
|
const objectId = url.searchParams.get("mapped_input_id");
|
||||||
|
if (moduleKey) {
|
||||||
|
rows = rows.filter((item) => item.module_key === moduleKey);
|
||||||
|
}
|
||||||
|
if (scenario) {
|
||||||
|
rows = rows.filter((item) => item.scenario_name.toLowerCase().includes(scenario));
|
||||||
|
}
|
||||||
|
if (status) {
|
||||||
|
rows = rows.filter((item) => item.status === status);
|
||||||
|
}
|
||||||
|
if (objectId) {
|
||||||
|
rows = rows.filter((item) => item.mapped_input_id === objectId);
|
||||||
|
}
|
||||||
|
const sortBy = url.searchParams.get("sort_by") || "last_occurred_at";
|
||||||
|
const dir = url.searchParams.get("sort_order") === "asc" ? 1 : -1;
|
||||||
|
rows.sort((a, b) => {
|
||||||
|
const av = String((a as Record<string, unknown>)[sortBy] ?? "");
|
||||||
|
const bv = String((b as Record<string, unknown>)[sortBy] ?? "");
|
||||||
|
return av < bv ? -dir : av > bv ? dir : 0;
|
||||||
|
});
|
||||||
|
const page = Number(url.searchParams.get("page") || "1");
|
||||||
|
const pageSize = Number(url.searchParams.get("page_size") || "20");
|
||||||
|
const start = Math.max(0, (page - 1) * pageSize);
|
||||||
|
return { items: rows.slice(start, start + pageSize), total: rows.length, page, page_size: pageSize };
|
||||||
|
}
|
||||||
|
|
||||||
|
function listGets(mock: Mock) {
|
||||||
|
return mock.requests.filter((item) => item.method === "GET" && item.pathname === "/alarms");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function noPageScroll(page: Page): Promise<void> {
|
||||||
|
const overflow = await page.evaluate(
|
||||||
|
() => document.documentElement.scrollWidth - document.documentElement.clientWidth,
|
||||||
|
);
|
||||||
|
expect(overflow).toBeLessThanOrEqual(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function expectInsideViewport(page: Page, testId: string): Promise<void> {
|
||||||
|
const box = await page.getByTestId(testId).boundingBox();
|
||||||
|
const viewport = page.viewportSize();
|
||||||
|
expect(box).toBeTruthy();
|
||||||
|
expect(viewport).toBeTruthy();
|
||||||
|
expect(box!.y).toBeGreaterThanOrEqual(-1);
|
||||||
|
expect(box!.y + box!.height).toBeLessThanOrEqual(viewport!.height + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
test.describe("alarm center", () => {
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 1440, height: 900 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("filters on search, then claim, progress, and close", async ({ page }) => {
|
||||||
|
await signIn(page, ["watchman-operator"]);
|
||||||
|
const mock = await mockAlarms(page);
|
||||||
|
await page.goto("/#/alarms");
|
||||||
|
await expect(page.getByTestId("alarm-table")).toBeVisible();
|
||||||
|
await expect(page.getByTestId("alarm-table")).toContainText("待处理");
|
||||||
|
await expect(page.getByTestId("alarm-table")).toContainText("处理中");
|
||||||
|
await expect(page.getByTestId("alarm-table")).toContainText("已关闭");
|
||||||
|
await expect(page.getByRole("columnheader", { name: "等级" })).toHaveCount(0);
|
||||||
|
await expect(page.getByTestId("alarm-list-toolbar")).not.toContainText("等级");
|
||||||
|
await expect(page.locator("body")).not.toContainText("已恢复");
|
||||||
|
expect(listGets(mock)).toHaveLength(1);
|
||||||
|
expect(listGets(mock)[0].search).toContain("page=1");
|
||||||
|
expect(listGets(mock)[0].search).toContain("page_size=20");
|
||||||
|
expect(listGets(mock)[0].search).toContain("sort_by=last_occurred_at");
|
||||||
|
|
||||||
|
await page.getByTestId("alarm-filter-scenario").locator("input").fill("不会命中");
|
||||||
|
expect(listGets(mock)).toHaveLength(1);
|
||||||
|
await page.getByTestId("alarm-filter-search").click();
|
||||||
|
await expect(page.getByTestId("alarm-no-match")).toContainText("没有符合条件的报警");
|
||||||
|
expect(listGets(mock).at(-1)?.search).toContain("scenario_name=");
|
||||||
|
await page.screenshot({ path: path.join(evidenceDir, "U06-no-match-1440x900.png") });
|
||||||
|
|
||||||
|
await page.getByTestId("alarm-filter-reset").click();
|
||||||
|
await expect(page.getByTestId("alarm-table")).toBeVisible();
|
||||||
|
await page.getByRole("columnheader", { name: "模块" }).click();
|
||||||
|
await expect.poll(() => listGets(mock).at(-1)?.search ?? "").toContain("sort_by=module_key");
|
||||||
|
await expect.poll(() => listGets(mock).at(-1)?.search ?? "").toContain("sort_order=asc");
|
||||||
|
|
||||||
|
await page.getByTestId(`alarm-row-${PENDING}`).getByTestId("alarm-open").click();
|
||||||
|
await expect(page.getByTestId("alarm-detail-status")).toContainText("待处理");
|
||||||
|
await expect(page.getByTestId("footer-claim")).toBeVisible();
|
||||||
|
await expect(page.getByTestId("footer-close")).toHaveCount(0);
|
||||||
|
await expect(page.getByTestId("footer-progress")).toHaveCount(0);
|
||||||
|
await expect(page.locator("body")).not.toContainText("计划时间");
|
||||||
|
await expect(page.locator("body")).not.toContainText("规则原文");
|
||||||
|
|
||||||
|
await page.getByTestId("footer-claim").click();
|
||||||
|
await expect(page.getByTestId("alarm-detail-status")).toContainText("处理中");
|
||||||
|
await expect(page.getByTestId("alarm-handler")).toContainText(SUBJECT);
|
||||||
|
const claim = mock.requests.find((item) => item.pathname.endsWith("/claim"));
|
||||||
|
expect(claim?.key).toBeTruthy();
|
||||||
|
|
||||||
|
await page.getByTestId("footer-progress").click();
|
||||||
|
await page.getByTestId("progress-submit").click();
|
||||||
|
await expect(page.getByTestId("alarm-progress-dialog")).toBeVisible();
|
||||||
|
await expect(page.getByText("请填写说明")).toBeVisible();
|
||||||
|
await page.getByTestId("progress-note").locator("textarea").fill("已现场核对");
|
||||||
|
await page.getByTestId("progress-submit").click();
|
||||||
|
await expect(page.getByTestId("alarm-history")).toContainText("已现场核对");
|
||||||
|
|
||||||
|
await page.getByTestId("footer-close").click();
|
||||||
|
await page.getByTestId("close-submit").click();
|
||||||
|
await expect(page.getByTestId("alarm-close-dialog")).toBeVisible();
|
||||||
|
await expect(page.getByText("请选择关闭结果")).toBeVisible();
|
||||||
|
await page.getByTestId("close-result").click();
|
||||||
|
await page.getByRole("option", { name: "已处理" }).click();
|
||||||
|
await page.getByTestId("close-note").locator("textarea").fill("可以关闭");
|
||||||
|
await page.getByTestId("close-submit").click();
|
||||||
|
await expect(page.getByTestId("alarm-detail-status")).toContainText("已关闭");
|
||||||
|
await expect(page.getByTestId("footer-back")).toBeVisible();
|
||||||
|
await expect(page.getByTestId("footer-claim")).toHaveCount(0);
|
||||||
|
await expect(page.getByTestId("footer-progress")).toHaveCount(0);
|
||||||
|
await expect(page.getByTestId("footer-close")).toHaveCount(0);
|
||||||
|
await expect(page.getByTestId("alarm-close-dialog")).toBeHidden();
|
||||||
|
await expect(page.locator("body")).not.toContainText("已恢复");
|
||||||
|
await expect(page.locator("body")).not.toContainText(SERVER_SECRET);
|
||||||
|
await page.screenshot({ path: path.join(evidenceDir, "U06-closed-1440x900.png") });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a viewer does not see handling buttons", async ({ page }) => {
|
||||||
|
await signIn(page, ["watchman-viewer"]);
|
||||||
|
await mockAlarms(page);
|
||||||
|
await page.goto(`/#/alarms/${PENDING}`);
|
||||||
|
await expect(page.getByTestId("alarm-summary")).toBeVisible();
|
||||||
|
await expect(page.getByTestId("footer-back")).toBeVisible();
|
||||||
|
await expect(page.getByTestId("footer-claim")).toHaveCount(0);
|
||||||
|
await expect(page.getByTestId("footer-progress")).toHaveCount(0);
|
||||||
|
await expect(page.getByTestId("footer-close")).toHaveCount(0);
|
||||||
|
await page.screenshot({ path: path.join(evidenceDir, "U06-viewer-1440x900.png") });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an admin can close another handler's alarm and cannot take it or write progress", async ({ page }) => {
|
||||||
|
await signIn(page, ["watchman-admin"]);
|
||||||
|
await mockAlarms(page);
|
||||||
|
await page.goto(`/#/alarms/${PROCESSING}`);
|
||||||
|
await expect(page.getByTestId("alarm-handler")).toContainText(OTHER);
|
||||||
|
await expect(page.getByTestId("footer-close")).toBeVisible();
|
||||||
|
await expect(page.getByTestId("footer-claim")).toHaveCount(0);
|
||||||
|
await expect(page.getByTestId("footer-progress")).toHaveCount(0);
|
||||||
|
await page.getByTestId("footer-close").click();
|
||||||
|
await page.getByTestId("close-result").click();
|
||||||
|
await page.getByRole("option", { name: "误报" }).click();
|
||||||
|
await page.getByTestId("close-note").locator("textarea").fill("管理者关闭");
|
||||||
|
await page.getByTestId("close-submit").click();
|
||||||
|
await expect(page.getByTestId("alarm-detail-status")).toContainText("已关闭");
|
||||||
|
await expect(page.getByTestId("alarm-handler")).toContainText(OTHER);
|
||||||
|
await expect(page.getByTestId("footer-close")).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a claim conflict refreshes and hides the server message", async ({ page }) => {
|
||||||
|
await signIn(page, ["watchman-operator"]);
|
||||||
|
await mockAlarms(page, { claimConflict: true });
|
||||||
|
await page.goto(`/#/alarms/${PENDING}`);
|
||||||
|
await page.getByTestId("footer-claim").click();
|
||||||
|
await expect(page.getByTestId("alarm-command-error")).toContainText("已经有处理人");
|
||||||
|
await expect(page.getByTestId("alarm-command-error")).toContainText("页面已按最新状态刷新");
|
||||||
|
await expect(page.getByTestId("footer-claim")).toHaveCount(0);
|
||||||
|
await expect(page.locator("body")).not.toContainText(SERVER_SECRET);
|
||||||
|
await page.screenshot({ path: path.join(evidenceDir, "U06-conflict-1440x900.png") });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a missing subject says there is no handling scope", async ({ page }) => {
|
||||||
|
await signIn(page, ["watchman-operator"], "");
|
||||||
|
await mockAlarms(page);
|
||||||
|
await page.goto("/#/alarms");
|
||||||
|
await expect(page.getByTestId("alarm-no-scope")).toContainText("没有处理范围,所以看不到报警");
|
||||||
|
await expect(page.getByTestId("alarm-empty")).toHaveCount(0);
|
||||||
|
await page.screenshot({ path: path.join(evidenceDir, "U06-no-scope-1440x900.png") });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an empty page is different from a filter miss", async ({ page }) => {
|
||||||
|
await signIn(page, ["watchman-operator"]);
|
||||||
|
await mockAlarms(page, { alarms: [] });
|
||||||
|
await page.goto("/#/alarms");
|
||||||
|
await expect(page.getByTestId("alarm-empty")).toContainText("还没有报警");
|
||||||
|
await page.screenshot({ path: path.join(evidenceDir, "U06-empty-1440x900.png") });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a failed list can be retried without showing the server message", async ({ page }) => {
|
||||||
|
await signIn(page, ["watchman-operator"]);
|
||||||
|
await mockAlarms(page, { listFailuresLeft: 1 });
|
||||||
|
await page.goto("/#/alarms");
|
||||||
|
await expect(page.getByTestId("alarm-load-error")).toBeVisible();
|
||||||
|
await expect(page.getByTestId("alarm-load-error")).not.toContainText(SERVER_SECRET);
|
||||||
|
await page.screenshot({ path: path.join(evidenceDir, "U06-load-failed-1440x900.png") });
|
||||||
|
await page.getByTestId("alarm-retry").click();
|
||||||
|
await expect(page.getByTestId("alarm-table")).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a closed alarm keeps the basis and only the back button", async ({ page }) => {
|
||||||
|
await signIn(page, ["watchman-admin"]);
|
||||||
|
await mockAlarms(page);
|
||||||
|
await page.goto(`/#/alarms/${CLOSED}`);
|
||||||
|
await expect(page.getByTestId("alarm-closed-basis-hint")).toContainText("报警保持关闭");
|
||||||
|
await expect(page.getByTestId("alarm-history")).toContainText("已核对尺寸");
|
||||||
|
await expect(page.getByTestId("footer-back")).toBeVisible();
|
||||||
|
await expect(page.getByTestId("footer-claim")).toHaveCount(0);
|
||||||
|
await expect(page.getByTestId("footer-progress")).toHaveCount(0);
|
||||||
|
await expect(page.getByTestId("footer-close")).toHaveCount(0);
|
||||||
|
await expect(page.locator("body")).not.toContainText("已恢复");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const viewport of [
|
||||||
|
{ name: "1440x900", width: 1440, height: 900 },
|
||||||
|
{ name: "1280x800", width: 1280, height: 800 },
|
||||||
|
{ name: "1920x1080", width: 1920, height: 1080 },
|
||||||
|
]) {
|
||||||
|
test(`list and detail stay in view at ${viewport.name}`, async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: viewport.width, height: viewport.height });
|
||||||
|
await signIn(page, ["watchman-operator"]);
|
||||||
|
await mockAlarms(page);
|
||||||
|
await page.goto("/#/alarms");
|
||||||
|
await expect(page.getByTestId("alarm-table")).toBeVisible();
|
||||||
|
await expect(page.getByTestId("alarm-pagination")).toBeVisible();
|
||||||
|
await expectInsideViewport(page, "alarm-pagination");
|
||||||
|
await noPageScroll(page);
|
||||||
|
await page.screenshot({ path: path.join(evidenceDir, `U06-list-${viewport.name}.png`) });
|
||||||
|
|
||||||
|
await page.getByTestId(`alarm-row-${CLOSED}`).getByTestId("alarm-open").click();
|
||||||
|
await expect(page.getByTestId("alarm-footer")).toBeVisible();
|
||||||
|
await page.getByTestId("alarm-scroll").evaluate((node) => {
|
||||||
|
node.scrollTop = node.scrollHeight;
|
||||||
|
});
|
||||||
|
await expectInsideViewport(page, "alarm-footer");
|
||||||
|
await expect(page.getByTestId("alarm-summary")).toBeVisible();
|
||||||
|
await noPageScroll(page);
|
||||||
|
await page.screenshot({ path: path.join(evidenceDir, `U06-detail-${viewport.name}.png`) });
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -38,6 +38,7 @@
|
|||||||
"datasources": "Data sources",
|
"datasources": "Data sources",
|
||||||
"queries": "Queries",
|
"queries": "Queries",
|
||||||
"mappings": "Mappings & Rules",
|
"mappings": "Mappings & Rules",
|
||||||
|
"alarms": "Alarms",
|
||||||
"create": "New",
|
"create": "New",
|
||||||
"detail": "Details",
|
"detail": "Details",
|
||||||
"version": "Version v{no}"
|
"version": "Version v{no}"
|
||||||
@@ -453,5 +454,171 @@
|
|||||||
"unsupported_engine": "This data source engine is not supported yet",
|
"unsupported_engine": "This data source engine is not supported yet",
|
||||||
"unsupported_datasource": "This data source type is not supported yet"
|
"unsupported_datasource": "This data source type is not supported yet"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"alarm": {
|
||||||
|
"list": {
|
||||||
|
"filterModule": "Module",
|
||||||
|
"filterScenario": "Scenario name",
|
||||||
|
"filterObject": "Object id",
|
||||||
|
"filterStatus": "Status",
|
||||||
|
"filterFrom": "Last seen from",
|
||||||
|
"filterTo": "Last seen to",
|
||||||
|
"filterSearch": "Search",
|
||||||
|
"filterReset": "Reset",
|
||||||
|
"loadFailed": "The alarm list could not be loaded",
|
||||||
|
"retry": "Retry",
|
||||||
|
"empty": "No alarms yet",
|
||||||
|
"emptyHint": "There are no alarms in the current handling scope.",
|
||||||
|
"noMatch": "No alarms match these filters",
|
||||||
|
"noMatchHint": "Change the filters, or reset them.",
|
||||||
|
"noScope": "No handling scope, so alarms stay hidden",
|
||||||
|
"noScopeHint": "This account has no subject that can see alarms. That does not mean the tenant has none.",
|
||||||
|
"forbidden": "No permission to view alarms",
|
||||||
|
"objectInvalid": "The object id must be a full id",
|
||||||
|
"timeOrder": "The start time cannot be later than the end time",
|
||||||
|
"resultSep": " · "
|
||||||
|
},
|
||||||
|
"columns": {
|
||||||
|
"module": "Module",
|
||||||
|
"scenario": "Scenario",
|
||||||
|
"object": "Object",
|
||||||
|
"lastOccurred": "Last seen",
|
||||||
|
"status": "Status",
|
||||||
|
"actions": "Actions"
|
||||||
|
},
|
||||||
|
"status": {
|
||||||
|
"pending": "Pending",
|
||||||
|
"processing": "In progress",
|
||||||
|
"closed": "Closed"
|
||||||
|
},
|
||||||
|
"closeResult": {
|
||||||
|
"resolved": "Handled",
|
||||||
|
"false_positive": "False positive"
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"open": "Open",
|
||||||
|
"back": "Back to list",
|
||||||
|
"claim": "Handle",
|
||||||
|
"progress": "Add progress",
|
||||||
|
"close": "Close",
|
||||||
|
"submitting": "Submitting"
|
||||||
|
},
|
||||||
|
"role": {
|
||||||
|
"watchman-admin": "Admin",
|
||||||
|
"watchman-operator": "Operator",
|
||||||
|
"watchman-viewer": "Viewer"
|
||||||
|
},
|
||||||
|
"detail": {
|
||||||
|
"loading": "Loading alarm",
|
||||||
|
"loadFailed": "The alarm could not be loaded",
|
||||||
|
"sectionFailed": "Some sections did not load",
|
||||||
|
"notFound": "This alarm was not found",
|
||||||
|
"summary": "Summary",
|
||||||
|
"occurrences": "Observations",
|
||||||
|
"occurrencesHint": "Each observation shows only the time, cycle, and event returned by the API.",
|
||||||
|
"occurrencesEmpty": "No observations yet",
|
||||||
|
"evidence": "Basis",
|
||||||
|
"revisionEvidence": "Same-cycle revision basis",
|
||||||
|
"revisionEmpty": "No revision basis",
|
||||||
|
"closedBasis": "Basis after close",
|
||||||
|
"closedBasisEmpty": "No basis after close",
|
||||||
|
"closedBasisHint": "These records were kept after the alarm was closed. The alarm stays closed, and the last-seen time and observation count do not change because of them.",
|
||||||
|
"history": "Handling history",
|
||||||
|
"historyEmpty": "No handling history yet",
|
||||||
|
"fields": {
|
||||||
|
"status": "Status",
|
||||||
|
"scenario": "Scenario",
|
||||||
|
"module": "Module",
|
||||||
|
"scenarioKey": "Scenario key",
|
||||||
|
"object": "Object",
|
||||||
|
"count": "Observations",
|
||||||
|
"firstOccurred": "First seen",
|
||||||
|
"lastOccurred": "Last seen",
|
||||||
|
"handler": "Current handler",
|
||||||
|
"claimedAt": "Handling started at",
|
||||||
|
"closedAt": "Closed at",
|
||||||
|
"cycle": "Cycle",
|
||||||
|
"event": "Event",
|
||||||
|
"openedAt": "Opened at",
|
||||||
|
"updatedAt": "Updated at",
|
||||||
|
"previous": "Previous linked alarm",
|
||||||
|
"none": "None"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"occurrence": {
|
||||||
|
"observedAt": "Observed at",
|
||||||
|
"receivedAt": "Received at",
|
||||||
|
"cycle": "Cycle",
|
||||||
|
"event": "Event"
|
||||||
|
},
|
||||||
|
"evidenceCols": {
|
||||||
|
"receivedAt": "Received at",
|
||||||
|
"recordedAt": "Recorded at",
|
||||||
|
"observedAt": "Observed at",
|
||||||
|
"snapshotVersion": "Snapshot version",
|
||||||
|
"cycle": "Cycle",
|
||||||
|
"event": "Event"
|
||||||
|
},
|
||||||
|
"historyCols": {
|
||||||
|
"seq": "Seq",
|
||||||
|
"command": "Action",
|
||||||
|
"actor": "Actor",
|
||||||
|
"handler": "Handler",
|
||||||
|
"note": "Note",
|
||||||
|
"result": "Result",
|
||||||
|
"evidence": "Evidence ref",
|
||||||
|
"at": "Time"
|
||||||
|
},
|
||||||
|
"commandName": {
|
||||||
|
"claim": "Handle",
|
||||||
|
"progress": "Progress",
|
||||||
|
"close": "Close"
|
||||||
|
},
|
||||||
|
"progressDialog": {
|
||||||
|
"title": "Add progress",
|
||||||
|
"note": "Note",
|
||||||
|
"notePlaceholder": "What was done this time",
|
||||||
|
"evidence": "Evidence ref",
|
||||||
|
"evidencePlaceholder": "Optional",
|
||||||
|
"required": "A note is required",
|
||||||
|
"cancel": "Cancel",
|
||||||
|
"submit": "Save progress"
|
||||||
|
},
|
||||||
|
"closeDialog": {
|
||||||
|
"title": "Close alarm",
|
||||||
|
"result": "Close result",
|
||||||
|
"resultPlaceholder": "Choose a result",
|
||||||
|
"note": "Note",
|
||||||
|
"notePlaceholder": "Why it is being closed this way",
|
||||||
|
"evidence": "Evidence ref",
|
||||||
|
"evidencePlaceholder": "Optional",
|
||||||
|
"resultRequired": "Choose a close result",
|
||||||
|
"noteRequired": "A note is required",
|
||||||
|
"cancel": "Cancel",
|
||||||
|
"submit": "Confirm close"
|
||||||
|
},
|
||||||
|
"command": {
|
||||||
|
"claimed": "Handling started",
|
||||||
|
"progressSaved": "Progress saved",
|
||||||
|
"closed": "Closed",
|
||||||
|
"failed": "The action did not finish",
|
||||||
|
"conflictRefreshed": "The page was refreshed to the latest state"
|
||||||
|
},
|
||||||
|
"errors": {
|
||||||
|
"already_claimed": "This alarm already has a handler",
|
||||||
|
"not_current_handler": "Only the current handler can do this",
|
||||||
|
"illegal_transition": "This action is not available in the current state",
|
||||||
|
"already_closed": "This alarm is already closed",
|
||||||
|
"idempotency_payload_mismatch": "This submit id was already used for different content",
|
||||||
|
"handling_history_missing": "The handling record is incomplete. Refresh and try again",
|
||||||
|
"idempotency_key_required": "A submit id is missing. Try again",
|
||||||
|
"idempotency_key_too_long": "The submit id is too long",
|
||||||
|
"note_invalid": "The note is not valid",
|
||||||
|
"evidence_ref_invalid": "The evidence ref is not valid",
|
||||||
|
"close_result_invalid": "The close result is not valid",
|
||||||
|
"not_found": "This alarm was not found",
|
||||||
|
"forbidden": "Not allowed ({node})",
|
||||||
|
"forbiddenPlain": "Not allowed to finish this action"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -38,6 +38,7 @@
|
|||||||
"datasources": "แหล่งข้อมูล",
|
"datasources": "แหล่งข้อมูล",
|
||||||
"queries": "คิวรี",
|
"queries": "คิวรี",
|
||||||
"mappings": "การแมปและกฎ",
|
"mappings": "การแมปและกฎ",
|
||||||
|
"alarms": "การแจ้งเตือน",
|
||||||
"create": "สร้างใหม่",
|
"create": "สร้างใหม่",
|
||||||
"detail": "รายละเอียด",
|
"detail": "รายละเอียด",
|
||||||
"version": "เวอร์ชัน v{no}"
|
"version": "เวอร์ชัน v{no}"
|
||||||
@@ -453,5 +454,171 @@
|
|||||||
"unsupported_engine": "ยังไม่รองรับเอนจินของแหล่งข้อมูลนี้",
|
"unsupported_engine": "ยังไม่รองรับเอนจินของแหล่งข้อมูลนี้",
|
||||||
"unsupported_datasource": "ยังไม่รองรับแหล่งข้อมูลประเภทนี้"
|
"unsupported_datasource": "ยังไม่รองรับแหล่งข้อมูลประเภทนี้"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"alarm": {
|
||||||
|
"list": {
|
||||||
|
"filterModule": "โมดูล",
|
||||||
|
"filterScenario": "ชื่อสถานการณ์",
|
||||||
|
"filterObject": "รหัสวัตถุ",
|
||||||
|
"filterStatus": "สถานะ",
|
||||||
|
"filterFrom": "เกิดล่าสุดตั้งแต่",
|
||||||
|
"filterTo": "เกิดล่าสุดถึง",
|
||||||
|
"filterSearch": "ค้นหา",
|
||||||
|
"filterReset": "ล้าง",
|
||||||
|
"loadFailed": "โหลดรายการแจ้งเตือนไม่สำเร็จ",
|
||||||
|
"retry": "ลองใหม่",
|
||||||
|
"empty": "ยังไม่มีการแจ้งเตือน",
|
||||||
|
"emptyHint": "ในช่วงการจัดการปัจจุบันยังไม่มีการแจ้งเตือน",
|
||||||
|
"noMatch": "ไม่มีการแจ้งเตือนที่ตรงเงื่อนไข",
|
||||||
|
"noMatchHint": "ลองเปลี่ยนตัวกรอง หรือกดล้าง",
|
||||||
|
"noScope": "ไม่มีขอบเขตการจัดการ จึงไม่เห็นการแจ้งเตือน",
|
||||||
|
"noScopeHint": "บัญชีนี้ไม่มีตัวตนที่ใช้ดูการแจ้งเตือน นี่ไม่ได้แปลว่าทั้งผู้เช่าไม่มีการแจ้งเตือน",
|
||||||
|
"forbidden": "ไม่มีสิทธิ์ดูการแจ้งเตือน",
|
||||||
|
"objectInvalid": "รหัสวัตถุต้องเป็นรหัสเต็ม",
|
||||||
|
"timeOrder": "เวลาเริ่มต้องไม่ช้ากว่าเวลาสิ้นสุด",
|
||||||
|
"resultSep": " · "
|
||||||
|
},
|
||||||
|
"columns": {
|
||||||
|
"module": "โมดูล",
|
||||||
|
"scenario": "สถานการณ์",
|
||||||
|
"object": "วัตถุ",
|
||||||
|
"lastOccurred": "เกิดล่าสุด",
|
||||||
|
"status": "สถานะ",
|
||||||
|
"actions": "การทำงาน"
|
||||||
|
},
|
||||||
|
"status": {
|
||||||
|
"pending": "รอดำเนินการ",
|
||||||
|
"processing": "กำลังดำเนินการ",
|
||||||
|
"closed": "ปิดแล้ว"
|
||||||
|
},
|
||||||
|
"closeResult": {
|
||||||
|
"resolved": "จัดการแล้ว",
|
||||||
|
"false_positive": "แจ้งผิด"
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"open": "เปิด",
|
||||||
|
"back": "กลับรายการ",
|
||||||
|
"claim": "ดำเนินการ",
|
||||||
|
"progress": "เพิ่มความคืบหน้า",
|
||||||
|
"close": "ปิด",
|
||||||
|
"submitting": "กำลังส่ง"
|
||||||
|
},
|
||||||
|
"role": {
|
||||||
|
"watchman-admin": "ผู้ดูแล",
|
||||||
|
"watchman-operator": "ผู้ปฏิบัติ",
|
||||||
|
"watchman-viewer": "ผู้ดู"
|
||||||
|
},
|
||||||
|
"detail": {
|
||||||
|
"loading": "กำลังโหลดรายละเอียด",
|
||||||
|
"loadFailed": "โหลดรายละเอียดไม่สำเร็จ",
|
||||||
|
"sectionFailed": "บางส่วนโหลดไม่สำเร็จ",
|
||||||
|
"notFound": "ไม่พบการแจ้งเตือนนี้",
|
||||||
|
"summary": "สรุป",
|
||||||
|
"occurrences": "การสังเกต",
|
||||||
|
"occurrencesHint": "แต่ละรายการแสดงเฉพาะเวลา รอบ และเหตุการณ์ที่ส่วนต่อประสานส่งมา",
|
||||||
|
"occurrencesEmpty": "ยังไม่มีบันทึกการสังเกต",
|
||||||
|
"evidence": "หลักฐานประกอบ",
|
||||||
|
"revisionEvidence": "หลักฐานการแก้ไขในรอบเดียวกัน",
|
||||||
|
"revisionEmpty": "ไม่มีหลักฐานการแก้ไข",
|
||||||
|
"closedBasis": "หลักฐานหลังปิด",
|
||||||
|
"closedBasisEmpty": "ไม่มีหลักฐานหลังปิด",
|
||||||
|
"closedBasisHint": "บันทึกเหล่านี้เกิดหลังปิดรายการ การแจ้งเตือนยังคงปิดอยู่ เวลาที่เกิดล่าสุดและจำนวนการสังเกตไม่เปลี่ยนเพราะบันทึกเหล่านี้",
|
||||||
|
"history": "ประวัติการจัดการ",
|
||||||
|
"historyEmpty": "ยังไม่มีประวัติการจัดการ",
|
||||||
|
"fields": {
|
||||||
|
"status": "สถานะ",
|
||||||
|
"scenario": "สถานการณ์",
|
||||||
|
"module": "โมดูล",
|
||||||
|
"scenarioKey": "คีย์สถานการณ์",
|
||||||
|
"object": "วัตถุ",
|
||||||
|
"count": "จำนวนการสังเกต",
|
||||||
|
"firstOccurred": "เกิดครั้งแรก",
|
||||||
|
"lastOccurred": "เกิดล่าสุด",
|
||||||
|
"handler": "ผู้ดูแลปัจจุบัน",
|
||||||
|
"claimedAt": "เวลาเริ่มดำเนินการ",
|
||||||
|
"closedAt": "เวลาปิด",
|
||||||
|
"cycle": "รอบ",
|
||||||
|
"event": "เหตุการณ์",
|
||||||
|
"openedAt": "เวลาเปิด",
|
||||||
|
"updatedAt": "เวลาอัปเดต",
|
||||||
|
"previous": "การแจ้งเตือนที่เชื่อมไว้ก่อนหน้า",
|
||||||
|
"none": "ไม่มี"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"occurrence": {
|
||||||
|
"observedAt": "เวลาสังเกต",
|
||||||
|
"receivedAt": "เวลารับ",
|
||||||
|
"cycle": "รอบ",
|
||||||
|
"event": "เหตุการณ์"
|
||||||
|
},
|
||||||
|
"evidenceCols": {
|
||||||
|
"receivedAt": "เวลารับ",
|
||||||
|
"recordedAt": "เวลาบันทึก",
|
||||||
|
"observedAt": "เวลาสังเกต",
|
||||||
|
"snapshotVersion": "เวอร์ชันสแนปช็อต",
|
||||||
|
"cycle": "รอบ",
|
||||||
|
"event": "เหตุการณ์"
|
||||||
|
},
|
||||||
|
"historyCols": {
|
||||||
|
"seq": "ลำดับ",
|
||||||
|
"command": "การกระทำ",
|
||||||
|
"actor": "ผู้ทำ",
|
||||||
|
"handler": "ผู้ดูแล",
|
||||||
|
"note": "คำอธิบาย",
|
||||||
|
"result": "ผล",
|
||||||
|
"evidence": "อ้างอิงหลักฐาน",
|
||||||
|
"at": "เวลา"
|
||||||
|
},
|
||||||
|
"commandName": {
|
||||||
|
"claim": "ดำเนินการ",
|
||||||
|
"progress": "ความคืบหน้า",
|
||||||
|
"close": "ปิด"
|
||||||
|
},
|
||||||
|
"progressDialog": {
|
||||||
|
"title": "เพิ่มความคืบหน้า",
|
||||||
|
"note": "คำอธิบาย",
|
||||||
|
"notePlaceholder": "รอบนี้ทำอะไรไป",
|
||||||
|
"evidence": "อ้างอิงหลักฐาน",
|
||||||
|
"evidencePlaceholder": "ไม่บังคับ",
|
||||||
|
"required": "ต้องใส่คำอธิบาย",
|
||||||
|
"cancel": "ยกเลิก",
|
||||||
|
"submit": "บันทึกความคืบหน้า"
|
||||||
|
},
|
||||||
|
"closeDialog": {
|
||||||
|
"title": "ปิดการแจ้งเตือน",
|
||||||
|
"result": "ผลการปิด",
|
||||||
|
"resultPlaceholder": "เลือกผล",
|
||||||
|
"note": "คำอธิบาย",
|
||||||
|
"notePlaceholder": "ทำไมจึงปิดแบบนี้",
|
||||||
|
"evidence": "อ้างอิงหลักฐาน",
|
||||||
|
"evidencePlaceholder": "ไม่บังคับ",
|
||||||
|
"resultRequired": "กรุณาเลือกผลการปิด",
|
||||||
|
"noteRequired": "ต้องใส่คำอธิบาย",
|
||||||
|
"cancel": "ยกเลิก",
|
||||||
|
"submit": "ยืนยันการปิด"
|
||||||
|
},
|
||||||
|
"command": {
|
||||||
|
"claimed": "เริ่มดำเนินการแล้ว",
|
||||||
|
"progressSaved": "บันทึกความคืบหน้าแล้ว",
|
||||||
|
"closed": "ปิดแล้ว",
|
||||||
|
"failed": "การทำงานไม่เสร็จ",
|
||||||
|
"conflictRefreshed": "หน้านี้รีเฟรชเป็นสถานะล่าสุดแล้ว"
|
||||||
|
},
|
||||||
|
"errors": {
|
||||||
|
"already_claimed": "การแจ้งเตือนนี้มีผู้ดูแลแล้ว ดำเนินการซ้ำไม่ได้",
|
||||||
|
"not_current_handler": "ไม่ใช่ผู้ดูแลปัจจุบัน จึงทำรายการนี้ไม่ได้",
|
||||||
|
"illegal_transition": "สถานะปัจจุบันทำรายการนี้ไม่ได้",
|
||||||
|
"already_closed": "การแจ้งเตือนนี้ปิดแล้ว",
|
||||||
|
"idempotency_payload_mismatch": "รหัสส่งนี้ถูกใช้กับเนื้อหาอื่นแล้ว",
|
||||||
|
"handling_history_missing": "ประวัติการจัดการไม่ครบ โปรดรีเฟรชแล้วลองใหม่",
|
||||||
|
"idempotency_key_required": "ไม่มีรหัสส่ง โปรดลองใหม่",
|
||||||
|
"idempotency_key_too_long": "รหัสส่งยาวเกินไป",
|
||||||
|
"note_invalid": "คำอธิบายไม่ถูกต้อง",
|
||||||
|
"evidence_ref_invalid": "การอ้างอิงหลักฐานไม่ถูกต้อง",
|
||||||
|
"close_result_invalid": "ผลการปิดไม่ถูกต้อง",
|
||||||
|
"not_found": "ไม่พบการแจ้งเตือนนี้",
|
||||||
|
"forbidden": "ไม่มีสิทธิ์ ({node})",
|
||||||
|
"forbiddenPlain": "ไม่มีสิทธิ์ทำการนี้ให้เสร็จ"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -39,6 +39,7 @@
|
|||||||
"datasources": "数据源",
|
"datasources": "数据源",
|
||||||
"queries": "查询",
|
"queries": "查询",
|
||||||
"mappings": "映射与规则",
|
"mappings": "映射与规则",
|
||||||
|
"alarms": "报警",
|
||||||
"create": "新建",
|
"create": "新建",
|
||||||
"detail": "详情",
|
"detail": "详情",
|
||||||
"version": "版本 v{no}"
|
"version": "版本 v{no}"
|
||||||
@@ -454,5 +455,171 @@
|
|||||||
"unsupported_engine": "该数据源引擎暂不支持",
|
"unsupported_engine": "该数据源引擎暂不支持",
|
||||||
"unsupported_datasource": "该数据源类型暂不支持"
|
"unsupported_datasource": "该数据源类型暂不支持"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"alarm": {
|
||||||
|
"list": {
|
||||||
|
"filterModule": "模块",
|
||||||
|
"filterScenario": "场景名称",
|
||||||
|
"filterObject": "对象编号",
|
||||||
|
"filterStatus": "状态",
|
||||||
|
"filterFrom": "最近发生起",
|
||||||
|
"filterTo": "最近发生止",
|
||||||
|
"filterSearch": "查询",
|
||||||
|
"filterReset": "重置",
|
||||||
|
"loadFailed": "报警列表加载失败",
|
||||||
|
"retry": "重试",
|
||||||
|
"empty": "还没有报警",
|
||||||
|
"emptyHint": "当前处理范围内还没有报警。",
|
||||||
|
"noMatch": "没有符合条件的报警",
|
||||||
|
"noMatchHint": "试试改筛选条件,或点重置。",
|
||||||
|
"noScope": "没有处理范围,所以看不到报警",
|
||||||
|
"noScopeHint": "当前账号没有可用来查看报警的主体。这不是租户里没有报警。",
|
||||||
|
"forbidden": "没有查看报警的权限",
|
||||||
|
"objectInvalid": "对象编号需要是完整的编号",
|
||||||
|
"timeOrder": "开始时间不能晚于结束时间",
|
||||||
|
"resultSep": " · "
|
||||||
|
},
|
||||||
|
"columns": {
|
||||||
|
"module": "模块",
|
||||||
|
"scenario": "场景",
|
||||||
|
"object": "对象",
|
||||||
|
"lastOccurred": "最近发生",
|
||||||
|
"status": "状态",
|
||||||
|
"actions": "操作"
|
||||||
|
},
|
||||||
|
"status": {
|
||||||
|
"pending": "待处理",
|
||||||
|
"processing": "处理中",
|
||||||
|
"closed": "已关闭"
|
||||||
|
},
|
||||||
|
"closeResult": {
|
||||||
|
"resolved": "已处理",
|
||||||
|
"false_positive": "误报"
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"open": "打开",
|
||||||
|
"back": "返回列表",
|
||||||
|
"claim": "处理",
|
||||||
|
"progress": "追加进展",
|
||||||
|
"close": "关闭",
|
||||||
|
"submitting": "提交中"
|
||||||
|
},
|
||||||
|
"role": {
|
||||||
|
"watchman-admin": "管理者",
|
||||||
|
"watchman-operator": "处理者",
|
||||||
|
"watchman-viewer": "查看者"
|
||||||
|
},
|
||||||
|
"detail": {
|
||||||
|
"loading": "报警详情加载中",
|
||||||
|
"loadFailed": "报警详情加载失败",
|
||||||
|
"sectionFailed": "部分内容没有载入",
|
||||||
|
"notFound": "没有找到这条报警",
|
||||||
|
"summary": "摘要",
|
||||||
|
"occurrences": "观测",
|
||||||
|
"occurrencesHint": "每条观测只显示接口里的时间、周期和事件。",
|
||||||
|
"occurrencesEmpty": "还没有观测记录",
|
||||||
|
"evidence": "依据",
|
||||||
|
"revisionEvidence": "同周期修订依据",
|
||||||
|
"revisionEmpty": "没有修订依据",
|
||||||
|
"closedBasis": "关闭后依据",
|
||||||
|
"closedBasisEmpty": "没有关闭后依据",
|
||||||
|
"closedBasisHint": "这些记录出现在关闭之后。报警保持关闭,最近发生时间和观测次数不会因此改变。",
|
||||||
|
"history": "处理历史",
|
||||||
|
"historyEmpty": "还没有处理记录",
|
||||||
|
"fields": {
|
||||||
|
"status": "状态",
|
||||||
|
"scenario": "场景",
|
||||||
|
"module": "模块",
|
||||||
|
"scenarioKey": "场景键",
|
||||||
|
"object": "对象",
|
||||||
|
"count": "观测次数",
|
||||||
|
"firstOccurred": "首次发生",
|
||||||
|
"lastOccurred": "最近发生",
|
||||||
|
"handler": "当前处理人",
|
||||||
|
"claimedAt": "开始处理时间",
|
||||||
|
"closedAt": "关闭时间",
|
||||||
|
"cycle": "周期",
|
||||||
|
"event": "事件",
|
||||||
|
"openedAt": "打开时间",
|
||||||
|
"updatedAt": "更新时间",
|
||||||
|
"previous": "关联的上一条报警",
|
||||||
|
"none": "无"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"occurrence": {
|
||||||
|
"observedAt": "观测时间",
|
||||||
|
"receivedAt": "接收时间",
|
||||||
|
"cycle": "周期",
|
||||||
|
"event": "事件"
|
||||||
|
},
|
||||||
|
"evidenceCols": {
|
||||||
|
"receivedAt": "接收时间",
|
||||||
|
"recordedAt": "记录时间",
|
||||||
|
"observedAt": "观测时间",
|
||||||
|
"snapshotVersion": "快照版本",
|
||||||
|
"cycle": "周期",
|
||||||
|
"event": "事件"
|
||||||
|
},
|
||||||
|
"historyCols": {
|
||||||
|
"seq": "序号",
|
||||||
|
"command": "动作",
|
||||||
|
"actor": "操作者",
|
||||||
|
"handler": "处理人",
|
||||||
|
"note": "说明",
|
||||||
|
"result": "结果",
|
||||||
|
"evidence": "证据引用",
|
||||||
|
"at": "时间"
|
||||||
|
},
|
||||||
|
"commandName": {
|
||||||
|
"claim": "处理",
|
||||||
|
"progress": "进展",
|
||||||
|
"close": "关闭"
|
||||||
|
},
|
||||||
|
"progressDialog": {
|
||||||
|
"title": "追加进展",
|
||||||
|
"note": "说明",
|
||||||
|
"notePlaceholder": "写这次处理做了什么",
|
||||||
|
"evidence": "证据引用",
|
||||||
|
"evidencePlaceholder": "选填",
|
||||||
|
"required": "请填写说明",
|
||||||
|
"cancel": "取消",
|
||||||
|
"submit": "保存进展"
|
||||||
|
},
|
||||||
|
"closeDialog": {
|
||||||
|
"title": "关闭报警",
|
||||||
|
"result": "关闭结果",
|
||||||
|
"resultPlaceholder": "选择结果",
|
||||||
|
"note": "说明",
|
||||||
|
"notePlaceholder": "说明为什么这样关闭",
|
||||||
|
"evidence": "证据引用",
|
||||||
|
"evidencePlaceholder": "选填",
|
||||||
|
"resultRequired": "请选择关闭结果",
|
||||||
|
"noteRequired": "请填写说明",
|
||||||
|
"cancel": "取消",
|
||||||
|
"submit": "确认关闭"
|
||||||
|
},
|
||||||
|
"command": {
|
||||||
|
"claimed": "已开始处理",
|
||||||
|
"progressSaved": "进展已保存",
|
||||||
|
"closed": "已关闭",
|
||||||
|
"failed": "操作未完成",
|
||||||
|
"conflictRefreshed": "页面已按最新状态刷新"
|
||||||
|
},
|
||||||
|
"errors": {
|
||||||
|
"already_claimed": "这条报警已经有处理人,不能再处理",
|
||||||
|
"not_current_handler": "不是当前处理人,不能完成这个操作",
|
||||||
|
"illegal_transition": "当前状态不能做这个操作",
|
||||||
|
"already_closed": "这条报警已经关闭",
|
||||||
|
"idempotency_payload_mismatch": "同一个提交编号被用在了不同的内容上",
|
||||||
|
"handling_history_missing": "处理记录不完整,请刷新后再试",
|
||||||
|
"idempotency_key_required": "缺少提交编号,请重试",
|
||||||
|
"idempotency_key_too_long": "提交编号过长",
|
||||||
|
"note_invalid": "说明不合法",
|
||||||
|
"evidence_ref_invalid": "证据引用不合法",
|
||||||
|
"close_result_invalid": "关闭结果不合法",
|
||||||
|
"not_found": "没有找到这条报警",
|
||||||
|
"forbidden": "没有权限({node})",
|
||||||
|
"forbiddenPlain": "没有权限完成这个操作"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -38,6 +38,7 @@
|
|||||||
"datasources": "資料來源",
|
"datasources": "資料來源",
|
||||||
"queries": "查詢",
|
"queries": "查詢",
|
||||||
"mappings": "映射與規則",
|
"mappings": "映射與規則",
|
||||||
|
"alarms": "警報",
|
||||||
"create": "新增",
|
"create": "新增",
|
||||||
"detail": "詳情",
|
"detail": "詳情",
|
||||||
"version": "版本 v{no}"
|
"version": "版本 v{no}"
|
||||||
@@ -453,5 +454,171 @@
|
|||||||
"unsupported_engine": "該資料來源引擎暫不支援",
|
"unsupported_engine": "該資料來源引擎暫不支援",
|
||||||
"unsupported_datasource": "該資料來源類型暫不支援"
|
"unsupported_datasource": "該資料來源類型暫不支援"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"alarm": {
|
||||||
|
"list": {
|
||||||
|
"filterModule": "模組",
|
||||||
|
"filterScenario": "場景名稱",
|
||||||
|
"filterObject": "物件編號",
|
||||||
|
"filterStatus": "狀態",
|
||||||
|
"filterFrom": "最近發生起",
|
||||||
|
"filterTo": "最近發生止",
|
||||||
|
"filterSearch": "查詢",
|
||||||
|
"filterReset": "重設",
|
||||||
|
"loadFailed": "警報清單載入失敗",
|
||||||
|
"retry": "重試",
|
||||||
|
"empty": "還沒有警報",
|
||||||
|
"emptyHint": "目前處理範圍內還沒有警報。",
|
||||||
|
"noMatch": "沒有符合條件的警報",
|
||||||
|
"noMatchHint": "試試改篩選條件,或點重設。",
|
||||||
|
"noScope": "沒有處理範圍,所以看不到警報",
|
||||||
|
"noScopeHint": "目前帳號沒有可用來查看警報的主體。這不是租戶裡沒有警報。",
|
||||||
|
"forbidden": "沒有查看警報的權限",
|
||||||
|
"objectInvalid": "物件編號需要是完整的編號",
|
||||||
|
"timeOrder": "開始時間不能晚於結束時間",
|
||||||
|
"resultSep": " · "
|
||||||
|
},
|
||||||
|
"columns": {
|
||||||
|
"module": "模組",
|
||||||
|
"scenario": "場景",
|
||||||
|
"object": "物件",
|
||||||
|
"lastOccurred": "最近發生",
|
||||||
|
"status": "狀態",
|
||||||
|
"actions": "操作"
|
||||||
|
},
|
||||||
|
"status": {
|
||||||
|
"pending": "待處理",
|
||||||
|
"processing": "處理中",
|
||||||
|
"closed": "已關閉"
|
||||||
|
},
|
||||||
|
"closeResult": {
|
||||||
|
"resolved": "已處理",
|
||||||
|
"false_positive": "誤報"
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"open": "打開",
|
||||||
|
"back": "返回清單",
|
||||||
|
"claim": "處理",
|
||||||
|
"progress": "追加進展",
|
||||||
|
"close": "關閉",
|
||||||
|
"submitting": "提交中"
|
||||||
|
},
|
||||||
|
"role": {
|
||||||
|
"watchman-admin": "管理者",
|
||||||
|
"watchman-operator": "處理者",
|
||||||
|
"watchman-viewer": "查看者"
|
||||||
|
},
|
||||||
|
"detail": {
|
||||||
|
"loading": "警報詳情載入中",
|
||||||
|
"loadFailed": "警報詳情載入失敗",
|
||||||
|
"sectionFailed": "部分內容沒有載入",
|
||||||
|
"notFound": "沒有找到這條警報",
|
||||||
|
"summary": "摘要",
|
||||||
|
"occurrences": "觀測",
|
||||||
|
"occurrencesHint": "每條觀測只顯示介面裡的時間、週期和事件。",
|
||||||
|
"occurrencesEmpty": "還沒有觀測記錄",
|
||||||
|
"evidence": "依據",
|
||||||
|
"revisionEvidence": "同週期修訂依據",
|
||||||
|
"revisionEmpty": "沒有修訂依據",
|
||||||
|
"closedBasis": "關閉後依據",
|
||||||
|
"closedBasisEmpty": "沒有關閉後依據",
|
||||||
|
"closedBasisHint": "這些記錄出現在關閉之後。警報保持關閉,最近發生時間和觀測次數不會因此改變。",
|
||||||
|
"history": "處理歷史",
|
||||||
|
"historyEmpty": "還沒有處理記錄",
|
||||||
|
"fields": {
|
||||||
|
"status": "狀態",
|
||||||
|
"scenario": "場景",
|
||||||
|
"module": "模組",
|
||||||
|
"scenarioKey": "場景鍵",
|
||||||
|
"object": "物件",
|
||||||
|
"count": "觀測次數",
|
||||||
|
"firstOccurred": "首次發生",
|
||||||
|
"lastOccurred": "最近發生",
|
||||||
|
"handler": "目前處理人",
|
||||||
|
"claimedAt": "開始處理時間",
|
||||||
|
"closedAt": "關閉時間",
|
||||||
|
"cycle": "週期",
|
||||||
|
"event": "事件",
|
||||||
|
"openedAt": "打開時間",
|
||||||
|
"updatedAt": "更新時間",
|
||||||
|
"previous": "關聯的上一條警報",
|
||||||
|
"none": "無"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"occurrence": {
|
||||||
|
"observedAt": "觀測時間",
|
||||||
|
"receivedAt": "接收時間",
|
||||||
|
"cycle": "週期",
|
||||||
|
"event": "事件"
|
||||||
|
},
|
||||||
|
"evidenceCols": {
|
||||||
|
"receivedAt": "接收時間",
|
||||||
|
"recordedAt": "記錄時間",
|
||||||
|
"observedAt": "觀測時間",
|
||||||
|
"snapshotVersion": "快照版本",
|
||||||
|
"cycle": "週期",
|
||||||
|
"event": "事件"
|
||||||
|
},
|
||||||
|
"historyCols": {
|
||||||
|
"seq": "序號",
|
||||||
|
"command": "動作",
|
||||||
|
"actor": "操作者",
|
||||||
|
"handler": "處理人",
|
||||||
|
"note": "說明",
|
||||||
|
"result": "結果",
|
||||||
|
"evidence": "證據引用",
|
||||||
|
"at": "時間"
|
||||||
|
},
|
||||||
|
"commandName": {
|
||||||
|
"claim": "處理",
|
||||||
|
"progress": "進展",
|
||||||
|
"close": "關閉"
|
||||||
|
},
|
||||||
|
"progressDialog": {
|
||||||
|
"title": "追加進展",
|
||||||
|
"note": "說明",
|
||||||
|
"notePlaceholder": "寫這次處理做了什麼",
|
||||||
|
"evidence": "證據引用",
|
||||||
|
"evidencePlaceholder": "選填",
|
||||||
|
"required": "請填寫說明",
|
||||||
|
"cancel": "取消",
|
||||||
|
"submit": "儲存進展"
|
||||||
|
},
|
||||||
|
"closeDialog": {
|
||||||
|
"title": "關閉警報",
|
||||||
|
"result": "關閉結果",
|
||||||
|
"resultPlaceholder": "選擇結果",
|
||||||
|
"note": "說明",
|
||||||
|
"notePlaceholder": "說明為什麼這樣關閉",
|
||||||
|
"evidence": "證據引用",
|
||||||
|
"evidencePlaceholder": "選填",
|
||||||
|
"resultRequired": "請選擇關閉結果",
|
||||||
|
"noteRequired": "請填寫說明",
|
||||||
|
"cancel": "取消",
|
||||||
|
"submit": "確認關閉"
|
||||||
|
},
|
||||||
|
"command": {
|
||||||
|
"claimed": "已開始處理",
|
||||||
|
"progressSaved": "進展已儲存",
|
||||||
|
"closed": "已關閉",
|
||||||
|
"failed": "操作未完成",
|
||||||
|
"conflictRefreshed": "頁面已按最新狀態重新整理"
|
||||||
|
},
|
||||||
|
"errors": {
|
||||||
|
"already_claimed": "這條警報已經有處理人,不能再處理",
|
||||||
|
"not_current_handler": "不是目前處理人,不能完成這個操作",
|
||||||
|
"illegal_transition": "目前狀態不能做這個操作",
|
||||||
|
"already_closed": "這條警報已經關閉",
|
||||||
|
"idempotency_payload_mismatch": "同一個提交編號被用在了不同的內容上",
|
||||||
|
"handling_history_missing": "處理記錄不完整,請重新整理後再試",
|
||||||
|
"idempotency_key_required": "缺少提交編號,請重試",
|
||||||
|
"idempotency_key_too_long": "提交編號過長",
|
||||||
|
"note_invalid": "說明不合法",
|
||||||
|
"evidence_ref_invalid": "證據引用不合法",
|
||||||
|
"close_result_invalid": "關閉結果不合法",
|
||||||
|
"not_found": "沒有找到這條警報",
|
||||||
|
"forbidden": "沒有權限({node})",
|
||||||
|
"forbiddenPlain": "沒有權限完成這個操作"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -18,7 +18,12 @@ const { t } = useI18n();
|
|||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
const auth = useAuthStore();
|
const auth = useAuthStore();
|
||||||
|
|
||||||
const CRUMB_LINKS: Record<string, string> = { datasources: "/datasources", queries: "/queries", mappings: "/mappings" };
|
const CRUMB_LINKS: Record<string, string> = {
|
||||||
|
datasources: "/datasources",
|
||||||
|
queries: "/queries",
|
||||||
|
mappings: "/mappings",
|
||||||
|
alarms: "/alarms",
|
||||||
|
};
|
||||||
|
|
||||||
/** Where a non-final crumb goes. A query's "detail" crumb is the draft page of the same query. */
|
/** Where a non-final crumb goes. A query's "detail" crumb is the draft page of the same query. */
|
||||||
function crumbLink(key: string): string | undefined {
|
function crumbLink(key: string): string | undefined {
|
||||||
@@ -95,6 +100,9 @@ const activeClass = "!bg-[#eef0fb] !font-semibold !text-[var(--color-primary)]";
|
|||||||
<RouterLink to="/mappings" :class="linkClass" :active-class="activeClass" data-testid="nav-mappings">
|
<RouterLink to="/mappings" :class="linkClass" :active-class="activeClass" data-testid="nav-mappings">
|
||||||
{{ t("nav.mappings") }}
|
{{ t("nav.mappings") }}
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
|
<RouterLink to="/alarms" :class="linkClass" :active-class="activeClass" data-testid="nav-alarms">
|
||||||
|
{{ t("nav.alarms") }}
|
||||||
|
</RouterLink>
|
||||||
</nav>
|
</nav>
|
||||||
<div
|
<div
|
||||||
class="mt-3 border-t border-[var(--border-subtle)] px-2.5 pt-3"
|
class="mt-3 border-t border-[var(--border-subtle)] px-2.5 pt-3"
|
||||||
|
|||||||
@@ -0,0 +1,706 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
/**
|
||||||
|
* Alarm detail: summary, observations, evidence, and handling history.
|
||||||
|
* Boundary: footer commands follow the role rules. A closed alarm keeps only
|
||||||
|
* 返回. Server error text is not rendered. Closed basis is not a recovery.
|
||||||
|
* Depends on the alarm read APIs and the three command routes.
|
||||||
|
*/
|
||||||
|
import { computed, nextTick, onMounted, reactive, ref, watch } from "vue";
|
||||||
|
import { useI18n } from "vue-i18n";
|
||||||
|
import { useRoute, useRouter } from "vue-router";
|
||||||
|
import {
|
||||||
|
ElAlert,
|
||||||
|
ElButton,
|
||||||
|
ElDialog,
|
||||||
|
ElForm,
|
||||||
|
ElFormItem,
|
||||||
|
ElInput,
|
||||||
|
ElMessage,
|
||||||
|
ElOption,
|
||||||
|
ElSelect,
|
||||||
|
ElTable,
|
||||||
|
ElTableColumn,
|
||||||
|
ElTag,
|
||||||
|
type FormInstance,
|
||||||
|
type FormRules,
|
||||||
|
} from "element-plus";
|
||||||
|
import { useAuthStore } from "../stores/auth";
|
||||||
|
import {
|
||||||
|
ALARM_PERMISSION,
|
||||||
|
alarmCommandVisibility,
|
||||||
|
clearIdempotencyKey,
|
||||||
|
holdIdempotencyKey,
|
||||||
|
type IdempotencyHold,
|
||||||
|
} from "./actions";
|
||||||
|
import { appendProgress, claimAlarm, closeAlarm, getAlarm, listEvidence, listHistory, listOccurrences } from "./client";
|
||||||
|
import { describeAlarmError, isAlarmConflict, isAlarmForbidden, isAlarmNotFound } from "./errors";
|
||||||
|
import { formatDateTime } from "./format";
|
||||||
|
import type { AlarmRecord, ClosedBasis, EvidenceBundle, HistoryEvent, OccurrenceList } from "./types";
|
||||||
|
|
||||||
|
const { t, te } = useI18n();
|
||||||
|
const route = useRoute();
|
||||||
|
const router = useRouter();
|
||||||
|
const auth = useAuthStore();
|
||||||
|
|
||||||
|
const alarm = ref<AlarmRecord | null>(null);
|
||||||
|
const occurrences = ref<OccurrenceList["items"]>([]);
|
||||||
|
const evidence = ref<EvidenceBundle | null>(null);
|
||||||
|
const history = ref<HistoryEvent[]>([]);
|
||||||
|
const phase = ref<"loading" | "ready" | "error" | "forbidden" | "missing">("loading");
|
||||||
|
const loadError = ref("");
|
||||||
|
const sectionError = ref("");
|
||||||
|
const commandError = ref("");
|
||||||
|
const commandConflict = ref(false);
|
||||||
|
const commandBusy = ref(false);
|
||||||
|
|
||||||
|
const progressOpen = ref(false);
|
||||||
|
const closeOpen = ref(false);
|
||||||
|
const progressModel = reactive({ note: "", evidence: "" });
|
||||||
|
const closeModel = reactive({ result: "", note: "", evidence: "" });
|
||||||
|
const progressForm = ref<FormInstance>();
|
||||||
|
const closeForm = ref<FormInstance>();
|
||||||
|
|
||||||
|
const claimHold = ref<IdempotencyHold>(clearIdempotencyKey());
|
||||||
|
const progressHold = ref<IdempotencyHold>(clearIdempotencyKey());
|
||||||
|
const closeHold = ref<IdempotencyHold>(clearIdempotencyKey());
|
||||||
|
|
||||||
|
let loadSeq = 0;
|
||||||
|
|
||||||
|
const commands = computed(() =>
|
||||||
|
alarmCommandVisibility({
|
||||||
|
roles: auth.user?.roles ?? [],
|
||||||
|
subject: auth.user?.subject,
|
||||||
|
status: alarm.value?.status ?? "",
|
||||||
|
currentHandler: alarm.value?.current_handler ?? null,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const progressRules = computed<FormRules>(() => ({
|
||||||
|
note: [{ required: true, whitespace: true, message: t("alarm.progressDialog.required"), trigger: "blur" }],
|
||||||
|
}));
|
||||||
|
const closeRules = computed<FormRules>(() => ({
|
||||||
|
result: [{ required: true, message: t("alarm.closeDialog.resultRequired"), trigger: "change" }],
|
||||||
|
note: [{ required: true, whitespace: true, message: t("alarm.closeDialog.noteRequired"), trigger: "blur" }],
|
||||||
|
}));
|
||||||
|
|
||||||
|
function newKey(): string {
|
||||||
|
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
||||||
|
return crypto.randomUUID();
|
||||||
|
}
|
||||||
|
return `alarm-${Date.now()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function textOrNone(value: string | null | undefined): string {
|
||||||
|
if (value === null || value === undefined || value.trim() === "") {
|
||||||
|
return t("alarm.detail.fields.none");
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusText(status: string): string {
|
||||||
|
const key = `alarm.status.${status}`;
|
||||||
|
return te(key) ? t(key) : status;
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusTag(status: string): "warning" | "primary" | "info" {
|
||||||
|
if (status === "pending") {
|
||||||
|
return "warning";
|
||||||
|
}
|
||||||
|
if (status === "processing") {
|
||||||
|
return "primary";
|
||||||
|
}
|
||||||
|
return "info";
|
||||||
|
}
|
||||||
|
|
||||||
|
function named(group: string, value: string | null | undefined): string {
|
||||||
|
if (!value) {
|
||||||
|
return t("alarm.detail.fields.none");
|
||||||
|
}
|
||||||
|
const key = `alarm.${group}.${value}`;
|
||||||
|
return te(key) ? t(key) : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function roleText(role: string): string {
|
||||||
|
const key = `alarm.role.${role}`;
|
||||||
|
return te(key) ? t(key) : role;
|
||||||
|
}
|
||||||
|
|
||||||
|
function backToList(): void {
|
||||||
|
void router.push({ name: "alarm-list" });
|
||||||
|
}
|
||||||
|
|
||||||
|
function openPrevious(): void {
|
||||||
|
const id = alarm.value?.previous_alarm_id;
|
||||||
|
if (!id) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void router.push({ name: "alarm-detail", params: { id } });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load(): Promise<void> {
|
||||||
|
const id = String(route.params.id ?? "");
|
||||||
|
const seq = ++loadSeq;
|
||||||
|
phase.value = "loading";
|
||||||
|
loadError.value = "";
|
||||||
|
sectionError.value = "";
|
||||||
|
alarm.value = null;
|
||||||
|
occurrences.value = [];
|
||||||
|
evidence.value = null;
|
||||||
|
history.value = [];
|
||||||
|
if (!id) {
|
||||||
|
phase.value = "missing";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const [alarmResult, occurrenceResult, evidenceResult, historyResult] = await Promise.allSettled([
|
||||||
|
getAlarm(id),
|
||||||
|
listOccurrences(id),
|
||||||
|
listEvidence(id),
|
||||||
|
listHistory(id),
|
||||||
|
]);
|
||||||
|
if (seq !== loadSeq) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (alarmResult.status === "rejected") {
|
||||||
|
if (isAlarmNotFound(alarmResult.reason)) {
|
||||||
|
phase.value = "missing";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
phase.value = isAlarmForbidden(alarmResult.reason) ? "forbidden" : "error";
|
||||||
|
loadError.value = describeAlarmError(
|
||||||
|
alarmResult.reason,
|
||||||
|
t,
|
||||||
|
te,
|
||||||
|
"alarm.detail.loadFailed",
|
||||||
|
ALARM_PERMISSION.read,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
alarm.value = alarmResult.value;
|
||||||
|
if (occurrenceResult.status === "fulfilled") {
|
||||||
|
occurrences.value = occurrenceResult.value.items;
|
||||||
|
}
|
||||||
|
if (evidenceResult.status === "fulfilled") {
|
||||||
|
evidence.value = evidenceResult.value;
|
||||||
|
}
|
||||||
|
if (historyResult.status === "fulfilled") {
|
||||||
|
history.value = historyResult.value.items;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
occurrenceResult.status === "rejected" ||
|
||||||
|
evidenceResult.status === "rejected" ||
|
||||||
|
historyResult.status === "rejected"
|
||||||
|
) {
|
||||||
|
const reason =
|
||||||
|
(occurrenceResult.status === "rejected" && occurrenceResult.reason) ||
|
||||||
|
(evidenceResult.status === "rejected" && evidenceResult.reason) ||
|
||||||
|
(historyResult.status === "rejected" && historyResult.reason);
|
||||||
|
sectionError.value = describeAlarmError(reason, t, te, "alarm.detail.sectionFailed", ALARM_PERMISSION.read);
|
||||||
|
}
|
||||||
|
phase.value = "ready";
|
||||||
|
}
|
||||||
|
|
||||||
|
function permissionFor(command: "claim" | "progress" | "close"): string {
|
||||||
|
if (command === "claim") {
|
||||||
|
return ALARM_PERMISSION.take;
|
||||||
|
}
|
||||||
|
if (command === "progress") {
|
||||||
|
return ALARM_PERMISSION.progress;
|
||||||
|
}
|
||||||
|
return ALARM_PERMISSION.close;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runCommand(
|
||||||
|
command: "claim" | "progress" | "close",
|
||||||
|
send: () => Promise<unknown>,
|
||||||
|
): Promise<boolean> {
|
||||||
|
if (commandBusy.value) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
commandBusy.value = true;
|
||||||
|
commandError.value = "";
|
||||||
|
commandConflict.value = false;
|
||||||
|
try {
|
||||||
|
await send();
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
commandConflict.value = isAlarmConflict(error);
|
||||||
|
commandError.value = describeAlarmError(
|
||||||
|
error,
|
||||||
|
t,
|
||||||
|
te,
|
||||||
|
"alarm.command.failed",
|
||||||
|
permissionFor(command),
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
commandBusy.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function finishCommand(ok: boolean, successKey: string, closeDialog: () => void): Promise<void> {
|
||||||
|
if (ok) {
|
||||||
|
closeDialog();
|
||||||
|
ElMessage.success(t(successKey));
|
||||||
|
} else if (commandConflict.value) {
|
||||||
|
closeDialog();
|
||||||
|
}
|
||||||
|
await load();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onClaim(): Promise<void> {
|
||||||
|
const id = alarm.value?.id;
|
||||||
|
if (!id || !commands.value.claim) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
claimHold.value = holdIdempotencyKey(claimHold.value, "claim", newKey);
|
||||||
|
const key = claimHold.value.key;
|
||||||
|
const ok = await runCommand("claim", () => claimAlarm(id, key));
|
||||||
|
if (ok) {
|
||||||
|
claimHold.value = clearIdempotencyKey();
|
||||||
|
}
|
||||||
|
await finishCommand(ok, "alarm.command.claimed", () => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openProgress(): Promise<void> {
|
||||||
|
progressModel.note = "";
|
||||||
|
progressModel.evidence = "";
|
||||||
|
commandError.value = "";
|
||||||
|
commandConflict.value = false;
|
||||||
|
progressOpen.value = true;
|
||||||
|
await nextTick();
|
||||||
|
progressForm.value?.clearValidate();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitProgress(): Promise<void> {
|
||||||
|
const id = alarm.value?.id;
|
||||||
|
if (!id || !commands.value.progress || commandBusy.value) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const valid = await progressForm.value?.validate().catch(() => false);
|
||||||
|
if (!valid) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const note = progressModel.note.trim();
|
||||||
|
const evidenceRef = progressModel.evidence.trim();
|
||||||
|
const payload = JSON.stringify({ note, evidence_ref: evidenceRef });
|
||||||
|
progressHold.value = holdIdempotencyKey(progressHold.value, payload, newKey);
|
||||||
|
const body = evidenceRef ? { note, evidence_ref: evidenceRef } : { note };
|
||||||
|
const ok = await runCommand("progress", () => appendProgress(id, progressHold.value.key, body));
|
||||||
|
if (ok) {
|
||||||
|
progressHold.value = clearIdempotencyKey();
|
||||||
|
}
|
||||||
|
await finishCommand(ok, "alarm.command.progressSaved", () => {
|
||||||
|
progressOpen.value = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openClose(): Promise<void> {
|
||||||
|
closeModel.result = "";
|
||||||
|
closeModel.note = "";
|
||||||
|
closeModel.evidence = "";
|
||||||
|
commandError.value = "";
|
||||||
|
commandConflict.value = false;
|
||||||
|
closeOpen.value = true;
|
||||||
|
await nextTick();
|
||||||
|
closeForm.value?.clearValidate();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitClose(): Promise<void> {
|
||||||
|
const id = alarm.value?.id;
|
||||||
|
if (!id || !commands.value.close || commandBusy.value) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const valid = await closeForm.value?.validate().catch(() => false);
|
||||||
|
if (!valid) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const note = closeModel.note.trim();
|
||||||
|
const evidenceRef = closeModel.evidence.trim();
|
||||||
|
const payload = JSON.stringify({ result: closeModel.result, note, evidence_ref: evidenceRef });
|
||||||
|
closeHold.value = holdIdempotencyKey(closeHold.value, payload, newKey);
|
||||||
|
const body = evidenceRef
|
||||||
|
? { result: closeModel.result, note, evidence_ref: evidenceRef }
|
||||||
|
: { result: closeModel.result, note };
|
||||||
|
const ok = await runCommand("close", () => closeAlarm(id, closeHold.value.key, body));
|
||||||
|
if (ok) {
|
||||||
|
closeHold.value = clearIdempotencyKey();
|
||||||
|
}
|
||||||
|
await finishCommand(ok, "alarm.command.closed", () => {
|
||||||
|
closeOpen.value = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function keepDialog(done: () => void): void {
|
||||||
|
if (commandBusy.value) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
done();
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => route.params.id,
|
||||||
|
() => {
|
||||||
|
void load();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
void load();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex h-full min-h-0 flex-col" data-testid="alarm-detail">
|
||||||
|
<div class="min-h-0 flex-1 overflow-y-auto p-5" data-testid="alarm-scroll">
|
||||||
|
<p v-if="phase === 'loading'" data-testid="alarm-detail-loading">{{ t("alarm.detail.loading") }}</p>
|
||||||
|
<ElAlert
|
||||||
|
v-else-if="phase === 'missing'"
|
||||||
|
type="warning"
|
||||||
|
data-testid="alarm-missing"
|
||||||
|
:title="t('alarm.detail.notFound')"
|
||||||
|
show-icon
|
||||||
|
:closable="false"
|
||||||
|
/>
|
||||||
|
<ElAlert
|
||||||
|
v-else-if="phase === 'forbidden' || phase === 'error'"
|
||||||
|
type="error"
|
||||||
|
data-testid="alarm-detail-error"
|
||||||
|
:title="loadError || t('alarm.detail.loadFailed')"
|
||||||
|
show-icon
|
||||||
|
:closable="false"
|
||||||
|
/>
|
||||||
|
<template v-else-if="alarm">
|
||||||
|
<ElAlert
|
||||||
|
v-if="commandError"
|
||||||
|
class="mb-3.5"
|
||||||
|
:type="commandConflict ? 'warning' : 'error'"
|
||||||
|
data-testid="alarm-command-error"
|
||||||
|
:title="commandError"
|
||||||
|
:description="commandConflict ? t('alarm.command.conflictRefreshed') : undefined"
|
||||||
|
show-icon
|
||||||
|
:closable="false"
|
||||||
|
/>
|
||||||
|
<ElAlert
|
||||||
|
v-if="sectionError"
|
||||||
|
class="mb-3.5"
|
||||||
|
type="error"
|
||||||
|
data-testid="alarm-section-error"
|
||||||
|
:title="sectionError"
|
||||||
|
show-icon
|
||||||
|
:closable="false"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4" data-testid="alarm-summary">
|
||||||
|
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("alarm.detail.summary") }}</h3>
|
||||||
|
<dl class="grid grid-cols-1 gap-x-6 gap-y-3 sm:grid-cols-2">
|
||||||
|
<div>
|
||||||
|
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.status") }}</dt>
|
||||||
|
<dd>
|
||||||
|
<ElTag :type="statusTag(alarm.status)" effect="light" data-testid="alarm-detail-status">
|
||||||
|
{{ statusText(alarm.status) }}
|
||||||
|
</ElTag>
|
||||||
|
<span v-if="alarm.close_result">
|
||||||
|
{{ t("alarm.list.resultSep") }}{{ named("closeResult", alarm.close_result) }}
|
||||||
|
</span>
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.scenario") }}</dt>
|
||||||
|
<dd>{{ alarm.scenario_name }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.module") }}</dt>
|
||||||
|
<dd>{{ alarm.module_key }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.scenarioKey") }}</dt>
|
||||||
|
<dd>{{ alarm.scenario_key }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.object") }}</dt>
|
||||||
|
<dd data-testid="alarm-identity">{{ alarm.identity_key }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.count") }}</dt>
|
||||||
|
<dd>{{ alarm.occurrence_count }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.firstOccurred") }}</dt>
|
||||||
|
<dd>{{ formatDateTime(alarm.first_occurred_at) || t("alarm.detail.fields.none") }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.lastOccurred") }}</dt>
|
||||||
|
<dd>{{ formatDateTime(alarm.last_occurred_at) || t("alarm.detail.fields.none") }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.handler") }}</dt>
|
||||||
|
<dd data-testid="alarm-handler">{{ textOrNone(alarm.current_handler) }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.claimedAt") }}</dt>
|
||||||
|
<dd>{{ formatDateTime(alarm.claimed_at) || t("alarm.detail.fields.none") }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.closedAt") }}</dt>
|
||||||
|
<dd>{{ formatDateTime(alarm.closed_at) || t("alarm.detail.fields.none") }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.cycle") }}</dt>
|
||||||
|
<dd>{{ textOrNone(alarm.cycle_key) }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.event") }}</dt>
|
||||||
|
<dd>{{ textOrNone(alarm.event_key) }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.openedAt") }}</dt>
|
||||||
|
<dd>{{ formatDateTime(alarm.opened_at) || t("alarm.detail.fields.none") }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.updatedAt") }}</dt>
|
||||||
|
<dd>{{ formatDateTime(alarm.updated_at) || t("alarm.detail.fields.none") }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.previous") }}</dt>
|
||||||
|
<dd>
|
||||||
|
<ElButton
|
||||||
|
v-if="alarm.previous_alarm_id"
|
||||||
|
link
|
||||||
|
type="primary"
|
||||||
|
data-testid="alarm-previous"
|
||||||
|
@click="openPrevious"
|
||||||
|
>
|
||||||
|
{{ alarm.previous_alarm_id }}
|
||||||
|
</ElButton>
|
||||||
|
<span v-else>{{ t("alarm.detail.fields.none") }}</span>
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4" data-testid="alarm-occurrences">
|
||||||
|
<h3 class="mb-1 text-[14.5px] font-semibold">{{ t("alarm.detail.occurrences") }}</h3>
|
||||||
|
<p class="mb-2.5 text-[var(--text-muted)]">{{ t("alarm.detail.occurrencesHint") }}</p>
|
||||||
|
<ElTable :data="occurrences" row-key="id" :empty-text="t('alarm.detail.occurrencesEmpty')">
|
||||||
|
<ElTableColumn :label="t('alarm.occurrence.observedAt')" min-width="160">
|
||||||
|
<template #default="{ row }">{{ formatDateTime(row.observed_at) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('alarm.occurrence.receivedAt')" min-width="160">
|
||||||
|
<template #default="{ row }">{{ formatDateTime(row.received_at) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn prop="cycle_key" :label="t('alarm.occurrence.cycle')" min-width="120" />
|
||||||
|
<ElTableColumn prop="event_key" :label="t('alarm.occurrence.event')" min-width="120" />
|
||||||
|
</ElTable>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4" data-testid="alarm-evidence">
|
||||||
|
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("alarm.detail.evidence") }}</h3>
|
||||||
|
<h4 class="mb-2 font-semibold">{{ t("alarm.detail.revisionEvidence") }}</h4>
|
||||||
|
<ElTable
|
||||||
|
:data="evidence?.revision_evidence ?? []"
|
||||||
|
row-key="id"
|
||||||
|
:empty-text="t('alarm.detail.revisionEmpty')"
|
||||||
|
>
|
||||||
|
<ElTableColumn :label="t('alarm.evidenceCols.receivedAt')" min-width="160">
|
||||||
|
<template #default="{ row }">{{ formatDateTime(row.received_at) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('alarm.evidenceCols.recordedAt')" min-width="160">
|
||||||
|
<template #default="{ row }">{{ formatDateTime(row.recorded_at) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn prop="snapshot_version_no" :label="t('alarm.evidenceCols.snapshotVersion')" min-width="110" />
|
||||||
|
</ElTable>
|
||||||
|
<h4 class="mb-1 mt-4 font-semibold">{{ t("alarm.detail.closedBasis") }}</h4>
|
||||||
|
<p class="mb-2.5 text-[var(--text-muted)]" data-testid="alarm-closed-basis-hint">
|
||||||
|
{{ t("alarm.detail.closedBasisHint") }}
|
||||||
|
</p>
|
||||||
|
<ElTable :data="evidence?.closed_basis ?? []" row-key="id" :empty-text="t('alarm.detail.closedBasisEmpty')">
|
||||||
|
<ElTableColumn :label="t('alarm.evidenceCols.observedAt')" min-width="160">
|
||||||
|
<template #default="{ row }">{{ formatDateTime((row as ClosedBasis).observed_at) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('alarm.evidenceCols.receivedAt')" min-width="160">
|
||||||
|
<template #default="{ row }">{{ formatDateTime(row.received_at) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn prop="cycle_key" :label="t('alarm.evidenceCols.cycle')" min-width="120" />
|
||||||
|
<ElTableColumn prop="event_key" :label="t('alarm.evidenceCols.event')" min-width="120" />
|
||||||
|
</ElTable>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4" data-testid="alarm-history">
|
||||||
|
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("alarm.detail.history") }}</h3>
|
||||||
|
<ElTable :data="history" row-key="id" :empty-text="t('alarm.detail.historyEmpty')">
|
||||||
|
<ElTableColumn prop="seq" :label="t('alarm.historyCols.seq')" width="72" />
|
||||||
|
<ElTableColumn :label="t('alarm.historyCols.command')" min-width="100">
|
||||||
|
<template #default="{ row }">{{ named("commandName", (row as HistoryEvent).command) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('alarm.historyCols.actor')" min-width="140">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ (row as HistoryEvent).actor_subject }}
|
||||||
|
{{ roleText((row as HistoryEvent).actor_role) }}
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn prop="handler_subject" :label="t('alarm.historyCols.handler')" min-width="120" />
|
||||||
|
<ElTableColumn :label="t('alarm.historyCols.note')" min-width="180">
|
||||||
|
<template #default="{ row }">{{ textOrNone((row as HistoryEvent).note) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('alarm.historyCols.result')" min-width="100">
|
||||||
|
<template #default="{ row }">{{ named("closeResult", (row as HistoryEvent).close_result) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('alarm.historyCols.evidence')" min-width="140">
|
||||||
|
<template #default="{ row }">{{ textOrNone((row as HistoryEvent).evidence_ref) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('alarm.historyCols.at')" min-width="160">
|
||||||
|
<template #default="{ row }">{{ formatDateTime((row as HistoryEvent).recorded_at) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
</ElTable>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<footer
|
||||||
|
data-testid="alarm-footer"
|
||||||
|
class="flex shrink-0 flex-wrap items-center justify-center gap-2 border-t border-[var(--border-subtle)] bg-white px-5 py-3"
|
||||||
|
>
|
||||||
|
<ElButton data-testid="footer-back" :disabled="commandBusy" @click="backToList">
|
||||||
|
{{ t("alarm.actions.back") }}
|
||||||
|
</ElButton>
|
||||||
|
<template v-if="phase === 'ready' && alarm && alarm.status !== 'closed'">
|
||||||
|
<ElButton
|
||||||
|
v-if="commands.claim"
|
||||||
|
type="primary"
|
||||||
|
data-testid="footer-claim"
|
||||||
|
:loading="commandBusy"
|
||||||
|
@click="onClaim"
|
||||||
|
>
|
||||||
|
{{ t("alarm.actions.claim") }}
|
||||||
|
</ElButton>
|
||||||
|
<ElButton
|
||||||
|
v-if="commands.progress"
|
||||||
|
data-testid="footer-progress"
|
||||||
|
:disabled="commandBusy"
|
||||||
|
@click="openProgress"
|
||||||
|
>
|
||||||
|
{{ t("alarm.actions.progress") }}
|
||||||
|
</ElButton>
|
||||||
|
<ElButton
|
||||||
|
v-if="commands.close"
|
||||||
|
type="primary"
|
||||||
|
data-testid="footer-close"
|
||||||
|
:disabled="commandBusy"
|
||||||
|
@click="openClose"
|
||||||
|
>
|
||||||
|
{{ t("alarm.actions.close") }}
|
||||||
|
</ElButton>
|
||||||
|
</template>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<ElDialog
|
||||||
|
v-model="progressOpen"
|
||||||
|
align-center
|
||||||
|
append-to-body
|
||||||
|
:close-on-click-modal="false"
|
||||||
|
:before-close="keepDialog"
|
||||||
|
:title="t('alarm.progressDialog.title')"
|
||||||
|
width="480px"
|
||||||
|
data-testid="alarm-progress-dialog"
|
||||||
|
>
|
||||||
|
<ElAlert
|
||||||
|
v-if="commandError && progressOpen"
|
||||||
|
class="mb-3"
|
||||||
|
type="error"
|
||||||
|
:title="commandError"
|
||||||
|
show-icon
|
||||||
|
:closable="false"
|
||||||
|
/>
|
||||||
|
<ElForm
|
||||||
|
ref="progressForm"
|
||||||
|
:model="progressModel"
|
||||||
|
:rules="progressRules"
|
||||||
|
label-position="top"
|
||||||
|
@submit.prevent
|
||||||
|
>
|
||||||
|
<ElFormItem :label="t('alarm.progressDialog.note')" prop="note" data-testid="progress-note">
|
||||||
|
<ElInput
|
||||||
|
v-model="progressModel.note"
|
||||||
|
type="textarea"
|
||||||
|
:rows="4"
|
||||||
|
maxlength="2000"
|
||||||
|
:placeholder="t('alarm.progressDialog.notePlaceholder')"
|
||||||
|
/>
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem :label="t('alarm.progressDialog.evidence')" data-testid="progress-evidence">
|
||||||
|
<ElInput
|
||||||
|
v-model="progressModel.evidence"
|
||||||
|
maxlength="512"
|
||||||
|
:placeholder="t('alarm.progressDialog.evidencePlaceholder')"
|
||||||
|
/>
|
||||||
|
</ElFormItem>
|
||||||
|
</ElForm>
|
||||||
|
<template #footer>
|
||||||
|
<ElButton :disabled="commandBusy" @click="progressOpen = false">
|
||||||
|
{{ t("alarm.progressDialog.cancel") }}
|
||||||
|
</ElButton>
|
||||||
|
<ElButton type="primary" data-testid="progress-submit" :loading="commandBusy" @click="submitProgress">
|
||||||
|
{{ commandBusy ? t("alarm.actions.submitting") : t("alarm.progressDialog.submit") }}
|
||||||
|
</ElButton>
|
||||||
|
</template>
|
||||||
|
</ElDialog>
|
||||||
|
|
||||||
|
<ElDialog
|
||||||
|
v-model="closeOpen"
|
||||||
|
align-center
|
||||||
|
append-to-body
|
||||||
|
:close-on-click-modal="false"
|
||||||
|
:before-close="keepDialog"
|
||||||
|
:title="t('alarm.closeDialog.title')"
|
||||||
|
width="480px"
|
||||||
|
data-testid="alarm-close-dialog"
|
||||||
|
>
|
||||||
|
<ElAlert
|
||||||
|
v-if="commandError && closeOpen"
|
||||||
|
class="mb-3"
|
||||||
|
type="error"
|
||||||
|
:title="commandError"
|
||||||
|
show-icon
|
||||||
|
:closable="false"
|
||||||
|
/>
|
||||||
|
<ElForm
|
||||||
|
ref="closeForm"
|
||||||
|
:model="closeModel"
|
||||||
|
:rules="closeRules"
|
||||||
|
label-position="top"
|
||||||
|
@submit.prevent
|
||||||
|
>
|
||||||
|
<ElFormItem :label="t('alarm.closeDialog.result')" prop="result" data-testid="close-result">
|
||||||
|
<ElSelect v-model="closeModel.result" class="w-full" :placeholder="t('alarm.closeDialog.resultPlaceholder')">
|
||||||
|
<ElOption :label="t('alarm.closeResult.resolved')" value="resolved" />
|
||||||
|
<ElOption :label="t('alarm.closeResult.false_positive')" value="false_positive" />
|
||||||
|
</ElSelect>
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem :label="t('alarm.closeDialog.note')" prop="note" data-testid="close-note">
|
||||||
|
<ElInput
|
||||||
|
v-model="closeModel.note"
|
||||||
|
type="textarea"
|
||||||
|
:rows="4"
|
||||||
|
maxlength="2000"
|
||||||
|
:placeholder="t('alarm.closeDialog.notePlaceholder')"
|
||||||
|
/>
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem :label="t('alarm.closeDialog.evidence')" data-testid="close-evidence">
|
||||||
|
<ElInput
|
||||||
|
v-model="closeModel.evidence"
|
||||||
|
maxlength="512"
|
||||||
|
:placeholder="t('alarm.closeDialog.evidencePlaceholder')"
|
||||||
|
/>
|
||||||
|
</ElFormItem>
|
||||||
|
</ElForm>
|
||||||
|
<template #footer>
|
||||||
|
<ElButton :disabled="commandBusy" @click="closeOpen = false">
|
||||||
|
{{ t("alarm.closeDialog.cancel") }}
|
||||||
|
</ElButton>
|
||||||
|
<ElButton type="primary" data-testid="close-submit" :loading="commandBusy" @click="submitClose">
|
||||||
|
{{ commandBusy ? t("alarm.actions.submitting") : t("alarm.closeDialog.submit") }}
|
||||||
|
</ElButton>
|
||||||
|
</template>
|
||||||
|
</ElDialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,362 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
/**
|
||||||
|
* Alarm list. Filters stay local until 查询. Sort and page are server-side.
|
||||||
|
* Boundary: no severity filter or column (D39). Empty copy distinguishes no
|
||||||
|
* alarms, no match, and no handling subject. Row action is 打开 only.
|
||||||
|
* Depends on the alarm list API and the signed-in subject.
|
||||||
|
*/
|
||||||
|
import { computed, onMounted, reactive, ref } from "vue";
|
||||||
|
import { useI18n } from "vue-i18n";
|
||||||
|
import { useRouter } from "vue-router";
|
||||||
|
import {
|
||||||
|
ElAlert,
|
||||||
|
ElButton,
|
||||||
|
ElDatePicker,
|
||||||
|
ElInput,
|
||||||
|
ElOption,
|
||||||
|
ElPagination,
|
||||||
|
ElSelect,
|
||||||
|
ElTable,
|
||||||
|
ElTableColumn,
|
||||||
|
ElTag,
|
||||||
|
vLoading,
|
||||||
|
} from "element-plus";
|
||||||
|
import { LIST_DEFAULT_PAGE_SIZE, LIST_PAGE_SIZES, actionsColumnWidth } from "../tableLayout";
|
||||||
|
import { useAuthStore } from "../stores/auth";
|
||||||
|
import { ALARM_PERMISSION, alarmListEmptyKind, hasAlarmSubject } from "./actions";
|
||||||
|
import { listAlarms } from "./client";
|
||||||
|
import { describeAlarmError, isAlarmForbidden } from "./errors";
|
||||||
|
import {
|
||||||
|
alarmFilterIssue,
|
||||||
|
alarmFiltersActive,
|
||||||
|
alarmListParams,
|
||||||
|
emptyAlarmFilters,
|
||||||
|
type AlarmFilterDraft,
|
||||||
|
} from "./filters";
|
||||||
|
import { formatDateTime } from "./format";
|
||||||
|
import type { AlarmRecord } from "./types";
|
||||||
|
|
||||||
|
const { t, te } = useI18n();
|
||||||
|
const router = useRouter();
|
||||||
|
const auth = useAuthStore();
|
||||||
|
|
||||||
|
const items = ref<AlarmRecord[]>([]);
|
||||||
|
const total = ref(0);
|
||||||
|
const phase = ref<"loading" | "ready" | "error" | "forbidden">("loading");
|
||||||
|
const loadError = ref("");
|
||||||
|
const filterIssue = ref<"object" | "time-order" | null>(null);
|
||||||
|
|
||||||
|
const draft = reactive<AlarmFilterDraft>(emptyAlarmFilters());
|
||||||
|
const applied = reactive<AlarmFilterDraft>(emptyAlarmFilters());
|
||||||
|
|
||||||
|
const page = ref(1);
|
||||||
|
const pageSize = ref(LIST_DEFAULT_PAGE_SIZE);
|
||||||
|
const sortBy = ref("last_occurred_at");
|
||||||
|
const sortOrder = ref<"asc" | "desc">("desc");
|
||||||
|
const actionsWidth = actionsColumnWidth(1);
|
||||||
|
|
||||||
|
const hasSubject = computed(() => hasAlarmSubject(auth.user?.subject));
|
||||||
|
const hasFilters = computed(() => alarmFiltersActive(applied));
|
||||||
|
const emptyKind = computed(() =>
|
||||||
|
alarmListEmptyKind({
|
||||||
|
phase: phase.value,
|
||||||
|
total: total.value,
|
||||||
|
hasSubject: hasSubject.value,
|
||||||
|
hasFilters: hasFilters.value,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const showTable = computed(() => phase.value === "loading" || (phase.value === "ready" && total.value > 0));
|
||||||
|
const showPager = computed(
|
||||||
|
() => emptyKind.value === "none" && (phase.value === "loading" || total.value > 0),
|
||||||
|
);
|
||||||
|
|
||||||
|
function copyFilters(target: AlarmFilterDraft, source: AlarmFilterDraft): void {
|
||||||
|
target.moduleKey = source.moduleKey;
|
||||||
|
target.scenarioName = source.scenarioName;
|
||||||
|
target.objectId = source.objectId;
|
||||||
|
target.status = source.status;
|
||||||
|
target.from = source.from;
|
||||||
|
target.to = source.to;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load(): Promise<void> {
|
||||||
|
phase.value = "loading";
|
||||||
|
loadError.value = "";
|
||||||
|
try {
|
||||||
|
const result = await listAlarms(
|
||||||
|
alarmListParams(applied, {
|
||||||
|
sortBy: sortBy.value,
|
||||||
|
sortOrder: sortOrder.value,
|
||||||
|
page: page.value,
|
||||||
|
pageSize: pageSize.value,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
items.value = result.items;
|
||||||
|
total.value = result.total;
|
||||||
|
phase.value = "ready";
|
||||||
|
} catch (error) {
|
||||||
|
items.value = [];
|
||||||
|
total.value = 0;
|
||||||
|
if (isAlarmForbidden(error)) {
|
||||||
|
phase.value = "forbidden";
|
||||||
|
loadError.value = describeAlarmError(error, t, te, "alarm.list.loadFailed", ALARM_PERMISSION.read);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
phase.value = "error";
|
||||||
|
loadError.value = describeAlarmError(error, t, te, "alarm.list.loadFailed", ALARM_PERMISSION.read);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyFilters(): void {
|
||||||
|
const issue = alarmFilterIssue(draft);
|
||||||
|
filterIssue.value = issue;
|
||||||
|
if (issue) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
copyFilters(applied, draft);
|
||||||
|
page.value = 1;
|
||||||
|
void load();
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetFilters(): void {
|
||||||
|
const blank = emptyAlarmFilters();
|
||||||
|
copyFilters(draft, blank);
|
||||||
|
copyFilters(applied, blank);
|
||||||
|
filterIssue.value = null;
|
||||||
|
page.value = 1;
|
||||||
|
void load();
|
||||||
|
}
|
||||||
|
|
||||||
|
function onSortChange(payload: { prop: string | null; order: string | null }): void {
|
||||||
|
const sortable = new Set(["module_key", "scenario_name", "last_occurred_at", "status"]);
|
||||||
|
if (!payload.prop || !payload.order || !sortable.has(payload.prop)) {
|
||||||
|
sortBy.value = "last_occurred_at";
|
||||||
|
sortOrder.value = "desc";
|
||||||
|
} else {
|
||||||
|
sortBy.value = payload.prop;
|
||||||
|
sortOrder.value = payload.order === "ascending" ? "asc" : "desc";
|
||||||
|
}
|
||||||
|
page.value = 1;
|
||||||
|
void load();
|
||||||
|
}
|
||||||
|
|
||||||
|
function onPageChange(next: number): void {
|
||||||
|
page.value = next;
|
||||||
|
void load();
|
||||||
|
}
|
||||||
|
|
||||||
|
function onSizeChange(next: number): void {
|
||||||
|
pageSize.value = next;
|
||||||
|
page.value = 1;
|
||||||
|
void load();
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusText(status: string): string {
|
||||||
|
const key = `alarm.status.${status}`;
|
||||||
|
return te(key) ? t(key) : status;
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusTag(status: string): "warning" | "primary" | "info" {
|
||||||
|
if (status === "pending") {
|
||||||
|
return "warning";
|
||||||
|
}
|
||||||
|
if (status === "processing") {
|
||||||
|
return "primary";
|
||||||
|
}
|
||||||
|
return "info";
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeResultText(value: string | null): string {
|
||||||
|
if (!value) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
const key = `alarm.closeResult.${value}`;
|
||||||
|
return te(key) ? t(key) : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function openDetail(source: unknown): void {
|
||||||
|
const row = source as AlarmRecord;
|
||||||
|
void router.push({ name: "alarm-detail", params: { id: row.id } });
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
void load();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex h-full min-h-0 flex-col overflow-hidden" data-testid="alarm-list">
|
||||||
|
<div class="flex shrink-0 flex-wrap items-center gap-2 px-5 pb-3 pt-5" data-testid="alarm-list-toolbar">
|
||||||
|
<div class="w-[140px]" data-testid="alarm-filter-module">
|
||||||
|
<ElInput v-model="draft.moduleKey" clearable :placeholder="t('alarm.list.filterModule')" />
|
||||||
|
</div>
|
||||||
|
<div class="w-[180px]" data-testid="alarm-filter-scenario">
|
||||||
|
<ElInput v-model="draft.scenarioName" clearable :placeholder="t('alarm.list.filterScenario')" />
|
||||||
|
</div>
|
||||||
|
<div class="w-[220px]" data-testid="alarm-filter-object">
|
||||||
|
<ElInput v-model="draft.objectId" clearable :placeholder="t('alarm.list.filterObject')" />
|
||||||
|
</div>
|
||||||
|
<div class="w-[200px]" data-testid="alarm-filter-from">
|
||||||
|
<ElDatePicker
|
||||||
|
v-model="draft.from"
|
||||||
|
style="width: 100%"
|
||||||
|
type="datetime"
|
||||||
|
:placeholder="t('alarm.list.filterFrom')"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="w-[200px]" data-testid="alarm-filter-to">
|
||||||
|
<ElDatePicker
|
||||||
|
v-model="draft.to"
|
||||||
|
style="width: 100%"
|
||||||
|
type="datetime"
|
||||||
|
:placeholder="t('alarm.list.filterTo')"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="w-[120px]" data-testid="alarm-filter-status">
|
||||||
|
<ElSelect v-model="draft.status" clearable class="w-full" :placeholder="t('alarm.list.filterStatus')">
|
||||||
|
<ElOption :label="t('alarm.status.pending')" value="pending" />
|
||||||
|
<ElOption :label="t('alarm.status.processing')" value="processing" />
|
||||||
|
<ElOption :label="t('alarm.status.closed')" value="closed" />
|
||||||
|
</ElSelect>
|
||||||
|
</div>
|
||||||
|
<ElButton type="primary" data-testid="alarm-filter-search" @click="applyFilters">
|
||||||
|
{{ t("alarm.list.filterSearch") }}
|
||||||
|
</ElButton>
|
||||||
|
<ElButton data-testid="alarm-filter-reset" @click="resetFilters">
|
||||||
|
{{ t("alarm.list.filterReset") }}
|
||||||
|
</ElButton>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex min-h-0 flex-1 flex-col px-5">
|
||||||
|
<ElAlert
|
||||||
|
v-if="filterIssue"
|
||||||
|
class="mb-3"
|
||||||
|
type="warning"
|
||||||
|
data-testid="alarm-filter-issue"
|
||||||
|
:title="filterIssue === 'object' ? t('alarm.list.objectInvalid') : t('alarm.list.timeOrder')"
|
||||||
|
show-icon
|
||||||
|
:closable="false"
|
||||||
|
/>
|
||||||
|
<ElAlert
|
||||||
|
v-if="phase === 'error'"
|
||||||
|
type="error"
|
||||||
|
data-testid="alarm-load-error"
|
||||||
|
:title="loadError"
|
||||||
|
show-icon
|
||||||
|
:closable="false"
|
||||||
|
/>
|
||||||
|
<div v-if="phase === 'error'" class="mt-3">
|
||||||
|
<ElButton data-testid="alarm-retry" @click="load">{{ t("alarm.list.retry") }}</ElButton>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-else-if="phase === 'forbidden'"
|
||||||
|
data-testid="alarm-forbidden"
|
||||||
|
class="flex flex-1 items-center justify-center rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("alarm.list.forbidden") }}</h3>
|
||||||
|
<p class="text-[var(--text-secondary)]">{{ loadError }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-else-if="emptyKind === 'no-scope'"
|
||||||
|
data-testid="alarm-no-scope"
|
||||||
|
class="flex flex-1 items-center justify-center rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("alarm.list.noScope") }}</h3>
|
||||||
|
<p class="text-[var(--text-secondary)]">{{ t("alarm.list.noScopeHint") }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-else-if="emptyKind === 'empty'"
|
||||||
|
data-testid="alarm-empty"
|
||||||
|
class="flex flex-1 items-center justify-center rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("alarm.list.empty") }}</h3>
|
||||||
|
<p class="text-[var(--text-secondary)]">{{ t("alarm.list.emptyHint") }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-else-if="emptyKind === 'no-match'"
|
||||||
|
data-testid="alarm-no-match"
|
||||||
|
class="flex flex-1 items-center justify-center rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("alarm.list.noMatch") }}</h3>
|
||||||
|
<p class="text-[var(--text-secondary)]">{{ t("alarm.list.noMatchHint") }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="showTable" class="min-h-0 flex-1" data-testid="alarm-table-wrap">
|
||||||
|
<ElTable
|
||||||
|
v-loading="phase === 'loading'"
|
||||||
|
height="100%"
|
||||||
|
:data="items"
|
||||||
|
row-key="id"
|
||||||
|
data-testid="alarm-table"
|
||||||
|
:default-sort="{ prop: 'last_occurred_at', order: 'descending' }"
|
||||||
|
@sort-change="onSortChange"
|
||||||
|
>
|
||||||
|
<ElTableColumn
|
||||||
|
prop="module_key"
|
||||||
|
:label="t('alarm.columns.module')"
|
||||||
|
min-width="120"
|
||||||
|
sortable="custom"
|
||||||
|
/>
|
||||||
|
<ElTableColumn
|
||||||
|
prop="scenario_name"
|
||||||
|
:label="t('alarm.columns.scenario')"
|
||||||
|
min-width="160"
|
||||||
|
sortable="custom"
|
||||||
|
/>
|
||||||
|
<ElTableColumn prop="identity_key" :label="t('alarm.columns.object')" min-width="140" />
|
||||||
|
<ElTableColumn
|
||||||
|
prop="last_occurred_at"
|
||||||
|
:label="t('alarm.columns.lastOccurred')"
|
||||||
|
min-width="160"
|
||||||
|
sortable="custom"
|
||||||
|
>
|
||||||
|
<template #default="{ row }">{{ formatDateTime(row.last_occurred_at) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn prop="status" :label="t('alarm.columns.status')" min-width="140" sortable="custom">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<ElTag :type="statusTag(row.status)" effect="light" data-testid="alarm-status">
|
||||||
|
{{ statusText(row.status) }}
|
||||||
|
</ElTag>
|
||||||
|
<span v-if="row.status === 'closed' && row.close_result">
|
||||||
|
{{ t("alarm.list.resultSep") }}{{ closeResultText(row.close_result) }}
|
||||||
|
</span>
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('alarm.columns.actions')" :width="actionsWidth" align="right" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div class="whitespace-nowrap" :data-testid="`alarm-row-${row.id}`">
|
||||||
|
<ElButton link type="primary" data-testid="alarm-open" @click="openDetail(row)">
|
||||||
|
{{ t("alarm.actions.open") }}
|
||||||
|
</ElButton>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
</ElTable>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<footer
|
||||||
|
v-if="showPager"
|
||||||
|
data-testid="alarm-pagination"
|
||||||
|
class="flex shrink-0 items-center justify-end border-t border-[var(--border-subtle)] bg-white px-5 py-3"
|
||||||
|
>
|
||||||
|
<ElPagination
|
||||||
|
background
|
||||||
|
layout="total, sizes, prev, pager, next"
|
||||||
|
:total="total"
|
||||||
|
:page-size="pageSize"
|
||||||
|
:page-sizes="[...LIST_PAGE_SIZES]"
|
||||||
|
:current-page="page"
|
||||||
|
@current-change="onPageChange"
|
||||||
|
@size-change="onSizeChange"
|
||||||
|
/>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
/**
|
||||||
|
* Command visibility, empty-state choice, and idempotency reuse.
|
||||||
|
* Covers D39: viewer hides commands, admin cannot steal a handler or write for them.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import {
|
||||||
|
alarmCommandVisibility,
|
||||||
|
alarmListEmptyKind,
|
||||||
|
clearIdempotencyKey,
|
||||||
|
hasAlarmSubject,
|
||||||
|
holdIdempotencyKey,
|
||||||
|
} from "./actions";
|
||||||
|
|
||||||
|
const admin = ["watchman-admin"];
|
||||||
|
const operator = ["watchman-operator"];
|
||||||
|
const viewer = ["watchman-viewer"];
|
||||||
|
|
||||||
|
describe("alarm command visibility", () => {
|
||||||
|
it("hides every command from a viewer, including a pending alarm", () => {
|
||||||
|
expect(
|
||||||
|
alarmCommandVisibility({
|
||||||
|
roles: viewer,
|
||||||
|
subject: "subj-chen",
|
||||||
|
status: "pending",
|
||||||
|
currentHandler: null,
|
||||||
|
}),
|
||||||
|
).toEqual({ claim: false, progress: false, close: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lets an operator claim a pending alarm and nothing else", () => {
|
||||||
|
expect(
|
||||||
|
alarmCommandVisibility({
|
||||||
|
roles: operator,
|
||||||
|
subject: "subj-chen",
|
||||||
|
status: "pending",
|
||||||
|
currentHandler: null,
|
||||||
|
}),
|
||||||
|
).toEqual({ claim: true, progress: false, close: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lets the current handler add progress and close, and hides claim", () => {
|
||||||
|
expect(
|
||||||
|
alarmCommandVisibility({
|
||||||
|
roles: operator,
|
||||||
|
subject: "subj-chen",
|
||||||
|
status: "processing",
|
||||||
|
currentHandler: "subj-chen",
|
||||||
|
}),
|
||||||
|
).toEqual({ claim: false, progress: true, close: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("hides claim, progress, and close when someone else is the handler", () => {
|
||||||
|
expect(
|
||||||
|
alarmCommandVisibility({
|
||||||
|
roles: operator,
|
||||||
|
subject: "subj-zhao",
|
||||||
|
status: "processing",
|
||||||
|
currentHandler: "subj-lin",
|
||||||
|
}),
|
||||||
|
).toEqual({ claim: false, progress: false, close: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lets an admin close another handler's alarm without taking it or writing progress", () => {
|
||||||
|
expect(
|
||||||
|
alarmCommandVisibility({
|
||||||
|
roles: admin,
|
||||||
|
subject: "subj-chen",
|
||||||
|
status: "processing",
|
||||||
|
currentHandler: "subj-lin",
|
||||||
|
}),
|
||||||
|
).toEqual({ claim: false, progress: false, close: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lets an admin who is the handler write progress and close", () => {
|
||||||
|
expect(
|
||||||
|
alarmCommandVisibility({
|
||||||
|
roles: [...admin, ...viewer],
|
||||||
|
subject: "subj-chen",
|
||||||
|
status: "processing",
|
||||||
|
currentHandler: "subj-chen",
|
||||||
|
}),
|
||||||
|
).toEqual({ claim: false, progress: true, close: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves only the back action after close, including for an admin", () => {
|
||||||
|
expect(
|
||||||
|
alarmCommandVisibility({
|
||||||
|
roles: admin,
|
||||||
|
subject: "subj-chen",
|
||||||
|
status: "closed",
|
||||||
|
currentHandler: "subj-lin",
|
||||||
|
}),
|
||||||
|
).toEqual({ claim: false, progress: false, close: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("hides commands when the session has no handling subject", () => {
|
||||||
|
expect(hasAlarmSubject(" ")).toBe(false);
|
||||||
|
expect(hasAlarmSubject("a\nb")).toBe(false);
|
||||||
|
expect(hasAlarmSubject("subj-chen")).toBe(true);
|
||||||
|
expect(
|
||||||
|
alarmCommandVisibility({
|
||||||
|
roles: admin,
|
||||||
|
subject: "",
|
||||||
|
status: "processing",
|
||||||
|
currentHandler: "subj-lin",
|
||||||
|
}),
|
||||||
|
).toEqual({ claim: false, progress: false, close: false });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("alarm list empty kind", () => {
|
||||||
|
it("uses no-scope before the other empty copies", () => {
|
||||||
|
expect(
|
||||||
|
alarmListEmptyKind({ phase: "ready", total: 0, hasSubject: false, hasFilters: true }),
|
||||||
|
).toBe("no-scope");
|
||||||
|
expect(
|
||||||
|
alarmListEmptyKind({ phase: "ready", total: 3, hasSubject: false, hasFilters: false }),
|
||||||
|
).toBe("no-scope");
|
||||||
|
expect(
|
||||||
|
alarmListEmptyKind({ phase: "ready", total: 0, hasSubject: true, hasFilters: false }),
|
||||||
|
).toBe("empty");
|
||||||
|
expect(
|
||||||
|
alarmListEmptyKind({ phase: "ready", total: 0, hasSubject: true, hasFilters: true }),
|
||||||
|
).toBe("no-match");
|
||||||
|
expect(
|
||||||
|
alarmListEmptyKind({ phase: "ready", total: 2, hasSubject: true, hasFilters: false }),
|
||||||
|
).toBe("none");
|
||||||
|
expect(
|
||||||
|
alarmListEmptyKind({ phase: "forbidden", total: 0, hasSubject: false, hasFilters: false }),
|
||||||
|
).toBe("none");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("idempotency hold", () => {
|
||||||
|
it("reuses the key until the payload changes", () => {
|
||||||
|
const first = holdIdempotencyKey(clearIdempotencyKey(), "note-a", () => "k1");
|
||||||
|
const again = holdIdempotencyKey(first, "note-a", () => "k2");
|
||||||
|
const edited = holdIdempotencyKey(again, "note-b", () => "k3");
|
||||||
|
expect(again).toEqual({ key: "k1", payload: "note-a" });
|
||||||
|
expect(edited).toEqual({ key: "k3", payload: "note-b" });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
/**
|
||||||
|
* Which handling buttons the signed-in role may see.
|
||||||
|
* Boundary: presentation only. The API still accepts or rejects the command.
|
||||||
|
* Depends on the session role, the snapshot subject, and the alarm status.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const ALARM_PERMISSION = {
|
||||||
|
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",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const ROLE_ADMIN = "watchman-admin";
|
||||||
|
const ROLE_OPERATOR = "watchman-operator";
|
||||||
|
|
||||||
|
export type AlarmCommandVisibility = {
|
||||||
|
claim: boolean;
|
||||||
|
progress: boolean;
|
||||||
|
close: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const HIDDEN: AlarmCommandVisibility = { claim: false, progress: false, close: false };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A blank subject has no handling scope. Newlines match the read API, which
|
||||||
|
* treats that session as having no subject. This does not grant access.
|
||||||
|
*/
|
||||||
|
export function hasAlarmSubject(subject: string | null | undefined): boolean {
|
||||||
|
if (typeof subject !== "string") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const cleaned = subject.trim();
|
||||||
|
if (!cleaned || /[\r\n\u0000]/.test(cleaned)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hide commands the role cannot complete.
|
||||||
|
* A viewer never sees claim, progress, or close.
|
||||||
|
* An admin may close another person's alarm, but cannot take over the handler
|
||||||
|
* or write progress for them. A closed alarm has no command buttons.
|
||||||
|
*/
|
||||||
|
export function alarmCommandVisibility(input: {
|
||||||
|
roles: readonly string[];
|
||||||
|
subject: string | null | undefined;
|
||||||
|
status: string;
|
||||||
|
currentHandler: string | null;
|
||||||
|
}): AlarmCommandVisibility {
|
||||||
|
if (!hasAlarmSubject(input.subject)) {
|
||||||
|
return HIDDEN;
|
||||||
|
}
|
||||||
|
const admin = input.roles.includes(ROLE_ADMIN);
|
||||||
|
const operator = input.roles.includes(ROLE_OPERATOR);
|
||||||
|
if (!admin && !operator) {
|
||||||
|
return HIDDEN;
|
||||||
|
}
|
||||||
|
const subject = input.subject!.trim();
|
||||||
|
const self = input.currentHandler !== null && input.currentHandler === subject;
|
||||||
|
if (input.status === "pending") {
|
||||||
|
return { claim: true, progress: false, close: false };
|
||||||
|
}
|
||||||
|
if (input.status === "processing") {
|
||||||
|
return { claim: false, progress: self, close: admin || self };
|
||||||
|
}
|
||||||
|
return HIDDEN;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AlarmListPhase = "loading" | "ready" | "error" | "forbidden";
|
||||||
|
export type AlarmListEmptyKind = "none" | "no-scope" | "empty" | "no-match";
|
||||||
|
|
||||||
|
/** Pick the empty copy. No subject wins over rows, "no alarms", and "no match". */
|
||||||
|
export function alarmListEmptyKind(input: {
|
||||||
|
phase: AlarmListPhase;
|
||||||
|
total: number;
|
||||||
|
hasSubject: boolean;
|
||||||
|
hasFilters: boolean;
|
||||||
|
}): AlarmListEmptyKind {
|
||||||
|
if (input.phase !== "ready") {
|
||||||
|
return "none";
|
||||||
|
}
|
||||||
|
if (!input.hasSubject) {
|
||||||
|
return "no-scope";
|
||||||
|
}
|
||||||
|
if (input.total > 0) {
|
||||||
|
return "none";
|
||||||
|
}
|
||||||
|
if (input.hasFilters) {
|
||||||
|
return "no-match";
|
||||||
|
}
|
||||||
|
return "empty";
|
||||||
|
}
|
||||||
|
|
||||||
|
export type IdempotencyHold = { key: string; payload: string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reuse the key while the payload is unchanged so a retry does not append a
|
||||||
|
* second progress note when the first response was lost.
|
||||||
|
*/
|
||||||
|
export function holdIdempotencyKey(
|
||||||
|
hold: IdempotencyHold,
|
||||||
|
payload: string,
|
||||||
|
makeKey: () => string,
|
||||||
|
): IdempotencyHold {
|
||||||
|
if (hold.key !== "" && hold.payload === payload) {
|
||||||
|
return hold;
|
||||||
|
}
|
||||||
|
return { key: makeKey(), payload };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearIdempotencyKey(): IdempotencyHold {
|
||||||
|
return { key: "", payload: "" };
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
/**
|
||||||
|
* Alarm HTTP calls. Reads are GET. Commands send x-idempotency-key and a JSON body.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
vi.mock("@watchman/api", async () => {
|
||||||
|
const actual = await vi.importActual<typeof import("@watchman/api")>("@watchman/api");
|
||||||
|
return { ...actual, requestJson: vi.fn() };
|
||||||
|
});
|
||||||
|
|
||||||
|
import { requestJson } from "@watchman/api";
|
||||||
|
import { appendProgress, claimAlarm, closeAlarm, getAlarm, listAlarms, listHistory } from "./client";
|
||||||
|
import { alarmListParams, emptyAlarmFilters } from "./filters";
|
||||||
|
|
||||||
|
const mocked = vi.mocked(requestJson);
|
||||||
|
|
||||||
|
function lastCall(): { url: string; init: RequestInit } {
|
||||||
|
const call = mocked.mock.calls[mocked.mock.calls.length - 1];
|
||||||
|
return { url: String(call[0]), init: (call[1] ?? {}) as RequestInit };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("alarm client", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
mocked.mockReset();
|
||||||
|
mocked.mockResolvedValue({});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lists and reads under /alarms", async () => {
|
||||||
|
await listAlarms(
|
||||||
|
alarmListParams(emptyAlarmFilters(), {
|
||||||
|
sortBy: "last_occurred_at",
|
||||||
|
sortOrder: "desc",
|
||||||
|
page: 1,
|
||||||
|
pageSize: 20,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(lastCall().url).toContain("/alarms?");
|
||||||
|
expect(lastCall().init.method).toBeUndefined();
|
||||||
|
await getAlarm("alarm id");
|
||||||
|
expect(lastCall().url).toBe("/alarms/alarm%20id");
|
||||||
|
await listHistory("a1");
|
||||||
|
expect(lastCall().url).toBe("/alarms/a1/history");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends the idempotency key and does not put a handler on the command body", async () => {
|
||||||
|
await claimAlarm("a1", "key-1");
|
||||||
|
const claim = lastCall();
|
||||||
|
expect(claim.url).toBe("/alarms/a1/claim");
|
||||||
|
expect(claim.init.method).toBe("POST");
|
||||||
|
expect(new Headers(claim.init.headers).get("x-idempotency-key")).toBe("key-1");
|
||||||
|
expect(JSON.parse(String(claim.init.body))).toEqual({});
|
||||||
|
|
||||||
|
await appendProgress("a1", "key-2", { note: "checked" });
|
||||||
|
expect(JSON.parse(String(lastCall().init.body))).toEqual({ note: "checked" });
|
||||||
|
|
||||||
|
await closeAlarm("a1", "key-3", { result: "resolved", note: "done" });
|
||||||
|
const close = lastCall();
|
||||||
|
expect(close.url).toBe("/alarms/a1/close");
|
||||||
|
expect(JSON.parse(String(close.init.body))).toEqual({ result: "resolved", note: "done" });
|
||||||
|
expect(String(close.init.body)).not.toContain("current_handler");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
/**
|
||||||
|
* Alarm list, detail, and the three handling commands.
|
||||||
|
* Boundary: unwraps the success envelope. It does not decide who may press a button.
|
||||||
|
* Depends on the console session client and the /alarms routes.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { api } from "../api";
|
||||||
|
import { alarmListQuery, type AlarmListParams } from "./filters";
|
||||||
|
import type {
|
||||||
|
AlarmList,
|
||||||
|
AlarmRecord,
|
||||||
|
CommandResult,
|
||||||
|
EvidenceBundle,
|
||||||
|
HistoryList,
|
||||||
|
OccurrenceList,
|
||||||
|
} from "./types";
|
||||||
|
|
||||||
|
const JSON_HEADERS = { "Content-Type": "application/json" };
|
||||||
|
|
||||||
|
function base(id: string): string {
|
||||||
|
return `/alarms/${encodeURIComponent(id)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function commandInit(idempotencyKey: string, body: unknown): RequestInit {
|
||||||
|
return {
|
||||||
|
method: "POST",
|
||||||
|
headers: { ...JSON_HEADERS, "x-idempotency-key": idempotencyKey },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listAlarms(params: AlarmListParams): Promise<AlarmList> {
|
||||||
|
return api<AlarmList>(`/alarms${alarmListQuery(params)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAlarm(id: string): Promise<AlarmRecord> {
|
||||||
|
return api<AlarmRecord>(base(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listOccurrences(id: string): Promise<OccurrenceList> {
|
||||||
|
return api<OccurrenceList>(`${base(id)}/occurrences`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listEvidence(id: string): Promise<EvidenceBundle> {
|
||||||
|
return api<EvidenceBundle>(`${base(id)}/evidence`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listHistory(id: string): Promise<HistoryList> {
|
||||||
|
return api<HistoryList>(`${base(id)}/history`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function claimAlarm(id: string, idempotencyKey: string): Promise<CommandResult> {
|
||||||
|
return api<CommandResult>(`${base(id)}/claim`, commandInit(idempotencyKey, {}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function appendProgress(
|
||||||
|
id: string,
|
||||||
|
idempotencyKey: string,
|
||||||
|
body: { note: string; evidence_ref?: string },
|
||||||
|
): Promise<CommandResult> {
|
||||||
|
return api<CommandResult>(`${base(id)}/progress`, commandInit(idempotencyKey, body));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function closeAlarm(
|
||||||
|
id: string,
|
||||||
|
idempotencyKey: string,
|
||||||
|
body: { result: string; note: string; evidence_ref?: string },
|
||||||
|
): Promise<CommandResult> {
|
||||||
|
return api<CommandResult>(`${base(id)}/close`, commandInit(idempotencyKey, body));
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
/**
|
||||||
|
* Envelope errors stay on stable reasons. Server message text must not surface.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { BusinessError } from "@watchman/api";
|
||||||
|
import { describeAlarmError, isAlarmConflict, isAlarmNotFound } from "./errors";
|
||||||
|
|
||||||
|
const MESSAGES: Record<string, string> = {
|
||||||
|
"alarm.errors.already_claimed": "已经有处理人",
|
||||||
|
"alarm.errors.forbidden": "没有权限({node})",
|
||||||
|
"alarm.errors.forbiddenPlain": "没有权限完成这个操作",
|
||||||
|
"codes.40000": "参数错误",
|
||||||
|
"codes.42000": "权限不足",
|
||||||
|
"alarm.list.loadFailed": "报警列表加载失败",
|
||||||
|
};
|
||||||
|
const t = (key: string, named?: Record<string, unknown>) => {
|
||||||
|
const template = MESSAGES[key] ?? key;
|
||||||
|
if (!named) {
|
||||||
|
return template;
|
||||||
|
}
|
||||||
|
return template.replace(/\{(\w+)\}/g, (_match, name: string) => String(named[name] ?? ""));
|
||||||
|
};
|
||||||
|
const te = (key: string) => key in MESSAGES;
|
||||||
|
|
||||||
|
function business(
|
||||||
|
code: number,
|
||||||
|
status: number,
|
||||||
|
details: Record<string, unknown> = {},
|
||||||
|
message = "SECRET server text",
|
||||||
|
): BusinessError {
|
||||||
|
return new BusinessError({ code, message, details, status, requestId: "r" });
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("describeAlarmError", () => {
|
||||||
|
it("uses the stable reason and hides the server message", () => {
|
||||||
|
const text = describeAlarmError(
|
||||||
|
business(40000, 409, { reason: "already_claimed" }),
|
||||||
|
t,
|
||||||
|
te,
|
||||||
|
"alarm.list.loadFailed",
|
||||||
|
);
|
||||||
|
expect(text).toBe("已经有处理人");
|
||||||
|
expect(text).not.toContain("SECRET");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows the permission node we already know, not the server message", () => {
|
||||||
|
const text = describeAlarmError(
|
||||||
|
business(42000, 403, {}, "raw denial"),
|
||||||
|
t,
|
||||||
|
te,
|
||||||
|
"alarm.list.loadFailed",
|
||||||
|
"perm:data:emp:watchman.alarm.take",
|
||||||
|
);
|
||||||
|
expect(text).toBe("没有权限(perm:data:emp:watchman.alarm.take)");
|
||||||
|
expect(text).not.toContain("raw denial");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to the numeric code, then to the fallback, without the thrown text", () => {
|
||||||
|
expect(describeAlarmError(business(40000, 400, { reason: "unheard" }), t, te, "alarm.list.loadFailed")).toBe(
|
||||||
|
"参数错误 (40000)",
|
||||||
|
);
|
||||||
|
expect(describeAlarmError(business(50000, 500), t, te, "alarm.list.loadFailed")).toBe(
|
||||||
|
"报警列表加载失败 (50000)",
|
||||||
|
);
|
||||||
|
expect(describeAlarmError(new Error("SECRET network"), t, te, "alarm.list.loadFailed")).toBe(
|
||||||
|
"报警列表加载失败",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("alarm error status", () => {
|
||||||
|
it("treats HTTP 404 as not found and HTTP 409 as conflict", () => {
|
||||||
|
expect(isAlarmNotFound(business(40000, 404, { reason: "not_found" }))).toBe(true);
|
||||||
|
expect(isAlarmNotFound(business(40000, 400))).toBe(false);
|
||||||
|
expect(isAlarmConflict(business(40000, 409, { reason: "already_claimed" }))).toBe(true);
|
||||||
|
expect(isAlarmConflict(business(40000, 400))).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
/**
|
||||||
|
* Alarm API failures as fixed copy. The server message is never shown.
|
||||||
|
* Boundary: reason codes and the numeric envelope code only.
|
||||||
|
* Depends on BusinessError from the shared API client.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { BusinessError } from "@watchman/api";
|
||||||
|
|
||||||
|
type Translate = (key: string, named?: Record<string, unknown>) => string;
|
||||||
|
type Exists = (key: string) => boolean;
|
||||||
|
|
||||||
|
export function describeAlarmError(
|
||||||
|
error: unknown,
|
||||||
|
t: Translate,
|
||||||
|
te: Exists,
|
||||||
|
fallbackKey: string,
|
||||||
|
permissionNode?: string,
|
||||||
|
): string {
|
||||||
|
if (!(error instanceof BusinessError)) {
|
||||||
|
return t(fallbackKey);
|
||||||
|
}
|
||||||
|
if (error.status === 403 || error.code === 42000) {
|
||||||
|
if (permissionNode) {
|
||||||
|
return t("alarm.errors.forbidden", { node: permissionNode });
|
||||||
|
}
|
||||||
|
return t("alarm.errors.forbiddenPlain");
|
||||||
|
}
|
||||||
|
const reason = error.details.reason;
|
||||||
|
if (typeof reason === "string" && te(`alarm.errors.${reason}`)) {
|
||||||
|
return t(`alarm.errors.${reason}`);
|
||||||
|
}
|
||||||
|
if (te(`codes.${error.code}`)) {
|
||||||
|
return `${t(`codes.${error.code}`)} (${error.code})`;
|
||||||
|
}
|
||||||
|
return `${t(fallbackKey)} (${error.code})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isAlarmNotFound(error: unknown): boolean {
|
||||||
|
return error instanceof BusinessError && error.status === 404;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isAlarmConflict(error: unknown): boolean {
|
||||||
|
return error instanceof BusinessError && error.status === 409;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isAlarmForbidden(error: unknown): boolean {
|
||||||
|
return error instanceof BusinessError && (error.status === 403 || error.code === 42000);
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
/**
|
||||||
|
* Filter drafts stay local until they become a server query.
|
||||||
|
* Covers: no severity param, timezone on time filters, invalid object id blocked.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import {
|
||||||
|
alarmFilterIssue,
|
||||||
|
alarmFiltersActive,
|
||||||
|
alarmListParams,
|
||||||
|
alarmListQuery,
|
||||||
|
emptyAlarmFilters,
|
||||||
|
} from "./filters";
|
||||||
|
|
||||||
|
const query = { sortBy: "last_occurred_at", sortOrder: "desc" as const, page: 1, pageSize: 20 };
|
||||||
|
|
||||||
|
describe("alarm list filters", () => {
|
||||||
|
it("omits empty filters and never sends a severity field", () => {
|
||||||
|
const params = alarmListParams(emptyAlarmFilters(), query);
|
||||||
|
const text = alarmListQuery(params);
|
||||||
|
expect(text).toContain("sort_by=last_occurred_at");
|
||||||
|
expect(text).toContain("sort_order=desc");
|
||||||
|
expect(text).toContain("page=1");
|
||||||
|
expect(text).toContain("page_size=20");
|
||||||
|
expect(text).not.toContain("module_key");
|
||||||
|
expect(text).not.toContain("severity");
|
||||||
|
expect(text).not.toContain("level");
|
||||||
|
expect(alarmFiltersActive(emptyAlarmFilters())).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends a timezone-aware range and the object id", () => {
|
||||||
|
const draft = {
|
||||||
|
...emptyAlarmFilters(),
|
||||||
|
moduleKey: " furnace ",
|
||||||
|
scenarioName: "炉温",
|
||||||
|
objectId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
|
||||||
|
status: "pending",
|
||||||
|
from: new Date("2026-11-18T01:00:00.000Z"),
|
||||||
|
to: new Date("2026-11-18T02:00:00.000Z"),
|
||||||
|
};
|
||||||
|
const text = alarmListQuery(alarmListParams(draft, { ...query, page: 2 }));
|
||||||
|
expect(text).toContain("module_key=furnace");
|
||||||
|
expect(text).toContain("scenario_name=");
|
||||||
|
expect(text).toContain("mapped_input_id=aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa");
|
||||||
|
expect(text).toContain("status=pending");
|
||||||
|
expect(text).toContain("occurred_from=2026-11-18T01%3A00%3A00.000Z");
|
||||||
|
expect(text).toContain("page=2");
|
||||||
|
expect(alarmFiltersActive(draft)).toBe(true);
|
||||||
|
expect(alarmFilterIssue(draft)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects an object id that is not a uuid and a reversed time range", () => {
|
||||||
|
expect(alarmFilterIssue({ ...emptyAlarmFilters(), objectId: "furnace-01" })).toBe("object");
|
||||||
|
expect(
|
||||||
|
alarmFilterIssue({
|
||||||
|
...emptyAlarmFilters(),
|
||||||
|
from: new Date("2026-11-18T02:00:00.000Z"),
|
||||||
|
to: new Date("2026-11-18T01:00:00.000Z"),
|
||||||
|
}),
|
||||||
|
).toBe("time-order");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
/**
|
||||||
|
* List filter draft turned into the alarm query string.
|
||||||
|
* Boundary: sends only supported query params, and only after 查询.
|
||||||
|
* Depends on the list route's page, sort, and filter names.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const OBJECT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
|
export type AlarmFilterDraft = {
|
||||||
|
moduleKey: string;
|
||||||
|
scenarioName: string;
|
||||||
|
objectId: string;
|
||||||
|
status: string;
|
||||||
|
from: Date | null;
|
||||||
|
to: Date | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AlarmFilterIssue = "object" | "time-order" | null;
|
||||||
|
|
||||||
|
export type AlarmListParams = {
|
||||||
|
module_key?: string;
|
||||||
|
scenario_name?: string;
|
||||||
|
mapped_input_id?: string;
|
||||||
|
status?: string;
|
||||||
|
occurred_from?: string;
|
||||||
|
occurred_to?: string;
|
||||||
|
sort_by: string;
|
||||||
|
sort_order: "asc" | "desc";
|
||||||
|
page: number;
|
||||||
|
page_size: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function emptyAlarmFilters(): AlarmFilterDraft {
|
||||||
|
return {
|
||||||
|
moduleKey: "",
|
||||||
|
scenarioName: "",
|
||||||
|
objectId: "",
|
||||||
|
status: "",
|
||||||
|
from: null,
|
||||||
|
to: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function alarmFiltersActive(draft: AlarmFilterDraft): boolean {
|
||||||
|
return (
|
||||||
|
draft.moduleKey.trim() !== "" ||
|
||||||
|
draft.scenarioName.trim() !== "" ||
|
||||||
|
draft.objectId.trim() !== "" ||
|
||||||
|
draft.status !== "" ||
|
||||||
|
draft.from !== null ||
|
||||||
|
draft.to !== null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Block a request the API would reject, without showing the server sentence. */
|
||||||
|
export function alarmFilterIssue(draft: AlarmFilterDraft): AlarmFilterIssue {
|
||||||
|
const objectId = draft.objectId.trim();
|
||||||
|
if (objectId !== "" && !OBJECT_ID.test(objectId)) {
|
||||||
|
return "object";
|
||||||
|
}
|
||||||
|
if (draft.from && draft.to && draft.from.getTime() > draft.to.getTime()) {
|
||||||
|
return "time-order";
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function alarmListParams(
|
||||||
|
draft: AlarmFilterDraft,
|
||||||
|
query: { sortBy: string; sortOrder: "asc" | "desc"; page: number; pageSize: number },
|
||||||
|
): AlarmListParams {
|
||||||
|
return {
|
||||||
|
module_key: draft.moduleKey.trim() || undefined,
|
||||||
|
scenario_name: draft.scenarioName.trim() || undefined,
|
||||||
|
mapped_input_id: draft.objectId.trim() || undefined,
|
||||||
|
status: draft.status || undefined,
|
||||||
|
occurred_from: draft.from ? draft.from.toISOString() : undefined,
|
||||||
|
occurred_to: draft.to ? draft.to.toISOString() : undefined,
|
||||||
|
sort_by: query.sortBy,
|
||||||
|
sort_order: query.sortOrder,
|
||||||
|
page: query.page,
|
||||||
|
page_size: query.pageSize,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function alarmListQuery(params: AlarmListParams): string {
|
||||||
|
const q = new URLSearchParams();
|
||||||
|
const set = (key: string, value: string | number | undefined) => {
|
||||||
|
if (value === undefined || value === "") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
q.set(key, String(value));
|
||||||
|
};
|
||||||
|
set("module_key", params.module_key);
|
||||||
|
set("scenario_name", params.scenario_name);
|
||||||
|
set("mapped_input_id", params.mapped_input_id);
|
||||||
|
set("status", params.status);
|
||||||
|
set("occurred_from", params.occurred_from);
|
||||||
|
set("occurred_to", params.occurred_to);
|
||||||
|
set("sort_by", params.sort_by);
|
||||||
|
set("sort_order", params.sort_order);
|
||||||
|
set("page", params.page);
|
||||||
|
set("page_size", params.page_size);
|
||||||
|
const text = q.toString();
|
||||||
|
return text ? `?${text}` : "";
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
/**
|
||||||
|
* Alarm timestamps for tables. Empty or invalid values stay blank.
|
||||||
|
* Boundary: display only. It does not parse filter input.
|
||||||
|
* Depends on the browser time zone.
|
||||||
|
*/
|
||||||
|
|
||||||
|
function pad(value: number): string {
|
||||||
|
return String(value).padStart(2, "0");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "2026-11-17 09:12" in the browser's time zone, or "" when unset or invalid. */
|
||||||
|
export function formatDateTime(iso: string | null | undefined): string {
|
||||||
|
if (!iso) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
const date = new Date(iso);
|
||||||
|
if (Number.isNaN(date.getTime())) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
/**
|
||||||
|
* Alarm copy is present in all four languages and does not say the alarm recovered.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import zhCN from "../../locales/zh-CN/common.json";
|
||||||
|
import zhTW from "../../locales/zh-TW/common.json";
|
||||||
|
import en from "../../locales/en/common.json";
|
||||||
|
import th from "../../locales/th/common.json";
|
||||||
|
|
||||||
|
function leafKeys(value: unknown, prefix = ""): string[] {
|
||||||
|
if (value === null || typeof value !== "object") {
|
||||||
|
return [prefix];
|
||||||
|
}
|
||||||
|
return Object.entries(value as Record<string, unknown>).flatMap(([key, child]) =>
|
||||||
|
leafKeys(child, prefix ? `${prefix}.${key}` : key),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function texts(value: unknown): string[] {
|
||||||
|
if (typeof value === "string") {
|
||||||
|
return [value];
|
||||||
|
}
|
||||||
|
if (value && typeof value === "object") {
|
||||||
|
return Object.values(value as Record<string, unknown>).flatMap(texts);
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const BANNED = ["已恢复", "已恢復", "recovered", "Recovered"];
|
||||||
|
|
||||||
|
describe("alarm locale keys", () => {
|
||||||
|
const base = leafKeys((zhCN as { alarm: unknown }).alarm).sort();
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
["zh-TW", zhTW],
|
||||||
|
["en", en],
|
||||||
|
["th", th],
|
||||||
|
])("%s has the same alarm keys as zh-CN", (_name, messages) => {
|
||||||
|
expect(leafKeys((messages as { alarm: unknown }).alarm).sort()).toEqual(base);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
["zh-CN", zhCN],
|
||||||
|
["zh-TW", zhTW],
|
||||||
|
["en", en],
|
||||||
|
["th", th],
|
||||||
|
])("%s fills every alarm string and does not say recovered", (_name, messages) => {
|
||||||
|
const alarm = (messages as { alarm: unknown }).alarm;
|
||||||
|
const nav = (messages as { nav: Record<string, string> }).nav;
|
||||||
|
expect(nav.alarms).toBeTruthy();
|
||||||
|
expect(texts(alarm).every((text) => text.trim() !== "")).toBe(true);
|
||||||
|
const joined = texts(alarm).join("\n");
|
||||||
|
for (const word of BANNED) {
|
||||||
|
expect(joined).not.toContain(word);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("names the handling reasons the page can show", () => {
|
||||||
|
for (const reason of [
|
||||||
|
"already_claimed",
|
||||||
|
"not_current_handler",
|
||||||
|
"illegal_transition",
|
||||||
|
"already_closed",
|
||||||
|
"idempotency_payload_mismatch",
|
||||||
|
"forbidden",
|
||||||
|
"forbiddenPlain",
|
||||||
|
]) {
|
||||||
|
expect(leafKeys(zhCN)).toContain(`alarm.errors.${reason}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
/**
|
||||||
|
* Alarm console types matched to the S3 read and command payloads.
|
||||||
|
* Boundary: fields the alarm API already returns. No severity, planned time, or rule text.
|
||||||
|
* Depends on the list, detail, occurrence, evidence, and history responses.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type AlarmStatus = "pending" | "processing" | "closed";
|
||||||
|
export type CloseResult = "resolved" | "false_positive";
|
||||||
|
|
||||||
|
export type AlarmRecord = {
|
||||||
|
id: string;
|
||||||
|
status: string;
|
||||||
|
current_handler: string | null;
|
||||||
|
claimed_at: string | null;
|
||||||
|
closed_at: string | null;
|
||||||
|
close_result: string | null;
|
||||||
|
occurrence_count: number;
|
||||||
|
first_occurred_at: string | null;
|
||||||
|
last_occurred_at: string | null;
|
||||||
|
previous_alarm_id: string | null;
|
||||||
|
mapped_input_id: string;
|
||||||
|
identity_key: string;
|
||||||
|
module_key: string;
|
||||||
|
scenario_key: string;
|
||||||
|
scenario_name: string;
|
||||||
|
snapshot_id: string;
|
||||||
|
snapshot_version_no: number;
|
||||||
|
cycle_key: string;
|
||||||
|
event_key: string;
|
||||||
|
opened_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AlarmList = {
|
||||||
|
items: AlarmRecord[];
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
page_size: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AlarmOccurrence = {
|
||||||
|
id: string;
|
||||||
|
mapped_input_revision_id: string;
|
||||||
|
mapping_version_id: string;
|
||||||
|
rule_version_id: string;
|
||||||
|
snapshot_id: string;
|
||||||
|
snapshot_version_no: number;
|
||||||
|
module_key: string;
|
||||||
|
scenario_key: string;
|
||||||
|
scenario_name: string;
|
||||||
|
cycle_key: string;
|
||||||
|
event_key: string;
|
||||||
|
observed_at: string;
|
||||||
|
received_at: string;
|
||||||
|
created_at: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type OccurrenceList = {
|
||||||
|
alarm_id: string;
|
||||||
|
items: AlarmOccurrence[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type RevisionEvidence = {
|
||||||
|
id: string;
|
||||||
|
occurrence_id: string;
|
||||||
|
mapped_input_revision_id: string;
|
||||||
|
mapping_version_id: string;
|
||||||
|
rule_version_id: string;
|
||||||
|
snapshot_id: string;
|
||||||
|
snapshot_version_no: number;
|
||||||
|
received_at: string;
|
||||||
|
recorded_at: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ClosedBasis = {
|
||||||
|
id: string;
|
||||||
|
original_occurrence_id: string;
|
||||||
|
mapped_input_revision_id: string;
|
||||||
|
mapping_version_id: string;
|
||||||
|
rule_version_id: string;
|
||||||
|
snapshot_id: string;
|
||||||
|
snapshot_version_no: number;
|
||||||
|
cycle_key: string;
|
||||||
|
event_key: string;
|
||||||
|
observed_at: string;
|
||||||
|
received_at: string;
|
||||||
|
recorded_at: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type EvidenceBundle = {
|
||||||
|
alarm_id: string;
|
||||||
|
revision_evidence: RevisionEvidence[];
|
||||||
|
closed_basis: ClosedBasis[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type HistoryEvent = {
|
||||||
|
id: string;
|
||||||
|
seq: number;
|
||||||
|
command: string;
|
||||||
|
actor_subject: string;
|
||||||
|
actor_role: string;
|
||||||
|
handler_subject: string;
|
||||||
|
from_status: string;
|
||||||
|
to_status: string;
|
||||||
|
note: string | null;
|
||||||
|
close_result: string | null;
|
||||||
|
evidence_ref: string | null;
|
||||||
|
recorded_at: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type HistoryList = {
|
||||||
|
alarm_id: string;
|
||||||
|
items: HistoryEvent[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CommandResult = {
|
||||||
|
alarm_id: string;
|
||||||
|
event_id: string;
|
||||||
|
command: string;
|
||||||
|
status: string;
|
||||||
|
current_handler: string | null;
|
||||||
|
close_result: string | null;
|
||||||
|
replayed: boolean;
|
||||||
|
};
|
||||||
@@ -15,6 +15,8 @@ import QueryList from "./queries/QueryList.vue";
|
|||||||
import QueryVersionView from "./queries/QueryVersionView.vue";
|
import QueryVersionView from "./queries/QueryVersionView.vue";
|
||||||
import MappingList from "./mappings/MappingList.vue";
|
import MappingList from "./mappings/MappingList.vue";
|
||||||
import MappingEdit from "./mappings/MappingEdit.vue";
|
import MappingEdit from "./mappings/MappingEdit.vue";
|
||||||
|
import AlarmList from "./alarms/AlarmList.vue";
|
||||||
|
import AlarmDetail from "./alarms/AlarmDetail.vue";
|
||||||
|
|
||||||
export function createAppRouter(history: RouterHistory = createWebHashHistory()) {
|
export function createAppRouter(history: RouterHistory = createWebHashHistory()) {
|
||||||
return createRouter({
|
return createRouter({
|
||||||
@@ -77,6 +79,8 @@ export function createAppRouter(history: RouterHistory = createWebHashHistory())
|
|||||||
},
|
},
|
||||||
{ path: "/mappings", name: "mapping-list", component: MappingList, meta: { crumbs: ["mappings"] } },
|
{ path: "/mappings", name: "mapping-list", component: MappingList, meta: { crumbs: ["mappings"] } },
|
||||||
{ path: "/mappings/:id", name: "mapping-detail", component: MappingEdit, meta: { crumbs: ["mappings", "detail"] } },
|
{ path: "/mappings/:id", name: "mapping-detail", component: MappingEdit, meta: { crumbs: ["mappings", "detail"] } },
|
||||||
|
{ path: "/alarms", name: "alarm-list", component: AlarmList, meta: { crumbs: ["alarms"] } },
|
||||||
|
{ path: "/alarms/:id", name: "alarm-detail", component: AlarmDetail, meta: { crumbs: ["alarms", "detail"] } },
|
||||||
{ path: "/:pathMatch(.*)*", redirect: "/" },
|
{ path: "/:pathMatch(.*)*", redirect: "/" },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ export default defineConfig({
|
|||||||
"/datasources": "http://127.0.0.1:8000",
|
"/datasources": "http://127.0.0.1:8000",
|
||||||
"/queries": "http://127.0.0.1:8000",
|
"/queries": "http://127.0.0.1:8000",
|
||||||
"/mappings": "http://127.0.0.1:8000",
|
"/mappings": "http://127.0.0.1:8000",
|
||||||
|
"/alarms": "http://127.0.0.1:8000",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||