Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b071c2a7a4 | ||
|
|
47d3b85a4b | ||
|
|
df991417d7 | ||
|
|
00f97a4e8a | ||
|
|
252709709c |
No files matched your search
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: marionettist-builder
|
||||
description: Orchestrates the full repository Marionettist flow from analysis to slice coding and review
|
||||
model: gpt-5.5
|
||||
model: grok-4.7
|
||||
---
|
||||
|
||||
You are the local Marionettist build orchestrator.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: marionettist-coder
|
||||
description: Implements only the currently approved Marionettist coding slice or approved parallel group
|
||||
model: gpt-5.4
|
||||
model: grok-4.7
|
||||
---
|
||||
|
||||
You are the local Marionettist coding agent.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: marionettist-critic
|
||||
description: Audits requirement, plan, context, scope, and validation risks before coding or at Marionettist gates
|
||||
model: claude-opus-5-5
|
||||
model: grok-4.7
|
||||
---
|
||||
|
||||
You are the local Marionettist critic.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: marionettist-planner
|
||||
description: Builds Marionettist implementation slices, validation strategy, and risk notes from approved analysis context
|
||||
model: gpt-5.5
|
||||
model: gpt-5.6-sol
|
||||
---
|
||||
|
||||
You are the local Marionettist planner.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: marionettist-reviewer
|
||||
description: Independent read-only review for boundary, regression, validation, and knowledge-sync risks
|
||||
model: claude-opus-5-5
|
||||
model: grok-4.7
|
||||
---
|
||||
|
||||
You are the local independent Marionettist reviewer.
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
profiles:
|
||||
think:
|
||||
description: "Deep reasoning, planning, and gate decisions"
|
||||
default: "openai/gpt-5.5"
|
||||
default: "gpt-5.6-sol"
|
||||
temperature: 0.1
|
||||
build:
|
||||
description: "Focused coding and implementation from approved task context"
|
||||
default: "openai/gpt-5.4"
|
||||
default: "grok-4.7"
|
||||
temperature: 0.1
|
||||
review:
|
||||
description: "Reflective, cautious, nuanced review"
|
||||
default: "deepseek/deepseek-v4-pro"
|
||||
default: "grok-4.7"
|
||||
temperature: 0.0
|
||||
run:
|
||||
description: "Fast utility work such as indexing and validation"
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
# Module Boundary Summary
|
||||
|
||||
## Module Scope
|
||||
|
||||
- Target area: 字段映射与规则判断。新的映射、规则、输入修订和试算,挂在已有查询定义上。
|
||||
- Related areas: 查询定义与只读预览;控制台页面;管理员角色门禁。
|
||||
- Cross-area impact: 试算会调用查询当前版本的预览。不改查询正文、版本不可变和 SQL Server 拒绝试跑。报警、场景、通知不在本模块落表。
|
||||
|
||||
## Modifiability
|
||||
|
||||
- Modifiable: `services/watchman` 中新增的映射/规则/输入代码、新迁移、对应测试;确认原型之后的 `web/apps/console` 新页面;`docs/tasks/M05.md`、`docs/progress.md`、`docs/decisions.md`。
|
||||
- Restricted areas: 查询执行器只可调用,不可放宽只读和 SQL Server 限制。权限检查沿用服务端角色门禁。
|
||||
- Forbidden areas: 报警、场景、Cron、企微、原因分析;`.env.local`、`.cursor/mcp.json`;生产库和未授权提交。
|
||||
|
||||
## Loaded Context
|
||||
|
||||
- `docs/project/knowledge-map.md` 的产品范围、公司规范、控制台界面。
|
||||
- `docs/current/frontend-ui.md` 由 D25 指向,列表和页脚在实现 UI 时读取。
|
||||
- 未把 `docs/target/` 当作当前行为。
|
||||
|
||||
## Dependency Direction
|
||||
|
||||
查询定义和预览结果流向映射。映射的列流向规则。规则试算只读这些列。报警以后读取输入身份,本模块不反向依赖报警。
|
||||
|
||||
## Boundary Risks
|
||||
|
||||
- 身份修订若写成新输入,会把 M06 的去重做坏。
|
||||
- 权限点不能在需求里编造后直接当已注册编码。
|
||||
- 迁移版本号与查询迁移串行,不能并行改 `migrations/versions`。
|
||||
|
||||
## Recommended Modification Path
|
||||
|
||||
1. 先持久化映射和版本,再写身份修订,再写规则结构,再写纯计算。
|
||||
2. 接口和权限放在计算可用之后。
|
||||
3. HTML 原型确认后才写 Vue。
|
||||
|
||||
## Uncertainty
|
||||
|
||||
- 新权限点的注册表里还没有映射/规则编码。实现该切片时再核对规范,对不上就停。
|
||||
@@ -0,0 +1,133 @@
|
||||
# Task Context Pack
|
||||
|
||||
## Task Goal
|
||||
|
||||
实现 M05:查询上的字段映射、可配置身份、结构化规则,以及正常/异常/未知试算。不创建报警。
|
||||
|
||||
## Knowledge Posture
|
||||
|
||||
- Mode: standard
|
||||
- Maturity: L1
|
||||
|
||||
## Current Slice Or Group
|
||||
|
||||
S6 HTML 原型已给出。S7 未批准,须先确认原型。
|
||||
|
||||
## Gate Policy
|
||||
|
||||
- Recommended: strict
|
||||
- Selected: autonomous
|
||||
- finalApprovalRequired: true
|
||||
- Policy Notes: 配置默认是 balanced。用户指定 autonomous。该选择不取消分析确认、计划 critic、`risk_score >= 4`、原型确认和最终验收。
|
||||
|
||||
## Bugfix Context
|
||||
|
||||
本任务不是缺陷修复。
|
||||
|
||||
## Requirement Source
|
||||
|
||||
`.task/2026-11-18/m05-mapping-rules/requirement.md`
|
||||
|
||||
## Implementation Source
|
||||
|
||||
`.task/2026-11-18/m05-mapping-rules/implementation-plan.md`
|
||||
|
||||
## Involved Modules Or Areas
|
||||
|
||||
查询定义(只调用预览)、新建映射与规则、控制台新页面、管理员门禁。
|
||||
|
||||
## Loaded Context
|
||||
|
||||
### Global Rules
|
||||
|
||||
`AGENTS.md` 项目本地段要求一个会话聚焦 M05,主 Agent 不代替独立审查。公司规范篇目在写代码前按切片再查最新版本。
|
||||
|
||||
### Knowledge Map Matches
|
||||
|
||||
产品范围指向 `docs/progress.md`、`docs/decisions.md`。控制台界面指向 `docs/current/frontend-ui.md`,只在 S7 读取。
|
||||
|
||||
### Path-Proximity Rules
|
||||
|
||||
目标目录下没有另外的 `MODULE_RULES.md`。
|
||||
|
||||
### Excluded Context
|
||||
|
||||
未读阶段 B/C 文档,未读 Cron 复用文档。那些属于 M08 及以后。
|
||||
|
||||
## Loaded Rules
|
||||
|
||||
- `AGENTS.md`
|
||||
- `.cursor/rules/sy-standards.mdc`
|
||||
- `.cursor/rules/workflow-rules.mdc`
|
||||
|
||||
## Loaded Docs
|
||||
|
||||
- `docs/tasks/INDEX.md`
|
||||
- `docs/decisions.md`(D27)
|
||||
- `需求冻结文档_V1.1_交接稿.md` 第 5~6 章
|
||||
- `.task/2026-11-18/m05-mapping-rules/boundary.md`
|
||||
|
||||
## Execution Mode
|
||||
|
||||
- Mode: sequential
|
||||
- Current Slice Or Group: S6
|
||||
- Parallel Members: 无
|
||||
- Fallback Order: S1 到 S8
|
||||
- Shared Files: `services/watchman/migrations`、`auth/access.py`
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Resolution Rule: 迁移和权限串行
|
||||
- Validation Level: slice
|
||||
|
||||
## Execution Chain
|
||||
|
||||
计划确认 → 计划 critic → S1 → 审查 → 因 S2 为 risk 4 而停下。后续每片按计划里的 gateClass 和 risk_score 决定是否还要单独确认。
|
||||
|
||||
## Allowed Modification Scope
|
||||
|
||||
确认 S1 之后,只允许计划中 S1 的路径。当前允许的写入只有任务文档。
|
||||
|
||||
## Forbidden Modification Scope
|
||||
|
||||
报警、场景、Cron、企微、查询只读边界、原型确认前的 Vue、密钥文件。
|
||||
|
||||
## Key Existing Classes Or Entrypoints
|
||||
|
||||
- 查询:`services/watchman/src/watchman/api/routes/queries.py`、`services/watchman/src/watchman/services/queries.py`
|
||||
- 权限:`services/watchman/src/watchman/auth/access.py` 中的 `watchman-admin` 与 `perm:data:emp:watchman.query.*`
|
||||
- 控制台查询页:`web/apps/console/src/queries/`
|
||||
|
||||
## Required Behavior
|
||||
|
||||
以 requirement.md 的 Business Rules 和 Acceptance Criteria 为准。结论用正常、异常、未知。不勾身份列时多行取第一行并提示跳过行数。
|
||||
|
||||
## Non-goals
|
||||
|
||||
报警、场景、原因分析、脚本、SQL Server 试跑。
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
见实现计划。当前不执行。
|
||||
|
||||
## Validation Commands
|
||||
|
||||
- 后端:在 `services/watchman` 运行 `uv run pytest`
|
||||
- 迁移:`alembic upgrade head`
|
||||
- 前端:在 `web/apps/console` 运行 `pnpm test:unit`
|
||||
- UI 切片另加 Playwright。未跑的命令记为未运行。
|
||||
|
||||
## Assumptions
|
||||
|
||||
与 requirement.md 的 Assumptions 相同。其中版本方式、嵌套深度 4、普通试算不落库,用户还没单独点名,但是按 D26 和“试算不产生报警”写下的。
|
||||
|
||||
## Risks
|
||||
|
||||
第一行依赖结果顺序。身份修订不能变成新业务事件。权限点编码实现时再核对。
|
||||
|
||||
## Stop Conditions
|
||||
|
||||
- 用户尚未确认本计划。
|
||||
- S1 前的计划 critic 尚未通过。
|
||||
- S4 前显式停下,即使 S3 已通过。判定语义不自动开写。
|
||||
- S7 前必须有原型确认。
|
||||
- 权限点规范与项目先例冲突时停下。
|
||||
- 最终 DONE_LOCAL 需要用户确认。
|
||||
@@ -0,0 +1,508 @@
|
||||
# M05 字段映射与规则判断 Implementation Plan
|
||||
|
||||
## Requirement Source
|
||||
|
||||
`.task/2026-11-18/m05-mapping-rules/requirement.md`(D27)
|
||||
|
||||
## Scope Summary
|
||||
|
||||
查询上的映射与规则、可配置身份、正常/异常/未知试算、原型确认后的控制台。不写报警和场景。
|
||||
|
||||
## Involved Modules Or Areas
|
||||
|
||||
- `services/watchman`:模型、迁移、映射、身份修订、规则校验、判定函数、API、权限。
|
||||
- `web/apps/console`:仅 S7,且 S6 原型已确认。
|
||||
- 查询预览只调用,不改只读边界。
|
||||
|
||||
## Loaded Rules
|
||||
|
||||
- `AGENTS.md` 项目本地段
|
||||
- `.cursor/rules/sy-standards.mdc`
|
||||
- `standards://api/permission-nodes?version=1.0.0`
|
||||
- `standards://api/api-envelope?version=1.1.0`
|
||||
- 本任务 `gatePolicy.selected=autonomous`,建议 strict
|
||||
|
||||
## Loaded Docs
|
||||
|
||||
- `docs/tasks/INDEX.md` M05
|
||||
- `docs/decisions.md` D05、D22、D24、D25、D26、D27
|
||||
- `docs/current/frontend-ui.md`(UI 切片再读)
|
||||
- `.task/2026-11-18/m05-mapping-rules/boundary.md`
|
||||
|
||||
## Global Forbidden Scope
|
||||
|
||||
- 报警、场景、Cron、企微、原因分析、任意脚本
|
||||
- 放宽 SQL Server 查询试跑或查询只读限制
|
||||
- 原型确认前修改 `web/apps/console` 的正式页面
|
||||
- `.env.local`、`.cursor/mcp.json`、凭证、生产库
|
||||
- `git reset --hard`、未授权 commit
|
||||
- 把未知写成报警,或把执行失败写成正常/未知
|
||||
|
||||
## Execution Strategy
|
||||
|
||||
- Complexity: complex
|
||||
- Default Execution: sequential
|
||||
- Parallel Execution: not-needed
|
||||
- Fallback Execution: sequential
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Resolution Rule: 迁移目录和权限模块串行;后一片不得改前一片已冻结的结论枚举。
|
||||
|
||||
开工前先做一次计划 critic。Tier L 的 reviewLevel 为 critic-required,这里把它写成 S1 之前的显式停点。autonomous 不跳过它,也不跳过 `risk_score >= 4` 和原型确认。
|
||||
|
||||
## Slice Dependency Graph
|
||||
|
||||
| Slice | Depends On | Can Run In Parallel With | Fallback Order | Shared Files | Merge Owner | Conflict Risk |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| S1 映射与版本 | 计划确认且 critic 通过 | 无 | 1 | `services/watchman/migrations` | 主 Agent | high |
|
||||
| S2 身份与修订 | S1 | 无 | 2 | `services/watchman/migrations` | 主 Agent | high |
|
||||
| S3 规则结构 | S1 | 无 | 3 | `services/watchman/migrations` | 主 Agent | high |
|
||||
| S4 判定函数 | S3 | 无 | 4 | 无共享迁移 | 主 Agent | low |
|
||||
| S5 API 与权限 | S2、S4 | 无 | 5 | `auth/access.py` | 主 Agent | high |
|
||||
| S6 HTML 原型 | S5 的字段口径 | 无 | 6 | `.task/.../prototype` | 主 Agent | low |
|
||||
| S7 Vue | S6 用户确认原型 | 无 | 7 | `web/apps/console` | 主 Agent | medium |
|
||||
| S8 模块审查与测试 | S7 | 无 | 8 | 证据目录 | 主 Agent | low |
|
||||
|
||||
## Implementation Slices
|
||||
|
||||
### Slice 1: 映射模型与不可变版本
|
||||
|
||||
#### Goal
|
||||
|
||||
能保存映射:所属查询、选用列、类型、身份勾选、乘数和偏移;保存产生不可变版本并设为当前版本。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `services/watchman/src/watchman/models/`
|
||||
- `services/watchman/src/watchman/services/` 中新建的映射服务
|
||||
- `services/watchman/migrations/versions/`
|
||||
- `services/watchman/tests/` 中本切片测试
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 规则判定、API 路由、前端、报警表
|
||||
- 既有查询迁移文件的改写
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: 分析确认,且计划 critic 通过
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: 任何其他迁移切片
|
||||
- Fallback Order: 1
|
||||
- Shared Files: `services/watchman/migrations`
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: high
|
||||
- Gate Class: high-risk
|
||||
- Risk Score: 4
|
||||
- Gate Reasons: database-schema, immutable-version
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 单人实现后独立审查
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 映射定义、列配置、不可变版本和当前版本指针。新表都带 `tenant_id`,按 `20261118_0006` 的形式 `ENABLE`/`FORCE ROW LEVEL SECURITY`、建立 `tenant_isolation` 策略,并 `GRANT` 给 `watchman_app`。
|
||||
2. 保存即新版本。历史版本不可更新、不可删除。数据库层沿用 `20261118_0007`:对版本表 `REVOKE UPDATE, DELETE`,并加语句级 BEFORE UPDATE/DELETE/TRUNCATE 触发器。
|
||||
3. 列类型只接受数值、文本、布尔、日期时间。身份列为布尔标记。每条映射最多一列可标为观测时间,该标记不代替身份列。换算只存乘数和偏移。日期时间列与比较值用 `timestamptz`;无时区的值在进入比较前即为非法,不按机器本地时区解释。比较归一到 UTC。
|
||||
4. 对照查询当前版本的输出列;缺失列拒绝保存。
|
||||
|
||||
#### Validation
|
||||
|
||||
- 在 `services/watchman` 运行 `uv run pytest`,至少包含:跨租户读写被拒;对历史映射版本 `UPDATE` 被拒;对历史映射版本 `DELETE` 被拒。
|
||||
- `alembic upgrade head` 与对应 downgrade 都在真实 PostgreSQL 上跑通。SQLite 不能代替 FORCE RLS。命令没跑就记未运行,不记通过。
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 验收标准 1 的数据侧成立:多列可保存,类型、身份标记和可选观测时间标记可回读。
|
||||
- 上述跨租户、UPDATE 被拒、DELETE 被拒三条测试实际通过。
|
||||
- 版本内容不可改,由数据库拒绝证明,不单靠服务层。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
- 向下迁移先 `DROP POLICY`,再删除触发器,然后删除本切片新增表。不改查询表。downgrade 未在真实 PostgreSQL 跑通时,不得宣称可回滚。
|
||||
|
||||
### Slice 2: 输入身份与修订
|
||||
|
||||
#### Goal
|
||||
|
||||
按 D27 持久化输入。勾选身份列时按列值唯一;不勾时每条映射只有一条输入。值变化追加修订,相同值不追加。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- S1 已建立的映射服务及其测试
|
||||
- 新的输入/修订模型与迁移
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 报警表、判定枚举的报警副作用、前端
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S1
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: S3 同时写迁移
|
||||
- Fallback Order: 2
|
||||
- Shared Files: `services/watchman/migrations`
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: high
|
||||
- Gate Class: high-risk
|
||||
- Risk Score: 4
|
||||
- Gate Reasons: input-identity, dedup-contract
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 单人实现后独立审查
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 唯一约束落在租户、映射加身份值上,不包含度量值和运行号。
|
||||
2. 不勾身份列时使用固定的映射级身份。
|
||||
3. 身份列为空的行拒绝形成输入。
|
||||
4. 度量变化写修订;相同度量不写新修订。
|
||||
5. 同一次结果里多行身份值相同:按返回顺序保留第一行,其余计入跳过重复行,不写第二条修订。
|
||||
6. 输入表和修订表同样带 `tenant_id`,按 S1 启用 FORCE RLS、`tenant_isolation` 和 `watchman_app` 授权,并有跨租户被拒测试。修订行追加后禁止 UPDATE/DELETE,强制方式与映射版本相同。
|
||||
|
||||
#### Validation
|
||||
|
||||
- `uv run pytest`:多身份、第一行策略的持久化入口、同身份重复行只留第一行、修订、重读
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 验收标准 2、3 的持久化侧成立。
|
||||
- 测试证明运行号不会把同一身份拆开。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
- 向下迁移先 `DROP POLICY`、再删除修订表触发器,然后删除输入表和修订表。不删除映射定义。downgrade 未在真实 PostgreSQL 跑通时,不得宣称可回滚。
|
||||
|
||||
### Slice 3: 规则结构校验
|
||||
|
||||
#### Goal
|
||||
|
||||
保存结构化条件。非法运算符、过深嵌套、空组、文本上的大小比较,在保存时拒绝。不执行用户代码。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- 规则模型、迁移、校验服务、测试
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 判定真值表实现放在 S4
|
||||
- 前端、报警
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S1
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: S2 的迁移文件
|
||||
- Fallback Order: 3
|
||||
- Shared Files: `services/watchman/migrations`
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: high
|
||||
- Gate Class: high-risk
|
||||
- Risk Score: 4
|
||||
- Gate Reasons: database-schema, reject-code-execution
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 单人实现后独立审查
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 规则属于映射,保存即不可变版本。规则定义和规则版本表带 `tenant_id`,按 S1 启用 FORCE RLS。规则版本在数据库层禁止 UPDATE/DELETE,方式与映射版本相同,并有 UPDATE 被拒、DELETE 被拒测试。
|
||||
2. 条件节点只含列引用、白名单运算符、比较值和 AND/OR。日期时间比较值必须带时区,缺时区在保存时拒绝。
|
||||
3. 深度上限 4。比较值类型须与列类型相容。
|
||||
|
||||
#### Validation
|
||||
|
||||
- `uv run pytest`:拒绝脚本片段、未知运算符、超深树、错误类型比较
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 非法规则不能保存。
|
||||
- 合法规则回读与提交结构一致。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
- 向下迁移先 `DROP POLICY`、再删除规则版本触发器,然后删除规则表。不删除映射表和输入表。downgrade 未在真实 PostgreSQL 跑通时,不得宣称可回滚。
|
||||
|
||||
### Slice 4: 正常/异常/未知计算
|
||||
|
||||
#### Goal
|
||||
|
||||
纯函数按冻结真值表计算。缺失与非法都得出未知,但原因不同。换算只使用已配置的乘数和偏移。执行失败不进入这三种结论。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- 判定与映射转换的纯函数及测试
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 写报警、改身份唯一约束、前端
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S3
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: 无
|
||||
- Fallback Order: 4
|
||||
- Shared Files: 无
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: low
|
||||
- Gate Class: standard
|
||||
- Risk Score: 3
|
||||
- Gate Reasons: judgment-semantics, explicit-stop-before-slice
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 测试先固定真值表,再写函数
|
||||
|
||||
S4 固化判定语义。即便上一片是已批准的 S3,开始 S4 前仍停下确认真值表测试范围。autonomous 不跳过这个显式停点。
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 固定 AND/OR 和比较边界的测试,用 `normal`/`abnormal`/`unknown` 做断言,展示文案仍是正常、异常、未知。
|
||||
2. 实现转换:缺失保持缺失;非法不变成 0 或空字符串。
|
||||
3. 未配置换算的单位差记为非法。
|
||||
4. 多行且无身份列时,计算只用第一行,并返回跳过行数。
|
||||
5. 零行返回空结果,不返回正常、未知或执行失败。
|
||||
6. 至少一条跨时区用例:同一时刻的两个带时区值比较为相等;无时区值记为非法。
|
||||
7. 当前查询版本已删除映射列时,计算拒绝并指出缺失列,不静默跳过。
|
||||
|
||||
#### Validation
|
||||
|
||||
- `uv run pytest` 覆盖验收标准 4、5、6 的计算部分
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 真值表测试通过。
|
||||
- 没有一条测试把执行异常断言成未知。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
- 删除判定函数不影响已写入的映射版本。
|
||||
|
||||
### Slice 5: API 与权限
|
||||
|
||||
#### Goal
|
||||
|
||||
管理员可以维护映射、规则并试算。其他角色被拒绝。普通试算不写正式输入。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `services/watchman/src/watchman/api/`
|
||||
- `services/watchman/src/watchman/auth/access.py` 及对应依赖
|
||||
- API 测试
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 新角色名、前端页面、报警路由
|
||||
- 未对照权限点规范就发明另一套检查
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S2、S4
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: 无
|
||||
- Fallback Order: 5
|
||||
- Shared Files: `auth/access.py`
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: high
|
||||
- Gate Class: high-risk
|
||||
- Risk Score: 4
|
||||
- Gate Reasons: permissions, api-contract
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 先核对 `standards://api/permission-nodes?version=1.0.0`,编码与查询模块先例不一致时停
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 读写和试算只允许 `watchman-admin`。试算复用既有查询预览执行器,不新写一套只读执行。SQL Server 仍拒绝试跑。预览所用权限点先核对规范:能沿用 `perm:data:emp:watchman.query.preview` 就沿用;要新编码时对不上注册表就停。
|
||||
2. 信封按 `standards://api/api-envelope?version=1.1.0`。
|
||||
3. 结论码用 `normal`、`abnormal`、`unknown`。界面只显示正常、异常、未知。不把中文词写成数据库枚举。
|
||||
4. 试算响应分开:结论、缺失、非法、无法形成身份、采用第一行、同身份重复行被跳过、空结果、映射列在当前查询版本中已不存在、执行失败。
|
||||
5. 查询预览失败时不返回正常或未知。零行不返回正常。
|
||||
|
||||
#### Validation
|
||||
|
||||
- `uv run pytest`:管理员成功,操作者与查看者拒绝,试算无报警行
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 验收标准 7 的“试算不产生报警”和验收标准 8 成立。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
- 去掉新路由和权限函数。不改查询权限点的含义。
|
||||
|
||||
### Slice 6: HTML 原型
|
||||
|
||||
#### Goal
|
||||
|
||||
用静态页面把映射、规则和试算走通,供确认后再写 Vue。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `.task/2026-11-18/m05-mapping-rules/prototype/`
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- `web/apps/console` 正式页面
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S5 的响应字段
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: S7
|
||||
- Fallback Order: 6
|
||||
- Shared Files: 无
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: low
|
||||
- Gate Class: simple
|
||||
- Risk Score: 2
|
||||
- Gate Reasons: prototype-before-vue
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 主 Agent 给出原型并停下等确认
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 列表、映射表单、规则条件、预览结果。
|
||||
2. 按钮位置按 D22、D25 的静态结构摆放。
|
||||
3. 文案使用正常、异常、未知。
|
||||
|
||||
#### Validation
|
||||
|
||||
- 人工打开原型,核对多列、身份列可空、第一行提示、三种结论。
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 原型覆盖验收标准 1、2、6 的可见部分。
|
||||
- 用户确认前不开始 S7。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
- 删除原型目录不影响服务。
|
||||
|
||||
### Slice 7: Vue 控制台
|
||||
|
||||
#### Goal
|
||||
|
||||
按已确认原型做控制台页面,接上 S5 的接口。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `web/apps/console/src/` 下新建的映射与规则页面、路由和本模块测试
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 未确认原型就改页面
|
||||
- 查询编辑页的行为改变,除非只增加入口链接
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S6 的用户确认
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: 无
|
||||
- Fallback Order: 7
|
||||
- Shared Files: 控制台路由
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: medium
|
||||
- Gate Class: standard
|
||||
- Risk Score: 3
|
||||
- Gate Reasons: prototype-confirmed, ui-contract
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 对照 `standards://frontend/frontend-stack` 与 `standards://frontend/element-plus` 的最新版本
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 实现前重读 `docs/current/frontend-ui.md`。
|
||||
2. 列表、编辑、试算。
|
||||
3. 页面按钮位置按 D22、D25。
|
||||
|
||||
#### Validation
|
||||
|
||||
- `pnpm test:unit`(`web/apps/console`)
|
||||
- 浏览器走通保存、重开、试算、非管理员不可写
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 验收标准 1、2、6、7 的界面侧成立。
|
||||
- 试算结果与接口一致。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
- 撤回新页面和路由入口。不删服务端数据。
|
||||
|
||||
### Slice 8: 模块审查与正式测试
|
||||
|
||||
#### Goal
|
||||
|
||||
对 S1~S7 做一次整体独立审查,并在通过的候选上跑正式测试。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- 审查指出的切片内缺陷
|
||||
- `docs/tasks/M05.md`、`docs/progress.md`、`docs/evidence/M05/`
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 借修复扩大到报警或场景
|
||||
- 未重新审查就标 DONE_LOCAL
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S7
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: 无
|
||||
- Fallback Order: 8
|
||||
- Shared Files: 证据目录
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: low
|
||||
- Gate Class: boundary-sensitive
|
||||
- Risk Score: 3
|
||||
- Gate Reasons: module-acceptance
|
||||
- Validation Level: final
|
||||
- Recommended Agent Strategy: 审查用与实现不同的模型系列;审查者默认不改代码
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 独立审查边界、真值表、身份和权限。
|
||||
2. 修复后再审,最多三轮,然后停下来问。
|
||||
3. 正式 pytest、前端单测、Playwright 和截图。
|
||||
|
||||
#### Validation
|
||||
|
||||
- `uv run pytest`
|
||||
- `pnpm test:unit`
|
||||
- Playwright 覆盖映射保存、试算三种结论、第一行提示
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 审查通过,命令实际跑过,证据路径写在 `docs/tasks/M05.md`。
|
||||
- DONE_LOCAL 仍等用户最终确认。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
- 不回滚已通过的迁移,除非审查认定迁移本身错误。那种情况先停。
|
||||
|
||||
## Parallel Slice Groups
|
||||
|
||||
无。迁移和权限文件串行。
|
||||
|
||||
## Final Validation
|
||||
|
||||
- 后端 `uv run pytest`
|
||||
- 控制台 `pnpm test:unit`
|
||||
- 映射与试算的 Playwright
|
||||
- 非管理员拒绝的接口测试
|
||||
|
||||
## Documentation Update Requirement
|
||||
|
||||
- 实现过程更新 `docs/tasks/M05.md` 与 `docs/progress.md`。
|
||||
- S8 同步 `docs/tasks/INDEX.md` 里 M05 的 PASS/FAIL/UNKNOWN 措辞,改为正常/异常/未知。M06 里「不改原始 FAIL」改成「不改原始异常判定」,不改变 M06 的范围。
|
||||
- 行为口径有变时才改 `docs/decisions.md`。
|
||||
- 不把源码清单写进 `docs/project/knowledge-map.md`。
|
||||
|
||||
## Risks
|
||||
|
||||
- S2 的第一行策略依赖查询顺序。计划里已写成假设,测试要用有 ORDER BY 的样例,并另有一条记录“无排序时第一行不稳定”。
|
||||
- S5 的权限点若规范不允许按查询模块先例新增,该切片停止,不改用前端隐藏代替。
|
||||
@@ -0,0 +1,46 @@
|
||||
# Task Intake Result
|
||||
|
||||
## Task Type
|
||||
|
||||
feature。Tier L(新模块、迁移、输入身份、判定语义;后续报警与场景会依赖这份契约)。
|
||||
|
||||
## Current Understanding
|
||||
|
||||
- M04 已 DONE_LOCAL。本会话推进 M05:字段映射、类型/空值、输入身份、结构化规则、PASS/FAIL/UNKNOWN、样例测试(INDEX;A-021~A-026;冻结稿 A-04、第 6 章)。
|
||||
- 不做:报警创建/合并(M06)、场景草稿与 Cron(M08)、规则原因分析(M12)、任意脚本、数据质量规则转人工。
|
||||
- O06 仍 OPEN。已确认的只有 D05:同一输入不重新触发;关闭后新周期或新独立事件可新建。同周期值更正如何改报警,不在本模块自行决定。
|
||||
- 查询侧已有不可变版本、`current_version_no`、只读预览(PostgreSQL/MySQL)。SQL Server 查询试跑仍不做。
|
||||
|
||||
## Gate Policy
|
||||
|
||||
- config/default: balanced
|
||||
- allowTaskOverride: true
|
||||
- recommended: strict
|
||||
- selected: autonomous
|
||||
- reason or override reason: 用户在本任务入口明确指定 autonomous。建议 strict 是因为有迁移、输入身份和判定语义,且 tier-policy 对 Tier L 的 gateHint 为 prefer-strict。建议不覆盖用户选择。
|
||||
- effective: autonomous
|
||||
- finalApprovalRequired: true
|
||||
|
||||
autonomous 不取消:分析到编码的确认、最终验收、high-risk/boundary-sensitive、需要 critic 的切片、显式停点、危险命令,以及 `risk_score >= 4`。
|
||||
|
||||
## Blocking Questions
|
||||
|
||||
已关闭(D27)。身份列可配置、可为空;不勾时多行取结果顺序的第一行。日期只是可选身份列。
|
||||
|
||||
## Non-blocking Assumptions
|
||||
|
||||
- 版本方式沿用 D26:保存即插入不可变版本并设为当前;可激活历史版本。不恢复草稿/发布两步。
|
||||
- 权限沿用查询模块:仅 `watchman-admin`。公司权限点规范(`standards://api/permission-nodes?version=1.0.0`)要求编码先存在于注册表,禁止编造。现有查询点是项目内 `perm:data:emp:watchman.query.*`,规范目录里没有映射/规则点。编码阶段再按同一项目先例声明,不在本轮把新编码写成已注册事实。
|
||||
- 正式 Vue 前先确认 HTML 原型(D21/D24 先例)。
|
||||
- 列表遵循 D25。
|
||||
- 比较运算符以冻结稿已列的等于、不等于、大于、大于等于、小于、小于等于为上限。不含正则、脚本、窗口和跨事件序列。
|
||||
- 条件嵌套深度上限暂按 4。空条件组在保存时拒绝。
|
||||
- 样例试算不创建报警、不发通知、不写正式运行。
|
||||
|
||||
## Recommended Next Step
|
||||
|
||||
用户确认计划。确认后做计划 critic,通过后再进入 S1。当前不编码。
|
||||
|
||||
## Suggested Prompt For Next Step
|
||||
|
||||
确认 M05 计划后做计划 critic,通过再实现 S1。不写业务代码,直到计划被确认。
|
||||
@@ -0,0 +1,294 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Watchman M05 映射与规则 · 静态原型(S6)</title>
|
||||
<style>
|
||||
:root {
|
||||
--primary: #5e6ad2; --primary-soft: #eef0fb; --text: #1f2328; --text-2: #59636e; --muted: #8b949e;
|
||||
--surface: #ffffff; --soft: #f6f8fa; --border: #d0d7de; --border-2: #eaeef2;
|
||||
--ok: #1a7f37; --ok-bg: #e9f6ec; --warn: #9a6700; --warn-bg: #fff8e1; --err: #cf222e; --err-bg: #fdecee;
|
||||
--radius: 8px;
|
||||
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; height: 100%; }
|
||||
body { font-family: var(--font); font-size: 13.5px; color: var(--text); background: var(--soft); line-height: 1.55; }
|
||||
button, input, select { font: inherit; color: inherit; }
|
||||
[hidden] { display: none !important; }
|
||||
.proto { background: #fffbe6; border-bottom: 1px dashed #d4b106; padding: 8px 16px; display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; font-size: 12.5px; }
|
||||
.proto-title { font-weight: 600; color: #7a5b00; }
|
||||
.proto-group { display: flex; align-items: center; gap: 6px; }
|
||||
.proto-btn { border: 1px solid var(--border); background: #fff; border-radius: 6px; padding: 2px 9px; cursor: pointer; }
|
||||
.proto-btn.on { background: var(--primary); border-color: var(--primary); color: #fff; }
|
||||
.proto-note { flex-basis: 100%; color: #7a5b00; }
|
||||
.shell { display: flex; height: calc(100vh - 78px); min-height: 520px; }
|
||||
.side { width: 196px; flex: none; background: var(--surface); border-right: 1px solid var(--border-2); padding: 14px 10px; display: flex; flex-direction: column; }
|
||||
.brand { font-weight: 700; font-size: 16px; padding: 4px 10px 14px; }
|
||||
.nav-item { padding: 7px 10px; border-radius: 6px; color: var(--text-2); }
|
||||
.nav-item.cur { background: var(--primary-soft); color: var(--primary); font-weight: 600; }
|
||||
.nav-item.off { color: var(--muted); }
|
||||
.side .who { margin-top: auto; padding: 10px; color: var(--text-2); font-size: 12.5px; }
|
||||
.main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
|
||||
.top { height: 48px; flex: none; background: var(--surface); border-bottom: 1px solid var(--border-2); display: flex; align-items: center; padding: 0 20px; }
|
||||
.crumb { color: var(--text-2); } .crumb b { color: var(--text); font-weight: 600; }
|
||||
.content { flex: 1; overflow: auto; padding: 16px 20px; min-height: 0; }
|
||||
.pagefoot { flex: none; background: var(--surface); border-top: 1px solid var(--border-2); display: flex; align-items: center; justify-content: center; gap: 8px; padding: 12px 20px; }
|
||||
.listfoot { flex: none; background: var(--surface); border-top: 1px solid var(--border-2); display: flex; justify-content: flex-end; padding: 8px 20px; color: var(--text-2); font-size: 12.5px; }
|
||||
.tools { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; }
|
||||
.tools .grow { flex: 1; }
|
||||
.tools input, .tools select { width: 180px; }
|
||||
.btn { border: 1px solid var(--border); background: var(--surface); border-radius: 6px; padding: 5px 14px; cursor: pointer; }
|
||||
.btn.primary { background: var(--primary); border-color: var(--primary); color: #fff; }
|
||||
.btn.link { border: 0; background: none; color: var(--primary); padding: 1px 6px; }
|
||||
.btn:disabled { color: var(--muted); background: var(--soft); cursor: not-allowed; }
|
||||
input, select { border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; background: #fff; width: 100%; }
|
||||
.card { background: var(--surface); border: 1px solid var(--border-2); border-radius: var(--radius); padding: 16px 18px; margin-bottom: 16px; }
|
||||
.card h3 { margin: 0 0 12px; font-size: 14.5px; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th { text-align: left; font-weight: 600; color: var(--text-2); background: var(--soft); padding: 9px 12px; border-bottom: 1px solid var(--border-2); }
|
||||
td { padding: 8px 12px; border-bottom: 1px solid var(--border-2); vertical-align: middle; }
|
||||
.table-wrap { border: 1px solid var(--border-2); border-radius: var(--radius); background: #fff; overflow: auto; }
|
||||
.ops { white-space: nowrap; width: 196px; text-align: right; }
|
||||
.modal-mask { position: fixed; inset: 0; background: rgba(31,35,40,.4); display: flex; align-items: center; justify-content: center; z-index: 20; }
|
||||
.modal { background: #fff; border-radius: var(--radius); padding: 18px 20px; width: 640px; max-width: 92vw; max-height: 80vh; overflow: auto; }
|
||||
.modal h3 { margin: 0 0 8px; font-size: 15px; }
|
||||
.modal .actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 14px; }
|
||||
.tag { display: inline-block; padding: 0 8px; border-radius: 10px; font-size: 12px; line-height: 20px; }
|
||||
.tag.abnormal { background: var(--err-bg); color: var(--err); }
|
||||
.tag.normal { background: var(--ok-bg); color: var(--ok); }
|
||||
.tag.unknown { background: var(--warn-bg); color: var(--warn); }
|
||||
.tag.grey { background: var(--soft); color: var(--text-2); border: 1px solid var(--border-2); }
|
||||
.miss { background: #fff8e1; }
|
||||
.badcell { background: var(--err-bg); }
|
||||
.note { border-radius: var(--radius); padding: 8px 12px; font-size: 12.5px; background: var(--soft); border: 1px solid var(--border-2); color: var(--text-2); margin-bottom: 12px; }
|
||||
.note.warn { background: var(--warn-bg); border-color: #f1dc9a; color: var(--warn); }
|
||||
.flash { border-radius: var(--radius); padding: 8px 12px; margin-bottom: 12px; background: var(--ok-bg); border: 1px solid #b7e0c2; color: #145c2a; }
|
||||
.empty { text-align: center; padding: 56px 20px; background: #fff; border: 1px dashed var(--border); border-radius: var(--radius); }
|
||||
.result { border-radius: var(--radius); padding: 12px 14px; border: 1px solid; margin-top: 12px; }
|
||||
.result.abnormal { background: var(--err-bg); border-color: #f4b8be; }
|
||||
.result.normal { background: var(--ok-bg); border-color: #b7e0c2; }
|
||||
.result.unknown { background: var(--warn-bg); border-color: #f1dc9a; }
|
||||
.result.empty { background: var(--soft); border-color: var(--border); }
|
||||
.result.error { background: var(--err-bg); border-color: #f4b8be; }
|
||||
.hint { color: var(--muted); font-size: 12px; }
|
||||
.mono { font-family: ui-monospace, Consolas, monospace; font-size: 12.5px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="proto">
|
||||
<span class="proto-title">静态原型 · 不是正式页面</span>
|
||||
<span class="proto-group"><span>角色</span>
|
||||
<button class="proto-btn on" data-role="admin">管理员</button>
|
||||
<button class="proto-btn" data-role="operator">处理者</button>
|
||||
<button class="proto-btn" data-role="viewer">查看者</button>
|
||||
</span>
|
||||
<span class="proto-group"><span>试算样例</span>
|
||||
<button class="proto-btn on" data-out="abnormal">异常</button>
|
||||
<button class="proto-btn" data-out="normal">正常</button>
|
||||
<button class="proto-btn" data-out="missing">未知·缺失</button>
|
||||
<button class="proto-btn" data-out="invalid">未知·非法</button>
|
||||
<button class="proto-btn" data-out="empty">空结果</button>
|
||||
<button class="proto-btn" data-out="error">执行失败</button>
|
||||
<button class="proto-btn" data-out="first">只用第一行</button>
|
||||
</span>
|
||||
<div class="proto-note">映射和判断规则共用一个版本。切换版本时字段和条件一起换。基于某一版编辑后,另存为新版本,旧版本不改。</div>
|
||||
</div>
|
||||
<div class="shell">
|
||||
<aside class="side">
|
||||
<div class="brand">预警平台</div>
|
||||
<div class="nav-item off">数据源</div>
|
||||
<div class="nav-item off">查询</div>
|
||||
<div class="nav-item cur">映射与规则</div>
|
||||
<div class="who" id="who">管理员</div>
|
||||
</aside>
|
||||
<div class="main">
|
||||
<div class="top"><div class="crumb" id="crumb">预警平台 / <b>映射与规则</b></div></div>
|
||||
<div class="content" id="content"></div>
|
||||
<div class="pagefoot" id="foot" hidden></div>
|
||||
<div class="listfoot" id="listfoot" hidden>共 1 条</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-mask" id="mask" hidden>
|
||||
<div class="modal" id="modal"></div>
|
||||
</div>
|
||||
<script>
|
||||
var state = { view: "list", role: "admin", outcome: "abnormal", flash: "", editing: null, ruleEditing: null };
|
||||
function col(name, label, type, extra) {
|
||||
extra = extra || {};
|
||||
return { name: name, label: label, type: type, identity: !!extra.identity, observe: !!extra.observe, multiply: extra.multiply || "", offset: extra.offset || "" };
|
||||
}
|
||||
var versions = [
|
||||
{ no: 1, columns: [col("temperature", "温度", "number"), col("pressure", "压力", "number")], rules: [{ column: "温度", op: "大于", value: "90" }] },
|
||||
{ no: 2, columns: [col("temperature", "温度", "number"), col("pressure", "压力", "number"), col("serial", "设备", "string", { identity: true }), col("observed_at", "观测时间", "datetime", { observe: true })], rules: [{ column: "温度", op: "大于", value: "80" }, { column: "压力", op: "大于", value: "10" }] }
|
||||
];
|
||||
var current = 2;
|
||||
var draft = null;
|
||||
|
||||
function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { "&": "&", "<": "<", ">": ">", '"': """ }[c]; }); }
|
||||
|
||||
function render() {
|
||||
document.querySelectorAll("[data-role]").forEach(function (b) { b.classList.toggle("on", b.dataset.role === state.role); });
|
||||
document.querySelectorAll("[data-out]").forEach(function (b) { b.classList.toggle("on", b.dataset.out === state.outcome); });
|
||||
document.getElementById("who").textContent = { admin: "管理员", operator: "处理者", viewer: "查看者" }[state.role];
|
||||
var crumb = "预警平台 / <b>映射与规则</b>";
|
||||
if (state.view === "detail") crumb += " / <b>详情</b>";
|
||||
if (state.view === "trial") crumb += " / <b>试算</b>";
|
||||
document.getElementById("crumb").innerHTML = crumb;
|
||||
var denied = state.role !== "admin";
|
||||
var foot = document.getElementById("foot");
|
||||
var listfoot = document.getElementById("listfoot");
|
||||
foot.hidden = true;
|
||||
listfoot.hidden = true;
|
||||
var html = "";
|
||||
if (denied) {
|
||||
html = '<div class="empty"><h3>无法进入映射与规则</h3><p>只有管理员可以维护映射、规则和试算。</p></div>';
|
||||
} else if (state.view === "list") {
|
||||
listfoot.hidden = false;
|
||||
html = (state.flash ? '<div class="flash">' + esc(state.flash) + "</div>" : "") +
|
||||
'<div class="tools"><input id="qname" placeholder="名称" value="炉温"><select><option>全部查询</option><option>当前炉温</option></select>' +
|
||||
'<button class="btn" id="do-filter">查询</button><button class="btn" id="do-reset">重置</button><span class="grow"></span>' +
|
||||
'<button class="btn primary" id="go-new">新建</button></div>' +
|
||||
'<div class="table-wrap"><table><thead><tr><th>名称</th><th>查询</th><th>当前版本</th><th>身份列</th><th class="ops">操作</th></tr></thead><tbody><tr>' +
|
||||
"<td>炉温与压力</td><td>当前炉温</td><td>v" + current + "</td><td>" + identityText(version(current)) + "</td>" +
|
||||
'<td class="ops"><button class="btn link" id="go-detail">打开</button><button class="btn link" id="open-switch">切换版本</button><button class="btn link" id="go-trial">试算</button></td></tr></tbody></table></div>';
|
||||
} else if (state.view === "detail") {
|
||||
foot.hidden = false;
|
||||
var base = draft.base;
|
||||
var next = versions[versions.length - 1].no + 1;
|
||||
html = '<div class="note">正在基于 v' + base + " 编辑。保存后成为 v" + next + ",并设为当前版本。v" + base + " 不会被修改。</div>" +
|
||||
'<div class="card"><h3>选用列 <span class="hint">来源 v' + base + " · 当前生效 v" + current + '</span></h3><div class="table-wrap"><table><thead><tr><th>查询列</th><th>类型</th><th>身份</th><th>观测时间</th><th>乘数</th><th>偏移</th></tr></thead><tbody>' +
|
||||
draft.columns.map(function (c, i) {
|
||||
return "<tr><td>" + esc(c.label) + " <span class=\"mono\">" + esc(c.name) + "</span></td><td>" + esc(c.type) + "</td>" +
|
||||
'<td><input type="checkbox" data-id="' + i + '"' + (c.identity ? " checked" : "") + "></td>" +
|
||||
'<td><input type="checkbox" data-obs="' + i + '"' + (c.observe ? " checked" : "") + (c.type !== "datetime" ? " disabled" : "") + "></td>" +
|
||||
"<td>" + (c.type === "number" ? '<input data-mul="' + i + '" value="' + esc(c.multiply) + '" placeholder="不换算">' : "—") + "</td>" +
|
||||
"<td>" + (c.type === "number" ? '<input data-off="' + i + '" value="' + esc(c.offset) + '" placeholder="不换算">' : "—") + "</td></tr>";
|
||||
}).join("") + "</tbody></table></div></div>" +
|
||||
'<div class="card"><h3>判断规则 <span class="hint">与字段同属 v' + base + "</span></h3>" +
|
||||
'<div class="table-wrap"><table><thead><tr><th>列</th><th>比较</th><th>比较值</th></tr></thead><tbody>' +
|
||||
draft.rules.map(function (row, i) {
|
||||
return "<tr><td>" + esc(row.column) + '</td><td><select data-op="' + i + '"><option' + (row.op === "大于" ? " selected" : "") + '>大于</option><option' + (row.op === "大于等于" ? " selected" : "") + ">大于等于</option></select></td>" +
|
||||
'<td><input data-val="' + i + '" value="' + esc(row.value) + '"></td></tr>';
|
||||
}).join("") + "</tbody></table></div>" +
|
||||
'<p class="hint">条件描述异常。成立为异常,不成立为正常。这里没有单独的规则版本。</p></div>';
|
||||
foot.innerHTML = '<button class="btn" id="back-list">返回列表</button><button class="btn" id="open-switch">切换版本</button><button class="btn primary" id="save-map">另存为新版本</button>';
|
||||
} else {
|
||||
foot.hidden = false;
|
||||
html = trialHtml();
|
||||
foot.innerHTML = '<button class="btn" id="back-list">返回列表</button><button class="btn" id="go-detail">打开当前版本</button>';
|
||||
}
|
||||
document.getElementById("content").innerHTML = html;
|
||||
bind();
|
||||
}
|
||||
|
||||
function trialHtml() {
|
||||
var o = state.outcome;
|
||||
if (o === "empty") {
|
||||
return '<div class="result empty"><b>空结果</b><div>查询没有返回行。这不是正常,也不是未知,也不是执行失败。</div></div>';
|
||||
}
|
||||
if (o === "error") {
|
||||
return '<div class="result error"><b>执行失败</b><div>当前查询版本里已经没有映射列 temperature。没有给出正常、异常或未知。</div></div>';
|
||||
}
|
||||
var skip = "";
|
||||
if (o === "first" || !hasIdentity(version(current))) {
|
||||
skip = '<div class="note warn">未勾选身份列。本次结果有 3 行,采用第一行,跳过 2 行。换行顺序要靠查询自己排序。</div>';
|
||||
}
|
||||
var tempStatus = o === "missing" ? "缺失" : (o === "invalid" ? "非法" : "有效");
|
||||
var tempVal = o === "missing" ? "—" : (o === "invalid" ? "hot" : (o === "normal" ? "70" : "81.2"));
|
||||
var code = (o === "missing" || o === "invalid") ? "unknown" : (o === "normal" ? "normal" : "abnormal");
|
||||
var label = { unknown: "未知", normal: "正常", abnormal: "异常" }[code];
|
||||
var cls = o === "missing" ? "miss" : (o === "invalid" ? "badcell" : "");
|
||||
return skip + '<div class="card"><h3>映射结果</h3><div class="table-wrap"><table><thead><tr><th>列</th><th>原始值</th><th>转换后</th><th>字段状态</th></tr></thead><tbody>' +
|
||||
'<tr class="' + cls + '"><td>温度</td><td class="mono">' + esc(tempVal) + "</td><td class=\"mono\">" + esc(tempVal) + "</td><td>" + tempStatus + "</td></tr>" +
|
||||
"<tr><td>压力</td><td class=\"mono\">12</td><td class=\"mono\">12</td><td>有效</td></tr></tbody></table></div>" +
|
||||
'<p class="hint">缺失保持为空,不会变成 0。非法值不会变成空字符串。两者的结论都是未知,但状态不同。</p></div>' +
|
||||
'<div class="result ' + code + '"><b>' + label + '</b><div>温度大于 80 且压力大于 10。实际温度 ' + esc(tempVal) + ",比较值 80。</div>" +
|
||||
'<div class="hint">接口码 ' + code + " · 版本 v" + current + " · 观测时间 " + (hasObserve(version(current)) ? "2026-11-18 09:00 +08:00" : "本次试算时间") + "</div></div>";
|
||||
}
|
||||
|
||||
function version(no) { return versions.filter(function (v) { return v.no === no; })[0]; }
|
||||
function identityText(v) {
|
||||
var names = v.columns.filter(function (c) { return c.identity; }).map(function (c) { return c.label; });
|
||||
return names.length ? names.join("、") : "未勾选";
|
||||
}
|
||||
function hasIdentity(v) { return v.columns.some(function (c) { return c.identity; }); }
|
||||
function hasObserve(v) { return v.columns.some(function (c) { return c.observe; }); }
|
||||
function cloneColumns(list) { return list.map(function (c) { return col(c.name, c.label, c.type, c); }); }
|
||||
function ruleText(v) { return v.rules.map(function (row) { return row.column + row.op + row.value; }).join(" 且 "); }
|
||||
function cloneRules(list) { return list.map(function (row) { return { column: row.column, op: row.op, value: row.value }; }); }
|
||||
function loadMap(no) {
|
||||
var source = version(no);
|
||||
draft = { base: no, columns: cloneColumns(source.columns), rules: cloneRules(source.rules) };
|
||||
state.view = "detail";
|
||||
closeModal();
|
||||
render();
|
||||
}
|
||||
function closeModal() { document.getElementById("mask").hidden = true; }
|
||||
function openSwitch() {
|
||||
var rows = versions.slice().reverse().map(function (v) {
|
||||
var active = current === v.no;
|
||||
return "<tr><td>v" + v.no + (active ? ' <span class="tag grey">当前</span>' : "") + "</td><td>" + esc(identityText(v) + " · " + ruleText(v)) + "</td><td class=\"ops\">" +
|
||||
(active ? "" : '<button class="btn link" data-act="activate" data-no="' + v.no + '">激活</button>') +
|
||||
'<button class="btn link" data-act="edit" data-no="' + v.no + '">以此编辑</button></td></tr>';
|
||||
}).join("");
|
||||
document.getElementById("modal").innerHTML = "<h3>切换版本</h3><p class=\"hint\">一个版本同时包含字段映射和判断规则。激活不产生新版本。以此编辑后另存,字段和条件一起成为新版本。</p>" +
|
||||
'<div class="table-wrap"><table><thead><tr><th>版本</th><th>内容</th><th class="ops">操作</th></tr></thead><tbody>' + rows + "</tbody></table></div>" +
|
||||
'<div class="actions"><button class="btn" id="close-modal">关闭</button></div>';
|
||||
document.getElementById("mask").hidden = false;
|
||||
document.getElementById("close-modal").onclick = closeModal;
|
||||
document.getElementById("modal").onclick = function (ev) {
|
||||
var t = ev.target;
|
||||
if (!t.dataset || !t.dataset.act) return;
|
||||
var no = +t.dataset.no;
|
||||
if (t.dataset.act === "activate") { current = no; state.flash = "已将 v" + no + " 设为当前版本。字段和判断规则一起切换,没有新增版本。"; closeModal(); render(); }
|
||||
if (t.dataset.act === "edit") loadMap(no);
|
||||
};
|
||||
}
|
||||
|
||||
function bind() {
|
||||
var go = function (id, fn) { var n = document.getElementById(id); if (n) n.onclick = fn; };
|
||||
go("go-detail", function () { state.flash = ""; loadMap(current); });
|
||||
go("go-new", function () { loadMap(current); });
|
||||
go("go-trial", function () { state.view = "trial"; render(); });
|
||||
go("back-list", function () { state.view = "list"; render(); });
|
||||
go("open-switch", function () { openSwitch(); });
|
||||
go("save-map", function () {
|
||||
readDraft();
|
||||
var no = versions[versions.length - 1].no + 1;
|
||||
var base = draft.base;
|
||||
versions.push({ no: no, columns: cloneColumns(draft.columns), rules: cloneRules(draft.rules) });
|
||||
current = no;
|
||||
state.view = "list";
|
||||
state.flash = "已按 v" + base + " 的字段和判断规则另存为 v" + no + ",并设为当前版本。v" + base + " 未改。";
|
||||
render();
|
||||
});
|
||||
go("do-filter", function () { state.flash = "已按名称筛选。输入时不会自动筛选。"; render(); });
|
||||
go("do-reset", function () { state.flash = ""; render(); });
|
||||
document.querySelectorAll("[data-id]").forEach(function (box) {
|
||||
box.onchange = function () { draft.columns[+box.dataset.id].identity = box.checked; };
|
||||
});
|
||||
document.querySelectorAll("[data-obs]").forEach(function (box) {
|
||||
box.onchange = function () {
|
||||
draft.columns.forEach(function (c, i) { c.observe = i === +box.dataset.obs && box.checked && c.type === "datetime"; });
|
||||
render();
|
||||
};
|
||||
});
|
||||
}
|
||||
function readDraft() {
|
||||
document.querySelectorAll("[data-mul]").forEach(function (input) { draft.columns[+input.dataset.mul].multiply = input.value; });
|
||||
document.querySelectorAll("[data-off]").forEach(function (input) { draft.columns[+input.dataset.off].offset = input.value; });
|
||||
document.querySelectorAll("[data-op]").forEach(function (input) { draft.rules[+input.dataset.op].op = input.value; });
|
||||
document.querySelectorAll("[data-val]").forEach(function (input) { draft.rules[+input.dataset.val].value = input.value; });
|
||||
}
|
||||
|
||||
document.querySelector(".proto").onclick = function (ev) {
|
||||
var t = ev.target;
|
||||
if (t.dataset.role) { state.role = t.dataset.role; state.view = "list"; render(); }
|
||||
if (t.dataset.out) { state.outcome = t.dataset.out; if (state.role === "admin") state.view = "trial"; render(); }
|
||||
};
|
||||
render();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,165 @@
|
||||
# M05 字段映射与规则判断 Requirement
|
||||
|
||||
## Goal
|
||||
|
||||
在已有查询定义上维护字段映射和结构化判断规则,并用样例行试算。每行给出正常、异常或未知。本模块不创建报警。
|
||||
|
||||
## Background
|
||||
|
||||
M04 已交付查询定义、不可变版本和只读预览。冻结稿 A-04、第 6 章和 A-021~A-026 把映射、输入身份和是否异常放在报警之前。D27 收口了本模块的字段和身份口径。O06 里“修订后报警怎么改”仍归 M06。
|
||||
|
||||
## In Scope
|
||||
|
||||
- 挂在查询定义上的映射:选用结果列、类型、可选身份列、可选数值换算。
|
||||
- 挂在映射上的规则:结构化条件,AND/OR,样例试算。
|
||||
- 正常/异常/未知,以及与之分开的字段状态、执行失败。
|
||||
- 输入身份和值修订的持久化。同一身份不因重读新开一条。
|
||||
- 管理界面。正式 Vue 之前先确认 HTML 原型。
|
||||
|
||||
## Out Of Scope
|
||||
|
||||
- 报警创建、合并、关闭后新周期(M06,O06 的报警半边)。
|
||||
- 场景草稿、发布、Cron(M08)。
|
||||
- 规则原因分析(M12)和数据质量规则转人工。
|
||||
- 任意脚本、正则、窗口、跨事件序列、NOT。
|
||||
- SQL Server 查询试跑。
|
||||
- 从行内单位文本自动猜换算。
|
||||
|
||||
## Current Behavior
|
||||
|
||||
查询可以定义、版本化和预览。没有映射、规则、输入身份或判定结果。
|
||||
|
||||
## Required Behavior
|
||||
|
||||
配置人员选择一条查询,勾选要使用的结果列。每列标明类型。数值列可以配置乘数和偏移。身份列由人勾选,可以不勾,也可以勾多列;日期列只有被勾成身份列时才参与区分。
|
||||
|
||||
规则引用这些列。每条条件选择一列、一个已允许的运算符和一个比较值。条件可以按 AND/OR 组合。
|
||||
|
||||
试算展示原始列、转换后的值、字段状态,以及正常/异常/未知。同时给出规则的文字说明、实际值、比较值、命中条件、规则版本、观测时间和输入依据。试算不写报警,不发通知。
|
||||
|
||||
零行是空结果,不是正常,不是未知,也不是执行失败。单行里的指标为空仍按缺失处理。
|
||||
|
||||
## User Flow
|
||||
|
||||
1. 从查询进入映射,勾选列、类型、身份列和换算,保存。
|
||||
2. 在该映射下编写规则,保存。
|
||||
3. 用贴入的样例,或对该查询当前版本做一次只读预览(仅 PostgreSQL/MySQL),查看映射和判定。
|
||||
4. 重开已保存的映射和规则,条件与保存时一致。
|
||||
|
||||
## Business Rules
|
||||
|
||||
业务结论只有三种,界面和接口都使用这些词:
|
||||
|
||||
| 结论 | 含义 |
|
||||
|---|---|
|
||||
| 正常 | 有效数据已经足以确定异常条件不成立 |
|
||||
| 异常 | 有效数据已经足以确定异常条件成立 |
|
||||
| 未知 | 必要数据不足,不能可靠确定 |
|
||||
|
||||
执行失败另记,不写成正常、异常或未知。
|
||||
|
||||
单条比较:两边都能按声明类型比较,条件成立为异常,不成立为正常。缺值或非法值为未知。
|
||||
|
||||
AND:已有一条正常,则整组正常;全部为异常,则整组异常;还没有正常且存在未知,则整组未知。
|
||||
|
||||
OR:已有一条异常,则整组异常;全部为正常,则整组正常;还没有异常且存在未知,则整组未知。
|
||||
|
||||
字段状态与结论分开:缺失、非法都导致未知,但预览里必须能看出是哪一种。缺失保持为空,不转成 0 或空字符串。
|
||||
|
||||
身份:
|
||||
|
||||
- 勾了身份列时,这些列的值合起来区分输入。值变化只追加修订,不新开身份。度量值、运行号和整行哈希都不进入身份。
|
||||
- 不勾身份列时,这条映射本身是唯一输入。结果有多行时采用本次返回顺序的第一行。
|
||||
- 身份列已勾选但该行身份值为空:该行不能形成身份,不写入输入。
|
||||
- 同一次结果里多行身份值相同:按返回顺序保留第一行,其余计入跳过的重复行,不在同一次里写多条修订。
|
||||
|
||||
未知不创建报警。本模块没有报警写入。空结果也不创建报警,不记成正常。
|
||||
|
||||
## Data Rules
|
||||
|
||||
- 一条查询可有多条映射。一条映射可有多条规则。
|
||||
- 映射和判断规则共用同一个不可变版本。切换当前版本时,字段和条件一起切换。可基于某一历史版本编辑字段和条件,保存时另存为一个新版本并设为当前,被打开的历史版本内容不变。判断规则没有单独的版本号。
|
||||
- 同一身份且度量值无变化:不追加修订。
|
||||
- 试算样例可以不落成正式输入。正式输入只在明确的保存试算中写入。默认的页面试算不写输入。见 Assumptions。
|
||||
- 列是否还存在,对照该查询的当前版本。当前版本去掉了已选列时,保存和试算都拒绝,并说明缺哪一列。
|
||||
- 新表带 `tenant_id`,并按现有业务表启用强制行级安全。映射版本内容在数据库层禁止更新和删除。
|
||||
- 日期时间列与日期时间比较值使用带时区的时间,比较前归一到 UTC。没有时区的值视为非法,不按机器本地时区猜。
|
||||
- 每条映射最多把一列标成观测时间。不标时,详情里的观测时间用本次试算时间。观测时间列不自动变成身份列。
|
||||
|
||||
## API Contract
|
||||
|
||||
对外操作:映射的维护与读取、规则的维护与读取、映射试算、规则试算。响应信封遵循 `standards://api/api-envelope?version=1.1.0`。路径在实现切片里按现有查询路由风格确定,不在本需求里另造一套信封。
|
||||
|
||||
试算响应能区分:一行结论、字段缺失、字段非法、无法形成身份、采用了第一行、同身份重复行被跳过、空结果、映射列在当前查询版本中已不存在、执行失败。
|
||||
|
||||
结论的存储和接口使用稳定英文码 `normal`、`abnormal`、`unknown`。界面文案固定为正常、异常、未知。不把这三个中文词写成数据库枚举。空结果和执行失败不使用这三个码。
|
||||
|
||||
## UI Requirements
|
||||
|
||||
- 列表遵循 D25。详情和表单的页面按钮遵循 D22。
|
||||
- 正式 Vue 前先给出 HTML 原型并经确认。
|
||||
- 映射页能勾选列、类型、身份列、最多一列观测时间、乘数和偏移。
|
||||
- 规则页用结构化条件,不用脚本框。
|
||||
- 预览高亮缺失和非法。采用第一行时写明跳过的行数。
|
||||
- 判定结果使用正常、异常、未知。
|
||||
|
||||
## Compatibility Requirements
|
||||
|
||||
- 不改查询版本不可变、只读预览和 SQL Server 不试跑的现有行为。
|
||||
- 不改已有权限角色名。`watchman-admin` 继续是配置人员角色。
|
||||
|
||||
## Error Handling
|
||||
|
||||
- 查询预览失败:执行失败,不产生正常或未知。
|
||||
- 类型对不上、未配置的单位差、无法解析:字段非法,结论未知。
|
||||
- 系统异常:执行失败。
|
||||
- 空条件、超过嵌套深度、未知运算符、对文本或布尔使用大小比较:保存时拒绝。
|
||||
|
||||
## Permissions And Security
|
||||
|
||||
仅 `watchman-admin` 可读取、保存和试算。操作者与查看者不能写,也不能靠隐藏按钮绕过。
|
||||
|
||||
权限点编码在实现时按 `standards://api/permission-nodes?version=1.0.0` 声明,并沿用现有 `perm:data:emp:watchman.query.*` 的项目写法。需求不把尚未注册的编码写成已存在事实。
|
||||
|
||||
## Assumptions
|
||||
|
||||
- 映射和规则的版本方式与 D26 相同。
|
||||
- 比较类型为数值、文本、布尔、日期时间。数值和日期时间可用等于、不等于、大于、大于等于、小于、小于等于。文本和布尔只有等于、不等于。
|
||||
- 条件嵌套深度上限为 4。根组算第 1 层,叶子也算一层。空组拒绝。
|
||||
- 第一行指本次结果集的返回顺序。顺序要稳定,由查询自己写 ORDER BY。
|
||||
- 换算写在映射上,不读取行里的单位文字。
|
||||
- 页面上的普通试算不写正式输入;持久修订由单独的保存动作写入。
|
||||
- 没有标成观测时间的列时,试算说明里的时间用本次试算时间。这条现在写进 Data Rules,因为冻结稿要求详情展示观测时间,而用户已确认日期不是必填。
|
||||
- 同一次结果中的重复身份保留第一行。这是为了和「第一行」口径一致,S2 之前若要改,先改需求再写代码。
|
||||
|
||||
## Risks
|
||||
|
||||
- 不勾身份列时,多行只留第一行。查询若没有 ORDER BY,下一次第一行可能变了,修订会记在同一条输入上。
|
||||
- 身份持久化会被 M06 拿去合并报警。本模块的修订不能被实现成新的业务事件。
|
||||
- 新权限点若与公司注册表不一致,实现时要停下来核对,不能临时改成只靠前端隐藏。
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
1. 一行中的多列指标可以同时被映射,规则的每条条件能选择其中一列。
|
||||
2. 不勾身份列时,多行样例只用第一行,并显示跳过行数;勾选身份列后,不同身份值分成不同输入。
|
||||
3. 同一身份的新度量值追加修订;相同值的重读不新开输入,也不把运行号算进身份。
|
||||
4. 缺失保持缺失,非法值不变成 0 或空字符串;两者结论都是未知,预览能区分。
|
||||
5. 未配置换算的单位差为非法。已配置的乘数和偏移按配置生效。
|
||||
6. AND/OR 符合 Business Rules 中的三值表。执行失败不显示为正常或未知。
|
||||
7. 保存后再打开,条件一致。试算不产生报警。
|
||||
8. 非管理员调用写和试算被拒绝。
|
||||
9. 查询返回零行时结果为空结果,不出现正常、未知或执行失败。
|
||||
10. 当前查询版本去掉已选列时,试算被拒绝并指出缺失列。
|
||||
11. 带时区的日期时间按 UTC 比较;没有时区的值记为非法。
|
||||
|
||||
## Deferred Questions
|
||||
|
||||
- O06:同一身份修订之后,原报警是否更新。M06 再定。
|
||||
- 普通试算与“保存为正式输入”是否分成两个按钮,若实现时界面放不下,再问一次,不自行改成每次试算都落库。
|
||||
|
||||
## Source Notes
|
||||
|
||||
- D05、D22、D24、D25、D26、D27。
|
||||
- `需求冻结文档_V1.1_交接稿.md` A-04、第 6 章。
|
||||
- `docs/tasks/INDEX.md` M05;`docs/tasks/CHECKLIST-v1.md` A-021~A-026。
|
||||
- `docs/development-plan.md` 4.2:身份不同于运行号,整行哈希不能用来丢掉跨周期事件。本模块用可配置身份列实现这一点。
|
||||
@@ -0,0 +1,166 @@
|
||||
# M05 计划 Critic 审查
|
||||
|
||||
- 模式:plan-review(S1 之前的 critic-required 停点)
|
||||
- 任务:`.task/2026-11-18/m05-mapping-rules`
|
||||
- 日期:2026-11-18
|
||||
- 审查范围:requirement.md、implementation-plan.md、context-pack.md、boundary.md、D05/D22/D24/D25/D26/D27、`docs/tasks/INDEX.md` M05、冻结稿 A-04 与第 6 章、`AGENTS.md` 项目本地段;并抽查 `models/query.py`、`auth/access.py`、`migrations/versions/`。
|
||||
- 本次审查不改任何产品代码、迁移或前端。
|
||||
|
||||
## 当前结论(第二轮复审,2026-11-18 晚)
|
||||
|
||||
**PASS_WITH_WARNINGS**
|
||||
|
||||
**S1 可以开始:是。** 没有剩余阻断项。详见文末「复审(第二轮)」。下面第一轮的 FAIL 结论已被取代,保留作为修订依据。
|
||||
|
||||
## 第一轮结论(已取代)
|
||||
|
||||
**FAIL**
|
||||
|
||||
**S1 可以开始:否。** 需要先按下面「阻断项」修订实现计划(只改 S1 的 Steps/Validation/Rollback 三段即可,不必重做整份计划),修订后再放行 S1。
|
||||
|
||||
说明:FAIL 的原因不是需求口径错了。需求与 D27、冻结稿第 6 章在语义上一致;问题集中在 S1 这一片的 schema 契约与验证证据,按现在的写法实现出来的表会违反仓库既有的租户隔离与不可变强制约定,且 S1 的 Done Criteria 没有对应测试。
|
||||
|
||||
## 先确认没有问题的部分
|
||||
|
||||
- 需求与 D27 一致:映射挂查询、一行多列、身份列可配置可为空、日期列只是可选身份列、不勾身份列时整条映射一条输入并取第一行、同一身份只追加修订、缺失与非法分开但都为未知、系统异常另记、单位只做已配置乘数与偏移、结论用正常/异常/未知。
|
||||
- 三值真值表与冻结稿 6.1 一致(异常=命中,正常=未命中,未知=信息不足;AND 已有正常即正常,OR 已有异常即异常)。
|
||||
- 安全底线未被突破:未知不创建报警、技术失败不写成正常或未知、本模块不写报警状态,这三条在需求、boundary.md 与计划的 Global Forbidden Scope 中都有明确表述。S4 的 Done Criteria「没有一条测试把执行异常断言成未知」是有效约束。
|
||||
- 身份口径完整:运行号与整行哈希都被排除在身份之外,身份列为空的行不写入输入,值变化只追加修订,相同值不追加(S2 Steps 1~4)。
|
||||
- 权限点没有被编造。需求与计划都只引用既有 `perm:data:emp:watchman.query.*` 写法,把新编码推迟到 S5 并要求先核对规范,与 `auth/access.py` 现状(admin-only 的 datasource/query 节点)一致。已通过 sy-standards 核对版本:`standards://api/permission-nodes` 最新为 1.0.0、`standards://api/api-envelope` 最新为 1.1.0,计划引用的版本号正确。
|
||||
- 门禁设置正确:S1 为 `gateClass: high-risk` + `risk_score: 4`,计划把「计划 critic 通过」写成 S1 的前置依赖,context-pack 的 Stop Conditions 明确 autonomous 不取消 critic、不取消 `risk_score >= 4` 停顿、不取消原型确认与最终验收。`marionettist.config.yaml` 的 `allowTaskOverride: true`,`.task/active.json` 为 `phase: analysis`、`allowedToCode: false`、`lastGate: plan-confirmed-awaiting-critic`,状态自洽。
|
||||
- 切片没有混入报警、场景、Cron、企微、原因分析或任意脚本;S6 原型先于 S7 的顺序和停点成立。
|
||||
- S1 的文件范围是真的:`models/query.py`、`auth/access.py`、`migrations/versions/`(head 为 `20261118_0009`)均存在,S1 Step 4 要对照的「查询当前版本输出列」在 `query_definitions.current_version_no` 与 `query_versions.output_schema` 上确实可取。
|
||||
|
||||
## 阻断项(修订后 S1 才能开始)
|
||||
|
||||
### B1. S1 的建表步骤漏了 tenant_id 与强制 RLS,会破坏既有租户隔离
|
||||
|
||||
证据:`20261117_0004_data_sources.py`、`20261118_0006_query_definitions.py` 对每张业务表都执行 `ENABLE / FORCE ROW LEVEL SECURITY`、建 `tenant_isolation` 策略(`tenant_id = current_setting('app.tenant_id', true)`)并显式 `GRANT` 给 `watchman_app`;`models/query.py` 的两张表都带 `tenant_id`;仓库已有 `tests/test_rls.py`、`tests/test_datasource_rls.py` 守这条线。
|
||||
|
||||
问题:S1 的 Steps 只写了「映射定义、列配置、不可变版本和当前版本指针」,完全没有 `tenant_id`、RLS 策略和授权。按计划字面实现出来的映射表将没有任何租户隔离,任何租户只要拿到 id 就能读写别的租户的映射,而且与 ORM 会话设置 `app.tenant_id` 的现有机制不一致。这是安全边界问题,不是风格问题。
|
||||
|
||||
要求的最小修订:S1 Steps 增加一条「新表均带 `tenant_id`,按 0006 的 `_enable_rls` 同形式启用 FORCE RLS、建 `tenant_isolation` 策略并授权 `watchman_app`」;Validation 增加一条跨租户读写被拒的测试(可仿 `test_datasource_rls.py`);Rollback Notes 补上「向下迁移同时 DROP POLICY」。
|
||||
|
||||
### B2. 「历史版本不可更新、不可删除」没有强制层,也没有对应测试
|
||||
|
||||
证据:`20261118_0007_query_versions_immutable.py` 的文件说明已经写明,0006 当时只靠「服务层拒绝」是不够的(那个 Python helper 在写路径上根本没人调用),所以改成 `REVOKE UPDATE, DELETE` + 语句级 BEFORE UPDATE/DELETE/TRUNCATE 触发器两层强制。
|
||||
|
||||
问题:S1 的 Step 2 写「保存即新版本。历史版本不可更新、不可删除」,Done Criteria 写「版本内容不可改」,但 Steps 没说在哪一层强制,Validation 只有「`uv run pytest` 覆盖本切片」和「`alembic upgrade head` 对空库可升级」。这正是审查项 7 指出的情况:S1 可以在没有任何一条测试证明不可变的情况下被宣布完成,而且很可能重犯 0007 修掉的那个缺陷。
|
||||
|
||||
要求的最小修订:S1 Steps 明确不可变由数据库层强制(沿用 0007 的 REVOKE + 语句级触发器形式);Validation 增加两条具体断言——对历史映射版本执行 UPDATE 被拒、执行 DELETE 被拒;Done Criteria 绑定这两条测试,而不是绑定一句描述。
|
||||
|
||||
### B3. 观测时间与时区在 S1 的列配置 schema 里没有位置,决定晚了就要再改一次高风险迁移
|
||||
|
||||
证据:冻结稿 4.3 要求输入契约能表达「观测时间/统计周期」,并明确「时区不可依赖执行机器隐式默认值」;6.2 要求判定详情展示「自然语言规则、实际值、比较值、命中条件、版本、观测时间和输入依据」。
|
||||
|
||||
问题:S1 的列配置只有「类型、身份布尔标记、乘数与偏移」,没有任何「哪一列是观测时间」的声明位;需求的 Required Behavior 列举试算要展示的内容时也漏了观测时间和输入依据。需求 Assumptions 里有一条「没有观测时间列时用本次试算时间」,但这条不在用户本次确认的五条假设之内,等于是未确认口径。同时,日期时间列与日期时间比较值的时区约定(存 tz-aware 还是裸值、比较时按哪个时区)在需求、S1、S3、S4 里都没有写,冻结稿恰好禁止依赖机器隐式默认。
|
||||
|
||||
为什么必须在 S1 之前定:列配置 schema 和日期时间列的存储形态都是 S1 的表结构。这两件事留到 S4/S5 再决定,就要对一张 `risk_score: 4` 的表再加一次迁移。
|
||||
|
||||
要求的最小修订(二选一,并把选择写进 requirement 的 Assumptions 与 S1 Steps):
|
||||
- 在列配置中增加一个可选的「观测时间列」声明,与身份标记并列;或
|
||||
- 明确记录「本模块不声明观测时间列,判定详情一律使用试算时间」,并作为需要用户点头的口径列出。
|
||||
|
||||
无论选哪一种,都要在 S1 Steps 写死日期时间列与日期时间比较值的时区约定(建议统一 tz-aware 存储、比较前归一),并在 S4 的真值表测试里固定一条跨时区用例。
|
||||
|
||||
## 非阻断警告(S1 可以带着走,但要在指定切片前落实)
|
||||
|
||||
### W1. 空结果(零行)语义缺失 —— S4/S5 之前必须补
|
||||
|
||||
冻结稿 4.3 明确「空结果、单行指标为空、源连接失败是不同情况」,且空结果「不自动代表指标为零、业务正常或报警恢复」。requirement 的 Business Rules、Error Handling、Acceptance Criteria,以及 S4 Steps、S5 Step 3 的响应状态列表,都没有「查询返回零行」这一种。不勾身份列时更直接:没有第一行可取。按现状实现,S4 很可能把零行落成「正常」或笼统的「未知」,两种都踩到冻结稿红线。补法:在 requirement 增加一条明确结论与一条验收标准,并把「空结果」加进 S5 的响应状态枚举。
|
||||
|
||||
### W2. 「当前版本删掉了已选列」在试算侧没有落片 —— S4/S5 之前补
|
||||
|
||||
requirement 的 Data Rules 要求「当前版本去掉了已选列时,映射不能静默继续试算」。S1 Step 4 只覆盖了保存时拒绝,试算时的这条路径没有任何切片负责,S5 Step 3 的响应状态里也没有这一种。请在 S5 的响应状态中增加「映射列在当前查询版本中已不存在」,并在 S4 或 S5 的 Validation 里加一条用例。
|
||||
|
||||
### W3. 同一次结果中多行命中同一身份值,行为未定义 —— S2 之前定
|
||||
|
||||
S2 Step 1 把唯一约束落在「映射 + 身份值」上,但没说同一次试算里两行身份值相同时怎么办(取第一行?按顺序各写一条修订?拒绝?)。这会直接决定唯一约束冲突时的处理,也会影响 M06 的合并口径。请在 S2 开工前写死,并配一条测试。
|
||||
|
||||
### W4. `docs/tasks/INDEX.md` 仍写 PASS/FAIL/UNKNOWN,与 D27 的正常/异常/未知冲突
|
||||
|
||||
INDEX(2026-11-17)M05 验收段写的是「PASS/FAIL/UNKNOWN」,M06 还写「不改原始 FAIL」。按冲突顺序,D27(2026-11-18,用户逐项确认)优先,需求用中文三词是对的。但计划的 Documentation Update Requirement 只列了 `docs/tasks/M05.md` 和 `docs/progress.md`,没有列 INDEX。这会让后续审查者拿 INDEX 当权威。请在 S8 的文档同步里加上修订 INDEX 的 M05/M06 措辞。
|
||||
|
||||
### W5. 「接口也用正常/异常/未知」要区分枚举码与展示文案 —— S5 决定
|
||||
|
||||
D27 的原意是术语统一,不等于要把中文字面量作为线上枚举值或数据库枚举。S5 请对照 `standards://api/api-envelope?version=1.1.0`(最新版,已核)决定是「稳定英文码 + 中文展示文案」还是中文值,并写进 S5 Steps。界面文案保持正常/异常/未知不变。无论选哪种,都不要把三词写死进数据库枚举类型。
|
||||
|
||||
### W6. S5 调用查询预览的路径没有写成步骤
|
||||
|
||||
requirement 允许试算对当前版本做一次只读预览(仅 PostgreSQL/MySQL),但没有任何切片的 Steps 写「复用既有查询预览执行器」。boundary.md 写了「查询执行器只可调用」,建议把这句落到 S5 Steps 里,并顺带明确预览权限点是沿用 `perm:data:emp:watchman.query.preview` 还是另立——仍然按 B 项原则:核对规范,对不上就停,不编码。
|
||||
|
||||
### W7. S1 的 Rollback Notes 不完整,且没有 downgrade 验证
|
||||
|
||||
「向下迁移只删除本切片新增表」漏了策略与触发器(0006 的 downgrade 是先 DROP POLICY 再 drop_table)。另外 Validation 只验 `upgrade head`,没有验 downgrade,而 Rollback Notes 却承诺可回滚。建议要么补一条 downgrade 验证,要么如实写明该命令未运行。
|
||||
|
||||
### W8. RLS 相关测试需要真实 Postgres,环境不具备时必须记 NOT_RUN
|
||||
|
||||
`alembic upgrade head` 与 RLS 用例依赖真实 Postgres(FORCE RLS 在 SQLite 上无意义)。请在 S1 的 Validation 里写明运行环境,命令没真正跑就按 `AGENTS.md` 第 7 条如实记为未运行,不要写成 PASS。
|
||||
|
||||
### W9. autonomous 下 S3 → S4 会自动连推,建议对 S4 另设停点(建议性)
|
||||
|
||||
S4 是 `standard` + `risk_score: 3`,按 autonomous 规则可以在 S3(risk 4)完成后不经确认直接进入。S4 固化的是本模块的核心语义(三值真值表、缺失与非法的区分、第一行与跳过行数)。考虑到 W1、W2、B3 的时区用例都要在 S4 落地,建议在计划里把 S4 之前也写成显式停点,或要求 S4 先把真值表测试提交给审查。这是建议,不是阻断。
|
||||
|
||||
## 放行条件
|
||||
|
||||
按 B1、B2、B3 修订 `implementation-plan.md` 的 S1 Steps/Validation/Rollback Notes,并把 B3 选定的观测时间口径与时区约定回写到 `requirement.md` 的 Assumptions(若选「不声明观测时间列」,该条需用户确认)。这些改完之后 S1 即可开始,W1~W9 按各自标注的切片时点处理。
|
||||
|
||||
---
|
||||
|
||||
# 复审(第二轮)
|
||||
|
||||
- 模式:plan-review 复审
|
||||
- 时间:2026-11-18 晚
|
||||
- 依据:重新完整读取 `requirement.md`、`implementation-plan.md`、`context-pack.md` 当前内容,未沿用上一轮记忆。
|
||||
- 结论:**PASS_WITH_WARNINGS**,**S1 可以开始:是**,无剩余阻断项。
|
||||
|
||||
## 阻断项核验
|
||||
|
||||
**B1(tenant_id 与强制 RLS)已修复。** S1 Step 1 明确「新表都带 `tenant_id`,按 `20261118_0006` 的形式 `ENABLE`/`FORCE ROW LEVEL SECURITY`、建立 `tenant_isolation` 策略,并 `GRANT` 给 `watchman_app`」;Validation 要求跨租户读写被拒的测试;Rollback Notes 要求先 `DROP POLICY`。与 0006 的既有形式一致。
|
||||
|
||||
**B2(不可变版本的强制层与证据)已修复。** S1 Step 2 指明沿用 `20261118_0007`:版本表 `REVOKE UPDATE, DELETE` 加语句级 BEFORE UPDATE/DELETE/TRUNCATE 触发器;Validation 列出 `UPDATE` 被拒、`DELETE` 被拒两条测试;Done Criteria 写成「由数据库拒绝证明,不单靠服务层」。这条堵住了上一轮「S1 可以在零证据下宣布完成」的口子。
|
||||
|
||||
**B3(观测时间与时区)已修复,且位置正确。** 口径写进了 `requirement.md` 的 Data Rules(每条映射最多一列观测时间、不标时用试算时间、观测时间列不自动变身份列;日期时间用带时区值、比较前归一 UTC、无时区视为非法),不再是未确认假设;Required Behavior 补上了「观测时间和输入依据」,与冻结稿 6.2 的判定详情要求对齐;S1 Step 3 与 Done Criteria 承接了 schema 侧,S4 Step 6 有跨时区与无时区用例,AC11 可验收。
|
||||
|
||||
## 非阻断警告核验
|
||||
|
||||
W1 空结果(需求 Required Behavior/Business Rules/API Contract/AC9、S4 Step 5、S5 Step 5)、W2 缺列保存与试算双侧拒绝(Data Rules/AC10、S1 Step 4、S4 Step 7、S5 Step 4)、W3 同次重复身份保留第一行(Business Rules、S2 Step 5)、W4 INDEX 措辞归入 S8(Documentation Update Requirement,含 M06「不改原始异常判定」且声明不改 M06 范围)、W5 英文码加中文文案且不建中文数据库枚举(API Contract、S4 Step 1、S5 Step 3)、W6 复用既有查询预览执行器并先核对预览权限点(S5 Step 1)、W7/W8 downgrade 与真实 PostgreSQL 写进 S1 Validation 且未跑记未运行、W9 S4 显式停点(S4 Execution 段与 context-pack Stop Conditions),均已落实。
|
||||
|
||||
## 本轮新增的非阻断警告
|
||||
|
||||
### R1. S2 新建输入/修订表时没有重复 B1 的 RLS 模式 —— S2 开工前补
|
||||
|
||||
S2 的 Allowed Modification Scope 含「新的输入/修订模型与迁移」,Step 1 的唯一约束已包含租户,说明表上会有 `tenant_id`。但 S2 的 Steps 没有写 `ENABLE`/`FORCE ROW LEVEL SECURITY`、`tenant_isolation` 策略与 `GRANT`,Validation 也没有跨租户被拒用例和真实 PostgreSQL 的 upgrade/downgrade 要求。这是与 B1 同一类的问题,只是落在另一片。S2 是独立的 `risk_score: 4` 停点,不影响 S1 开工,但在 S2 批准前必须按 S1 的写法补齐。
|
||||
|
||||
### R2. S3 规则版本既没有 RLS 模式,也没有 B2 的不可变强制 —— S3 开工前补
|
||||
|
||||
`requirement.md` Data Rules 写「映射和规则各自保存即产生不可变版本」,但数据库层那条只写了「映射版本内容在数据库层禁止更新和删除」,没有覆盖规则版本。对应地,S3 Step 1 只说「保存即不可变版本」,没有 `REVOKE UPDATE, DELETE` 与触发器,也没有 RLS 与 `tenant_id`;S3 Validation 只有四条拒绝非法规则的用例,没有跨租户、`UPDATE` 被拒、`DELETE` 被拒。建议把需求那句改成覆盖映射版本与规则版本,并把 S3 的 Steps/Validation 对齐 S1。
|
||||
|
||||
### R3. 规则里配置的无时区日期时间比较值,是保存时拒绝还是运行时非法,没有写死 —— S3 开工前定
|
||||
|
||||
S1 Step 3 把「无时区值为非法」同时写给了列和比较值,但比较值由 S3 的规则表存储,S3 Step 3 只要求「比较值类型须与列类型相容」。需求 Error Handling 的保存时拒绝清单里也没有这一项,而 AC11 的措辞偏向运行时字段非法。建议明确:人工配置的比较值在保存时拒绝(配置错误应当早失败),行数据里的无时区值在运行时记为非法、结论未知。两者分开写,避免 S3 与 S4 各写一半。
|
||||
|
||||
### R4. S4、S5 的 Validation 行没有跟上新增的步骤和验收标准
|
||||
|
||||
S4 Steps 已覆盖空结果、跨时区、缺列三件事,但 Validation 仍写「覆盖验收标准 4、5、6 的计算部分」,没有点名 AC9、AC10、AC11;S5 Steps 4、5 已列出空结果、重复身份跳过、缺列三种响应状态,但 Validation 仍只有「管理员成功,操作者与查看者拒绝,试算无报警行」。按现状,这些新口径有实现而无门禁。建议把 AC9~AC11 和三种新响应状态分别写进 S4、S5 的 Validation。
|
||||
|
||||
### R5. 零行时是否写入正式输入,没有写明
|
||||
|
||||
「保存试算」会写正式输入,但空结果既不是三种结论也没有行可用。S2 与 S5 都没说零行时不写输入与修订。建议在 S2 加一句「空结果不写输入、不写修订」,避免实现时顺手写一条空身份。
|
||||
|
||||
### R6. `context-pack.md` 有三处与修订后的计划/需求不同步 —— S1 开工前刷新
|
||||
|
||||
这份文件是实现者直接读的,当前落后于另外两份:
|
||||
1. Validation Commands 仍写「迁移:`alembic upgrade head`」,没有 S1 已要求的真实 PostgreSQL 与 downgrade。
|
||||
2. Assumptions 仍写「版本方式、嵌套深度 4、普通试算不落库,用户还没单独点名」,但用户已在 2026-11-18 确认了这几条(含第一行口径与身份值为空的行不形成输入)。保留旧措辞会让后续 Agent 把已确认口径当成待确认。
|
||||
3. Required Behavior 只提中文三词,没有提 `normal`/`abnormal`/`unknown` 接口码、空结果和观测时间。
|
||||
|
||||
这三处都是文档同步,不改变实现方向,但建议在 S1 动工前顺手改掉。
|
||||
|
||||
### R7. 两处措辞小问题(可选)
|
||||
|
||||
S1 的 Goal 一句仍只列「所属查询、选用列、类型、身份勾选、乘数和偏移」,没带观测时间标记,而 Step 3 与 Done Criteria 都有;另外需求说「结论的存储和接口使用稳定英文码」,但没有任何切片说明结论会被落到哪张表(试算是瞬态,修订存的是度量值)。若本模块实际不持久化结论,建议把「存储」二字改成只约束接口,免得 S2 多建一列。
|
||||
|
||||
## 放行结论
|
||||
|
||||
S1 可以按现在的 `implementation-plan.md` 开始。R1、R2、R3、R5 必须在对应切片(S2、S3)批准前落实,R4、R6 建议在 S1 动工前后顺手处理,R7 为可选。S2、S3、S5 仍是 `risk_score: 4` 的独立停点,S4 前有显式停点,这些都不因本次 PASS_WITH_WARNINGS 而放宽。
|
||||
@@ -0,0 +1,24 @@
|
||||
# S1 Review
|
||||
|
||||
- 切片:S1 映射模型与不可变版本
|
||||
- 审查:独立审查,与实现不是同一模型系列
|
||||
- 推荐:PASS_WITH_WARNINGS
|
||||
- 阻断项:无
|
||||
|
||||
## 已核对
|
||||
|
||||
- 三张新表有 `tenant_id`,并启用强制行级安全。
|
||||
- 版本表和列配置表由数据库拒绝 UPDATE/DELETE/TRUNCATE。
|
||||
- 观测时间列最多一列。身份标记和乘数、偏移已保存。
|
||||
- 保存时会拒绝当前查询版本里不存在的列。
|
||||
- 没有接口、权限点、报警表或输入修订表。
|
||||
|
||||
## 警告
|
||||
|
||||
1. 测试只拒绝了版本表的 UPDATE/DELETE,没有对列配置表做同样的拒绝测试。迁移里已经保护了列配置表。
|
||||
2. 外键只核对 id,不核对租户。与查询模块现有写法相同。服务层按当前租户查找父行。
|
||||
3. 观测时间列没有限制必须是日期时间类型。需求只写了最多一列。S4 把该列当时间用之前要补上类型限制。
|
||||
4. 版本指针没有外键,与查询定义的指针方式相同。
|
||||
5. 声明类型和查询输出类型的比较留到试算,不在 S1。
|
||||
|
||||
实现方报告:真实 PostgreSQL 上 `alembic upgrade head`、`downgrade -1` 再升级通过。主 Agent 重跑 `uv run pytest tests/test_mapping_versions.py`:6 passed。审查未重跑测试。
|
||||
@@ -0,0 +1,26 @@
|
||||
# S2 Review
|
||||
|
||||
- 切片:S2 输入身份与修订
|
||||
- 审查:独立审查,与实现不是同一模型系列
|
||||
- 推荐:PASS_WITH_WARNINGS
|
||||
- 阻断项:无
|
||||
|
||||
## 已核对
|
||||
|
||||
- 唯一约束是租户、映射、身份键。度量值和运行号不在键里。
|
||||
- 不勾身份列时使用固定的映射级身份,一批只取第一行。
|
||||
- 勾了身份列时,同一批里同一身份只保留第一行。
|
||||
- 值变化追加修订,相同值不追加。
|
||||
- 两张新表有 `tenant_id` 和强制行级安全。修订行在数据库层拒绝 UPDATE、DELETE、TRUNCATE。
|
||||
- 没有接口、权限点、报警或规则判定。
|
||||
|
||||
## 警告
|
||||
|
||||
1. 身份列只有 `None` 或缺失会跳过。空字符串和纯空格仍会建成输入。需求写的是“身份值为空”,空字符串算不算空,留到下次改这段持久化之前确认。
|
||||
2. 修订表自己的跨租户读写、不勾身份列时的重读、身份值为 `None`,测试里还没有。
|
||||
3. 个别测试按全表取修订行,库里有别的数据时可能拿错行。
|
||||
4. 身份键对类型敏感:数值 `1`、字符串 `"1"` 会变成两个身份。
|
||||
5. 一批里出现不带时区的日期时间时,整批失败。判定阶段才把这种值记为非法。
|
||||
6. `mappings.py` 模块注释仍写着不做输入持久化,和现在的代码不符。
|
||||
|
||||
实现方报告:真实 PostgreSQL 上升级、降一级再升级通过。主 Agent 重跑 `uv run pytest tests/test_mapped_input_revisions.py tests/test_mapping_versions.py`:14 passed。审查未重跑。
|
||||
@@ -0,0 +1,25 @@
|
||||
# S3 Review
|
||||
|
||||
- 切片:S3 规则结构校验
|
||||
- 审查:独立审查,与实现不是同一模型系列
|
||||
- 推荐:PASS_WITH_WARNINGS
|
||||
- 阻断项:无
|
||||
|
||||
## 已核对
|
||||
|
||||
- 规则定义和规则版本带 `tenant_id`,并启用强制行级安全。
|
||||
- 历史规则版本在数据库层拒绝 UPDATE、DELETE、TRUNCATE。
|
||||
- 条件只接受 AND/OR 组和叶子。叶子只有列、运算符、比较值。
|
||||
- 文本和布尔拒绝大小比较。日期时间比较值没有时区时,保存即拒绝。
|
||||
- 深度按根组第 1 层、叶子也算一层,上限 4。空组拒绝。
|
||||
- 保存时不执行用户代码,也没有正常/异常/未知的计算。
|
||||
- 没有接口和权限点。
|
||||
|
||||
## 警告
|
||||
|
||||
1. 运算符如果不是字符串,而是列表或对象,会抛出未处理的类型错误。规则不会保存,但调用方看到的不是校验失败。S5 之前改成先判断类型。
|
||||
2. 深度计数已按上面的口径写进需求。还缺一条“刚好 4 层可以保存”的测试。
|
||||
3. 拒绝测试大多只断言抛了校验错误,没有断言原因。布尔列的大小比较、列不在当前映射版本里、组运算符非法,都还没有对应用例。
|
||||
4. 规则版本没有记下校验时所对照的映射版本。试算前仍要再核对列是否还在。
|
||||
|
||||
审查重跑 `uv run pytest tests/test_rule_versions.py`:8 passed。主 Agent 重跑 S1 至 S3 共 22 passed。迁移升级和降级由实现方在真实 PostgreSQL 报告通过,审查未重跑。
|
||||
@@ -0,0 +1,26 @@
|
||||
# S4 Review
|
||||
|
||||
- 切片:S4 正常/异常/未知计算
|
||||
- 审查:独立审查,与实现不是同一模型系列
|
||||
- 推荐:PASS_WITH_WARNINGS(第三次复审)
|
||||
- 阻断项:无
|
||||
|
||||
## 过程
|
||||
|
||||
第一次审查为 BLOCKED:真值表覆盖不足,缺列检查只看规则列,比较中的意外错误被写成未知。修复后第二次仍为 BLOCKED:浮点行值乘以 Decimal 乘数会抛错。第三次复审关闭了这个问题。
|
||||
|
||||
## 已核对
|
||||
|
||||
- 结论码是 `normal`、`abnormal`、`unknown`。零行是 `empty`。缺映射列是 `error`,并给出列名。
|
||||
- AND/OR 的未知组合、等值边界、缺失和非法的字段状态都有测试。
|
||||
- 配置了乘数或偏移时,整数和浮点先转成 Decimal 再运算。非有限数值是非法,结论为未知。
|
||||
- 没有写报警,没有迁移。
|
||||
|
||||
## 警告
|
||||
|
||||
- 还没有用例证明“配置的比较值非法时会抛出,而不是返回未知”。
|
||||
- 多行且有身份列时,顶层结论只代表第一行。
|
||||
- 条件树的运算符若不是 `and`,计算函数会按 OR 处理。保存规则时已经拒绝这种树。
|
||||
- 函数说明仍写着只检查规则列,代码已经检查全部映射列。
|
||||
|
||||
主 Agent 重跑 `uv run pytest tests/test_judgment.py`:12 passed。审查同样重跑 12 passed。
|
||||
@@ -0,0 +1,26 @@
|
||||
# S5 Review
|
||||
|
||||
- 切片:S5 接口与权限
|
||||
- 审查:独立审查,与实现不是同一模型系列
|
||||
- 推荐:PASS_WITH_WARNINGS(复审)
|
||||
- 阻断项:无
|
||||
|
||||
## 过程
|
||||
|
||||
第一次审查为 BLOCKED:查询试算没有提交,预览审计会丢;规则版本保存不核对规则是否属于地址里的映射。两处已改,复审通过。
|
||||
|
||||
## 已核对
|
||||
|
||||
- 权限点是 `perm:data:emp:watchman.mapping.read`、`write`、`trial`,只放行 `watchman-admin`。
|
||||
- 贴入样例的试算不写正式输入,也不要求查询预览权限。
|
||||
- 重跑当前查询的试算同时要求映射试算和既有查询预览权限,并调用既有预览。失败时结果是错误,不是正常或未知。预览之后会提交,审计记录保留。
|
||||
- 规则不属于该映射时,保存版本返回 404。
|
||||
- 没有新角色,没有报警写入,没有新的 SQL 执行器。
|
||||
|
||||
## 警告
|
||||
|
||||
- 保存规则版本时先按未加锁的读取核对归属,并发保存同一条规则可能得到 500,唯一约束仍会挡住重复行。
|
||||
- 规则 id 不是合法 UUID 时,可能是 500 而不是 404。
|
||||
- 接口测试只有 2 个用例,没有覆盖 SQL Server 拒绝和只读路由的 403。
|
||||
|
||||
主 Agent 与审查都重跑了 `uv run pytest tests/test_mapping_api.py`:2 passed。
|
||||
@@ -0,0 +1,23 @@
|
||||
# S7 Review
|
||||
|
||||
- 切片:S7 正式页面,以及判断规则并入映射版本
|
||||
- 审查:独立审查
|
||||
- 推荐:BLOCKED(第三次)
|
||||
- 已用复查次数:3
|
||||
|
||||
## 已成立
|
||||
|
||||
- 映射版本上有 `condition_tree`,保存时字段和条件在同一个新版本里。
|
||||
- 激活只改当前版本号,不新增版本。
|
||||
- 列表没有「判断规则」按钮。
|
||||
- 打开已有版本时会读服务端的当前版本,试算提交的是页面上的 JSON 行。
|
||||
|
||||
## 仍阻断
|
||||
|
||||
新建映射还没有版本。详情页把空的当前版本当成 0 去读取,请求失败后,页面上仍留着写死的列 `n` 和条件 `n eq 1`。这时点「另存为新版本」会把这份占位内容存成 v1。
|
||||
|
||||
## 修复后复审
|
||||
|
||||
推荐:PASS_WITH_WARNINGS。
|
||||
|
||||
新建映射没有版本时,不再请求版本 0。初始字段来自该查询的输出列,页面里不再有占位列 `n`。`seed.spec.ts` 通过。编辑页是否跳过版本加载,还没有组件测试。
|
||||
@@ -0,0 +1,30 @@
|
||||
# S8 模块审查
|
||||
|
||||
- 推荐:PASS_WITH_WARNINGS(修复后复审)
|
||||
- 第一次为 BLOCKED:数值字符串比较、粘贴试算不核对查询列、ISO 时间被判非法、条件组重开被清空。
|
||||
- 修复后复审通过。
|
||||
|
||||
## 已核对
|
||||
|
||||
- 正常、异常、未知、空结果、执行失败分开。
|
||||
- 字段和判断条件存在同一个映射版本。激活不新增版本。
|
||||
- 列表没有「判断规则」按钮。
|
||||
- 新建映射不请求版本 0,不用占位列 `n`。
|
||||
- 管理员权限、行级安全和版本不可改仍在。
|
||||
|
||||
## 警告
|
||||
|
||||
- 比较值留空时,页面会提示保存失败。
|
||||
- 组合条件用「并且/或者」和一条条条件编辑,不再用 JSON 文本框。
|
||||
- 列表总数会跟着名称和查询筛选走。
|
||||
- 试算会显示「采用第一行,跳过 N 行」。
|
||||
- Playwright 已跑通,截图在 `docs/evidence/M05/ui/`。
|
||||
- 旧的独立规则版本接口还在,新页面不用它。
|
||||
- 映射 Playwright:1 passed。截图:trial-normal.png、trial-abnormal.png、trial-unknown.png、trial-first-row.png。
|
||||
|
||||
## 测试
|
||||
|
||||
- `uv run pytest tests/test_judgment.py tests/test_mapping_api.py tests/test_rule_versions.py tests/test_mapping_versions.py`:28 passed。
|
||||
- `pnpm test:unit`:95 passed。
|
||||
- 全量 `uv run pytest`:3 个数据源列表用例失败,失败点是新建记录不在返回的第一页,不是本模块断言。
|
||||
- Playwright:未运行。
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"taskId": "2026-11-18/m05-mapping-rules",
|
||||
"module": "M05",
|
||||
"title": "字段映射与规则判断模块",
|
||||
"type": "feature",
|
||||
"tier": "L",
|
||||
"phase": "done",
|
||||
"allowedToCode": false,
|
||||
"currentSlice": "S8",
|
||||
"proposedNextSlice": null,
|
||||
"lastGate": "user-closed-done-local",
|
||||
"status": "DONE_LOCAL",
|
||||
"gatePolicy": {
|
||||
"selected": "autonomous",
|
||||
"effective": "autonomous",
|
||||
"recommended": "strict",
|
||||
"finalApprovalRequired": true,
|
||||
"allowTaskOverride": true,
|
||||
"overrideReason": "用户在任务入口明确指定 autonomous"
|
||||
},
|
||||
"gates": {
|
||||
"requirementFrozen": true,
|
||||
"planApproved": true,
|
||||
"contextPackReady": true,
|
||||
"criticPassed": true,
|
||||
"implementationDone": true,
|
||||
"reviewPassed": true,
|
||||
"validationPassed": true
|
||||
},
|
||||
"notes": [
|
||||
"User confirmed the plan on 2026-11-18 with 继续, including the listed assumptions.",
|
||||
"Plan critic recheck PASS_WITH_WARNINGS. S1 may start. S2/S3 must repeat RLS; S3 versions must be immutable in the database."
|
||||
],
|
||||
"updatedAt": "2026-11-19T02:05:00Z"
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
# Module Boundary Summary
|
||||
|
||||
## Module Scope
|
||||
|
||||
- Target area: M06 报警实例、判定关联、人工处理历史、列表/详情 API 与控制台。
|
||||
- Related areas: M05 输入修订与判定;M01 `RunRecord`/审计;M02 角色与会话;后续 M07/M08/M09 的稳定接口边界。
|
||||
- Cross-area impact: M06 消费既有异常事实和合成发布快照,不反向修改 M05,也不创建场景、调度、通知或次数策略。
|
||||
|
||||
## Modifiability
|
||||
|
||||
- Modifiable: `services/watchman` 新增 alarms 模型/服务/路由/迁移/测试;`auth/access.py`、`auth/principal.py` 的已批准报警权限接入;`api/app.py` 路由注册;`web/apps/console` 新增报警页面、路由、四语言、测试;M06 任务与证据文档。
|
||||
- Restricted areas: M05 模型只可引用,不可改写身份或判定语义;M01 通用审计/运行记录只可复用;共享权限、路由、模型导出与迁移目录必须串行修改。
|
||||
- Forbidden areas: M07 企微和真实消息;M08 场景/Cron/正式发布实体;M09 次数窗口/升级;可编排工作流引擎;自动恢复;转派/重开/审批;生产库、真实外发、凭证、`.env.local`、`.cursor/mcp.json`、未授权提交。
|
||||
|
||||
## Loaded Context
|
||||
|
||||
- Rules: `AGENTS.md`、Marionettist workflow、sy-standards workspace rules。
|
||||
- Docs: 冻结稿第 7、8、10、13、15 章,`docs/decisions.md` D05/D19/D20/D22/D25/D27/D28/D32~D35,`docs/tasks/INDEX.md`、`CHECKLIST-v1.md`、M05 交接、测试计划。
|
||||
- Standards: `api-envelope?version=1.1.0`、`error-handling?version=1.1.1`、`permission-nodes?version=1.0.0`、`frontend-stack?version=2.1.0`、`element-plus?version=1.0.2`、`code-comments?version=1.1.1`、`security/red-line?version=1.1.0`。
|
||||
|
||||
## Dependency Direction
|
||||
|
||||
`MappedInputRevision`/正式异常事实 + 合成场景发布快照 → 报警 occurrence → 报警实例 → 追加式处理记录 → API → UI。M07/M09 以后读取报警身份和关闭有效性;M06 不依赖它们的表或执行器。M08 正式发布就绪后按 requirement「M08 收尾备注」替换合成快照路径。
|
||||
|
||||
## Boundary Risks
|
||||
|
||||
- 正式 occurrence 必须与试算隔离(D35)。
|
||||
- 合成快照只做最小字段;不得建正式场景表(D35 + M08 收尾)。
|
||||
- 处理范围来自合成快照声明,禁止默认 operator 全租户(D35)。
|
||||
- 报警创建/合并、并发接手/关闭需要 PostgreSQL 唯一约束、行锁或乐观并发;SQLite 或纯 Mock 不足以验收。
|
||||
- 公司权限规范禁止编造权限点;编码与注册方式必须在权限切片先核对。
|
||||
- 公司信封建议 cursor 分页,但 D25 已确认本项目业务列表使用 `page/page_size`;M06 沿用项目契约。
|
||||
|
||||
## Recommended Modification Path
|
||||
|
||||
1. 建报警/occurrence/判定引用与历史关联,数据库强制租户隔离和幂等。
|
||||
2. 建正向状态服务和追加式处理记录,再接后端权限与快照范围。
|
||||
3. 接只读与命令 API;写命令要求幂等键并返回明确冲突。
|
||||
4. 原型确认后实现 Vue,最后做模块整体审查、正式测试与视觉证据。
|
||||
|
||||
## Uncertainty
|
||||
|
||||
- 无阻塞业务不确定性。表名和合并键字段布局可在 S1 按现有模型风格落地,但不得扩大到可编排工作流或 M08 正式场景表。
|
||||
- 权限点字面值不是可照邻近模块编造的实现细节。S3 必须先对照 `standards://api/permission-nodes?version=1.0.0` 与仓库已有节点;规范和仓库都没有报警权限点时停止并询问。
|
||||
- 「处理范围」只确认了来源和缺省拒绝。字段布局未冻结,不得写成新的已确认授权模型。
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
# Task Context Pack
|
||||
|
||||
## Task Goal
|
||||
|
||||
实现 M06 报警创建/有限合并、列表/详情、接手、进展、关闭、新周期关联和 UI;不发送真实消息。
|
||||
|
||||
## Knowledge Posture
|
||||
|
||||
- Mode: `standard`
|
||||
- Maturity: `L1`
|
||||
|
||||
## Current Slice Or Group
|
||||
|
||||
无已批准编码片。提议下一片为 S1;requirement 已冻结(D32~D35),等待 plan-review critic 与分析→编码确认;`allowedToCode=false`。
|
||||
|
||||
## Gate Policy
|
||||
|
||||
- Config Default: `balanced`
|
||||
- Recommended: `strict`
|
||||
- Selected / Effective: `autonomous`
|
||||
- finalApprovalRequired: `true`
|
||||
- Policy Notes: 用户选择覆盖默认,但不取消分析确认、Tier L critic、`risk_score >= 4`、原型确认和最终批准。
|
||||
|
||||
## Requirement Source
|
||||
|
||||
`.task/2026-11-19/m06-alarm-center/requirement.md`(已冻结)
|
||||
|
||||
## Implementation Source
|
||||
|
||||
`.task/2026-11-19/m06-alarm-center/implementation-plan.md`(待 plan critic / 编码前门禁批准)
|
||||
|
||||
## Involved Modules Or Areas
|
||||
|
||||
M05 输入修订/判定、M01 审计/运行、M02 会话角色、新报警领域、控制台。
|
||||
|
||||
## Loaded Context
|
||||
|
||||
### Global Rules
|
||||
|
||||
- `AGENTS.md`
|
||||
- `.cursor/rules/workflow-rules.mdc`
|
||||
- `.cursor/rules/sy-standards.mdc`
|
||||
- `.cursor/rules/00-repository-rules.mdc`
|
||||
|
||||
### Knowledge Map Matches
|
||||
|
||||
- 产品范围与进度:`docs/progress.md`、`docs/decisions.md`、冻结稿、INDEX。
|
||||
- 公司规范与 Marionettist:workflow 与 sy-standards。
|
||||
- 控制台界面:`docs/current/frontend-ui.md`。
|
||||
|
||||
### Path-Proximity Rules
|
||||
|
||||
目标源码路径向上只有仓库根 `AGENTS.md`,未发现更近的 `MODULE_RULES.md` 或 `HARNESS_RULES.md`。
|
||||
|
||||
### Excluded Context
|
||||
|
||||
未加载 M07 企微实现、M08 Cron 复用、M09 次数策略、阶段 B/C 细节;它们不属于当前实现范围。
|
||||
|
||||
## Loaded Rules And Standards
|
||||
|
||||
- `standards://api/api-envelope?version=1.1.0`
|
||||
- `standards://api/error-handling?version=1.1.1`
|
||||
- `standards://api/permission-nodes?version=1.0.0`
|
||||
- `standards://frontend/frontend-stack?version=2.1.0`
|
||||
- `standards://frontend/element-plus?version=1.0.2`
|
||||
- `standards://engineering/code-comments?version=1.1.1`
|
||||
- `standards://security/red-line?version=1.1.0`
|
||||
|
||||
## Loaded Docs
|
||||
|
||||
- `需求冻结文档_V1.1_交接稿.md`
|
||||
- `docs/tasks/INDEX.md`、`docs/tasks/CHECKLIST-v1.md`
|
||||
- `docs/decisions.md`、`docs/testing-plan.md`
|
||||
- `docs/current/frontend-ui.md`
|
||||
- M05 requirement、context、boundary、implementation plan
|
||||
|
||||
## Execution Mode
|
||||
|
||||
- Mode: sequential
|
||||
- Current Slice Or Group: none
|
||||
- Parallel Members: none
|
||||
- Fallback Order: S1 → S2 → S3 → S4 → S5 → S6
|
||||
- Shared Files: migrations、model exports、auth、API app、router、locales
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Resolution Rule: 共享文件和迁移串行;不得覆盖任务开始前的未提交修改。
|
||||
- Validation Level: analysis only / NOT_RUN
|
||||
|
||||
## Execution Chain
|
||||
|
||||
正式异常事实 → occurrence 幂等 → 报警创建/有限合并 → 追加式人工状态历史 → API 权限 → 原型 → Vue → 整体 review/正式验证。
|
||||
|
||||
## Allowed Modification Scope
|
||||
|
||||
当前仅任务文档、`docs/tasks/M06.md`、`docs/progress.md`、`.task/active.json`。编码获批后按 implementation-plan 当前片逐片开放。
|
||||
|
||||
## Forbidden Modification Scope
|
||||
|
||||
当前禁止所有业务源码。全任务禁止 M07/M08/M09、真实消息、自动恢复、转派/重开/审批、生产库、凭证、未授权提交,以及覆盖既有工作区修改。
|
||||
|
||||
## Key Existing Classes Or Entrypoints
|
||||
|
||||
- M05:`models/mapping.py` 的 `MappedInput`/`MappedInputRevision`;`services/judgment.py` 的纯 `evaluate_rows`;`api/routes/mappings.py` 仅试算。
|
||||
- M01:`models/platform.py` 的 `RunRecord`/`AuditEvent`,无场景发布快照。
|
||||
- 权限:`auth/access.py`、`auth/principal.py`;当前角色存在但对象范围仍未实现。
|
||||
- API:`api/app.py` 统一 handler/路由注册。
|
||||
- UI:`web/apps/console/src/router.ts`、`api.ts`、四语言 common/errors。
|
||||
- Alarm skeleton: 未发现。
|
||||
|
||||
## Required Behavior
|
||||
|
||||
以已冻结 requirement 与 D32~D35 为准。
|
||||
|
||||
## Non-goals
|
||||
|
||||
消息发送、场景/Cron、次数/升级、可编排工作流引擎、自动恢复、转派、重开、审批、真实系统联调。
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
见 implementation-plan;当前不执行。
|
||||
|
||||
## Test Strategy
|
||||
|
||||
- Commands: 真实 PostgreSQL migration + pytest;前端 unit/typecheck/build;Playwright U06。
|
||||
- Required Evidence: RLS、幂等、并发创建/接手/关闭、越范围拒绝、试算零报警、V030~V037,以及 V042 的 M06 部分、三视口截图。V038~V041 不属于本模块。
|
||||
- Allowed NOT_RUN Reasons: 本轮为分析与 plan-review,尚未获批编码候选。D32~D35 已冻结,不得再以口径未定跳过以后的 PostgreSQL、RLS 和并发验证。NOT_RUN 不计 PASS。
|
||||
|
||||
## Validation Commands
|
||||
|
||||
- `cd services/watchman && uv run alembic upgrade head`
|
||||
- 隔离 PostgreSQL 上 M06 迁移 downgrade/upgrade
|
||||
- `cd services/watchman && uv run pytest`
|
||||
- `cd web/apps/console && pnpm test:unit`
|
||||
- `cd web/apps/console && pnpm typecheck`
|
||||
- `cd web/apps/console && pnpm build`
|
||||
- `cd web/apps/console && pnpm test:e2e -- alarms.spec.ts`
|
||||
|
||||
## Assumptions
|
||||
|
||||
- 合成数据/Mock 默认;不触达真实 MES 或企微。
|
||||
- D22/D25 和项目现有 `page/page_size` 契约继续适用。
|
||||
- 关闭有效性只由报警终态导出,不创建通知/升级任务、意图行或次数窗口。
|
||||
|
||||
## Risks
|
||||
|
||||
- 正式判定入口缺失,不能复用试算产生副作用。
|
||||
- 场景快照和数据范围缺失会导致跨模块兼容或横向越权。
|
||||
- 数据库唯一约束、RLS 和并发必须在 PostgreSQL 验证。
|
||||
|
||||
## Stop Conditions
|
||||
|
||||
- plan 未批准或 plan-review critic 未通过。
|
||||
- 分析→编码门禁未获用户明确确认,`allowedToCode=false`。`autonomous` 不得跳过 S1~S3 完成后的停顿,也不得在用户确认原型前开始 S5。
|
||||
- 权限点无法按 `standards://api/permission-nodes?version=1.0.0` 与仓库已有节点核对时停止,禁止按 `watchman.*` 邻近模式编造。
|
||||
- M05 `evaluate_rows` 或试算路由写入 occurrence/报警时停止。
|
||||
- 出现通知/升级意图表、次数窗口读写,或撤回已受理消息的命令时停止。
|
||||
- 实现滑向可编排工作流或正式场景表时停止并询问。
|
||||
- S4 原型未确认时禁止 S5。
|
||||
- 最终 `DONE_LOCAL` 需要用户批准。
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
# M06 报警中心与人工处理 Implementation Plan
|
||||
|
||||
## Requirement Source
|
||||
|
||||
`.task/2026-11-19/m06-alarm-center/requirement.md`(已冻结;D32~D35)。编码前仍需 plan-review critic 与分析→编码用户确认。
|
||||
|
||||
## Scope Summary
|
||||
|
||||
报警事实与有限合并、正向人工状态机、追加历史、API、原型确认后的控制台;不发送消息,不实现场景/Cron、次数升级或可编排工作流。
|
||||
|
||||
## Involved Modules Or Areas
|
||||
|
||||
- `services/watchman`:新 alarm 持久化、服务、API、权限、测试。
|
||||
- `web/apps/console`:新报警列表/详情、路由、四语言、单测/Playwright。
|
||||
- 复用:M05 输入修订与版本引用;M01 审计/运行契约;M02 会话角色。
|
||||
|
||||
## Loaded Rules And Standards
|
||||
|
||||
- `AGENTS.md`、Marionettist workflow、workspace rules。
|
||||
- `standards://api/api-envelope?version=1.1.0`
|
||||
- `standards://api/error-handling?version=1.1.1`
|
||||
- `standards://api/permission-nodes?version=1.0.0`
|
||||
- `standards://frontend/frontend-stack?version=2.1.0`
|
||||
- `standards://frontend/element-plus?version=1.0.2`
|
||||
- `standards://engineering/code-comments?version=1.1.1`
|
||||
- `standards://security/red-line?version=1.1.0`
|
||||
|
||||
## Loaded Docs
|
||||
|
||||
- `docs/tasks/INDEX.md`、`docs/tasks/CHECKLIST-v1.md`
|
||||
- `docs/decisions.md`
|
||||
- `需求冻结文档_V1.1_交接稿.md`
|
||||
- `docs/current/frontend-ui.md`、`docs/testing-plan.md`
|
||||
- M05 requirement/context/boundary 及实际 M05 模型、服务、试算路由。
|
||||
|
||||
## Global Forbidden Scope
|
||||
|
||||
- M07 企微/真实消息、M08 场景/Cron/正式发布实体、M09 次数/升级、可编排工作流引擎。
|
||||
- 自动恢复、转派、重开、审批、批量关闭。
|
||||
- 改写 M05 输入/修订/判定事实;把试算当正式异常。
|
||||
- 编造权限点;用前端隐藏替代后端权限;默认 operator 全租户。
|
||||
- 改已合入迁移;生产库/真实外发/凭证/`.env.local`/`.cursor/mcp.json`。
|
||||
- 未授权 Git commit、push 或覆盖任务开始前的工作区修改。
|
||||
|
||||
## Execution Strategy
|
||||
|
||||
- Complexity: complex / Tier L
|
||||
- Default Execution: sequential
|
||||
- Parallel Execution: not-needed
|
||||
- Fallback Execution: sequential
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Resolution Rule: 迁移、`auth/access.py`、`auth/principal.py`、`api/app.py`、前端 router/locales 均串行;后片不得改前片冻结的状态与幂等语义。
|
||||
- Critic: requirement 冻结后、编码前必须 plan-review;高风险片完成 review/validation 后需 pre-done critic;最终仍需 final approval。
|
||||
- Gate Policy: selected `autonomous`。它不取消分析→编码确认。S1、S2、S3 完成后必须暂停(`high-risk` 或 `boundary-sensitive`,且 `risk_score >= 4`,并要求 critic)。S4 写完原型也不等于可进入 S5,必须先有用户原型确认。只有该确认已经发生,且下一片仍是已批准的 `simple`/`standard`、`risk_score <= 3`、无 critic、无其他停顿条件时,才可能按 autonomous 续行。S6 必须暂停,最终批准仍然必需。
|
||||
|
||||
## Slice Dependency Graph
|
||||
|
||||
| Slice | Depends On | Can Run In Parallel With | Fallback Order | Shared Files | Merge Owner | Conflict Risk |
|
||||
|---|---|---|---:|---|---|---|
|
||||
| S1 报警事实与合并 | D32~D35 已确认、requirement 冻结、plan critic PASS | 无 | 1 | migrations/models exports | 主 Agent | high |
|
||||
| S2 人工状态与历史 | S1、D32/D33 | 无 | 2 | migrations/auth | 主 Agent | high |
|
||||
| S3 API 与权限 | S1、S2、权限点核对 | 无 | 3 | auth/app router | 主 Agent | high |
|
||||
| S4 HTML 原型 | S3 稳定响应契约 | 无 | 4 | task prototype | 主 Agent | low |
|
||||
| S5 Vue 报警中心 | S4 用户确认 | 无 | 5 | router/locales | 主 Agent | medium |
|
||||
| S6 模块审查与正式验证 | S1~S5 | 无 | 6 | evidence/progress | 主 Agent | medium |
|
||||
|
||||
## Implementation Slices
|
||||
|
||||
### S1 报警事实、occurrence、有限合并与新周期关联
|
||||
|
||||
- Goal: 用正式异常事实原子创建/关联报警,重复 occurrence 幂等,新独立事件可新建并关联历史。
|
||||
- Allowed Scope: 新 alarm models/services/migration/tests;必要的模型导出;仅引用 M05/M01。
|
||||
- Forbidden Scope: 人工处理 API/UI、M07/M08/M09、修改旧迁移。
|
||||
- Mode: sequential
|
||||
- Depends On: D32~D35;plan critic PASS;分析→编码确认。
|
||||
- Gate Class: `high-risk`
|
||||
- Risk Score: `5`
|
||||
- Gate Reasons: `database-schema`, `alarm-dedup`, `merge-semantics`, `cross-module-contract`
|
||||
- Critic: plan-review 前置;片后 pre-done。
|
||||
- Validation Level: slice
|
||||
- Steps:
|
||||
1. 新表启用/强制 RLS,租户由服务端注入。
|
||||
2. occurrence 稳定幂等键、判定/输入修订/合成快照引用及数据库唯一约束。
|
||||
3. 报警结构化 merge key、有效范围、新事件历史关联。
|
||||
4. 使用事务与锁/约束处理并发创建,不按文本合并。
|
||||
5. PASS/UNKNOWN/执行失败无报警副作用。M05 `evaluate_rows` 与试算路由不得写入 occurrence 或报警。
|
||||
6. 同周期值更正只追加 M05 修订并保留依据;不改写原始 FAIL,不自动新建报警,不自动重发。
|
||||
- Validation:
|
||||
- `cd services/watchman && uv run alembic upgrade head`
|
||||
- 隔离的真实 PostgreSQL 上做 migration downgrade/upgrade、RLS、并发、重复、新周期、同周期修订,以及试算零报警行。SQLite 或纯 Mock 不能当作本片通过。
|
||||
- Done Criteria: V030~V033 数据侧通过;重复提交只产生一个 occurrence。D35 最小快照契约已冻结,实施时不得扩成 M08 正式场景表。
|
||||
- Rollback Notes: 新迁移只新增;已合入后不得改旧迁移,修正用新迁移。
|
||||
|
||||
### S2 正向状态机、处理历史与关闭有效性
|
||||
|
||||
- Goal: `pending -> processing -> closed`、进展追加、并发保护;落实 D36(关闭后同键不重开但留依据/日志);关闭后未执行意图是否仍有效只由报警终态导出。
|
||||
- Allowed Scope: 新 alarm handling service/models/migration/tests;修正 S1 `record_formal_failure` 对已关闭同键的行为以符合 D36。主体判断只用当前处理人与既有三角色,不改权限点常量。
|
||||
- Forbidden Scope: 通知/升级任务表、意图行、次数窗口的读写或清零、撤回已受理消息、直接关闭、转派、重开、自动恢复、可编排工作流。不得注册或编造权限点;本片的主体判断只用当前处理人与既有三角色,权限点字面值留到 S3。
|
||||
- Mode: sequential
|
||||
- Depends On: S1;D32/D33/D35/D36。
|
||||
- Gate Class: `high-risk`
|
||||
- Risk Score: `5`
|
||||
- Gate Reasons: `permissions`, `state-machine`, `concurrency`, `terminal-state`
|
||||
- Critic: 片后 pre-done。
|
||||
- Validation Level: slice
|
||||
- Steps:
|
||||
1. 原子接手并记录唯一当前处理人/接手时间。
|
||||
2. 追加进展,不更新旧记录。
|
||||
3. 校验关闭主体、结果、说明,追加终态记录。
|
||||
4. 并发/重复命令幂等,相同键不同 payload 冲突。
|
||||
5. 关闭有效性只由终态导出:`closed` 表示绑定该报警的未执行意图应视为失效。不落意图行,不提供撤回,不读写、不清零 M09 次数窗口。
|
||||
6. D36:已关闭同合并键再来正式异常时,不重开、不新开;追加可追溯依据和审计日志;更新 S1 相关测试。
|
||||
- Validation: 隔离的真实 PostgreSQL 并发测试覆盖 V034~V037,以及 V042 的 M06 部分(关闭不清零、不建窗口或意图表、新旧报警身份不混淆、无撤回接口);另加 D36 关闭后同键追加依据/日志用例。SQLite 或纯 Mock 不能当作本片通过。V038~V041 不在本片。
|
||||
- Done Criteria: 无双处理人、无矛盾终态;原始异常和历史不可覆盖;D36 有断言。
|
||||
- Rollback Notes: 若实现偏离 D33 的三状态和关闭结果枚举,停止,不另加兼容分支。
|
||||
|
||||
### S3 报警列表/详情/命令 API 与后端授权
|
||||
|
||||
- Goal: 提供分页筛选、详情依据、历史和三类命令,所有读取/操作后端校验。
|
||||
- Allowed Scope: 新 alarm routes/schemas/dependencies/tests;`auth/access.py`、`auth/principal.py`、`api/app.py` 的最小接入。
|
||||
- Forbidden Scope: 新角色名、手写错误 JSON、未核对规范的权限点、前端。
|
||||
- Mode: sequential
|
||||
- Depends On: S1、S2;`permission-nodes` 核对(范围按 D35)。
|
||||
- Gate Class: `boundary-sensitive`
|
||||
- Risk Score: `4`
|
||||
- Gate Reasons: `api-contract`, `permissions`, `object-scope`, `shared-auth-files`
|
||||
- Critic: 片后 pre-done。
|
||||
- Validation Level: slice
|
||||
- Steps:
|
||||
1. 先对照 `standards://api/permission-nodes?version=1.0.0` 和仓库已有节点。报警权限点若规范和仓库都不存在,停止并询问,禁止按 `watchman.*` 邻近模式编造。
|
||||
2. 列表按 D25 后端筛选、排序、`page/page_size`;详情 ID 不得绕过范围。
|
||||
3. 接手/进展/关闭读取 `x-idempotency-key`,service 抛语义异常。
|
||||
4. 冲突复用现有 `ConflictError`(HTTP 409,信封码 40000),不新造业务码 409。越权复用 `ForbiddenError`(42000 加权限点)。字段错误走统一信封;新增错误码同步四语言。
|
||||
- Validation: `cd services/watchman && uv run pytest` 必须打在隔离 PostgreSQL 上,覆盖 admin/operator/viewer、越范围 ID、HTTP 409、幂等和信封。不得用 SQLite 或 Mock 代替授权与租户隔离断言。
|
||||
- Done Criteria: A-040~A-043 API 侧通过;无范围来源时禁止开放 operator。
|
||||
- Rollback Notes: 撤回新路由/依赖,不改变既有角色和查询/映射权限。
|
||||
|
||||
### S4 HTML 原型确认
|
||||
|
||||
- Goal: 在正式 Vue 前确认列表、详情、接手、进展、关闭和冲突反馈。
|
||||
- Allowed Scope: `.task/2026-11-19/m06-alarm-center/prototype/`
|
||||
- Forbidden Scope: `web/apps/console` 正式页面。
|
||||
- Mode: sequential
|
||||
- Depends On: S3 响应字段稳定。
|
||||
- Gate Class: `simple`
|
||||
- Risk Score: `2`
|
||||
- Gate Reasons: `prototype-before-vue`
|
||||
- Critic: no;需用户原型确认。
|
||||
- Validation Level: slice
|
||||
- Steps: 静态走通 U06;核对 D22/D25、非恢复文案、关闭校验与冲突提示。
|
||||
- Validation: 浏览器人工检查三个桌面视口。
|
||||
- Done Criteria: 用户确认原型后才允许 S5。
|
||||
- Rollback Notes: 删除原型不影响产品。
|
||||
|
||||
### S5 Vue 报警中心
|
||||
|
||||
- Goal: 实现报警筛选列表、详情依据、处理历史及接手/进展/关闭交互。
|
||||
- Allowed Scope: `web/apps/console/src/alarms/`、最小 router/nav、四语言、unit/e2e。
|
||||
- Forbidden Scope: 修改后端业务语义、前端伪造授权、通知/升级页面。
|
||||
- Mode: sequential
|
||||
- Depends On: S4 用户确认。
|
||||
- Gate Class: `standard`
|
||||
- Risk Score: `3`
|
||||
- Gate Reasons: `ui-contract`, `confirmed-prototype`, `shared-router-locales`
|
||||
- Critic: no per-slice;仍纳入 Tier L 最终 pre-done。
|
||||
- Validation Level: slice
|
||||
- Steps:
|
||||
1. Element Plus 具名导入,沿用现有 console 骨架与客户端。
|
||||
2. 列表加载/空/无匹配/失败/无权;服务端排序分页。
|
||||
3. 详情展示依据和处理历史;命令 loading、防重复、409 刷新提示。
|
||||
4. 四语言同步,不把服务端 message 直接展示。
|
||||
- Validation:
|
||||
- `cd web/apps/console && pnpm test:unit`
|
||||
- `cd web/apps/console && pnpm typecheck`
|
||||
- `cd web/apps/console && pnpm build`
|
||||
- Playwright U06,1440×900、1280×800、1920×1080。
|
||||
- Done Criteria: A-044~A-047 UI 侧通过,关闭后无误操作且不显示恢复。
|
||||
- Rollback Notes: 撤回新页面、路由与文案,不删后端事实。
|
||||
|
||||
### S6 模块整体审查、正式验证与收口
|
||||
|
||||
- Goal: 对 S1~S5 做独立整体 review、修复复审、正式测试和视觉检查。
|
||||
- Allowed Scope: 切片内缺陷;M06 任务/证据/进度文档。
|
||||
- Forbidden Scope: 借修复扩到 M07/M08/M09;未重审重测即标 DONE。
|
||||
- Mode: sequential
|
||||
- Depends On: S1~S5。
|
||||
- Gate Class: `boundary-sensitive`
|
||||
- Risk Score: `4`
|
||||
- Gate Reasons: `module-acceptance`, `tier-l`, `final-validation`
|
||||
- Critic: reviewer 后 pre-done 必须执行。
|
||||
- Validation Level: final
|
||||
- Steps:
|
||||
1. 高风险两阶段 diff review,重点为幂等、合并、并发、权限、RLS 和边界。
|
||||
2. 修复后复审,最多三次。
|
||||
3. 正式后端、迁移、前端、Playwright 与截图;记录 Mock/未运行/真实阻塞。
|
||||
4. 用户最终批准后才标 `DONE_LOCAL`。
|
||||
- Validation: 下述 Final Validation 全部适用命令。
|
||||
- Done Criteria: reviewer PASS/PASS_WITH_WARNINGS、pre-done critic PASS、验证证据齐全;最终批准仍必需。
|
||||
- Rollback Notes: 迁移缺陷先停并用新迁移修正,不做破坏性回滚。
|
||||
|
||||
## Parallel Slice Groups
|
||||
|
||||
无。迁移、权限、路由和业务语义存在顺序依赖。
|
||||
|
||||
## Final Validation
|
||||
|
||||
- `cd services/watchman && uv run alembic upgrade head`
|
||||
- 隔离 PostgreSQL 上 downgrade/upgrade(仅 M06 新迁移范围)
|
||||
- `cd services/watchman && uv run pytest`
|
||||
- `cd web/apps/console && pnpm test:unit`
|
||||
- `cd web/apps/console && pnpm typecheck`
|
||||
- `cd web/apps/console && pnpm build`
|
||||
- `cd web/apps/console && pnpm test:e2e -- alarms.spec.ts`
|
||||
- 专项:V030~V037,以及 V042 的 M06 部分;U06 三视口;跨租户、越范围、重复/并发命令。RLS、唯一约束和并发接手/关闭只认隔离 PostgreSQL,不认 SQLite 或纯 Mock。V038~V041 不在本模块。
|
||||
|
||||
## Documentation Update Requirement
|
||||
|
||||
- 实施中更新 `docs/tasks/M06.md`、`docs/progress.md` 与 `docs/evidence/M06/summary.md`。
|
||||
- D32~D35 已由用户确认并写入 `docs/decisions.md`。编码时不得把 O04/O05/O06 重新当成未决问题,也不得改写这些已确认结论。
|
||||
- S6 正式验证前,把 `docs/testing-plan.md` 的 V033、V042 期望改成 D34、D32 口径。当前 V042 仍写「不预设窗口是否清零」,不能当作 M06 的测试真源。
|
||||
- 行为/边界意义改变时再评估 current docs 与 knowledge map;仅新增源码不更新 knowledge map。
|
||||
|
||||
## Risks
|
||||
|
||||
- `planApproved=false`,`allowedToCode=false`。plan-review 通过不等于可以写业务代码,仍须用户明确确认分析→编码。
|
||||
- D32~D35 已关闭范围、快照和正式异常契约。未声明的处理范围必须拒绝,禁止回退为 operator 全租户。
|
||||
- M05 只有试算路径。`evaluate_rows` 和试算路由不得产生报警或 occurrence。
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
# Task Intake Result
|
||||
|
||||
## Task Type
|
||||
|
||||
feature。Tier L:M06 是跨数据库、状态机、权限、API 与 UI 的新模块,且 O04/O05/O06 会改变核心业务语义。
|
||||
|
||||
## Tier Policy
|
||||
|
||||
- Active Source: 项目本地 `.marionettist/tier-policy.yml`,结构有效,未使用 fallback。
|
||||
- Selected Tier: L
|
||||
- Description: complex, cross-cutting, boundary-sensitive, or concretely high-risk work。
|
||||
- Match Rules: 多区域、跨边界、工作流敏感;数据库并发、权限及状态终态具有具体高风险。
|
||||
- Workflow Hint: `full-marionettist`
|
||||
- Gate Hint: `prefer-strict`(仅建议)
|
||||
- Review Level: `critic-required`
|
||||
- Model Profile Hint: `think`
|
||||
- minTier / maxTier: `L` / `null`
|
||||
- Warning: `modelProfileHint` 自动交叉校验仍是 deferred hardening;本仓 `.marionettist/model-profiles.yml` 已存在 `think: gpt-5.6-sol`。
|
||||
|
||||
## Current Understanding
|
||||
|
||||
- 前置 M05 已 `DONE_LOCAL`。M06 覆盖 P-006、A-037~A-047。
|
||||
- 范围:报警创建/有限范围合并、列表/详情、接手、进展、关闭、新周期关联和控制台 UI。
|
||||
- 不做:真实消息、M07 企微、M08 场景/Cron、M09 次数窗口/升级。
|
||||
- D05 已确认同一输入不重新触发,关闭后新统计周期或独立事件可以新建并关联历史。
|
||||
- 现有代码没有 alarms 模型、服务、路由或页面。M05 已有 `MappedInputRevision` 与纯试算结论,但没有持久化的正式判定事件。
|
||||
- M01 只有通用 `RunRecord`/审计记录,没有场景发布快照实体。M06 不能顺手建设 M08。
|
||||
- 当前权限只按 Casdoor 三角色判断;`require_object_access` 仍默认拒绝,没有“范围内处理者”的数据范围来源。
|
||||
- 工作区在本任务开始前已有未提交修改;本任务不得覆盖这些修改,也不提交 Git。
|
||||
|
||||
## Gate Policy
|
||||
|
||||
- config/default: `balanced`
|
||||
- allowTaskOverride: `true`
|
||||
- recommended: `strict`(Tier L、迁移、权限、并发状态机和开放业务口径)
|
||||
- selected: `autonomous`
|
||||
- reason or override reason: 用户在 M06 入口明确指定。
|
||||
- effective: `autonomous`
|
||||
- finalApprovalRequired: `true`
|
||||
- policy notes: `autonomous` 不取消分析→编码确认、critic、`risk_score >= 4`、业务阻塞、原型确认或最终批准。
|
||||
|
||||
## Blocking Questions
|
||||
|
||||
1. O04:关闭怎样终结本报警尚未执行的通知/升级意图;已受理消息不可撤回;次数窗口是否继续累计可延后 M09。
|
||||
2. O05:接手/关闭主体、关闭结果枚举、说明要求,以及“范围内”的授权来源。
|
||||
3. O06:同周期值更正对原报警及新报警的影响。
|
||||
4. M01/M08 边界:M06 使用的合成发布快照最小字段与稳定身份尚无现成代码契约。
|
||||
|
||||
## Non-blocking Assumptions
|
||||
|
||||
- 状态仅允许 `pending -> processing -> closed`;不做直接关闭、转派、重开、审批或自动恢复。
|
||||
- 人工操作追加记录,不覆盖原始异常判定、输入修订或旧处理记录。
|
||||
- PostgreSQL、RLS、服务端租户注入、统一信封、四语言与现有 D22/D25 页面布局继续沿用。
|
||||
- 列表分页沿用项目已确认的 `page/page_size`,不在 M06 改造全仓分页协议。
|
||||
|
||||
## Recommended Next Step
|
||||
|
||||
先由用户确认 O04/O05/O06、处理范围来源和合成发布快照契约;随后更新 requirement 为冻结状态,运行 Tier L 计划 critic,再请求跨越分析→编码门禁。
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
# M06 报警中心 · 静态 HTML 原型(S4)
|
||||
|
||||
**状态:待用户确认。确认前不得据此编写 Vue 页面,不得开始 S5。**
|
||||
|
||||
## 如何打开
|
||||
|
||||
用浏览器直接打开本目录的 `index.html`(双击即可)。单文件,无构建、无 CDN、无接口请求。侧栏 logo 使用仓库里的 `web/apps/console/src/assets/logo.jpg`,用相对路径引用;打不开时只少一张图,页面仍可走查。
|
||||
|
||||
路径:`.task/2026-11-19/m06-alarm-center/prototype/index.html`
|
||||
|
||||
刷新页面会回到初始样例。走查改过的数据也可以点原型条上的「还原样例」。
|
||||
|
||||
## 黄色原型条
|
||||
|
||||
顶部黄条不是未来产品,只用于切换角色、主体和画面。正式 Vue 会删掉它。
|
||||
|
||||
- **角色**:管理者 / 处理者 / 查看者。查看者能看列表和详情。接手、进展、关闭会提示无权,并带上对应权限点。
|
||||
- **主体**:`subj-chen`、`subj-lin`、`subj-zhao`,或「无」。无主体时列表为空,文案说明没有处理范围,不是租户里没有报警。
|
||||
- **画面**:样例、加载中、空列表、加载失败、无权、范围外。无权和范围外不看当前角色,用来确认这两种版式。
|
||||
- **模拟**:不模拟 / 接手冲突 / 幂等冲突。后两个会让下一次对应操作失败且不写历史。「再次关闭」只在已经打开一条已关闭报警时有意义。
|
||||
|
||||
## 主要页面
|
||||
|
||||
| 页面 | 内容 |
|
||||
| --- | --- |
|
||||
| 列表 | 模块、场景名称、对象、最近发生起止、状态。点「查询」才筛选,「重置」清空再查。没有等级筛选项,也没有等级列。表头排序对应 `sort_by` / `sort_order`,底栏分页对应 `page` / `page_size`(10 / 20 / 50,默认 20)。行内只有「打开」。没有「新建」。 |
|
||||
| 详情 | 摘要、观测(观测时间 / 计划时间 / 接收时间分列)、判定演示、同周期修订、关闭后依据、处理历史。页脚居中:返回列表、接手、追加进展、关闭。已关闭后页脚只留返回列表。 |
|
||||
| 接手 | 待处理可接手。已有其他处理人时提示冲突,不改当前处理人。管理者也不能把处理人抢走。 |
|
||||
| 进展 | 只有当前处理人能写。说明必填,证据引用选填。 |
|
||||
| 关闭 | 结果只有「已处理 / 误报」,说明必填。待处理不能直接关闭。处理中可由当前处理人或管理者关闭。管理者关闭不替换原来的处理人。 |
|
||||
| 状态 | 加载中、还没有报警、没有符合条件的报警、加载失败(可重试)、无权、没有找到这条报警、没有处理范围。文案是固定中文,不展示服务端原文。 |
|
||||
|
||||
样例是虚构的炉温、气压和尺寸数据。`alm-1003` 已关闭,并且带一条关闭后依据:报警保持已关闭,最近发生和观测次数都不改。页面正文不使用「已恢复」。
|
||||
|
||||
## 和 S3 接口的对应
|
||||
|
||||
列表筛选对应已有参数:`module_key`、`scenario_name`(包含)、`mapped_input_id`、`status`、`occurred_from` / `occurred_to`(按最近发生)。排序字段与 `alarm_reads._SORT` 一致。对象列不排序,因为接口不能按身份键排序。
|
||||
|
||||
详情里的计划时间、规则原文、实际值和比较值**不是**当前接口字段,表格和判定块里写了「演示」。occurrence 接口现有观测时间、接收时间、创建时间。创建时间没有单独做列,避免和计划时间混在一起。
|
||||
|
||||
权限点只用 D38 已有四个,没有新编码:
|
||||
|
||||
- `perm:data:emp:watchman.alarm.read`
|
||||
- `perm:data:emp:watchman.alarm.take`
|
||||
- `perm:data:emp:watchman.alarm.progress`
|
||||
- `perm:data:emp:watchman.alarm.close`
|
||||
|
||||
## 按钮位置
|
||||
|
||||
- 列表的「查询 / 重置」在表格上方。分页在底栏右对齐,不放页面操作。报警没有「新建」。
|
||||
- 行内「打开」留在该行,操作列宽按 1 个链接按钮约 72px。
|
||||
- 详情的返回、接手、进展、关闭在页脚居中,正文滚动时页脚留在滚动区域外面。
|
||||
- 关闭和进展用 480px 对话框。说明没填、关闭结果没选,对话框不关。提交中按钮变为「提交中」并不能再点。
|
||||
|
||||
约定来自 D22、D25 和 `docs/current/frontend-ui.md`。S5 再用 Element Plus 具名组件实现,不要把本页的原生按钮抄进正式页面。
|
||||
|
||||
## 建议走查
|
||||
|
||||
1. 默认管理者、`subj-chen`、样例。改筛选条件先不点查询,列表应不变。再点查询、重置。
|
||||
2. 点「最近发生」切换升降序。底栏仍是分页,不是操作按钮。
|
||||
3. 打开 `alm-1001`。先点关闭,应提示待处理不能直接关闭。再接手、追加进展(空说明应被拦住)、关闭(不选结果、不填说明应被拦住;选「已处理」并填写后变为已关闭)。页脚不再提供接手和关闭。
|
||||
4. 切到处理者 `subj-zhao`,打开 `alm-1002`(当前处理人是 `subj-lin`)。接手、进展、关闭都应被拒绝,处理人不变。
|
||||
5. 切回管理者,打开同一条,关闭对话框应能打开(管理者可以关闭,但不能写进展)。
|
||||
6. 切到查看者,点接手,应看到无权和 `watchman.alarm.take`。列表本身仍在。
|
||||
7. 用原型条看加载中、空列表、加载失败、无权、范围外,以及主体「无」。
|
||||
8. 打开 `alm-1003`,看关闭后依据和三条处理历史。点「再次关闭」,历史条数不应增加。确认页面没有「已恢复」。
|
||||
|
||||
## 三个桌面视口请人眼看
|
||||
|
||||
本片没有跑 Playwright,也没有在浏览器里把窗口改成这三个尺寸。下面是确认时要看的点。黄条会占高度,判断时看黄条下面的产品区域。
|
||||
|
||||
| 视口 | 看什么 |
|
||||
| --- | --- |
|
||||
| 1440×900 | 筛选可以换行,但表格和底部分页仍同时可见。详情页脚的按钮居中,正文往下滚时页脚不跟着走。操作列不撑得很宽。 |
|
||||
| 1280×800 | 黄条换行后,列表底栏和详情页脚仍留在窗口里。筛选换行后表格还看得见表头。表格若放不下,只在表格区域内横向滚动,整页不跟着左右滚。详情事实区仍能读,页脚按钮可以换行,但保持居中。 |
|
||||
| 1920×1080 | 表格拉开后操作列仍大约 72px。筛选控件保持各自宽度,不拉成整行一条。详情卡片随内容区变宽,页脚仍居中。 |
|
||||
|
||||
## 请确认后再做 S5
|
||||
|
||||
1. 列表和详情都不放等级。需求原文写过等级,报警行没有这个字段。S5 在有字段来源之前也不做。
|
||||
2. 计划时间是否只为这次看版式。若 S5 不展示计划时间,详情只保留观测时间和接收时间。
|
||||
3. 规则原文、实际值、比较值是否留到有接口字段再做。S5 可以先只展示观测、依据和处理历史。
|
||||
4. 查看者是继续显示接手 / 进展 / 关闭并在点击后提示无权,还是按角色不显示这些按钮。不显示也不代替后端检查。
|
||||
5. 已关闭后页脚只留「返回列表」。再次关闭的拒绝只在误操作时出现。
|
||||
6. 三种空状态的文案:还没有报警;没有符合条件的报警;没有处理范围所以看不到报警。
|
||||
7. 管理者可以关闭他人已接手的报警,不能替换处理人,也不能代写进展。
|
||||
|
||||
## 不包含
|
||||
|
||||
- `web/apps/console` 正式页面、后端、M07 / M08 / M09。
|
||||
- 真实请求、等级、转派、重开、审批、通知和次数升级。
|
||||
- 四语言。原型只有简体中文。
|
||||
@@ -0,0 +1,910 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Watchman M06 报警中心 · 静态原型(S4)</title>
|
||||
<style>
|
||||
:root {
|
||||
--primary: #5e6ad2; --primary-soft: #eef0fb; --text: #1f2328; --text-2: #59636e; --muted: #8b949e;
|
||||
--surface: #ffffff; --soft: #f6f8fa; --border: #d0d7de; --border-2: #eaeef2;
|
||||
--ok: #1a7f37; --ok-bg: #e9f6ec; --warn: #9a6700; --warn-bg: #fff8e1; --err: #cf222e; --err-bg: #fdecee;
|
||||
--radius: 8px;
|
||||
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; height: 100%; }
|
||||
body { font-family: var(--font); font-size: 13.5px; color: var(--text); background: var(--soft); line-height: 1.55; display: flex; flex-direction: column; }
|
||||
button, input, select, textarea { font: inherit; color: inherit; }
|
||||
button { cursor: pointer; }
|
||||
[hidden] { display: none !important; }
|
||||
.proto { flex: none; background: #fffbe6; border-bottom: 1px dashed #d4b106; padding: 8px 16px; display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; font-size: 12.5px; }
|
||||
.proto-title { font-weight: 600; color: #7a5b00; }
|
||||
.proto-group { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
|
||||
.proto-group .lbl { color: #7a5b00; }
|
||||
.proto-btn { border: 1px solid var(--border); background: #fff; border-radius: 6px; padding: 2px 9px; }
|
||||
.proto-btn.on { background: var(--primary); border-color: var(--primary); color: #fff; }
|
||||
.proto-note { flex-basis: 100%; color: #7a5b00; }
|
||||
.shell { flex: 1; min-height: 0; display: flex; }
|
||||
.side { width: 192px; flex: none; background: var(--surface); border-right: 1px solid var(--border-2); padding: 14px 10px; display: flex; flex-direction: column; }
|
||||
.brand { display: flex; align-items: center; gap: 8px; font-weight: 700; font-size: 16px; padding: 4px 10px 14px; }
|
||||
.brand img { width: 28px; height: 28px; object-fit: contain; }
|
||||
.nav-item { padding: 7px 10px; border-radius: 6px; color: var(--text-2); }
|
||||
.nav-item.cur { background: var(--primary-soft); color: var(--primary); font-weight: 600; }
|
||||
.side .who { margin-top: auto; border-top: 1px solid var(--border-2); padding: 12px 10px 4px; color: var(--text-2); font-size: 12.5px; }
|
||||
.side .who .btn { width: 100%; margin-top: 8px; }
|
||||
.main { flex: 1; min-width: 0; display: flex; flex-direction: column; }
|
||||
.top { height: 48px; flex: none; background: var(--surface); border-bottom: 1px solid var(--border-2); display: flex; align-items: center; padding: 0 20px; }
|
||||
.crumb { color: var(--text-2); }
|
||||
.crumb b { color: var(--text); font-weight: 600; }
|
||||
.crumb-btn { border: 0; background: none; padding: 0; color: var(--text-2); }
|
||||
.crumb-btn:hover { color: var(--primary); }
|
||||
.content.fill { flex: 1; min-height: 0; overflow: hidden; display: flex; flex-direction: column; }
|
||||
.content.scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px 20px 24px; }
|
||||
.listpage { flex: 1; min-height: 0; display: flex; flex-direction: column; padding: 16px 20px 0; }
|
||||
.tools { display: flex; flex-wrap: wrap; align-items: flex-end; gap: 8px; margin-bottom: 8px; }
|
||||
.field { display: flex; flex-direction: column; gap: 2px; }
|
||||
.field span { font-size: 12px; color: var(--muted); }
|
||||
.field input, .field select { height: 32px; }
|
||||
.field.w-mod select { width: 132px; }
|
||||
.field.w-name input { width: 160px; }
|
||||
.field.w-obj select { width: 132px; }
|
||||
.field.w-time input { width: 178px; }
|
||||
.field.w-status select { width: 120px; }
|
||||
.btn { height: 32px; border: 1px solid var(--border); background: var(--surface); border-radius: 6px; padding: 0 14px; }
|
||||
.btn.primary { background: var(--primary); border-color: var(--primary); color: #fff; }
|
||||
.btn.link { height: auto; border: 0; background: none; color: var(--primary); padding: 1px 6px; }
|
||||
.btn.tiny { height: 28px; padding: 0 10px; }
|
||||
.btn:disabled { color: var(--muted); background: var(--soft); border-color: var(--border-2); cursor: not-allowed; }
|
||||
.btn.primary:disabled { color: #fff; background: #b9c0ee; border-color: #b9c0ee; }
|
||||
.applied { margin: 0 0 8px; color: var(--text-2); font-size: 12px; }
|
||||
.stage { flex: 1; min-height: 0; overflow: auto; background: #fff; border: 1px solid var(--border-2); border-radius: var(--radius); }
|
||||
.stage.plain { border: 0; background: transparent; display: flex; align-items: center; justify-content: center; }
|
||||
table { width: 100%; border-collapse: collapse; min-width: 1040px; }
|
||||
th { text-align: left; font-weight: 600; color: var(--text-2); background: var(--soft); padding: 9px 12px; border-bottom: 1px solid var(--border-2); position: sticky; top: 0; z-index: 1; }
|
||||
td { padding: 8px 12px; border-bottom: 1px solid var(--border-2); vertical-align: middle; background: #fff; }
|
||||
.sort { border: 0; background: none; padding: 0; font-weight: 600; color: inherit; }
|
||||
.sort.on { color: var(--primary); }
|
||||
.ops { width: 72px; text-align: right; white-space: nowrap; }
|
||||
.pagefoot, .listfoot { flex: none; background: var(--surface); border-top: 1px solid var(--border-2); }
|
||||
.pagefoot { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 8px; padding: 12px 20px; }
|
||||
.listfoot { display: flex; justify-content: flex-end; align-items: center; gap: 8px; padding: 8px 20px; color: var(--text-2); font-size: 12.5px; }
|
||||
.listfoot select { height: 28px; width: auto; }
|
||||
.card { background: var(--surface); border: 1px solid var(--border-2); border-radius: var(--radius); padding: 16px 18px; margin-bottom: 16px; }
|
||||
.card h3 { margin: 0 0 12px; font-size: 14.5px; }
|
||||
.card table { min-width: 720px; }
|
||||
.facts { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px 16px; margin: 0; }
|
||||
.facts div { min-width: 0; }
|
||||
.facts dt { color: var(--muted); font-size: 12px; }
|
||||
.facts dd { margin: 2px 0 0; }
|
||||
.tag { display: inline-block; padding: 0 8px; border-radius: 10px; font-size: 12px; line-height: 20px; }
|
||||
.tag.pending { background: var(--warn-bg); color: var(--warn); }
|
||||
.tag.processing { background: var(--primary-soft); color: var(--primary); }
|
||||
.tag.closed { background: var(--soft); color: var(--text-2); border: 1px solid var(--border-2); }
|
||||
.tag.ok { background: var(--ok-bg); color: var(--ok); }
|
||||
.tag.warn { background: var(--warn-bg); color: var(--warn); }
|
||||
.banner { border-radius: var(--radius); padding: 8px 12px; margin-bottom: 12px; }
|
||||
.banner.ok { background: var(--ok-bg); border: 1px solid #b7e0c2; color: #145c2a; }
|
||||
.banner.warn { background: var(--warn-bg); border: 1px solid #f1dc9a; color: var(--warn); }
|
||||
.banner.err { background: var(--err-bg); border: 1px solid #f4b8be; color: var(--err); }
|
||||
.empty { text-align: center; padding: 48px 20px; }
|
||||
.empty h3 { margin: 0 0 6px; font-size: 15px; }
|
||||
.empty p { margin: 0; color: var(--text-2); }
|
||||
.hint { color: var(--muted); font-size: 12px; margin: 8px 0 0; }
|
||||
.mono { font-family: ui-monospace, Consolas, monospace; font-size: 12.5px; }
|
||||
.judge { margin-top: 10px; padding-top: 10px; border-top: 1px dashed var(--border-2); }
|
||||
.judge + .judge { border-top: 1px dashed var(--border-2); }
|
||||
.spin { width: 22px; height: 22px; border: 2px solid var(--border); border-top-color: var(--primary); border-radius: 50%; animation: spin .8s linear infinite; margin: 0 auto 10px; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
@media (prefers-reduced-motion: reduce) { .spin { animation: none; border-top-color: var(--border); } }
|
||||
.modal-mask { position: fixed; inset: 0; background: rgba(31,35,40,.4); display: flex; align-items: center; justify-content: center; z-index: 20; padding: 16px; }
|
||||
.modal { background: #fff; border-radius: var(--radius); padding: 18px 20px; width: 480px; max-width: 100%; }
|
||||
.modal h3 { margin: 0 0 6px; font-size: 15px; }
|
||||
.modal label { display: block; margin-top: 12px; }
|
||||
.modal label span { display: block; font-size: 12px; color: var(--text-2); margin-bottom: 4px; }
|
||||
.modal textarea { width: 100%; min-height: 96px; resize: vertical; }
|
||||
.modal .choices { display: flex; gap: 16px; margin-top: 4px; }
|
||||
.modal .result-row > span { display: block; font-size: 12px; color: var(--text-2); margin: 12px 0 4px; }
|
||||
.modal .choices label { display: flex; align-items: center; gap: 6px; margin: 0; }
|
||||
.stage.in { border: 0; border-radius: 0; }
|
||||
.modal .actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; }
|
||||
.modal .err { color: var(--err); font-size: 12.5px; margin: 8px 0 0; }
|
||||
input, select, textarea { border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; background: #fff; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="proto">
|
||||
<span class="proto-title">静态原型 · 不是正式页面</span>
|
||||
<span class="proto-group"><span class="lbl">角色</span>
|
||||
<button type="button" class="proto-btn" data-act="role" data-role="admin">管理者</button>
|
||||
<button type="button" class="proto-btn" data-act="role" data-role="operator">处理者</button>
|
||||
<button type="button" class="proto-btn" data-act="role" data-role="viewer">查看者</button>
|
||||
</span>
|
||||
<span class="proto-group"><span class="lbl">主体</span>
|
||||
<button type="button" class="proto-btn" data-act="subject" data-subject="subj-chen">subj-chen</button>
|
||||
<button type="button" class="proto-btn" data-act="subject" data-subject="subj-lin">subj-lin</button>
|
||||
<button type="button" class="proto-btn" data-act="subject" data-subject="subj-zhao">subj-zhao</button>
|
||||
<button type="button" class="proto-btn" data-act="subject" data-subject="">无</button>
|
||||
</span>
|
||||
<span class="proto-group"><span class="lbl">画面</span>
|
||||
<button type="button" class="proto-btn" data-act="screen" data-screen="ready">样例</button>
|
||||
<button type="button" class="proto-btn" data-act="screen" data-screen="loading">加载中</button>
|
||||
<button type="button" class="proto-btn" data-act="screen" data-screen="empty">空列表</button>
|
||||
<button type="button" class="proto-btn" data-act="screen" data-screen="failure">加载失败</button>
|
||||
<button type="button" class="proto-btn" data-act="screen" data-screen="forbidden">无权</button>
|
||||
<button type="button" class="proto-btn" data-act="screen" data-screen="missing">范围外</button>
|
||||
</span>
|
||||
<span class="proto-group"><span class="lbl">模拟</span>
|
||||
<button type="button" class="proto-btn" data-act="sim" data-sim="">不模拟</button>
|
||||
<button type="button" class="proto-btn" data-act="sim" data-sim="claim">处理冲突</button>
|
||||
<button type="button" class="proto-btn" data-act="sim" data-sim="idem">幂等冲突</button>
|
||||
<button type="button" class="proto-btn" data-act="reclose">再次关闭</button>
|
||||
<button type="button" class="proto-btn" data-act="reset-seed">还原样例</button>
|
||||
</span>
|
||||
<div class="proto-note">黄色区域只用于走查,正式页面没有。筛选要点「查询」才生效。关闭只表示人工终态。计划时间列是版式演示,当前接口没有这个字段。</div>
|
||||
</div>
|
||||
<div class="shell">
|
||||
<aside class="side">
|
||||
<div class="brand"><img src="../../../../web/apps/console/src/assets/logo.jpg" alt=""><span>预警平台</span></div>
|
||||
<div class="nav-item">概览</div>
|
||||
<div class="nav-item">数据源</div>
|
||||
<div class="nav-item">查询</div>
|
||||
<div class="nav-item">映射与规则</div>
|
||||
<div class="nav-item cur">报警</div>
|
||||
<div class="who">
|
||||
<div id="who">已登录:管理者</div>
|
||||
<div id="who-sub">主体 subj-chen</div>
|
||||
<button type="button" class="btn" data-act="logout">退出</button>
|
||||
</div>
|
||||
</aside>
|
||||
<div class="main">
|
||||
<div class="top"><div class="crumb" id="crumb">预警平台 / <b>报警</b></div></div>
|
||||
<div class="content fill" id="content"></div>
|
||||
<div class="pagefoot" id="foot" data-testid="alarm-footer" hidden></div>
|
||||
<div class="listfoot" id="listfoot" data-testid="alarm-pagination" hidden></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-mask" id="mask" hidden>
|
||||
<div class="modal" id="modal" role="dialog" aria-modal="true"></div>
|
||||
</div>
|
||||
<script>
|
||||
var NODES = {
|
||||
read: "perm:data:emp:watchman.alarm.read",
|
||||
take: "perm:data:emp:watchman.alarm.take",
|
||||
progress: "perm:data:emp:watchman.alarm.progress",
|
||||
close: "perm:data:emp:watchman.alarm.close"
|
||||
};
|
||||
var MODULES = { furnace: "炉温模块", utility: "公辅模块", quality: "质量模块" };
|
||||
var OBJECTS = { "mi-furnace-01": "炉-01", "mi-comp-02": "空压-02", "mi-part-09": "零件-09" };
|
||||
var ROLE_LABEL = { admin: "管理者", operator: "处理者", viewer: "查看者" };
|
||||
var STATUS_LABEL = { pending: "待处理", processing: "处理中", closed: "已关闭" };
|
||||
var COMMAND_LABEL = { claim: "处理", progress: "追加进展", close: "关闭" };
|
||||
|
||||
function occ(id, observed, planned, received, cycle, rule, actual, expect) {
|
||||
return {
|
||||
id: id, observed_at: observed, planned_at: planned, received_at: received, cycle_key: cycle,
|
||||
mapping_version: "v2", rule_version: "v2",
|
||||
judgment: { rule: rule, actual: actual, expect: expect, hit: true }
|
||||
};
|
||||
}
|
||||
function ev(seq, command, actor, role, handler, from, to, note, result, evidence, at) {
|
||||
return {
|
||||
seq: seq, command: command, actor_subject: actor, actor_role: role, handler_subject: handler,
|
||||
from_status: from, to_status: to, note: note, close_result: result, evidence_ref: evidence, recorded_at: at
|
||||
};
|
||||
}
|
||||
function blankDraft() {
|
||||
return { module: "", scenario: "", object: "", status: "", from: "", to: "" };
|
||||
}
|
||||
function buildSeed() {
|
||||
return [
|
||||
{
|
||||
id: "alm-1001", module_key: "furnace", scenario_key: "furnace-overtemp", scenario_name: "炉温超限",
|
||||
mapped_input_id: "mi-furnace-01", status: "pending", current_handler: null, claimed_at: null, closed_at: null,
|
||||
close_result: null, occurrence_count: 2, first_occurred_at: "2026-11-19T08:00:00+08:00",
|
||||
last_occurred_at: "2026-11-19T08:15:00+08:00", previous_alarm_id: null, snapshot_version_no: 3,
|
||||
cycle_key: "2026-11-19-08", event_key: "evt-1001", opened_at: "2026-11-19T08:00:05+08:00",
|
||||
occurrences: [
|
||||
occ("occ-1001-1", "2026-11-19T08:00:00+08:00", "2026-11-19T07:55:00+08:00", "2026-11-19T08:00:20+08:00", "2026-11-19-08", "炉温大于 80", "91.2", "80"),
|
||||
occ("occ-1001-2", "2026-11-19T08:15:00+08:00", "2026-11-19T08:10:00+08:00", "2026-11-19T08:15:18+08:00", "2026-11-19-08", "炉温大于 80", "93.0", "80")
|
||||
],
|
||||
revision_evidence: [{ id: "ev-1001-1", occurrence_id: "occ-1001-1", recorded_at: "2026-11-19T08:20:00+08:00", mapping_version: "v2", rule_version: "v2", snapshot_version_no: 3 }],
|
||||
closed_basis: [],
|
||||
history: []
|
||||
},
|
||||
{
|
||||
id: "alm-1002", module_key: "utility", scenario_key: "air-pressure", scenario_name: "气压偏低",
|
||||
mapped_input_id: "mi-comp-02", status: "processing", current_handler: "subj-lin",
|
||||
claimed_at: "2026-11-19T08:50:00+08:00", closed_at: null, close_result: null, occurrence_count: 1,
|
||||
first_occurred_at: "2026-11-19T08:40:00+08:00", last_occurred_at: "2026-11-19T08:40:00+08:00",
|
||||
previous_alarm_id: null, snapshot_version_no: 3, cycle_key: "2026-11-19-08", event_key: "evt-1002",
|
||||
opened_at: "2026-11-19T08:40:06+08:00",
|
||||
occurrences: [occ("occ-1002-1", "2026-11-19T08:40:00+08:00", "2026-11-19T08:35:00+08:00", "2026-11-19T08:40:11+08:00", "2026-11-19-08", "气压低于 0.60", "0.42", "0.60")],
|
||||
revision_evidence: [], closed_basis: [],
|
||||
history: [ev(1, "claim", "subj-lin", "operator", "subj-lin", "pending", "processing", null, null, null, "2026-11-19T08:50:00+08:00")]
|
||||
},
|
||||
{
|
||||
id: "alm-1003", module_key: "furnace", scenario_key: "furnace-overtemp", scenario_name: "炉温超限",
|
||||
mapped_input_id: "mi-furnace-01", status: "closed", current_handler: "subj-lin",
|
||||
claimed_at: "2026-11-18T15:00:00+08:00", closed_at: "2026-11-18T16:30:00+08:00", close_result: "resolved",
|
||||
occurrence_count: 1, first_occurred_at: "2026-11-18T14:40:00+08:00", last_occurred_at: "2026-11-18T14:40:00+08:00",
|
||||
previous_alarm_id: null, snapshot_version_no: 3, cycle_key: "2026-11-18-14", event_key: "evt-1003",
|
||||
opened_at: "2026-11-18T14:40:04+08:00",
|
||||
occurrences: [occ("occ-1003-1", "2026-11-18T14:40:00+08:00", "2026-11-18T14:35:00+08:00", "2026-11-18T14:40:09+08:00", "2026-11-18-14", "炉温大于 80", "88.4", "80")],
|
||||
revision_evidence: [],
|
||||
closed_basis: [{
|
||||
id: "basis-1003-1", observed_at: "2026-11-19T07:05:00+08:00", received_at: "2026-11-19T07:05:12+08:00",
|
||||
recorded_at: "2026-11-19T07:05:20+08:00", cycle_key: "2026-11-18-14", event_key: "evt-1003-later"
|
||||
}],
|
||||
history: [
|
||||
ev(1, "claim", "subj-lin", "operator", "subj-lin", "pending", "processing", null, null, null, "2026-11-18T15:00:00+08:00"),
|
||||
ev(2, "progress", "subj-lin", "operator", "subj-lin", "processing", "processing", "已核对现场读数,仍高于阈值。", null, "rec-temp-118", "2026-11-18T15:40:00+08:00"),
|
||||
ev(3, "close", "subj-lin", "operator", "subj-lin", "processing", "closed", "现场已完成处置并复核读数。", "resolved", null, "2026-11-18T16:30:00+08:00")
|
||||
]
|
||||
},
|
||||
{
|
||||
id: "alm-1004", module_key: "quality", scenario_key: "dimension", scenario_name: "尺寸超差",
|
||||
mapped_input_id: "mi-part-09", status: "closed", current_handler: "subj-zhao",
|
||||
claimed_at: "2026-11-17T09:10:00+08:00", closed_at: "2026-11-17T09:40:00+08:00", close_result: "false_positive",
|
||||
occurrence_count: 1, first_occurred_at: "2026-11-17T09:00:00+08:00", last_occurred_at: "2026-11-17T09:00:00+08:00",
|
||||
previous_alarm_id: null, snapshot_version_no: 2, cycle_key: "2026-11-17-09", event_key: "evt-1004",
|
||||
opened_at: "2026-11-17T09:00:08+08:00",
|
||||
occurrences: [occ("occ-1004-1", "2026-11-17T09:00:00+08:00", "2026-11-17T08:55:00+08:00", "2026-11-17T09:00:16+08:00", "2026-11-17-09", "尺寸大于 12.0", "12.4", "12.0")],
|
||||
revision_evidence: [], closed_basis: [],
|
||||
history: [
|
||||
ev(1, "claim", "subj-zhao", "operator", "subj-zhao", "pending", "processing", null, null, null, "2026-11-17T09:10:00+08:00"),
|
||||
ev(2, "close", "subj-zhao", "operator", "subj-zhao", "processing", "closed", "核对后确认是标定漂移,不是工艺异常。", "false_positive", null, "2026-11-17T09:40:00+08:00")
|
||||
]
|
||||
},
|
||||
{
|
||||
id: "alm-1005", module_key: "quality", scenario_key: "dimension", scenario_name: "尺寸超差",
|
||||
mapped_input_id: "mi-part-09", status: "pending", current_handler: null, claimed_at: null, closed_at: null,
|
||||
close_result: null, occurrence_count: 1, first_occurred_at: "2026-11-19T10:05:00+08:00",
|
||||
last_occurred_at: "2026-11-19T10:05:00+08:00", previous_alarm_id: null, snapshot_version_no: 3,
|
||||
cycle_key: "2026-11-19-10", event_key: "evt-1005", opened_at: "2026-11-19T10:05:04+08:00",
|
||||
occurrences: [occ("occ-1005-1", "2026-11-19T10:05:00+08:00", "2026-11-19T10:00:00+08:00", "2026-11-19T10:05:10+08:00", "2026-11-19-10", "尺寸大于 12.0", "12.8", "12.0")],
|
||||
revision_evidence: [], closed_basis: [], history: []
|
||||
},
|
||||
{
|
||||
id: "alm-1006", module_key: "furnace", scenario_key: "furnace-overtemp", scenario_name: "炉温超限",
|
||||
mapped_input_id: "mi-furnace-01", status: "pending", current_handler: null, claimed_at: null, closed_at: null,
|
||||
close_result: null, occurrence_count: 1, first_occurred_at: "2026-11-19T11:20:00+08:00",
|
||||
last_occurred_at: "2026-11-19T11:20:00+08:00", previous_alarm_id: "alm-1001", snapshot_version_no: 3,
|
||||
cycle_key: "2026-11-19-11", event_key: "evt-1006", opened_at: "2026-11-19T11:20:05+08:00",
|
||||
occurrences: [occ("occ-1006-1", "2026-11-19T11:20:00+08:00", "2026-11-19T11:15:00+08:00", "2026-11-19T11:20:12+08:00", "2026-11-19-11", "炉温大于 80", "90.1", "80")],
|
||||
revision_evidence: [], closed_basis: [], history: []
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
var state = {
|
||||
role: "admin",
|
||||
subject: "subj-chen",
|
||||
screen: "ready",
|
||||
view: "list",
|
||||
detailId: null,
|
||||
draft: blankDraft(),
|
||||
applied: blankDraft(),
|
||||
sortBy: "last_occurred_at",
|
||||
sortOrder: "desc",
|
||||
page: 1,
|
||||
pageSize: 20,
|
||||
notice: null,
|
||||
dialog: null,
|
||||
simulate: "",
|
||||
busy: false
|
||||
};
|
||||
var alarms = buildSeed();
|
||||
var submitToken = 0;
|
||||
|
||||
function clone(v) { return JSON.parse(JSON.stringify(v)); }
|
||||
function esc(s) {
|
||||
return String(s == null ? "" : s).replace(/[&<>"]/g, function (c) {
|
||||
return { "&": "&", "<": "<", ">": ">", '"': """ }[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,17 +1,17 @@
|
||||
{
|
||||
"taskId": "2026-11-18/m04-version-activate",
|
||||
"taskId": "2026-11-19/m06-alarm-center",
|
||||
"type": "feature",
|
||||
"phase": "done",
|
||||
"allowedToCode": false,
|
||||
"currentSlice": "S4",
|
||||
"lastGate": "user-approved-done-local",
|
||||
"nextCommand": "start M05 when ready",
|
||||
"currentSlice": "S6",
|
||||
"lastGate": "user-closed-done-local",
|
||||
"nextCommand": "none",
|
||||
"gatePolicy": {
|
||||
"selected": "balanced",
|
||||
"effective": "balanced",
|
||||
"recommended": "balanced",
|
||||
"selected": "autonomous",
|
||||
"effective": "autonomous",
|
||||
"recommended": "strict",
|
||||
"finalApprovalRequired": true,
|
||||
"allowTaskOverride": true
|
||||
},
|
||||
"updatedAt": "2026-11-18T10:31:00Z"
|
||||
"updatedAt": "2026-11-19T07:25:00Z"
|
||||
}
|
||||
@@ -20,9 +20,11 @@
|
||||
|
||||
| 角色 | 选择标准 | 当前真实模型 ID |
|
||||
|---|---|---|
|
||||
| 主 Agent | 长上下文、计划、工具及可靠委派 | 未确认 |
|
||||
| 实现 | 当前环境可用的主流强编码模型;若用户限定 Grok 则选其已获准可用版本 | 未确认 |
|
||||
| Reviewer | 与实现**不同系列**,擅长推理/编码/安全;不能只是同系列不同大小 | 未确认 |
|
||||
| 主 Agent/编排 | 用户指定;`marionettist-builder` | `grok-4.7` |
|
||||
| 需求冻结/任务切片 | 用户指定 GPT Sol;`think` profile、`marionettist-planner` | `gpt-5.6-sol` |
|
||||
| 实现 | 用户指定;`marionettist-coder`、`build` profile | `grok-4.7` |
|
||||
| Reviewer | 用户指定;片审/diff 审查 | `grok-4.7` |
|
||||
| Critic | 用户指定;计划审计/门禁就绪 | `grok-4.7` |
|
||||
| 正式后端测试 | 能准确执行和解释输出,适配测试工具 | 未确认 |
|
||||
| Playwright 执行 | 快速低成本、有工具能力,需要看图时具视觉能力 | 未确认 |
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
| D05 | 同一输入不重新触发;关闭后新统计周期/新独立事件可新建并关联历史 | 本轮第 5 点 |
|
||||
| D06 | 目录 D:\PROJECT\watchman,授权 git init;本轮先规划不写业务代码 | 本轮第 6 点及任务要求 |
|
||||
| D07 | 主 Agent 把控,子 Agent 开发、独立 review 和测试;过程在 docs。原小片粒度由 D10 调整 | 用户补充要求及后续修订 |
|
||||
| D08 | 实现用强编码模型,review 用不同系列强模型,浏览器可快速便宜模型 | 用户补充方向,具体型号尚未指定 |
|
||||
| D08 | 实现用强编码模型,浏览器可快速便宜模型;review 模型见 D29 | 用户补充方向;review 具体型号由 D29 指定 |
|
||||
| D09 | MES 通过配置,不做客户核心定制;大屏独立、能力模块为流程/指标/视频 | 前轮用户明确答复 |
|
||||
| D10 | 以功能模块为大任务,一个会话聚焦一个大任务;Agent 可自主拆小步骤逐步实现,不再由用户管理 133 小片 | 2026-11-17 用户修正 |
|
||||
| D11 | Cron 编辑和调度优先复用开源库/框架,不自行开发通用编辑器和调度引擎 | 2026-11-17 用户要求及本轮公开资料核查 |
|
||||
@@ -32,19 +32,33 @@
|
||||
| D24 | M04:查询正文采用参数化 SQL 模板(命名参数绑定;不可绑标识符白名单;不靠 SELECT 前缀)。本轮交付不可变查询版本(草稿可编辑,publish 生成只读快照;库级禁止 UPDATE/DELETE)。正式定时/场景采集留给 M08;本轮含定义 CRUD、版本、只读预览与配套 UI。执行必须经 M03 usable/熔断。仅 watchman-admin。正式 Vue 前须确认 HTML 原型。SQL Server 本轮不做查询试跑(无服务端强制只读会话),连接测试仍可用;预览仅 PostgreSQL/MySQL | 2026-11-18 用户确认 1=A、2b 及 Marionettist 计划;审查复审后收紧 SQL Server 与版本不可变 |
|
||||
| D25 | 控制台业务列表默认:表格上方有筛选条件(至少名称模糊;有类型/归属/状态则一并提供),「查询/重置」按钮提交筛选(禁止输入即筛),「新建」等页面按钮靠右;表头 `sortable=custom` 走后端 SQL 排序并配合分页;操作列按按钮数固定宽度。用户对本页另有说明时从其说明。细则见 `docs/current/frontend-ui.md` | 2026-11-18 用户明确要求;同日补充查询/重置、服务端排序分页、操作列宽 |
|
||||
| D26 | M04 增补:去掉查询「草稿/发布」两步。保存内容即插入下一不可变版本并自动设为 `current_version_no`;可激活任一历史版本为当前生效(详情与列表均可切换)。版本内容仍不可变。`draft_*` 列本轮保留并镜像 current,对外 API/UI 不暴露 draft。权限沿用既有 query write/publish,不新造权限点 | 2026-11-18 用户确认 1=C、2=A 并批准实现计划 |
|
||||
| D27 | M05:映射和规则挂在查询上,一条查询可有多条映射,一条映射可有多条规则;场景仍归 M08。查询列名即字段,不固定六格;一行可有多列指标,规则的每条条件自选列。身份列可配置、可为空,日期只是可选身份列。不勾身份列时整条映射是一条输入,多行取结果顺序的第一行。同一身份的值变化只追加修订。缺失与非法分开记录,结论都是未知;系统异常另记。单位只做已配置的乘数和偏移。条件成立为异常,不成立为正常;界面和接口用正常/异常/未知 | 2026-11-18 用户在 M05 入口逐项确认,最后明确多行默认第一行且身份/日期可配置 |
|
||||
| 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 |
|
||||
| D30 | 需求冻结与任务切片设计使用 GPT Sol:`think` profile 与 `marionettist-planner` 均为 `gpt-5.6-sol`(覆盖 `requirement-freezer`/`implementation-slicer` 的 reasoning 映射) | 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 | 状态 | 问题 | 建议供选择,非默认已批准 | 阻塞 |
|
||||
|---|---|---|---|---|
|
||||
| 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 |
|
||||
| O03 | OPEN | 每一级阈值是累加接收人还是替换?一次越过多级如何发? | 用户举例甲→甲乙→甲乙丙,建议显式配置每级最终目标;默认执行最高新命中级或逐级分别执行需用户选择;达到阈值触发,每级每窗口一次 | P-005、A-050~A-054 |
|
||||
| O04 | OPEN | 已关闭后新事件继续计入窗口吗?关闭时尚未发送的通知怎么办? | 建议关闭终结该报警未执行意图,新事件可新建但窗口次数不被人工关闭清零;任务必须绑定新报警身份;已受理消息不能撤回 | P-006、A-043、A-049、A-051 |
|
||||
| O05 | OPEN | 接手/关闭权限及关闭结果枚举 | 建议范围内处理者可接手,当前处理人或管理者可关闭,结果“已处理/误报”,说明必填;不做转派/重开 | P-006、A-041~A-043 |
|
||||
| O06 | OPEN | 同周期值更正是否更新原报警、是否允许新报警? | 同一输入身份重读不重报已确认;“版本变更”不能随意当新业务事件。建议保留修订记录,不自动重发,实际规则需批准 | P-006、A-023、A-039 |
|
||||
| O04 | CONFIRMED | 见 D32。关闭终结该报警未执行意图;已受理不可撤回;窗口不因关闭清零 | 用户确认建议 | P-006、A-043、A-049、A-051 |
|
||||
| O05 | CONFIRMED | 见 D33。MVP 固定接手/关闭权限与结果枚举;可编排工作流后置 | 用户确认建议并登记后置 | P-006、A-041~A-043 |
|
||||
| O06 | CONFIRMED | 见 D34。同周期更正只追加修订,不自动新报警/重发 | 用户确认建议 | P-006、A-023、A-039 |
|
||||
| O07 | OPEN | 停机漏跑、跨周期任务重叠、启停及改 Cron 后的旧任务 | 建议每场景不并发推进进度,逾期运行有界跳过/显式补跑且不自动补发历史消息;用户需确认具体业务行为 | P-004、A-033~A-036 |
|
||||
| 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 |
|
||||
|
||||
|
After Width: | Height: | Size: 57 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
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 @@
|
||||
|
||||
## 当前快照
|
||||
|
||||
- 当前阶段:M04 查询定义与采集 **DONE_LOCAL**(D24 查询模块 + D25 列表筛选排序 + D26 保存即版本/激活;用户确认可提交)。
|
||||
- 当前大任务:无(M04 已完成)。下一候选:M05(见 `docs/tasks/INDEX.md`)。
|
||||
- 用户授权:D21–D26。收尾任务 `gatePolicy.selected=balanced`。
|
||||
- Git:用户授权 commit/push。
|
||||
- 下一步:按 INDEX 进入 M05。
|
||||
- 当前阶段:M06 **DONE_LOCAL**。
|
||||
- 当前大任务:M06 已关闭。下一步是 M07,尚未开工。
|
||||
- 用户授权:D32–D40。本任务 `gatePolicy.selected=autonomous`。用户已确认最终批准、提交并推送。
|
||||
- Git:候选提交 `47d3b85`(本台账绑定见后续 docs 提交)。
|
||||
- 下一步:M07 开工前另确认。
|
||||
|
||||
## 大任务状态
|
||||
|
||||
@@ -15,10 +15,13 @@
|
||||
| M01 基础框架 | DONE_LOCAL | 实现 Composer;审查/复审异系列 | `8fb16f4` | PASS_WITH_WARNINGS(必改已关) | pytest 23;unit 8;e2e 3 | 已完成 |
|
||||
| M02 统一登录与权限 | DONE_LOCAL | 主 Agent;复审 claude-opus | `f8e1c77` | 复审阻塞已由 D20 关闭 | pytest 58;unit 10;登录 Playwright 4 | 已完成 |
|
||||
| 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/` | 已完成;下一 M05 |
|
||||
| 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/` | 已完成 |
|
||||
| M06 报警中心与人工处理 | DONE_LOCAL | 主 Agent 收尾;审查/critic `grok-4.7` | `47d3b85` | 模块+pre-done 均为 PASS_WITH_WARNINGS | pytest 523;unit 126;e2e 11;截图 `docs/evidence/M06/` | 已完成(本地边界) |
|
||||
|
||||
## 当前阻塞
|
||||
|
||||
- O08:跨系列子 Agent 授权仍开放。
|
||||
- O01–O07:业务口径,不阻塞 M04 已冻结范围(D24/D26)。
|
||||
- O01/O02/O03/O07:仍分别留待 M08/M09。
|
||||
- M06 后置(不阻塞 MVP):可编排人工处理工作流;M08 正式发布替换合成快照。
|
||||
- M04:SQL Server 查询试跑本轮明确不做(无服务端只读会话);连接测试仍可用。`draft_*` 列本轮保留镜像、未物理删除。
|
||||
@@ -14,8 +14,8 @@
|
||||
| M02 | 统一登录与权限模块 | M01 | Casdoor/OIDC 接入、后端授权、前端会话、范围及权限测试;真实配置缺失单列 |
|
||||
| M03 | 数据源配置模块 | M02 | 数据源 API+列表/编辑+连接测试、凭证保护及引用提示 |
|
||||
| M04 | 查询定义与采集模块 | M03 | 受控查询、参数与输出契约、只读执行、预览和配套界面;不开放任意脚本 |
|
||||
| M05 | 字段映射与规则判断模块 | M04 | 映射预览、类型/空值、输入身份、结构化规则编辑、PASS/FAIL/UNKNOWN、测试 |
|
||||
| M06 | 报警中心与人工处理模块 | M05 | 报警创建/合并、详情/列表、接手、进展、关闭、新周期规则与 UI;不发送真实消息 |
|
||||
| M05 | 字段映射与规则判断模块 | M04 | 映射预览、类型/空值、输入身份、结构化规则编辑、正常/异常/未知、测试 |
|
||||
| M06 | 报警中心与人工处理模块 | M05 | 报警创建/合并、详情/列表、处理、进展、关闭、新周期规则与 UI;不发送真实消息 |
|
||||
| M07 | 企业微信通知模块 | M06 | 应用和机器人、目标/模板、多目标任务、试发、结果和失败重试、完整 UI |
|
||||
| M08 | 场景配置与 Cron 调度模块 | M05、M07 | 组合场景、草稿/发布/启停、开源 Cron 编辑/解析/定时触发、样例运行;基础正式链可验证 |
|
||||
| M09 | 次数统计与分层通知模块 | M06、M07、M08;次数口径已定 | 计数窗口、阈值及步骤、升级意图、配置预览与记录;不做时间升级 |
|
||||
@@ -54,11 +54,11 @@ M01 基础框架中包含最小授权接口契约,正式登录在 M02;不允
|
||||
### M05 字段映射与规则判断
|
||||
|
||||
- 内部分解示例:映射与转换 → 输入身份 → 条件 schema → 计算器 → 编辑/样例 UI → 边界测试。
|
||||
- 验收:比较边界、AND/OR 缺失真值表、重复输入与新周期;UNKNOWN 不默认报警。规则原因分析不在此模块。
|
||||
- 验收:比较边界、AND/OR 缺失真值表、重复输入与新周期;未知不默认报警。规则原因分析不在此模块。
|
||||
|
||||
### M06 报警中心与人工处理
|
||||
|
||||
- 内部分解示例:报警模型与合并 → 状态服务及权限 → 处理历史 → API/列表/详情 → 接手/关闭 UI → 并发和新周期测试。
|
||||
- 内部分解示例:报警模型与合并 → 状态服务及权限 → 处理历史 → API/列表/详情 → 处理/关闭 UI → 并发和新周期测试。
|
||||
- 验收:待处理→处理中→已关闭;关闭有结果说明;不改原始 FAIL,不伪称恢复;重复事件不重复报,新周期可关联新报警。
|
||||
- 依赖场景发布版本时用 M01 契约中的合成发布快照,不在此顺手实现 M08;整体发布链在 M08/M11 联调。
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# M05 字段映射与规则判断模块
|
||||
|
||||
一个会话聚焦本模块。S1~S8 已审查。用户于 2026-11-19 确认收口,标 DONE_LOCAL。
|
||||
|
||||
## 内部步骤
|
||||
|
||||
- [x] 关闭阻塞口径,冻结需求并切片。
|
||||
- [x] 用户以「继续」确认计划(含版本方式、深度 4、试算不落库、第一行顺序)。
|
||||
- [x] 计划 critic 复审 PASS_WITH_WARNINGS。
|
||||
- [x] S1 映射模型、强制行级安全、版本不可变。审查 PASS_WITH_WARNINGS。
|
||||
- [x] S2 输入身份与修订。审查 PASS_WITH_WARNINGS。
|
||||
- [x] S3 规则结构校验。审查 PASS_WITH_WARNINGS。
|
||||
- [x] S4 正常/异常/未知计算。审查 PASS_WITH_WARNINGS。
|
||||
- [x] S5 接口与权限。审查 PASS_WITH_WARNINGS。
|
||||
- [x] S6 HTML 原型。浏览器点过列表、详情保存、试算、规则和越权拒绝。
|
||||
- [x] S7 正式页面。判断规则与映射同版。新建无版本时用查询输出列。审查 PASS_WITH_WARNINGS。
|
||||
- [x] S8 模块复审 PASS_WITH_WARNINGS。映射相关 pytest 已过;控制台 unit 95 passed。Playwright 1 passed,截图在 `docs/evidence/M05/ui/`。
|
||||
- [x] 用户确认收口,标 DONE_LOCAL。
|
||||
|
||||
## 目标与边界
|
||||
|
||||
- 前置:M04 DONE_LOCAL。
|
||||
- 范围:A-021~A-026。映射预览、类型与空值、输入身份、结构化条件、正常/异常/未知、样例测试。
|
||||
- 明确不做:报警(M06)、场景与 Cron(M08)、原因分析(M12)、任意脚本。
|
||||
- 已确认 D27:映射/规则挂在查询上;列不固定;身份列可空;不勾身份列时多行取第一行;结论用正常/异常/未知。
|
||||
- O06 的报警更新仍归 M06。
|
||||
|
||||
## 证据与结论
|
||||
|
||||
- 证据:`docs/tasks/M05.md`;需求与计划在 `.task/2026-11-18/m05-mapping-rules/`
|
||||
- 状态:DONE_LOCAL。`gatePolicy.selected=autonomous`。
|
||||
@@ -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 |
|
||||
| V031 | 同合并范围持续 FAIL,之后跨范围 | 范围内关联,范围外可新建,历史依据留存 | A-038 |
|
||||
| V032 | 关闭后旧输入重投、新周期新事件到达 | 旧不重报,新可新建并关联历史 | A-039 |
|
||||
| V033 | 同周期源值更正 | 按 O06 最终口径,不因 payload hash 改变乱报 | A-039 |
|
||||
| V033 | 同周期源值更正 | 按 D34:只追加修订/依据,不自动新建报警、不自动重发;不因 payload hash 改变乱报 | A-039 |
|
||||
| V034 | 两人同时接手/重复接手 | 唯一处理人,后到返回冲突或幂等结果 | A-041 |
|
||||
| V035 | 追加进展后再查询 | 原文、操作者、时间不可覆盖 | A-042 |
|
||||
| V036 | 非处理人关闭、缺结果或依据、并发关闭 | 按权限拒绝/提示,只有一个合法终态 | A-043 |
|
||||
@@ -95,7 +95,7 @@ Cron 用例验证“动态配置、正确触发、停用和防重”等业务结
|
||||
| V039 | 两个独立事件并发达到阈值 | 不丢计数,恰好一个同级意图 | A-049、A-050 |
|
||||
| V040 | N-1、N、N+1 次及一次越过多级 | 达到阈值、跳级/逐级按 O03,每级不重复 | A-050 |
|
||||
| V041 | 固定或滑动窗口边界、规则版本变更 | 按批准口径,分组不混、重置有依据 | A-049 |
|
||||
| V042 | 关闭旧报警后窗口内有新事件 | 严格按 O04 最终决定执行;不预设窗口是否清零,旧报警和新报警的任务身份不能混淆 | A-051 |
|
||||
| V042 | 关闭旧报警后窗口内有新事件 | M06 部分按 D32:关闭使绑定旧报警的未执行意图失效;已受理不可撤回;次数窗口不因关闭清零(窗口细则归 M09)。旧报警与新报警身份不得混淆。V038~V041/完整次数升级不在 M06 | A-051 |
|
||||
| V043 | 未满足次数条件但无人响应很久 | 不触发后置的时间升级 | A-050 |
|
||||
| V044 | 预览模拟重复/独立事件序列 | 计数和预计目标清晰,绝无真实发送 | A-053 |
|
||||
|
||||
|
||||
@@ -29,16 +29,16 @@ models:
|
||||
profiles:
|
||||
think:
|
||||
description: "Deep reasoning, planning, and gate decisions"
|
||||
default: "openai/gpt-5.5"
|
||||
fallback: "openai/gpt-5.4"
|
||||
default: "gpt-5.6-sol"
|
||||
fallback: "gpt-5.6-sol"
|
||||
build:
|
||||
description: "Focused coding and implementation from approved task context"
|
||||
default: "openai/gpt-5.3-codex"
|
||||
fallback: "deepseek/deepseek-v4-pro"
|
||||
default: "grok-4.7"
|
||||
fallback: "grok-4.7"
|
||||
review:
|
||||
description: "Reflective, cautious, nuanced review"
|
||||
default: "deepseek/deepseek-v4-pro"
|
||||
fallback: "deepseek/deepseek-v4-pro"
|
||||
default: "grok-4.7"
|
||||
fallback: "grok-4.7"
|
||||
run:
|
||||
description: "Fast utility work such as indexing and validation"
|
||||
default: "deepseek/deepseek-v4-flash"
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
"""Create versioned query mappings with forced tenant isolation.
|
||||
|
||||
Revision ID: 20261118_0010
|
||||
Revises: 20261118_0009
|
||||
Create Date: 2026-11-18
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision: str = "20261118_0010"
|
||||
down_revision: Union[str, None] = "20261118_0009"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
APP_ROLE = "watchman_app"
|
||||
DEFINITIONS = "mapping_definitions"
|
||||
VERSIONS = "mapping_versions"
|
||||
COLUMNS = "mapping_column_configs"
|
||||
FUNCTION = "mapping_versions_reject_mutation"
|
||||
TRIGGER = "trg_mapping_versions_append_only"
|
||||
COLUMN_FUNCTION = "mapping_column_configs_reject_mutation"
|
||||
COLUMN_TRIGGER = "trg_mapping_column_configs_append_only"
|
||||
|
||||
|
||||
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 upgrade() -> None:
|
||||
op.create_table(
|
||||
DEFINITIONS,
|
||||
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(
|
||||
"query_definition_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey("query_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("latest_version_no", sa.Integer(), nullable=True),
|
||||
sa.Column("current_version_no", sa.Integer(), nullable=True),
|
||||
sa.Column("created_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.CheckConstraint(
|
||||
"latest_version_no IS NULL OR latest_version_no >= 1",
|
||||
name="ck_mapping_definitions_latest_version",
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"current_version_no IS NULL OR current_version_no >= 1",
|
||||
name="ck_mapping_definitions_current_version",
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_mapping_definitions_query_definition_id", DEFINITIONS, ["query_definition_id"]
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
VERSIONS,
|
||||
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(
|
||||
"definition_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey(f"{DEFINITIONS}.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("version_no", sa.Integer(), nullable=False),
|
||||
sa.Column("saved_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||
sa.Column("saved_by", sa.String(length=128), nullable=True),
|
||||
sa.UniqueConstraint("definition_id", "version_no", name="uq_mapping_versions_definition_version"),
|
||||
sa.CheckConstraint("version_no >= 1", name="ck_mapping_versions_version_no"),
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
COLUMNS,
|
||||
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(
|
||||
"mapping_version_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey(f"{VERSIONS}.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("source_column_name", sa.String(length=128), nullable=False),
|
||||
sa.Column("value_type", sa.String(length=16), nullable=False),
|
||||
sa.Column("is_identity", sa.Boolean(), server_default=sa.text("false"), nullable=False),
|
||||
sa.Column("is_observation_time", sa.Boolean(), server_default=sa.text("false"), nullable=False),
|
||||
sa.Column("numeric_multiply", sa.Numeric(precision=24, scale=8), nullable=True),
|
||||
sa.Column("numeric_offset", sa.Numeric(precision=24, scale=8), nullable=True),
|
||||
sa.UniqueConstraint(
|
||||
"mapping_version_id",
|
||||
"source_column_name",
|
||||
name="uq_mapping_column_configs_version_source",
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"value_type IN ('number', 'string', 'boolean', 'datetime')",
|
||||
name="ck_mapping_column_configs_value_type",
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"(value_type = 'number') OR (numeric_multiply IS NULL AND numeric_offset IS NULL)",
|
||||
name="ck_mapping_column_configs_numeric_only",
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
"uq_mapping_column_configs_one_observation_time",
|
||||
COLUMNS,
|
||||
["mapping_version_id"],
|
||||
unique=True,
|
||||
postgresql_where=sa.text("is_observation_time"),
|
||||
)
|
||||
|
||||
for table in (DEFINITIONS, VERSIONS, COLUMNS):
|
||||
_enable_rls(table)
|
||||
|
||||
op.execute(f"REVOKE UPDATE, DELETE ON TABLE {VERSIONS} FROM {APP_ROLE}")
|
||||
op.execute(f"GRANT SELECT, INSERT ON TABLE {VERSIONS} TO {APP_ROLE}")
|
||||
op.execute(f"REVOKE UPDATE, DELETE ON TABLE {COLUMNS} FROM {APP_ROLE}")
|
||||
op.execute(f"GRANT SELECT, INSERT ON TABLE {COLUMNS} TO {APP_ROLE}")
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE FUNCTION {FUNCTION}() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'mapping_versions is append-only: saved versions are immutable'
|
||||
USING ERRCODE = 'restrict_violation';
|
||||
END;
|
||||
$$
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE FUNCTION {COLUMN_FUNCTION}() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'mapping_column_configs is append-only: saved versions are immutable'
|
||||
USING ERRCODE = 'restrict_violation';
|
||||
END;
|
||||
$$
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE TRIGGER {TRIGGER}
|
||||
BEFORE UPDATE OR DELETE OR TRUNCATE ON {VERSIONS}
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION {FUNCTION}()
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE TRIGGER {COLUMN_TRIGGER}
|
||||
BEFORE UPDATE OR DELETE OR TRUNCATE ON {COLUMNS}
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION {COLUMN_FUNCTION}()
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
for table in (COLUMNS, VERSIONS, DEFINITIONS):
|
||||
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {table}")
|
||||
op.execute(f"DROP TRIGGER IF EXISTS {COLUMN_TRIGGER} ON {COLUMNS}")
|
||||
op.execute(f"DROP TRIGGER IF EXISTS {TRIGGER} ON {VERSIONS}")
|
||||
op.execute(f"DROP FUNCTION IF EXISTS {COLUMN_FUNCTION}()")
|
||||
op.execute(f"DROP FUNCTION IF EXISTS {FUNCTION}()")
|
||||
op.drop_index("uq_mapping_column_configs_one_observation_time", table_name=COLUMNS)
|
||||
op.drop_table(COLUMNS)
|
||||
op.drop_table(VERSIONS)
|
||||
op.drop_index("ix_mapping_definitions_query_definition_id", table_name=DEFINITIONS)
|
||||
op.drop_table(DEFINITIONS)
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Create tenant-scoped mapped-input identities and append-only revisions.
|
||||
|
||||
Revision ID: 20261118_0011
|
||||
Revises: 20261118_0010
|
||||
Create Date: 2026-11-18
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision: str = "20261118_0011"
|
||||
down_revision: Union[str, None] = "20261118_0010"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
APP_ROLE = "watchman_app"
|
||||
INPUTS = "mapped_inputs"
|
||||
REVISIONS = "mapped_input_revisions"
|
||||
FUNCTION = "mapped_input_revisions_reject_mutation"
|
||||
TRIGGER = "trg_mapped_input_revisions_append_only"
|
||||
|
||||
|
||||
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 upgrade() -> None:
|
||||
op.create_table(
|
||||
INPUTS,
|
||||
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(
|
||||
"mapping_definition_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey("mapping_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("identity_key", sa.String(length=4096), nullable=False),
|
||||
sa.Column("latest_revision_no", sa.Integer(), nullable=True),
|
||||
sa.Column("created_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.UniqueConstraint(
|
||||
"tenant_id",
|
||||
"mapping_definition_id",
|
||||
"identity_key",
|
||||
name="uq_mapped_inputs_tenant_mapping_identity",
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"latest_revision_no IS NULL OR latest_revision_no >= 1",
|
||||
name="ck_mapped_inputs_latest_revision",
|
||||
),
|
||||
)
|
||||
op.create_index("ix_mapped_inputs_mapping_definition_id", INPUTS, ["mapping_definition_id"])
|
||||
|
||||
op.create_table(
|
||||
REVISIONS,
|
||||
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(
|
||||
"input_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey("mapped_inputs.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("revision_no", sa.Integer(), nullable=False),
|
||||
sa.Column("mapped_values", postgresql.JSONB(), nullable=False),
|
||||
sa.Column("recorded_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||
sa.UniqueConstraint("input_id", "revision_no", name="uq_mapped_input_revisions_input_revision"),
|
||||
sa.CheckConstraint("revision_no >= 1", name="ck_mapped_input_revisions_revision_no"),
|
||||
)
|
||||
op.create_index("ix_mapped_input_revisions_input_id", REVISIONS, ["input_id"])
|
||||
|
||||
for table in (INPUTS, REVISIONS):
|
||||
_enable_rls(table)
|
||||
|
||||
op.execute(f"REVOKE UPDATE, DELETE ON TABLE {REVISIONS} FROM {APP_ROLE}")
|
||||
op.execute(f"GRANT SELECT, INSERT ON TABLE {REVISIONS} TO {APP_ROLE}")
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE FUNCTION {FUNCTION}() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'mapped_input_revisions is append-only: revisions are immutable'
|
||||
USING ERRCODE = 'restrict_violation';
|
||||
END;
|
||||
$$
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE TRIGGER {TRIGGER}
|
||||
BEFORE UPDATE OR DELETE OR TRUNCATE ON {REVISIONS}
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION {FUNCTION}()
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
for table in (REVISIONS, INPUTS):
|
||||
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {table}")
|
||||
op.execute(f"DROP TRIGGER IF EXISTS {TRIGGER} ON {REVISIONS}")
|
||||
op.execute(f"DROP FUNCTION IF EXISTS {FUNCTION}()")
|
||||
op.drop_index("ix_mapped_input_revisions_input_id", table_name=REVISIONS)
|
||||
op.drop_table(REVISIONS)
|
||||
op.drop_index("ix_mapped_inputs_mapping_definition_id", table_name=INPUTS)
|
||||
op.drop_table(INPUTS)
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Create immutable structured rules for mappings.
|
||||
|
||||
Revision ID: 20261118_0012
|
||||
Revises: 20261118_0011
|
||||
Create Date: 2026-11-18
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision: str = "20261118_0012"
|
||||
down_revision: Union[str, None] = "20261118_0011"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
APP_ROLE = "watchman_app"
|
||||
DEFINITIONS = "rule_definitions"
|
||||
VERSIONS = "rule_versions"
|
||||
FUNCTION = "rule_versions_reject_mutation"
|
||||
TRIGGER = "trg_rule_versions_append_only"
|
||||
|
||||
|
||||
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 upgrade() -> None:
|
||||
op.create_table(
|
||||
DEFINITIONS,
|
||||
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("mapping_definition_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("mapping_definitions.id", ondelete="RESTRICT"), nullable=False),
|
||||
sa.Column("latest_version_no", sa.Integer(), nullable=True),
|
||||
sa.Column("current_version_no", sa.Integer(), nullable=True),
|
||||
sa.Column("created_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.CheckConstraint("latest_version_no IS NULL OR latest_version_no >= 1", name="ck_rule_definitions_latest_version"),
|
||||
sa.CheckConstraint("current_version_no IS NULL OR current_version_no >= 1", name="ck_rule_definitions_current_version"),
|
||||
)
|
||||
op.create_index("ix_rule_definitions_mapping_definition_id", DEFINITIONS, ["mapping_definition_id"])
|
||||
op.create_table(
|
||||
VERSIONS,
|
||||
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("definition_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("rule_definitions.id", ondelete="RESTRICT"), nullable=False),
|
||||
sa.Column("version_no", sa.Integer(), nullable=False),
|
||||
sa.Column("condition_tree", postgresql.JSONB(), nullable=False),
|
||||
sa.Column("saved_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||
sa.Column("saved_by", sa.String(length=128), nullable=True),
|
||||
sa.UniqueConstraint("definition_id", "version_no", name="uq_rule_versions_definition_version"),
|
||||
sa.CheckConstraint("version_no >= 1", name="ck_rule_versions_version_no"),
|
||||
)
|
||||
for table in (DEFINITIONS, VERSIONS):
|
||||
_enable_rls(table)
|
||||
op.execute(f"REVOKE UPDATE, DELETE ON TABLE {VERSIONS} FROM {APP_ROLE}")
|
||||
op.execute(f"GRANT SELECT, INSERT ON TABLE {VERSIONS} TO {APP_ROLE}")
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE FUNCTION {FUNCTION}() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'rule_versions is append-only: saved versions are immutable'
|
||||
USING ERRCODE = 'restrict_violation';
|
||||
END;
|
||||
$$
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE TRIGGER {TRIGGER}
|
||||
BEFORE UPDATE OR DELETE OR TRUNCATE ON {VERSIONS}
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION {FUNCTION}()
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
for table in (VERSIONS, DEFINITIONS):
|
||||
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {table}")
|
||||
op.execute(f"DROP TRIGGER IF EXISTS {TRIGGER} ON {VERSIONS}")
|
||||
op.execute(f"DROP FUNCTION IF EXISTS {FUNCTION}()")
|
||||
op.drop_table(VERSIONS)
|
||||
op.drop_index("ix_rule_definitions_mapping_definition_id", table_name=DEFINITIONS)
|
||||
op.drop_table(DEFINITIONS)
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Store mapping condition trees on immutable mapping versions.
|
||||
|
||||
Revision ID: 20261118_0013
|
||||
Revises: 20261118_0012
|
||||
Create Date: 2026-11-18
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision: str = "20261118_0013"
|
||||
down_revision: Union[str, None] = "20261118_0012"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("mapping_versions", sa.Column("condition_tree", postgresql.JSONB(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("mapping_versions", "condition_tree")
|
||||
@@ -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()
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Seed three mapping examples on the M04 demo source.
|
||||
|
||||
One simple threshold, one nested condition group, and one time-and-value group.
|
||||
Re-running keeps an existing mapping instead of appending another version.
|
||||
Does not print passwords or connection strings.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
from watchman.core.config import get_settings, merge_layered_env, reload_settings
|
||||
from watchman.core.db import session_scope
|
||||
from watchman.models.mapping import MappingDefinition
|
||||
from watchman.services import datasources as ds_service
|
||||
from watchman.services import mappings as mapping_service
|
||||
from watchman.services.judgment import evaluate_rows
|
||||
from watchman.services.queries import list_queries
|
||||
|
||||
from seed_m04_demo import (
|
||||
DS_NAME,
|
||||
OUTPUT_SCHEMA,
|
||||
PARAM_SCHEMA_OPTIONAL,
|
||||
SQL_OPTIONAL,
|
||||
_require_pg,
|
||||
ensure_datasource,
|
||||
ensure_query,
|
||||
)
|
||||
|
||||
COLUMNS = [
|
||||
{"source_column_name": "line_code", "value_type": "string", "is_identity": True, "is_observation_time": False, "numeric_multiply": None, "numeric_offset": None},
|
||||
{"source_column_name": "lot_no", "value_type": "string", "is_identity": True, "is_observation_time": False, "numeric_multiply": None, "numeric_offset": None},
|
||||
{"source_column_name": "metric", "value_type": "string", "is_identity": False, "is_observation_time": False, "numeric_multiply": None, "numeric_offset": None},
|
||||
{"source_column_name": "reading_value", "value_type": "number", "is_identity": False, "is_observation_time": False, "numeric_multiply": None, "numeric_offset": None},
|
||||
{"source_column_name": "sampled_at", "value_type": "datetime", "is_identity": False, "is_observation_time": True, "numeric_multiply": None, "numeric_offset": None},
|
||||
]
|
||||
|
||||
ROWS = [
|
||||
{"line_code": "L1", "lot_no": "LOT-1002", "metric": "temp_c", "reading_value": 91, "sampled_at": "2026-11-18T02:05:00+00:00"},
|
||||
{"line_code": "L2", "lot_no": "LOT-2001", "metric": "temp_c", "reading_value": 72.3, "sampled_at": "2026-11-18T02:10:00+00:00"},
|
||||
{"line_code": "L1", "lot_no": "LOT-1001", "metric": "pressure_kpa", "reading_value": 101.2, "sampled_at": "2026-11-18T02:01:00+00:00"},
|
||||
{"line_code": "L2", "lot_no": "LOT-2001", "metric": "pressure_kpa", "reading_value": 98, "sampled_at": "2026-11-18T02:11:00+00:00"},
|
||||
{"line_code": "L3", "lot_no": "LOT-3001", "metric": "temp_c", "reading_value": None, "sampled_at": "2026-11-18T02:20:00+00:00"},
|
||||
{"line_code": "L3", "lot_no": "LOT-3002", "metric": "temp_c", "reading_value": 91, "sampled_at": "2026-11-18T02:30:00"},
|
||||
]
|
||||
|
||||
EXAMPLES = [
|
||||
{
|
||||
"name": "示例·简单规则·读数大于85",
|
||||
"description": "一条条件:reading_value 大于 85。不看指标名。",
|
||||
"tree": {"column": "reading_value", "operator": "gt", "value": 85},
|
||||
},
|
||||
{
|
||||
"name": "示例·规则组·温度或压力超限",
|
||||
"description": "两组条件用「或者」连接:温度大于 85,或压力大于 100。",
|
||||
"tree": {
|
||||
"op": "or",
|
||||
"items": [
|
||||
{"op": "and", "items": [
|
||||
{"column": "metric", "operator": "eq", "value": "temp_c"},
|
||||
{"column": "reading_value", "operator": "gt", "value": 85},
|
||||
]},
|
||||
{"op": "and", "items": [
|
||||
{"column": "metric", "operator": "eq", "value": "pressure_kpa"},
|
||||
{"column": "reading_value", "operator": "gt", "value": 100},
|
||||
]},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "示例·规则组·观测时间并且读数大于80",
|
||||
"description": "同一组里两条都要满足:观测时间晚于 2026-11-18 02:00(带时区),并且读数大于 80。",
|
||||
"tree": {
|
||||
"op": "and",
|
||||
"items": [
|
||||
{"column": "sampled_at", "operator": "gt", "value": "2026-11-18T02:00:00+00:00"},
|
||||
{"column": "reading_value", "operator": "gt", "value": 80},
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def ensure_mapping(query_id: str, tree: dict) -> str:
|
||||
from sqlalchemy import select
|
||||
|
||||
with session_scope() as session:
|
||||
row = session.scalar(select(MappingDefinition).where(MappingDefinition.query_definition_id == query_id))
|
||||
if row is not None and row.current_version_no:
|
||||
print(f"mapping kept: query={query_id} current=v{row.current_version_no}")
|
||||
return str(row.id)
|
||||
if row is None:
|
||||
row = mapping_service.create_mapping(session, query_definition_id=query_id)
|
||||
version = mapping_service.save_mapping_version(session, str(row.id), COLUMNS, condition_tree=tree, saved_by="seed_m05_examples")
|
||||
session.commit()
|
||||
print(f"mapping saved: id={row.id} current=v{version.version_no}")
|
||||
return str(row.id)
|
||||
|
||||
|
||||
def show_trial(name: str, tree: dict) -> None:
|
||||
judged = evaluate_rows(ROWS, COLUMNS, tree, [column["source_column_name"] for column in COLUMNS])
|
||||
codes = [item["code"] for item in judged.get("rows", [])]
|
||||
print(f"trial {name}: {judged.get('outcome')} {codes or judged}")
|
||||
empty = evaluate_rows([], COLUMNS, tree, [column["source_column_name"] for column in COLUMNS])
|
||||
print(f"trial {name} empty: {empty.get('outcome')}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
reload_settings()
|
||||
env = merge_layered_env()
|
||||
pg = _require_pg(env)
|
||||
print(f"tenant={get_settings().tenant_id}")
|
||||
datasource_id = ensure_datasource(pg)
|
||||
with session_scope() as session:
|
||||
source = next((row for row in ds_service.list_datasources(session) if row.name == DS_NAME), None)
|
||||
if source is None:
|
||||
raise SystemExit("demo datasource is missing")
|
||||
datasource_id = str(source.id)
|
||||
for example in EXAMPLES:
|
||||
query_id = ensure_query(
|
||||
datasource_id,
|
||||
name=example["name"],
|
||||
description=example["description"],
|
||||
sql_template=SQL_OPTIONAL,
|
||||
param_schema=PARAM_SCHEMA_OPTIONAL,
|
||||
)
|
||||
ensure_mapping(query_id, example["tree"])
|
||||
show_trial(example["name"], example["tree"])
|
||||
with session_scope() as session:
|
||||
names = [row.name for row in list_queries(session)]
|
||||
print("queries now include: " + ", ".join(name for name in names if name.startswith("示例·")))
|
||||
print("output schema columns: " + ", ".join(item["name"] for item in OUTPUT_SCHEMA))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,6 +1,6 @@
|
||||
"""FastAPI application factory.
|
||||
|
||||
Registers envelope middleware and global exception handlers.
|
||||
Registers envelope middleware, global exception handlers, and the HTTP routers.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -10,7 +10,7 @@ from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
from watchman.api.routes import auth, datasources, health, 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.errors import AppError, ValidationError
|
||||
from watchman.core.request_id import REQUEST_ID_HEADER, resolve_request_id
|
||||
@@ -79,6 +79,8 @@ def create_app(*, validate_runtime: bool = True) -> FastAPI:
|
||||
app.include_router(platform.router)
|
||||
app.include_router(datasources.router)
|
||||
app.include_router(queries.router)
|
||||
app.include_router(mappings.router)
|
||||
app.include_router(alarms.router)
|
||||
|
||||
@app.exception_handler(AppError)
|
||||
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)
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Mapping, rule, and trial routes using existing mapping, rule, query-preview, and judgment services.
|
||||
|
||||
Boundary: validates request shapes and permissions; it never persists trial rows or executes SQL directly.
|
||||
Depends on service-layer persistence and the existing query preview path.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from watchman.auth.principal import (
|
||||
require_mapping_reader, require_mapping_trialer, require_mapping_writer, require_query_previewer,
|
||||
)
|
||||
from watchman.core.db import get_db_session
|
||||
from watchman.core.errors import NotFoundError, ValidationError
|
||||
from watchman.core.response import success_body
|
||||
from watchman.models.mapping import MappingColumnConfig, MappingDefinition, MappingVersion, RuleDefinition, RuleVersion
|
||||
from watchman.models.query import QueryDefinition
|
||||
from watchman.services import mappings as mapping_service
|
||||
from watchman.services import queries as query_service
|
||||
from watchman.services import rules as rule_service
|
||||
from watchman.services.judgment import evaluate_rows
|
||||
|
||||
router = APIRouter(prefix="/mappings", tags=["mappings"])
|
||||
|
||||
|
||||
class MappingCreate(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
query_definition_id: str
|
||||
|
||||
|
||||
class MappingVersionCreate(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
columns: list[dict[str, Any]]
|
||||
condition_tree: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class RuleCreate(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class RuleVersionCreate(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
condition_tree: dict[str, Any]
|
||||
|
||||
|
||||
class TrialBody(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
condition_tree: dict[str, Any] | None = None
|
||||
rows: list[dict[str, Any]] | None = None
|
||||
query_params: dict[str, Any] = Field(default_factory=dict)
|
||||
row_limit: int | None = None
|
||||
|
||||
|
||||
def _row_limit(value: int | None) -> int:
|
||||
"""Default the query trial to 10 rows and keep a caller-chosen limit inside 1..100."""
|
||||
chosen = 10 if value is None else value
|
||||
return min(100, max(1, chosen))
|
||||
|
||||
|
||||
def _ok(request: Request, data: Any) -> JSONResponse:
|
||||
return JSONResponse(content=success_body(data, request_id=request.state.request_id))
|
||||
|
||||
|
||||
def _mapping(session: Session, mapping_id: str) -> MappingDefinition:
|
||||
return mapping_service._get_mapping(session, mapping_id, lock=False)
|
||||
|
||||
|
||||
def _snapshot(session: Session, mapping: MappingDefinition) -> tuple[MappingVersion, list[MappingColumnConfig]]:
|
||||
version, columns = mapping_service._current_mapping_snapshot(session, mapping)
|
||||
return version, columns
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_mapping(request: Request, body: MappingCreate, _: None = Depends(require_mapping_writer), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
row = mapping_service.create_mapping(session, query_definition_id=body.query_definition_id)
|
||||
session.commit()
|
||||
return _ok(request, {"id": str(row.id), "query_definition_id": str(row.query_definition_id)})
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_mappings(
|
||||
request: Request, name: str | None = None, query: str | None = None, page: int = 1,
|
||||
page_size: int = 20, sort_by: str = "created_at", sort_order: str = "desc",
|
||||
_: None = Depends(require_mapping_reader), session: Session = Depends(get_db_session),
|
||||
) -> JSONResponse:
|
||||
stmt = select(MappingDefinition, QueryDefinition.name).join(QueryDefinition, QueryDefinition.id == MappingDefinition.query_definition_id)
|
||||
if name:
|
||||
stmt = stmt.where(QueryDefinition.name.ilike(f"%{name}%"))
|
||||
if query:
|
||||
stmt = stmt.where(QueryDefinition.name.ilike(f"%{query}%"))
|
||||
order = MappingDefinition.created_at.desc() if sort_order == "desc" else MappingDefinition.created_at.asc()
|
||||
rows = session.execute(stmt.order_by(order).offset((page - 1) * page_size).limit(page_size)).all()
|
||||
count = select(func.count()).select_from(MappingDefinition).join(QueryDefinition, QueryDefinition.id == MappingDefinition.query_definition_id)
|
||||
if name:
|
||||
count = count.where(QueryDefinition.name.ilike(f"%{name}%"))
|
||||
if query:
|
||||
count = count.where(QueryDefinition.name.ilike(f"%{query}%"))
|
||||
total = session.scalar(count) or 0
|
||||
return _ok(request, {"items": [{"id": str(row.id), "name": query_name, "query": query_name, "current_version_no": row.current_version_no} for row, query_name in rows], "total": total, "page": page, "page_size": page_size})
|
||||
|
||||
|
||||
@router.get("/{mapping_id}")
|
||||
def get_mapping(request: Request, mapping_id: str, _: None = Depends(require_mapping_reader), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
row = _mapping(session, mapping_id)
|
||||
return _ok(request, {"id": str(row.id), "query_definition_id": str(row.query_definition_id), "current_version_no": row.current_version_no})
|
||||
|
||||
|
||||
@router.post("/{mapping_id}/versions")
|
||||
def save_mapping_version(request: Request, mapping_id: str, body: MappingVersionCreate, _: None = Depends(require_mapping_writer), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
row = mapping_service.save_mapping_version(session, mapping_id, body.columns, condition_tree=body.condition_tree)
|
||||
session.commit()
|
||||
return _ok(request, {"id": str(row.id), "version_no": row.version_no, "condition_tree": row.condition_tree})
|
||||
|
||||
|
||||
@router.get("/{mapping_id}/versions")
|
||||
def list_mapping_versions(request: Request, mapping_id: str, _: None = Depends(require_mapping_reader), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
mapping = _mapping(session, mapping_id)
|
||||
rows = session.scalars(select(MappingVersion).where(MappingVersion.definition_id == mapping.id).order_by(MappingVersion.version_no.desc()))
|
||||
return _ok(request, {"items": [{"id": str(row.id), "version_no": row.version_no} for row in rows]})
|
||||
|
||||
|
||||
@router.get("/{mapping_id}/versions/{version_no}")
|
||||
def get_mapping_version(request: Request, mapping_id: str, version_no: int, _: None = Depends(require_mapping_reader), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
mapping = _mapping(session, mapping_id)
|
||||
version = session.scalar(select(MappingVersion).where(MappingVersion.definition_id == mapping.id, MappingVersion.version_no == version_no))
|
||||
if version is None:
|
||||
raise NotFoundError("Mapping version not found")
|
||||
columns = list(session.scalars(select(MappingColumnConfig).where(MappingColumnConfig.mapping_version_id == version.id)))
|
||||
return _ok(request, {"id": str(version.id), "version_no": version.version_no, "condition_tree": version.condition_tree, "columns": [{"source_column_name": c.source_column_name, "value_type": c.value_type, "is_identity": c.is_identity, "is_observation_time": c.is_observation_time, "numeric_multiply": str(c.numeric_multiply) if c.numeric_multiply is not None else None, "numeric_offset": str(c.numeric_offset) if c.numeric_offset is not None else None} for c in columns]})
|
||||
|
||||
|
||||
@router.post("/{mapping_id}/versions/{version_no}/activate")
|
||||
def activate_mapping_version(request: Request, mapping_id: str, version_no: int, _: None = Depends(require_mapping_writer), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
mapping = _mapping(session, mapping_id)
|
||||
version = session.scalar(select(MappingVersion).where(MappingVersion.definition_id == mapping.id, MappingVersion.version_no == version_no))
|
||||
if version is None:
|
||||
raise NotFoundError("Mapping version not found")
|
||||
mapping.current_version_no = version_no
|
||||
session.commit()
|
||||
return _ok(request, {"id": str(mapping.id), "current_version_no": mapping.current_version_no})
|
||||
|
||||
|
||||
@router.post("/{mapping_id}/rules")
|
||||
def create_rule(request: Request, mapping_id: str, body: RuleCreate | None = None, _: None = Depends(require_mapping_writer), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
row = rule_service.create_rule(session, mapping_definition_id=mapping_id)
|
||||
session.commit()
|
||||
return _ok(request, {"id": str(row.id), "mapping_definition_id": str(row.mapping_definition_id)})
|
||||
|
||||
|
||||
@router.get("/{mapping_id}/rules/{rule_id}")
|
||||
def get_rule(request: Request, mapping_id: str, rule_id: str, _: None = Depends(require_mapping_reader), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
rule = session.get(RuleDefinition, rule_id)
|
||||
if rule is None or str(rule.mapping_definition_id) != mapping_id:
|
||||
raise NotFoundError("Rule not found")
|
||||
return _ok(request, {"id": str(rule.id), "current_version_no": rule.current_version_no})
|
||||
|
||||
|
||||
@router.post("/{mapping_id}/rules/{rule_id}/versions")
|
||||
def save_rule_version(request: Request, mapping_id: str, rule_id: str, body: RuleVersionCreate, _: None = Depends(require_mapping_writer), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
rule = session.get(RuleDefinition, rule_id)
|
||||
if rule is None or str(rule.mapping_definition_id) != mapping_id:
|
||||
raise NotFoundError("Rule not found")
|
||||
row = rule_service.save_rule_version(session, rule_id, body.condition_tree)
|
||||
session.commit()
|
||||
return _ok(request, {"id": str(row.id), "version_no": row.version_no, "condition_tree": row.condition_tree})
|
||||
|
||||
|
||||
def _judge(session: Session, mapping: MappingDefinition, columns: list[Any], tree: dict[str, Any] | None, rows: list[dict[str, Any]], names: list[str]) -> dict[str, Any]:
|
||||
chosen = tree if isinstance(tree, dict) and tree else None
|
||||
if chosen is None:
|
||||
return {"outcome": "error", "details": {"reason": "rule_missing"}}
|
||||
types = {column.source_column_name: column.value_type for column in columns}
|
||||
try:
|
||||
rule_service._validate_tree(chosen, types)
|
||||
except ValidationError as exc:
|
||||
return {"outcome": "error", "details": getattr(exc, "details", {})}
|
||||
return evaluate_rows(rows, columns, chosen, names)
|
||||
|
||||
|
||||
@router.post("/{mapping_id}/trial")
|
||||
def trial_mapping(request: Request, mapping_id: str, body: TrialBody, _: None = Depends(require_mapping_trialer), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
mapping = _mapping(session, mapping_id)
|
||||
version, columns = _snapshot(session, mapping)
|
||||
names = mapping_service.current_query_column_names(session, mapping)
|
||||
return _ok(request, _judge(session, mapping, columns, body.condition_tree or version.condition_tree, body.rows or [], names))
|
||||
|
||||
|
||||
@router.post("/{mapping_id}/trial-query")
|
||||
def trial_mapping_query(
|
||||
request: Request, mapping_id: str, body: TrialBody,
|
||||
_: None = Depends(require_mapping_trialer), __: None = Depends(require_query_previewer),
|
||||
session: Session = Depends(get_db_session),
|
||||
) -> JSONResponse:
|
||||
mapping = _mapping(session, mapping_id)
|
||||
version, columns = _snapshot(session, mapping)
|
||||
limit = _row_limit(body.row_limit)
|
||||
preview = query_service.preview_current(session, str(mapping.query_definition_id), body.query_params)
|
||||
if preview["status"] not in ("success", "empty"):
|
||||
session.commit()
|
||||
return _ok(request, {"outcome": "error", "details": preview.get("details", {})})
|
||||
source_rows = list(preview.get("rows") or [])[:limit]
|
||||
data = _judge(session, mapping, columns, body.condition_tree or version.condition_tree, source_rows, preview.get("columns") or [])
|
||||
data["input_rows"] = source_rows
|
||||
session.commit()
|
||||
return _ok(request, data)
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Role checks for the Watchman permission nodes.
|
||||
|
||||
Decides enter, platform write, object read, and the three datasource nodes (read,
|
||||
write, test) and the four query nodes (read, write, publish, preview) from Casdoor role names.
|
||||
Decides enter, platform write, object read, datasource, query, mapping, and the
|
||||
four approved alarm nodes from the existing Casdoor role names.
|
||||
Depends on semantic errors only; it does not call Casdoor or open a session.
|
||||
"""
|
||||
|
||||
@@ -21,6 +21,15 @@ QUERY_READ_NODE = "perm:data:emp:watchman.query.read"
|
||||
QUERY_WRITE_NODE = "perm:data:emp:watchman.query.write"
|
||||
QUERY_PUBLISH_NODE = "perm:data:emp:watchman.query.publish"
|
||||
QUERY_PREVIEW_NODE = "perm:data:emp:watchman.query.preview"
|
||||
MAPPING_READ_NODE = "perm:data:emp:watchman.mapping.read"
|
||||
MAPPING_WRITE_NODE = "perm:data:emp:watchman.mapping.write"
|
||||
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_OPERATOR = "watchman-operator"
|
||||
@@ -94,6 +103,61 @@ def require_query_preview(role_names: list[str]) -> None:
|
||||
raise ForbiddenError(permission_node=QUERY_PREVIEW_NODE)
|
||||
|
||||
|
||||
def require_mapping_read(role_names: list[str]) -> None:
|
||||
"""Allow mapping and rule reads only for watchman-admin."""
|
||||
if ROLE_ADMIN not in role_names:
|
||||
raise ForbiddenError(permission_node=MAPPING_READ_NODE)
|
||||
|
||||
|
||||
def require_mapping_write(role_names: list[str]) -> None:
|
||||
"""Allow mapping and rule writes only for watchman-admin."""
|
||||
if ROLE_ADMIN not in role_names:
|
||||
raise ForbiddenError(permission_node=MAPPING_WRITE_NODE)
|
||||
|
||||
|
||||
def require_mapping_trial(role_names: list[str]) -> None:
|
||||
"""Allow mapping and rule trials only for watchman-admin."""
|
||||
if ROLE_ADMIN not in role_names:
|
||||
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:
|
||||
"""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.
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from dataclasses import dataclass
|
||||
from datetime import timedelta
|
||||
from typing import Protocol
|
||||
from urllib.parse import quote
|
||||
@@ -15,9 +17,16 @@ from fastapi import Cookie, Depends, Request
|
||||
|
||||
from watchman.auth.casdoor import DefaultCasdoorPort, UrllibCasdoorHttpTransport
|
||||
from watchman.auth.access import (
|
||||
require_alarm_close,
|
||||
require_alarm_progress,
|
||||
require_alarm_read,
|
||||
require_alarm_take,
|
||||
require_datasource_read,
|
||||
require_datasource_test,
|
||||
require_datasource_write,
|
||||
require_mapping_read,
|
||||
require_mapping_trial,
|
||||
require_mapping_write,
|
||||
require_platform_write,
|
||||
require_query_preview,
|
||||
require_query_publish,
|
||||
@@ -133,8 +142,8 @@ def _load_session(
|
||||
session_token: str | None,
|
||||
sessions: SessionStore,
|
||||
directory: RoleDirectory,
|
||||
) -> tuple[str, list[str]]:
|
||||
"""Return (login_name, fresh role names) for the caller's session, or raise 41000 / 503.
|
||||
) -> tuple[str, str, list[str]]:
|
||||
"""Return (subject, login_name, fresh roles) or raise 41000 / 503.
|
||||
|
||||
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.
|
||||
@@ -150,7 +159,7 @@ def _load_session(
|
||||
if now - row.role_checked_at >= ROLE_FRESHNESS:
|
||||
roles = directory.lookup_roles(login_name=row.login_name)
|
||||
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(
|
||||
@@ -160,7 +169,7 @@ def _load_session_roles(
|
||||
directory: RoleDirectory,
|
||||
) -> list[str]:
|
||||
"""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(
|
||||
@@ -220,7 +229,7 @@ def require_query_publisher(
|
||||
directory: RoleDirectory = Depends(get_role_directory),
|
||||
) -> str:
|
||||
"""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)
|
||||
return login_name
|
||||
|
||||
@@ -233,3 +242,101 @@ def require_query_previewer(
|
||||
) -> None:
|
||||
"""Reject a draft or version preview unless the session is admin."""
|
||||
require_query_preview(_load_session_roles(request, session_token, sessions, directory))
|
||||
|
||||
|
||||
def require_mapping_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),
|
||||
) -> None:
|
||||
"""Reject mapping reads unless the session is watchman-admin."""
|
||||
require_mapping_read(_load_session_roles(request, session_token, sessions, directory))
|
||||
|
||||
|
||||
def require_mapping_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),
|
||||
) -> None:
|
||||
"""Reject mapping writes unless the session is watchman-admin."""
|
||||
require_mapping_write(_load_session_roles(request, session_token, sessions, directory))
|
||||
|
||||
|
||||
def require_mapping_trialer(
|
||||
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),
|
||||
) -> None:
|
||||
"""Reject mapping trials unless the session is watchman-admin."""
|
||||
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,14 +1,26 @@
|
||||
"""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.datasource import DataSource
|
||||
from watchman.models.mapping import MappingColumnConfig, MappingDefinition, MappingVersion
|
||||
from watchman.models.platform import AuditEvent, RunRecord
|
||||
from watchman.models.query import QueryDefinition, QueryVersion
|
||||
|
||||
__all__ = [
|
||||
"Alarm",
|
||||
"AlarmClosedBasis",
|
||||
"AlarmHandlingCommand",
|
||||
"AlarmHandlingEvent",
|
||||
"AlarmOccurrence",
|
||||
"AlarmRevisionEvidence",
|
||||
"AuthSession",
|
||||
"AuditEvent",
|
||||
"DataSource",
|
||||
"MappingColumnConfig",
|
||||
"MappingDefinition",
|
||||
"MappingVersion",
|
||||
"QueryDefinition",
|
||||
"QueryVersion",
|
||||
"RunRecord",
|
||||
|
||||
@@ -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,264 @@
|
||||
"""Tenant-scoped query mappings and immutable column snapshots.
|
||||
|
||||
Boundary: stores mapping definitions and their versioned column selections; validation and
|
||||
version creation live in `watchman.services.mappings`. Depends on query definitions only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
Numeric,
|
||||
String,
|
||||
UniqueConstraint,
|
||||
func,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import JSONB, UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from watchman.models.base import Base
|
||||
|
||||
MAPPING_VALUE_TYPES = ("number", "string", "boolean", "datetime")
|
||||
|
||||
|
||||
class MappingDefinition(Base):
|
||||
"""One configurable mapping attached to a query definition and its active version."""
|
||||
|
||||
__tablename__ = "mapping_definitions"
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"latest_version_no IS NULL OR latest_version_no >= 1",
|
||||
name="ck_mapping_definitions_latest_version",
|
||||
),
|
||||
CheckConstraint(
|
||||
"current_version_no IS NULL OR current_version_no >= 1",
|
||||
name="ck_mapping_definitions_current_version",
|
||||
),
|
||||
)
|
||||
|
||||
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)
|
||||
query_definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("query_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
latest_version_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
current_version_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
created_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 MappingVersion(Base):
|
||||
"""An append-only snapshot of a mapping definition; content lives in its column rows."""
|
||||
|
||||
__tablename__ = "mapping_versions"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("definition_id", "version_no", name="uq_mapping_versions_definition_version"),
|
||||
CheckConstraint("version_no >= 1", name="ck_mapping_versions_version_no"),
|
||||
)
|
||||
|
||||
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)
|
||||
definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapping_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
version_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
condition_tree: Mapped[dict[str, object] | None] = mapped_column(JSONB, nullable=True)
|
||||
saved_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
saved_by: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
|
||||
|
||||
class MappingColumnConfig(Base):
|
||||
"""A selected query-output column and its declared mapping configuration."""
|
||||
|
||||
__tablename__ = "mapping_column_configs"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"mapping_version_id",
|
||||
"source_column_name",
|
||||
name="uq_mapping_column_configs_version_source",
|
||||
),
|
||||
CheckConstraint(
|
||||
"value_type IN ('number', 'string', 'boolean', 'datetime')",
|
||||
name="ck_mapping_column_configs_value_type",
|
||||
),
|
||||
CheckConstraint(
|
||||
"(value_type = 'number') OR (numeric_multiply IS NULL AND numeric_offset IS NULL)",
|
||||
name="ck_mapping_column_configs_numeric_only",
|
||||
),
|
||||
Index(
|
||||
"uq_mapping_column_configs_one_observation_time",
|
||||
"mapping_version_id",
|
||||
unique=True,
|
||||
postgresql_where=text("is_observation_time"),
|
||||
),
|
||||
)
|
||||
|
||||
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)
|
||||
mapping_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapping_versions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
source_column_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
value_type: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
is_identity: Mapped[bool] = mapped_column(
|
||||
Boolean, nullable=False, server_default=text("false")
|
||||
)
|
||||
is_observation_time: Mapped[bool] = mapped_column(
|
||||
Boolean, nullable=False, server_default=text("false")
|
||||
)
|
||||
numeric_multiply: Mapped[Decimal | None] = mapped_column(Numeric(24, 8), nullable=True)
|
||||
numeric_offset: Mapped[Decimal | None] = mapped_column(Numeric(24, 8), nullable=True)
|
||||
|
||||
|
||||
class MappedInput(Base):
|
||||
"""A stable mapped-input identity whose latest revision pointer may advance."""
|
||||
|
||||
__tablename__ = "mapped_inputs"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"tenant_id",
|
||||
"mapping_definition_id",
|
||||
"identity_key",
|
||||
name="uq_mapped_inputs_tenant_mapping_identity",
|
||||
),
|
||||
CheckConstraint(
|
||||
"latest_revision_no IS NULL OR latest_revision_no >= 1",
|
||||
name="ck_mapped_inputs_latest_revision",
|
||||
),
|
||||
)
|
||||
|
||||
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)
|
||||
mapping_definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapping_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
identity_key: Mapped[str] = mapped_column(String(4096), nullable=False)
|
||||
latest_revision_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
created_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 MappedInputRevision(Base):
|
||||
"""An append-only non-identity value snapshot for one mapped input."""
|
||||
|
||||
__tablename__ = "mapped_input_revisions"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("input_id", "revision_no", name="uq_mapped_input_revisions_input_revision"),
|
||||
CheckConstraint("revision_no >= 1", name="ck_mapped_input_revisions_revision_no"),
|
||||
)
|
||||
|
||||
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)
|
||||
input_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapped_inputs.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,
|
||||
)
|
||||
revision_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
mapped_values: Mapped[dict[str, object]] = mapped_column(JSONB, nullable=False)
|
||||
recorded_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
|
||||
|
||||
class RuleDefinition(Base):
|
||||
"""A rule attached to one mapping definition with a mutable current-version pointer."""
|
||||
|
||||
__tablename__ = "rule_definitions"
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"latest_version_no IS NULL OR latest_version_no >= 1",
|
||||
name="ck_rule_definitions_latest_version",
|
||||
),
|
||||
CheckConstraint(
|
||||
"current_version_no IS NULL OR current_version_no >= 1",
|
||||
name="ck_rule_definitions_current_version",
|
||||
),
|
||||
)
|
||||
|
||||
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)
|
||||
mapping_definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapping_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
latest_version_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
current_version_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
created_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 RuleVersion(Base):
|
||||
"""An append-only validated condition tree for one rule definition."""
|
||||
|
||||
__tablename__ = "rule_versions"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("definition_id", "version_no", name="uq_rule_versions_definition_version"),
|
||||
CheckConstraint("version_no >= 1", name="ck_rule_versions_version_no"),
|
||||
)
|
||||
|
||||
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)
|
||||
definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("rule_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
version_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
condition_tree: Mapped[dict[str, object]] = mapped_column(JSONB, nullable=False)
|
||||
saved_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
saved_by: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
@@ -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,131 @@
|
||||
"""Pure mapped-row judgment with explicit normal, abnormal, unknown, empty, and error outcomes.
|
||||
|
||||
Boundary: transforms supplied rows only; it opens no sessions and never persists inputs or alarms.
|
||||
Depends only on Python value coercion and declarative mapping/rule structures.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from datetime import datetime, timezone
|
||||
from decimal import Decimal
|
||||
from typing import Any, Mapping, Sequence
|
||||
|
||||
|
||||
def _aware_datetime(raw: Any) -> datetime | None:
|
||||
parsed = raw
|
||||
if isinstance(raw, str):
|
||||
try:
|
||||
parsed = datetime.fromisoformat(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
if not isinstance(parsed, datetime) or parsed.tzinfo is None or parsed.utcoffset() is None:
|
||||
return None
|
||||
return parsed.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def _finite_number(value: Any) -> Decimal:
|
||||
if isinstance(value, bool) or isinstance(value, str) and not value.strip():
|
||||
raise ValueError("comparison value is not a finite number")
|
||||
try:
|
||||
number = value if isinstance(value, Decimal) else Decimal(str(value))
|
||||
except Exception as exc:
|
||||
raise ValueError("comparison value is not a finite number") from exc
|
||||
if not number.is_finite():
|
||||
raise ValueError("comparison value is not a finite number")
|
||||
return number
|
||||
|
||||
|
||||
def _get(config: Any, name: str) -> Any:
|
||||
return config.get(name) if isinstance(config, Mapping) else getattr(config, name)
|
||||
|
||||
|
||||
def _value(raw: Any, config: Any) -> tuple[Any, str | None]:
|
||||
if raw is None:
|
||||
return None, "missing"
|
||||
kind = _get(config, "value_type")
|
||||
if kind == "number":
|
||||
if isinstance(raw, bool) or not isinstance(raw, (int, float, Decimal)):
|
||||
return None, "invalid"
|
||||
if isinstance(raw, Decimal):
|
||||
if not raw.is_finite():
|
||||
return None, "invalid"
|
||||
elif not math.isfinite(raw):
|
||||
return None, "invalid"
|
||||
multiply = _get(config, "numeric_multiply")
|
||||
offset = _get(config, "numeric_offset")
|
||||
if multiply is not None or offset is not None:
|
||||
value = raw if isinstance(raw, Decimal) else Decimal(str(raw))
|
||||
return value * (multiply if multiply is not None else Decimal(1)) + (
|
||||
offset if offset is not None else Decimal(0)
|
||||
), None
|
||||
return raw, None
|
||||
if kind == "datetime":
|
||||
parsed = _aware_datetime(raw)
|
||||
if parsed is None:
|
||||
return None, "invalid"
|
||||
return parsed, None
|
||||
if (kind == "string" and not isinstance(raw, str)) or (kind == "boolean" and not isinstance(raw, bool)):
|
||||
return None, "invalid"
|
||||
return raw, None
|
||||
|
||||
|
||||
def _leaf(node: Mapping[str, Any], row: Mapping[str, Any], configs: dict[str, Any], status: dict[str, str]) -> str:
|
||||
column = node["column"]
|
||||
value, problem = _value(row.get(column), configs[column])
|
||||
if problem:
|
||||
status[column] = problem
|
||||
return "unknown"
|
||||
expected = node["value"]
|
||||
kind = _get(configs[column], "value_type")
|
||||
if kind == "number":
|
||||
expected = _finite_number(expected)
|
||||
value = value if isinstance(value, Decimal) else Decimal(str(value))
|
||||
if kind == "datetime":
|
||||
expected = _aware_datetime(expected)
|
||||
if expected is None:
|
||||
raise ValueError("configured datetime comparison value must include a timezone")
|
||||
operators = {"eq": lambda: value == expected, "ne": lambda: value != expected, "gt": lambda: value > expected, "gte": lambda: value >= expected, "lt": lambda: value < expected, "lte": lambda: value <= expected}
|
||||
return "abnormal" if operators[node["operator"]]() else "normal"
|
||||
|
||||
|
||||
def _tree(node: Mapping[str, Any], row: Mapping[str, Any], configs: dict[str, Any], status: dict[str, str]) -> str:
|
||||
if "items" not in node:
|
||||
return _leaf(node, row, configs, status)
|
||||
codes = [_tree(item, row, configs, status) for item in node["items"]]
|
||||
if node["op"] == "and":
|
||||
return "normal" if "normal" in codes else ("abnormal" if all(c == "abnormal" for c in codes) else "unknown")
|
||||
return "abnormal" if "abnormal" in codes else ("normal" if all(c == "normal" for c in codes) else "unknown")
|
||||
|
||||
|
||||
def evaluate_rows(
|
||||
rows: Sequence[Mapping[str, Any]],
|
||||
mapping_columns: Sequence[Any],
|
||||
condition_tree: Mapping[str, Any],
|
||||
current_query_columns: Sequence[str],
|
||||
) -> dict[str, Any]:
|
||||
"""Evaluate supplied rows without persistence; missing rule columns return error, never unknown."""
|
||||
try:
|
||||
configs = {_get(config, "source_column_name"): config for config in mapping_columns}
|
||||
required = set(configs) | {node["column"] for node in _leaves(condition_tree)}
|
||||
missing = sorted(required - set(current_query_columns))
|
||||
if missing:
|
||||
return {"outcome": "error", "missing_columns": missing}
|
||||
if not rows:
|
||||
return {"outcome": "empty", "skipped_rows": 0}
|
||||
candidates = rows if any(_get(c, "is_identity") for c in mapping_columns) else rows[:1]
|
||||
results = []
|
||||
for row in candidates:
|
||||
status: dict[str, str] = {}
|
||||
results.append({"code": _tree(condition_tree, row, configs, status), "field_status": status})
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return {"outcome": "error"}
|
||||
return {**results[0], "outcome": "result", "rows": results, "skipped_rows": len(rows) - len(candidates)}
|
||||
|
||||
|
||||
def _leaves(node: Mapping[str, Any]):
|
||||
if "items" not in node:
|
||||
yield node
|
||||
else:
|
||||
for item in node["items"]:
|
||||
yield from _leaves(item)
|
||||