feat(queries): 完成 M04 查询定义与版本激活
交付不可变查询版本、保存即生效与激活(D26),并带控制台列表筛选排序与试跑预览;补 RLS 下 current_version_no 回填迁移。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
8c0335040f
commit
21cc721fcc
97 files changed
+13354
-153
No files matched your search
@@ -0,0 +1,78 @@
|
||||
# Task Context Pack
|
||||
|
||||
## Task Goal
|
||||
|
||||
M04:受控查询草稿、不可变版本、只读预览与控制台(A-016~A-020;D24)。
|
||||
|
||||
## Current Slice Or Group
|
||||
|
||||
分析完成;用户已确认计划并要求执行全部切片。下一编码切片:**S1**。
|
||||
|
||||
## Requirement Source
|
||||
|
||||
`.task/2026-11-18/m04-queries/requirement.md`
|
||||
|
||||
## Implementation Source
|
||||
|
||||
`.task/2026-11-18/m04-queries/implementation-plan.md`
|
||||
|
||||
## Involved Modules Or Knowledge Areas
|
||||
|
||||
- 查询定义/版本;只读执行;M03 数据源 usable/熔断
|
||||
- 控制台查询 UI(S5)
|
||||
|
||||
## Loaded Rules
|
||||
|
||||
- `AGENTS.md`;sy-standards(API 信封、错误、权限点、前端、红线、注释)
|
||||
- Marionettist autonomous;原型确认停点;`risk_score>=4` 片际停
|
||||
|
||||
## Loaded Docs
|
||||
|
||||
- `docs/tasks/INDEX.md` M04;交接稿 A-02;`docs/decisions.md`;`docs/current/frontend-ui.md`
|
||||
- M03 `assert_usable`/datasources API
|
||||
|
||||
## Allowed Modification Scope
|
||||
|
||||
按当前切片:见 implementation-plan 各 Slice Allowed Modification Scope。
|
||||
|
||||
## Forbidden Modification Scope
|
||||
|
||||
- 秘密入库/入日志;映射/报警/企微/场景正式采集;生产破坏性操作
|
||||
- S4 确认前改 Vue 查询页
|
||||
|
||||
## Key Existing Entrypoints
|
||||
|
||||
- `services/watchman/src/watchman/services/datasources.py`:`assert_usable`、`list_references`、失败记账
|
||||
- `services/watchman/src/watchman/api/routes/datasources.py`
|
||||
- `services/watchman/src/watchman/auth/access.py`
|
||||
- `web/apps/console/src/datasources/`(UI 模式参考)
|
||||
- `.task/2026-11-17/m03-datasource/prototype/`(原型模式参考)
|
||||
|
||||
## Gate Policy
|
||||
|
||||
- selected / effective: autonomous
|
||||
- finalApprovalRequired: true
|
||||
|
||||
## Validation Commands
|
||||
|
||||
```
|
||||
cd services/watchman && uv run pytest
|
||||
cd services/watchman && uv run alembic upgrade head
|
||||
cd web/apps/console && pnpm test:unit && pnpm test:e2e && pnpm typecheck
|
||||
```
|
||||
|
||||
## Assumptions
|
||||
|
||||
- 权限点 `watchman.query.*` 仅 admin
|
||||
- 预览不进报警
|
||||
- 正式采集留给 M08
|
||||
|
||||
## Risks
|
||||
|
||||
- SQL 注入与任意标识符;熔断绕过;版本可变回归
|
||||
|
||||
## Stop Conditions
|
||||
|
||||
- S4→S5:原型未确认
|
||||
- high-risk/boundary-sensitive/risk>=4 片审未过
|
||||
- 最终验收前不标 DONE_LOCAL(除非用户明确授权)
|
||||
@@ -0,0 +1,168 @@
|
||||
# M04 查询定义与采集 Implementation Plan
|
||||
|
||||
## Requirement Source
|
||||
|
||||
`.task/2026-11-18/m04-queries/requirement.md`(D24)
|
||||
|
||||
## Scope Summary
|
||||
|
||||
参数化 SQL 查询草稿、不可变版本发布、只读预览执行与控制台 UI。正式场景采集不在本轮。
|
||||
|
||||
## Involved Modules Or Areas
|
||||
|
||||
- `services/watchman`:模型、迁移、执行器、API、权限、数据源 references 回填。
|
||||
- `web/apps/console`:仅 S4 确认后的查询页面。
|
||||
- 不改 Casdoor 登录语义;不改熔断参数模型本身。
|
||||
|
||||
## Loaded Rules
|
||||
|
||||
- `AGENTS.md` 项目本地段;`.cursor/rules/sy-standards.mdc`
|
||||
- Marionettist `gatePolicy.selected=autonomous`
|
||||
|
||||
## Loaded Docs
|
||||
|
||||
- `docs/tasks/INDEX.md` M04;交接稿 A-02;`docs/decisions.md` D14/D19/D22/D23/D24
|
||||
- `docs/current/frontend-ui.md`
|
||||
- M03:`assert_usable`、datasources routes/services
|
||||
|
||||
## Global Forbidden Scope
|
||||
|
||||
- 口令、连接串、加密密钥、预览全文入仓库/日志/证据。
|
||||
- `.env.local`、`.cursor/mcp.json`
|
||||
- 映射/规则/报警/企微/场景 Cron 正式采集
|
||||
- 原型确认前的 Vue 查询页(S5 起允许)
|
||||
- 生产库、`git reset --hard`、未授权自动 commit
|
||||
|
||||
## Execution Strategy
|
||||
|
||||
- Complexity: complex
|
||||
- Default Execution: sequential
|
||||
- Parallel Execution: not-needed
|
||||
- Merge Owner: 主 Agent
|
||||
|
||||
## Slice Dependency Graph
|
||||
|
||||
| Slice | Depends On | Fallback Order | Gate Class | Risk Score |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| S1 模型与版本 | 分析确认 | 1 | high-risk | 4 |
|
||||
| S2 只读执行器 | S1 | 2 | high-risk | 4 |
|
||||
| S3 API 与权限 | S1、S2 | 3 | boundary-sensitive | 4 |
|
||||
| S4 HTML 原型 | S3 字段口径 | 4 | simple | 2 |
|
||||
| S5 Vue 页面 | S4 用户确认 | 5 | standard | 3 |
|
||||
| S6 整体验收 | S5 | 6 | boundary-sensitive | 3 |
|
||||
|
||||
## Implementation Slices
|
||||
|
||||
### Slice 1: 模型、迁移与不可变版本约束
|
||||
|
||||
#### Goal
|
||||
|
||||
平台库可按租户保存查询草稿与不可变版本;RLS 生效;版本内容更新路径在服务/测试层被拒绝。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `services/watchman/src/watchman/models/`
|
||||
- `services/watchman/migrations/`
|
||||
- `services/watchman/tests/` 本切片测试
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- API 路由、执行器真实连源、前端
|
||||
|
||||
#### Gate Class / Risk Score
|
||||
|
||||
high-risk / 4 — schema-migration
|
||||
|
||||
#### Validation
|
||||
|
||||
- `uv run pytest` 本切片测试;`alembic upgrade head`
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 表与 RLS 就绪;版本行内容不可被服务辅助函数更新(测试覆盖)
|
||||
|
||||
### Slice 2: 只读执行器
|
||||
|
||||
#### Goal
|
||||
|
||||
对给定 SQL 模板+参数+限制在 usable 数据源上只读执行;空/非法类型/失败三分;绑定防注入。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `services/watchman/src/watchman/queries/`(或等价包)
|
||||
- `services/watchman/src/watchman/services/` 执行相关
|
||||
- 测试;必要时薄改 datasources 记账调用
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 前端;发布 API 完整面
|
||||
|
||||
#### Gate Class / Risk Score
|
||||
|
||||
high-risk / 4 — device/datasource communication, injection
|
||||
|
||||
#### Validation
|
||||
|
||||
- 单元/集成:绑定、超时、行数、空结果、类型不匹配、参数含 SQL 片段不注入
|
||||
|
||||
### Slice 3: API、权限、引用回填
|
||||
|
||||
#### Goal
|
||||
|
||||
CRUD/启停/publish/版本/preview/references;四权限点;审计;数据源 references 列查询。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `api/routes/`、`auth/access.py`、`services/`、`api/app.py` 注册
|
||||
- datasources `list_references` 回填
|
||||
- 测试
|
||||
|
||||
#### Gate Class / Risk Score
|
||||
|
||||
boundary-sensitive / 4 — permissions, public API
|
||||
|
||||
#### Validation
|
||||
|
||||
- API 测试:权限拒绝、发布递增、版本只读、预览三分、信封
|
||||
|
||||
### Slice 4: HTML 原型
|
||||
|
||||
#### Goal
|
||||
|
||||
静态原型覆盖列表/编辑/版本/预览/角色门,供确认。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `.task/2026-11-18/m04-queries/prototype/` 仅
|
||||
|
||||
#### Gate Class / Risk Score
|
||||
|
||||
simple / 2
|
||||
|
||||
#### Stop
|
||||
|
||||
用户确认前不开始 S5。
|
||||
|
||||
### Slice 5: Vue 控制台
|
||||
|
||||
#### Goal
|
||||
|
||||
按确认原型与 D22 实现查询页与 e2e/单测。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `web/apps/console/**` 查询相关、导航、四语言、e2e
|
||||
|
||||
#### Gate Class / Risk Score
|
||||
|
||||
standard / 3
|
||||
|
||||
### Slice 6: 模块整体 review 与正式测试
|
||||
|
||||
#### Goal
|
||||
|
||||
独立 review、修复、pytest/unit/Playwright 证据、主 Agent 验收(DONE_LOCAL 仅用户最终确认后)。
|
||||
|
||||
#### Gate Class / Risk Score
|
||||
|
||||
boundary-sensitive / 3
|
||||
@@ -0,0 +1,46 @@
|
||||
# Task Intake Result
|
||||
|
||||
## Task Type
|
||||
|
||||
feature。Tier L(只读执行、注入防护、迁移、不可变版本、跨前后端)。
|
||||
|
||||
## Current Understanding
|
||||
|
||||
- M03 DONE_LOCAL。推进 M04:受控查询定义、参数/输出契约、只读执行、预览与配套 UI(A-016~A-020)。
|
||||
- 用户确认:参数化 SQL 模板(A);不可变查询版本本轮交付(2b);正式定时/场景采集留给 M08。
|
||||
- 正式 Vue 前须 HTML 原型确认(与 M03/D21 同模式)。
|
||||
- 执行须经 M03 `assert_usable`/熔断记账,不得绕过。
|
||||
|
||||
## Gate Policy
|
||||
|
||||
- config/default: balanced
|
||||
- allowTaskOverride: true
|
||||
- recommended: balanced
|
||||
- selected: autonomous
|
||||
- reason or override reason: 用户在 Marionettist 入口明确选择 autonomous。
|
||||
- effective: autonomous
|
||||
- finalApprovalRequired: true
|
||||
|
||||
说明:autonomous 不取消分析→编码门禁、最终验收、`gateClass: high-risk|boundary-sensitive`、critic、显式停点、危险命令,以及 `risk_score >= 4`。HTML 原型确认为 S5 前显式停点。用户于 2026-11-18 确认计划并要求执行全部 todos,视为越过分析→编码门禁。
|
||||
|
||||
## Blocking Questions
|
||||
|
||||
已关闭:
|
||||
|
||||
1. 查询正文 = 参数化 SQL 模板。
|
||||
2. M04 交付不可变查询版本(publish/只读历史);正式采集留给 M08。
|
||||
|
||||
## Non-blocking Assumptions
|
||||
|
||||
- 权限仅 `watchman-admin`,权限点 `watchman.query.{read,write,publish,preview}`。
|
||||
- 预览不进报警/通知。
|
||||
- 定义/版本 references 先空列表;数据源 references 可回填查询引用。
|
||||
- 标识符白名单用于不可绑定对象名;不靠 SELECT 前缀。
|
||||
|
||||
## Recommended Next Step
|
||||
|
||||
编码 S1(模型与迁移)。
|
||||
|
||||
## Suggested Prompt For Next Step
|
||||
|
||||
按 `implementation-plan.md` Slice 1 实现 query_definitions/query_versions 与 RLS/不可变约束测试。
|
||||
@@ -0,0 +1,79 @@
|
||||
# M04 查询定义 · 静态 HTML 原型(S4)
|
||||
|
||||
**状态:待维护者确认,确认前不得据此编写 Vue 页面。** 未经确认信息架构、按钮位置与各预览状态,不改正式 Vue 应用,也不动后端。
|
||||
|
||||
## 如何打开
|
||||
|
||||
直接用浏览器打开本目录的 `index.html`(双击即可)。单文件,无构建、无 CDN、无网络请求。
|
||||
|
||||
## 控件说明
|
||||
|
||||
顶部黄色虚线条「原型切换」不属于未来产品,只用于评审。
|
||||
|
||||
- **角色**:管理者 / 处理者 / 查看者。只有管理者能进入查询界面;处理者和查看者只看到「无法进入查询」(后端对应 42000 并带权限点)。
|
||||
- **画面**(仅管理者):空列表、列表、新建草稿、编辑草稿、编辑(已停用)、版本只读。
|
||||
- **预览结果**:未试跑 / 试跑中 / 成功 / 空结果 / 非法类型 / 失败 / 已停用 / 熔断中。点按钮立即展示该结果,并让之后点页脚「试跑预览」得到同一结果(先显示约 1 秒试跑中)。
|
||||
- **失败子类型**:超时 / 连接失败 / SQL 语法错误(三类分开展示;连接失败注明计入熔断统计)。
|
||||
- 编辑页中的名称、SQL、参数、输出、标识符、限制可以真的改;「保存草稿」「发布」「停用/启用」只修改本页内存数据,刷新即还原。
|
||||
|
||||
## 原型包含
|
||||
|
||||
| 画面 | 内容 |
|
||||
| --- | --- |
|
||||
| 门禁 | 非管理者看到拒绝页,无列表、无表单 |
|
||||
| 空列表 | 说明 + 表格上方「新建」 |
|
||||
| 列表 | 名称、数据源、状态、最新版本、更新时间、行内「打开」「预览」;已停用行「预览」置灰 |
|
||||
| 新建/编辑草稿 | 名称、用途说明、数据源(已停用的灰显)、SQL 模板(示例 `:line_code`,实时标出未声明参数)、参数 schema(名称/类型/必填/默认值)、输出 schema(名称/类型)、允许标识符(标签)、`timeout_ms`、`max_rows`、状态、试跑预览区、版本列表、引用占位 |
|
||||
| 版本只读 | 冻结的 SQL、参数、输出、标识符、限制;可试跑;无保存、无发布 |
|
||||
| 预览结果 | 成功(样例行,示例脱敏列)、空结果、非法类型(契约不符明细)、失败(超时/连接/语法)、已停用、熔断中 |
|
||||
| 发布 | 页脚「发布」弹出确认;有未保存修改时先提示保存;成功后版本列表新增 vN |
|
||||
|
||||
页脚按钮(居中、在滚动区外):
|
||||
|
||||
- 新建:返回列表、保存草稿、发布(置灰,需先保存)、试跑预览(置灰,需先保存)。
|
||||
- 编辑草稿:返回列表、保存草稿、发布、停用/启用、试跑预览。
|
||||
- 版本只读:返回列表、返回草稿、试跑预览。
|
||||
- 列表页「新建」在表格上方;行内「打开」「预览」留在行内;版本列表行内「打开」。依据 `docs/current/frontend-ui.md`(D22)。
|
||||
|
||||
## 原型不包含
|
||||
|
||||
- 真实请求、真实数据源或口令;所有数据虚构,数据源名称无真实地址。
|
||||
- 结构化表/字段选择器、任意脚本、字段映射、规则、报警、通知、场景定时采集。
|
||||
- 非数据库数据源、查询物理删除、列表分页/筛选、审计页。
|
||||
- 引用的具体内容(查询侧恒为「尚无引用」)。
|
||||
- 服务端上限的真实值(页面里的 30000/1000 仅为示意)。
|
||||
|
||||
## 按钮与未来 Vue(Element Plus)对应
|
||||
|
||||
| 原型 | Vue 实现 |
|
||||
| --- | --- |
|
||||
| 列表「新建」 | `el-button type="primary"`,放在 `el-table` 上方 |
|
||||
| 列表/版本表 | `el-table`;行内「打开」「预览」用 `el-button link` |
|
||||
| 状态 | `el-tag` 或 `el-badge`;停用行「预览」`disabled` |
|
||||
| 表单 | `el-form` + `el-form-item`、`el-input`、`el-input type="textarea"`、`el-select`、`el-input-number` |
|
||||
| SQL 模板 | `el-input type="textarea"` 等宽字体(如需高亮另行评审,不引入新依赖前先问) |
|
||||
| 参数/输出 schema | 可编辑 `el-table` + `el-input`/`el-select`/`el-checkbox`;行内删除 |
|
||||
| 允许标识符 | `el-tag closable` + `el-input` 回车添加 |
|
||||
| 页脚 | 滚动区外的固定区,`el-button` 居中;保存草稿 `primary`,发布 `plain`,停用 `type="danger" plain`,其余默认 |
|
||||
| 发布确认 | `ElMessageBox.confirm` |
|
||||
| 预览结果 | `el-alert`(成功/警告/错误)+ `el-table` 展示样例;试跑中用 `v-loading` |
|
||||
| 无权限 | 空状态页(`el-empty`);真正权限由后端判定,前端隐藏不算安全控制 |
|
||||
| 原型切换条、「原型本地模拟」提示、`正式版本进行删除` 标注 | 正式版全部删除 |
|
||||
|
||||
视觉 token:主色 `#5e6ad2`、圆角 8px、基础字号 13.5px。
|
||||
|
||||
## 请维护者确认
|
||||
|
||||
1. 预览使用「已保存草稿」还是「表单当前内容」?原型按已保存草稿,有未保存修改时给提示。
|
||||
2. 查询停用后:「试跑预览」按钮仍可点并明确拒绝(原型做法),还是直接置灰?停用时「发布」是否允许?原型未限制。
|
||||
3. 发布入口只在页脚(原型做法),版本区不放第二个发布按钮,是否同意?
|
||||
4. 输出契约只有名称和类型,敏感列脱敏策略未设字段;原型只用固定示例遮盖 `operator_name`。是否需要「脱敏」列?
|
||||
5. 标识符白名单的 SQL 占位语法未定;原型只展示允许列表。
|
||||
6. 版本只读页面包含数据源名,并以 `详情 / 版本 vN` 作为面包屑,是否合适?
|
||||
7. 预览成功样例固定 3 行;超出 `max_rows` 的截断提示未做。是否需要?
|
||||
8. 失败子类型中,超时是否计入熔断,以后端口径为准,原型未声明。
|
||||
|
||||
## 约束
|
||||
|
||||
- 所有数据均为虚构;不含真实口令;不含 API 调用。
|
||||
- 不改 Vue 应用与后端,不提交 git。
|
||||
@@ -0,0 +1,842 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Watchman M04 查询定义 · 静态原型(S4)</title>
|
||||
<style>
|
||||
:root {
|
||||
--primary: #5e6ad2;
|
||||
--primary-soft: #eef0fb;
|
||||
--text: #1f2328;
|
||||
--text-2: #59636e;
|
||||
--muted: #8b949e;
|
||||
--surface: #ffffff;
|
||||
--soft: #f6f8fa;
|
||||
--border: #d0d7de;
|
||||
--border-2: #eaeef2;
|
||||
--ok: #1a7f37;
|
||||
--ok-bg: #e9f6ec;
|
||||
--warn: #9a6700;
|
||||
--warn-bg: #fff8e1;
|
||||
--err: #cf222e;
|
||||
--err-bg: #fdecee;
|
||||
--radius: 8px;
|
||||
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; height: 100%; }
|
||||
body { font-family: var(--font); font-size: 13.5px; color: var(--text); background: var(--soft); line-height: 1.55; }
|
||||
button, input, select, textarea { font: inherit; color: inherit; }
|
||||
[hidden] { display: none !important; }
|
||||
|
||||
/* ---- prototype toolbar (not part of product) ---- */
|
||||
.proto {
|
||||
background: #fffbe6; border-bottom: 1px dashed #d4b106; padding: 8px 16px;
|
||||
display: flex; flex-wrap: wrap; gap: 8px 20px; align-items: center; font-size: 12.5px;
|
||||
}
|
||||
.proto-title { font-weight: 600; color: #7a5b00; }
|
||||
.proto-group { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
|
||||
.proto-group > .lbl { color: var(--text-2); margin-right: 2px; }
|
||||
.proto-btn {
|
||||
border: 1px solid var(--border); background: var(--surface); border-radius: 6px;
|
||||
padding: 2px 9px; cursor: pointer; font-size: 12.5px;
|
||||
}
|
||||
.proto-btn:hover { border-color: var(--primary); color: var(--primary); }
|
||||
.proto-btn.on { background: var(--primary); border-color: var(--primary); color: #fff; }
|
||||
.proto-note { flex-basis: 100%; color: #7a5b00; }
|
||||
.proto select { border: 1px solid var(--border); border-radius: 6px; padding: 2px 6px; background: #fff; font-size: 12.5px; }
|
||||
|
||||
/* ---- shell ---- */
|
||||
.shell { display: flex; height: calc(100vh - 120px); min-height: 520px; }
|
||||
.side { width: 196px; flex: none; background: var(--surface); border-right: 1px solid var(--border-2); padding: 14px 10px; }
|
||||
.brand { font-weight: 700; font-size: 16px; padding: 4px 10px 14px; letter-spacing: .3px; }
|
||||
.nav-item { padding: 7px 10px; border-radius: 6px; color: var(--text-2); }
|
||||
.nav-item.cur { background: var(--primary-soft); color: var(--primary); font-weight: 600; }
|
||||
.nav-item.off { color: var(--muted); }
|
||||
.main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
|
||||
.top { height: 48px; flex: none; background: var(--surface); border-bottom: 1px solid var(--border-2);
|
||||
display: flex; align-items: center; justify-content: space-between; padding: 0 20px; }
|
||||
.pagefoot { flex: none; background: var(--surface); border-top: 1px solid var(--border-2);
|
||||
display: flex; align-items: center; justify-content: center; flex-wrap: wrap; gap: 8px; padding: 12px 20px; }
|
||||
.list-actions { display: flex; justify-content: flex-end; margin-bottom: 12px; }
|
||||
.crumb { color: var(--text-2); }
|
||||
.crumb b { color: var(--text); font-weight: 600; }
|
||||
.who { color: var(--text-2); display: flex; align-items: center; gap: 8px; }
|
||||
.tag { display: inline-block; padding: 0 8px; border-radius: 10px; font-size: 12px; line-height: 20px; background: var(--primary-soft); color: var(--primary); }
|
||||
.tag.grey { background: var(--soft); color: var(--text-2); border: 1px solid var(--border-2); }
|
||||
.tag.ok { background: var(--ok-bg); color: var(--ok); }
|
||||
.tag.warn { background: var(--warn-bg); color: var(--warn); }
|
||||
.content { flex: 1; overflow: auto; padding: 20px; }
|
||||
.local-banner { background: var(--primary-soft); border: 1px solid #d5d9f5; color: #3f49a8; border-radius: var(--radius);
|
||||
padding: 7px 12px; margin-bottom: 14px; font-size: 12.5px; }
|
||||
.flash { border-radius: var(--radius); padding: 8px 12px; margin-bottom: 14px; border: 1px solid; font-size: 13px; }
|
||||
.flash.ok { background: var(--ok-bg); border-color: #b7e0c2; color: #145c2a; }
|
||||
.flash.warn { background: var(--warn-bg); border-color: #f1dc9a; color: var(--warn); }
|
||||
.flash.bad { background: var(--err-bg); border-color: #f4b8be; color: #8e1a23; }
|
||||
.card { background: var(--surface); border: 1px solid var(--border-2); border-radius: var(--radius); padding: 16px 18px; margin-bottom: 16px; }
|
||||
.card h3 { margin: 0 0 12px; font-size: 14.5px; display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.card h3 .sub { font-weight: 400; font-size: 12px; color: var(--muted); }
|
||||
.btn { border: 1px solid var(--border); background: var(--surface); border-radius: 6px; padding: 5px 14px; cursor: pointer; }
|
||||
.btn:hover:not(:disabled) { border-color: var(--primary); color: var(--primary); }
|
||||
.btn.primary { background: var(--primary); border-color: var(--primary); color: #fff; }
|
||||
.btn.primary:hover:not(:disabled) { background: #4f5bc4; color: #fff; }
|
||||
.btn.outline { border-color: var(--primary); color: var(--primary); }
|
||||
.btn.danger { color: var(--err); }
|
||||
.btn.danger:hover:not(:disabled) { border-color: var(--err); color: var(--err); }
|
||||
.btn.sm { padding: 1px 8px; font-size: 12.5px; }
|
||||
.btn:disabled { color: var(--muted); background: var(--soft); border-color: var(--border); cursor: not-allowed; }
|
||||
.btn.link { border: 0; background: none; color: var(--primary); padding: 1px 6px; }
|
||||
.btn.link.danger { color: var(--err); }
|
||||
.btn.link:disabled { color: var(--muted); background: none; }
|
||||
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th { text-align: left; font-weight: 600; color: var(--text-2); background: var(--soft); padding: 9px 12px; border-bottom: 1px solid var(--border-2); white-space: nowrap; }
|
||||
td { padding: 10px 12px; border-bottom: 1px solid var(--border-2); vertical-align: middle; }
|
||||
tr.hl td { background: #fafbff; }
|
||||
tr.off td { color: var(--muted); }
|
||||
.mono { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12.5px; }
|
||||
.table-wrap { overflow-x: auto; border: 1px solid var(--border-2); border-radius: var(--radius); background: var(--surface); }
|
||||
.table-wrap table th:first-child, .table-wrap table td:first-child { padding-left: 16px; }
|
||||
.table-wrap.inner table td { padding: 6px 10px; }
|
||||
.ops { white-space: nowrap; }
|
||||
.tbl-tools { display: flex; justify-content: flex-end; margin: -4px 0 8px; }
|
||||
|
||||
.status { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ok); }
|
||||
.status.off .dot { background: var(--muted); }
|
||||
|
||||
.empty { text-align: center; padding: 56px 20px; background: var(--surface); border: 1px dashed var(--border); border-radius: var(--radius); }
|
||||
.empty h3 { margin: 0 0 6px; font-size: 15px; }
|
||||
.empty p { margin: 0 0 14px; color: var(--text-2); }
|
||||
.empty.sm { padding: 18px 20px; }
|
||||
.empty.sm p { margin: 0; }
|
||||
|
||||
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 24px; max-width: 820px; }
|
||||
.field { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
|
||||
.field.full { grid-column: 1 / -1; }
|
||||
.field > label { color: var(--text-2); font-size: 12.5px; }
|
||||
.req { color: var(--err); margin-left: 2px; }
|
||||
input[type=text], input[type=number], select, textarea {
|
||||
border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; background: var(--surface); width: 100%; outline: none; }
|
||||
input:focus, select:focus, textarea:focus { border-color: var(--primary); box-shadow: 0 0 0 2px var(--primary-soft); }
|
||||
input:disabled, select:disabled, textarea:disabled { background: var(--soft); color: var(--text-2); cursor: not-allowed; }
|
||||
.table-wrap.inner input[type=text], .table-wrap.inner select { padding: 3px 8px; }
|
||||
textarea.sql { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12.5px; line-height: 1.6; resize: vertical; }
|
||||
pre.sql { margin: 0; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12.5px; line-height: 1.6;
|
||||
background: var(--soft); border: 1px solid var(--border-2); border-radius: 6px; padding: 10px 12px; white-space: pre-wrap; }
|
||||
.hint { color: var(--muted); font-size: 12px; }
|
||||
.drop-later { color: #7a5b00; }
|
||||
.check { display: flex; align-items: center; gap: 8px; }
|
||||
|
||||
.chips { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-top: 6px; }
|
||||
.chip { display: inline-flex; align-items: center; gap: 4px; padding: 0 8px; line-height: 22px; border-radius: 4px; font-size: 12px;
|
||||
border: 1px solid var(--border); background: var(--soft); font-family: ui-monospace, Consolas, monospace; }
|
||||
.chip.ok { background: var(--ok-bg); border-color: #b7e0c2; color: #145c2a; }
|
||||
.chip.bad { background: var(--err-bg); border-color: #f4b8be; color: #8e1a23; }
|
||||
.chip.dim { color: var(--muted); }
|
||||
.chip button { border: 0; background: none; cursor: pointer; color: var(--muted); padding: 0 2px; }
|
||||
.chip button:hover { color: var(--err); }
|
||||
.ident-add { display: flex; gap: 8px; margin-top: 10px; max-width: 420px; }
|
||||
|
||||
.note { border-radius: var(--radius); padding: 8px 12px; font-size: 12.5px; background: var(--soft); border: 1px solid var(--border-2); color: var(--text-2); }
|
||||
.note.warn { background: var(--warn-bg); border-color: #f1dc9a; color: var(--warn); }
|
||||
|
||||
.pv-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px 20px; max-width: 820px; margin-bottom: 12px; }
|
||||
.pv-target { margin-bottom: 10px; color: var(--text-2); font-size: 12.5px; }
|
||||
|
||||
.result { border-radius: var(--radius); padding: 12px 14px; border: 1px solid; margin-top: 12px; }
|
||||
.result .r-title { font-weight: 600; margin-bottom: 2px; }
|
||||
.result .r-body { font-size: 13px; }
|
||||
.result .r-meta { margin-top: 6px; font-size: 12px; opacity: .85; }
|
||||
.result .r-table { margin-top: 10px; background: #fff; color: var(--text); }
|
||||
.result .r-table td, .result .r-table th { white-space: nowrap; }
|
||||
.result.ok { background: var(--ok-bg); border-color: #b7e0c2; color: #145c2a; }
|
||||
.result.bad { background: var(--err-bg); border-color: #f4b8be; color: #8e1a23; }
|
||||
.result.pend { background: var(--primary-soft); border-color: #d5d9f5; color: #3f49a8; }
|
||||
.result.warn { background: var(--warn-bg); border-color: #f1dc9a; color: var(--warn); }
|
||||
.result.grey { background: var(--soft); border-color: var(--border); color: var(--text-2); }
|
||||
.spin { display: inline-block; width: 12px; height: 12px; border: 2px solid #c3c8f0; border-top-color: var(--primary); border-radius: 50%; animation: sp .8s linear infinite; vertical-align: -2px; margin-right: 6px; }
|
||||
@keyframes sp { to { transform: rotate(360deg); } }
|
||||
.focus { outline: 2px solid var(--primary-soft); border-color: var(--primary); }
|
||||
|
||||
.kv { display: grid; grid-template-columns: 96px 1fr; gap: 4px 12px; font-size: 13px; }
|
||||
.kv dt { color: var(--muted); } .kv dd { margin: 0; }
|
||||
|
||||
.modal-mask { position: fixed; inset: 0; background: rgba(31,35,40,.4); display: flex; align-items: center; justify-content: center; z-index: 10; }
|
||||
.modal { background: #fff; border-radius: var(--radius); padding: 18px 20px; width: 400px; max-width: 90vw; box-shadow: 0 8px 28px rgba(0,0,0,.18); }
|
||||
.modal h3 { margin: 0 0 8px; font-size: 15px; }
|
||||
.modal p { margin: 0 0 16px; color: var(--text-2); }
|
||||
.modal .row { display: flex; justify-content: flex-end; gap: 8px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="proto" id="proto">
|
||||
<span class="proto-title">原型切换</span>
|
||||
<div class="proto-group"><span class="lbl">角色</span><span id="p-roles"></span></div>
|
||||
<div class="proto-group"><span class="lbl">画面</span><span id="p-screens"></span></div>
|
||||
<div class="proto-group"><span class="lbl">预览结果</span><span id="p-results"></span></div>
|
||||
<div class="proto-group" id="p-fsub-wrap"><span class="lbl">失败子类型</span><select id="p-fsub"></select></div>
|
||||
<div class="proto-note">此条仅用于评审,不属于未来产品。所有数据均为虚构,页面不发送任何网络请求,不含真实密码或地址。点「预览结果」按钮会立即展示该结果,并让页脚「试跑预览」之后得到同一结果。正式版本进行删除</div>
|
||||
</div>
|
||||
|
||||
<div class="shell" id="shell">
|
||||
<aside class="side">
|
||||
<div class="brand">Watchman</div>
|
||||
<div class="nav-item off">数据源</div>
|
||||
<div class="nav-item cur" id="nav-q">查询</div>
|
||||
</aside>
|
||||
<div class="main">
|
||||
<header class="top">
|
||||
<div class="crumb" id="crumb">Watchman / <b>查询</b></div>
|
||||
<div class="who">当前角色 <span class="tag" id="who-role"></span></div>
|
||||
</header>
|
||||
<main class="content" id="view"></main>
|
||||
<div class="pagefoot" id="pagefoot" hidden></div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="modal-root"></div>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var ROLES = { admin: '管理者', handler: '处理者', viewer: '查看者' };
|
||||
var SCREENS = [
|
||||
['empty', '空列表'], ['list', '列表'], ['create', '新建草稿'], ['edit', '编辑草稿'], ['editoff', '编辑(已停用)'], ['version', '版本只读']
|
||||
];
|
||||
var RESULT_KINDS = [
|
||||
['none', '未试跑'], ['running', '试跑中'], ['success', '成功'], ['empty', '空结果'], ['illegal_type', '非法类型'],
|
||||
['failure', '失败'], ['disabled', '已停用'], ['circuit_open', '熔断中']
|
||||
];
|
||||
var FSUB = [['timeout', '超时'], ['connection', '连接失败'], ['syntax', 'SQL 语法错误']];
|
||||
var TYPES = ['string', 'integer', 'number', 'boolean', 'datetime'];
|
||||
var NOW = '2026-11-18 14:37';
|
||||
|
||||
// All sample data below is fictional. Hosts/datasources use reserved ".example.test" naming only.
|
||||
var DS = [
|
||||
{ id: 'ds1', name: '产线工艺库', on: true },
|
||||
{ id: 'ds2', name: '设备台账库', on: true },
|
||||
{ id: 'ds3', name: '质检结果库', on: true },
|
||||
{ id: 'ds4', name: '历史归档库', on: false }
|
||||
];
|
||||
|
||||
var SQL1 = 'SELECT lot_no, temperature, operator_name, measured_at\nFROM process_readings\nWHERE line_code = :line_code\n AND measured_at >= :since\n AND temperature >= :min_temp\nORDER BY measured_at DESC';
|
||||
var SQL1_V2 = 'SELECT lot_no, temperature, measured_at\nFROM process_readings\nWHERE line_code = :line_code\n AND measured_at >= :since';
|
||||
var SQL1_V1 = 'SELECT lot_no, temperature\nFROM process_readings\nWHERE line_code = :line_code';
|
||||
var P_LINE = { name: 'line_code', type: 'string', req: true, def: '' };
|
||||
var P_SINCE = { name: 'since', type: 'datetime', req: false, def: '2026-11-17 00:00:00' };
|
||||
var P_MIN = { name: 'min_temp', type: 'number', req: false, def: '0' };
|
||||
|
||||
function clone(x) { return JSON.parse(JSON.stringify(x)); }
|
||||
function ver(no, at, sql, params, outputs, idents, timeout, maxRows) {
|
||||
return { no: no, at: at, by: 'admin.demo', sql: sql, params: clone(params), outputs: clone(outputs), idents: idents.slice(), timeout: timeout, maxRows: maxRows };
|
||||
}
|
||||
|
||||
var QUERIES = [
|
||||
{ id: 1, name: '产线温度采样', desc: '示例:按产线与时间窗取最近温度读数(虚构)', ds: 'ds1', on: true, updated: '2026-11-18 09:40',
|
||||
sql: SQL1, params: [P_LINE, P_SINCE, P_MIN],
|
||||
outputs: [{ name: 'lot_no', type: 'string' }, { name: 'temperature', type: 'number' }, { name: 'operator_name', type: 'string' }, { name: 'measured_at', type: 'datetime' }],
|
||||
idents: ['process_readings', 'lot_no', 'temperature', 'operator_name', 'measured_at'], timeout: 5000, maxRows: 200, versions: [] },
|
||||
{ id: 2, name: '设备停机记录', desc: '示例:按设备编码取停机事件(虚构)', ds: 'ds2', on: true, updated: '2026-11-17 16:05',
|
||||
sql: 'SELECT equipment_code, stop_reason, stopped_at, duration_min\nFROM equipment_downtime\nWHERE equipment_code = :equipment_code\n AND stopped_at >= :since',
|
||||
params: [{ name: 'equipment_code', type: 'string', req: true, def: '' }, P_SINCE],
|
||||
outputs: [{ name: 'equipment_code', type: 'string' }, { name: 'stop_reason', type: 'string' }, { name: 'stopped_at', type: 'datetime' }, { name: 'duration_min', type: 'integer' }],
|
||||
idents: ['equipment_downtime'], timeout: 3000, maxRows: 100, versions: [] },
|
||||
{ id: 3, name: '质检不良统计', desc: '示例:按批次汇总不良代码,尚未发布(虚构)', ds: 'ds3', on: false, updated: '2026-11-16 11:22',
|
||||
sql: 'SELECT defect_code, COUNT(*) AS cnt\nFROM qc_results\nWHERE batch_no = :batch_no\nGROUP BY defect_code',
|
||||
params: [{ name: 'batch_no', type: 'string', req: true, def: '' }],
|
||||
outputs: [{ name: 'defect_code', type: 'string' }, { name: 'cnt', type: 'integer' }],
|
||||
idents: ['qc_results'], timeout: 5000, maxRows: 200, versions: [] },
|
||||
{ id: 4, name: '在制批次清单', desc: '示例:当前在制批次(虚构)', ds: 'ds1', on: true, updated: '2026-11-15 08:50',
|
||||
sql: 'SELECT lot_no, step_code, started_at\nFROM wip_lots\nWHERE line_code = :line_code',
|
||||
params: [P_LINE],
|
||||
outputs: [{ name: 'lot_no', type: 'string' }, { name: 'step_code', type: 'string' }, { name: 'started_at', type: 'datetime' }],
|
||||
idents: ['wip_lots'], timeout: 5000, maxRows: 500, versions: [] }
|
||||
];
|
||||
(function seed() {
|
||||
var q1 = QUERIES[0], q2 = QUERIES[1], q4 = QUERIES[3];
|
||||
q1.versions = [
|
||||
ver(3, '2026-11-18 09:40', SQL1, q1.params, q1.outputs, q1.idents, 5000, 200),
|
||||
ver(2, '2026-11-14 15:20', SQL1_V2, [P_LINE, P_SINCE], [{ name: 'lot_no', type: 'string' }, { name: 'temperature', type: 'number' }, { name: 'measured_at', type: 'datetime' }], ['process_readings'], 5000, 100),
|
||||
ver(1, '2026-11-10 10:02', SQL1_V1, [P_LINE], [{ name: 'lot_no', type: 'string' }, { name: 'temperature', type: 'number' }], ['process_readings'], 3000, 50)
|
||||
];
|
||||
q2.versions = [ver(1, '2026-11-17 16:05', q2.sql, q2.params, q2.outputs, q2.idents, 3000, 100)];
|
||||
q4.versions = [
|
||||
ver(2, '2026-11-15 08:50', q4.sql, q4.params, q4.outputs, q4.idents, 5000, 500),
|
||||
ver(1, '2026-11-12 13:30', q4.sql, q4.params, q4.outputs.slice(0, 2), q4.idents, 5000, 200)
|
||||
];
|
||||
})();
|
||||
|
||||
var state = {
|
||||
role: 'admin', screen: 'list', cur: 1, ver: 3, draft: null, pvals: {}, preview: null,
|
||||
sim: 'success', fsub: 'timeout', flash: null, dirty: false, modal: false,
|
||||
focusPreview: false, scrollPreview: false, refocus: null, timer: null, nextId: 5
|
||||
};
|
||||
|
||||
function $(id) { return document.getElementById(id); }
|
||||
function isAdmin() { return state.role === 'admin'; }
|
||||
function esc(s) { return String(s == null ? '' : s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); }
|
||||
function later(text) { return text + ' <span class="drop-later">正式版本进行删除</span>'; }
|
||||
function qById(id) { for (var i = 0; i < QUERIES.length; i++) if (QUERIES[i].id === id) return QUERIES[i]; return QUERIES[0]; }
|
||||
function curQ() { return qById(state.cur); }
|
||||
function dsName(id) { for (var i = 0; i < DS.length; i++) if (DS[i].id === id) return DS[i].name; return '—'; }
|
||||
function verOf(q, no) { for (var i = 0; i < q.versions.length; i++) if (q.versions[i].no === no) return q.versions[i]; return q.versions[0]; }
|
||||
function latestNo(q) { return q.versions.length ? q.versions[0].no : 0; }
|
||||
function isCreate() { return state.screen === 'create'; }
|
||||
function isVersion() { return state.screen === 'version'; }
|
||||
|
||||
/* ---------- draft / preview params ---------- */
|
||||
function blankDraft() {
|
||||
return { name: '', desc: '', ds: 'ds1', sql: '', params: [], outputs: [], idents: [], timeout: 5000, maxRows: 200 };
|
||||
}
|
||||
function loadDraft(id) {
|
||||
var q = qById(id);
|
||||
state.draft = { name: q.name, desc: q.desc, ds: q.ds, sql: q.sql, params: clone(q.params), outputs: clone(q.outputs), idents: q.idents.slice(), timeout: q.timeout, maxRows: q.maxRows };
|
||||
state.dirty = false;
|
||||
}
|
||||
function sourceParams() { return isVersion() ? verOf(curQ(), state.ver).params : state.draft.params; }
|
||||
function initPvals() {
|
||||
state.pvals = {};
|
||||
sourceParams().forEach(function (p) { state.pvals[p.name] = p.def || ''; });
|
||||
}
|
||||
function setPath(path, val) {
|
||||
var parts = path.split('.'), o = state, i;
|
||||
for (i = 0; i < parts.length - 1; i++) o = o[parts[i]];
|
||||
o[parts[parts.length - 1]] = val;
|
||||
}
|
||||
|
||||
/* ---------- prototype toolbar ---------- */
|
||||
function screenOn(id) {
|
||||
var s = state.screen, q = qById(state.cur);
|
||||
if (id === 'edit') return s === 'edit' && q.on;
|
||||
if (id === 'editoff') return s === 'edit' && !q.on;
|
||||
return s === id;
|
||||
}
|
||||
function renderProto() {
|
||||
var r = '', s = '', k, b = '';
|
||||
for (k in ROLES) r += '<button class="proto-btn' + (state.role === k ? ' on' : '') + '" data-role="' + k + '">' + ROLES[k] + '</button> ';
|
||||
$('p-roles').innerHTML = r;
|
||||
SCREENS.forEach(function (x) { s += '<button class="proto-btn' + (screenOn(x[0]) ? ' on' : '') + '" data-screen="' + x[0] + '">' + x[1] + '</button> '; });
|
||||
$('p-screens').innerHTML = s;
|
||||
RESULT_KINDS.forEach(function (x) { b += '<button class="proto-btn' + ((state.preview || 'none') === x[0] ? ' on' : '') + '" data-result="' + x[0] + '">' + x[1] + '</button> '; });
|
||||
$('p-results').innerHTML = b;
|
||||
var o = '';
|
||||
FSUB.forEach(function (x) { o += '<option value="' + x[0] + '"' + (state.fsub === x[0] ? ' selected' : '') + '>' + x[1] + '</option>'; });
|
||||
$('p-fsub').innerHTML = o;
|
||||
$('who-role').textContent = ROLES[state.role];
|
||||
$('nav-q').className = 'nav-item' + (isAdmin() ? ' cur' : ' off');
|
||||
}
|
||||
|
||||
/* ---------- shared pieces ---------- */
|
||||
function banner() {
|
||||
return '<div class="local-banner">' + later('原型本地模拟:此页面不会向任何服务发送请求,「保存草稿」「发布」「试跑预览」等只会切换本页的演示状态。') + '</div>' +
|
||||
(state.flash ? '<div class="flash ' + state.flash[0] + '">' + esc(state.flash[1]) + '</div>' : '');
|
||||
}
|
||||
function setCrumb(leaf) {
|
||||
var html = 'Watchman / <b>查询</b>';
|
||||
if (leaf) html += ' / <b>' + leaf + '</b>';
|
||||
$('crumb').innerHTML = html;
|
||||
}
|
||||
function setFoot(actions) {
|
||||
var foot = $('pagefoot');
|
||||
foot.hidden = !actions;
|
||||
foot.innerHTML = actions || '';
|
||||
}
|
||||
function statusCell(q) {
|
||||
return q.on ? '<span class="status"><span class="dot"></span>启用</span>' : '<span class="status off"><span class="dot"></span>已停用</span>';
|
||||
}
|
||||
function verCell(q) { return q.versions.length ? 'v' + latestNo(q) : '<span class="hint">未发布</span>'; }
|
||||
|
||||
function listTable(rows) {
|
||||
var h = '<div class="table-wrap"><table><thead><tr>' +
|
||||
'<th>名称</th><th>数据源</th><th>状态</th><th>最新版本</th><th>更新时间</th><th>操作</th></tr></thead><tbody>';
|
||||
rows.forEach(function (q) {
|
||||
var dsOff = false;
|
||||
h += '<tr class="' + (q.on ? '' : 'off') + '"><td>' + esc(q.name) + '</td><td>' + esc(dsName(q.ds)) + '</td><td>' + statusCell(q) +
|
||||
'</td><td class="mono">' + verCell(q) + '</td><td class="mono">' + q.updated + '</td><td class="ops">' +
|
||||
'<button class="btn link" data-act="open" data-id="' + q.id + '">打开</button>' +
|
||||
'<button class="btn link"' + (q.on && !dsOff ? ' data-act="preview" data-id="' + q.id + '"' : ' disabled title="已停用,不能预览"') + '>预览</button>' +
|
||||
'</td></tr>';
|
||||
});
|
||||
return h + '</tbody></table></div>';
|
||||
}
|
||||
|
||||
/* ---------- schema editors ---------- */
|
||||
function typeSelect(path, val, ro) {
|
||||
var h = '<select data-bind="' + path + '"' + (ro ? ' disabled' : '') + '>';
|
||||
TYPES.forEach(function (t) { h += '<option' + (t === val ? ' selected' : '') + '>' + t + '</option>'; });
|
||||
return h + '</select>';
|
||||
}
|
||||
function paramsEditor(ps, ro) {
|
||||
var h = '';
|
||||
if (!ro) h += '<div class="tbl-tools"><button class="btn sm" data-act="add-param">添加参数</button></div>';
|
||||
if (!ps.length) return h + '<div class="empty sm"><p>尚未声明参数。SQL 中的 :name 必须在此声明,未声明的参数会被拒绝。</p></div>';
|
||||
h += '<div class="table-wrap inner"><table><thead><tr><th>参数名</th><th>类型</th><th>必填</th><th>默认值</th>' + (ro ? '' : '<th>操作</th>') + '</tr></thead><tbody>';
|
||||
ps.forEach(function (p, i) {
|
||||
var b = 'draft.params.' + i;
|
||||
if (ro) {
|
||||
h += '<tr><td class="mono">' + esc(p.name) + '</td><td class="mono">' + p.type + '</td><td>' + (p.req ? '是' : '否') + '</td><td class="mono">' + (p.def === '' ? '<span class="hint">—</span>' : esc(p.def)) + '</td></tr>';
|
||||
} else {
|
||||
h += '<tr><td><input type="text" class="mono" data-bind="' + b + '.name" value="' + esc(p.name) + '" placeholder="例如 line_code"></td>' +
|
||||
'<td>' + typeSelect(b + '.type', p.type) + '</td>' +
|
||||
'<td><input type="checkbox" data-bind="' + b + '.req"' + (p.req ? ' checked' : '') + '></td>' +
|
||||
'<td><input type="text" data-bind="' + b + '.def" value="' + esc(p.def) + '" placeholder="可空"></td>' +
|
||||
'<td class="ops"><button class="btn link danger" data-act="del-param" data-i="' + i + '">删除</button></td></tr>';
|
||||
}
|
||||
});
|
||||
return h + '</tbody></table></div>';
|
||||
}
|
||||
function outputsEditor(os, ro) {
|
||||
var h = '';
|
||||
if (!ro) h += '<div class="tbl-tools"><button class="btn sm" data-act="add-out">添加输出字段</button></div>';
|
||||
if (!os.length) return h + '<div class="empty sm"><p>尚未声明输出字段。输出契约用于检查结果类型。</p></div>';
|
||||
h += '<div class="table-wrap inner"><table><thead><tr><th>字段名</th><th>类型</th>' + (ro ? '' : '<th>操作</th>') + '</tr></thead><tbody>';
|
||||
os.forEach(function (o, i) {
|
||||
var b = 'draft.outputs.' + i;
|
||||
if (ro) h += '<tr><td class="mono">' + esc(o.name) + '</td><td class="mono">' + o.type + '</td></tr>';
|
||||
else h += '<tr><td><input type="text" class="mono" data-bind="' + b + '.name" value="' + esc(o.name) + '" placeholder="例如 lot_no"></td>' +
|
||||
'<td>' + typeSelect(b + '.type', o.type) + '</td>' +
|
||||
'<td class="ops"><button class="btn link danger" data-act="del-out" data-i="' + i + '">删除</button></td></tr>';
|
||||
});
|
||||
return h + '</tbody></table></div>';
|
||||
}
|
||||
function identsBlock(ids, ro) {
|
||||
var h = '<div class="chips">';
|
||||
if (!ids.length) h += '<span class="hint">无(不允许动态标识符)</span>';
|
||||
ids.forEach(function (t, i) {
|
||||
h += '<span class="chip">' + esc(t) + (ro ? '' : '<button title="移除" data-act="del-ident" data-i="' + i + '">×</button>') + '</span>';
|
||||
});
|
||||
h += '</div>';
|
||||
if (!ro) h += '<div class="ident-add"><input type="text" id="f-ident-input" placeholder="输入标识符后按回车,例如 process_readings"><button class="btn" data-act="add-ident">添加</button></div>';
|
||||
h += '<div class="hint" style="margin-top:6px">' + later('标识符(表/字段名)不能作为绑定参数的值;只有这里声明的名称允许出现在 SQL 的标识符位置,留空即不允许。占位语法待维护者确认。') + '</div>';
|
||||
return h;
|
||||
}
|
||||
|
||||
/* ---------- SQL chips (live) ---------- */
|
||||
function detectParams(sql) {
|
||||
var out = [], re = /(^|[^:\w]):([A-Za-z_]\w*)/g, m;
|
||||
while ((m = re.exec(sql || ''))) if (out.indexOf(m[2]) < 0) out.push(m[2]);
|
||||
return out;
|
||||
}
|
||||
function chipsHtml(sql, params) {
|
||||
var used = detectParams(sql), declared = params.map(function (p) { return p.name; }), h = '';
|
||||
if (!used.length) return '<span class="hint">SQL 中尚未使用 :参数。</span>';
|
||||
h += '<span class="hint">SQL 中的参数:</span>';
|
||||
used.forEach(function (n) {
|
||||
h += declared.indexOf(n) >= 0 ? '<span class="chip ok">:' + esc(n) + '</span>' : '<span class="chip bad" title="未在参数 schema 中声明,保存会被拒绝">:' + esc(n) + ' 未声明</span>';
|
||||
});
|
||||
declared.forEach(function (n) { if (n && used.indexOf(n) < 0) h += '<span class="chip dim" title="已声明但 SQL 中未使用">' + esc(n) + ' 未使用</span>'; });
|
||||
return h;
|
||||
}
|
||||
function refreshChips() {
|
||||
var el = $('sql-chips');
|
||||
if (el && state.draft) el.innerHTML = chipsHtml(state.draft.sql, state.draft.params);
|
||||
}
|
||||
|
||||
/* ---------- preview ---------- */
|
||||
function pvInputs(ps) {
|
||||
if (!ps.length) return '<div class="hint" style="margin-bottom:12px">该查询没有声明参数,可直接试跑。</div>';
|
||||
var h = '<div class="pv-grid">';
|
||||
ps.forEach(function (p) {
|
||||
var v = state.pvals[p.name] == null ? '' : state.pvals[p.name], inp;
|
||||
if (p.type === 'boolean') {
|
||||
inp = '<select data-bind="pvals.' + p.name + '"><option value=""' + (v === '' ? ' selected' : '') + '>(未填)</option><option value="true"' + (v === 'true' ? ' selected' : '') + '>true</option><option value="false"' + (v === 'false' ? ' selected' : '') + '>false</option></select>';
|
||||
} else {
|
||||
inp = '<input type="' + (p.type === 'integer' || p.type === 'number' ? 'number' : 'text') + '" data-bind="pvals.' + p.name + '" value="' + esc(v) + '" placeholder="' + (p.type === 'datetime' ? 'YYYY-MM-DD HH:MM:SS' : '') + '">';
|
||||
}
|
||||
h += '<div class="field"><label><span class="mono">' + esc(p.name) + '</span> · ' + p.type + (p.req ? '<span class="req">*</span>' : '') + '</label>' + inp + '</div>';
|
||||
});
|
||||
return h + '</div>';
|
||||
}
|
||||
function refreshPvParams() {
|
||||
var el = $('pv-params');
|
||||
if (el) el.innerHTML = pvInputs(sourceParams());
|
||||
}
|
||||
|
||||
function maskCol(n) { return /operator|person|user/i.test(n); }
|
||||
function sampleVal(o, i) {
|
||||
if (maskCol(o.name)) return '张**';
|
||||
if (o.type === 'integer') return String(i * 3 + 2);
|
||||
if (o.type === 'number') return (71.2 + i * 0.8).toFixed(1);
|
||||
if (o.type === 'boolean') return i % 2 ? 'true' : 'false';
|
||||
if (o.type === 'datetime') return '2026-11-18 08:' + (10 + i * 5) + ':00';
|
||||
return o.name === 'lot_no' ? 'LOT-100' + i : o.name + '-' + i;
|
||||
}
|
||||
function successTable(outs) {
|
||||
var h = '<div class="table-wrap r-table"><table><thead><tr>';
|
||||
outs.forEach(function (o) { h += '<th>' + esc(o.name) + (maskCol(o.name) ? ' <span class="tag warn">脱敏</span>' : '') + '</th>'; });
|
||||
h += '</tr></thead><tbody>';
|
||||
for (var i = 1; i <= 3; i++) {
|
||||
h += '<tr>';
|
||||
outs.forEach(function (o) { h += '<td class="mono">' + esc(sampleVal(o, i)) + '</td>'; });
|
||||
h += '</tr>';
|
||||
}
|
||||
return h + '</tbody></table></div>';
|
||||
}
|
||||
function contextInfo() {
|
||||
var q = curQ();
|
||||
if (isVersion()) { var v = verOf(q, state.ver); return { outs: v.outputs, timeout: v.timeout, maxRows: v.maxRows, dsId: q.ds, label: '版本 v' + v.no + '(已冻结)' }; }
|
||||
var d = isCreate() ? state.draft : q; return { outs: d.outputs, timeout: d.timeout, maxRows: d.maxRows, dsId: d.ds, label: '草稿(已保存内容)' };
|
||||
}
|
||||
function resultPanel(kind) {
|
||||
var q = curQ(), c = contextInfo(), dsn = dsName(c.dsId);
|
||||
var limits = 'timeout_ms=' + c.timeout + ' · max_rows=' + c.maxRows;
|
||||
var foot = '仅预览:不创建报警、不发送通知、不进入正式运行';
|
||||
if (kind === 'running') {
|
||||
return '<div class="result pend"><div class="r-title"><span class="spin"></span>试跑中</div><div class="r-body">' + later('正在试跑「' + esc(q.name) + '」(本地模拟,未发出任何请求)…') + '</div></div>';
|
||||
}
|
||||
if (kind === 'success') {
|
||||
return '<div class="result ok"><div class="r-title">试跑成功</div><div class="r-body">返回 3 行样例,列符合输出契约。标记「脱敏」的列按简单策略遮盖。</div>' +
|
||||
successTable(c.outs) +
|
||||
'<div class="r-meta">' + later('耗时示意 0.32 秒(虚构) · ' + limits + ' · 数据源 ' + esc(dsn)) + '<br>' + foot + '</div></div>';
|
||||
}
|
||||
if (kind === 'empty') {
|
||||
return '<div class="result grey"><div class="r-title">空结果</div><div class="r-body">查询已成功执行,但没有符合条件的行。这不是失败,也不是类型错误。</div>' +
|
||||
'<div class="r-meta">' + later('耗时示意 0.18 秒(虚构) · ' + limits) + '<br>' + foot + '</div></div>';
|
||||
}
|
||||
if (kind === 'illegal_type') {
|
||||
var col = null, i;
|
||||
for (i = 0; i < c.outs.length; i++) if (c.outs[i].type !== 'string') { col = c.outs[i]; break; }
|
||||
if (!col) col = c.outs[0] || { name: 'value', type: 'integer' };
|
||||
var exp = col.type === 'string' ? 'integer' : col.type;
|
||||
return '<div class="result warn"><div class="r-title">输出类型不匹配</div><div class="r-body">查询已执行,但返回值与输出契约不符,整批结果不视为合法输出。</div>' +
|
||||
'<div class="table-wrap r-table"><table><thead><tr><th>行</th><th>字段</th><th>契约类型</th><th>实际值(样例)</th></tr></thead><tbody>' +
|
||||
'<tr><td class="mono">2</td><td class="mono">' + esc(col.name) + '</td><td class="mono">' + exp + '</td><td class="mono">"N/A"(字符串)</td></tr>' +
|
||||
'<tr><td class="mono">5</td><td class="mono">' + esc(col.name) + '</td><td class="mono">' + exp + '</td><td class="mono">"--"(字符串)</td></tr>' +
|
||||
'</tbody></table></div>' +
|
||||
'<div class="r-meta">' + later('共 2 处不匹配(虚构) · ' + limits) + '<br>' + foot + '</div></div>';
|
||||
}
|
||||
if (kind === 'failure') {
|
||||
var f = {
|
||||
timeout: ['执行超时', '超过 timeout_ms=' + c.timeout + ' 仍未返回,已中止查询。可缩小时间窗或调整限制后重试。', '超时不是 SQL 语法错误,也不是类型不匹配'],
|
||||
connection: ['连接失败', '无法连接到数据源「' + dsn + '」。', '连接类失败会计入该数据源的熔断统计(与 M03 一致)'],
|
||||
syntax: ['SQL 语法错误', '源库拒绝了该 SQL:near "FORM"(虚构示例)。请检查 SQL 模板。', '语法错误不属于连接失败,不计入熔断统计']
|
||||
}[state.fsub];
|
||||
return '<div class="result bad"><div class="r-title">试跑失败 · ' + f[0] + '</div><div class="r-body">' + esc(f[1]) + '</div>' +
|
||||
'<div class="r-meta">' + later(f[2] + ' · ' + limits) + '<br>' + foot + '</div></div>';
|
||||
}
|
||||
if (kind === 'disabled') {
|
||||
var body = !q.on ? '查询「' + q.name + '」已停用,不能试跑。请先在页脚「启用」。' : '所绑定的数据源「' + dsn + '」已停用,不能试跑。';
|
||||
return '<div class="result warn"><div class="r-title">已停用,未执行</div><div class="r-body">' + esc(body) + '</div>' +
|
||||
'<div class="r-meta">' + later('被拒绝时不会向源库发起任何查询。') + '</div></div>';
|
||||
}
|
||||
if (kind === 'circuit_open') {
|
||||
return '<div class="result bad"><div class="r-title">数据源熔断中,未执行</div><div class="r-body">数据源「' + esc(dsn) + '」当前熔断开闸,不会向源库发起查询。预计恢复时间 2026-11-18 15:10(示意)。</div>' +
|
||||
'<div class="r-meta">' + later('熔断由数据源侧连续失败触发;此处不绕过熔断。') + '</div></div>';
|
||||
}
|
||||
return '<div class="note">' + later('尚未试跑。填写参数后点击页脚「试跑预览」可演示结果(本地模拟)。') + '</div>';
|
||||
}
|
||||
function previewCard() {
|
||||
var ver_ = isVersion(), c = contextInfo();
|
||||
var h = '<div class="card' + (state.focusPreview ? ' focus' : '') + '" id="pv-card"><h3>试跑预览<span class="sub">仅返回样例,不进入报警</span></h3>';
|
||||
h += '<div class="pv-target">预览对象:<b>' + c.label + '</b>' + (ver_ ? '' : '') + '</div>';
|
||||
if (!ver_) h += '<div class="note warn" id="pv-dirty" style="margin-bottom:10px"' + (state.dirty ? '' : ' hidden') + '>' + later('当前有未保存修改;预览使用已保存的草稿,不含这些修改(待确认)。') + '</div>';
|
||||
h += '<div id="pv-params">' + pvInputs(sourceParams()) + '</div>';
|
||||
h += '<div id="pv-result">' + resultPanel(state.preview || 'none') + '</div>';
|
||||
return h + '</div>';
|
||||
}
|
||||
|
||||
/* ---------- versions ---------- */
|
||||
function versionsCard(q, hlNo) {
|
||||
var h = '<div class="card"><h3>版本<span class="sub">仅已发布版本;发布请使用页脚「发布」</span></h3>';
|
||||
if (isCreate()) return h + '<div class="empty sm"><p>保存草稿并发布后,版本会出现在这里。</p></div></div>';
|
||||
if (!q.versions.length) return h + '<div class="empty sm"><p>尚未发布。发布后会生成 v1,且内容不可再改。</p></div></div>';
|
||||
h += '<div class="table-wrap"><table><thead><tr><th>版本</th><th>发布时间</th><th>发布人</th><th>数据库限制</th><th>操作</th></tr></thead><tbody>';
|
||||
q.versions.forEach(function (v, idx) {
|
||||
h += '<tr class="' + (v.no === hlNo ? 'hl' : '') + '"><td class="mono">v' + v.no + (idx === 0 ? ' <span class="tag ok">最新</span>' : '') + '</td><td class="mono">' + v.at + '</td><td class="mono">' + v.by +
|
||||
'</td><td class="mono">timeout ' + v.timeout + ' / rows ' + v.maxRows + '</td><td class="ops"><button class="btn link" data-act="openver" data-no="' + v.no + '">打开</button></td></tr>';
|
||||
});
|
||||
return h + '</tbody></table></div></div>';
|
||||
}
|
||||
|
||||
/* ---------- footers ---------- */
|
||||
function footEdit() {
|
||||
var q = curQ(), create = isCreate(), h = '';
|
||||
h += '<button class="btn" data-act="list">返回列表</button>';
|
||||
h += '<button class="btn primary" data-act="save">保存草稿</button>';
|
||||
h += create ? '<button class="btn" disabled title="请先保存草稿">发布</button>' : '<button class="btn outline" data-act="publish">发布</button>';
|
||||
if (!create) h += q.on ? '<button class="btn danger" data-act="toggle">停用</button>' : '<button class="btn" data-act="toggle">启用</button>';
|
||||
h += create ? '<button class="btn" disabled title="请先保存草稿">试跑预览</button>' : '<button class="btn" data-act="run"' + (state.preview === 'running' ? ' disabled' : '') + '>试跑预览</button>';
|
||||
return h;
|
||||
}
|
||||
function footVersion() {
|
||||
return '<button class="btn" data-act="list">返回列表</button><button class="btn" data-act="draft">返回草稿</button>' +
|
||||
'<button class="btn" data-act="run"' + (state.preview === 'running' ? ' disabled' : '') + '>试跑预览</button>';
|
||||
}
|
||||
|
||||
/* ---------- screens ---------- */
|
||||
function vDenied() {
|
||||
setCrumb(''); setFoot('');
|
||||
return banner() + '<div class="empty"><h3>无法进入查询</h3><p>只有管理者可以进入查询界面。</p>' +
|
||||
'<p class="hint" style="margin:0">' + later('后端返回 42000,并带缺失的权限点 perm:data:emp:watchman.query.read。') + '</p></div>';
|
||||
}
|
||||
function vEmpty() {
|
||||
setCrumb(''); setFoot('');
|
||||
return banner() + '<div class="list-actions"><button class="btn primary" data-act="create">新建</button></div>' +
|
||||
'<div class="empty"><h3>还没有查询</h3><p>管理者可以新建第一个查询定义:选择数据源,写参数化 SQL,声明参数与输出契约。</p></div>';
|
||||
}
|
||||
function vList() {
|
||||
setCrumb(''); setFoot('');
|
||||
return banner() + '<div class="list-actions"><button class="btn primary" data-act="create">新建</button></div>' + listTable(QUERIES) +
|
||||
'<p class="hint" style="margin-top:10px">' + later('已停用的行保持可见,「预览」置灰;「打开」进入草稿详情。分页/筛选未在需求中确认,原型未做。') + '</p>';
|
||||
}
|
||||
|
||||
function basicCard() {
|
||||
var d = state.draft, q = curQ(), create = isCreate(), dsOpts = '';
|
||||
DS.forEach(function (x) {
|
||||
dsOpts += '<option value="' + x.id + '"' + (d.ds === x.id ? ' selected' : '') + (x.on ? '' : ' disabled') + '>' + x.name + (x.on ? '' : '(已停用)') + '</option>';
|
||||
});
|
||||
var st = create ? '<span class="hint">新建后默认启用</span>' : statusCell(q) + ' <span class="hint">· 通过页脚「' + (q.on ? '停用' : '启用') + '」切换</span>';
|
||||
return '<div class="card"><h3>基本信息' + (create ? '<span class="sub">草稿</span>' : '<span class="sub">草稿 · 最新已发布 ' + (q.versions.length ? 'v' + latestNo(q) : '无') + '</span>') + '</h3>' +
|
||||
'<div class="form-grid">' +
|
||||
'<div class="field"><label>名称<span class="req">*</span></label><input type="text" data-bind="draft.name" value="' + esc(d.name) + '" placeholder="租户内唯一"></div>' +
|
||||
'<div class="field"><label>数据源<span class="req">*</span></label><select data-bind="draft.ds">' + dsOpts + '</select>' +
|
||||
'<span class="hint">' + later('仅可选择可用的数据库数据源;已停用的灰显不可选。') + '</span></div>' +
|
||||
'<div class="field full"><label>用途说明</label><textarea rows="2" data-bind="draft.desc">' + esc(d.desc) + '</textarea></div>' +
|
||||
'<div class="field"><label>状态</label><div>' + st + '</div></div>' +
|
||||
'</div></div>';
|
||||
}
|
||||
function sqlCard() {
|
||||
var d = state.draft;
|
||||
return '<div class="card"><h3>SQL 模板</h3>' +
|
||||
'<div class="field"><textarea class="sql" rows="8" data-bind="draft.sql" spellcheck="false" placeholder="SELECT lot_no FROM process_readings WHERE line_code = :line_code">' + esc(d.sql) + '</textarea>' +
|
||||
'<span class="hint">' + later('使用命名参数,例如 :line_code,值一律参数绑定,不拼接进 SQL。不靠 SELECT 前缀判定安全,是否只读由数据源账户与执行器保证。') + '</span></div>' +
|
||||
'<div class="chips" id="sql-chips">' + chipsHtml(d.sql, d.params) + '</div></div>';
|
||||
}
|
||||
function limitsCard() {
|
||||
var d = state.draft;
|
||||
return '<div class="card"><h3>执行限制</h3><div class="form-grid">' +
|
||||
'<div class="field"><label>timeout_ms<span class="req">*</span></label><input type="number" data-bind="draft.timeout" value="' + esc(d.timeout) + '"></div>' +
|
||||
'<div class="field"><label>max_rows<span class="req">*</span></label><input type="number" data-bind="draft.maxRows" value="' + esc(d.maxRows) + '"></div>' +
|
||||
'<div class="field full"><span class="hint">' + later('服务端有上限封顶(示意:timeout_ms ≤ 30000,max_rows ≤ 1000,具体值以后端为准),表单填过大会被拒绝。') + '</span></div>' +
|
||||
'</div></div>';
|
||||
}
|
||||
function vEdit() {
|
||||
var create = isCreate(), q = curQ(), d = state.draft;
|
||||
setCrumb(create ? '新建' : '详情');
|
||||
setFoot(footEdit());
|
||||
var h = banner();
|
||||
if (!create && !q.on) h += '<div class="note warn" style="margin-bottom:14px">该查询已停用。仍可查看与编辑草稿,但不能试跑预览;可在页脚「启用」。</div>';
|
||||
h += basicCard() + sqlCard();
|
||||
h += '<div class="card"><h3>参数 schema<span class="sub">命名参数 · 未知参数拒绝</span></h3>' + paramsEditor(d.params, false) + '</div>';
|
||||
h += '<div class="card"><h3>输出 schema<span class="sub">输出契约 · 用于检查结果类型</span></h3>' + outputsEditor(d.outputs, false) + '</div>';
|
||||
h += '<div class="card"><h3>允许的标识符</h3>' + identsBlock(d.idents, false) + '</div>';
|
||||
h += limitsCard();
|
||||
h += previewCard();
|
||||
h += versionsCard(q, 0);
|
||||
h += '<div class="card"><h3>引用<span class="sub">场景尚未落地</span></h3><div class="empty sm"><p>尚无引用</p></div></div>';
|
||||
return h;
|
||||
}
|
||||
function vVersion() {
|
||||
var q = curQ(), v = verOf(q, state.ver);
|
||||
setCrumb('详情 / 版本 v' + v.no);
|
||||
setFoot(footVersion());
|
||||
var h = banner();
|
||||
h += '<div class="note" style="margin-bottom:14px">版本 v' + v.no + ' 已冻结,内容不可修改。更正需回到草稿修改后发布新版本;这里仍可试跑预览。</div>';
|
||||
h += '<div class="card"><h3>版本信息<span class="sub"><span class="tag grey">只读</span></span></h3><dl class="kv">' +
|
||||
'<dt>查询</dt><dd>' + esc(q.name) + '</dd><dt>版本</dt><dd class="mono">v' + v.no + (v.no === latestNo(q) ? ' <span class="tag ok">最新</span>' : '') + '</dd>' +
|
||||
'<dt>发布时间</dt><dd class="mono">' + v.at + '</dd><dt>发布人</dt><dd class="mono">' + v.by + '</dd><dt>数据源</dt><dd>' + esc(dsName(q.ds)) + '</dd></dl></div>';
|
||||
h += '<div class="card"><h3>SQL 模板<span class="sub">冻结</span></h3><pre class="sql">' + esc(v.sql) + '</pre></div>';
|
||||
h += '<div class="card"><h3>参数 schema<span class="sub">冻结</span></h3>' + paramsEditor(v.params, true) + '</div>';
|
||||
h += '<div class="card"><h3>输出 schema<span class="sub">冻结</span></h3>' + outputsEditor(v.outputs, true) + '</div>';
|
||||
h += '<div class="card"><h3>允许的标识符<span class="sub">冻结</span></h3>' + identsBlock(v.idents, true) + '</div>';
|
||||
h += '<div class="card"><h3>执行限制<span class="sub">冻结</span></h3><dl class="kv"><dt>timeout_ms</dt><dd class="mono">' + v.timeout + '</dd><dt>max_rows</dt><dd class="mono">' + v.maxRows + '</dd></dl></div>';
|
||||
h += previewCard();
|
||||
h += versionsCard(q, v.no);
|
||||
return h;
|
||||
}
|
||||
|
||||
/* ---------- modal ---------- */
|
||||
function renderModal() {
|
||||
var root = $('modal-root');
|
||||
if (!state.modal) { root.innerHTML = ''; return; }
|
||||
var q = curQ(), next = latestNo(q) + 1;
|
||||
root.innerHTML = '<div class="modal-mask"><div class="modal"><h3>确认发布 v' + next + '?</h3>' +
|
||||
'<p>将把当前已保存的草稿固化为不可变版本 v' + next + '。发布后不能修改或删除,更正需发布新版本。</p>' +
|
||||
'<div class="row"><button class="btn" data-act="cancel-pub">取消</button><button class="btn primary" data-act="confirm-pub">确认发布</button></div>' +
|
||||
'<p class="hint" style="margin:10px 0 0">' + later('未来用 ElMessageBox 确认。') + '</p></div></div>';
|
||||
}
|
||||
|
||||
/* ---------- render / navigation ---------- */
|
||||
function render(resetScroll) {
|
||||
renderProto();
|
||||
var view = $('view'), st = view.scrollTop, s = state.screen, h;
|
||||
if (!isAdmin()) h = vDenied();
|
||||
else if (s === 'empty') h = vEmpty();
|
||||
else if (s === 'list') h = vList();
|
||||
else if (s === 'create' || s === 'edit') h = vEdit();
|
||||
else if (s === 'version') h = vVersion();
|
||||
else h = vList();
|
||||
view.innerHTML = h;
|
||||
renderModal();
|
||||
sizeShell();
|
||||
view.scrollTop = resetScroll ? 0 : st;
|
||||
if (state.scrollPreview || state.focusPreview) {
|
||||
var pc = $('pv-card');
|
||||
if (pc) pc.scrollIntoView({ block: state.focusPreview ? 'start' : 'nearest' });
|
||||
state.scrollPreview = false;
|
||||
}
|
||||
if (state.refocus) { var f = $(state.refocus); if (f) f.focus(); state.refocus = null; }
|
||||
}
|
||||
function sizeShell() {
|
||||
$('shell').style.setProperty('height', 'calc(100vh - ' + $('proto').offsetHeight + 'px)');
|
||||
}
|
||||
function clearTimer() { if (state.timer) { clearTimeout(state.timer); state.timer = null; } }
|
||||
function go(screen, flash) {
|
||||
clearTimer();
|
||||
state.screen = screen;
|
||||
state.flash = flash || null;
|
||||
state.preview = null;
|
||||
state.modal = false;
|
||||
if (screen === 'create') { state.draft = blankDraft(); state.dirty = false; initPvals(); }
|
||||
else if (screen === 'edit') { loadDraft(state.cur); initPvals(); }
|
||||
else if (screen === 'version') { initPvals(); }
|
||||
render(true);
|
||||
}
|
||||
function setFlash(cls, text, keepScroll) { state.flash = [cls, text]; render(!keepScroll); }
|
||||
|
||||
/* ---------- actions ---------- */
|
||||
function validate() {
|
||||
var d = state.draft, i, names = [];
|
||||
if (!String(d.name).trim()) return '名称必填。';
|
||||
for (i = 0; i < QUERIES.length; i++) if (QUERIES[i].name === d.name.trim() && (isCreate() || QUERIES[i].id !== state.cur)) return '租户内名称已存在:' + d.name.trim() + '。';
|
||||
if (!String(d.sql).trim()) return 'SQL 模板必填。';
|
||||
for (i = 0; i < d.params.length; i++) {
|
||||
var n = d.params[i].name;
|
||||
if (!/^[A-Za-z_]\w*$/.test(n)) return '参数名不合法:' + (n || '(空)') + '。';
|
||||
if (names.indexOf(n) >= 0) return '参数名重复:' + n + '。';
|
||||
names.push(n);
|
||||
}
|
||||
var used = detectParams(d.sql);
|
||||
for (i = 0; i < used.length; i++) if (names.indexOf(used[i]) < 0) return 'SQL 含未声明参数 :' + used[i] + ',未知参数会被拒绝。';
|
||||
for (i = 0; i < d.outputs.length; i++) if (!/^[A-Za-z_]\w*$/.test(d.outputs[i].name)) return '输出字段名不合法:' + (d.outputs[i].name || '(空)') + '。';
|
||||
var t = Number(d.timeout), r = Number(d.maxRows);
|
||||
if (!(t >= 1 && t <= 30000)) return 'timeout_ms 需在 1~30000 之间(示意上限)。';
|
||||
if (!(r >= 1 && r <= 1000)) return 'max_rows 需在 1~1000 之间(示意上限)。';
|
||||
return null;
|
||||
}
|
||||
function doSave() {
|
||||
var err = validate();
|
||||
if (err) { setFlash('bad', '无法保存:' + err); return; }
|
||||
var d = state.draft, q;
|
||||
if (isCreate()) {
|
||||
q = { id: state.nextId++, versions: [], on: true };
|
||||
QUERIES.push(q);
|
||||
state.cur = q.id;
|
||||
} else q = curQ();
|
||||
q.name = d.name.trim(); q.desc = d.desc; q.ds = d.ds; q.sql = d.sql;
|
||||
q.params = clone(d.params); q.outputs = clone(d.outputs); q.idents = d.idents.slice();
|
||||
q.timeout = Number(d.timeout); q.maxRows = Number(d.maxRows); q.updated = NOW;
|
||||
if (state.screen === 'create') { go('edit', ['ok', '草稿已保存(本地模拟)。']); return; }
|
||||
loadDraft(q.id);
|
||||
setFlash('ok', '草稿已保存(本地模拟)。');
|
||||
}
|
||||
function doPublish() {
|
||||
if (state.dirty) { setFlash('warn', '有未保存修改,请先保存草稿再发布。'); return; }
|
||||
var q = curQ();
|
||||
if (!q.sql || !q.sql.trim()) { setFlash('bad', '无法发布:草稿 SQL 为空。'); return; }
|
||||
state.modal = true; renderModal();
|
||||
}
|
||||
function confirmPublish() {
|
||||
var q = curQ(), no = latestNo(q) + 1;
|
||||
q.versions.unshift(ver(no, NOW, q.sql, q.params, q.outputs, q.idents, q.timeout, q.maxRows));
|
||||
q.updated = NOW;
|
||||
state.modal = false;
|
||||
setFlash('ok', '已发布 v' + no + '(本地模拟)。版本内容已冻结,继续修改草稿不影响它。');
|
||||
}
|
||||
function runPreview() {
|
||||
clearTimer();
|
||||
state.preview = 'running'; state.scrollPreview = true; render();
|
||||
state.timer = setTimeout(function () {
|
||||
state.timer = null; state.preview = !curQ().on ? 'disabled' : state.sim; state.scrollPreview = true; render();
|
||||
}, 1000);
|
||||
}
|
||||
function pickResult(kind) {
|
||||
clearTimer();
|
||||
if (kind !== 'none' && kind !== 'running') state.sim = kind;
|
||||
if (state.screen !== 'edit' && state.screen !== 'version') {
|
||||
if (!isAdmin()) { render(); return; }
|
||||
state.cur = state.cur || 1; go('edit');
|
||||
}
|
||||
state.preview = kind === 'none' ? null : kind;
|
||||
state.scrollPreview = true; render();
|
||||
}
|
||||
|
||||
/* ---------- events ---------- */
|
||||
document.addEventListener('click', function (e) {
|
||||
var t = e.target.closest('button');
|
||||
if (!t || t.disabled) return;
|
||||
if (t.hasAttribute('data-role')) { state.role = t.getAttribute('data-role'); render(); return; }
|
||||
if (t.hasAttribute('data-screen')) {
|
||||
var sc = t.getAttribute('data-screen');
|
||||
if (sc === 'edit') { state.cur = state.cur === 3 ? 1 : state.cur; go('edit'); }
|
||||
else if (sc === 'editoff') { state.cur = 3; go('edit'); }
|
||||
else if (sc === 'version') { state.cur = state.cur === 3 ? 1 : state.cur; state.ver = latestNo(curQ()); go('version'); }
|
||||
else go(sc);
|
||||
return;
|
||||
}
|
||||
if (t.hasAttribute('data-result')) { pickResult(t.getAttribute('data-result')); return; }
|
||||
var act = t.getAttribute('data-act');
|
||||
if (!act) return;
|
||||
var i = +t.getAttribute('data-i'), d = state.draft;
|
||||
switch (act) {
|
||||
case 'list': go('list'); break;
|
||||
case 'create': go('create'); break;
|
||||
case 'open': state.cur = +t.getAttribute('data-id'); go('edit'); break;
|
||||
case 'preview': state.cur = +t.getAttribute('data-id'); state.focusPreview = true; go('edit'); state.focusPreview = false; break;
|
||||
case 'draft': go('edit'); break;
|
||||
case 'openver': state.ver = +t.getAttribute('data-no'); go('version'); break;
|
||||
case 'save': doSave(); break;
|
||||
case 'publish': doPublish(); break;
|
||||
case 'confirm-pub': confirmPublish(); break;
|
||||
case 'cancel-pub': state.modal = false; renderModal(); break;
|
||||
case 'toggle': var q = curQ(); q.on = !q.on; q.updated = NOW; state.preview = null; setFlash('ok', q.on ? '已启用(本地模拟)。' : '已停用(本地模拟)。已发布版本不受影响。'); break;
|
||||
case 'run': runPreview(); break;
|
||||
case 'add-param': d.params.push({ name: '', type: 'string', req: false, def: '' }); state.dirty = true; render(); break;
|
||||
case 'del-param': d.params.splice(i, 1); state.dirty = true; initPvalsKeep(); render(); break;
|
||||
case 'add-out': d.outputs.push({ name: '', type: 'string' }); state.dirty = true; render(); break;
|
||||
case 'del-out': d.outputs.splice(i, 1); state.dirty = true; render(); break;
|
||||
case 'del-ident': d.idents.splice(i, 1); state.dirty = true; render(); break;
|
||||
case 'add-ident': addIdent(); break;
|
||||
}
|
||||
});
|
||||
function initPvalsKeep() {
|
||||
var old = state.pvals; state.pvals = {};
|
||||
sourceParams().forEach(function (p) { state.pvals[p.name] = old[p.name] != null ? old[p.name] : (p.def || ''); });
|
||||
}
|
||||
function addIdent() {
|
||||
var el = $('f-ident-input'), v = el ? el.value.trim() : '';
|
||||
if (!v) return;
|
||||
if (!/^[A-Za-z_][\w.]*$/.test(v)) { state.refocus = 'f-ident-input'; setFlash('warn', '标识符只能包含字母、数字、下划线和点:' + v, true); return; }
|
||||
if (state.draft.idents.indexOf(v) < 0) state.draft.idents.push(v);
|
||||
state.dirty = true; state.refocus = 'f-ident-input'; render();
|
||||
}
|
||||
function onBind(e) {
|
||||
var el = e.target, path = el.getAttribute && el.getAttribute('data-bind');
|
||||
if (!path) return;
|
||||
var val = el.type === 'checkbox' ? el.checked : el.value;
|
||||
setPath(path, val);
|
||||
if (path.indexOf('draft.') === 0) {
|
||||
state.dirty = true;
|
||||
var pd = $('pv-dirty'); if (pd) pd.hidden = false;
|
||||
if (path === 'draft.sql' || /^draft\.params\./.test(path)) refreshChips();
|
||||
if (e.type === 'change' && /^draft\.params\./.test(path)) { initPvalsKeep(); refreshPvParams(); }
|
||||
}
|
||||
}
|
||||
document.addEventListener('input', onBind);
|
||||
document.addEventListener('change', function (e) {
|
||||
if (e.target.id === 'p-fsub') { state.fsub = e.target.value; if (state.preview === 'failure') render(); return; }
|
||||
onBind(e);
|
||||
});
|
||||
document.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Enter' && e.target.id === 'f-ident-input') { e.preventDefault(); addIdent(); }
|
||||
});
|
||||
window.addEventListener('resize', sizeShell);
|
||||
|
||||
render(true);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,105 @@
|
||||
# M04 查询定义与采集 Requirement
|
||||
|
||||
## Goal
|
||||
|
||||
维护者能在控制台维护受控查询草稿(参数化 SQL、参数 schema、输出契约、执行限制),发布不可变版本,并对草稿或已发布版本做只读预览试跑。预览区分空结果、非法类型与执行失败;不进入报警/通知,也不承担场景定时采集。
|
||||
|
||||
## Background
|
||||
|
||||
- 模块:`docs/tasks/INDEX.md` M04;覆盖旧细项 A-016~A-020;需求 A-02。
|
||||
- 前置:M03 DONE_LOCAL。数据源 usable/熔断见 D23;查询执行必须调用 `assert_usable` 与失败记账入口。
|
||||
- 决策:D14 RLS;D19 三角色;D22 按钮/密码框约定;**D24** 本模块口径(参数化 SQL + 不可变版本 + 预览边界)。
|
||||
- 门禁:`gatePolicy.selected=autonomous`;Vue 前 HTML 原型确认。
|
||||
|
||||
## In Scope
|
||||
|
||||
- `query_definitions`:租户内名称唯一;绑定可用数据库数据源;草稿 SQL/参数 schema/输出契约/限制;启停。
|
||||
- `query_versions`:`publish` 从当前草稿拷贝不可变快照;`(definition_id, version_no)` 唯一;内容禁止改写/删除字段更新。
|
||||
- 参数:命名参数绑定;未知参数拒绝;类型/必填/默认值校验。
|
||||
- 标识符:不可作绑定值的表/字段等仅允许白名单(本阶段可先支持固定占位语法或显式允许列表字段,禁止任意拼接)。
|
||||
- 只读执行器:超时、最大行数;不靠 `SELECT` 前缀判定安全;平台库事务与源库查询分离。
|
||||
- 预览 API/UI:草稿预览与指定版本预览;空/非法类型/失败三分;样例脱敏;不写正式报警。
|
||||
- 权限:仅 admin 的 read/write/publish/preview。
|
||||
- 引用:查询定义/版本 references 返回空列表+稳定占位;数据源 references 可列出引用它的查询(只读提示)。
|
||||
- 控制台:列表、编辑草稿、发布、版本只读、试跑预览;布局遵守 D22/`docs/current/frontend-ui.md`。
|
||||
- 审计:创建、更新草稿、启停、发布、预览(预览审计不含结果全文/秘密)。
|
||||
|
||||
## Out Of Scope
|
||||
|
||||
- 结构化表/字段选择器(非参数化 SQL)。
|
||||
- 任意脚本、eval、动态拼 SQL 条件串。
|
||||
- 字段映射、规则判定、报警、企微、场景 Cron 正式采集(M05/M06/M07/M08)。
|
||||
- 非数据库数据源执行。
|
||||
- 绕过熔断直连源库。
|
||||
- 真实 MES/生产库写入;口令或预览全文入库外日志/仓库。
|
||||
- 查询物理删除(本阶段停用即可)。
|
||||
|
||||
## Required Behavior
|
||||
|
||||
- 有权限用户可 CRUD 草稿;停用后仍可查看,不可预览执行(或明确拒绝并提示);可再启用。
|
||||
- `publish` 生成递增 `version_no`;历史版本只读;草稿可继续改,不影响已发布快照。
|
||||
- 预览前 `assert_usable(datasource)`;源停用或熔断开闸则拒绝预览并记账策略与 M03 业务失败一致(连接类失败计入熔断)。
|
||||
- 参数含 SQL 片段时仍参数绑定,不形成结构注入。
|
||||
- 多行/多对象结果可返回;不在本模块串联报警。
|
||||
- 空结果、输出契约类型不匹配、超时/连接/语法类失败分开展示。
|
||||
- 跨租户不可见。无会话 41000;非 admin 42000 且带权限点。
|
||||
|
||||
## User Flow
|
||||
|
||||
1. 管理者打开查询列表。
|
||||
2. 新建:选数据源、用途、SQL 模板、参数与输出契约、限制 → 保存草稿。
|
||||
3. 可对草稿试跑预览(填参数)。
|
||||
4. 发布 → 生成版本;可查看版本列表与只读详情;可对版本试跑。
|
||||
5. 继续改草稿不影响已发布版本;再次发布得到新版本号。
|
||||
6. 停用定义后不可作为后续场景候选(约定字段/列表过滤);本阶段场景未落地,提供稳定 `enabled` 语义即可。
|
||||
|
||||
## Business Rules
|
||||
|
||||
- 租户内 `name` 唯一。无物理删除。
|
||||
- 版本内容不可变;更正靠新版本。
|
||||
- 预览不创建报警、不发送通知、不推进正式 run 业务状态机(若写 run_records 须明确 `sample`/试跑标记且默认不做;本轮预览结果仅 API 响应)。
|
||||
- 最新已发布版本号可空(从未发布)。
|
||||
- 数据源被引用时,数据源 references 返回查询条目;查询侧 references 仍可空(场景未到)。
|
||||
|
||||
## Data Rules
|
||||
|
||||
- 租户服务端注入;表启用 RLS。
|
||||
- SQL/参数/输出/限制可回显给有权限用户;源库口令永不回显。
|
||||
- 预览响应可含样例行,敏感列按输出契约或简单脱敏策略处理;日志不得落完整结果集或口令。
|
||||
|
||||
## API Contract(摘要)
|
||||
|
||||
- `GET/POST /queries`,`GET/PATCH /queries/{id}`,`POST .../enable|disable`,`POST .../publish`
|
||||
- `GET /queries/{id}/versions`,`GET /queries/{id}/versions/{version_no}`
|
||||
- `POST /queries/{id}/preview`(草稿),`POST /queries/{id}/versions/{version_no}/preview`
|
||||
- `GET /queries/{id}/references`
|
||||
- 统一信封;错误码沿用平台约定。
|
||||
|
||||
## Permission Nodes
|
||||
|
||||
- `perm:data:emp:watchman.query.read`
|
||||
- `perm:data:emp:watchman.query.write`
|
||||
- `perm:data:emp:watchman.query.publish`
|
||||
- `perm:data:emp:watchman.query.preview`
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- A-016:参数/输出/限制 schema;未知字段拒绝。
|
||||
- A-017:绑定、只读账户前提(配置层)、超时与行数限制;不靠 SELECT 前缀。
|
||||
- A-018:空/失败/非法类型分开;样例脱敏。
|
||||
- A-019:列表与编辑 UI;越权不可保存。
|
||||
- A-020:试跑预览 UI;不进入正式报警。
|
||||
- 不可变版本:发布后历史不可改;新发布递增版本号。
|
||||
- V009/V010/V011 口径的自动化或集成测试有证据。
|
||||
|
||||
## Assumptions
|
||||
|
||||
- 首版白名单机制:禁止通过参数改写标识符;若 SQL 需动态标识符,仅接受定义时声明的允许标识符集合(可为空=不允许动态标识符)。
|
||||
- 默认限制:超时与 max_rows 有服务端上限封顶,防止表单填过大。
|
||||
- 原型确认前不改正式 Vue 查询页;用户确认计划并要求执行全部切片后,S4 产出原型,S5 在原型落地后实现(若原型与冻结 UX 一致则连续推进)。
|
||||
|
||||
## Risks And Stop Conditions
|
||||
|
||||
- 注入/任意 SQL 风险:执行器与评审必查。
|
||||
- 迁移/权限/熔断边界:`risk_score>=4` 切片在 autonomous 下仍停片际确认(实现后片审再续)。
|
||||
- 禁止真实生产库破坏性操作;禁止秘密入库。
|
||||
@@ -0,0 +1,30 @@
|
||||
# M04 MUST-FIX Recheck
|
||||
|
||||
## Verdict
|
||||
|
||||
PASS
|
||||
|
||||
## Scope
|
||||
|
||||
Bounded recheck of the two MUST-FIX findings in `review-module-m04.md`; this is not a new module-wide review.
|
||||
|
||||
## Findings Closed
|
||||
|
||||
1. **Immutable query versions — closed.**
|
||||
- Migration `20261118_0007` revokes `UPDATE`/`DELETE` from `watchman_app` and installs a statement-level `BEFORE UPDATE OR DELETE OR TRUNCATE` rejection trigger.
|
||||
- The trigger also rejects mutations attempted by the migrator/table-owner, so a later privilege grant cannot bypass the append-only boundary.
|
||||
- Regression coverage verifies app-role Core and ORM mutation failures, unchanged stored SQL, allowed inserts, and owner-side update/delete/truncate rejection.
|
||||
|
||||
2. **SQL Server preview write risk — closed.**
|
||||
- `run_query` refuses SQL Server immediately after datasource usability checks, before template validation, secret decryption, or any source connection, with `engine_readonly_unsupported`.
|
||||
- `queries/drivers.py` has no SQL Server runner, so direct `fetch_rows` calls also fail without opening a connection. The M03 connectivity probe remains separate and unchanged.
|
||||
- Regression coverage exercises SELECT, UPDATE, DELETE, and `EXEC` refusal plus the API outcome and no-connection path.
|
||||
|
||||
## Validation
|
||||
|
||||
- `uv run pytest tests/test_query_versions.py tests/test_query_execute.py tests/test_query_api.py -q`
|
||||
- Result: **194 passed**; one pre-existing dependency deprecation warning from Starlette `TestClient`.
|
||||
|
||||
## Notes
|
||||
|
||||
No new high-severity issue was found in these remediations.
|
||||
@@ -0,0 +1,46 @@
|
||||
# M04 Module Review
|
||||
|
||||
## Verdict
|
||||
|
||||
FAIL
|
||||
|
||||
## Must-fix
|
||||
|
||||
1. **Published versions are not actually immutable at the persistence boundary** (confidence: 100)
|
||||
- **Location:** `services/watchman/migrations/versions/20261118_0006_query_definitions.py:42`; `services/watchman/src/watchman/services/query_versions.py:23`; `services/watchman/src/watchman/services/queries.py:385`
|
||||
- The migration grants `watchman_app` `UPDATE` on `query_versions` and installs no trigger or database rule to reject updates. The only guard is the standalone `forbid_version_content_mutation()` helper, but no production write path calls it. Any present or future application code using a SQLAlchemy session can therefore alter a published SQL snapshot and commit it.
|
||||
- This violates D24's immutable-published-version requirement despite the absence of an HTTP update route.
|
||||
- **Fix:** enforce append-only versions at the database boundary (for example, revoke UPDATE/DELETE for the application role, or add an update/delete-rejecting trigger with a narrowly controlled maintenance path). Add an integration test that attempts a direct ORM/Core update and proves it is rejected.
|
||||
|
||||
2. **SQL Server previews can execute writes when the saved datasource credentials have write access** (confidence: 98)
|
||||
- **Location:** `services/watchman/src/watchman/queries/drivers.py:260`
|
||||
- PostgreSQL and MySQL establish a read-only transaction before executing the submitted template. The SQL Server runner sends the template directly via `cur.execute(sql, params)` and has no equivalent server-side read-only transaction or application gate. `DataSource.read_only_intent` is only stored/displayed and is never checked or verified before execution (`services/watchman/src/watchman/services/datasources.py:303`, `services/watchman/src/watchman/queries/execute.py:151`).
|
||||
- A single-statement `UPDATE`, `DELETE`, DDL, or an executing stored procedure is accepted by the template parser and will mutate a SQL Server datasource whenever its configured login has write privileges. Parameter binding prevents value injection; it does not make arbitrary SQL read-only. This violates the read-only-preview boundary.
|
||||
- **Fix:** do not allow SQL Server preview until a server-enforced read-only execution method is available, or require and verify a least-privileged read-only login as an executable precondition. Add a live SQL Server regression test proving a write statement cannot change data.
|
||||
|
||||
## Should-fix
|
||||
|
||||
None.
|
||||
|
||||
## Notes
|
||||
|
||||
- Review covered the supplied M04 backend, API/auth, datasource-reference, frontend, tests, migrations, and task/documentation scope.
|
||||
- The reviewed API routes correctly restrict query operations to `watchman-admin`; parameter values are bound rather than text-spliced; preview outcomes keep empty, illegal-type, and failure distinct; and preview audit payloads omit SQL, parameters, and rows.
|
||||
- Existing test results were provided by the orchestrator. This review did not re-run them.
|
||||
|
||||
## Remediation
|
||||
|
||||
Both must-fix findings were addressed (no commit made).
|
||||
|
||||
1. **Immutable `query_versions` at the DB boundary** — new migration `20261118_0007_query_versions_immutable`:
|
||||
- `REVOKE UPDATE, DELETE` on `query_versions` from `watchman_app`; `SELECT, INSERT` re-asserted.
|
||||
- Statement-level `BEFORE UPDATE OR DELETE OR TRUNCATE` trigger (`trg_query_versions_append_only`) that always raises `restrict_violation` (23001), so it also stops the table owner and any future grant, even when forced RLS hides all rows.
|
||||
- Downgrade drops trigger and function and restores the 0006 grants (round-trip upgrade/downgrade/upgrade verified locally).
|
||||
- Tests (`test_query_versions.py`): app-role privilege matrix; Core and ORM UPDATE/DELETE fail with SQLSTATE 42501 and the stored SQL is unchanged; INSERT of a new version still works; the owner (migrator) is rejected by the trigger for UPDATE/DELETE/TRUNCATE.
|
||||
- Because the app role can no longer delete versions, test cleanup now uses a superuser purge (`tests/_privileged_cleanup.py`, `session_replication_role = replica`); there is no application maintenance path.
|
||||
2. **SQL Server read-only boundary** — chosen fix: refuse, do not gate on statement text.
|
||||
- `run_query` returns `failure_kind = engine_readonly_unsupported` (fixed safe message, no details from the driver) for `engine == "sqlserver"` right after `assert_usable`, before validation, secret decryption or any connection. The circuit is untouched.
|
||||
- `_run_sqlserver` was removed from `queries/drivers.py`, so `fetch_rows` also raises `UnsupportedDataSourceError` for SQL Server: no write path exists even if the guard were bypassed. The M03 probe (`datasources/probe.py`) is unchanged.
|
||||
- Tests: `run_query` on a sqlserver datasource is refused for SELECT, UPDATE, DELETE and EXEC with no driver/secret access; `fetch_rows("sqlserver")` opens nothing; an API preview test confirms the refusal outcome and a single audit event.
|
||||
|
||||
Validation: `uv run pytest` in `services/watchman` — 456 passed. Not covered: a live SQL Server test (none needed, since execution is refused); the frontend has not been checked for display of the new `failure_kind`.
|
||||
@@ -0,0 +1,32 @@
|
||||
# M04 Slice S1 Review Note (coder self-check)
|
||||
|
||||
Status: implemented; awaiting independent review (not a review verdict).
|
||||
|
||||
## Files created
|
||||
|
||||
- `services/watchman/src/watchman/models/query.py` — `QueryDefinition`, `QueryVersion`, `VERSION_CONTENT_COLUMNS`
|
||||
- `services/watchman/migrations/versions/20261118_0006_query_definitions.py` — revises `20261118_0005`
|
||||
- `services/watchman/src/watchman/services/query_versions.py` — `forbid_version_content_mutation`, `assert_version_immutable`
|
||||
- `services/watchman/tests/test_query_versions.py` — 28 tests
|
||||
|
||||
## Files changed
|
||||
|
||||
- `services/watchman/src/watchman/models/__init__.py` — export new models
|
||||
|
||||
## Design notes
|
||||
|
||||
- `datasource_id` and `definition_id` FKs are `ON DELETE RESTRICT`; extra index `ix_query_definitions_datasource_id`.
|
||||
- Both tables: ENABLE + FORCE RLS, `tenant_isolation` policy, full CRUD grant to `watchman_app`.
|
||||
- `query_versions` has no `updated_at`. Immutability is enforced only by the service helper (frozen: content columns plus `tenant_id`, `definition_id`, `version_no`, `published_at`, `published_by`). It is NOT enforced at DB level because UPDATE is granted per the slice spec; direct SQL/ORM writes bypass the helper. Later slices must route all version writes through the service layer. A DB trigger is a possible hardening for the reviewer to consider.
|
||||
- `latest_published_version_no` is not FK-linked to `query_versions` (set by publish logic in S3).
|
||||
|
||||
## Validation
|
||||
|
||||
- `uv run alembic upgrade head` — PASS (to `20261118_0006`); downgrade to `0005` then upgrade again — PASS.
|
||||
- `uv run pytest tests/test_query_versions.py` — 28 passed.
|
||||
- `uv run pytest` (full) — 290 passed, 1 pre-existing deprecation warning.
|
||||
- No real passwords; datasource rows use a placeholder ciphertext and synthetic host/user.
|
||||
|
||||
## Scope check
|
||||
|
||||
- Only `models/`, `migrations/`, `services/query_versions.py` (explicitly requested), `tests/` touched. No API routes, executor, frontend, M03 circuit changes, or git commits.
|
||||
@@ -0,0 +1,71 @@
|
||||
# M04 Slice S2 — 只读执行器:实现自检记录
|
||||
|
||||
状态:实现完成,待独立 review(本文件是 coder 自检,不是独立审查结论)。未 commit。
|
||||
|
||||
## 变更文件
|
||||
|
||||
新增:
|
||||
- `services/watchman/src/watchman/queries/__init__.py`(边界说明、导出)
|
||||
- `services/watchman/src/watchman/queries/result.py`(`QueryRunResult`、状态/failure_kind 常量)
|
||||
- `services/watchman/src/watchman/queries/schema.py`(param/output schema 解析、值类型校验)
|
||||
- `services/watchman/src/watchman/queries/template.py`(模板扫描、`:name` 绑定、`{{ident}}` 白名单、单语句检查)
|
||||
- `services/watchman/src/watchman/queries/drivers.py`(PG/MySQL/SQL Server 单语句执行与失败分类)
|
||||
- `services/watchman/src/watchman/queries/execute.py`(`run_query` 编排)
|
||||
- `services/watchman/tests/test_query_execute.py`
|
||||
|
||||
修改(薄改):
|
||||
- `services/watchman/src/watchman/services/datasources.py`:新增 `build_probe_target(row)`、`record_connection_failure(session, datasource_id, category)`;未改既有函数。
|
||||
|
||||
未触碰:路由、前端、`query_definitions` schema/迁移、`.env*`。
|
||||
|
||||
## 行为摘要
|
||||
|
||||
`run_query` 顺序:`assert_usable` → 限制/schema/参数/标识符校验 → 内存解密 → `commit`(网络调用期间不持有事务)→ 执行(`max_rows+1`)→ 分类。
|
||||
|
||||
| 情形 | status | failure_kind |
|
||||
| --- | --- | --- |
|
||||
| 有行且符合输出契约 | success | — |
|
||||
| 0 行 | empty | — |
|
||||
| 声明列类型不符(details 仅含字段名/期望类型/实际 Python 类型名/首个违规行号,不含值) | illegal_type | — |
|
||||
| 数据源停用/熔断打开(不连接、不读密钥) | failure | disabled / circuit_open |
|
||||
| 校验失败(未知参数、缺必填、类型错、`{{x}}` 不在白名单、多语句、非法限制/schema) | failure | validation |
|
||||
| 连接 auth/timeout/unreachable/rejected | failure | auth_failed / timeout / unreachable / rejected,**记入熔断** |
|
||||
| 连接中途断开 | failure | unreachable,**记入熔断** |
|
||||
| 语句超时(PG statement_timeout/MySQL read_timeout) | failure | timeout,**不记熔断** |
|
||||
| SQL 语法/运行错误 | failure | sql_error(PG 附 SQLSTATE),**不记熔断** |
|
||||
| 超过 `max_rows` | failure | limit_exceeded(不返回行) |
|
||||
|
||||
- 绑定:模板 `:name` → `%(name)s` 由驱动绑定;`::` 转型、字符串/引号标识符/注释/PG `$$` 内的 `:name`、`{{}}` 不当作占位符;无参数时不转义 `%`,有参数时转义为 `%%`。参数值不可能成为标识符(测试覆盖)。
|
||||
- 白名单:`{{ident}}` 必须在 `allowed_identifiers` 且匹配 `^[A-Za-z_][A-Za-z0-9_]*$`,按引擎加引号(`"x"` / `` `x` `` / `[x]`);空列表=不允许;校验发生在连接之前。
|
||||
- 只读:PG 用 `BEGIN READ ONLY` + `SET LOCAL statement_timeout`,结束 rollback;MySQL `SET SESSION TRANSACTION READ ONLY` + `START TRANSACTION READ ONLY` + 尽力设置 `MAX_EXECUTION_TIME`;SQL Server 无会话级只读,依赖只读账户(A-017 配置层前提)。不以 `SELECT` 前缀判定安全。额外加了“必须单语句”的结构检查(允许末尾 `;`)。
|
||||
- 限制:`timeout_ms`/`max_rows` 必须是 ≥1 的 int,超过 `MAX_TIMEOUT_MS`/`MAX_ROWS_LIMIT` 被封顶;其余视为 `validation`。
|
||||
- 日志:仅记录引擎、数据源 id、状态、行数;不记口令、连接串、参数值、结果集。
|
||||
|
||||
## 验证
|
||||
|
||||
- `uv run pytest tests/test_query_execute.py`:71 passed(含对 `WATCHMAN_TEST_PG_*` 本地源库的真实执行:绑定防注入、`%` 转义、类型参数、空/illegal_type/sql_error 三分、行数上限、语句超时不记熔断、会话只读(CREATE TABLE 被拒、`transaction_read_only=on`)、错误口令 auth_failed 记账、端口不可达记账)。
|
||||
- `uv run pytest`(全量):361 passed,无失败。
|
||||
- 覆盖要求映射:参数含 SQL 片段不改结构(模板测试+fake+live);空/失败/illegal_type 区分;disabled/circuit 拒绝且驱动未被调用;未知参数;`{{ident}}` 不在白名单/空白名单拒绝。
|
||||
- MySQL 仅用 fake 驱动测试(连接 auth 映射、只读 SET、语法错误、连接丢失 vs read_timeout);SQL Server 未做任何自动化测试(无环境);二者的真实库行为 **NOT_RUN**。
|
||||
|
||||
## 设计决定/需要 reviewer 与用户确认的点
|
||||
|
||||
1. **`nullish` 语义未在需求中定义**:当前实现为“该列不做类型约束”;另外 SQL `NULL` 对所有声明类型都通过类型检查(认为 NULL 是缺值而非类型错误)。若产品想要“只能为 NULL”或“非 NULL 才算合法”,需改 `schema.check_output_value`。
|
||||
2. **成功不记账**:按任务说明只对连接类失败调用 `record_probe_outcome`(`update_last_test=False`,不改 `last_test_*`);成功的预览不会重置失败计数。
|
||||
3. **语句超时不算连接类失败**:慢查询/运行时超时不开闸;连接阶段超时和连接丢失才记入。MySQL `read_timeout` 与连接中途断开在驱动层难区分,按“超时链→timeout(不记);2006/2013 无超时链→unreachable(记)”处理。
|
||||
4. **`param_schema[].required` 缺省为 true**(更严格);`required=true` 且带 `default` 时,缺参仍拒绝(按字面规则)。`boolean` 严格要求 bool(MySQL tinyint 返回 int 会判 illegal_type);`integer` 不接受 Decimal。
|
||||
5. **`run_query` 内部 `commit`**:校验失败/连接失败记账后都会 commit,以免熔断计数随调用方丢弃结果而丢失;S3 路由无需再为熔断额外提交,但应知道会话已被提交。
|
||||
6. `run_query` 对查询类问题**返回** `QueryRunResult`,不抛错;`NotFoundError`(未知数据源)和 `DatasourceSecretUnavailableError` 仍向上抛,由 S3 映射信封。
|
||||
7. `drivers.py` 复用了 `watchman.datasources.probe` 的私有分类助手(`_classify_after_failure` 等),使连接失败分类与探测一致;若后续希望公开,可在 probe 中提升为公共 API(本片未改 probe)。
|
||||
8. 结果行中 `Decimal→float`、`bytes→hex`、日期时间→ISO 字符串、其他→`str`;输出契约之外的列原样返回(脱敏策略留给 S3/预览层)。
|
||||
9. 同名重复列只保留最后一个值(dict)。
|
||||
|
||||
## 残余风险
|
||||
|
||||
- 只读保证依赖数据库账户权限:PG 事务内用户 SQL 无法在单语句内切回读写,但仍应使用只读账户(配置层)。
|
||||
- 无参数模板时 psycopg 可能走简单协议;已由“单语句”结构检查约束,但该检查是词法级的,不是完整 SQL 解析。
|
||||
- SQL Server 路径无自动化证据。
|
||||
|
||||
## 文档同步
|
||||
|
||||
无设计语义变化需要更新 `docs/`;M04 任务卡进度由主 Agent 更新。
|
||||
@@ -0,0 +1,82 @@
|
||||
# M04 Slice S3 — API、权限、引用回填:实现自检记录
|
||||
|
||||
状态:实现完成,待独立 review(本文件是 coder 自检,不是独立审查结论)。未 commit。
|
||||
|
||||
## 变更文件
|
||||
|
||||
新增:
|
||||
- `services/watchman/src/watchman/services/queries.py`(定义 CRUD、启停、publish、版本读取、预览编排、序列化)
|
||||
- `services/watchman/src/watchman/api/routes/queries.py`(`/queries` 路由,`extra="forbid"` 请求模型)
|
||||
- `services/watchman/tests/test_query_api.py`(84 个用例)
|
||||
|
||||
修改:
|
||||
- `auth/access.py`:四个节点常量 + `require_query_read/write/publish/preview`(仅 `watchman-admin`)
|
||||
- `auth/principal.py`:`require_query_reader/writer/publisher/previewer`;把 `_load_session_roles` 的会话读取抽成 `_load_session`(返回 login_name + roles,行为不变);`require_query_publisher` 返回 login_name 供 `published_by`
|
||||
- `api/app.py`:注册 `queries.router`
|
||||
- `services/datasources.py`:`list_references` 回填查询条目 `{type:"query", id, name, enabled}`,按 name 排序,仅本租户
|
||||
- `api/routes/datasources.py`:仅 references 路由 docstring
|
||||
|
||||
未触碰:S1 模型/迁移、`query_versions.py`、`queries/` 执行器包、前端、`.env*`、`docs/`。
|
||||
|
||||
## 路由与契约
|
||||
|
||||
| 路由 | 权限 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `GET /queries?enabled=` | read | 摘要列表(不含草稿内容) |
|
||||
| `POST /queries` | write | 创建启用的未发布定义 |
|
||||
| `GET /queries/{id}` | read | 摘要 + `draft{sql_template,param_schema,output_schema,allowed_identifiers,timeout_ms,max_rows}`,含 `latest_published_version_no` |
|
||||
| `PATCH /queries/{id}` | write | name/description/datasource_id/草稿六字段;不含 enabled 与任何版本字段 |
|
||||
| `POST /{id}/disable|enable` | write | |
|
||||
| `POST /{id}/publish` | publish | 返回完整冻结版本 |
|
||||
| `GET /{id}/versions`、`/{id}/versions/{n}` | read | 摘要(新→旧)/完整内容 |
|
||||
| `POST /{id}/preview`、`/{id}/versions/{n}/preview` | preview | body `{params:{}}`(可省略,`extra=forbid`) |
|
||||
| `GET /{id}/references` | read | `{id, items: []}` |
|
||||
|
||||
- 输入字段名用 `sql_template` 等(不带 `draft_`),输出放在 `draft` 对象里,键名相同,便于 GET → PATCH 往返。
|
||||
- 未知/越权字段(tenant_id、enabled、version_no、published_by、latest_published_version_no、`draft_*`)→ 40000。
|
||||
- 版本无任何 PATCH/PUT/DELETE/POST 路由(测试断言 404/405);唯一写入门(定义 PATCH)拒绝版本形字段。
|
||||
- 信封、错误码沿用既有:无会话 41000;非 admin 42000 + `permission_node`;404 用 `NotFoundError`(含跨租户、非法 UUID);重名 409 `duplicate_name`;预览停用 409 `reason=disabled`。
|
||||
|
||||
## 行为摘要
|
||||
|
||||
- **创建/PATCH 校验**:复用 S2 `parse_param_schema/parse_output_schema/parse_allowed_identifiers`(未知键、重复、非法类型→40000 reason);SQL 模板不得全空白;`timeout_ms/max_rows` 必须是 ≥1 的严格 int(拒绝 bool/0/负数),超过服务端上限按 S2 口径**封顶**(不拒绝);数据源须存在于本租户且 `kind=database`,否则 400(`datasource_not_found`/`datasource_not_database`)。不对 SQL 模板做深度解析(模板问题在预览中以 `failure/validation` 呈现)。
|
||||
- **publish**:锁定定义行(`FOR UPDATE`)→ 重新校验草稿 → `version_no = (latest or 0)+1` → 只 INSERT 版本行,复制 draft 六字段 → 更新 `latest_published_version_no`;`published_by` = 会话 `login_name`(截断 128)。版本行没有任何更新路径;`UNIQUE(definition_id, version_no)` 兜底并发(映射 409 `version_conflict`)。停用的定义仍可发布。
|
||||
- **预览**:先断言定义启用(否则 409,不运行、不审计)→ 把草稿/版本内容拷出 ORM 对象(`run_query` 会 commit)→ 调 S2 `run_query`(定义当前绑定的数据源)→ 写审计 → 路由 commit。`QueryRunResult` 映射:
|
||||
- `success`/`empty`:`columns, rows, row_count, masked_columns`
|
||||
- `illegal_type`:`columns, details.fields`(仅字段名/类型,无值)
|
||||
- `failure`:`failure_kind, details`
|
||||
- 失败的运行是 HTTP 200 的结果(`status=failure`),不是 API 错误。
|
||||
- **样例脱敏**:输出契约没有敏感标记,采用按列名的简单策略(`password/pwd/secret/token/credential/api_key/private_key/id_card/phone/mobile/email`,大小写不敏感),非 NULL 值替换为 `***`,并返回 `masked_columns`。S2 说明过脱敏留给本层。
|
||||
- **审计**:`query.create`(id,name,datasource_id)、`query.update`(id,name,**字段名列表**,无 SQL)、`query.enable/disable`(id,name)、`query.publish`(id,name,version_no)、`query.preview`(**仅** id、status,版本预览加 version_no;不含 name、SQL、参数、行、消息)。幂等键由服务端生成。
|
||||
- **数据源 references**:`{id, items:[{type:"query",id,name,enabled}]}`,随查询改绑/停用实时变化,不含其他租户。查询侧 references 仍恒为空。
|
||||
- 时间戳序列化统一转 UTC ISO(新写入值与重新读取值时区会不同,否则前后不相等)。
|
||||
|
||||
## 验证
|
||||
|
||||
- `uv run pytest tests/test_query_api.py`:84 passed
|
||||
- `uv run pytest`(全量):**445 passed**(S2 后基线 361 + 本片 84),无失败;无需网络或真实源库
|
||||
- 覆盖:节点字符串与角色规则;12 条路由 × 匿名 41000;12 条路由 × 4 类非 admin 42000 带正确节点且数据未变;create/list/get/patch/enable/disable+`?enabled=` 过滤;创建与 PATCH 的未知字段/空值/非法 schema/限制/数据源校验;重名 409;publish v1→v2、草稿后改不影响 v1、版本列表与详情、published_by、审计;版本不可通过任何端点改;预览成功/空/illegal_type/failure 四种形状(fake `run_query`);脱敏;预览审计无数据;版本预览用冻结内容、草稿预览用草稿;停用定义 409 且不运行不审计;真实 `run_query` 的无网络路径(unknown_param 校验失败、数据源停用);查询 references 为空;数据源 references 列出/改绑/停用/跨租户;跨租户 id 404。
|
||||
- 未运行:对真实源库的 HTTP 预览成功路径(S2 的 live 测试覆盖执行器本身;本片用 fake)。浏览器/前端:不在本片。
|
||||
|
||||
## 设计决定/需要 reviewer 与用户确认的点
|
||||
|
||||
1. **输入/输出字段命名**:输入 `sql_template…`,输出 `draft.{…}`;S4 原型与 S5 按此口径。若希望扁平 `draft_*` 需改序列化。
|
||||
2. **版本不快照 datasource_id**:版本预览使用定义**当前**绑定的数据源。若用户后来改绑数据源,旧版本预览会跑在新数据源上。需求未要求版本冻结数据源(S1 表也没有该列);如需冻结应回到 S1 加列。
|
||||
3. **停用定义仍可发布**,只拒绝预览。需求仅说停用后不可预览。
|
||||
4. **数据源停用/熔断**在预览中是 `status=failure, failure_kind=disabled|circuit_open`(S2 语义,HTTP 200),而**查询定义停用**是 409。两者故意不同:前者是运行结果,后者是调用前置条件。
|
||||
5. **绑定数据源时只要求存在且 `kind=database`**,不要求当前 enabled/熔断闭合(那是运行时状态,由 `assert_usable` 把关)。需求写“可用数据库数据源”,如要求创建时必须 usable 需确认。
|
||||
6. **脱敏策略是列名正则**,可能漏掉不含关键词的敏感列、误伤含关键词的列;输出契约尚无敏感标记。
|
||||
7. **PATCH 空 body 为成功空操作**(会写一条 `query.update`,`fields: []`),与数据源 PATCH 一致。
|
||||
8. `principal.py` 的 `_load_session_roles` 被改写为 `_load_session` 的薄包装(行为不变,数据源/平台测试全绿)。
|
||||
9. `preview` 失败信息只经 S2 的固定文案/安全 details 透出;若 S2 details 扩展含值需同步检查。
|
||||
10. 没有写权限节点登记到公司 `standards://api/permission-nodes`(本次 sy-standards 检索未执行;节点串按任务指令原样使用)。
|
||||
|
||||
## 残余风险
|
||||
|
||||
- 预览会对真实源库执行用户 SQL(只读保证依赖 S2 与只读账户);本片未新增任何绕过 `assert_usable` 的路径。
|
||||
- 并发 publish 依赖行锁+唯一约束;未写并发测试(测试库单进程)。
|
||||
- `published_by` 取 `login_name`(非 Casdoor subject);如审计需要稳定主体 id 应改为 subject。
|
||||
|
||||
## 文档同步
|
||||
|
||||
无设计语义变化需要更新 `docs/`;`docs/progress.md`、M04 任务卡、`knowledge-map` 由主 Agent 更新。
|
||||
@@ -0,0 +1,16 @@
|
||||
# Review S4 — HTML prototype
|
||||
|
||||
## Status
|
||||
|
||||
PASS — static prototype delivered for maintainer UX confirmation.
|
||||
|
||||
## Files
|
||||
|
||||
- `.task/2026-11-18/m04-queries/prototype/index.html`
|
||||
- `.task/2026-11-18/m04-queries/prototype/README.md`
|
||||
|
||||
## Notes
|
||||
|
||||
- Covers gate, empty/list, draft edit, version readonly, preview outcome switcher, publish confirm.
|
||||
- Follows D22 footer/list button rules and M03 prototype interaction pattern.
|
||||
- User execute-all-todos authorization (2026-11-18): S5 proceeds using prototype defaults documented in README (preview saved draft; disable allows click-then-reject for preview; name-based masking).
|
||||
@@ -0,0 +1,26 @@
|
||||
# Review S5 — Vue queries console
|
||||
|
||||
## Status
|
||||
|
||||
PASS_WITH_WARNINGS — module landed; unit/typecheck verified in session; e2e evidence pending formal S6 run.
|
||||
|
||||
## Scope delivered
|
||||
|
||||
- `web/apps/console/src/queries/**` — list/edit/gate/version/preview helpers
|
||||
- Routes under `/queries` in `router.ts`; nav/crumbs in `AppShell.vue`
|
||||
- `allowsQueries` admin gate in `session.ts`
|
||||
- Locales (四语言) + `docs/current/frontend-ui.md` 查询节
|
||||
- Unit specs: validation/payload/client/errors/locales
|
||||
- E2E: `web/apps/console/e2e/queries.spec.ts` (mocked API)
|
||||
|
||||
## UX defaults locked for S5
|
||||
|
||||
- Preview saved draft; dirty form disables preview / prompts save before publish
|
||||
- Disabled: list preview disabled; detail preview click → 409 explanation
|
||||
- Masking via API `masked_columns`
|
||||
|
||||
## Remaining for S6
|
||||
|
||||
- Formal Playwright run + screenshots under `docs/evidence/M04/ui/`
|
||||
- Independent module review across S1–S5
|
||||
- Full pytest regression
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"taskId": "2026-11-18/m04-queries",
|
||||
"module": "M04",
|
||||
"title": "查询定义与采集模块",
|
||||
"type": "feature",
|
||||
"tier": "L",
|
||||
"phase": "final-approval",
|
||||
"allowedToCode": false,
|
||||
"currentSlice": "S6-done",
|
||||
"proposedNextSlice": null,
|
||||
"lastGate": "module-review-pass-awaiting-final-approval",
|
||||
"status": "VERIFIED_LOCAL",
|
||||
"gatePolicy": {
|
||||
"selected": "autonomous",
|
||||
"effective": "autonomous",
|
||||
"recommended": "balanced",
|
||||
"finalApprovalRequired": true,
|
||||
"allowTaskOverride": true
|
||||
},
|
||||
"validation": {
|
||||
"pytest": "456 passed",
|
||||
"consoleUnitQueries": "51 passed",
|
||||
"e2eQueries": "16 passed",
|
||||
"evidence": "docs/evidence/M04/ui/"
|
||||
},
|
||||
"notes": [
|
||||
"D24 parameterized SQL + immutable versions; formal collection deferred to M08",
|
||||
"Module review FAIL then remediations: DB append-only versions; SQL Server preview refused",
|
||||
"Recheck PASS"
|
||||
],
|
||||
"updatedAt": "2026-11-18T07:30:00Z"
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
# Context Pack — m04-version-activate
|
||||
|
||||
## Task goal
|
||||
|
||||
去掉查询草稿/发布两步;保存即新版本并生效;支持版本激活(列表+详情)。
|
||||
|
||||
## Requirement / plan
|
||||
|
||||
- `.task/2026-11-18/m04-version-activate/requirement.md`
|
||||
- `.task/2026-11-18/m04-version-activate/implementation-plan.md`
|
||||
- D26 in `docs/decisions.md`
|
||||
|
||||
## Allowed modification scope
|
||||
|
||||
- `services/watchman/src/watchman/models/query.py`
|
||||
- `services/watchman/src/watchman/services/queries.py`
|
||||
- `services/watchman/src/watchman/api/routes/queries.py`
|
||||
- `services/watchman/migrations/versions/20261118_0008_*.py`
|
||||
- `services/watchman/tests/test_query_*.py`
|
||||
- `web/apps/console/src/queries/**`
|
||||
- `web/apps/console/locales/**`
|
||||
- `web/apps/console/e2e/queries.spec.ts`
|
||||
- `docs/decisions.md`, `docs/progress.md`, `docs/tasks/M04.md`, `docs/current/frontend-ui.md`
|
||||
- `.task/active.json` and this task directory
|
||||
|
||||
## Forbidden
|
||||
|
||||
- Dropping `draft_*` columns
|
||||
- New permission node codes
|
||||
- Scene/cron/alarm modules
|
||||
- Auto commit/push
|
||||
|
||||
## Current approved slice
|
||||
|
||||
- All slices S1–S4 completed; phase `finalization`.
|
||||
- Awaiting user final approval for DONE_LOCAL / optional commit.
|
||||
|
||||
## Validation
|
||||
|
||||
- query* pytest: 201 passed
|
||||
- console unit `src/queries`: 52 passed
|
||||
- e2e `queries.spec.ts`: 16 passed
|
||||
@@ -0,0 +1,10 @@
|
||||
# Implementation Plan
|
||||
|
||||
| Slice | Content | gateClass | risk_score |
|
||||
|-------|---------|-----------|------------|
|
||||
| S1 | migration + save-as-version / activate service | boundary-sensitive | 4 |
|
||||
| S2 | API reshape | standard | 3 |
|
||||
| S3 | console UI | standard | 3 |
|
||||
| S4 | tests + docs | standard | 2 |
|
||||
|
||||
gatePolicy.selected=balanced(用户批准整份 plan 后连续执行)。
|
||||
@@ -0,0 +1,28 @@
|
||||
# M04 增补:去掉草稿 + 版本激活
|
||||
|
||||
## Goal
|
||||
|
||||
查询定义不再使用「草稿/发布」两步。保存内容即生成不可变新版本并自动设为当前生效;可激活任一历史版本;列表与详情均可切换。
|
||||
|
||||
## Decisions
|
||||
|
||||
- D26(1=C,2=A):版本切换=激活 `current_version_no`;保存内容=新版本且自动 current。
|
||||
- 版本行仍不可变(D24 库级约束保留)。`draft_*` 列本轮保留并镜像 current,对外不暴露 draft。
|
||||
|
||||
## In Scope
|
||||
|
||||
- `current_version_no` 迁移与回填。
|
||||
- create → v1 + current;save-as-version;activate;去 publish/draft API 形状。
|
||||
- 控制台:保存/激活/列表切换版本;文案去草稿/发布。
|
||||
|
||||
## Out Of Scope
|
||||
|
||||
- 物理删除 `draft_*` 列。
|
||||
- 场景采集(M08)。
|
||||
- 新权限点编码。
|
||||
|
||||
## Acceptance
|
||||
|
||||
- 新建保存即有 v1 且为 current;再保存得 v2 且 current=v2。
|
||||
- 激活旧版后列表/详情/默认预览跟 current。
|
||||
- UI 无保存草稿/发布/返回草稿;列表可切换版本。
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"taskId": "2026-11-18/m04-version-activate",
|
||||
"type": "feature",
|
||||
"phase": "done",
|
||||
"allowedToCode": false,
|
||||
"currentSlice": "S4",
|
||||
"completedSlices": ["S1", "S2", "S3", "S4"],
|
||||
"status": "DONE_LOCAL",
|
||||
"validation": {
|
||||
"pytest_query": "201 passed",
|
||||
"unit_queries": "52 passed",
|
||||
"e2e_queries": "16 passed"
|
||||
},
|
||||
"gatePolicy": {
|
||||
"selected": "balanced",
|
||||
"effective": "balanced",
|
||||
"recommended": "balanced",
|
||||
"finalApprovalRequired": true,
|
||||
"allowTaskOverride": true
|
||||
},
|
||||
"updatedAt": "2026-11-18T10:31:00Z"
|
||||
}
|
||||
+8
-7
@@ -1,16 +1,17 @@
|
||||
{
|
||||
"taskId": "2026-11-17/m03-datasource",
|
||||
"taskId": "2026-11-18/m04-version-activate",
|
||||
"type": "feature",
|
||||
"phase": "done",
|
||||
"allowedToCode": false,
|
||||
"currentSlice": "done",
|
||||
"lastGate": "done-local",
|
||||
"nextCommand": "none — M03 DONE_LOCAL; pick next module from docs/tasks/INDEX.md",
|
||||
"currentSlice": "S4",
|
||||
"lastGate": "user-approved-done-local",
|
||||
"nextCommand": "start M05 when ready",
|
||||
"gatePolicy": {
|
||||
"selected": "autonomous",
|
||||
"effective": "autonomous",
|
||||
"selected": "balanced",
|
||||
"effective": "balanced",
|
||||
"recommended": "balanced",
|
||||
"finalApprovalRequired": true,
|
||||
"allowTaskOverride": true
|
||||
},
|
||||
"updatedAt": "2026-11-18T04:50:00Z"
|
||||
"updatedAt": "2026-11-18T10:31:00Z"
|
||||
}
|
||||
Reference in new issue
Block a user