diff --git a/.github/dependabot.yml b/.github/dependabot.yml index e677fb4..515f13c 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -5,6 +5,11 @@ updates: schedule: interval: weekly open-pull-requests-limit: 5 + - package-ecosystem: npm + directory: /web + schedule: + interval: weekly + open-pull-requests-limit: 5 - package-ecosystem: github-actions directory: / schedule: diff --git a/.gitignore b/.gitignore index 85a393f..753d59b 100644 --- a/.gitignore +++ b/.gitignore @@ -11,7 +11,7 @@ __pycache__/ .coverage coverage.xml htmlcov/ -build/ +/build/ dist/ .queryforge/ .idea/ diff --git a/README.md b/README.md index f104c01..4aaf0ae 100644 --- a/README.md +++ b/README.md @@ -415,7 +415,6 @@ CI runs the offline acceptance gate on Python 3.11 and 3.12. | Evaluation | [NL2SQL evaluation](docs/nl2sql_evaluation.md) | | Reports | [Report artifacts](docs/report_artifact.md) | | Subject scoping | [Subject tree](docs/subject_tree.md) | -| Verification | [Final acceptance](docs/phase2_final_acceptance.md) | | GitHub release | [First-publish checklist](docs/github_release.md) | | Documentation index | [All guides](docs/README.md) | diff --git a/README.zh-CN.md b/README.zh-CN.md index 20cf2ff..fae89cd 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -395,7 +395,6 @@ CI 会在 Python 3.11 和 3.12 上执行离线验收。 | 评测 | [NL2SQL 评测](docs/nl2sql_evaluation.md) | | 报告 | [报告产物](docs/report_artifact.md) | | 主题域裁剪 | [Subject Tree](docs/subject_tree.md) | -| 验收 | [最终验收](docs/phase2_final_acceptance.md) | | GitHub 发布 | [首次发布清单](docs/github_release.md) | | 文档索引 | [全部指南](docs/README.md) | diff --git a/docs/README.md b/docs/README.md index 7f48c65..b7faa4d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,7 +12,6 @@ ## Architecture - [Agent team architecture](agent_team_architecture.md) -- [Workflow comparison](workflow_comparison.md) - [Subject tree](subject_tree.md) - [Semantic contracts](semantic_contracts.md) @@ -21,8 +20,3 @@ - [GitHub release checklist](github_release.md) - [Report artifacts](report_artifact.md) - [NL2SQL evaluation](nl2sql_evaluation.md) -- [Final acceptance](phase2_final_acceptance.md) -- [Semantic source inventory](semantic_source_inventory.md) - -The `reproduction/` directory preserves historical build prompts and design context. -It is documentation, not runtime code. diff --git a/docs/phase2_final_acceptance.md b/docs/phase2_final_acceptance.md deleted file mode 100644 index 1adab6a..0000000 --- a/docs/phase2_final_acceptance.md +++ /dev/null @@ -1,55 +0,0 @@ -# Phase 2 Final Acceptance Report - -## Status - -**Passed.** Phase 2 completes the default Agent Team orchestration evolution while retaining -the governed SQLite SQL core. Final offline acceptance completed with **11/11 checks**, **213** -targeted upgrade tests, and **247** full-suite tests passing; **7** optional-dependency tests -were skipped in the base environment. - -## Completed Capabilities - -| Phase | Capability | Status | -| --- | --- | --- | -| A | Seven task routes, role decision artifacts, quality gates | Complete | -| B | Conversation Memory and Bounded Tool Loop | Complete | -| C | Structured Reasoning, Parallel + Selection, Subject Tree | Complete | -| D | Streaming events, static Report Artifact, enhanced MCP | Complete | - -## Verification - -- `scripts/run_acceptance.py --full`: 11/11 offline checks. -- Targeted upgrade suite: 213 passing tests, 7 optional-dependency skips. -- Full suite: 247 passing tests, 7 optional-dependency skips. -- Default workflow benchmark: two model calls per simple request. -- Phase B/C benchmark isolates each scenario's history/run state. Wall-clock values are - environment observations; the stable regression gate is the two-call default/minimal budget. - Tool Loop stays bounded and two parallel candidates require one additional model call. -- `tests/test_phase2_final_acceptance.py` verifies all task routes, default compatibility, - report generation and progress streaming end-to-end. - -## Architecture and Safety - -All normal query entrypoints use `AgentService -> Router -> Orchestrator -> WorkflowRunner`. -The orchestrator records five compact stages: `analysis`, `candidate`, `execution`, -`completion`, and `delivery`. Metadata and SQL-review requests use direct read-only paths that -intentionally do not execute generated SQL. Every SQL preview and execution path uses -`DatabaseTool` and its AST policy; Governance artifacts are created before normal execution. - -Advanced features remain opt-in or minimal by default: no session without an explicit session -request, Tool Loop disabled, single candidate, Subject Tree disabled, and streaming only when -the stream endpoint or CLI option is selected. - -## Known Limits and Next Directions - -- Report charts prefer the Vega Embed CDN and include an inline SVG fallback; full interactive - rendering still requires the CDN. -- Streaming exposes workflow progress, not provider token streaming or cancellation. -- MCP has no built-in authentication, tenant isolation or rate limiting; keep it in a controlled - local environment. -- SQL review performs static syntax, policy, readability and performance checks, plus explicit - governed metric-alias contract checks. It does not yet prove semantic correctness for arbitrary - SQL expressions. - -Next candidates are provider token streaming/cancellation, authenticated transports, richer -semantic SQL review, report export formats, and domain profiles. diff --git a/docs/reproduction/README.md b/docs/reproduction/README.md deleted file mode 100644 index bbf7311..0000000 --- a/docs/reproduction/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# Reproduction Prompts - -This directory stores phased vibe-coding reproduction prompts and reference notes. -They are documentation assets, not runtime code. - -```text -vibe-coding-reproduce/ 基础 NL2SQL 复现 prompts -vibe-coding-reproduce-upgrade/ 进阶能力复现 prompts -vibe-coding-reproduce-agent-team/ Agent Team 协作层复现 prompts -vibe-coding-reproduce-phase2/ Agent Team 深度进化 prompts -``` - -Runtime code lives under `queryforge/`. Shared sample databases live under -`sample_data/` at the project root to avoid duplicated binary and CSV fixtures. diff --git a/docs/reproduction/vibe-coding-reproduce-agent-team/00_README.md b/docs/reproduction/vibe-coding-reproduce-agent-team/00_README.md deleted file mode 100644 index d05bd80..0000000 --- a/docs/reproduction/vibe-coding-reproduce-agent-team/00_README.md +++ /dev/null @@ -1,122 +0,0 @@ -# QueryForge 多 Agent 协作层强化 Prompts - -这个文件夹是第三阶段复现交付物。它的主体仍然是前两个文件夹逐步复现出的 `QueryForge` 项目: - -- `vibe-coding-reproduce/`:基础版,自然语言转 SQL 主链路。 -- `vibe-coding-reproduce-upgrade/`:进阶版,多模型、Skills、反思、修复、知识库、可视化、多端入口。 - -本阶段不是创建一个新的“Agent Team 项目”,也不是替换原来的 SQL Agent workflow,而是在原复现项目之上**新增一个可选的多 Agent 协作层**。这个协作层参考 `dw_agent_team_pkg_副本/dw-agent-team` 的设计思想,用来组织、调度和增强原项目已有能力。 - -## 目标 - -目标是让原复现项目保持原有主链路可运行,同时在开启 `--agent-team` 或同等配置时,走多 Agent 协作编排: - -```text -用户请求 - -> Entry Router - -> Orchestrator - -> 多角色协作层 - -> 复用原有 Workflow / Node / Tool / Knowledge / Visualization - -> Skills 三层加载 - -> 结构化 Artifacts - -> HITL Checkpoints - -> 统一 Delivery -``` - -核心原则: - -1. 原复现项目是主体。 -2. `WorkflowRunner / Workflow / Node` 仍是 SQL 执行主链路。 -3. 多 Agent 协作层只做路由、编排、分工、质检、治理和交付汇总。 -4. 新增能力必须复用已有模块,例如 `GenSqlNode`、`FixNode`、`ReflectNode`、SQL history、LanceDB、Visualization。 -5. 必须保留旧模式:不开启多 Agent 时,项目仍按原 workflow 跑通。 - -## 参考到的关键模式 - -来自 `dw_agent_team_pkg_副本/dw-agent-team` 的关键设计: - -1. Entry Router 只做路由,不做业务决策。 -2. Orchestrator 负责分类、编排、上下文管理、质量关卡、最终交付。 -3. 专业 Agent 角色边界清晰,例如产品、架构、开发、QA、运维、知识库、治理。 -4. Skill 与 Agent 分离:角色定义不等于工作流细节,工作流细节放到 Skill 中。 -5. Skills 支持 base + task-specific + platform overlay 的三层加载。 -6. 每个阶段输出结构化 artifact,靠 schema 约束交接。 -7. Human-in-the-Loop checkpoint 不可绕过。 -8. Runtime state 独立持久化,支持恢复、回退、审计。 -9. Hook / guard / telemetry 用于安全、恢复和观测。 -10. 多 Agent 并行用于知识检索、QA、方案对比,而不是所有任务都串行。 - -## 适配后的多 Agent 协作层 - -建议在原项目上新增这些协作角色: - -| Agent | 职责 | -| --- | --- | -| EntryRouterAgent | 判断任务类型,路由到 orchestrator 或轻量直接回答 | -| OrchestratorAgent | 管理全局状态、选择流程、调度子 Agent、做交付汇总 | -| ProductAnalystAgent | 把自然语言问题转成结构化分析需求 | -| SchemaArchitectAgent | 判断相关表、字段、join path、指标口径 | -| SQLDeveloperAgent | 生成 SQL、修复 SQL、解释 SQL | -| DataQAAgent | 执行只读验证、检查 SQL 结果是否符合需求 | -| KnowledgeAgent | 查询历史 SQL、schema docs、skills、reference SQL、向量知识库 | -| VisualizationAgent | 判断结果是否适合可视化,生成图表配置 | -| GovernanceAgent | 做 SQL 安全、成本风险、全表扫描风险、敏感字段风险检查 | -| OpsAgent | 管理 API/MCP/Gateway 入口、运行配置、smoke tests | - -## 使用顺序 - -1. `prompts/01_extract_dw_team_patterns.md` -2. `prompts/02_agent_team_architecture.md` -3. `prompts/03_entry_router_and_orchestrator.md` -4. `prompts/04_role_agents.md` -5. `prompts/05_skill_layering_contract.md` -6. `prompts/06_state_artifacts_checkpoints.md` -7. `prompts/07_multi_agent_runtime.md` -8. `prompts/08_governance_and_safety.md` -9. `prompts/09_hooks_observability_recovery.md` -10. `prompts/10_integration_acceptance.md` -11. `prompts/11_future_extensions.md` - -辅助阅读: - -- `reference/dw_agent_team_patterns.md` -- `reference/queryforge_agent_team_map.md` - -## 最终会得到什么 - -完成本文件夹 prompts 后,原复现项目仍然是一个自然语言转 SQL 项目,只是多了一个可选协作层: - -```text -CLI / API / MCP / Gateway - -> EntryRouterAgent - -> OrchestratorAgent - -> KnowledgeAgent 并行检索 - -> ProductAnalystAgent 需求结构化 - -> SchemaArchitectAgent schema / join path - -> SQLDeveloperAgent 生成 SQL - -> DataQAAgent 验证结果 - -> GovernanceAgent 安全和成本 gate - -> VisualizationAgent 可选图表 - -> OpsAgent smoke test / deployment readiness - -> Delivery Report -``` - -关闭多 Agent 层时: - -```text -CLI / API / MCP / Gateway - -> WorkflowRunner - -> 原有 workflow -``` - -开启多 Agent 层时: - -```text -CLI / API / MCP / Gateway - -> EntryRouterAgent - -> OrchestratorAgent - -> 调度多个协作 Agent - -> 复用原有 WorkflowRunner / Node / Tool -``` - -它仍然不是完整 DW Agent Team,也不依赖 ByteDance 内部平台命令。它复现的是“在原 SQL Agent 项目上增加多 Agent 协作层”的架构思想:角色边界、Skills 分层、状态机、产物契约、检查点和恢复机制。 diff --git a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/01_extract_dw_team_patterns.md b/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/01_extract_dw_team_patterns.md deleted file mode 100644 index ce0e073..0000000 --- a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/01_extract_dw_team_patterns.md +++ /dev/null @@ -1,67 +0,0 @@ -# Prompt 01: 提炼 DW Agent Team 多 Agent 模式 - -复制下面整段给 Codex 使用。 - -```text -你现在要继续强化已有 QueryForge 项目。前两阶段已经实现了自然语言转 SQL、Skills、多模型、反思、修复、历史 SQL、LanceDB、可视化、日志和多端入口。 - -重要定位: - -本阶段必须以已有 QueryForge 为主体。不要创建新项目,不要重命名项目,不要替换原来的 WorkflowRunner / Workflow / Node 主链路。我们只是借鉴 DW Agent Team 的多 Agent 协作思想,给原复现项目增加一个可选的多 Agent 协作层。 - -本阶段参考一个新的项目:DW Agent Team。请先不要写代码,本轮只做架构模式提炼。 - -DW Agent Team 的关键特征: - -1. Entry Router 只做路由,不做业务执行。 -2. Orchestrator 负责分类、编排、上下文管理、质量关卡和最终交付。 -3. 多个专业 Agent 分工: - - Product Manager - - Architect - - Developer - - QA - - Ops - - Knowledge Base - - Governance -4. Agent 与 Skill 分离。 -5. Skills 使用三层加载: - - base skill - - task-specific skill - - platform/datasource overlay skill -6. 每个阶段产出结构化 artifact,并通过 schema 约束。 -7. 有 task_state,记录 current_phase、completed_phases、artifacts、retry_counts、checkpoints、blocked reason。 -8. 有 Human-in-the-Loop checkpoints,不能绕过关键确认。 -9. 有 hooks / guard / telemetry / recovery 机制。 -10. 支持并行调用知识库、QA、治理等子 Agent。 - -请基于以上信息,完成以下分析: - -1. 哪些模式适合迁移到 QueryForge。 -2. 哪些模式不适合迁移,原因是什么。 -3. QueryForge 应该新增哪些 Agent 角色。 -4. QueryForge 应该新增哪些 Skills 分层。 -5. QueryForge 在保留原 Context 的前提下,应该新增哪些 artifact schema。 -6. QueryForge 在保留原 run/context 逻辑的前提下,task_state 应该如何设计。 -7. 哪些场景需要 HITL checkpoint。 -8. 多 Agent 架构与现有 Workflow/Node 架构如何共存。 - -限制: - -- 不要写代码。 -- 不要照搬 DW Agent Team 的内部平台命令。 -- 不要引入 bytedcli、Dorado、Meego、飞书真实集成。 -- 不要推倒现有 QueryForge 架构。 -- 不要让多 Agent 层重写已有 GenSqlNode、ExecuteSqlNode、ReflectNode、FixNode、VisualizationNode。 -- 不开启多 Agent 层时,原项目必须仍然能按旧 workflow 跑通。 - -输出要求: - -- 一份结构化架构分析。 -- 最后给出下一轮“在原项目上新增多 Agent 协作层”的输入摘要。 - -验收标准: - -- 能清晰解释 DW Agent Team 的核心架构价值。 -- 能把它迁移成适合 SQL Agent 的本地可复现方案。 -- 能区分“架构思想”与“内部平台绑定实现”。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/02_agent_team_architecture.md b/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/02_agent_team_architecture.md deleted file mode 100644 index 7ff7c50..0000000 --- a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/02_agent_team_architecture.md +++ /dev/null @@ -1,112 +0,0 @@ -# Prompt 02: 原项目上的多 Agent 协作层架构设计 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请为 QueryForge 设计“多 Agent 协作层”。本轮仍不写代码,只输出可实施设计。 - -关键定位: - -QueryForge 原项目是主体。多 Agent 协作层必须作为原项目的增量 wrapper / orchestration layer 存在。不要新建另一个项目,不要替换原有 WorkflowRunner / Workflow / Node,不要复制已有 SQL 生成、执行、反思、修复、可视化逻辑。 - -现有能力假设: - -- CLI/API/MCP/Gateway 多入口 -- WorkflowRunner / Workflow / Node -- 多 LLM provider -- Skills 系统 -- DateParserNode / Plan Mode -- ReflectNode / FixNode retry -- SQL history cache / LanceDB -- Visualization -- Logging - -目标: - -在现有 workflow 之上增加可选多 Agent 编排层,而不是替换现有节点。开启多 Agent 时,由协作层调度和增强;关闭多 Agent 时,原 workflow 完全照旧运行。 - -请设计: - -1. 新目录结构 - 至少包含: - - agents/ - - skills/ - - orchestrator/ - - runtime/ - - artifacts/ - - schemas/ - - hooks/ - -2. Agent 列表与职责 - - EntryRouterAgent - - OrchestratorAgent - - ProductAnalystAgent - - SchemaArchitectAgent - - SQLDeveloperAgent - - DataQAAgent - - KnowledgeAgent - - GovernanceAgent - - VisualizationAgent - - OpsAgent - -3. Agent 与现有 Node 的关系 - 必须说明哪些 Agent 复用已有 Node / Store / Tool: - - SQLDeveloperAgent 复用 GenSqlNode / FixNode - - DataQAAgent 复用 ExecuteSqlNode / ReflectNode 的部分逻辑,不重新实现数据库执行器 - - KnowledgeAgent 复用 SQL history / LanceDB - - VisualizationAgent 复用 VisualizationNode - - GovernanceAgent 复用已有 SQL guard / DatabaseTool 只读检查 - - OrchestratorAgent 最终仍调用已有 WorkflowRunner 或已有节点能力 - -4. Pipeline 类型 - 至少设计: - - ask_sql - - sql_review - - troubleshoot_sql - - explain_result - - build_report - -5. Orchestrator 调度策略 - - 串行阶段 - - 可并行阶段 - - 失败回退 - - retry budget - - HITL checkpoint - -6. Artifact 契约 - 设计这些 JSON artifact: - - analysis_request.json - - schema_plan.json - - sql_candidate.json - - execution_result.json - - qa_report.json - - governance_report.json - - visualization_artifact.json - - delivery_report.json - -7. Runtime state - 设计 `.queryforge/runs//state.json` 的核心字段。 - -限制: - -- 不要实现代码。 -- 不要做复杂分布式调度。 -- 不要把每个 Agent 做成独立进程,先允许同进程类调用。 -- 不要复制已有 workflow 逻辑。 -- 不要把多 Agent 协作层设计成新的主系统。 -- 不要破坏不开启 `--agent-team` 时的旧运行路径。 - -输出要求: - -- 架构设计文档。 -- ASCII workflow 图。 -- 目录结构图。 -- Agent/Skill/Artifact 映射表。 -- 下一轮实现 EntryRouter 和 Orchestrator 的任务清单。 - -验收标准: - -- 设计能在现有 QueryForge 上增量实现,且原 workflow 仍是核心执行主链路。 -- 多 Agent 和原 workflow 关系清楚。 -- 每个 Agent 职责边界清楚,不互相抢职责。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/03_entry_router_and_orchestrator.md b/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/03_entry_router_and_orchestrator.md deleted file mode 100644 index 0998837..0000000 --- a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/03_entry_router_and_orchestrator.md +++ /dev/null @@ -1,105 +0,0 @@ -# Prompt 03: EntryRouterAgent 与 OrchestratorAgent - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请在 QueryForge 中实现 EntryRouterAgent 和 OrchestratorAgent。 - -本轮目标: - -在原 QueryForge 项目上新增一个可选的多 Agent 协作入口和总协调层。只实现路由、状态、调度骨架,不实现所有专业 Agent 的完整能力。 - -重要约束: - -- 原 `WorkflowRunner / Workflow / Node` 是主体,不能删除、替换或绕开。 -- EntryRouterAgent 和 OrchestratorAgent 是 wrapper / orchestration layer。 -- `--agent-team` 未开启时,旧路径必须完全不变。 -- `--agent-team` 开启后,ask_sql 仍应能调用已有 WorkflowRunner 完成 SQL 主链路。 - -请先读取当前项目,再做增量修改。 - -实现要求: - -1. EntryRouterAgent - 职责: - - 接收用户输入和入口来源(CLI/API/MCP/Gateway)。 - - 分类任务类型。 - - 简单任务可直接返回。 - - 复杂任务交给 OrchestratorAgent。 - - 只做路由,不生成 SQL、不执行 SQL、不做业务判断。 - - 任务类型至少包括: - - ask_sql - - sql_review - - troubleshoot_sql - - explain_result - - build_report - - metadata_query - - unknown - -2. OrchestratorAgent - 职责: - - 创建 run_id。 - - 初始化 task_state。 - - 根据 task_type 选择 pipeline。 - - 调度后续 agent。 - - 管理 artifacts。 - - 管理 checkpoints。 - - 汇总 delivery_report。 - - 在专业 Agent 尚未完整实现时,调用已有 WorkflowRunner 作为核心执行 fallback。 - -3. Pipeline 定义 - 先实现配置化 pipeline,不要写死在大 if else 中。 - 例如: - - ask_sql: - - product_analyst - - knowledge - - schema_architect - - sql_developer - - governance - - data_qa - - visualization - - delivery - -4. Runtime State - 写入: - - `.queryforge/runs//state.json` - - `.queryforge/runs//artifacts/` - - `.queryforge/runs//logs/` - -5. CLI 集成 - - 增加 `--agent-team` 开关。 - - 未开启时保留旧 workflow。 - - 开启后走 EntryRouterAgent -> OrchestratorAgent。 - - 增加 `--show-agent-plan`。 - -6. 降级策略 - - 如果某个专业 Agent 还未实现,Orchestrator 应输出明确 TODO artifact,而不是崩溃。 - - 保证 ask_sql 可以 fallback 到已有 WorkflowRunner。 - - fallback 是正式设计的一部分,不是临时错误处理;它确保原复现项目始终可运行。 - -限制: - -- 不要实现完整专业 Agent。 -- 不要删除旧 CLI / WorkflowRunner。 -- 不要引入异步队列或多进程。 -- 不要绕过 Plan Mode / SQL guard。 -- 不要为了多 Agent 层重写 GenSqlNode、ExecuteSqlNode、ReflectNode、FixNode。 - -输出要求: - -- 直接修改文件。 -- 给出新增目录和文件。 -- 给出路由规则。 -- 给出 state.json 示例。 -- 给出验证命令。 - -验收标准: - -- `--agent-team --show-agent-plan` 能展示将要执行的 Agent pipeline。 -- ask_sql 可以通过 Orchestrator fallback 到旧 workflow 跑通。 -- 每次运行都有 run_id 和 state.json。 -- EntryRouter 不直接执行 SQL。 -- 不开启 `--agent-team` 时,原 CLI 行为不变。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/04_role_agents.md b/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/04_role_agents.md deleted file mode 100644 index 714e77b..0000000 --- a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/04_role_agents.md +++ /dev/null @@ -1,115 +0,0 @@ -# Prompt 04: 专业 Role Agents - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请为 QueryForge 的多 Agent 协作层实现专业 Role Agents 的最小可用版本。 - -本轮目标: - -在保留原 ask_sql workflow 主链路的前提下,让多个角色 Agent 围绕它协作并产出 artifacts。实现要轻量,不要一次做成大型框架。 - -重要约束: - -- Role Agents 是原项目的协作层,不是替代原 workflow 的新实现。 -- 能复用已有 Node / Store / Tool 的地方必须复用。 -- SQL 的最终生成、修复、执行、反思、可视化优先走已有模块。 - -请先读取当前项目,再做增量修改。 - -需要实现的 Agent: - -1. ProductAnalystAgent - 输入:用户问题、date_context。 - 输出:analysis_request.json。 - 职责: - - 提炼用户想要的指标、维度、过滤条件、排序、limit。 - - 不写 SQL。 - - 信息不足时输出 clarification_needed。 - -2. KnowledgeAgent - 输入:用户问题、analysis_request。 - 输出:knowledge_context.json。 - 职责: - - 查询 SQL history。 - - 查询 reference SQL。 - - 查询 LanceDB。 - - 查询本地 Skills 摘要。 - - 可与 ProductAnalystAgent 并行。 - -3. SchemaArchitectAgent - 输入:analysis_request、knowledge_context、当前数据库 schema。 - 输出:schema_plan.json。 - 职责: - - 选择相关表和字段。 - - 推断 join path。 - - 标注可能的指标计算口径。 - - 不生成最终 SQL。 - -4. SQLDeveloperAgent - 输入:schema_plan、analysis_request、skills_context、knowledge_context。 - 输出:sql_candidate.json。 - 职责: - - 优先调用现有 GenSqlNode 逻辑或模型层。 - - 生成 SQL、解释、tables_used。 - - 需要修复时复用 FixNode。 - -5. GovernanceAgent - 输入:sql_candidate、schema_plan。 - 输出:governance_report.json。 - 职责: - - 只读检查。 - - 多语句检查。 - - 全表扫描风险。 - - LIMIT 缺失风险。 - - 敏感字段风险。 - - 高成本 join 风险。 - -6. DataQAAgent - 输入:sql_candidate、execution_result、analysis_request。 - 输出:qa_report.json。 - 职责: - - 校验 row_count。 - - 检查结果列是否回答问题。 - - 检查空结果是否合理。 - - 可以调用 ReflectNode 的模型评估。 - -7. VisualizationAgent - 输入:execution_result、analysis_request。 - 输出:visualization_artifact.json。 - 职责: - - 复用已有 VisualizationNode 或 visualization 规则。 - - 不适合图表时输出 table fallback。 - -8. OpsAgent - 输入:run state。 - 输出:ops_report.json。 - 职责: - - smoke test。 - - API/MCP/Gateway readiness。 - - 配置检查。 - -限制: - -- 每个 Agent 先实现为 Python class,不要独立进程。 -- 每个 Agent 必须写 artifact。 -- 不要让 ProductAnalyst 直接写 SQL。 -- 不要让 SQLDeveloper 跳过 Governance。 -- 不要让 QA 修改 SQL;QA 只能建议 retry/fix。 -- 不要重写 SQLiteConnector、DatabaseTool、GenSqlNode、ExecuteSqlNode。 -- 不要破坏不开启 `--agent-team` 的旧路径。 - -输出要求: - -- 直接修改文件。 -- 给出每个 Agent 的输入/输出 artifact。 -- 给出 ask_sql pipeline 的新流程。 -- 给出验证命令。 - -验收标准: - -- `--agent-team` 下 ask_sql 产生多个 artifact。 -- SQL 执行前有 governance_report。 -- SQL 执行后有 qa_report。 -- 最终 delivery_report 汇总所有 Agent 结果。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/05_skill_layering_contract.md b/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/05_skill_layering_contract.md deleted file mode 100644 index 5f8e419..0000000 --- a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/05_skill_layering_contract.md +++ /dev/null @@ -1,110 +0,0 @@ -# Prompt 05: Skills 三层加载契约 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请把 QueryForge 原有 Skills 系统增强为类似 DW Agent Team 的三层加载契约。 - -本轮目标: - -在不推翻原 Skills 系统的前提下,让多 Agent 协作层中的每个 Role Agent 都能按固定顺序加载: - -1. role definition -2. base skill -3. task-specific skill -4. datasource overlay skill -5. runtime context - -请先读取当前项目,再做增量修改。 - -实现要求: - -1. Skills 目录结构 - 建议: - - skills/ - base/ - sql_agent/SKILL.md - safety/SKILL.md - product_analyst/ - analyze_question/SKILL.md - schema_architect/ - plan_schema/SKILL.md - sql_developer/ - nl2sql/SKILL.md - fix_sql/SKILL.md - data_qa/ - validate_result/SKILL.md - review_sql/SKILL.md - governance/ - sql_safety_gate/SKILL.md - cost_risk_gate/SKILL.md - knowledge/ - retrieve_context/SKILL.md - visualization/ - chart_selection/SKILL.md - datasource/ - sqlite/SKILL.md - duckdb/SKILL.md - -2. skill.yml metadata - 增加字段: - - name - - layer: base | task | overlay - - agent_roles - - task_types - - datasource_types - - priority - - enabled - -3. SkillLoadingPlan - 对每次 Agent 调用生成加载计划: - - role file - - base skills - - task skills - - overlay skills - - runtime context files/artifacts - -4. 加载顺序 - 必须固定: - role -> base -> task -> overlay -> runtime context - -5. 覆盖语义 - - overlay 可以覆盖 task skill 中与 SQL 方言、连接器、测试命令相关的要求。 - - task skill 可以覆盖 base skill 的一般流程。 - - safety base skill 不可被覆盖,只能更严格。 - -6. CLI - - `--show-skill-plan` - - `--skills` - - `--disable-skill` - -7. Artifact - 每个 Agent artifact 中记录: - - selected_skills - - skill_selection_reason - - skill_plan_hash - -限制: - -- Skill 仍然是 prompt/context,不执行任意代码。 -- 不实现远程 marketplace。 -- 不实现权限系统,但要预留 enabled/disabled。 -- 不要把所有技能一次加载到所有 Agent。 -- 不要删除或重写前一阶段已经实现的 SkillRegistry / SkillManager;应在其基础上扩展。 -- 不开启多 Agent 协作层时,原 Skills 注入方式仍可工作。 - -输出要求: - -- 直接修改文件。 -- 创建示例 Skills。 -- 给出 SQLDeveloperAgent 的 skill loading 示例。 -- 给出验证命令。 - -验收标准: - -- 每个 Agent 能生成 skill loading plan。 -- `--show-skill-plan` 可见加载顺序。 -- SQLite overlay 能影响 SQL 方言要求。 -- artifact 记录 selected_skills。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/06_state_artifacts_checkpoints.md b/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/06_state_artifacts_checkpoints.md deleted file mode 100644 index c137a32..0000000 --- a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/06_state_artifacts_checkpoints.md +++ /dev/null @@ -1,107 +0,0 @@ -# Prompt 06: State、Artifacts 与 HITL Checkpoints - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请为 QueryForge 的多 Agent 协作层实现结构化 state、artifacts 和 HITL checkpoints。 - -本轮目标: - -复现 DW Agent Team 的“状态机 + 阶段产物 + 人工确认点”思想,让多 Agent 协作层可恢复、可审计、可回退。原 Workflow 的 Context 仍然保留,state/artifacts 是协作层的外部运行记录,不替代 Context。 - -请先读取当前项目,再做增量修改。 - -实现要求: - -1. task_state - 文件位置: - `.queryforge/runs//state.json` - - 字段至少包含: - - run_id - - user_question - - task_type - - current_phase - - completed_phases - - artifacts - - retry_counts - - checkpoints - - blocked - - block_reason - - created_at - - updated_at - -2. phase enum - 至少包含: - - init - - classify - - product_analysis - - knowledge_retrieval - - schema_planning - - sql_development - - governance - - execution - - qa - - visualization - - delivery - - completed - - blocked - -3. artifact schemas - 在 `schemas/artifacts/` 下定义轻量 JSON schema 或 Pydantic model: - - analysis_request - - knowledge_context - - schema_plan - - sql_candidate - - governance_report - - execution_result - - qa_report - - visualization_artifact - - delivery_report - -4. checkpoint 类型 - - clarification_required - - plan_approval - - dangerous_sql_blocked - - high_cost_warning - - qa_failed - - delivery_review - -5. CLI 交互 - - `--resume-run ` - - `--list-runs` - - `--show-run ` - - `--approve-checkpoint :` - - `--reject-checkpoint :` - -6. Plan Mode 整合 - - Plan Mode 应写 checkpoint。 - - 用户 approve 后才能继续 execution。 - -7. 恢复策略 - - 如果 run interrupted,从 state.json 恢复 current_phase。 - - 已完成 artifact 不重复生成,除非 `--force-phase`。 - -限制: - -- 不实现数据库型 workflow engine。 -- 不实现复杂 UI。 -- 不绕过 checkpoint。 -- 不把 runtime artifacts 写进源码目录根部,必须写入 `.queryforge/runs/`。 -- 不要把原 Context 迁移成 state.json;state.json 只记录协作层运行状态和 artifact 路径。 - -输出要求: - -- 直接修改文件。 -- 给出 state.json 示例。 -- 给出 artifact 文件示例。 -- 给出 checkpoint 生命周期。 -- 给出验证命令。 - -验收标准: - -- 每次 agent-team run 都产生 state.json。 -- 每个阶段 artifact 路径写入 state。 -- Plan Mode 会产生可审批 checkpoint。 -- run 可以 list/show/resume。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/07_multi_agent_runtime.md b/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/07_multi_agent_runtime.md deleted file mode 100644 index e5f525d..0000000 --- a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/07_multi_agent_runtime.md +++ /dev/null @@ -1,88 +0,0 @@ -# Prompt 07: 多 Agent Runtime、并行与 Handoff - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请实现 QueryForge 多 Agent 协作层的轻量 runtime。 - -本轮目标: - -让 Orchestrator 能以统一方式调度 Role Agents,支持串行、并行、handoff 和失败回退。这个 runtime 只服务多 Agent 协作层,不替代原 WorkflowRunner。 - -请先读取当前项目,再做增量修改。 - -实现要求: - -1. AgentRuntime - 提供统一接口: - - run_agent(agent_name, input_context) - - run_agents_parallel(agent_specs) - - collect_artifacts() - - handle_failure() - -2. AgentSpec - 字段: - - agent_name - - phase - - input_artifacts - - output_artifact - - required - - can_run_parallel - - retry_limit - -3. 并行执行 - ask_sql pipeline 中允许并行: - - ProductAnalystAgent - - KnowledgeAgent - - sql_review pipeline 中允许并行: - - DataQAAgent - - GovernanceAgent - - KnowledgeAgent - -4. Handoff contract - 每个 Agent 返回: - - status: success | blocked | failed - - artifact_path - - summary - - risks - - next_suggestions - -5. 失败策略 - - required agent failed -> pipeline blocked。 - - optional agent failed -> 记录 warning,继续。 - - retry_limit 用尽 -> blocked。 - - blocked 必须写 block_reason。 - -6. Orchestrator 集成 - - pipeline 不再手写逐个调用。 - - 从 pipeline config 构建 AgentSpec。 - - Runtime 负责执行和收集。 - -7. 调试输出 - - `--show-agent-trace` - - trace 中展示每个 Agent 的开始、结束、耗时、artifact。 - -限制: - -- 可以用 Python asyncio 或线程池,但不要引入 Celery/RQ。 -- 不要求真正跨进程 subagent。 -- 不要并行执行会写同一个 artifact 的 Agent。 -- 不要让并行破坏 checkpoint 顺序。 -- 不要把原 WorkflowRunner 改造成 AgentRuntime;AgentRuntime 应该调用或包裹原 WorkflowRunner。 -- 不开启 `--agent-team` 时,AgentRuntime 不参与运行。 - -输出要求: - -- 直接修改文件。 -- 给出 runtime 设计说明。 -- 给出 ask_sql 和 sql_review 的 pipeline config。 -- 给出验证命令。 - -验收标准: - -- ProductAnalystAgent 和 KnowledgeAgent 可并行执行。 -- trace 能展示 Agent 执行顺序和耗时。 -- required/optional 失败行为不同。 -- Orchestrator 不再负责底层执行细节。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/08_governance_and_safety.md b/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/08_governance_and_safety.md deleted file mode 100644 index 0d48347..0000000 --- a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/08_governance_and_safety.md +++ /dev/null @@ -1,78 +0,0 @@ -# Prompt 08: GovernanceAgent 与安全门禁 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请强化 QueryForge 多 Agent 协作层的 GovernanceAgent 和安全门禁。 - -本轮目标: - -参考 DW Agent Team 中 Governance 的思想,但迁移为本地 SQL Agent 可实现的安全、成本和质量 gate。GovernanceAgent 必须复用原项目已有 SQL guard、DatabaseTool 只读检查或相关能力,不能另写一套执行入口。 - -请先读取当前项目,再做增量修改。 - -GovernanceAgent 要求: - -1. SQL 安全 gate - - 只允许 SELECT / WITH。 - - 拒绝 DDL/DML。 - - 拒绝多语句。 - - 拒绝危险函数或可疑注入片段。 - -2. 成本风险 gate - - 无 LIMIT 的大结果风险。 - - 无 WHERE 的大表扫描风险。 - - 多表 join 无 join key 风险。 - - 聚合无 group by 合理性检查。 - -3. Schema 风险 gate - - SQL 使用不存在的表或字段。 - - 字段名需要反引号但未处理。 - - join path 与 schema_plan 不一致。 - -4. 敏感字段 gate - - 通过配置维护 sensitive column patterns。 - - 例如 email、phone、address、id_card。 - - 命中时输出 warning 或 checkpoint。 - -5. Checkpoint 触发 - - dangerous_sql_blocked:直接阻断。 - - high_cost_warning:要求用户确认或 `--auto-approve-risk`。 - - sensitive_field_warning:根据配置决定阻断或提示。 - -6. Artifact - governance_report.json 包含: - - decision: pass | warn | block - - checks - - risks - - required_checkpoints - - suggested_changes - -7. 与 SQLDeveloperAgent / FixNode 集成 - - 如果 block 原因可修复,交给 FixNode。 - - 如果是危险 SQL,不允许自动修复后绕过,必须重新过 gate。 - -限制: - -- 不需要完整 SQL AST parser;如已有 sqlglot 可以使用,否则用保守规则。 -- 不做权限系统。 -- 不做真实脱敏。 -- 不允许 GovernanceAgent 执行 SQL。 -- 不要绕过原 DatabaseTool / ExecuteSqlNode 的只读防护;GovernanceAgent 是额外 gate,不是替代。 - -输出要求: - -- 直接修改文件。 -- 给出 gate 列表。 -- 给出 governance_report 示例。 -- 给出危险 SQL 测试命令。 -- 给出 high cost warning 测试命令。 - -验收标准: - -- DROP/INSERT/UPDATE/DELETE 被阻断。 -- 多语句被阻断。 -- 高成本查询能产生 checkpoint。 -- governance_report 写入 artifacts。 -- SQL 执行前必须通过 GovernanceAgent。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/09_hooks_observability_recovery.md b/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/09_hooks_observability_recovery.md deleted file mode 100644 index 57414e5..0000000 --- a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/09_hooks_observability_recovery.md +++ /dev/null @@ -1,86 +0,0 @@ -# Prompt 09: Hooks、观测与恢复机制 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请为 QueryForge 的多 Agent 协作层增加轻量 hooks、观测和恢复机制。 - -本轮目标: - -参考 DW Agent Team 的 SessionStart、PreToolUse、Stop、Telemetry、Recovery 思想,但用本地 Python runtime 实现,不依赖外部平台 hooks。hooks 只包裹协作层和原 workflow 调用,不改变原业务结果。 - -请先读取当前项目,再做增量修改。 - -实现要求: - -1. HookManager - 支持这些生命周期事件: - - session_start - - before_agent - - after_agent - - before_sql_execute - - after_sql_execute - - on_checkpoint - - on_error - - run_stop - -2. 内置 hooks - - recovery_hook:启动时发现未完成 run。 - - sql_guard_hook:执行 SQL 前调用 Governance gate。 - - telemetry_hook:记录 agent 运行、耗时、token/字符数摘要。 - - artifact_hook:每个阶段结束后校验 artifact 存在。 - - stop_hook:运行结束时写 run summary。 - -3. Recovery - - `--recover` 列出 interrupted/blocked runs。 - - `--resume-run ` 从 state.current_phase 继续。 - - `--archive-run ` 归档旧 run。 - -4. Observability - - `.queryforge/runs//trace.jsonl` - - `.queryforge/runs//summary.json` - - 每条 trace 包含: - - timestamp - - event - - agent - - phase - - duration_ms - - status - - artifact_path - - error - -5. CLI - - `--show-agent-trace` - - `--recover` - - `--resume-run` - - `--archive-run` - -6. 配置 - - hooks.yml 控制启用/禁用。 - - 默认启用 recovery、sql_guard、artifact、stop。 - - telemetry 可关闭。 - -限制: - -- 不接外部 telemetry endpoint。 -- 不实现 IDE 平台 hook 安装。 -- 不记录完整敏感 prompt,除非 debug 开启。 -- 不让 hooks 修改业务结果,除 sql_guard 可以阻断。 -- 不开启 `--agent-team` 时,不强制启用协作层 hooks;原日志系统仍可独立工作。 - -输出要求: - -- 直接修改文件。 -- 给出 hook lifecycle 图。 -- 给出 trace.jsonl 示例。 -- 给出恢复流程。 -- 给出验证命令。 - -验收标准: - -- 每次 agent-team run 有 trace.jsonl。 -- SQL 执行前触发 sql_guard_hook。 -- run_stop 会写 summary。 -- 可列出未完成 run。 -- 可 resume 一个 blocked/interrupted run。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/10_integration_acceptance.md b/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/10_integration_acceptance.md deleted file mode 100644 index dabd038..0000000 --- a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/10_integration_acceptance.md +++ /dev/null @@ -1,116 +0,0 @@ -# Prompt 10: 多 Agent Team 集成验收 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请对 QueryForge 的多 Agent 协作层做完整集成验收。 - -本轮目标: - -不要新增大功能。请验证多 Agent 协作层、原 workflow、Skills 三层加载、state/artifacts/checkpoints、runtime、governance、hooks 能一起工作。重点确认:原复现项目仍是主体,多 Agent 层只是可选增强。 - -请先读取当前项目,再执行检查和最小修复。 - -验收范围: - -1. 基础兼容 - - 不开启 `--agent-team` 时,旧 workflow 仍能跑通。 - - 开启 `--agent-team` 时,走 EntryRouter -> Orchestrator。 - - 开启 `--agent-team` 后,SQL 主链路仍复用原 WorkflowRunner / Node,而不是复制一套新逻辑。 - -2. 路由 - - ask_sql 能路由到 Orchestrator。 - - sql_review 能路由到 QA + Governance。 - - metadata_query 能路由到 KnowledgeAgent。 - - unknown 能给出澄清或 fallback。 - -3. Agent pipeline - ask_sql 至少经过: - - ProductAnalystAgent - - KnowledgeAgent - - SchemaArchitectAgent - - SQLDeveloperAgent - - GovernanceAgent - - DataQAAgent - - VisualizationAgent 可选 - - Delivery - -4. Artifacts - 检查 `.queryforge/runs//artifacts/` 中至少包含: - - analysis_request.json - - knowledge_context.json - - schema_plan.json - - sql_candidate.json - - governance_report.json - - execution_result.json - - qa_report.json - - delivery_report.json - -5. State - - state.json 包含 current_phase。 - - completed_phases 正确推进。 - - artifacts 路径可读。 - - blocked 状态可表示。 - -6. Skills - - `--show-skill-plan` 能展示 role/base/task/overlay/context。 - - SQLDeveloperAgent 使用 SQLite overlay。 - - artifact 记录 selected_skills。 - -7. Parallel - - ProductAnalystAgent 和 KnowledgeAgent 可并行。 - - trace 能看到并行阶段。 - -8. Governance - - SELECT 通过。 - - DROP/INSERT/UPDATE/DELETE 阻断。 - - high cost warning 产生 checkpoint。 - -9. Checkpoints - - Plan Mode checkpoint 不确认不执行。 - - high cost checkpoint 可 approve 后继续。 - - reject 后 run 标记 blocked。 - -10. Hooks / recovery - - trace.jsonl 存在。 - - summary.json 存在。 - - `--recover` 能列出未完成 run。 - - `--resume-run` 能继续。 - -11. Sample data - 使用已打包的: - - `sample_data/anime_streaming/anime_streaming.sqlite` - - 至少运行一个真实问题: - `What is the phone number of the anime with the highest total watch time?` - -允许修改: - -- 修 bug。 -- 补 smoke tests。 -- 改 README。 -- 改错误提示。 - -不允许修改: - -- 不新增大功能。 -- 不引入外部平台依赖。 -- 不破坏非 agent-team 模式。 -- 不用新实现替换原 GenSqlNode / ExecuteSqlNode / ReflectNode / FixNode / VisualizationNode。 - -输出要求: - -- 先列验收计划。 -- 执行验证。 -- 修复发现的问题。 -- 输出最终验收报告。 -- 输出从零运行命令。 - -最终验收标准: - -- agent-team 模式能端到端跑通 ask_sql。 -- 旧模式仍能跑通。 -- agent-team 模式复用原 workflow 核心能力。 -- 多 Agent 产物完整。 -- Governance gate 生效。 -- state/trace/summary 可用于调试和恢复。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/11_future_extensions.md b/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/11_future_extensions.md deleted file mode 100644 index 99ebfb6..0000000 --- a/docs/reproduction/vibe-coding-reproduce-agent-team/prompts/11_future_extensions.md +++ /dev/null @@ -1,89 +0,0 @@ -# Prompt 11: 多 Agent Team 后续扩展路线 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请为 QueryForge 的多 Agent 协作层设计后续扩展路线。本轮不写代码。 - -已完成能力假设: - -- EntryRouterAgent -- OrchestratorAgent -- Role Agents -- Skills 三层加载 -- State / Artifacts / Checkpoints -- AgentRuntime 并行和 handoff -- Governance gate -- Hooks / observability / recovery - -请基于当前项目,规划下一阶段可以继续增强的能力。 - -候选方向: - -1. 真正的 Agentic Tool Loop - - SQLDeveloperAgent 可以多轮调用 list_tables、describe_table、execute_sql_preview。 - -2. Multi-candidate SQL - - 多个 SQLDeveloperAgent 生成候选。 - - QA/Governance/Execution 评分后 selection。 - -3. Specialist Subagents - - 针对 finance、sales、education 等领域创建专属 schema scope + skills。 - -4. Team Memory - - Orchestrator 记住用户偏好、业务规则、常用数据库。 - -5. Knowledge Writing - - 成功案例沉淀到 reference SQL。 - - 用户说“记住”时写入本地 knowledge。 - -6. Conversation Follow-up - - 支持“刚才那个结果按县分组”。 - - 复用上一次 run artifacts。 - -7. Report Agent - - 从单图升级为多段分析报告。 - -8. Benchmark Harness - - 使用 tables/*.csv 的 gold_sql 做自动评测。 - -9. Agent Evaluation - - 对 ProductAnalyst、SchemaArchitect、SQLDeveloper、QA 各自打分。 - -10. UI - - Web 页面展示 pipeline、state、artifacts、trace。 - -11. 更完整 MCP - - 暴露 agent pipeline tools。 - - 暴露 artifacts resources。 - -12. Deployment Profile - - dev / demo / production 三套配置。 - -输出要求: - -1. 按优先级排序。 -2. 每个方向说明: - - 为什么值得做。 - - 依赖哪些现有模块。 - - MVP 怎么做。 - - 不建议一开始做什么。 - - 验收标准。 -3. 给出下一批 prompts 的文件清单。 -4. 给出风险清单。 - -限制: - -- 不要写代码。 -- 不要把所有功能都标成 P0。 -- 不要脱离 QueryForge 当前架构。 -- 不要引入 DW Agent Team 内部平台依赖。 -- 不要把后续扩展设计成新项目;必须继续以原复现项目为主体。 -- 不要规划会替换原 workflow 主链路的重构,除非明确说明兼容迁移路径。 - -验收标准: - -- 输出能作为下一轮 prompt 文件夹规划。 -- 能继续保持增量演进。 -- 能区分高学习价值和工程复杂度。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-agent-team/reference/dw_agent_team_patterns.md b/docs/reproduction/vibe-coding-reproduce-agent-team/reference/dw_agent_team_patterns.md deleted file mode 100644 index 0108807..0000000 --- a/docs/reproduction/vibe-coding-reproduce-agent-team/reference/dw_agent_team_patterns.md +++ /dev/null @@ -1,151 +0,0 @@ -# DW Agent Team 可借鉴模式 - -本文总结 `dw_agent_team_pkg_副本/dw-agent-team` 中值得迁移到 QueryForge 复现项目的模式。 - -## 1. Entry Router - -`agents/_entry.md` 的设计要点: - -- 入口只做路由,不做业务。 -- 读取上下文和分类信号。 -- 决定下一跳 agent。 -- 失败时退回 orchestrator。 - -迁移到 QueryForge: - -```text -EntryRouterAgent - -> metadata/query 问题:KnowledgeAgent - -> SQL 分析问题:OrchestratorAgent - -> SQL review:DataQAAgent + GovernanceAgent - -> visualization:VisualizationAgent - -> API/MCP/Gateway 运维:OpsAgent - -> 简单解释:直接回答 -``` - -## 2. Orchestrator - -`agents/orchestrator.md` 的设计要点: - -- 分类任务。 -- 选择流程。 -- 调度专业 Agent。 -- 管理上下文和质量关卡。 -- 处理回退和澄清。 -- 汇总最终交付。 - -迁移到 QueryForge: - -```text -OrchestratorAgent - classify request - choose pipeline - create task_state - dispatch agents - validate artifacts - checkpoint if needed - produce delivery report -``` - -## 3. Role Agents - -DW Agent Team 有明确角色边界: - -- Product Manager:需求结构化。 -- Architect:表设计和建模。 -- Developer:实现代码。 -- QA:测试和质量验证。 -- Ops:发布上线和排障。 -- Knowledge Base:知识检索。 -- Governance:治理和安全。 - -迁移到 QueryForge: - -- ProductAnalystAgent:把用户问题转成分析需求。 -- SchemaArchitectAgent:选择表、字段、join path、指标口径。 -- SQLDeveloperAgent:生成 SQL、修复 SQL。 -- DataQAAgent:验证 SQL 和结果。 -- KnowledgeAgent:检索历史 SQL / schema docs / reference SQL。 -- GovernanceAgent:只读安全、成本、敏感字段、全表扫描 gate。 -- OpsAgent:多端入口、配置、smoke test、运行状态。 - -## 4. Skills 三层加载 - -DW Agent Team 的 Developer Agent 使用: - -```text -base skill - + task-specific skill - + platform overlay skill -``` - -迁移到 QueryForge: - -```text -base SQL agent skill - + task skill: nl2sql / sql_review / troubleshooting / visualization - + datasource overlay: sqlite / duckdb / postgres -``` - -规则: - -- base 负责通用约束。 -- task skill 负责具体工作流。 -- datasource overlay 只覆盖方言、连接器、限制和测试命令。 - -## 5. Artifacts Schema - -DW Agent Team 用 JSON schema 约束阶段产物。 - -迁移到 QueryForge 的最小产物: - -- `analysis_request.json` -- `schema_plan.json` -- `sql_candidate.json` -- `qa_report.json` -- `governance_report.json` -- `visualization_artifact.json` -- `delivery_report.json` - -每个 Agent 只消费上游产物中自己需要的字段。 - -## 6. State 与 Checkpoint - -DW Agent Team 的 `task-state.schema.json` 包含: - -- task_id -- classification -- current_phase -- completed_phases -- artifacts -- retry_counts -- checkpoints -- blocked reason - -迁移到 QueryForge: - -```text -.queryforge/runs//state.json -.queryforge/runs//artifacts/*.json -.queryforge/runs//logs/*.log -``` - -Plan Mode、SQL 执行、危险 SQL、外部 API、Gateway 回复都可以作为 checkpoint。 - -## 7. Hooks / Guard / Telemetry - -DW Agent Team 的 hooks 做: - -- session recovery -- pre-tool guard -- telemetry -- stop reconciliation - -迁移到 QueryForge: - -- 启动时恢复未完成 run。 -- SQL 执行前做只读 guard。 -- 每个 Agent 产物写入 trace。 -- 结束时写 delivery summary。 - -不需要照搬平台 hooks,可在 Python runtime 内实现。 diff --git a/docs/reproduction/vibe-coding-reproduce-agent-team/reference/queryforge_agent_team_map.md b/docs/reproduction/vibe-coding-reproduce-agent-team/reference/queryforge_agent_team_map.md deleted file mode 100644 index 5cb83f8..0000000 --- a/docs/reproduction/vibe-coding-reproduce-agent-team/reference/queryforge_agent_team_map.md +++ /dev/null @@ -1,154 +0,0 @@ -# QueryForge 多 Agent 协作层映射 - -## 原复现项目是主体 - -进阶版 QueryForge 当前已有主链路: - -```text -WorkflowRunner - -> DateParserNode - -> SchemaLinkingNode - -> GenSqlNode - -> ExecuteSqlNode - -> ReflectNode / FixNode - -> OutputNode / VisualizationNode -``` - -第三阶段不是替换这条链路,而是在它外面增加一个可选协作层: - -```text -EntryRouterAgent - -> OrchestratorAgent - -> KnowledgeAgent - -> ProductAnalystAgent - -> SchemaArchitectAgent - -> SQLDeveloperAgent - -> DataQAAgent - -> GovernanceAgent - -> VisualizationAgent - -> OpsAgent - -> existing WorkflowRunner / Nodes -``` - -原则: - -- 原 `WorkflowRunner / Workflow / Node` 继续承担 SQL 生成、执行、反思、修复、输出等核心运行逻辑。 -- 新增 Agent 主要负责结构化需求、知识检索、schema 规划、治理 gate、QA 和交付汇总。 -- SQLDeveloperAgent 应优先调用已有 `GenSqlNode / FixNode`,而不是重写 SQL 生成。 -- VisualizationAgent 应优先调用已有 VisualizationNode。 -- KnowledgeAgent 应优先调用已有 SQL history / LanceDB。 - -## Pipeline 示例 - -### ask_sql:协作层包裹原 workflow - -```text -EntryRouterAgent - -> OrchestratorAgent - -> parallel: - KnowledgeAgent: history/reference/schema docs - ProductAnalystAgent: structured analysis request - -> SchemaArchitectAgent: tables, columns, join path - -> SQLDeveloperAgent: SQL candidate - -> GovernanceAgent: read-only / cost gate - -> existing ExecuteSqlNode / WorkflowRunner 执行 SQL - -> DataQAAgent: result validation - -> existing VisualizationNode 或 VisualizationAgent: optional chart - -> OrchestratorAgent: delivery report -``` - -### sql_review - -```text -EntryRouterAgent - -> DataQAAgent: correctness and result risk - -> GovernanceAgent: safety and cost risk - -> KnowledgeAgent: best practices - -> OrchestratorAgent: consolidated review -``` - -### troubleshoot - -```text -EntryRouterAgent - -> OpsAgent: classify failure - -> KnowledgeAgent: similar failures - -> SQLDeveloperAgent: repair proposal - -> DataQAAgent: verify repair - -> OrchestratorAgent: report -``` - -## Agent Artifact Contract - -```text -ProductAnalystAgent - output: analysis_request.json - -SchemaArchitectAgent - input: analysis_request.json + knowledge_context - output: schema_plan.json - -SQLDeveloperAgent - input: schema_plan.json + skills_context + date_context - output: sql_candidate.json - -GovernanceAgent - input: sql_candidate.json + schema_plan.json - output: governance_report.json - -DataQAAgent - input: sql_candidate.json + execution_result - output: qa_report.json - -VisualizationAgent - input: execution_result + analysis_request - output: visualization_artifact.json - -OrchestratorAgent - input: all artifacts - output: delivery_report.json -``` - -## Skills Loading Contract - -```text -Agent Role Definition - + Base Skill - + Task Skill - + Datasource Overlay - + Runtime Context -``` - -示例: - -```text -SQLDeveloperAgent - role: agents/sql_developer.md - base: skills/base/sql_agent/SKILL.md - task: skills/sql_developer/nl2sql/SKILL.md - overlay: skills/datasource/sqlite/SKILL.md - context: schema_plan + history_matches + date_context -``` - -## HITL Checkpoints - -建议保留这些检查点: - -- `requirement_unclear`:用户问题不清楚。 -- `plan_approval`:Plan Mode 下执行前确认。 -- `dangerous_sql_blocked`:SQL guard 拦截。 -- `high_cost_warning`:可能全表扫描或结果过大。 -- `qa_failed`:QA 判断结果不满足需求。 -- `delivery_review`:最终交付前确认。 - -## 不迁移的内容 - -不迁移 DW Agent Team 中强绑定内部平台的能力: - -- bytedcli Dorado / Oceanus / Meego 具体命令。 -- 飞书知识库真实拉取。 -- 影子任务 promote。 -- 内部 telemetry endpoint。 -- 平台 shim 安装脚本。 - -只迁移架构思想和可在本地复现的最小实现;实现主体仍然是前两个复现文件夹产出的 QueryForge 项目。 diff --git a/docs/reproduction/vibe-coding-reproduce-phase2/00_README.md b/docs/reproduction/vibe-coding-reproduce-phase2/00_README.md deleted file mode 100644 index fb79b69..0000000 --- a/docs/reproduction/vibe-coding-reproduce-phase2/00_README.md +++ /dev/null @@ -1,101 +0,0 @@ -# QueryForge 第二阶段:Agent Team 深度进化 Prompts - -这个文件夹是第四阶段复现交付物。前三阶段分别是: - -- `vibe-coding-reproduce/`:基础版,NL2SQL 主链路。 -- `vibe-coding-reproduce-upgrade/`:进阶版,多模型、Skills、反思、修复、知识库、可视化、多端入口。 -- `vibe-coding-reproduce-agent-team/`:Agent Team 层,路由、编排、角色、状态、artifact。 - -本阶段的起点是:**Agent Team 已经成为默认编排主链**,不再是可选包装层。所有入口(CLI/API/MCP/Gateway)都经过 EntryRouter → Orchestrator → WorkflowRunner。 - -## 本阶段目标 - -让 Agent Team 从"框架层面的编排"进化为"真正能提升准确率和体验的协作系统"。重点是: - -1. **填平补齐**:让现有角色和路由真正发挥作用,而不是信息打包。 -2. **增强自主性**:从单轮生成走向观察-行动循环。 -3. **提升质量**:多候选选择、结构化推理、主题范围控制。 -4. **丰富形态**:流式输出、报告交付、更完整的 MCP。 - -## 原则 - -1. **不推翻现有架构**:Agent Team 编排 + WorkflowRunner 执行的双层结构保持不变。 -2. **安全边界只增不减**:任何新能力都不能绕过 DatabaseTool 和 GovernanceAgent。 -3. **每步可验收**:每个 prompt 都有明确的验收标准和测试用例。 -4. **可配置可降级**:高级功能默认关闭或有预算限制,简单查询不增加额外成本。 - -## 阶段划分 - -### Phase A:填平补齐(4 个 prompt) - -让现有的 Agent Team 框架真正立得住。 - -| # | Prompt | 核心内容 | -|---|--------|---------| -| 01 | 路由落地:sql_review / metadata_query / explain 独立 pipeline | 让 EntryRouter 的分类真正改变执行路径 | -| 02 | 角色升级:ProductAnalyst / SchemaArchitect 决策化 | 从"信息打包"变成"有判断能力" | -| 03 | Artifact 质量门禁与阶段推进 | 每个角色 artifact 有 valid/warning/blocked 三级 | -| 04 | Phase A 集成验收 | 验证填平补齐后的稳定性和一致性 | - -### Phase B:增强自主性(3 个 prompt) - -从"被动生成"走向"主动观察-行动"。 - -| # | Prompt | 核心内容 | -|---|--------|---------| -| 05 | Conversation Memory:会话上下文与追问重写 | session_id、结构化记忆、指代消解 | -| 06 | 有界 Tool Loop:观察-行动-再规划 | 工具白名单、预算控制、多轮观察 | -| 07 | Structured Reasoning Node:可审计决策摘要 | 结构化推理、可校验、可复用 | - -### Phase C:质量提升(3 个 prompt) - -提升准确率和稳定性。 - -| # | Prompt | 核心内容 | -|---|--------|---------| -| 08 | Parallel + Selection:多候选生成与选择 | 2-3 个候选、规则+执行信号评分 | -| 09 | Subject Tree / Scoped Context:主题范围约束 | 减少 token、降低跨域误用 | -| 10 | Phase B+C 集成验收 | 自主性 + 质量提升的端到端验证 | - -### Phase D:形态扩展(3 个 prompt) - -丰富交互和交付形态。 - -| # | Prompt | 核心内容 | -|---|--------|---------| -| 11 | Streaming Output:节点级事件流 | SSE、CLI 进度、事件协议 | -| 12 | Report Artifact:静态 HTML 分析报告 | 多图、表格、口径说明 | -| 13 | MCP 增强:resources / prompts / sessions | 更完整的 MCP 协议支持 | -| 14 | 最终集体验收 | 全链路回归、性能基线、文档收尾 | - -## 使用顺序 - -按编号顺序使用,每个 prompt 完成后再进入下一个。Phase 之间的集成验收 prompt 不要跳过。 - -## 最终会得到什么 - -完成全部 prompts 后,QueryForge 从"有 Agent Team 外壳的 NL2SQL 工具"升级为"真正多 Agent 协作的分析系统": - -```text -CLI / API / MCP / Gateway - -> EntryRouterAgent (任务分类) - -> OrchestratorAgent (编排协调) - -> Conversation Memory (会话上下文) - -> ProductAnalystAgent (需求分析 + 歧义检测) - -> [Subject Tree 主题范围] - -> KnowledgeAgent (知识检索) - -> SchemaArchitectAgent (Schema 规划 + Join 推荐) - -> [Bounded Tool Loop] (可选,观察-行动循环) - -> [Parallel Candidates] (可选,多候选生成) - -> SQLDeveloperAgent (候选注册) - -> GovernanceAgent (安全治理) - -> WorkflowRunner (SQL 生成 / 执行 / 反射 / 修复) - -> DataQAAgent (质量报告) - -> VisualizationAgent (可视化) - -> OpsAgent (运维状态) - -> [Report Artifact] (可选,报告交付) - -> DeliveryReport - -> [Streaming] (可选,事件流) -``` - -它仍然不是企业级数据平台,但已经覆盖了从"单轮 SQL 生成"到"多 Agent 协作分析系统"的关键演进路径。 diff --git a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/01_routing_and_pipelines.md b/docs/reproduction/vibe-coding-reproduce-phase2/prompts/01_routing_and_pipelines.md deleted file mode 100644 index add1329..0000000 --- a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/01_routing_and_pipelines.md +++ /dev/null @@ -1,144 +0,0 @@ -# Prompt 01: 路由落地——让分类真正改变执行路径 - -复制下面整段给 Codex 使用。 - -```text -继续上一阶段。当前 QueryForge 的 Agent Team 已经是默认编排主链,EntryRouterAgent 能分类出多种任务类型,但所有分类最终都走同一套 ask_sql 工作流。 - -本轮目标:让 EntryRouter 的分类真正改变执行路径,至少实现 3 条独立 pipeline: - -1. sql_review:SQL 评审 pipeline -2. metadata_query:元数据查询 pipeline -3. explain_result:结果解释 pipeline(复用 ask_sql 的执行,但侧重解释) - -## 现状 - -当前代码位置(请先读取确认): -- queryforge/agent_team/agents/entry_router.py:EntryRouterAgent,返回 task_type 和 confidence -- queryforge/agent_team/orchestrator/pipeline_registry.py:PIPELINES 字典,目前所有类型都用同一套角色 -- queryforge/agent_team/orchestrator/orchestrator.py:OrchestratorAgent.run(),目前统一调 workflow -- queryforge/agent_team/agents/:各角色实现 - -## 本轮要做的事 - -### 1. 扩展 pipeline_registry - -为不同 task_type 定义不同的 pipeline 阶段。不是所有 pipeline 都要走完整的 SQL 生成-执行流程。 - -| task_type | pipeline | 说明 | -|-----------|----------|------| -| ask_sql | product_analyst → knowledge → schema_architect → sql_developer → governance → execute_sql → data_qa → visualization → ops → delivery | 现有默认流程 | -| sql_review | product_analyst → schema_architect → sql_developer → governance → review → ops → delivery | 不执行 SQL,只做静态评审 | -| metadata_query | schema_architect → knowledge → delivery | 只返回表结构/指标信息 | -| troubleshoot_sql | product_analyst → schema_architect → sql_developer → governance → execute_sql → data_qa → ops → delivery | 用户提供 SQL,定位并修复错误 | -| explain_result | product_analyst → schema_architect → sql_developer → governance → execute_sql → data_qa → explain → ops → delivery | 执行 SQL 后侧重解释 | -| build_report | product_analyst → knowledge → schema_architect → sql_developer → governance → execute_sql → data_qa → visualization → report → ops → delivery | 生成多图报告 | -| unknown | product_analyst → knowledge → schema_architect → sql_developer → governance → execute_sql → data_qa → visualization → ops → delivery | 回退到默认 ask_sql 行为 | - -注意:pipeline 是声明式的阶段列表,实际每个阶段由哪个 Agent 执行、执行什么逻辑,在 orchestrator 中映射。 - -### 2. 在 OrchestratorAgent 中实现阶段到 Agent 的映射 - -增加一个 `_execute_phase(state, phase, context, database_tool)` 方法,根据当前 phase 调用对应角色或操作。 - -关键映射: -- `product_analyst` → ProductAnalystAgent.run() -- `knowledge` → KnowledgeAgent.run() -- `schema_architect` → SchemaArchitectAgent.run() -- `sql_developer` → SQLDeveloperAgent.run() -- `governance` → GovernanceAgent.run() -- `review` → 新增 SQLReviewAgent(或用 Governance + SchemaArchitect 组合) -- `execute_sql` → 这是 WorkflowRunner 的职责,orchestrator 不直接执行 -- `data_qa` → DataQAAgent.run() -- `visualization` → VisualizationAgent.run() -- `explain` → 复用 ReflectNode 的解释能力,生成更详细的解释报告 -- `report` → 留 stub,标记为 degraded,Phase D 再实现 -- `ops` → OpsAgent.run() -- `delivery` → 生成 DeliveryReport - -### 3. 实现 SQLReviewAgent(最小可用) - -新建 queryforge/agent_team/agents/sql_review.py: - -职责:对一段用户提供的 SQL 做静态评审,输出评审报告。 - -评审维度(复用已有能力,不重新实现): -- 安全性:用 DatabaseTool.policy_engine 评估 -- 语法正确性:用 sqlglot parse 检查 -- 性能风险:SELECT *、无 LIMIT、多表 JOIN、全表扫描风险 -- 语义风险:是否符合语义模型口径(如果有) -- 可读性:表别名、列命名、格式 - -输入:用户问题(包含 SQL)、context、database_tool -输出:review_report artifact,包含各维度评分和改进建议 - -### 4. 实现 metadata_query 的快速路径 - -metadata_query 不应该走完整的 GenSQL -> Execute 流程,因为用户只是想看表结构/指标信息。 - -实现方式: -- 在 orchestrator 中检测到 task_type == "metadata_query" -- 直接调用 SchemaArchitectAgent,由它汇总表结构、语义模型实体、指标列表 -- KnowledgeAgent 补充相关的历史查询或文档 -- 直接生成交付,不调用 WorkflowRunner -- 输出格式:{ "status": "success", "metadata": {...}, "agent_team": {...}, "delivery_report": {...} } - -metadata 查询的内容包括: -- 表列表和简要说明 -- 指定表的字段列表和类型 -- 语义模型中的实体和指标(如果有) -- 常用查询示例(来自历史 SQL) - -### 5. 让 troubleshoot_sql 接受用户提供的 SQL - -当前 EntryRouter 分类出 troubleshoot_sql,但没有机制接收用户提供的 SQL。 - -实现方式: -- 在 AgentOptions 中增加可选字段 `provided_sql: str | None = None` -- 如果 provided_sql 不为空且 task_type 是 troubleshoot_sql,则把这段 SQL 作为初始候选 -- WorkflowRunner 仍然负责执行和反射修复,但起点是用户的 SQL 而不是 LLM 生成 -- 新增一个节点或在 GenSqlNode 中支持"使用提供的 SQL"模式 - -或者更简单的实现:在 ProductAnalystAgent 中检测问题中的 SQL 片段,提取出来存入 context,后续 SQLDeveloperAgent 直接使用。 - -请选择更优雅的方案并说明理由。 - -### 6. 更新 EntryRouter 的分类逻辑 - -- sql_review:匹配"review sql"、"审核 sql"、"检查 sql"、"sql review"等 -- metadata_query:匹配"show tables"、"表结构"、"list tables"、"schema"、"metadata"、"指标列表"等 -- troubleshoot_sql:匹配"sql error"、"sql 报错"、"debug sql"、"修复 sql"等,且问题中包含 SQL 片段 -- explain_result:匹配"explain"、"解释"、"为什么"、"原因"等 -- build_report:匹配"report"、"报告"、"dashboard"、"报表"等 -- ask_sql:默认 - -保持现有基于正则的确定性分类优先,不引入 LLM 分类器。 - -## 限制 - -- 不要引入新的 LLM 调用,所有新增 Agent 的评审/解释逻辑优先用规则和已有工具 -- SQLReviewAgent 不执行 SQL(只读 AST 和 Schema) -- metadata_query 不调用 LLM 生成 SQL -- 不破坏 ask_sql 的现有行为和测试 -- 所有新增 pipeline 都要有对应的 artifact 写入 -- 不要新增 agent_team 开关,所有入口都统一走 Orchestrator - -## 验收标准 - -1. `ask_sql` 行为不变,全量测试通过 -2. `sql_review` 分类正确,返回 review_report artifact,不执行 SQL -3. `metadata_query` 分类正确,返回表结构和指标信息,不走 GenSQL -4. `troubleshoot_sql` 能从问题中提取 SQL,以用户 SQL 为起点进行修复 -5. `explain_result` 返回更详细的解释报告(比默认 explanation 更丰富) -6. `build_report` 返回 degraded 状态的 report artifact(留待 Phase D 实现) -7. 所有 pipeline 都有 state.json 和 delivery_report -8. 新增对应测试:每种 pipeline 至少 2 个测试用例 - -## 输出要求 - -1. 先读取现有代码,确认 entry_router、pipeline_registry、orchestrator 的当前实现 -2. 给出实现方案和文件变更列表 -3. 实现代码 -4. 编写测试 -5. 运行测试,确保 ask_sql 全绿,新增 pipeline 测试通过 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/02_role_agents_decision_making.md b/docs/reproduction/vibe-coding-reproduce-phase2/prompts/02_role_agents_decision_making.md deleted file mode 100644 index 2ee6f2b..0000000 --- a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/02_role_agents_decision_making.md +++ /dev/null @@ -1,202 +0,0 @@ -# Prompt 02: 角色升级——ProductAnalyst / SchemaArchitect 决策化 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。当前 Agent Team 的角色中,ProductAnalystAgent 和 SchemaArchitectAgent 基本上是把 Context 里已有的信息重新打包成 artifact,没有独立的决策能力。 - -本轮目标:让这两个核心角色从"信息打包"升级为"有判断能力",真正为后续 SQL 生成提供价值。 - -## 现状(请先读取确认) - -- queryforge/agent_team/agents/product_analyst.py:当前实现 -- queryforge/agent_team/agents/schema_architect.py:当前实现 -- queryforge/schemas/models.py:Context 模型,看看有哪些字段 -- queryforge/agent/node/metric_search_node.py:指标搜索逻辑 -- queryforge/semantic/model.py:语义模型和匹配逻辑 - -## 本轮要做的事 - -### 1. ProductAnalystAgent 升级 - -当前 ProductAnalystAgent 只是用正则提取一些关键词。升级后应该做真正的需求分析: - -#### 1.1 需求澄清检测 - -检测问题中的模糊点和缺失信息,输出 clarification_needed 列表: - -```python -{ - "artifact_type": "analysis_request", - "status": "valid" | "warning" | "blocked", - "goal": "用户的分析目标", - "metrics": ["识别到的指标列表"], - "dimensions": ["识别到的维度/分组字段"], - "filters": ["识别到的过滤条件"], - "sort_by": ["排序字段"], - "limit": 数量或 null, - "grain": "分析粒度", - "time_range": "时间范围或 null", - "clarification_needed": [ - { - "aspect": "指标口径不明确", - "question": "用户说'销售额',是指订单金额还是实收金额?", - "severity": "low" | "medium" | "high" - } - ], - "ambiguities": ["其他歧义点"], - "assumptions": ["做出的假设"] -} -``` - -检测规则(不用 LLM,用规则实现): -- 指标口径不明确:问题中提到"销售额"、"收入"但语义模型中有多个相关指标 -- 维度缺失:提到了"排名"但没说按什么维度排 -- 时间范围缺失:涉及趋势、增长但没有时间范围 -- 粒度模糊:说"用户数"但没说明是去重用户还是订单用户 -- 比较基准缺失:提到"增长"、"同比"但没说和什么比 - -#### 1.2 指标和维度映射 - -如果有语义模型,ProductAnalystAgent 应该: -- 主动把用户提到的业务术语映射到语义模型的指标/维度 -- 检测用户提到的指标是否在 allowed_dimensions 内 -- 推荐最合适的指标,而不是等 MetricSearchNode 去匹配 - -注意:ProductAnalystAgent 不替代 MetricSearchNode,而是提前做业务层面的分析和建议。MetricSearchNode 仍然做精确的结构化匹配。 - -#### 1.3 artifact 状态三级制 - -analysis_request 的 status 字段: -- `valid`: 需求清晰,可以直接生成 SQL -- `warning`: 有一些模糊点,但做了合理假设,可以继续 -- `blocked`: 关键信息缺失,无法继续(比如完全不知道用户要查什么) - -blocked 状态会终止流程(由 orchestrator 判断)。 - -### 2. SchemaArchitectAgent 升级 - -当前 SchemaArchitectAgent 只是汇总已有信息。升级后应该做真正的 Schema 规划: - -#### 2.1 表选择和优先级排序 - -不只是把所有相关表列出来,还要: -- 按相关性排序 -- 标注每张表的角色(事实表、维度表、参考表) -- 标注哪些表是必须的,哪些是可选的 -- 检测是否遗漏了关键表(比如用户提到"销售额"但没选到订单表) - -#### 2.2 Join Path 推荐和风险评估 - -如果有语义模型: -- 推荐最优 Join Path -- 评估 fan-out 风险 -- 说明为什么选这条路径而不是另一条 -- 如果有多条路径,列出各自的 trade-off - -如果没有语义模型: -- 基于外键信息推荐 Join -- 标注"无外键约束,Join 可能不准确"的风险 - -#### 2.3 字段建议 - -为常见分析任务推荐字段: -- 时间维度字段 -- 维度/分组字段 -- 度量/聚合字段 -- 过滤字段 - -推荐依据: -- 语义模型中的维度定义 -- 字段名和类型 -- 历史 SQL 中常用的字段 -- 值提示(value hints) - -#### 2.4 schema_plan artifact 结构升级 - -```python -{ - "artifact_type": "schema_plan", - "status": "valid" | "warning" | "blocked", - "primary_tables": [ - { - "table_name": "fact_watch_session", - "role": "fact", - "relevance_score": 0.95, - "reason": "包含订单金额和数量,是销售额指标的主表", - "key_metrics": ["order_amount", "quantity"], - "key_dimensions": ["order_date", "customer_id"] - } - ], - "join_paths": [ - { - "path_name": "orders_to_customers", - "tables": ["fact_watch_session", "dim_user"], - "join_keys": [{"left": "customer_id", "right": "customer_id"}], - "cardinality": "many_to_one", - "fan_out_risk": false, - "recommended": true - } - ], - "recommended_fields": { - "time_dimensions": ["order_date"], - "group_by": ["customer_segment", "region"], - "aggregations": ["SUM(order_amount)", "COUNT(DISTINCT customer_id)"], - "filters": ["order_date >= '2024-01-01'"] - }, - "risks": [ - { - "type": "missing_join", - "severity": "medium", - "description": "用户提到地区,但没有选择区域维度表" - } - ], - "assumptions": [] -} -``` - -### 3. KnowledgeAgent 小幅升级 - -KnowledgeAgent 也顺便升级一下,但改动不用太大: -- 对历史 SQL 匹配结果按相关性和质量排序 -- 去重相似的历史 SQL -- 标注哪些历史 SQL 最值得参考(比如执行成功、有反射验证通过的) -- 如果历史 SQL 太少,标记为 warning - -### 4. Orchestrator 集成 - -OrchestratorAgent 需要: -- 根据 analysis_request 的 status 判断是否继续 -- 如果 status 是 blocked,终止并返回澄清建议 -- 如果 status 是 warning,在 delivery_report 中标注 -- schema_plan 的 warning 也要传递到最终结果 - -注意:不要因为 warning 就终止流程。warning 只是提示,不阻塞。 - -## 限制 - -- 不引入 LLM 调用,所有分析都用规则实现 -- 不改变 WorkflowRunner 和节点的内部逻辑 -- 不改变 Context 的字段定义(如果需要传递信息,用 artifact) -- 不破坏现有测试 -- ProductAnalystAgent 和 SchemaArchitectAgent 的输入输出接口不变(artifact 结构扩展但向后兼容) - -## 验收标准 - -1. ask_sql 全量测试通过 -2. ProductAnalystAgent 能检测至少 3 类模糊点 -3. analysis_request 有 valid/warning/blocked 三级状态 -4. SchemaArchitectAgent 能推荐 Join Path 并评估风险 -5. schema_plan 有表选择、Join 路径、字段建议、风险评估 -6. blocked 状态会终止流程并返回澄清建议 -7. warning 状态不阻塞,信息传递到最终结果 -8. 新增测试覆盖:模糊点检测、Join Path 推荐、blocked 终止、warning 传递 - -## 输出要求 - -1. 先读取现有代码,确认各角色的当前实现 -2. 给出升级方案和 artifact 结构定义 -3. 实现代码 -4. 编写测试 -5. 运行测试,确保全量通过 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/03_artifact_quality_gates.md b/docs/reproduction/vibe-coding-reproduce-phase2/prompts/03_artifact_quality_gates.md deleted file mode 100644 index 3cfe1da..0000000 --- a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/03_artifact_quality_gates.md +++ /dev/null @@ -1,167 +0,0 @@ -# Prompt 03: Artifact 质量门禁与阶段推进 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。当前 Agent Team 的各角色已经产生 artifact,但 artifact 只是"写了就过",没有质量门禁,也没有统一的状态推进机制。 - -本轮目标:建立 artifact 质量门禁体系和统一的阶段推进机制,让 Orchestrator 真正成为"编排者"而不是"调用器"。 - -## 现状(请先读取确认) - -- queryforge/agent_team/orchestrator/orchestrator.py:OrchestratorAgent 当前实现 -- queryforge/agent_team/agents/base.py:RoleAgent 基类 -- queryforge/agent_team/schemas/__init__.py:TaskState、ArtifactRef 等模型 -- queryforge/agent_team/runtime/state_store.py:状态存储 - -## 本轮要做的事 - -### 1. 统一 Artifact Status 体系 - -所有 artifact 都必须有明确的 status 字段,取值为: - -- `valid`: 完全通过,可以进入下一阶段 -- `warning`: 有一些问题,但不阻塞继续(默认行为) -- `blocked`: 严重问题,必须终止流程 -- `degraded`: 功能降级(比如某个 Agent 不可用,用 fallback 代替) - -在 RoleAgent 基类中增加 status 校验和统一 emit 方法。 - -### 2. 质量门禁(Quality Gates) - -在每个关键阶段后增加质量门禁检查: - -| 阶段 | 门禁检查 | 触发 blocked 的条件 | -|-----|---------|-------------------| -| analysis | 需求清晰度检查 | 完全无法识别分析目标、关键指标缺失 | -| schema | Schema 完整性检查 | 没有找到任何相关表 | -| sql_candidate | SQL 候选质量检查 | Governance 拒绝、SQL 为空或非法 | -| execution | 执行结果检查 | 执行失败且无法修复 | -| qa | 数据质量检查 | 结果严重不符合预期(由 Reflect 判断) | - -门禁逻辑放在 OrchestratorAgent 中,每个阶段完成后调用 `_check_gate(state, phase)` 方法。 - -### 3. 阶段推进状态机 - -将当前的"一次性调用所有角色"改为"逐阶段推进",每个阶段: -1. 执行该阶段的角色 -2. 检查门禁 -3. 如果 blocked,终止并记录 -4. 如果 warning,记录但继续 -5. 如果 valid,进入下一阶段 - -TaskState 增加字段: -- `current_phase`: 当前阶段 -- `completed_phases`: 已完成阶段列表 -- `pending_phases`: 待执行阶段列表 -- `blocked_phase`: 阻塞在哪个阶段(如果 blocked) -- `blocked_reason`: 阻塞原因 -- `warnings`: 所有 warning 列表 - -这些字段现在部分已有,但需要完善和统一使用。 - -### 4. Artifact Schema 校验 - -为每个 artifact 类型定义 Pydantic schema,在 emit 时校验: -- analysis_request -- knowledge_context -- schema_plan -- sql_candidate -- governance_report -- qa_report -- visualization_artifact -- ops_report -- delivery_report -- review_report(新增) - -校验失败的 artifact 标记为 `degraded` 并记录错误,但不阻塞流程(除非是关键阶段)。 - -### 5. 失败恢复与降级策略 - -定义每个角色的降级策略: - -| 角色 | 降级策略 | -|-----|---------| -| ProductAnalyst | 如果正则解析失败,用问题本身作为 goal,其他字段为空,status=warning | -| Knowledge | 如果历史/向量检索失败,返回空上下文,status=degraded | -| SchemaArchitect | 如果 Schema 读取失败,返回空 plan,status=blocked | -| SQLDeveloper | 必须有 SQL,否则 status=blocked | -| Governance | 如果策略引擎不可用,默认放行但 status=warning(慎用,安全第一) | -| DataQA | 如果检查失败,标记 warning 但继续 | -| Visualization | 如果失败,标记 degraded 但继续 | -| Ops | 永远不阻塞 | - -注意:Governance 的降级策略要谨慎。默认策略是:如果策略引擎不可用,应该 blocked 而不是放行,因为安全是底线。可以留一个配置项控制。 - -### 6. Orchestrator 重构 - -将 OrchestratorAgent 的 run 方法从"三个钩子"重构为"阶段状态机": - -```python -def run(self, *, run_id, decision, workflow, plan_only=False): - # 初始化状态 - state = self._initialize_state(run_id, decision, plan_only) - - try: - # Phase 1: Analysis - self._run_phase(state, "analysis", context=None) - if state.status == "blocked": - return self._blocked_output(state) - - # Phase 2: SQL Generation & Execution (via WorkflowRunner) - result = self._run_execution_phase(state, workflow) - - # Phase 3: Completion - self._run_phase(state, "completion", context=context_from_result) - - return self._success_output(state, result) - except Exception as exc: - return self._failed_output(state, exc) -``` - -等等,但是 WorkflowRunner 内部是一个完整的循环,怎么把阶段推进和它的执行结合起来? - -答案:保持三个生命周期钩子的设计,但在每个钩子中推进阶段状态。Orchestrator 的阶段推进通过钩子触发: -- analysis_hook → 推进 analysis 阶段 -- candidate_hook → 推进 sql_candidate 阶段(每次生成 SQL 都推进) -- completion_hook → 推进 completion 阶段 - -WorkflowRunner 内部的执行循环不变,Orchestrator 通过钩子感知进度。 - -### 7. 重试机制 - -某些阶段失败后可以重试: -- analysis 失败:不重试(输入就是问题本身) -- sql_candidate 失败:由 WorkflowRunner 的 Reflect/Fix 循环处理,Orchestrator 不单独重试 -- governance 拒绝:不重试(安全问题重试没用) -- execution 失败:由 WorkflowRunner 处理 - -Orchestrator 层面的重试主要是为未来的 Tool Loop 和并行候选做准备,本轮先建立机制但不启用。 - -## 限制 - -- 不改变 WorkflowRunner 的内部逻辑 -- 不引入 LLM 调用 -- 不破坏现有 artifact 结构(向后兼容) -- 所有门禁规则都用确定性规则实现 -- 不新增 agent_team 或其他开关 - -## 验收标准 - -1. 所有 artifact 都有 valid/warning/blocked/degraded 状态 -2. 关键阶段有质量门禁检查 -3. blocked 状态会终止流程并返回原因 -4. warning 状态会记录但不阻塞 -5. TaskState 完整记录阶段推进过程 -6. ask_sql 全量测试通过 -7. 新增测试覆盖:blocked 终止、warning 传递、阶段状态推进、artifact schema 校验 -8. 新增测试覆盖:各角色的降级策略 - -## 输出要求 - -1. 先读取现有代码,确认 Orchestrator 和各角色的当前实现 -2. 给出质量门禁设计和阶段状态机设计 -3. 实现代码 -4. 编写测试 -5. 运行测试,确保全量通过 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/04_phase_a_acceptance.md b/docs/reproduction/vibe-coding-reproduce-phase2/prompts/04_phase_a_acceptance.md deleted file mode 100644 index 136175c..0000000 --- a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/04_phase_a_acceptance.md +++ /dev/null @@ -1,104 +0,0 @@ -# Prompt 04: Phase A 集成验收 - -复制下面整段给 Codex 使用。 - -```text -Phase A(填平补齐)的三个 prompt 已经完成。本轮做集成验收,确保所有改动稳定、一致、可维护。 - -## 验收范围 - -1. 路由系统:sql_review / metadata_query / troubleshoot_sql / explain_result / build_report 各 pipeline 是否正常工作 -2. 角色升级:ProductAnalyst / SchemaArchitect / KnowledgeAgent 的决策能力 -3. 质量门禁:artifact 三级状态、阶段推进、blocked/warning 处理 -4. 回归验证:ask_sql 主链路不退化 - -## 验收清单 - -### 1. 路由系统验收 - -- [ ] EntryRouter 分类正确,所有 7 种 task_type 都能识别 -- [ ] ask_sql 行为与 Phase A 之前完全一致 -- [ ] sql_review 返回 review_report,不执行 SQL -- [ ] metadata_query 返回表结构和指标,不走 GenSQL -- [ ] troubleshoot_sql 能从问题提取 SQL 并修复 -- [ ] explain_result 返回详细解释报告 -- [ ] build_report 返回 degraded report artifact -- [ ] unknown 回退到 ask_sql 行为 -- [ ] 每种 pipeline 都有 state.json 和 delivery_report - -### 2. 角色升级验收 - -- [ ] ProductAnalystAgent 能检测至少 3 类模糊点 -- [ ] analysis_request 有 valid/warning/blocked 三级 -- [ ] blocked 状态会终止流程 -- [ ] warning 状态传递到最终结果 -- [ ] SchemaArchitectAgent 能推荐 Join Path 并评估风险 -- [ ] schema_plan 有表选择、Join 路径、字段建议、风险 -- [ ] KnowledgeAgent 对历史 SQL 排序和去重 -- [ ] 所有角色都有降级策略 - -### 3. 质量门禁验收 - -- [ ] 每个 artifact 都有 status 字段 -- [ ] analysis 阶段有门禁 -- [ ] schema 阶段有门禁 -- [ ] sql_candidate 阶段有门禁 -- [ ] execution 阶段有门禁 -- [ ] qa 阶段有门禁 -- [ ] TaskState 完整记录阶段推进 -- [ ] Artifact schema 校验 - -### 4. 回归验收 - -- [ ] 全量单元测试通过 -- [ ] ask_sql 输出结构不变(新增字段不算破坏) -- [ ] 所有入口(CLI/API/MCP/Gateway)都能正常工作 -- [ ] 性能没有明显退化(简单查询不增加额外 LLM 调用) -- [ ] 文档更新:README、架构文档、配置说明 - -## 要做的事 - -### 1. 编写集成验收测试 - -新建 tests/test_phasea_integration.py,包含: - -- 路由集成测试:每种 pipeline 至少 2 个用例 -- 角色升级测试:模糊点检测、Join Path 推荐、blocked/warning 处理 -- 质量门禁测试:各阶段门禁、阶段推进、artifact 校验 -- 端到端测试:从入口到输出的完整链路 - -### 2. 更新文档 - -- 更新 README.md:说明 Phase A 新增的能力 -- 更新 docs/agent_team_architecture.md:更新架构图和角色职责 -- 更新 docs/future_extensions.md:标记 Phase A 完成的项 - -### 3. 性能基线 - -简单度量(不用精确): -- 开启角色升级前后的简单查询耗时对比 -- artifact 写入的开销 -- 确认没有引入额外的 LLM 调用 - -### 4. Bug 修复和清理 - -- 修复验收中发现的问题 -- 清理冗余代码 -- 统一命名和代码风格 - -## 验收标准 - -1. 全量测试通过(至少 160+ 项,原 156 项 + 新增) -2. ask_sql 输出向后兼容 -3. 所有 pipeline 都能端到端跑通 -4. 文档与代码一致 -5. 没有新增 LLM 调用(Phase A 全是规则) -6. 代码整洁,没有明显的冗余或 TODO - -## 输出 - -1. 集成验收报告(测试结果、性能对比、问题清单) -2. 更新后的文档 -3. 修复后的代码 -4. Phase A 完成标记 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/05_conversation_memory.md b/docs/reproduction/vibe-coding-reproduce-phase2/prompts/05_conversation_memory.md deleted file mode 100644 index d685814..0000000 --- a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/05_conversation_memory.md +++ /dev/null @@ -1,152 +0,0 @@ -# Prompt 05: Conversation Memory——会话上下文与追问重写 - -复制下面整段给 Codex 使用。 - -```text -Phase A 已完成。现在进入 Phase B:增强自主性。 - -本轮目标:实现 Conversation Memory,支持自然的分析追问。 - -## 背景 - -当前 QueryForge 是单轮的:每个问题都是独立的,不知道上下文。真实的分析场景是追问式的: - -用户:"上个月各地区的销售额是多少?" -用户:"按产品类别再拆一下呢?" -用户:"只看华东区" - -第二个和第三个问题如果没有上下文,根本无法理解。 - -## 本轮要做的事 - -### 1. Session 模型 - -定义会话模型,保存结构化的上下文信息。 - -新增 queryforge/agent_team/schemas/session.py(或在现有 schemas 中扩展): - -```python -class SessionMemory(BaseModel): - session_id: str - created_at: str - updated_at: str - turn_count: int - last_question: str - last_sql: str - last_result_schema: list[str] # 列名,不保存数据行 - last_metrics: list[str] # 上轮用到的指标 - last_dimensions: list[str] # 上轮的分组维度 - last_filters: list[dict] # 上轮的过滤条件 - last_time_range: dict | None # 上轮的时间范围 - history: list[SessionTurn] # 最近 N 轮的摘要 -``` - -class SessionTurn(BaseModel): - turn_number: int - question: str - sql: str - metrics: list[str] - dimensions: list[str] - filters: list[dict] - result_schema: list[str] - status: str # success / failed - -存储位置:.queryforge/sessions/.json - -### 2. ProductAnalystAgent 扩展:追问重写 - -ProductAnalystAgent 增加追问识别和重写能力: - -检测追问模式(规则实现,不用 LLM): -- "按 X 再拆一下" → 在上轮基础上增加维度 X -- "只看 X" → 在上轮基础上增加过滤 X -- "按时间展开" → 在上轮基础上增加时间维度 -- "那个结果"、"刚才那个" → 指代上轮结果 -- "再加上 X" → 在上轮基础上增加指标 X -- "去掉 X" → 在上轮基础上移除维度/指标 X -- "TOP N" → 在上轮基础上增加排序和 LIMIT - -重写逻辑: -1. 检测是否为追问 -2. 如果是追问,基于上轮上下文和本轮增量,重写为独立问题 -3. 重写后的问题交给后续流程正常处理 -4. 在 analysis_request 中标记 `is_followup: true` 和 `rewritten_from: "..."` - -注意:追问重写是在 ProductAnalyst 阶段做的,不改变后续节点的逻辑。后续节点看到的是重写后的完整问题。 - -### 3. AgentOptions 增加 session_id - -- session_id: str | None = None -- 如果提供 session_id,加载对应会话 -- 如果不提供,创建新会话 -- 新增 reset_session: bool = False 选项 - -### 4. Orchestrator 集成 - -OrchestratorAgent 增加会话管理: -- run 方法增加 session_id 参数 -- 执行前:加载/创建会话 -- ProductAnalyst 阶段:传入会话上下文,做追问重写 -- 执行后:更新会话(保存本轮结果摘要) -- 最终输出中增加 session 信息 - -会话更新策略: -- 只保存最近 N 轮(默认 10 轮) -- 不保存完整结果行,只保存 schema 和摘要 -- 每轮的 SQL、指标、维度、过滤条件都保存 -- 失败的轮次也保存,但标记为 failed - -### 5. 入口集成 - -CLI: -- 新增 --session-id 参数 -- 新增 --new-session 参数(忽略旧会话) -- 新增 --reset-session 参数 - -API: -- AskRequest 增加 session_id 字段 -- 返回结果中包含 session_id - -MCP: -- ask_sql 工具增加 session_id 参数 - -Gateway: -- 每个 user_id + channel 组合自动维护一个 session - -### 6. 会话存储 - -新增 SessionStore(类似 StateStore 的设计): -- load(session_id) -> SessionMemory | None -- save(session_id, session) -> None -- create() -> str(生成新 session_id) -- reset(session_id) -> None - -存储格式:JSON 文件,原子写入。 - -## 限制 - -- 不用 LLM 做追问识别和重写,全部用规则实现 -- 不保存完整结果行,只保存 schema 和摘要 -- 会话有轮数上限(默认 10 轮),防止无限增长 -- 不破坏单轮模式:不传 session_id 时行为和以前完全一样 -- 不改变 WorkflowRunner 和节点内部逻辑 - -## 验收标准 - -1. 不传 session_id 时,行为和以前完全一样 -2. 传 session_id 时,追问能被正确识别和重写 -3. 至少支持 5 种追问模式:增加维度、增加过滤、增加指标、减少维度、修改排序 -4. 会话状态持久化,重启后仍可用 -5. 会话有轮数限制,不会无限增长 -6. 不保存结果行,保护数据隐私 -7. 新增测试覆盖:追问识别、重写正确性、会话持久化、轮数限制、重置 -8. ask_sql 全量测试通过 - -## 输出要求 - -1. 先读取现有代码,确认 ProductAnalystAgent 和 OrchestratorAgent 的当前实现 -2. 给出会话模型设计和追问重写规则 -3. 实现代码 -4. 编写测试 -5. 运行测试,确保全量通过 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/06_bounded_tool_loop.md b/docs/reproduction/vibe-coding-reproduce-phase2/prompts/06_bounded_tool_loop.md deleted file mode 100644 index 23f2dd7..0000000 --- a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/06_bounded_tool_loop.md +++ /dev/null @@ -1,176 +0,0 @@ -# Prompt 06: 有界 Tool Loop——观察-行动-再规划 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。Conversation Memory 已经实现。 - -本轮目标:实现有界 Tool Loop,让 Agent 可以主动观察 Schema 和数据,再生成 SQL。这是从"单轮生成"到"观察-行动循环"的关键一步。 - -## 背景 - -当前流程是:一次性生成 SQL → 执行 → 反射 → 修复。模型没有机会先了解数据再决定怎么查。 - -Tool Loop 让模型可以: -1. 先看有哪些表 -2. 深入了解某张表的字段 -3. 预览某个字段的枚举值 -4. 基于观察结果生成更准确的 SQL - -## 本轮要做的事 - -### 1. 定义工具集(Tool Set) - -只开放 4 个只读工具,严格控制范围: - -| 工具名 | 功能 | 参数 | 返回 | -|-------|------|------|------| -| `list_tables` | 列出所有表名 | 无 | 表名列表和简要描述 | -| `describe_table` | 查看表结构 | table_name | 字段列表、类型、主键、外键 | -| `preview_distinct_values` | 预览字段枚举值 | table_name, column_name, limit=20 | 去重后的值列表 | -| `execute_sql_preview` | 预览查询结果 | sql, limit=20 | 带 LIMIT 的查询结果 | - -安全约束: -- 所有工具都是只读的 -- `execute_sql_preview` 自动加 LIMIT,最多 100 行 -- 所有工具调用都经过 SQL 安全策略检查 -- 有轮数限制(默认 5 轮) -- 有总耗时限制(默认 30 秒) - -### 2. Tool Loop 节点 - -新增 ToolLoopNode(放在 queryforge/agent/node/tool_loop_node.py): - -职责: -- 调用 LLM,让模型选择工具和参数 -- 执行工具调用 -- 把观察结果反馈给模型 -- 循环直到模型说"我有足够信息了,可以生成 SQL 了" -- 或者达到轮数限制 - -输入:Context(包含 question、schema、history 等) -输出:更新后的 Context(包含 tool loop 的观察结果,以及可能更新的 sql_context) - -等等,Tool Loop 是在 GenSQL 之前还是之后? - -答案:**在 GenSQL 之前**,作为"信息收集"阶段。模型先通过工具收集信息,然后再生成 SQL。 - -但也可以设计为"生成 → 观察 → 修正"的循环。本轮先做"信息收集"模式,简单且安全。 - -### 3. LLM 工具调用协议 - -定义结构化的工具调用格式(用 JSON,不用 Function Calling): - -模型输出 JSON: -```json -{ - "thought": "我需要先了解订单表的结构", - "action": "describe_table", - "params": { - "table_name": "fact_watch_session" - } -} -``` - -或者: -```json -{ - "thought": "信息足够了,可以生成 SQL 了", - "action": "final_answer", - "params": { - "sql": "SELECT ...", - "explanation": "..." - } -} -``` - -为什么不用 Function Calling? -- 不是所有 Provider 都支持 Function Calling -- JSON 模式更通用,测试更简单 -- 后续可以再增加 Function Calling 支持 - -### 4. 预算控制 - -硬限制: -- 最大轮数:5 轮(可配置) -- 最大行数:预览结果最多 100 行 -- 最大耗时:30 秒(可配置) -- 工具白名单:只有上面 4 个工具 - -软限制: -- 如果模型反复调用同一个工具且没有新信息,提前终止 -- 如果模型调用 final_answer,直接退出循环 - -### 5. Agent Team 集成 - -Tool Loop 在 Agent Team 架构中的位置: - -``` -analysis lifecycle (ProductAnalyst, Knowledge, SchemaArchitect) - → Tool Loop (可选,信息收集) - → GenSqlNode - → candidate lifecycle (SQLDeveloper, Governance) - → execute_sql - → ... -``` - -放在 SchemaArchitect 之后、GenSQL 之前。由 SchemaArchitectAgent 判断是否需要 Tool Loop(或者由配置控制)。 - -配置项: -- `tool_loop_enabled: bool`,默认 false -- `tool_loop_max_rounds: int`,默认 5 -- `tool_loop_timeout_seconds: int`,默认 30 - -为什么默认关闭? -- 增加 LLM 调用次数,成本更高 -- 简单查询不需要 Tool Loop -- 避免性能退化 - -### 6. 观测和审计 - -每次 Tool Loop 都要记录: -- 每轮的 action 和 params -- 每轮的观察结果(截断后) -- 总轮数 -- 退出原因(final_answer / 轮数耗尽 / 超时 / 错误) - -记录到 Context 的 tool_loop_history 字段和 artifact 中。 - -### 7. 测试策略 - -测试 Tool Loop 需要 LLM 调用,所以用 mock LLM: -- 模拟模型选择 list_tables → describe_table → final_answer 的流程 -- 模拟模型超过最大轮数 -- 模拟模型调用不存在的工具 -- 模拟模型调用 final_answer 退出 - -## 限制 - -- 只开放 4 个只读工具 -- 严格的轮数、行数、时间限制 -- 所有工具调用都经过 SQL 安全策略检查 -- 默认关闭,需要显式开启 -- 不改变 GenSQL 之后的流程 -- execute_sql_preview 不是正式执行,正式执行仍走 ExecuteSqlNode - -## 验收标准 - -1. Tool Loop 可以正常工作:模型调用工具 → 观察 → 生成 SQL -2. 4 个工具都能正常调用 -3. 轮数限制生效:超过最大轮数后终止 -4. 行数限制生效:预览结果不超过限制 -5. 超时限制生效 -6. 工具调用都经过安全策略检查 -7. 默认关闭时,行为和以前完全一样 -8. 开启后,最终 SQL 仍然经过 Governance 和 ExecuteSqlNode 的双重校验 -9. 有完整的工具调用历史记录 -10. 新增测试覆盖:正常流程、超轮数、超行数、超时、非法工具、安全策略拦截 - -## 输出要求 - -1. 先读取现有代码,确认节点结构和 LLM 调用方式 -2. 给出 Tool Loop 设计和工具协议 -3. 实现代码 -4. 编写测试 -5. 运行测试,确保全量通过 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/07_structured_reasoning_node.md b/docs/reproduction/vibe-coding-reproduce-phase2/prompts/07_structured_reasoning_node.md deleted file mode 100644 index be87e07..0000000 --- a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/07_structured_reasoning_node.md +++ /dev/null @@ -1,156 +0,0 @@ -# Prompt 07: Structured Reasoning Node——可审计决策摘要 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。Tool Loop 已经实现。 - -本轮目标:实现 Structured Reasoning Node,把 SQL 生成的决策过程结构化、可审计、可校验。 - -## 背景 - -当前 SQL 生成是"黑盒"的:模型生成一段 SQL 和一段自然语言解释,但我们不知道模型是怎么想的——选了哪些表、为什么选这些 Join、用了什么指标、做了什么假设。 - -Structured Reasoning Node 让模型输出结构化的决策摘要,而不是自由文本解释。这样可以: -1. 审计:知道模型是怎么决策的 -2. 校验:检查决策和最终 SQL 是否一致 -3. 复用:决策摘要可以被其他节点(Reflect、Fix、Plan)复用 - -## 本轮要做的事 - -### 1. 定义 ReasoningResult 模型 - -在 queryforge/schemas/models.py 中新增: - -```python -class ReasoningResult(BaseModel): - goal: str # 分析目标 - grain: str # 分析粒度 - tables: list[str] # 选择的表 - joins: list[ReasoningJoin] # Join 决策 - metrics: list[ReasoningMetric] # 指标 - dimensions: list[str] # 维度/分组字段 - filters: list[ReasoningFilter] # 过滤条件 - time_range: str | None # 时间范围 - sorting: list[ReasoningSort] # 排序 - limit: int | None # 条数限制 - assumptions: list[str] # 做出的假设 - risks: list[str] # 识别到的风险 - confidence: float # 置信度 0-1 - strategy: str # 生成策略(直接生成 / 参考历史 / 参考指标) -``` - -class ReasoningJoin(BaseModel): - left_table: str - right_table: str - join_type: str # inner / left / right / full - left_key: str - right_key: str - reason: str - -class ReasoningMetric(BaseModel): - name: str - expression: str - alias: str - source: str # metric_model / ad_hoc - -class ReasoningFilter(BaseModel): - column: str - operator: str - value: str - logic: str # AND / OR - -class ReasoningSort(BaseModel): - column: str - direction: str # ASC / DESC - -### 2. GenSqlNode 改造:先生成 reasoning,再生成 SQL - -GenSqlNode 的流程从: -``` -Prompt → SQL + explanation -``` -改成: -``` -Prompt → ReasoningResult → SQL + explanation -``` - -两步走: -1. 让模型先输出结构化的推理摘要 -2. 基于推理摘要生成 SQL - -或者一步到位:让模型同时输出 reasoning 和 SQL。 - -建议:**一步到位**,因为两步会增加一次 LLM 调用,成本翻倍。可以让模型在一次 JSON 输出中同时包含 reasoning 和 sql。 - -GenSqlNode 的输出增加 `reasoning_result` 字段,存在 Context 中。 - -### 3. 校验:Reasoning vs SQL - -生成 SQL 后,用规则校验 reasoning 和 SQL 是否一致: - -检查项: -- SQL 中用到的表是否都在 reasoning.tables 中 -- SQL 中的 JOIN 是否和 reasoning.joins 一致 -- SQL 中的 GROUP BY 是否和 reasoning.dimensions 一致 -- SQL 中的 WHERE 是否和 reasoning.filters 匹配 -- SQL 中的 ORDER BY 是否和 reasoning.sorting 匹配 - -校验不通过怎么办? -- 记 warning,不阻塞 -- 在 reflect 阶段可以用这个作为反思的输入 -- 未来可以作为 Fix 的依据 - -### 4. Plan Mode 集成 - -Plan Mode 现在展示的是 SQL 和风险。可以增强为: -- 展示结构化推理摘要 -- 展示决策依据和假设 -- 让用户更容易判断要不要批准 - -### 5. ReflectNode 集成 - -ReflectNode 现在用自然语言评估 SQL 质量。可以把 reasoning_result 作为输入,让评估更有依据: -- 检查 reasoning 中的假设是否成立 -- 检查风险点是否被正确处理 -- 检查指标口径是否正确 - -### 6. Artifact 集成 - -SQLDeveloperAgent 的 sql_candidate artifact 中增加 reasoning 字段。 - -### 7. 输出集成 - -最终输出中增加 `reasoning` 字段(可选,默认关闭?)。 - -考虑到 token 和隐私问题,默认输出 reasoning 但只包含结构化字段,不包含模型的完整思考过程。 - -## 限制 - -- 不改变 SQL 生成的核心逻辑,只是增加结构化输出 -- 校验是 warning 级别,不阻塞 -- 不引入额外的 LLM 调用(在一次生成中同时输出 reasoning 和 SQL) -- 向后兼容:如果模型没有输出 reasoning 字段,用空值填充 -- 不改变 WorkflowRunner 的整体流程 - -## 验收标准 - -1. GenSqlNode 输出 ReasoningResult 结构化摘要 -2. ReasoningResult 包含 goal、tables、joins、metrics、dimensions、filters、assumptions、risks 等字段 -3. 有规则校验 reasoning 和 SQL 的一致性 -4. 校验不一致时记录 warning,不阻塞 -5. Plan Mode 展示推理摘要 -6. ReflectNode 可以利用推理摘要 -7. 最终输出中包含 reasoning 字段 -8. 向后兼容:没有 reasoning 时不报错 -9. 不增加额外的 LLM 调用次数 -10. 新增测试覆盖:reasoning 生成、一致性校验、缺失兼容 - -## 输出要求 - -1. 先读取现有代码,确认 GenSqlNode 和 ReflectNode 的实现 -2. 给出 ReasoningResult 模型设计和集成方案 -3. 实现代码 -4. 编写测试 -5. 运行测试,确保全量通过 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/08_parallel_candidates_selection.md b/docs/reproduction/vibe-coding-reproduce-phase2/prompts/08_parallel_candidates_selection.md deleted file mode 100644 index 33dbc42..0000000 --- a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/08_parallel_candidates_selection.md +++ /dev/null @@ -1,156 +0,0 @@ -# Prompt 08: Parallel + Selection——多候选生成与选择 - -复制下面整段给 Codex 使用。 - -```text -Phase B 已完成。现在进入 Phase C:质量提升。 - -本轮目标:实现多候选 SQL 生成与选择机制,通过多生成 + 多维度评分来提升准确率。 - -## 背景 - -当前 SQL 生成是单轮的:生成一个 SQL,执行,反射,修复。 - -Parallel + Selection 的思路是: -1. 一次生成 2-3 个 SQL 候选 -2. 用规则和执行信号对每个候选评分 -3. 选择最优的那个作为最终结果 - -这是一种"用算力换质量"的策略,适用于复杂查询或准确率要求高的场景。 - -## 本轮要做的事 - -### 1. 多候选生成 - -在 SQLDeveloper 阶段生成多个 SQL 候选。 - -生成策略: -- 候选 A:基于 Schema 和问题的直接生成(当前方式) -- 候选 B:参考历史 SQL 的生成 -- 候选 C:基于语义模型指标的生成 - -或者更简单:让模型生成 N 个不同的 SQL,每个都有不同的推理路径。 - -建议:**让模型一次生成 N 个候选**,但要控制数量,避免成本过高。默认 2 个,最多 3 个。 - -候选数量配置: -- `parallel_candidates: int`,默认 1(即关闭并行) -- 可配置为 2 或 3 - -为什么默认 1? -- 成本:多生成一个 SQL 多花一次 LLM 调用 -- 大多数简单查询不需要并行 -- 复杂查询可以手动开启 - -### 2. 选择器(Selector) - -新增 SQLSelector 类(放在 queryforge/agent/sql_selector.py): - -职责: -- 对每个候选评分 -- 选择最优的 -- 输出选择理由 - -评分维度(按权重从高到低): - -| 维度 | 权重 | 说明 | -|-----|------|------| -| AST 校验通过 | 基础项 | 不通过直接淘汰 | -| Governance 验证通过 | 基础项 | 不通过直接淘汰 | -| 语义模型口径匹配 | 高 | 指标/维度是否和语义模型一致 | -| 执行成功 | 高 | 是否能正常执行 | -| 结果非空 | 中 | 是否返回了数据 | -| 结果行数合理 | 中 | 行数在合理范围内 | -| Reflect 评分 | 中低 | ReflectNode 的评估结果 | -| 历史相似度 | 低 | 和历史成功 SQL 的相似程度 | -| 复杂度合理性 | 低 | 复杂度是否和问题匹配 | - -评分算法:加权求和,基础项不通过直接淘汰。 - -### 3. 执行预览验证 - -对每个候选做带 LIMIT 的预览执行(比如 LIMIT 20),验证: -- SQL 是否能正常执行 -- 返回的列是否合理 -- 行数是否在合理范围内 - -注意:只做预览,不做正式执行。正式执行还是在 ExecuteSqlNode 中。 - -预览执行也有预算控制: -- 最多预览 N 个候选(默认 2 个) -- 每个预览最多 M 行(默认 20 行) -- 预览总时间不超过 T 秒(默认 10 秒) - -### 4. Agent Team 集成 - -在 Agent Team 架构中,Parallel + Selection 的位置: - -``` -analysis lifecycle - → [Tool Loop 可选] - → SQLDeveloperAgent 生成多候选 - → GovernanceAgent 逐个验证 - → SQLSelector 选择最优 - → 执行最优 SQL - → completion lifecycle -``` - -SQLDeveloperAgent 负责生成多候选,SQLSelector 是一个新的角色或工具。 - -建议:把 SQLSelector 作为 SQLDeveloperAgent 的一部分,而不是独立角色。因为选择和生成是紧密相关的。 - -### 5. 候选选择过程可追溯 - -把每个候选的评分和选择理由都记录下来: -- 保存到 sql_candidate artifact -- 保存到 Context -- ReflectNode 可以参考这些信息 - -### 6. 配置项 - -新增配置: -- `parallel_candidates: int = 1`(候选数量,1 表示关闭) -- `parallel_max_preview: int = 2`(最多预览多少个) -- `selector_weights: dict`(各维度权重) -- `parallel_auto_trigger_complexity: int`(复杂度超过多少自动开启并行,可选) - -### 7. 测试策略 - -测试 SQLSelector 不需要 LLM,用 mock SQL 候选测试评分逻辑: -- 基础项淘汰测试 -- 各维度评分测试 -- 选择最优测试 -- 平局处理测试 - -端到端测试需要 LLM,用 mock 模拟。 - -## 限制 - -- 默认关闭(parallel_candidates=1),不影响现有行为 -- 候选数量限制为最多 3 个 -- 预览执行有严格的行数和时间限制 -- 正式执行仍然走 ExecuteSqlNode,不绕过任何安全检查 -- 选择器的评分是启发式的,不保证最优 -- 不引入新的 LLM Provider 依赖 - -## 验收标准 - -1. parallel_candidates=1 时,行为和以前完全一样 -2. parallel_candidates=2 时,生成 2 个候选并选择最优 -3. 选择器能正确淘汰 AST 校验不通过的候选 -4. 选择器能正确淘汰 Governance 拒绝的候选 -5. 执行成功的候选得分高于执行失败的 -6. 语义模型匹配度高的候选得分更高 -7. 选择过程可追溯,有完整的评分记录 -8. 预览执行有行数和时间限制 -9. 新增测试覆盖:选择器评分、候选淘汰、平局处理、预览限制 -10. ask_sql 全量测试通过 - -## 输出要求 - -1. 先读取现有代码,确认 GenSqlNode 和 SQLDeveloperAgent 的实现 -2. 给出多候选生成和选择器设计 -3. 实现代码 -4. 编写测试 -5. 运行测试,确保全量通过 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/09_subject_tree_scoped_context.md b/docs/reproduction/vibe-coding-reproduce-phase2/prompts/09_subject_tree_scoped_context.md deleted file mode 100644 index cf15820..0000000 --- a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/09_subject_tree_scoped_context.md +++ /dev/null @@ -1,179 +0,0 @@ -# Prompt 09: Subject Tree——主题范围约束与 Context 裁剪 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。Parallel + Selection 已经实现。 - -本轮目标:实现 Subject Tree(主题树),对查询进行范围约束,减少 token 消耗,降低跨域误用风险。 - -## 背景 - -当前 QueryForge 把所有 Schema 都塞进 Prompt 里。数据库表少的时候还好,表多了之后: -1. Token 消耗大 -2. 模型容易混淆不同业务域的表 -3. 跨域误用(比如把销售表和人力表乱 Join) - -Subject Tree 通过定义"主题"来约束查询范围:每个主题包含一组相关的表、指标、Skills 和知识源。查询时先选主题,再在主题范围内工作。 - -## 本轮要做的事 - -### 1. Subject 定义 - -新增 Subject 模型(放在 queryforge/semantic/subject.py 或 queryforge/agent_team/schemas/): - -```python -class Subject(BaseModel): - id: str # 主题 ID - name: str # 显示名称 - description: str # 描述 - synonyms: list[str] = [] # 同义词 - tables: list[str] = [] # 包含的表 - entities: list[str] = [] # 包含的语义模型实体 - metrics: list[str] = [] # 包含的指标 - skills: list[str] = [] # 相关的 Skills - knowledge_sources: list[str] = [] # 相关的知识源(reference_sql、documents 等) - default_time_field: str | None = None # 默认时间字段 - default_grain: str | None = None # 默认粒度 - priority: int = 0 # 优先级(用于歧义时选择) -``` - -### 2. Subject Tree 定义 - -```python -class SubjectTree(BaseModel): - version: str = "1.0" - subjects: list[Subject] - default_subject: str | None = None -``` - -### 3. 配置文件 - -Subject 用 YAML 文件定义,放在语义模型目录下或单独的 subject 目录: - -```yaml -# subjects.yml -version: "1.0" -default_subject: sales -subjects: - - id: sales - name: 销售分析 - description: 订单、客户、产品销售数据分析 - synonyms: ["销售额", "订单", "营收"] - tables: ["fact_watch_session", "dim_user", "dim_anime", "dim_date"] - entities: ["订单", "客户", "产品", "日期"] - metrics: ["销售额", "订单量", "客单价"] - skills: ["sales_best_practices"] - knowledge_sources: ["sales_reference_sql"] - - - id: inventory - name: 库存分析 - description: 库存、仓储、供应链分析 - synonyms: ["库存", "仓库", "存货"] - tables: ["fact_inventory", "dim_anime", "dim_warehouse"] - entities: ["库存", "产品", "仓库"] - metrics: ["库存量", "库存周转"] - skills: ["inventory_best_practices"] -``` - -### 4. Subject 选择 - -在 ProductAnalyst 阶段(或 SchemaArchitect 之前)自动选择主题。 - -选择策略(规则实现,不用 LLM): -1. 关键词匹配:问题中的关键词和主题的 name/synonyms 匹配 -2. 指标/维度匹配:问题中提到的指标属于哪个主题 -3. 默认主题:如果都不匹配,使用 default_subject -4. 无默认主题:使用全部 Schema(降级) - -选择结果存到 Context 和 artifact 中。 - -### 5. Context 裁剪 - -选择主题后,对 Context 中的 Schema 信息进行裁剪: -- 只保留主题内的表 -- 只保留主题内的语义模型实体和指标 -- 只加载主题相关的 Skills -- 只检索主题相关的历史 SQL 和知识库 - -裁剪发生在 SchemaLinkingNode 之前还是之后? - -建议:**在 SchemaLinkingNode 之前选择主题,SchemaLinkingNode 只加载主题内的表**。这样可以减少 Schema 加载和 token 消耗。 - -但要注意:如果主题选择错了,后续就找不到正确的表了。所以需要有 fallback 机制: -- 如果在主题内找不到相关表,自动扩大到全部 Schema -- 或者在 Reflect 阶段检测到"表不存在"时,自动切换主题重试 - -### 6. 主题切换与重试 - -ReflectNode 检测到以下情况时,可以触发主题切换重试: -- 引用了不存在的表 -- 表之间无法 Join(可能选错了主题) -- 结果完全不符合预期 - -切换策略: -- 第一次失败后,尝试第二匹配的主题 -- 如果都失败了,使用全部 Schema -- 最多切换 1-2 次主题,避免无限循环 - -### 7. Agent Team 集成 - -在 Agent Team 架构中,Subject Tree 的位置: - -``` -EntryRouter - → ProductAnalystAgent(识别主题关键词) - → SubjectSelector(选择主题,新增角色/阶段) - → SchemaArchitectAgent(在主题范围内规划) - → KnowledgeAgent(只检索主题相关知识) - → GenSqlNode(只看到主题内的 Schema) - → execution - → Reflect(检测是否需要切换主题) - → completion -``` - -SubjectSelector 可以作为 SchemaArchitectAgent 的一部分,也可以独立。建议独立,职责更清晰。 - -### 8. 配置和入口 - -配置项: -- `subject_tree_enabled: bool`,默认 false(数据库表少的时候不需要) -- `subject_tree_path: str`,subjects.yml 的路径 -- `default_subject: str`,默认主题 - -CLI: -- 新增 --subject 参数,手动指定主题 -- 新增 --list-subjects 参数,列出所有主题 - -API: -- AskRequest 增加 subject 字段 - -## 限制 - -- 默认关闭,不影响现有行为 -- 主题选择是启发式的,可能选错 -- 选错时有 fallback 机制(扩大范围重试) -- 不改变 SQL 生成和执行逻辑 -- 不引入 LLM 调用(主题选择用规则实现) - -## 验收标准 - -1. subject_tree_enabled=false 时,行为和以前完全一样 -2. 可以用 YAML 定义多个主题 -3. 主题选择能正确匹配关键词和指标 -4. Schema 裁剪生效:只加载主题内的表 -5. Skills 加载生效:只加载主题相关的 Skills -6. 历史 SQL 检索生效:只检索主题相关的历史 -7. 选错主题时有 fallback 机制 -8. 可以手动指定主题 -9. 新增测试覆盖:主题选择、Schema 裁剪、fallback 重试、手动指定 -10. ask_sql 全量测试通过 - -## 输出要求 - -1. 先读取现有代码,确认 SchemaLinkingNode 和 ProductAnalystAgent 的实现 -2. 给出 Subject Tree 设计和集成方案 -3. 实现代码 -4. 编写测试 -5. 运行测试,确保全量通过 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/10_phase_bc_acceptance.md b/docs/reproduction/vibe-coding-reproduce-phase2/prompts/10_phase_bc_acceptance.md deleted file mode 100644 index 009ef5b..0000000 --- a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/10_phase_bc_acceptance.md +++ /dev/null @@ -1,140 +0,0 @@ -# Prompt 10: Phase B+C 集成验收 - -复制下面整段给 Codex 使用。 - -```text -Phase B(增强自主性)和 Phase C(质量提升)的 prompts 已经完成。本轮做集成验收。 - -## 验收范围 - -1. Conversation Memory:会话上下文与追问重写 -2. Bounded Tool Loop:有界工具循环 -3. Structured Reasoning:结构化推理摘要 -4. Parallel + Selection:多候选生成与选择 -5. Subject Tree:主题范围约束 -6. 回归验证:ask_sql 主链路不退化 - -## 验收清单 - -### 1. Conversation Memory 验收 - -- [ ] 不传 session_id 时行为不变 -- [ ] 传 session_id 时,追问能正确识别和重写 -- [ ] 支持至少 5 种追问模式:增加维度、增加过滤、增加指标、减少维度、修改排序 -- [ ] 会话状态持久化 -- [ ] 会话有轮数限制 -- [ ] 不保存结果行 -- [ ] CLI/API/MCP 都支持 session_id - -### 2. Tool Loop 验收 - -- [ ] 默认关闭时行为不变 -- [ ] 开启后能正常调用 list_tables / describe_table / preview_distinct_values / execute_sql_preview -- [ ] 轮数限制生效 -- [ ] 行数限制生效 -- [ ] 超时限制生效 -- [ ] 工具调用都经过安全策略检查 -- [ ] final_answer 能正确退出循环 -- [ ] 有完整的调用历史记录 - -### 3. Structured Reasoning 验收 - -- [ ] GenSqlNode 输出 ReasoningResult 结构化摘要 -- [ ] ReasoningResult 包含完整字段 -- [ ] 有 reasoning 和 SQL 的一致性校验 -- [ ] 校验不一致时记录 warning,不阻塞 -- [ ] Plan Mode 展示推理摘要 -- [ ] ReflectNode 能利用推理摘要 -- [ ] 最终输出包含 reasoning 字段 -- [ ] 向后兼容:没有 reasoning 时不报错 -- [ ] 不增加额外的 LLM 调用 - -### 4. Parallel + Selection 验收 - -- [ ] parallel_candidates=1 时行为不变 -- [ ] 能生成多个候选 -- [ ] 选择器能正确评分和选择 -- [ ] AST 校验不通过的候选被淘汰 -- [ ] Governance 拒绝的候选被淘汰 -- [ ] 执行成功的候选得分更高 -- [ ] 语义匹配度高的候选得分更高 -- [ ] 选择过程可追溯 -- [ ] 预览执行有行数和时间限制 - -### 5. Subject Tree 验收 - -- [ ] 默认关闭时行为不变 -- [ ] 能用 YAML 定义多个主题 -- [ ] 主题选择正确 -- [ ] Schema 裁剪生效 -- [ ] Skills 加载生效 -- [ ] 历史 SQL 检索生效 -- [ ] 选错主题时有 fallback 机制 -- [ ] 可以手动指定主题 - -### 6. 回归验收 - -- [ ] 全量单元测试通过(180+ 项) -- [ ] ask_sql 输出向后兼容 -- [ ] 所有入口(CLI/API/MCP/Gateway)都能正常工作 -- [ ] 默认配置下性能没有明显退化 -- [ ] 文档更新 - -## 要做的事 - -### 1. 编写集成验收测试 - -新建 tests/test_phasebc_integration.py,包含: -- 会话上下文端到端测试 -- Tool Loop 端到端测试 -- 结构化推理测试 -- 多候选选择测试 -- 主题树端到端测试 -- 组合场景测试(比如会话 + Tool Loop + 多候选) - -### 2. 更新文档 - -- 更新 README.md -- 更新 docs/agent_team_architecture.md -- 更新 docs/future_extensions.md,标记已完成项 -- 新增 docs/subject_tree.md - -### 3. 性能测试 - -度量(简单对比): -- 默认配置 vs 关闭所有高级功能的耗时 -- Tool Loop 开启后的额外耗时 -- 多候选开启后的额外耗时 -- 确保默认配置下性能不退化 - -### 4. 配置默认值确认 - -确认所有高级功能的默认值都是"关闭"或"最小化": -- conversation_memory: 不传 session_id 就不启用 -- tool_loop: 默认关闭 -- parallel_candidates: 默认 1 -- subject_tree: 默认关闭 -- structured_reasoning: 总是输出但不影响流程 - -### 5. Bug 修复和清理 - -- 修复验收中发现的问题 -- 清理冗余代码 -- 统一命名和代码风格 - -## 验收标准 - -1. 全量测试通过(至少 180+ 项) -2. ask_sql 输出向后兼容 -3. 默认配置下性能不退化 -4. 所有高级功能都能正常开启和关闭 -5. 文档与代码一致 -6. 代码整洁,没有明显的冗余 - -## 输出 - -1. 集成验收报告 -2. 更新后的文档 -3. 修复后的代码 -4. Phase B+C 完成标记 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/11_streaming_output.md b/docs/reproduction/vibe-coding-reproduce-phase2/prompts/11_streaming_output.md deleted file mode 100644 index 730ccaa..0000000 --- a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/11_streaming_output.md +++ /dev/null @@ -1,168 +0,0 @@ -# Prompt 11: Streaming Output——节点级事件流 - -复制下面整段给 Codex 使用。 - -```text -Phase B+C 已完成。现在进入 Phase D:形态扩展。 - -本轮目标:实现 Streaming Output,让用户实时看到进度,而不是等完整结果。 - -## 背景 - -当前 QueryForge 是同步阻塞的:发出请求后,等所有步骤完成才返回结果。Tool Loop、多候选这些能力会让等待时间变长,用户不知道进度。 - -Streaming Output 让每个节点/阶段的完成都立即推送一个事件,用户可以实时看到: -- 正在分析问题... -- 正在检索 Schema... -- 正在生成 SQL... -- 正在执行 SQL... -- 正在反思修正... -- 完成! - -## 本轮要做的事 - -### 1. 事件协议(Event Protocol) - -定义统一的事件格式: - -```python -class WorkflowEvent(BaseModel): - event_id: str - event_type: str # node_started / node_completed / node_failed / phase_started / phase_completed / artifact_created / final_result - timestamp: str - run_id: str - node_name: str | None = None - phase_name: str | None = None - artifact_type: str | None = None - status: str | None = None # success / failed / skipped / warning - message: str | None = None - data: dict | None = None # 额外数据(不包含结果正文,避免泄露) -``` - -事件类型: -- `node_started`: 节点开始执行 -- `node_completed`: 节点执行完成 -- `node_failed`: 节点执行失败 -- `phase_started`: 阶段开始(Agent Team 的阶段) -- `phase_completed`: 阶段完成 -- `artifact_created`: 新 artifact 生成 -- `retrying`: 重试(反射修复、重新生成) -- `final_result`: 最终结果 - -### 2. EventBus / EventEmitter - -新增 EventEmitter 类(放在 queryforge/agent/event_emitter.py): - -职责: -- 收集事件 -- 推送给订阅者 -- 支持多种输出方式(callback、SSE、队列) - -接口: -```python -class EventEmitter: - def emit(self, event: WorkflowEvent) -> None: ... - def on_event(self, callback: Callable[[WorkflowEvent], None]) -> None: ... - def get_events(self) -> list[WorkflowEvent]: ... -``` - -### 3. Workflow Runner 集成 - -在 ReflectiveWorkflow 和 WorkflowRunner 中埋点: -- 每个节点开始前 emit node_started -- 每个节点完成后 emit node_completed -- 节点失败时 emit node_failed -- 重试时 emit retrying -- 最终结果时 emit final_result - -事件流由 EventEmitter 管理,通过 Context 传递。 - -### 4. Agent Team 集成 - -在 OrchestratorAgent 中埋点: -- 每个阶段开始时 emit phase_started -- 每个阶段完成时 emit phase_completed -- 每个 artifact 生成时 emit artifact_created -- blocked 时 emit node_failed - -### 5. API SSE 支持 - -FastAPI 增加 SSE 端点: -- `POST /ask/stream`:流式返回事件 -- 使用 Server-Sent Events 协议 -- 每个事件是一条 JSON - -或者:在现有 `/ask` 端点中增加 `Accept: text/event-stream` 头的支持。 - -建议:新增独立的 `/ask/stream` 端点,逻辑更清晰。 - -### 6. CLI 进度显示 - -CLI 增加 `--stream` 参数: -- 开启后,在 stderr 显示进度 -- 最终结果仍然在 stdout 输出(JSON 格式,便于管道处理) -- 进度显示用简单的文本或 emoji - -示例: -``` -🔍 分析问题... -📊 检索 Schema... -🧠 生成 SQL... -✅ SQL 生成完成 -⚙️ 执行 SQL... -🔄 第 1 次修复... -✅ 执行完成 -📈 生成可视化... -🎉 完成! -``` - -### 7. MCP 支持 - -MCP 工具增加流式支持: -- ask_sql_stream 工具 -- 或者在 ask_sql 结果中包含事件历史 - -MCP 的流式支持比较复杂,本轮可以先做"返回事件历史"的方式,后续再做真正的流式。 - -### 8. 配置 - -配置项: -- `streaming_enabled: bool`,默认 true(不影响 API,只是支持) -- `streaming_event_buffer_size: int`,默认 100 - -### 9. 测试策略 - -- 测试 EventEmitter 的事件收集 -- 测试 Workflow Runner 的事件埋点 -- 测试 API SSE 端点(用 TestClient) -- 测试 CLI 的 --stream 参数 - -## 限制 - -- 流式输出不改变业务逻辑 -- 最终 JSON 结果保持不变 -- 不流式传输结果数据(只传进度事件,不传行数据),避免数据安全问题 -- 不增加 LLM token 流式输出(那个是 Provider 层面的,不是工作流层面的) -- 向后兼容:不开启 streaming 时行为不变 - -## 验收标准 - -1. EventEmitter 能正确收集和分发事件 -2. Workflow Runner 的每个节点都有开始/完成事件 -3. Agent Team 的每个阶段都有开始/完成事件 -4. 重试事件正确触发 -5. API SSE 端点能正常工作 -6. CLI --stream 参数能显示进度 -7. 最终结果和非流式完全一致 -8. 不流式传输敏感数据 -9. 新增测试覆盖:事件收集、SSE 端点、CLI 进度 -10. ask_sql 全量测试通过 - -## 输出要求 - -1. 先读取现有代码,确认 Workflow Runner 和 API 的实现 -2. 给出事件协议和 EventEmitter 设计 -3. 实现代码 -4. 编写测试 -5. 运行测试,确保全量通过 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/12_report_artifact.md b/docs/reproduction/vibe-coding-reproduce-phase2/prompts/12_report_artifact.md deleted file mode 100644 index 5b5bc08..0000000 --- a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/12_report_artifact.md +++ /dev/null @@ -1,179 +0,0 @@ -# Prompt 12: Report Artifact——静态 HTML 分析报告 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。Streaming Output 已经实现。 - -本轮目标:实现 Report Artifact,从单张图升级为完整的静态 HTML 分析报告。 - -## 背景 - -当前 VisualizationAgent 只能生成一张 Vega-Lite 图表配置。对于复杂的分析任务,用户需要的是一份完整的报告: -- 问题和分析目标 -- SQL 和口径说明 -- 结果表格 -- 多张图表(趋势、对比、分布等) -- 关键发现 - -Report Artifact 把这些整合为一份静态 HTML 报告,可以直接在浏览器打开,也可以分享给别人。 - -## 本轮要做的事 - -### 1. Report 模型 - -新增 Report 模型(放在 queryforge/agent_team/schemas/report.py): - -```python -class ReportArtifact(BaseModel): - artifact_type: str = "report" - title: str - summary: str - sections: list[ReportSection] - generated_at: str - data_source: str - sql: str - metrics: list[str] - dimensions: list[str] - key_findings: list[str] - file_path: str # HTML 文件路径 -``` - -class ReportSection(BaseModel): - id: str - title: str - type: str # text / table / chart / metrics - content: dict # 根据 type 有不同结构 - -### 2. ReportGenerator - -新增 ReportGenerator 类(放在 queryforge/agent/report_generator.py): - -职责: -- 根据查询结果生成 HTML 报告 -- 支持多种 section 类型 -- 输出自包含的静态 HTML(CSS 内联) - -Section 类型: -- `text`: 文本段落 -- `table`: 数据表格 -- `chart`: Vega-Lite 图表(用 vega-embed 渲染) -- `metrics`: 指标卡片 -- `sql`: SQL 代码块(可折叠) - -### 3. 报告内容结构 - -一份标准报告包含: - -1. **Header**: 标题、生成时间、数据源 -2. **Summary**: 一句话总结 + 关键指标卡片 -3. **Result Table**: 结果表格(最多展示 50 行,超过的话提示下载) -4. **Charts**: 自动生成 1-3 张图表(根据数据特征选择) -5. **SQL & Methodology**: SQL 代码 + 口径说明 + 假设 -6. **Key Findings**: 3-5 条关键发现(基于结果和反射) -7. **Footer**: 生成工具、版本、免责声明 - -### 4. 图表自动选择 - -根据结果 schema 和数据特征自动选择图表类型: - -| 数据特征 | 推荐图表 | -|---------|---------| -| 1 个时间维度 + 1 个度量 | 折线图 | -| 1 个类别维度 + 1 个度量 | 柱状图 | -| 2 个类别维度 + 1 个度量 | 分组柱状图 | -| 1 个类别维度 + 多个度量 | 分组柱状图或折线图 | -| 只有度量,没有维度 | 指标卡片 | -| 占比数据 | 饼图(慎用) | -| 2 个度量 + 类别 | 散点图 | - -图表选择逻辑用规则实现,不用 LLM。 - -### 5. 关键发现生成 - -基于结果数据自动生成 3-5 条关键发现: - -发现类型: -- 最大值/最小值 -- 增长率/下降率 -- Top N -- 异常值(突增突降) -- 分布特征 - -用规则实现,不用 LLM(或者用 LLM 但作为可选增强)。 - -### 6. Agent Team 集成 - -Report 是 completion 阶段的一部分,在 DataQA 和 Visualization 之后: - -``` -execution - → DataQA - → Visualization - → ReportGenerator(新增) - → Ops - → Delivery -``` - -ReportAgent(新增角色)负责: -- 判断是否需要生成报告 -- 选择图表类型 -- 生成关键发现 -- 生成 HTML 文件 -- 返回 report artifact - -触发条件: -- task_type 是 build_report -- 或者用户问题中提到"报告"、"report" -- 或者结果行数超过阈值且有多个维度 - -### 7. 输出和下载 - -报告保存位置: -- `.queryforge/reports/.html` - -CLI: -- 新增 --report 参数,强制生成报告 -- 生成后输出报告路径 - -API: -- 新增 `GET /report/{run_id}` 端点,下载 HTML 报告 -- 或者在结果中包含 report_url - -### 8. 配置 - -配置项: -- `report_enabled: bool`,默认 true(支持但不强制) -- `report_max_rows: int`,默认 50(表格展示行数) -- `report_max_charts: int`,默认 3 -- `report_output_dir: str`,默认 `.queryforge/reports` - -## 限制 - -- 报告是静态 HTML,不依赖后端 -- 图表用 Vega-Lite + vega-embed CDN,不需要额外安装 -- 不做交互式报告(过滤、钻取等),那是 BI 工具的事 -- 不改变 SQL 生成和执行逻辑 -- 报告生成不阻塞主流程(失败了就跳过,标记 degraded) - -## 验收标准 - -1. 能生成自包含的 HTML 报告 -2. 报告包含:标题、摘要、表格、图表、SQL、关键发现 -3. 能根据数据特征自动选择图表类型 -4. 至少支持 3 种图表类型:折线图、柱状图、指标卡片 -5. 关键发现用规则生成,至少 3 种类型 -6. 报告不依赖后端,可以直接在浏览器打开 -7. 报告生成失败不阻塞主流程 -8. CLI 和 API 都能生成和获取报告 -9. 新增测试覆盖:报告生成、图表选择、关键发现、HTML 渲染 -10. ask_sql 全量测试通过 - -## 输出要求 - -1. 先读取现有代码,确认 VisualizationAgent 和 OutputNode 的实现 -2. 给出 Report 模型和生成器设计 -3. 实现代码 -4. 编写测试 -5. 运行测试,确保全量通过 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/13_mcp_enhanced.md b/docs/reproduction/vibe-coding-reproduce-phase2/prompts/13_mcp_enhanced.md deleted file mode 100644 index 4e6be44..0000000 --- a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/13_mcp_enhanced.md +++ /dev/null @@ -1,131 +0,0 @@ -# Prompt 13: MCP 增强——resources / prompts / sessions - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。Report Artifact 已经实现。 - -本轮目标:增强 MCP(Model Context Protocol)支持,从"只有 ask_sql 工具"升级为完整的 MCP server。 - -## 背景 - -当前 MCP server 只有基本的 ask_sql 工具。完整的 MCP 应该包含: -- Resources:可读取的数据源(表结构、指标、历史查询等) -- Prompts:可复用的 prompt 模板 -- Tools:可执行的操作(已有 ask_sql,需要补充) -- Sessions:会话管理 - -## 本轮要做的事 - -### 1. MCP Resources - -新增以下 resources: - -| Resource URI | 描述 | 内容 | -|-------------|------|------| -| `queryforge://tables` | 所有表列表 | 表名 + 简要描述 | -| `queryforge://tables/{table_name}` | 单表详情 | 字段、类型、主键、外键、样例行 | -| `queryforge://metrics` | 所有指标列表 | 指标名、描述、所属实体 | -| `queryforge://metrics/{metric_name}` | 单指标详情 | 指标定义、表达式、允许维度 | -| `queryforge://history` | 历史查询列表 | 最近 N 条成功查询 | -| `queryforge://skills` | 可用 Skills 列表 | Skill 名、描述、作用范围 | -| `queryforge://subjects` | 主题列表 | Subject id、名称、描述 | - -Resources 是只读的,供 MCP client 浏览和引用。 - -### 2. MCP Prompts - -新增以下 prompts: - -| Prompt Name | 描述 | 参数 | -|------------|------|------| -| `queryforge.analyze_data` | 数据分析模板 | question, subject | -| `queryforge.sql_review` | SQL 评审模板 | sql | -| `queryforge.troubleshoot` | SQL 排错模板 | sql, error_message | -| `queryforge.build_report` | 报告生成模板 | question, subject, metrics | - -Prompts 是可复用的模板,MCP client 可以加载后填充参数。 - -### 3. MCP Tools 增强 - -已有工具: -- `ask_sql`:执行自然语言查询 - -新增工具: -- `list_tables`:列出所有表 -- `describe_table`:查看表结构 -- `list_metrics`:列出所有指标 -- `preview_sql`:预览 SQL 结果(带 LIMIT) -- `review_sql`:评审 SQL -- `get_history`:获取历史查询 -- `new_session`:创建新会话 -- `reset_session`:重置当前会话 - -注意:所有工具都复用已有的能力,不重新实现。 - -### 4. Session 支持 - -MCP server 增加会话支持: -- 每个 MCP 连接维护一个 session -- 连续的查询自动使用同一会话 -- 提供 new_session 和 reset_session 工具 - -Session 复用 Phase B 实现的 Conversation Memory。 - -### 5. MCP Server 重构 - -当前 MCP server 可能是在一个单独的文件中,需要重构以支持 resources 和 prompts。 - -重构要点: -- 使用 MCP SDK 的 resources 和 prompts API -- 所有工具/资源/prompt 都复用 QueryForge 的核心能力 -- 保持向后兼容:ask_sql 工具的行为不变 -- 错误处理统一 - -### 6. 配置 - -配置项: -- `mcp_resources_enabled: bool`,默认 true -- `mcp_prompts_enabled: bool`,默认 true -- `mcp_session_enabled: bool`,默认 true -- `mcp_history_limit: int`,默认 20 - -### 7. 测试策略 - -MCP 的测试比较特殊,需要 MCP SDK 的测试支持。 - -测试内容: -- 每个 resource 都能正确返回数据 -- 每个 prompt 都能正确加载 -- 每个工具都能正常调用 -- session 能正确维护上下文 -- 错误处理正确 - -## 限制 - -- 所有 MCP 能力都复用已有核心能力,不重新实现 -- 不改变核心业务逻辑 -- 向后兼容:旧的 ask_sql 工具行为不变 -- 安全策略仍然生效:MCP 的工具调用也经过 Governance -- 不引入新的依赖(MCP SDK 已有) - -## 验收标准 - -1. MCP server 提供至少 5 种 resources -2. MCP server 提供至少 3 种 prompts -3. MCP server 提供至少 5 种 tools -4. session 能正确维护上下文 -5. 所有 MCP 能力都复用已有核心逻辑 -6. 向后兼容:ask_sql 行为不变 -7. 安全策略在 MCP 中也生效 -8. 新增测试覆盖:resources、prompts、tools、session -9. ask_sql 全量测试通过 - -## 输出要求 - -1. 先读取现有代码,确认 MCP server 的当前实现 -2. 给出 MCP 增强设计和资源/prompt/工具列表 -3. 实现代码 -4. 编写测试 -5. 运行测试,确保全量通过 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/14_final_acceptance.md b/docs/reproduction/vibe-coding-reproduce-phase2/prompts/14_final_acceptance.md deleted file mode 100644 index f086ff0..0000000 --- a/docs/reproduction/vibe-coding-reproduce-phase2/prompts/14_final_acceptance.md +++ /dev/null @@ -1,147 +0,0 @@ -# Prompt 14: 最终集体验收与文档收尾 - -复制下面整段给 Codex 使用。 - -```text -Phase D 的 prompts 已经完成。本轮做最终的全链路集体验收和文档收尾。 - -## 验收范围 - -整个第二阶段(Agent Team 深度进化)的全部能力: - -### Phase A:填平补齐 -- 路由系统:sql_review / metadata_query / troubleshoot_sql / explain_result / build_report -- 角色升级:ProductAnalyst / SchemaArchitect / KnowledgeAgent 决策化 -- 质量门禁:artifact 三级状态、阶段推进 - -### Phase B:增强自主性 -- Conversation Memory:会话上下文与追问重写 -- Bounded Tool Loop:有界工具循环 -- Structured Reasoning:结构化推理摘要 - -### Phase C:质量提升 -- Parallel + Selection:多候选生成与选择 -- Subject Tree:主题范围约束 - -### Phase D:形态扩展 -- Streaming Output:节点级事件流 -- Report Artifact:静态 HTML 分析报告 -- MCP 增强:resources / prompts / sessions - -### 回归验证 -- ask_sql 主链路不退化 -- 所有入口正常工作 -- 性能基线 - -## 验收清单 - -### 1. 功能完整性 - -- [ ] 7 种 task_type 路由正确 -- [ ] ProductAnalyst 决策化完成 -- [ ] SchemaArchitect 决策化完成 -- [ ] Artifact 质量门禁生效 -- [ ] Conversation Memory 正常工作 -- [ ] Tool Loop 正常工作(4 个工具) -- [ ] Structured Reasoning 正常输出 -- [ ] Parallel + Selection 正常工作 -- [ ] Subject Tree 正常工作 -- [ ] Streaming Output 正常工作 -- [ ] Report Artifact 正常生成 -- [ ] MCP resources/prompts/sessions 正常 - -### 2. 架构一致性 - -- [ ] 所有入口都经过 EntryRouter → Orchestrator → WorkflowRunner -- [ ] 没有绕过 Governance 的路径 -- [ ] 所有高级功能默认关闭或最小化 -- [ ] 模块职责清晰,没有越界 -- [ ] 代码风格一致 - -### 3. 性能基线 - -- [ ] 默认配置下,简单查询耗时不退化超过 10% -- [ ] 开启 Tool Loop 后,额外耗时可接受 -- [ ] 开启多候选后,额外耗时可接受 -- [ ] 报告生成耗时可接受 - -### 4. 测试覆盖率 - -- [ ] 全量单元测试通过(200+ 项) -- [ ] 每个新功能都有对应测试 -- [ ] 集成测试覆盖主要场景 -- [ ] 错误场景有测试覆盖 - -### 5. 文档完整性 - -- [ ] README.md 更新 -- [ ] 架构文档更新 -- [ ] 配置文档更新 -- [ ] API 文档更新 -- [ ] MCP 文档更新 - -## 要做的事 - -### 1. 全量回归测试 - -运行所有测试,确保全绿。 - -### 2. 编写端到端验收测试 - -新建 tests/test_phase2_final_acceptance.py,包含: -- 完整 ask_sql 端到端测试 -- sql_review 端到端测试 -- metadata_query 端到端测试 -- 会话上下文 + 追问测试 -- Tool Loop + 多候选组合测试 -- Subject Tree + 主题切换测试 -- 报告生成测试 -- Streaming 测试(如果可行) - -### 3. 文档更新 - -- 更新 README.md:全面介绍 Phase 2 新增能力 -- 更新 docs/agent_team_architecture.md:更新架构图和完整角色列表 -- 更新 docs/future_extensions.md:标记已完成项,新增后续方向 -- 更新 docs/configuration.md:新增配置项说明 -- 更新 docs/mcp_server.md:MCP 增强说明 -- 更新 docs/api_reference.md:API 端点更新 - -### 4. 代码清理 - -- 删除废弃的代码和 TODO -- 统一命名 -- 补充 docstring -- 修复 lint 警告 - -### 5. 示例数据和 demo - -- 准备 demo 脚本,展示各能力 -- 准备示例 subject 配置 -- 准备示例 SQL 评审用例 - -### 6. 最终验收报告 - -生成最终验收报告,包含: -- 功能清单和完成状态 -- 测试结果 -- 性能对比 -- 已知限制和后续方向 - -## 验收标准 - -1. 全量测试通过(200+ 项) -2. 所有新功能都能端到端跑通 -3. 默认配置下性能不退化超过 10% -4. 文档完整、准确、与代码一致 -5. 代码整洁,没有明显的冗余或 TODO -6. 所有入口(CLI/API/MCP/Gateway)都能正常工作 -7. 安全边界完整,没有绕过 Governance 的路径 - -## 输出 - -1. 最终验收报告 -2. 更新后的所有文档 -3. 清理后的代码 -4. Phase 2 完成标记和后续方向 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-phase2/reference/phase2_evolution_map.md b/docs/reproduction/vibe-coding-reproduce-phase2/reference/phase2_evolution_map.md deleted file mode 100644 index 5d29a36..0000000 --- a/docs/reproduction/vibe-coding-reproduce-phase2/reference/phase2_evolution_map.md +++ /dev/null @@ -1,173 +0,0 @@ -# QueryForge 第二阶段演进路径图 - -## 前三阶段回顾 - -### Phase 0: 基础版(vibe-coding-reproduce) -``` -CLI -> WorkflowRunner -> SchemaLinking -> GenSQL -> ExecuteSQL -> Output -``` -核心能力:自然语言转 SQL 的基础链路。 - -### Phase 1: 进阶版(vibe-coding-reproduce-upgrade) -``` -CLI / API / MCP / Gateway - -> DateParser - -> SchemaLinking + Skills + History + VectorStore - -> GenSQL - -> Plan Mode (可选) - -> ExecuteSQL - -> Reflect -> Fix/Regenerate (循环) - -> Output - -> Visualization (可选) - -> SQL History Cache -``` -核心能力:多模型、Skills、反思修复、知识库、可视化、多端入口。 - -### Phase 2: Agent Team 层(vibe-coding-reproduce-agent-team) -``` -CLI / API / MCP / Gateway - -> EntryRouterAgent (路由分类) - -> OrchestratorAgent (编排协调) - -> Analysis Hook: ProductAnalyst + Knowledge + SchemaArchitect - -> WorkflowRunner (SQL 生成/执行/反射/修复) - -> Candidate Hook: SQLDeveloper + Governance - -> Completion Hook: DataQA + Visualization + Ops - -> DeliveryReport -``` -核心能力:路由编排、角色协作、状态持久化、artifact 追踪。 - ---- - -## 本阶段(Phase 3: 深度进化)目标 - -从"框架层面的编排"进化为"真正能提升准确率和体验的协作系统"。 - -### Phase 3-A: 填平补齐 - -``` -EntryRouter - ├── ask_sql ────────┐ - ├── sql_review ────┤ - ├── metadata_query ─┤→ 各走各的 pipeline - ├── troubleshoot ───┤ - ├── explain ────────┤ - ├── build_report ───┘ - └── unknown ────────→ 回退到 ask_sql - -每个 pipeline 的角色都是有决策能力的,不是信息打包: - ProductAnalyst: 需求澄清检测、歧义识别、指标映射 - SchemaArchitect: 表选择排序、Join Path 推荐、风险评估 -``` - -新增:质量门禁 -``` -analysis gate → schema gate → sql_candidate gate → execution gate → qa gate - (blocked 终止,warning 记录但继续) -``` - -### Phase 3-B: 增强自主性 - -``` -Conversation Memory: - Session → ProductAnalyst 追问重写 → 完整问题 → 正常流程 - -Bounded Tool Loop: - SchemaArchitect → Tool Loop (list/describe/preview) → GenSQL - (最多 5 轮,严格只读,预算可控) - -Structured Reasoning: - GenSQL 同时输出 SQL + 结构化推理摘要 - 推理摘要可审计、可校验、可复用 -``` - -### Phase 3-C: 质量提升 - -``` -Parallel + Selection: - GenSQL → 2-3 个候选 → Selector (规则+执行信号评分) → 最优 SQL → 执行 - (默认 1 个,可配置) - -Subject Tree: - ProductAnalyst → Subject 选择 → 裁剪 Schema/Skills/History → GenSQL - (选错有 fallback,自动扩大范围重试) -``` - -### Phase 3-D: 形态扩展 - -``` -Streaming Output: - EventBus → SSE / CLI 进度 / MCP 事件流 - (只传进度事件,不传结果数据) - -Report Artifact: - Result → DataQA → Visualization → ReportGenerator → HTML 报告 - (多图、表格、口径说明、关键发现) - -MCP 增强: - Resources: tables / metrics / history / skills / subjects - Prompts: analyze / review / troubleshoot / build_report - Tools: ask_sql / list_tables / describe / preview / review / sessions - Sessions: 会话上下文持久化 -``` - ---- - -## 最终形态 - -``` -CLI / API / MCP / Gateway - ├─ [Streaming EventBus] (可选,进度推送) - │ - → EntryRouterAgent (任务分类) - → OrchestratorAgent (编排协调 + 质量门禁) - │ - ├─ [Session Memory] (可选,会话上下文) - ├─ [Subject Tree] (可选,主题范围约束) - │ - → Analysis Phase: - │ ├─ ProductAnalystAgent (需求分析 + 歧义检测 + 追问重写) - │ ├─ KnowledgeAgent (知识检索 + 排序去重) - │ └─ SchemaArchitectAgent (Schema 规划 + Join 推荐 + 风险) - │ - → [Tool Loop Phase] (可选,观察-行动循环) - │ ├─ list_tables - │ ├─ describe_table - │ ├─ preview_distinct_values - │ └─ execute_sql_preview - │ - → SQL Candidate Phase: - │ ├─ [Parallel Candidates] (可选,多候选生成) - │ ├─ SQLDeveloperAgent (候选注册 + 结构化推理) - │ └─ GovernanceAgent (安全治理 + 策略验证) - │ - → Execution Phase: - │ └─ WorkflowRunner (Plan Mode → Execute → Reflect → Fix/Regenerate) - │ - → Completion Phase: - │ ├─ DataQAAgent (质量报告 + 一致性检查) - │ ├─ VisualizationAgent (图表生成) - │ ├─ [Report Agent] (可选,完整 HTML 报告) - │ └─ OpsAgent (运维状态 + 健康检查) - │ - → DeliveryReport - │ - └─ [Artifacts] (持久化:state.json + 各角色 artifact) -``` - ---- - -## 能力演进阶梯 - -| 层级 | 能力 | 关键词 | -|-----|------|--------| -| L0 | 基础 NL2SQL | 单轮、单 SQL、无反思 | -| L1 | 反思修复 | Reflect + Fix + Regenerate | -| L2 | 知识增强 | Skills + History + VectorStore | -| L3 | Agent 编排 | EntryRouter + Orchestrator + Roles | -| L4 | 路由分化 | 多 pipeline + 角色决策化 | -| L5 | 对话能力 | Session Memory + 追问重写 | -| L6 | 自主观察 | Tool Loop + 结构化推理 | -| L7 | 质量提升 | 多候选选择 + 主题约束 | -| L8 | 形态扩展 | Streaming + Report + 完整 MCP | - -本阶段完成后,QueryForge 达到 L7-L8 水平。 diff --git a/docs/reproduction/vibe-coding-reproduce-upgrade/00_README.md b/docs/reproduction/vibe-coding-reproduce-upgrade/00_README.md deleted file mode 100644 index 23ef9a7..0000000 --- a/docs/reproduction/vibe-coding-reproduce-upgrade/00_README.md +++ /dev/null @@ -1,124 +0,0 @@ -# Datus-Agent 进阶复现 Prompts - -这个文件夹用于升级基础版 `QueryForge`。基础版只复现了 Datus-Agent 的 fixed workflow: - -```text -schema_linking -> gen_sql -> execute_sql -> output -``` - -进阶版的目标是在基础功能跑通后,继续复现原项目中更有代表性的 LLM Agent 能力,但仍然坚持“可执行、可分阶段、不过度工程化”。 - -## 使用前提 - -请先完成基础版交付物: - -- `vibe-coding-reproduce/` -- 得到一个可运行的 `QueryForge/` -- 已经能完成:自然语言问题 -> schema linking -> SQL generation -> SQL execution -> output - -本文件夹中的 prompts 假设你已经有这个基础项目。每个 prompt 都要求 Codex 先读取现有代码,再做增量修改。 - -## 本次增强范围 - -优先增强这些能力: - -1. Skills 系统 -2. 多 LLM 供应商:OpenAI、Claude、Gemini、DeepSeek、Qwen、GLM -3. ReflectNode:自动评估 SQL 和结果 -4. DateParserNode:解析自然语言日期 -5. Plan Mode:先审阅计划,再执行 SQL -6. 知识库缓存:存储历史 SQL、可复用成功查询 -7. 结果可视化:简单图表 -8. 完善日志系统 -9. SQL 修复重试机制 -10. LanceDB 向量存储 -11. MCP / API / Gateway 多端入口 - -## 推荐使用顺序 - -1. `prompts/01_upgrade_scope_and_architecture.md` -2. `prompts/02_config_and_multi_llm.md` -3. `prompts/03_skills_system.md` -4. `prompts/04_date_parser_and_plan_mode.md` -5. `prompts/05_reflect_and_sql_fix_retry.md` -6. `prompts/06_sql_history_cache.md` -7. `prompts/07_lancedb_vector_kb.md` -8. `prompts/08_result_visualization.md` -9. `prompts/09_logging_and_observability.md` -10. `prompts/10_api_mcp_gateway.md` -11. `prompts/11_integration_acceptance.md` -12. `prompts/12_future_extensions.md` - -辅助文档: - -- `upgrade_workflow_map.md`:展示基础版、进阶版和原项目 workflow 的映射关系。 -- 根目录 `sample_data/`:当前项目统一维护的 `anime_streaming` 和 `anime_streaming` 示例数据。 - -## 为什么仍然分阶段 - -这些能力彼此有依赖关系: - -- 多 LLM 供应商是 ReflectNode、FixNode、Plan Mode 的基础。 -- Skills 系统会改变 prompt 注入和工具边界。 -- DateParserNode 会影响 GenSqlNode 的输入上下文。 -- ReflectNode 和 FixNode 会改变 workflow 控制流。 -- 历史 SQL 缓存和 LanceDB 会影响 schema linking / SQL generation 的上下文。 -- API / MCP / Gateway 应该复用同一个 WorkflowRunner,不能复制业务逻辑。 - -所以升级 prompts 按“底座 -> 能力 -> 存储 -> 入口 -> 验收”的顺序组织。 - -## 仍然不建议一次性完整照搬的内容 - -原项目是企业级工程。进阶版可以更接近原项目,但仍不建议一次性复刻: - -- 完整权限系统 -- 完整 marketplace skill 分发 -- 完整 OpenAI Agents SDK tool loop -- 复杂 BI / Dashboard / Report artifact 体系 -- 多租户认证 -- 生产级 Gateway 回调签名 -- 复杂调度器和后台任务系统 - -这些可以放在最后的 future extensions 中继续扩展。 - -## 最终目标 - -完成全部 prompts 后,`QueryForge` 应该从一个“自然语言转 SQL demo”升级为一个中阶 SQL Agent: - -```text -CLI / API / MCP / Gateway - -> Plan Mode 可选 - -> DateParserNode 可选 - -> SchemaLinkingNode - -> GenSqlNode - -> ExecuteSqlNode - -> ReflectNode - -> FixNode retry 可选 - -> OutputNode - -> Visualization 可选 - -> SQL History Cache / LanceDB KB -``` - -它仍然不是完整 Datus-Agent,但已经覆盖了原项目中最有学习价值的 Agent 架构思想。 - -## 示例数据 - -复现资料本身不再重复打包样例数据。当前项目统一使用根目录下的示例数据: - -```text -sample_data/anime_streaming/ - anime_streaming.sqlite - tables/*.csv - success_story.csv - reference_sql/ - reference_template/ -sample_data/anime_streaming/ -``` - -建议用途: - -- `anime_streaming.sqlite`:所有 CLI/API/MCP/Gateway 端到端查询的主数据库。 -- `success_story.csv`:初始化 SQL history cache。 -- `reference_sql/`:初始化 Reference SQL 知识库或 LanceDB 文档。 -- `reference_template/`:作为 SQL 模板和 Skills 示例。 -- `anime_streaming/`:用于语义模型、SQL policy 和多实体数仓测试。 diff --git a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/01_upgrade_scope_and_architecture.md b/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/01_upgrade_scope_and_architecture.md deleted file mode 100644 index e43f0e2..0000000 --- a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/01_upgrade_scope_and_architecture.md +++ /dev/null @@ -1,69 +0,0 @@ -# Prompt 01: 进阶升级范围与架构重构 - -复制下面整段给 Codex 使用。 - -```text -你现在要基于已有的 QueryForge 项目做进阶升级。请先不要写代码,本轮只做升级范围确认和架构方案。 - -前提: - -基础版 QueryForge 已经能完成: - -CLI -> WorkflowRunner -> Workflow -> SchemaLinkingNode -> GenSqlNode -> ExecuteSqlNode -> OutputNode - -现在我希望在这个基础上逐步接近 Datus-Agent 原项目中的高级能力,包括: - -- Skills 系统 -- 多 LLM 供应商:OpenAI、Claude、Gemini、DeepSeek、Qwen、GLM -- ReflectNode 自动评估结果 -- DateParserNode 自然语言日期解析 -- Plan Mode 先审阅再执行 -- 历史 SQL 知识库缓存 -- 结果可视化 -- 完善日志系统 -- SQL 修复重试机制 -- LanceDB 向量存储 -- MCP / API / Gateway 多端入口 - -本轮目标: - -1. 分析当前 QueryForge 架构还缺哪些扩展点。 -2. 设计一个“可逐步升级”的模块架构,不要推倒重来。 -3. 给出升级路线图和模块依赖顺序。 -4. 明确哪些能力先做简化版,哪些能力可以后续再增强。 - -请输出: - -1. 当前基础版架构评估。 -2. 新增模块清单和职责: - - config - - model provider factory - - skill registry / skill manager - - date parser node - - plan mode - - reflect node - - fix node - - SQL history store - - vector store - - visualization - - logging - - API / MCP / Gateway adapters -3. 新的目录结构建议。 -4. 新的 workflow 图。 -5. Context 需要新增的字段。 -6. 每个升级阶段的顺序和验收标准。 - -限制: - -- 不要写代码。 -- 不要一次性实现全部能力。 -- 不要引入生产级权限、认证、多租户。 -- 不要把 API / MCP / Gateway 做成独立业务逻辑,它们必须复用同一个 WorkflowRunner。 -- 不要为了“像原项目”而引入过度复杂抽象。 - -验收标准: - -- 输出能作为后续 10+ 轮增量开发的总蓝图。 -- 能清晰说明为什么先做多模型和 Skills,再做反思、修复、知识库、多端入口。 -- 保持 QueryForge 可运行,不要求推倒重构。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/02_config_and_multi_llm.md b/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/02_config_and_multi_llm.md deleted file mode 100644 index fcdfaa1..0000000 --- a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/02_config_and_multi_llm.md +++ /dev/null @@ -1,86 +0,0 @@ -# Prompt 02: 配置系统与多 LLM 供应商 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请在 QueryForge 中实现轻量级多 LLM 供应商系统。 - -本轮目标: - -把基础版单一 OpenAI 调用升级为 provider factory,支持: - -- OpenAI -- Claude -- Gemini -- DeepSeek -- Qwen -- GLM - -这是后续 ReflectNode、FixNode、Plan Mode、Skills prompt 注入的基础。 - -请先读取当前项目文件,再做增量修改。 - -设计要求: - -1. 配置结构 - - 支持 `.env` 环境变量。 - - 支持一个简单 `config.yml` 或 `models.yml`。 - - 用户可以选择 active provider 和 model。 - - 每个 provider 至少包含: - - type - - model - - api_key env name - - base_url 可选 - - 不要实现原项目复杂的全局/项目级覆盖系统,只做轻量版本。 - -2. 模型抽象 - - 定义统一接口: - - generate_text - - generate_json - - generate_with_messages - - 所有 provider adapter 输出统一格式。 - - 失败时返回清晰错误。 - -3. Provider adapter - - OpenAI、DeepSeek、Qwen、GLM 可以优先走 OpenAI-compatible HTTP/chat completions。 - - Claude、Gemini 可以实现简化 adapter;如果没有 SDK,先通过清晰接口和 TODO fallback 保持可扩展。 - - 不要把所有 provider 的逻辑堆在一个函数里。 - -4. CLI - - 增加 `--model-provider` 和 `--model`。 - - 增加 `--list-models`。 - - 运行时打印当前使用的 provider/model。 - -5. GenSqlNode - - 改为通过 ModelFactory 获取模型。 - - 不直接依赖 OpenAI 类。 - -6. 测试/验证 - - 不要求所有 provider 都真实调用成功,因为用户可能没有所有 key。 - - 至少要验证: - - list models 正常。 - - 缺少 key 时提示友好。 - - OpenAI-compatible provider 能按配置构造请求。 - -限制: - -- 不引入 LiteLLM,除非你能说明它显著简化实现。 -- 不做 OAuth。 -- 不做模型缓存 LRU,最多保留一个简单实例缓存。 -- 不做流式输出。 - -输出要求: - -- 直接修改文件。 -- 给出新增/修改文件清单。 -- 给出配置示例。 -- 给出验证命令。 -- 说明每个 provider 的支持等级:已实现、OpenAI-compatible、占位扩展。 - -验收标准: - -- 现有 SQL 生成流程仍能运行。 -- GenSqlNode 不再绑定单一 OpenAI 类。 -- CLI 能选择 provider/model。 -- 缺少 API key 时有清晰错误。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/03_skills_system.md b/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/03_skills_system.md deleted file mode 100644 index 1a9dc00..0000000 --- a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/03_skills_system.md +++ /dev/null @@ -1,84 +0,0 @@ -# Prompt 03: Skills 系统 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请为 QueryForge 增加 Skills 系统。 - -本轮目标: - -复现 Datus-Agent 中 Skills 的核心思想:技能不是普通代码插件,而是一组可被模型读取的本地说明,用来影响 Agent 的行为、SQL 风格、业务规则和工具使用方式。 - -请先读取当前项目文件,再做增量修改。 - -实现范围: - -1. 本地 skills 目录 - 建议结构: - - skills/ - sql_best_practices/ - SKILL.md - skill.yml - business_rules/ - SKILL.md - skill.yml - -2. skill.yml metadata - 至少支持: - - name - - description - - allowed_nodes - - enabled - - priority - -3. SkillRegistry - - 扫描 skills 目录。 - - 读取 metadata。 - - 校验 SKILL.md 是否存在。 - - 返回可用技能列表。 - -4. SkillManager - - 根据 node name 过滤技能。 - - 加载技能内容。 - - 拼接成 `` 和 `` 文本块。 - - 提供给 GenSqlNode、ReflectNode、FixNode 使用。 - -5. CLI - - 增加 `--list-skills`。 - - 增加 `--skills skill_a,skill_b` 用于手动启用技能。 - - 如果未指定,则加载 enabled=true 且适用于当前节点的技能。 - -6. GenSqlNode 集成 - - 在 prompt 中注入可用 Skills 摘要。 - - 注入已加载 Skills 正文。 - - 明确告诉模型:Skills 是约束和业务规则,不是数据表。 - -7. 示例 Skills - - SQL 最佳实践:只读查询、避免 SELECT *、加 LIMIT、使用清晰别名。 - - 业务规则示例:订单金额字段含义、取消订单是否排除等。 - -限制: - -- 不实现远程 marketplace。 -- 不实现权限系统。 -- 不允许 Skill 直接执行任意代码。 -- Skill 本轮只作为 prompt context,不作为 Python plugin。 -- 不要过度设计复杂包管理。 - -输出要求: - -- 直接修改或新增文件。 -- 给出 Skills 目录结构。 -- 给出两个示例 Skill 的内容。 -- 给出如何在 SQL 生成 prompt 中注入 Skills 的说明。 -- 给出验证命令。 - -验收标准: - -- `--list-skills` 能列出本地 Skills。 -- GenSqlNode prompt 中能包含已加载 Skill 内容。 -- 未指定 Skills 时能自动加载 enabled 且适用于 gen_sql 的 Skills。 -- 禁用 Skill 后不会注入。 -- 原有 SQL 生成流程不被破坏。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/04_date_parser_and_plan_mode.md b/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/04_date_parser_and_plan_mode.md deleted file mode 100644 index af251ee..0000000 --- a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/04_date_parser_and_plan_mode.md +++ /dev/null @@ -1,89 +0,0 @@ -# Prompt 04: DateParserNode 与 Plan Mode - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请为 QueryForge 增加 DateParserNode 和 Plan Mode。 - -本轮目标: - -1. DateParserNode:把“最近 30 天”“本月”“上季度”“2024 年”等自然语言日期解析成明确日期上下文。 -2. Plan Mode:SQL 执行前先展示计划,用户确认后再执行。 - -请先读取当前项目文件,再做增量修改。 - -DateParserNode 要求: - -1. 放在 schema_linking 或 gen_sql 之前。 -2. 输入:SqlTask.question、当前日期。 -3. 输出:context.date_context。 -4. 支持规则优先: - - today - - yesterday - - last N days - - this month - - last month - - this quarter - - last quarter - - this year - - last year - - YYYY-MM-DD -5. 对中文表达也做基础支持: - - 今天 - - 昨天 - - 最近 N 天 - - 本月 - - 上月 - - 今年 - - 去年 -6. 可选 LLM fallback: - - 如果规则解析不到,允许调用当前 LLM 输出结构化日期。 - - fallback 必须可关闭。 -7. GenSqlNode prompt 要注入 date_context。 - -Plan Mode 要求: - -1. 增加 `--plan-mode`。 -2. 在执行 SQL 前生成执行计划。 -3. 计划内容至少包含: - - 用户问题 - - 识别的表 - - 日期上下文 - - 即将执行的 SQL - - 风险提示 -4. CLI 交互: - - 用户输入 yes 才执行。 - - 输入 no 或回车默认不执行。 -5. 非交互模式: - - 增加 `--auto-approve-plan`,用于测试或 API 调用。 - -Workflow 调整: - -建议进阶 workflow: - -date_parser -> schema_linking -> gen_sql -> plan_mode_check -> execute_sql -> output - -也可以把 plan mode 实现在 WorkflowRunner 中,但必须说明原因。 - -限制: - -- 不要做复杂自然语言时间库。 -- 不要引入大型依赖。 -- 不要在 plan mode 中执行 SQL。 -- 不要让 plan mode 依赖人工输入导致测试无法运行,必须提供 auto approve。 - -输出要求: - -- 直接修改文件。 -- 说明 workflow 顺序变化。 -- 给出日期解析示例。 -- 给出 plan mode 交互示例。 -- 给出验证命令。 - -验收标准: - -- 包含日期的问题能在 prompt 中注入明确日期范围。 -- `--plan-mode` 会先展示计划,不确认不执行 SQL。 -- `--auto-approve-plan` 可以让测试自动通过。 -- 原有无日期问题仍正常运行。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/05_reflect_and_sql_fix_retry.md b/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/05_reflect_and_sql_fix_retry.md deleted file mode 100644 index f1468d0..0000000 --- a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/05_reflect_and_sql_fix_retry.md +++ /dev/null @@ -1,95 +0,0 @@ -# Prompt 05: ReflectNode 与 SQL 修复重试 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请为 QueryForge 增加 ReflectNode 和 SQL 修复重试机制。 - -本轮目标: - -让系统不只是“生成一次 SQL 然后执行”,而是具备基础自我评估和修复能力。 - -请先读取当前项目文件,再做增量修改。 - -新增节点: - -1. ReflectNode - 位置:execute_sql 之后,output 之前。 - 输入: - - 用户问题 - - 生成的 SQL - - SQL 解释 - - 执行结果摘要 - - 表结构 - - 错误信息,如果有 - 输出: - - success - - strategy - - reason - - suggested_fix 可选 - -2. FixNode - 位置:当 SQL 执行失败或 ReflectNode 要求修复时触发。 - 输入: - - 用户问题 - - 原 SQL - - 执行错误 - - 表结构 - - date_context - - skills_context - 输出: - - fixed_sql - - explanation - -Reflect strategy 最小集合: - -- SUCCESS:结果可以接受,进入 output。 -- FIX_SQL:SQL 有错误或结果明显不对,进入 FixNode。 -- REGENERATE:当前 SQL 偏离问题,回到 GenSqlNode。 -- NEED_USER_REVIEW:模型无法判断,停止并输出人工审阅提示。 - -Workflow 控制流: - -- 增加 max_retries,默认 2。 -- execute_sql 失败时优先进入 FixNode。 -- FixNode 生成新 SQL 后重新执行。 -- execute_sql 成功后进入 ReflectNode。 -- ReflectNode 返回 FIX_SQL 或 REGENERATE 时,未超过 max_retries 才重试。 -- 超过 max_retries 后停止,并输出最后错误和尝试历史。 - -Context 新增字段: - -- reflection_result -- fix_attempts -- retry_count -- execution_errors -- sql_attempt_history - -LLM prompt 要求: - -- ReflectNode prompt 必须让模型只输出 JSON。 -- FixNode prompt 必须要求只生成 SQLite SELECT 或 WITH 查询。 -- 修复 SQL 不允许 DDL/DML。 - -限制: - -- 不实现复杂动态 DAG。 -- 不实现并行 selection。 -- 不做无限循环。 -- 不把错误直接隐藏,必须保留尝试历史。 - -输出要求: - -- 直接修改文件。 -- 说明 workflow 控制流。 -- 给出 ReflectNode 和 FixNode 的 prompt 结构。 -- 给出验证命令。 -- 给出一个故意错误 SQL 的修复测试方式。 - -验收标准: - -- SQL 执行失败时会尝试自动修复。 -- ReflectNode 能判断成功并进入 output。 -- 超过最大重试次数后有清晰错误。 -- 所有尝试会记录在 context 或输出摘要中。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/06_sql_history_cache.md b/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/06_sql_history_cache.md deleted file mode 100644 index 6f78b57..0000000 --- a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/06_sql_history_cache.md +++ /dev/null @@ -1,95 +0,0 @@ -# Prompt 06: 历史 SQL 知识库缓存 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请为 QueryForge 增加历史 SQL 知识库缓存。 - -本轮目标: - -复现 Datus-Agent 中 Reference SQL 的核心思想:把成功执行过的自然语言问题、SQL、解释、表、结果摘要存下来,后续生成 SQL 时可以参考相似历史案例。 - -请先读取当前项目文件,再做增量修改。 - -实现范围: - -1. SQLHistoryStore - - 使用 SQLite 存储,不要一开始就用 LanceDB。 - - 建议独立文件:`storage/sql_history_store.py`。 - - 存储字段: - - id - - question - - sql - - explanation - - tables_used - - success - - error - - row_count - - created_at - - provider - - model - -2. 写入时机 - - OutputNode 成功输出后写入历史。 - - SQL 执行失败也可以写入,但 success=false。 - - 不要写入敏感数据全量结果,只保存摘要。 - -3. 初始化原项目 success story - - 支持从 `sample_data/anime_streaming/success_story.csv` 导入历史 SQL。 - - CSV 至少包含 question 和 sql 字段。 - - 如果 CSV 中还有 evidence、expected_table、expected_knowledge 等字段,可以保存到 metadata。 - - 增加 CLI: - - `--import-success-stories sample_data/anime_streaming/success_story.csv` - - 导入时去重,避免重复写入同一个 question + sql。 - -4. 导入 reference SQL - - 支持读取 `sample_data/anime_streaming/reference_sql/*.sql`。 - - SQL 文件中注释行可以作为 question / evidence。 - - SQL 语句作为 reference_sql 保存。 - - 这个导入功能可以先做简单解析,不要求完美。 - -5. 检索方式 - - MVP 先实现关键词检索和简单相似度。 - - 输入当前 question,返回 top_k 历史 SQL。 - - 支持按 tables_used 过滤。 - -6. GenSqlNode 集成 - - 在生成 SQL prompt 中注入历史 SQL 示例。 - - 明确告诉模型:历史 SQL 是参考,不可盲目照抄。 - - 如果 schema 不匹配,必须以当前 schema 为准。 - -7. CLI - - `--history-top-k` - - `--show-history` - - `--clear-history` 可选,需要二次确认或明确参数。 - - `--import-success-stories` - - `--import-reference-sql` - -8. 配置 - - HISTORY_DB_PATH 默认 `.queryforge/history.db`。 - -限制: - -- 不保存完整查询结果。 -- 不引入向量库,本轮只做 SQLite 缓存。 -- 不做多用户权限。 -- 不做复杂相似度算法。 - -输出要求: - -- 直接修改文件。 -- 给出历史表结构说明。 -- 给出检索策略说明。 -- 给出 prompt 注入示例。 -- 给出验证命令。 - -验收标准: - -- 成功查询后会写入历史 SQL。 -- 可以从 `sample_data/anime_streaming/success_story.csv` 导入动漫平台成功案例。 -- 可以从 `sample_data/anime_streaming/reference_sql/` 导入参考 SQL。 -- 后续类似问题能检索到历史 SQL。 -- GenSqlNode 能把历史案例纳入 prompt。 -- 用户可以查看历史记录。 -- 历史库不存在时自动创建。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/07_lancedb_vector_kb.md b/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/07_lancedb_vector_kb.md deleted file mode 100644 index ee164d2..0000000 --- a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/07_lancedb_vector_kb.md +++ /dev/null @@ -1,89 +0,0 @@ -# Prompt 07: LanceDB 向量知识库 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请在 SQL history cache 的基础上增加可选 LanceDB 向量知识库。 - -本轮目标: - -复现 Datus-Agent 中向量检索的核心思想,但保持范围可控:只把历史 SQL 和 schema 文档向量化,用于辅助 GenSqlNode,不做完整 7 层 RAG。 - -请先读取当前项目文件,再做增量修改。 - -实现范围: - -1. VectorStore 抽象 - - 定义一个简单接口: - - add_documents - - search - - rebuild - - stats - - 先支持 LanceDB。 - - 如果 lancedb 未安装,系统要降级到 SQLite history 检索。 - -2. LanceDB 后端 - - 存储路径默认 `.queryforge/lancedb`。 - - 建议表: - - sql_history_vectors - - schema_doc_vectors - - 文档字段: - - id - - text - - metadata - - source_type - - created_at - -3. Embedding - - 优先使用轻量方式。 - - 可以支持 OpenAI embedding。 - - 如果没有 embedding key,提供清晰提示并禁用向量检索。 - - 不要强依赖大型本地模型。 - -4. 数据来源 - - 历史 SQL:question + sql + explanation + tables_used。 - - Schema doc:表名 + 字段名 + 字段类型。 - - 动漫平台 reference SQL:`sample_data/anime_streaming/reference_sql/*.sql`。 - - 动漫平台 reference template:`sample_data/anime_streaming/reference_template/*.j2`。 - - 原项目 success story:`sample_data/anime_streaming/success_story.csv`。 - -5. 检索集成 - - SchemaLinkingNode 可以读取 schema vector matches。 - - GenSqlNode 可以读取 sql history vector matches。 - - prompt 中分开标注: - - current schema - - similar historical SQL - - vector retrieved context - -6. CLI - - `--enable-vector-kb` - - `--rebuild-vector-kb` - - `--vector-top-k` - - `--kb-stats` - - `--kb-source sample_data/anime_streaming/reference_sql` - - `--kb-source sample_data/anime_streaming/reference_template` - -限制: - -- 不实现完整 RAGScope。 -- 不实现 Subject Tree。 -- 不实现 hybrid rerank。 -- 不要求 LanceDB 成为必需依赖。 -- LanceDB 失败时不能影响基础 SQL 查询功能。 - -输出要求: - -- 直接修改文件。 -- 说明新增依赖。 -- 说明降级策略。 -- 给出 rebuild 和 search 的验证命令。 -- 给出没有 lancedb / 没有 embedding key 时的行为。 - -验收标准: - -- 不启用 vector kb 时,原流程不变。 -- 启用后能把历史 SQL 或 schema docs 写入 LanceDB。 -- 启用后能把打包的 `reference_sql/`、`reference_template/`、`success_story.csv` 写入 LanceDB。 -- 类似问题能从 LanceDB 检索到上下文。 -- LanceDB 不可用时自动降级并提示。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/08_result_visualization.md b/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/08_result_visualization.md deleted file mode 100644 index 4ad35e8..0000000 --- a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/08_result_visualization.md +++ /dev/null @@ -1,79 +0,0 @@ -# Prompt 08: 结果可视化 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请为 QueryForge 增加简单结果可视化能力。 - -本轮目标: - -当 SQL 查询结果适合可视化时,自动生成一个简单图表配置或本地 HTML 图表,让用户不只看到 rows,还能看到趋势、排名或分布。 - -请先读取当前项目文件,再做增量修改。 - -实现范围: - -1. VisualizationNode - - 放在 OutputNode 之后或集成到 OutputNode 末尾。 - - 输入: - - question - - sql - - columns - - rows - - 输出: - - chart_type - - chart_config - - chart_path 可选 - - reason - -2. 图表类型 - 只支持最小集合: - - bar:分类 + 数值 - - line:日期/时间 + 数值 - - pie:分类占比,行数较少时 - - table:不适合图表时 fallback - -3. 判断规则 - - 如果有日期列 + 数值列,优先 line。 - - 如果有分类列 + 数值列,优先 bar。 - - 如果行数 <= 8 且有分类列 + 数值列,可选 pie。 - - 其他情况返回 table。 - -4. 输出方式 - 选择一种简单方式: - - 生成 Vega-Lite JSON 配置;或 - - 生成本地 HTML,使用轻量 CDN 图表库;或 - - 使用 matplotlib 输出 PNG。 - - 请优先选择最容易运行、依赖最少的方案,并说明原因。 - -5. CLI - - `--visualize` - - `--chart-output-dir` - - 如果未开启 visualize,只输出普通结果。 - -6. LLM 可选 - - 本轮优先用规则判断图表类型。 - - 可以预留 LLM 推荐图表类型接口,但不要默认依赖 LLM。 - -限制: - -- 不做复杂 dashboard。 -- 不做交互式 BI 编辑器。 -- 不做多图组合报告。 -- 不把可视化作为 SQL 查询成功的必要条件。 - -输出要求: - -- 直接修改文件。 -- 给出图表判断规则。 -- 给出输出文件路径策略。 -- 给出验证命令。 - -验收标准: - -- 查询结果为分类 + 数值时能生成 bar chart。 -- 查询结果为日期 + 数值时能生成 line chart。 -- 不适合图表时优雅 fallback 到 table。 -- 可视化失败不影响 SQL 输出。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/09_logging_and_observability.md b/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/09_logging_and_observability.md deleted file mode 100644 index cc99bb7..0000000 --- a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/09_logging_and_observability.md +++ /dev/null @@ -1,84 +0,0 @@ -# Prompt 09: 日志系统与轻量可观测性 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请为 QueryForge 增加完善但轻量的日志系统。 - -本轮目标: - -让每次 Agent 运行都有可追踪的 run_id、节点耗时、模型调用摘要、SQL 尝试历史和错误信息。不要做生产级 tracing,但要足够调试。 - -请先读取当前项目文件,再做增量修改。 - -实现范围: - -1. logging 配置 - - 使用 Python logging 标准库。 - - 支持 console + file。 - - 支持 LOG_LEVEL。 - - 日志文件默认 `.queryforge/logs/queryforge.log`。 - -2. run_id - - 每次 CLI/API/MCP/Gateway 调用生成 run_id。 - - run_id 要进入 Context。 - - 所有日志包含 run_id。 - -3. 节点日志 - 每个 Node 执行时记录: - - node name - - start time - - end time - - duration - - success/failure - - error message - -4. 模型调用日志 - - 记录 provider、model、prompt 字符数、返回字符数。 - - 不默认记录完整 prompt,避免泄露。 - - 可通过 `--debug-prompts` 显式保存 prompt 到 `.queryforge/traces/`。 - -5. SQL 日志 - - 记录生成 SQL。 - - 记录执行耗时。 - - 记录 row_count。 - - 记录 fix attempts。 - -6. 运行摘要 - - 每次运行结束后输出 run summary。 - - 包含: - - run_id - - question - - workflow nodes - - selected model - - retries - - history/vector matches count - - output status - -7. CLI - - `--log-level` - - `--debug-prompts` - - `--show-run-summary` - -限制: - -- 不引入 OpenTelemetry。 -- 不引入外部日志服务。 -- 不默认保存敏感完整 prompt。 -- 不把日志系统做成复杂框架。 - -输出要求: - -- 直接修改文件。 -- 说明日志字段。 -- 给出日志文件路径。 -- 给出验证命令。 - -验收标准: - -- 每次运行都有 run_id。 -- 节点执行耗时可见。 -- 错误可定位到具体节点。 -- debug-prompts 关闭时不保存完整 prompt。 -- debug-prompts 开启时能保存 prompt trace。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/10_api_mcp_gateway.md b/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/10_api_mcp_gateway.md deleted file mode 100644 index 2ce1573..0000000 --- a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/10_api_mcp_gateway.md +++ /dev/null @@ -1,97 +0,0 @@ -# Prompt 10: API / MCP / Gateway 多端入口 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请为 QueryForge 增加多端入口:API、MCP、Gateway。 - -本轮目标: - -复现 Datus-Agent 的多入口思想:不同入口共享同一个 WorkflowRunner,不复制核心业务逻辑。 - -请先读取当前项目文件,再做增量修改。 - -实现顺序: - -1. 服务层 - 先抽出统一服务: - - AgentService.ask(question, options) - - AgentService.plan(question, options) - - AgentService.list_models() - - AgentService.list_skills() - - AgentService.health() - - CLI、API、MCP、Gateway 都调用 AgentService。 - -2. REST API - - 使用 FastAPI。 - - 路由: - - GET /health - - GET /models - - GET /skills - - POST /ask - - POST /plan - - /ask 输入: - - question - - database - - model_provider 可选 - - model 可选 - - skills 可选 - - plan_mode 可选 - - auto_approve_plan 可选 - - visualize 可选 - - 输出复用 CLI final_output。 - -3. MCP - - 如果可用,使用 mcp Python SDK。 - - 暴露工具: - - ask_sql - - list_models - - list_skills - - get_history - - 如果 mcp SDK 未安装,提供清晰降级提示。 - - 不要求完整生产级 MCP Server,只要能展示工具映射思想。 - -4. Gateway - - 实现一个简化 HTTP webhook adapter。 - - 路由: - - POST /gateway/webhook - - 输入可模拟 Slack/Feishu: - - user_id - - channel - - text - - 输出: - - text response - - sql - - rows preview - - 不实现真实签名校验和平台 SDK。 - -5. CLI - - 增加启动 API 的命令或脚本说明。 - - CLI 仍然保留,不被 API 替代。 - -限制: - -- 不要把 API/Gateway 写成另一套 SQL 生成逻辑。 -- 不做认证。 -- 不做真实飞书/Slack SDK。 -- 不做 SSE streaming,除非非常简单。 -- MCP 不可用时不能影响 CLI/API。 - -输出要求: - -- 直接修改文件。 -- 给出新目录结构。 -- 给出 API 请求示例。 -- 给出 MCP 工具说明。 -- 给出 Gateway webhook 示例。 -- 给出验证命令。 - -验收标准: - -- CLI 仍可运行。 -- API /ask 能返回 SQL 和 rows。 -- API /health 能返回 ok。 -- Gateway webhook 能调用同一套 AgentService。 -- MCP 入口可用或有清晰降级提示。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/11_integration_acceptance.md b/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/11_integration_acceptance.md deleted file mode 100644 index e6c4fa4..0000000 --- a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/11_integration_acceptance.md +++ /dev/null @@ -1,114 +0,0 @@ -# Prompt 11: 进阶版集成验收 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请对 QueryForge 进阶版做完整集成验收。 - -本轮目标: - -不要新增大功能。请系统性验证前面所有升级能力是否能一起工作。 - -请先读取当前项目文件和 README,再执行检查。 - -验收范围: - -1. 基础主链路 - - CLI 输入自然语言问题。 - - 生成 SQL。 - - 执行 SQL。 - - 输出 rows。 - - 使用已打包的 `sample_data/anime_streaming/anime_streaming.sqlite` 作为主测试数据库。 - -2. 多模型 - - list models 正常。 - - 至少一个 OpenAI-compatible provider 可运行。 - - 缺少 key 有友好提示。 - -3. Skills - - list skills 正常。 - - 默认 enabled skill 会注入 GenSqlNode prompt。 - - 指定 skill 生效。 - - 禁用 skill 不注入。 - -4. DateParserNode - - 最近 30 天 / last 30 days。 - - 本月 / this month。 - - 去年 / last year。 - - date_context 出现在 GenSqlNode prompt。 - -5. Plan Mode - - 不确认不执行。 - - auto approve 可用于测试。 - -6. Reflect + Fix Retry - - SQL 执行失败能尝试修复。 - - Reflect SUCCESS 能进入 output。 - - 超过 max_retries 能清晰失败。 - -7. SQL History Cache - - 成功查询写入历史。 - - 能从 `sample_data/anime_streaming/success_story.csv` 导入动漫平台成功案例。 - - 能从 `sample_data/anime_streaming/reference_sql/` 导入参考 SQL。 - - 类似问题能检索历史。 - - history prompt 注入可见。 - -8. LanceDB Vector KB - - 未启用时不影响运行。 - - 启用但依赖缺失时能降级。 - - 启用且配置完整时能 rebuild / search。 - - 能索引已打包的 `reference_sql/` 和 `reference_template/`。 - -9. Visualization - - 排名问题生成 bar。 - - 时间序列生成 line。 - - 不适合图表时 fallback table。 - -10. Logging - - 每次运行有 run_id。 - - 节点耗时可见。 - - 错误能定位节点。 - -11. API / MCP / Gateway - - API health。 - - API ask。 - - Gateway webhook。 - - MCP 可用或降级清晰。 - -请执行: - -1. 静态检查。 -2. 依赖检查。 -3. bundled sample data 检查。 -4. smoke tests。 -5. 端到端手工命令。 -6. README 检查。 - -允许修改: - -- 修复集成 bug。 -- 补充最小测试。 -- 修正 README。 -- 调整错误信息。 - -不允许修改: - -- 不新增大功能。 -- 不大规模重构。 -- 不引入生产级认证/权限。 - -输出要求: - -- 给出验收报告。 -- 列出运行过的命令。 -- 列出通过项和失败项。 -- 对失败项做最小修复。 -- 最后给出“进阶版使用说明摘要”。 - -最终验收标准: - -- 基础链路不回退。 -- 每个增强点都有至少一个可验证入口。 -- 缺少可选依赖时有降级策略。 -- README 能指导新用户运行进阶版。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/12_future_extensions.md b/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/12_future_extensions.md deleted file mode 100644 index 31e2ade..0000000 --- a/docs/reproduction/vibe-coding-reproduce-upgrade/prompts/12_future_extensions.md +++ /dev/null @@ -1,105 +0,0 @@ -# Prompt 12: 后续扩展路线 - -复制下面整段给 Codex 使用。 - -```text -继续上一轮。现在请基于 QueryForge 进阶版,整理后续扩展路线。 - -本轮目标: - -不要写代码。请从原 Datus-Agent 项目中继续提炼值得学习的 LLM Agent 功能,形成下一阶段路线图。 - -已完成能力假设: - -- 多 LLM provider -- Skills -- DateParserNode -- Plan Mode -- ReflectNode -- FixNode retry -- SQL history cache -- LanceDB vector KB -- Visualization -- Logging -- API / MCP / Gateway - -请分析还能继续补充哪些功能,并按优先级排序。 - -候选方向: - -1. Agentic tool loop - - 让模型可以多轮调用 list_tables、describe_table、execute_sql preview。 - - 对比现在的一次性 prompt 生成 SQL。 - -2. Parallel + Selection - - 并行生成多个 SQL 候选。 - - 执行或评估后选择最优。 - -3. ReasoningNode - - 输出推理过程。 - - 与 GenSqlNode 分离。 - -4. MetricToSQL - - 支持业务指标定义。 - - search_metrics -> date_parser -> gen_sql。 - -5. Semantic Model - - 业务实体、字段别名、指标口径。 - - 用于减少字段误用。 - -6. Subject Tree / scoped context - - 按主题管理知识。 - - 限制检索范围。 - -7. Subagent - - 面向某个领域的定制 Agent。 - - 包含固定 skills、schema scope、model、workflow。 - -8. Conversation memory - - 多轮追问。 - - “刚才那个结果按月份拆一下”。 - -9. Streaming output - - 节点级进度。 - - LLM token streaming。 - -10. 权限与安全 - - 表级白名单。 - - SQL AST 检查。 - - 审计日志。 - -11. 更完整 MCP - - resources - - prompts - - tools - - session state - -12. Dashboard / Report artifact - - 从单次图表升级为报告和 dashboard。 - -输出要求: - -1. 给出下一阶段路线图。 -2. 每个功能说明: - - 为什么值得做。 - - 依赖哪些已有能力。 - - MVP 版本怎么做。 - - 不建议一开始做哪些复杂部分。 - - 验收标准。 -3. 给出推荐顺序。 -4. 给出风险清单。 -5. 给出可以继续拆成 prompts 的文件清单。 - -限制: - -- 不要写代码。 -- 不要把所有功能都标成最高优先级。 -- 不要脱离 QueryForge 当前架构。 -- 不要为了追求完整而牺牲可运行性。 - -验收标准: - -- 输出能作为下一批 prompt 文件夹的规划。 -- 能清晰区分“高学习价值”和“工程复杂但非必要”。 -- 能继续沿用增量升级思路。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce-upgrade/upgrade_workflow_map.md b/docs/reproduction/vibe-coding-reproduce-upgrade/upgrade_workflow_map.md deleted file mode 100644 index e328972..0000000 --- a/docs/reproduction/vibe-coding-reproduce-upgrade/upgrade_workflow_map.md +++ /dev/null @@ -1,112 +0,0 @@ -# 进阶 Workflow 映射图 - -## 基础版 - -```text -User - -> CLI - -> WorkflowRunner - -> Workflow - -> SchemaLinkingNode - -> GenSqlNode - -> ExecuteSqlNode - -> OutputNode -``` - -## 进阶版目标 - -```text -User - -> CLI / API / MCP / Gateway - -> WorkflowRunner - -> optional PlanModeNode - -> optional DateParserNode - -> SchemaLinkingNode - -> GenSqlNode - | uses: - | - selected LLM provider - | - available skills context - | - schema context - | - SQL history cache - | - optional LanceDB retrieval - -> ExecuteSqlNode - -> ReflectNode - | strategy: - | - SUCCESS -> OutputNode - | - FIX_SQL -> FixNode -> ExecuteSqlNode - | - REGENERATE -> GenSqlNode - | - NEED_USER_REVIEW -> stop with message - -> OutputNode - -> optional VisualizationNode - -> SQLHistoryStore -``` - -## 原项目能力对应 - -| 原项目能力 | 进阶复现对应 | 复现深度 | -| --- | --- | --- | -| `LLMBaseModel` + 多 provider | `models/` 下 provider adapter + factory | 中等 | -| `SkillManager` / `SkillRegistry` | 本地 `skills/` 目录 + metadata + prompt 注入 | 中等 | -| `ReflectNode` | 执行后 LLM 评估 + strategy | 中等 | -| `DateParserNode` | 规则优先 + LLM fallback 的日期上下文 | 中等 | -| `FixNode` | SQL 执行失败后自动修复重试 | 中等 | -| `Plan Mode` | 先输出执行计划,用户确认后运行 | 简化 | -| `Reference SQL RAG` | SQLite 历史 SQL 缓存 | 简化 | -| `LanceDB` | 可选向量检索历史 SQL / schema docs | 简化到中等 | -| `API` | FastAPI chat endpoint | 简化 | -| `MCP` | 暴露 ask_sql/list_tools 等工具 | 简化 | -| `Gateway` | HTTP webhook adapter | 简化 | - -## 控制流重点 - -基础版 workflow 是线性的。进阶版开始出现两类控制流: - -1. 前置增强节点 - - PlanModeNode - - DateParserNode - -2. 后置反馈节点 - - ReflectNode - - FixNode - -建议先让 workflow 支持“插入节点”和“重试循环”,但不要实现复杂 DAG。最小可用策略: - -```text -max_retries = 2 -run nodes in order -if execute_sql fails: - run FixNode - retry ExecuteSqlNode -if execute_sql succeeds: - run ReflectNode - if strategy == SUCCESS: - continue - if strategy == FIX_SQL and retry_count < max_retries: - run FixNode - retry ExecuteSqlNode - if strategy == REGENERATE and retry_count < max_retries: - run GenSqlNode - retry ExecuteSqlNode - else: - stop with clear error -``` - -## 数据流新增字段 - -进阶版 Context 建议新增: - -```text -plan -plan_approved -date_context -skills_context -selected_model -history_matches -vector_matches -reflection_result -fix_attempts -visualization -run_logs -``` - -这些字段足以承载进阶能力,不需要照搬原项目全部 schema。 diff --git a/docs/reproduction/vibe-coding-reproduce/00_README.md b/docs/reproduction/vibe-coding-reproduce/00_README.md deleted file mode 100644 index 1a7300f..0000000 --- a/docs/reproduction/vibe-coding-reproduce/00_README.md +++ /dev/null @@ -1,122 +0,0 @@ -# Datus-Agent MVP 复现 Prompts 交付物 - -这个文件夹是一套面向 vibe coding 的复现指引。目标不是完整重建 Datus-Agent,而是把它最核心、最有代表性的主功能提炼成一个低门槛 MVP:用户输入自然语言问题,程序识别相关数据表,调用 LLM 生成 SQL,执行 SQL,并返回 SQL、解释和结果。 - -## 如何使用 - -按顺序把 `prompts/` 下的文件逐个复制给 Codex。每一轮只推进一个阶段,不要跳步。每轮结束后,把 Codex 的输出保留在当前对话里,下一轮 prompt 会显式要求 Codex 基于上一轮结果继续。 - -建议顺序: - -1. `prompts/01_core_function_analysis.md` -2. `prompts/02_minimal_design.md` -3. `prompts/03_init_project.md` -4. `prompts/04_core_development.md` -5. `prompts/05_integration_validation.md` -6. `prompts/06_fix_and_wrap_up.md` - -辅助阅读: - -- `workflow_overview.md`:用图说明原项目 workflow 和 MVP workflow 的对应关系。 -- 根目录 `sample_data/anime_streaming/README.md`:说明当前项目统一维护的示例数据、表结构和推荐测试问题。 - -## 为什么这样拆分 - -Datus-Agent 原项目很大,包含 CLI、Web、API、MCP、Gateway、多模型适配、RAG 知识库、多数据库连接器、工作流编排、节点系统、工具系统、权限、观测和插件等能力。直接让 Codex “复刻整个项目”会导致范围失控、实现路线发散、依赖过多。 - -这套 prompt 按软件实现路径拆成六步: - -1. 先让 Codex 识别项目核心,避免把非核心功能带进 MVP。 -2. 再确定最小方案,把复杂架构压缩成可运行主链路。 -3. 初始化目录和配置,让后续开发有稳定落点。 -4. 开发核心模块,只实现 workflow、node、LLM、DB tool、SQLite connector。 -5. 做端到端联调,确保自然语言到 SQL 的完整闭环能跑通。 -6. 处理常见问题,收尾成一个可交付、可演示、可继续扩展的最小版本。 - -## 被认定为项目主要功能的内容 - -主要功能是“自然语言转 SQL 的智能数据库代理”。对应原项目中的核心链路是: - -```text -用户问题 - -> WorkflowRunner 创建 Workflow - -> Workflow 按顺序执行 Node - -> SchemaLinkingNode 找到相关表结构 - -> GenSQLAgenticNode / GenSqlNode 调用 LLM 生成 SQL - -> ExecuteSQLNode 执行 SQL - -> OutputNode 整理输出 -``` - -MVP 必须保留的模块: - -- CLI 入口:接收用户问题和数据库路径。 -- WorkflowRunner:负责创建并启动 workflow。 -- Workflow:保存上下文,按顺序推进节点。 -- Node 体系:统一节点接口,至少包含 schema linking、SQL generation、SQL execution、output。 -- LLM 层:封装一次文本生成调用。 -- 数据库工具层:提供 list tables、describe table、execute SQL。 -- SQLite connector:用最少依赖完成真实数据库查询。 -- Context 数据模型:承接节点之间的数据流。 - -## 被刻意省略的内容 - -这些内容在原项目中重要,但不是最小复现主功能所必需: - -| 省略内容 | 省略原因 | -| --- | --- | -| Web / REST API / MCP / 飞书 Slack Gateway | 多端入口会增加大量框架代码,CLI 足够验证主链路 | -| LanceDB 和 7 层 RAG 知识库 | 需要向量库、embedding、索引构建,MVP 可用全表 schema fallback 代替 | -| 多数据库适配器 | SQLite 内置、零服务依赖,足够演示 SQL 生成和执行 | -| 多模型 provider 和 LiteLLM 适配 | MVP 只保留一个 OpenAI-compatible 调用入口 | -| OpenAI Agents SDK tool loop | 原项目核心但实现复杂,MVP 用“schema 入 prompt + 生成 JSON SQL”复现主要效果 | -| 并行、反思、自动修复、selection | 属于准确率增强功能,先保证主链路可运行 | -| 权限、审计、观测、trace、checkpoint | 工程化能力,不影响最小主功能复现 | -| Subject Tree、RAGScope、Subagent | 领域化和上下文隔离能力,MVP 阶段不引入 | - -## 最终 MVP 预期效果 - -使用者跟随 prompts 与 Codex 连续交互后,应得到一个 `QueryForge` 项目。它能完成: - -```bash -python main.py \ - --database sample_data/anime_streaming/anime_streaming.sqlite \ - --question "What is the phone number of the anime with the highest total watch time?" -``` - -预期输出包含: - -- 用户问题 -- 识别到的表结构摘要 -- LLM 生成的 SQL -- SQL 解释 -- 查询结果表格或 JSON -- 出错时的清晰错误信息 - -## 示例数据 - -复现资料本身不再重复打包样例数据。当前项目统一使用根目录下的 `anime_streaming` 示例数据: - -```text -sample_data/anime_streaming/ - anime_streaming.sqlite - tables/*.csv - success_story.csv - reference_sql/ - reference_template/ -``` - -基础版复现项目应优先使用 `anime_streaming.sqlite` 做试运行,而不是只创建临时的 users/anime/watch sessions mock 数据。这样可以更接近原项目的真实 SQL 生成场景,包括多表 join、带空格的字段名、指标口径和参考 SQL。 - -## 与原项目的关键对应关系 - -| 原项目模块 | MVP 对应模块 | 保留的思想 | -| --- | --- | --- | -| `datus/cli/main.py` | `main.py` | CLI 作为最小入口 | -| `datus/agent/workflow_runner.py` | `agent/workflow_runner.py` | 负责 workflow 生命周期 | -| `datus/agent/workflow.py` | `agent/workflow.py` | 保存 context 并推进节点 | -| `datus/agent/node/*` | `agent/node/*` | 节点化执行单元 | -| `datus/tools/func_tool/database.py` | `tools/database_tool.py` | 数据库工具供生成与执行使用 | -| `datus/models/*` | `models/llm.py` | 封装模型调用 | -| `datus/storage/schema_metadata/*` | schema fallback | 为 SQL 生成提供表结构上下文 | - -这套交付物强调可执行性和最简单复现路径。prompt 本身不直接贴实现代码,而是提供足够具体的结构、接口、流程、限制和验收标准,让 Codex 在每一轮中生成或修改代码。 diff --git a/docs/reproduction/vibe-coding-reproduce/prompts/01_core_function_analysis.md b/docs/reproduction/vibe-coding-reproduce/prompts/01_core_function_analysis.md deleted file mode 100644 index 68b2e1b..0000000 --- a/docs/reproduction/vibe-coding-reproduce/prompts/01_core_function_analysis.md +++ /dev/null @@ -1,89 +0,0 @@ -# Prompt 01: 项目核心功能识别 - -复制下面整段给 Codex 使用。 - -```text -你现在是我的代码复现助手。我要基于一个名为 Datus-Agent 的项目做 MVP 复现。请先不要写代码,本轮只做核心功能识别和复现范围收敛。 - -项目背景: - -Datus-Agent 是一个 AI-powered SQL Agent。它的核心用户体验是:用户用自然语言提问,系统理解问题和数据库结构,生成 SQL,执行 SQL,并把结果返回给用户。 - -原项目包含这些主要部分: - -1. 多端入口 - - CLI - - Web - - REST API - - MCP Server - - 飞书/Slack Gateway - -2. Agent 与 workflow - - Agent 接收用户任务 - - WorkflowRunner 创建并执行 workflow - - Workflow 保存 Context,并按顺序推进 Node - - 默认 fixed workflow 是: - schema_linking -> gen_sql -> execute_sql -> output - - 其他增强 workflow 包含 reflect、date_parser、search_metrics、parallel、selection 等 - -3. Node 体系 - - SchemaLinkingNode:根据用户问题找到相关表结构 - - GenSQLAgenticNode:基于问题和 schema 生成 SQL - - ExecuteSQLNode:执行 SQL - - OutputNode:格式化最终输出 - - FixNode / ReflectNode / ReasoningNode 等用于增强准确率 - -4. LLM 层 - - 原项目支持多个供应商,例如 OpenAI、Claude、Gemini、DeepSeek、Qwen、Kimi - - 通过统一模型抽象和 LiteLLM / OpenAI Agents SDK 等方式调用模型 - -5. 工具系统 - - 数据库工具:list_tables、describe_table、execute_sql 等 - - 语义工具、指标工具、文档搜索工具、MCP 工具、Bash 工具等 - -6. RAG 与知识库 - - Schema Metadata - - Reference SQL - - Semantic Model - - Metric - - Document - - Reference Template - - Subject Tree - -7. 数据库适配 - - 支持 SQLite、DuckDB、PostgreSQL、MySQL、Snowflake、ClickHouse 等 - -本次目标: - -我不是要完整复刻整个项目,而是要做一个最小可复现版本,让不了解原项目的人也能通过代码理解它的主链路。 - -请你完成以下分析: - -1. 用一句话定义 Datus-Agent 的核心价值。 -2. 识别最关键用户流程,并用步骤表示。 -3. 从原项目中提炼必须保留的 MVP 模块。 -4. 明确哪些模块应该省略,并解释为什么省略。 -5. 给出 MVP 的边界:它必须能做什么,明确不做什么。 -6. 输出一个“原项目模块 -> MVP 模块”的对应表。 - -输入限制: - -- 你只能基于上面的项目描述分析。 -- 不要写代码。 -- 不要设计复杂基础设施。 -- 不要引入 Web、API、MCP、向量数据库、多数据库、多模型 provider。 - -预期输出: - -- 一份结构化分析文档。 -- 结论必须收敛到一个简单 MVP:CLI + Workflow + 4 个核心节点 + LLM 调用 + SQLite 数据库工具。 -- 最后给出“下一轮设计应该围绕哪些模块展开”的清单,供我复制到下一轮 prompt 使用。 - -验收标准: - -- 能准确识别自然语言转 SQL 是项目主功能。 -- 能把 fixed workflow 识别为 MVP 主流程。 -- 能明确保留 schema_linking、gen_sql、execute_sql、output。 -- 能明确省略非核心增强能力,并说明省略原因。 -- 输出内容可以直接作为下一轮最小实现方案设计的上下文。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce/prompts/02_minimal_design.md b/docs/reproduction/vibe-coding-reproduce/prompts/02_minimal_design.md deleted file mode 100644 index 1bba396..0000000 --- a/docs/reproduction/vibe-coding-reproduce/prompts/02_minimal_design.md +++ /dev/null @@ -1,108 +0,0 @@ -# Prompt 02: 最小实现方案设计 - -复制下面整段给 Codex 使用。使用前请确保上一轮已经得到“核心功能识别”的结论。 - -```text -继续上一轮。我们已经确认 MVP 目标是复现 Datus-Agent 的主功能:通过 CLI 输入自然语言问题,程序按 workflow 执行 schema linking、SQL generation、SQL execution、output,最终返回 SQL 和查询结果。 - -本轮请只做最小实现方案设计,不要写代码。 - -上一轮结论摘要: - -- 核心价值:自然语言转 SQL,并执行查询。 -- MVP 主流程:用户问题 -> schema_linking -> gen_sql -> execute_sql -> output。 -- 保留模块:CLI、WorkflowRunner、Workflow、Node 基类、4 个核心节点、Context 数据模型、LLM 调用层、数据库工具、SQLite connector。 -- 省略模块:Web、REST API、MCP、Gateway、向量数据库、RAG 七层知识库、多模型 provider、多数据库适配、权限、审计、trace、parallel、selection、reflect、fix、subagent。 - -请设计一个名为 QueryForge 的 MVP 项目。 - -设计要求: - -1. 技术栈 - - Python 3.11 或更高版本 - - SQLite,使用标准库 sqlite3 - - OpenAI-compatible chat completion API - - python-dotenv 用于读取环境变量 - - rich 可选,用于更好地打印表格;如果你认为会增加复杂度,可以不用 - - 尽量少依赖 - -2. 目录结构 - 请给出清晰目录结构,并解释每个文件职责。 - 目录必须至少覆盖: - - CLI 入口 - - config - - schemas / models - - agent/workflow - - agent/workflow_runner - - agent/node - - models/llm - - tools/database_tool - - db/sqlite_connector - - sample database 初始化或说明 - -3. 数据模型 - 请描述这些模型的字段和用途,不要写代码: - - SqlTask:表示一次用户查询任务 - - Context:节点间共享状态 - - TableSchema:表结构摘要 - - SQLContext:SQL 生成结果 - - NodeResult:节点执行结果 - -4. 模块接口 - 请描述关键类和方法的职责,不要写代码: - - WorkflowRunner.run(task) - - Workflow.run() - - Node.execute(context) - - SchemaLinkingNode.execute(context) - - GenSqlNode.execute(context) - - ExecuteSqlNode.execute(context) - - OutputNode.execute(context) - - LLM.generate(messages or prompt) - - SQLiteConnector.list_tables() - - SQLiteConnector.describe_table(table) - - SQLiteConnector.execute_sql(sql) - - DatabaseTool 的只读 SQL 防护 - -5. Workflow 设计 - 请用 ASCII 图画出 MVP workflow。 - 同时说明 Context 在每个节点后的状态变化。 - -6. Prompt 设计 - 请描述 GenSqlNode 给 LLM 的 prompt 应包含哪些信息: - - 角色 - - 用户问题 - - 可用表结构 - - SQL 方言为 SQLite - - 只能输出 SELECT 查询 - - 输出格式必须是 JSON,包含 sql、explanation、tables_used - -7. 错误处理 - 请设计最小错误处理策略: - - 没有 API key - - 数据库文件不存在 - - 没有表 - - LLM 输出不是 JSON - - SQL 不是 SELECT - - SQL 执行失败 - -限制条件: - -- 不写代码。 -- 不设计自动修复、反思、多轮 tool calling。 -- 不加入向量数据库或 embedding。 -- 不做多 datasource 管理。 -- 不做复杂配置系统。 - -预期输出: - -- 一份 MVP 技术设计文档。 -- 包含目录结构、模块职责、数据模型、接口说明、workflow 图、错误处理策略。 -- 最后输出“下一轮初始化项目时需要创建的文件清单”。 - -验收标准: - -- 设计足够简单,Codex 下一轮可以直接按它初始化项目。 -- 每个模块都有明确职责,且不重叠。 -- workflow 和 Context 数据流讲清楚。 -- 没有把原项目的非核心工程化能力带入 MVP。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce/prompts/03_init_project.md b/docs/reproduction/vibe-coding-reproduce/prompts/03_init_project.md deleted file mode 100644 index ac05d51..0000000 --- a/docs/reproduction/vibe-coding-reproduce/prompts/03_init_project.md +++ /dev/null @@ -1,152 +0,0 @@ -# Prompt 03: 技术栈与目录结构初始化 - -复制下面整段给 Codex 使用。使用前请确保上一轮已经产出 MVP 技术设计。 - -```text -继续上一轮。现在请开始初始化 QueryForge 项目。 - -本轮目标: - -只创建项目骨架、基础配置、数据模型、CLI 入口和可运行的空 workflow。不要实现 LLM 生成 SQL 和真实数据库逻辑,这些放到下一轮。 - -项目目标回顾: - -- 复现 Datus-Agent 的最小主链路。 -- 主流程是:CLI -> WorkflowRunner -> Workflow -> schema_linking -> gen_sql -> execute_sql -> output。 -- 本轮只搭骨架,确保项目可以启动,并能打印“workflow 尚未实现或 mock 结果”之类的占位输出。 - -请创建一个目录 `QueryForge/`,建议结构如下: - -```text -QueryForge/ - README.md - requirements.txt - .env.example - main.py - config.py - schemas/ - __init__.py - models.py - agent/ - __init__.py - workflow.py - workflow_runner.py - node/ - __init__.py - base.py - schema_linking_node.py - gen_sql_node.py - execute_sql_node.py - output_node.py - models/ - __init__.py - llm.py - tools/ - __init__.py - database_tool.py - db/ - __init__.py - sqlite_connector.py - sample_data/ - anime_streaming/ - README.md - anime_streaming.sqlite - tables/*.csv - success_story.csv - reference_sql/ - reference_template/ - sample/ - prepare_sample_data.py -``` - -你可以根据上一轮设计做少量调整,但必须解释原因。 - -本轮需要完成的内容: - -1. `requirements.txt` - - 只列必要依赖。 - - 必须包含 openai、python-dotenv、pydantic。 - - 如果使用 rich,也说明它只是显示增强,不是核心依赖。 - -2. `.env.example` - - 包含 OPENAI_API_KEY。 - - 包含 OPENAI_MODEL,给出默认模型名。 - - 包含 DATABASE_PATH,默认指向 sample_data/anime_streaming/anime_streaming.sqlite。 - - 不要创建真实 `.env`,避免写入敏感信息。 - -3. `config.py` - - 读取环境变量。 - - 提供一个简单配置对象或字典。 - - 对缺失 API key 不要在导入阶段报错,应在运行阶段给出清晰提示。 - -4. `schemas/models.py` - - 定义 SqlTask、Context、TableSchema、SQLContext、NodeResult。 - - 字段要足够支撑后续四个节点的数据传递。 - - 注意避免 Python 可变默认值问题。 - -5. `agent/node/base.py` - - 定义 Node 基类。 - - 定义统一 execute(context) 接口。 - - 定义 node name / description / status 等最小元信息。 - -6. 四个节点文件 - - 先写成可运行的占位实现。 - - 每个节点都接收 Context,返回 NodeResult。 - - 每个节点都明确自己将来要读写 Context 的哪些字段。 - -7. `agent/workflow.py` - - 支持按固定顺序执行节点。 - - 执行失败时停止并返回错误。 - - 成功时返回 Context 中的 final_output。 - -8. `agent/workflow_runner.py` - - 接收 config。 - - 创建 SqlTask 对应的 Workflow。 - - 按固定顺序装配四个节点。 - -9. `main.py` - - 使用 argparse。 - - 支持参数: - - `--question` - - `--database` - - `--show-workflow` - - 能启动 WorkflowRunner。 - -10. `sample_data/anime_streaming/` - - 从本 prompt 文件夹的 `sample_data/anime_streaming/` 复制到 `QueryForge/sample_data/anime_streaming/`。 - - 这套数据来自QueryForge 专门生成的动漫平台场景,包含 `anime_streaming.sqlite`、CSV、参考 SQL、参考模板和 success story。 - - 本轮只要求复制并在 README 中说明,不需要重新生成数据库。 - -11. `sample/prepare_sample_data.py` - - 提供一个轻量脚本,检查 bundled sample data 是否存在。 - - 如果目标路径没有 `anime_streaming.sqlite`,提示用户从 prompt 交付物复制。 - - 不要再默认创建 users/anime/watch sessions 这种临时 mock 数据。 - -输出要求: - -- 请直接创建或修改文件。 -- 不要只给建议。 -- 不要实现复杂业务逻辑。 -- 完成后说明你创建了哪些文件,每个文件现在的职责是什么。 -- 给出本轮验证命令。 - -限制条件: - -- 不实现真实 LLM 调用。 -- 不执行真实 SQL。 -- 不引入 Web/API/MCP。 -- 不引入向量库。 -- 不写过度抽象的插件系统或注册系统。 - -验收标准: - -- `python main.py --show-workflow --question "What is the phone number of the anime with the highest total watch time?"` 可以运行。 -- 程序能展示固定 workflow 顺序。 -- 程序能返回一个明确的占位 final output 或未实现提示。 -- 项目中包含 `sample_data/anime_streaming/anime_streaming.sqlite` 或清晰说明如何从交付物复制。 -- 项目结构清晰,下一轮可以直接补数据库、LLM 和节点逻辑。 - -下一轮衔接: - -完成后,请在回复最后列出“核心功能开发待办清单”,至少包含 SQLite connector、DatabaseTool、SchemaLinkingNode、GenSqlNode、ExecuteSqlNode、OutputNode。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce/prompts/04_core_development.md b/docs/reproduction/vibe-coding-reproduce/prompts/04_core_development.md deleted file mode 100644 index 54879cb..0000000 --- a/docs/reproduction/vibe-coding-reproduce/prompts/04_core_development.md +++ /dev/null @@ -1,156 +0,0 @@ -# Prompt 04: 核心功能开发 - -复制下面整段给 Codex 使用。使用前请确保上一轮已经创建 `QueryForge/` 项目骨架。 - -```text -继续上一轮。现在请在已有 QueryForge 项目中实现核心功能。 - -本轮目标: - -把占位 workflow 变成可运行的自然语言转 SQL 主链路。实现范围严格限制为: - -CLI 输入自然语言问题 - -> WorkflowRunner 创建固定 workflow - -> SchemaLinkingNode 获取数据库表结构 - -> GenSqlNode 调用 LLM 生成 SQLite SELECT SQL - -> ExecuteSqlNode 执行 SQL - -> OutputNode 返回 SQL、解释、结果 - -请先读取当前项目文件,再修改。不要重新生成整个项目。 - -实现要求: - -1. SQLiteConnector - 文件:`db/sqlite_connector.py` - 职责: - - 连接 SQLite 文件。 - - 判断数据库文件是否存在。 - - 列出用户表,排除 sqlite 内部表。 - - 获取指定表的字段名、类型、是否主键、是否可空。 - - 执行 SQL 并返回 columns + rows。 - - 对执行异常返回清晰错误,不要吞掉异常。 - -2. DatabaseTool - 文件:`tools/database_tool.py` - 职责: - - 包装 SQLiteConnector。 - - 提供 list_tables、describe_table、execute_sql。 - - execute_sql 必须只允许只读查询。 - - 对空 SQL、非 SELECT、包含多语句或明显 DDL/DML 的 SQL 给出错误。 - - 只读防护可以简单直接,不需要做完整 SQL parser。 - -3. 原项目 sample database - 文件:`sample/prepare_sample_data.py` - 职责: - - 使用随 prompts 交付物打包的 `sample_data/anime_streaming/anime_streaming.sqlite`。 - - 不要再创建 users/anime/watch sessions 临时 mock 数据作为主样例。 - - 检查 `sample_data/anime_streaming/anime_streaming.sqlite` 是否存在。 - - 检查数据库中至少包含 `dim_anime`、`fact_subscription`、`fact_rating` 三张表。 - - 检查 reference SQL 和 success story 文件是否存在。 - - 如果样例数据缺失,输出清晰提示:从项目根目录 `sample_data/anime_streaming/` 检查或恢复。 - - 数据要能支持几个原项目测试问题,例如: - - What is the highest eligible free rate for K-12 students in the dim_anime in Alameda County? - - Please list the lowest three eligible free rates for students aged 5-17 in continuation dim_anime. - - What is the phone number of the anime with the highest total watch time? - -4. LLM 层 - 文件:`models/llm.py` - 职责: - - 封装 OpenAI-compatible chat completion。 - - 从 config 读取 api key、model。 - - 提供一个 generate_json(prompt) 或等价方法。 - - 要求模型输出 JSON,但仍要处理模型返回 markdown code fence、前后多余文本等情况。 - - 如果没有 OPENAI_API_KEY,要返回清晰错误,不能抛出难懂堆栈。 - -5. SchemaLinkingNode - 文件:`agent/node/schema_linking_node.py` - 职责: - - 调用 DatabaseTool 获取表列表和表结构。 - - MVP 不做向量检索,先把所有表结构放入 Context。 - - 可以做一个非常简单的关键词过滤,但必须保证找不到关键词时 fallback 到所有表。 - - 输出写入 context.relevant_tables。 - -6. GenSqlNode - 文件:`agent/node/gen_sql_node.py` - 职责: - - 读取 context.sql_task.question 和 context.relevant_tables。 - - 构造 LLM prompt。 - - prompt 必须说明: - - 你是 SQLite SQL 专家。 - - 只能生成 SELECT 查询。 - - 只能使用给定表和字段。 - - 不要编造表名和字段名。 - - 输出 JSON,字段为 sql、explanation、tables_used。 - - 解析 LLM 输出为 SQLContext。 - - 如果解析失败,要返回 NodeResult failure,并提示原始模型输出。 - -7. ExecuteSqlNode - 文件:`agent/node/execute_sql_node.py` - 职责: - - 读取最后一个 SQLContext。 - - 调用 DatabaseTool.execute_sql。 - - 写入 context.execution_result。 - - 执行失败时返回失败结果,让 Workflow 停止。 - -8. OutputNode - 文件:`agent/node/output_node.py` - 职责: - - 整理最终输出。 - - 至少包含 question、sql、explanation、tables_used、columns、rows、row_count。 - - 控制输出格式,保证 CLI 易读。 - -9. Workflow / WorkflowRunner - 文件: - - `agent/workflow.py` - - `agent/workflow_runner.py` - 职责: - - 确保四个节点按固定顺序执行。 - - 每个节点执行前后可以打印简短阶段信息。 - - 任一节点失败时停止,并输出失败节点、错误原因、已生成的上下文摘要。 - -10. CLI - 文件:`main.py` - 职责: - - 支持 `--question`、`--database`、`--prepare-sample-data`、`--show-workflow`。 - - `--prepare-sample-data` 会检查 bundled sample data 是否可用后退出。 - - `--database` 默认指向 `sample_data/anime_streaming/anime_streaming.sqlite`。 - - 正常运行时校验数据库路径存在。 - - 打印最终结果。 - -限制条件: - -- 不实现 Web、API、MCP。 -- 不实现 RAG、embedding、LanceDB。 -- 不实现多数据库。 -- 不实现多模型 provider。 -- 不实现自动修复、反思、并行、selection。 -- 不引入复杂依赖。 -- 不把 prompt 写死成只适配 sample database;它应该能读取任意 SQLite 表结构。 - -输出要求: - -- 直接修改项目文件。 -- 不要只输出设计。 -- 修改完成后,列出变更文件和每个文件的作用。 -- 给出运行验证命令。 -- 如果你发现上一轮骨架有不合理之处,可以小范围调整,但必须说明调整原因。 - -验收标准: - -1. 可以初始化示例库: - `python main.py --prepare-sample-data` - -2. 可以查看 workflow: - `python main.py --show-workflow --question "What is the phone number of the anime with the highest total watch time?"` - -3. 设置 OPENAI_API_KEY 后可以运行: - `python main.py --database sample_data/anime_streaming/anime_streaming.sqlite --question "What is the phone number of the anime with the highest total watch time?"` - -4. 输出中必须包含: - - 生成 SQL - - SQL 解释 - - 查询结果 rows - - row_count - -5. 对危险 SQL 或执行错误有清晰错误提示。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce/prompts/05_integration_validation.md b/docs/reproduction/vibe-coding-reproduce/prompts/05_integration_validation.md deleted file mode 100644 index 0b0d9ee..0000000 --- a/docs/reproduction/vibe-coding-reproduce/prompts/05_integration_validation.md +++ /dev/null @@ -1,103 +0,0 @@ -# Prompt 05: 基础联调与运行验证 - -复制下面整段给 Codex 使用。使用前请确保上一轮已经实现核心功能。 - -```text -继续上一轮。现在请对 QueryForge 做基础联调和运行验证。 - -本轮目标: - -不要新增大功能。请验证现有 MVP 是否真的完成了主链路: - -自然语言问题 -> schema linking -> SQL generation -> SQL execution -> output - -请先读取当前项目文件,然后按下面顺序检查、运行、修复。 - -验证任务: - -1. 静态检查 - - 检查目录结构是否符合 MVP 设计。 - - 检查是否存在不必要的复杂功能,例如 Web、API、MCP、向量库、多数据库管理。 - - 检查所有 import 是否正确。 - - 检查数据模型是否存在可变默认值问题。 - -2. sample database 验证 - - 运行 sample database 检查命令。 - - 确认 `sample_data/anime_streaming/anime_streaming.sqlite` 存在。 - - 用 sqlite3 或 Python 验证至少有 `dim_anime`、`fact_subscription`、`fact_rating` 三张表。 - - 验证每张表都有示例数据。 - - 验证 `sample_data/anime_streaming/reference_sql/` 和 `success_story.csv` 存在。 - -3. 数据库工具验证 - - 验证 list_tables 能返回表名。 - - 验证 describe_table 能返回字段结构。 - - 验证 execute_sql 能执行 SELECT。 - - 验证 execute_sql 会拒绝 INSERT、UPDATE、DELETE、DROP、CREATE、多语句 SQL。 - -4. workflow 验证 - - 运行 `--show-workflow`,确认节点顺序是: - schema_linking -> gen_sql -> execute_sql -> output - - 检查每个节点是否只读写自己负责的 Context 字段。 - - 检查任一节点失败时 workflow 是否停止,并输出清晰错误。 - -5. LLM 输出解析验证 - - 检查 GenSqlNode 能解析纯 JSON。 - - 检查 GenSqlNode 能解析包在 markdown code fence 中的 JSON。 - - 检查解析失败时错误信息包含原始模型输出摘要。 - -6. 端到端验证 - 在设置 OPENAI_API_KEY 后,至少尝试这些问题: - - What is the highest eligible free rate for K-12 students in the dim_anime in Alameda County? - - Please list the lowest three eligible free rates for students aged 5-17 in continuation dim_anime. - - What is the phone number of the anime with the highest total watch time? - - 每次输出都应包含: - - question - - relevant tables - - sql - - explanation - - rows - - row_count - -7. 无 API key 降级验证 - - 未设置 OPENAI_API_KEY 时,程序应给出清晰提示。 - - 不应出现难懂堆栈。 - -允许修改: - -- 可以修复 bug。 -- 可以补充最小测试脚本或简单 pytest。 -- 可以改善错误信息。 -- 可以调整 README 的运行说明。 - -不允许修改: - -- 不要新增 Web/API/MCP。 -- 不要引入向量数据库。 -- 不要加入自动修复或反思节点。 -- 不要把 sample database 的表名硬编码进 SQL 生成逻辑。 -- 不要大规模重构项目结构。 - -输出要求: - -1. 先给出验证计划。 -2. 执行验证命令。 -3. 如果失败,定位原因并做最小修复。 -4. 最后输出验证报告,包含: - - 运行过的命令 - - 通过项 - - 修复项 - - 仍存在的限制 - - 下一轮收尾建议 - -验收标准: - -- sample database 能成功检查并用于查询。 -- sample database 使用原项目 `anime_streaming` 数据,而不是临时 mock 数据。 -- 数据库工具能独立工作。 -- workflow 顺序正确。 -- 主链路能在有 API key 时跑通。 -- 没有 API key 时错误提示友好。 -- 危险 SQL 被拒绝。 -- 输出能让用户看懂 SQL、解释和结果。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce/prompts/06_fix_and_wrap_up.md b/docs/reproduction/vibe-coding-reproduce/prompts/06_fix_and_wrap_up.md deleted file mode 100644 index aee30c8..0000000 --- a/docs/reproduction/vibe-coding-reproduce/prompts/06_fix_and_wrap_up.md +++ /dev/null @@ -1,92 +0,0 @@ -# Prompt 06: 常见问题修复与收尾 - -复制下面整段给 Codex 使用。使用前请确保上一轮已经完成基础联调。 - -```text -继续上一轮。现在请做 QueryForge 的常见问题修复和交付收尾。 - -本轮目标: - -把 MVP 整理成一个别人可以克隆、配置、运行、理解的最小项目。不要新增非核心功能。 - -请先读取上一轮验证报告和当前代码,然后完成以下工作。 - -常见问题修复清单: - -1. LLM 输出不稳定 - - 如果模型返回 markdown、解释文本、单引号 JSON 或多余前后缀,确保解析逻辑尽量稳健。 - - 如果仍无法解析,错误信息必须告诉用户模型返回了什么摘要,以及期望格式是什么。 - -2. SQL 安全边界 - - 确保只允许单条 SELECT 或 WITH 查询。 - - 拒绝分号拼接多语句。 - - 拒绝常见写操作关键词。 - - 在错误信息中说明 MVP 是只读模式。 - -3. Schema 上下文过长 - - 如果数据库表很多,请加入简单限制,例如最多展示前 N 张表或每张表最多 N 列。 - - 但不要实现向量检索。 - - 超出限制时在 prompt 中提示 schema 被截断。 - -4. CLI 体验 - - 错误信息要清晰。 - - `--help` 要能说明所有参数。 - - `--show-workflow` 要输出节点顺序和每个节点职责。 - -5. README - - 更新 QueryForge 的 README。 - - 必须包含: - - 项目是什么 - - 它复现了 Datus-Agent 的哪些核心思想 - - 安装步骤 - - 配置 `.env` - - 使用已打包的 `anime_streaming` sample database - - 运行示例 - - 常见错误 - - 明确说明省略了哪些原项目功能 - -6. 最小测试 - - 如果项目里已有测试框架,补充最小测试。 - - 如果没有测试框架,可以提供一个 `python` 命令或 `scripts/smoke_test.py` 做 smoke test。 - - 至少覆盖: - - sample database 存在性检查 - - `dim_anime`、`fact_subscription`、`fact_rating` 三张表可读取 - - list_tables - - describe_table - - SELECT 执行 - - 非只读 SQL 被拒绝 - - workflow 在无 API key 时给出友好错误 - -7. 最终项目边界说明 - - 在 README 或回复中明确: - - 这是 MVP,不是生产级 SQL Agent。 - - 它没有 RAG、MCP、多端入口、多数据库、多模型 provider。 - - 它保留的是原项目最核心的 workflow + node + context + tool 思想。 - -限制条件: - -- 不要新增 Web、API、MCP。 -- 不要新增向量库。 -- 不要新增复杂配置。 -- 不要引入 Docker,除非项目已经有明确需要。 -- 不要为了测试引入重型依赖。 -- 不要把代码重写成大型框架。 - -输出要求: - -1. 先列出你发现的问题。 -2. 做最小必要修改。 -3. 给出最终文件结构。 -4. 给出从零运行命令。 -5. 给出最终验收清单。 -6. 说明这个 MVP 与原 Datus-Agent 的对应关系。 - -最终验收标准: - -- 新用户能按 README 在 10 分钟内跑起来。 -- 已打包的 `anime_streaming` sample database 可用于试运行。 -- 至少一个自然语言问题可以端到端返回 SQL 和结果。 -- 无 API key、危险 SQL、数据库缺失等常见问题都有清晰提示。 -- 项目结构仍然简单。 -- README 明确说明复现范围和省略范围。 -``` diff --git a/docs/reproduction/vibe-coding-reproduce/workflow_overview.md b/docs/reproduction/vibe-coding-reproduce/workflow_overview.md deleted file mode 100644 index c1a5167..0000000 --- a/docs/reproduction/vibe-coding-reproduce/workflow_overview.md +++ /dev/null @@ -1,171 +0,0 @@ -# Workflow 图解:从 Datus-Agent 到 MVP - -本文用于帮助使用者理解原项目 workflow,并把它映射到 vibe coding 复现版本。 - -## 原项目核心链路 - -原项目有多个入口,但最终都会进入 Agent / Workflow 层。 - -```text -CLI / Web / API / MCP / Gateway - | - v -Agent - | - v -WorkflowRunner - | - v -generate_workflow(plan_type) - | - v -Workflow(context + node_order + nodes) - | - v -+------------------+ +-----------------+ +------------------+ +-------------+ -| SchemaLinkingNode| ---> | GenSQLAgenticNode| ---> | ExecuteSQLNode | ---> | OutputNode | -+------------------+ +-----------------+ +------------------+ +-------------+ - | | | | - v v v v - table_schemas SQLContext execution_result final_output - table_values sql / explanation rows / columns answer package -``` - -原项目 fixed workflow: - -```text -schema_linking -> gen_sql -> execute_sql -> output -``` - -原项目增强 workflow 示例: - -```text -reflection: -schema_linking -> gen_sql -> execute_sql -> reflect -> output - -metric_to_sql: -schema_linking -> search_metrics -> date_parser -> gen_sql -> execute_sql -> output - -chat_agentic: -chat -> execute_sql -> output -``` - -## MVP 复现链路 - -MVP 只复现 fixed workflow,不复现增强链路。 - -```text -User - | - | natural language question - v -+-------------------+ -| main.py CLI | -| parse args | -+-------------------+ - | - v -+-------------------+ -| WorkflowRunner | -| build SqlTask | -| create connector | -| assemble nodes | -+-------------------+ - | - v -+-------------------+ -| Workflow | -| owns Context | -| runs nodes | -+-------------------+ - | - v -+----------------------+ context.relevant_tables -| SchemaLinkingNode | --------------------------------+ -| list all tables | | -| describe columns | | -+----------------------+ | - | | - v | -+----------------------+ context.sql_contexts | -| GenSqlNode | <-------------------------------+ -| build LLM prompt | -| parse JSON SQL | -+----------------------+ - | - v -+----------------------+ context.execution_result -| ExecuteSqlNode | -| run read-only SQL | -+----------------------+ - | - v -+----------------------+ context.final_output -| OutputNode | -| format result | -+----------------------+ - | - v -CLI output -``` - -## Context 数据流 - -```text -初始 Context - sql_task = { question, database_path } - -SchemaLinkingNode 后 - relevant_tables = [ - { table_name, columns: [{ name, type, nullable, primary_key }] } - ] - -GenSqlNode 后 - sql_contexts = [ - { sql, explanation, tables_used } - ] - -ExecuteSqlNode 后 - execution_result = { - columns, - rows, - row_count - } - -OutputNode 后 - final_output = { - question, - relevant_tables, - sql, - explanation, - tables_used, - columns, - rows, - row_count - } -``` - -## 原项目能力与 MVP 取舍 - -| 原项目能力 | MVP 处理方式 | 原因 | -| --- | --- | --- | -| 多端入口 | 只保留 CLI | 最短路径验证主功能 | -| WorkflowRunner / Workflow | 保留简化版 | 这是项目核心结构 | -| Node 工厂与大量节点 | 保留 4 个核心节点 | fixed workflow 足够复现主链路 | -| Schema Metadata RAG | 直接读取 SQLite schema | 避免向量库和索引构建 | -| GenSQLAgenticNode tool loop | 简化为一次 LLM JSON SQL 生成 | 降低实现难度 | -| DBFuncTool | 简化为 DatabaseTool | 保留数据库工具思想 | -| 多数据库 connector | 只保留 SQLiteConnector | 零服务依赖 | -| Reflect / Fix / Reasoning | 省略 | 准确率增强,不是主链路必需 | -| MCP / Gateway / API | 省略 | 入口增强,不影响核心算法 | - -## 给 Codex 的实现重点 - -实现时不要追求企业级完整度,应优先保证下面四件事: - -1. Context 字段在节点之间清晰传递。 -2. LLM prompt 包含足够 schema 信息,且要求 JSON 输出。 -3. SQL 执行层默认只读。 -4. CLI 能端到端跑通 sample database。 - -一旦这四件事成立,就已经复现了 Datus-Agent 最有代表性的主功能骨架。 diff --git a/docs/semantic_authoring.md b/docs/semantic_authoring.md index d44e0a8..fc370b9 100644 --- a/docs/semantic_authoring.md +++ b/docs/semantic_authoring.md @@ -139,9 +139,6 @@ timezone, attribution window, denominator, late-arriving-data policy, or whether heuristic relationship is analytically valid. Those definitions belong in reviewed metrics, filters, Join Paths, ownership, freshness, and quality contracts. -The provenance used for this implementation is recorded in -[Semantic source inventory](semantic_source_inventory.md). - ## Weekly Drift Monitoring The checked-in [weekly workflow](../.github/workflows/semantic-weekly.yml) runs every diff --git a/docs/semantic_source_inventory.md b/docs/semantic_source_inventory.md deleted file mode 100644 index fea77e1..0000000 --- a/docs/semantic_source_inventory.md +++ /dev/null @@ -1,23 +0,0 @@ -# Semantic Layer Source Inventory - -## Coverage - -- Coverage level: repository-complete for QueryForge's SQLite and data-asset paths. -- Sources checked: semantic schemas and loader, builder, contract validator, asset - pipeline, workflow integration, tests, sample model, CLI, REST, MCP, and docs. -- Missing high-value lanes: production warehouse catalogs, organization-specific - metric dictionaries, and real dashboard definitions are outside this repository. -- Rejected or lower-confidence candidates: query history and LLM-generated SQL are - not treated as canonical semantic evidence. - -## Sources - -| Source | Type | Locator | Permission | Last checked | Supports | Gaps or caveats | Automation eligible | Update boundary | -| --- | --- | --- | --- | --- | --- | --- | --- | --- | -| Semantic schemas and loader | Code | `queryforge/domain/semantic/` | Read/write | 2026-07-24 | Entities, dimensions, metrics, relationships, Join Paths, physical validation | SQLite only | Yes | Update with tests | -| Semantic builder | Code | `queryforge/domain/semantic/builder.py` | Read/write | 2026-07-24 | Inference, curated merge, evidence report, atomic model publication | Heuristic metrics require review | Yes | Draft structural improvements; preserve curated definitions | -| Asset pipeline | Code | `queryforge/data_assets/` | Read/write | 2026-07-24 | Upload, quality, lineage, semantic publication | CSV/Parquet/API batch ingestion | Yes | Update with rollback and contract tests | -| Anime semantic model | Maintained contract | `sample_data/anime_streaming/semantic_model.yml` | Read/write | 2026-07-24 | Full worked example with multiple fact grains and business metrics | Synthetic domain | Yes | Preserve reviewed definitions | -| Automated tests | Tests | `tests/test_semantic_builder.py`, `tests/test_data_assets.py`, `tests/test_semantic_model.py` | Read/write | 2026-07-24 | Regression evidence | Does not establish organization-specific business truth | Yes | Update alongside behavior | -| Weekly semantic audit | Automation | `.github/workflows/semantic-weekly.yml`, `scripts/check_semantic_drift.py` | Read/write | 2026-07-24 | Schema, metric, relationship, Join Path, and quality drift | Becomes active after the repository is pushed with GitHub Actions enabled | Yes | Report only; baseline changes require explicit review | -| Query history and reference SQL | Derived evidence | `.queryforge/`, `sample_data/**/reference_sql/` | Local | 2026-07-24 | Query patterns and terminology | Never canonical by itself | No | Supporting evidence only | diff --git a/docs/workflow_comparison.md b/docs/workflow_comparison.md deleted file mode 100644 index a16b85e..0000000 --- a/docs/workflow_comparison.md +++ /dev/null @@ -1,209 +0,0 @@ -# Old and Current Workflow Comparison - -This document compares the original QueryForge MVP workflow with the current -governed analytics workflow. "Old" refers to the fixed MVP described in -`docs/reproduction/vibe-coding-reproduce/`, not the upstream Datus-Agent project. - -## 1. Flow Shape - -### Old MVP - -```text -CLI - -> WorkflowRunner - -> SchemaLinkingNode - -> GenSqlNode - -> ExecuteSqlNode - -> OutputNode -``` - -The workflow had one request type: generate one SQLite `SELECT`, execute it, and -format the result. A node failure stopped the request. - -### Current Workflow - -```text -CLI / REST-SSE / MCP / Gateway - -> AgentService - -> EntryRouterAgent - -> OrchestratorAgent - -> analysis -> candidate -> execution -> completion -> delivery - -> WorkflowRunner / ReflectiveWorkflow -``` - -The SQL execution kernel remains node-based: - -```text -scope -> date/schema/skill/metric context - -> optional Tool Loop or parallel candidates - -> SQL generation - -> Governance - -> DatabaseTool execution - -> reflection / bounded repair - -> output -``` - -The five stages are orchestration state, not five extra model calls. The default -simple path still uses one SQL candidate and two model calls: generation and -reflection. - -## 2. Code Mapping - -| Concern | Old MVP | Current implementation | Behavioral change | -| --- | --- | --- | --- | -| Entry | `main.py` created `WorkflowRunner` directly | `application/agent_service.py` is the shared service facade | All transports use the same service behavior. | -| Request type | One implicit NL2SQL request | `orchestration/agents/entry_router.py` selects task type | Metadata and SQL review do not need to execute generated SQL. | -| Orchestration | Fixed node order in `WorkflowRunner` | `orchestration/orchestrator/orchestrator.py` plus `pipeline_registry.py` | Persisted stage state, artifacts, quality gates, and delivery. | -| SQL loop | One generate/execute/output pass | `workflow/workflow.py:ReflectiveWorkflow` | Bounded reflection, repair, regeneration, Tool Loop, and candidate selection. | -| Schema context | Physical SQLite schema | `SchemaLinkingNode` plus semantic model and Subject Tree | Business names, metrics, Join Paths, grain, and fan-out constraints. | -| Execution | Connector call after basic read-only validation | `ExecuteSqlNode -> DatabaseTool -> SQLiteConnector` | Semantic join guard, policy decision capture, and read-only execution revalidation. | -| Output | SQL, explanation, rows | `OutputNode`, artifacts, report/SSE/MCP adapters | Stable response plus optional audit and delivery outputs. | - -## 3. Router Changes - -### Old behavior - -There was no Router module. Every non-empty CLI question was treated as an analytical -SQL request and entered the fixed workflow. There was no deterministic complexity -profile, request classification, custom task registration, or route-specific direct -path. - -### Current behavior - -`EntryRouterAgent` in -[`queryforge/orchestration/agents/entry_router.py`](../queryforge/orchestration/agents/entry_router.py) -is intentionally isolated from model, connector, `WorkflowRunner`, and SQL tool -dependencies. It cannot generate or execute SQL. - -It performs three tasks: - -1. Classifies requests using deterministic marker rules: - - `ask_sql` - - `sql_review` - - `troubleshoot_sql` - - `metadata_query` - - `explain_result` - - `build_report` - - `unknown` -2. Assigns `simple` or `complex` execution profiles using cross-table, metric, - comparison, ranking, grouping, filtering, request-length, and multi-question - signals. -3. Supports deployment-specific rules through `TaskRoute` and pipeline registration. - -`AgentService._run()` uses the decision to enable expensive mechanisms only when -needed: - -```text -simple -> one candidate, no Tool Loop -complex -> bounded Tool Loop + at least two candidates -``` - -The result is persisted as `routing_decision.json`, returned in `agent_team`, and -used to select one compact stage pipeline: - -| Task type | Pipeline | -| --- | --- | -| `ask_sql`, `troubleshoot_sql`, `explain_result`, `build_report`, `unknown` | `analysis -> candidate -> execution -> completion -> delivery` | -| `sql_review` | `analysis -> candidate -> review -> completion -> delivery` | -| `metadata_query` | `analysis -> delivery` | - -### Why this is different - -The Router is not an LLM planner. It is a cheap, deterministic admission and -execution-profile decision. This prevents simple metadata or review requests from -paying for a full SQL-generation loop, while keeping classification explainable and -testable. - -## 4. Governance Changes - -### Old behavior - -The MVP `DatabaseTool` performed one basic read-only check before calling SQLite. The -original reproduction specification explicitly allowed simple checks for empty SQL, -non-`SELECT`, multiple statements, and obvious DDL/DML. There was no separate -Governance artifact, table/column allowlist, function blacklist, recursive CTE -control, query-shape budget, or candidate-stage decision. - -### Current behavior - -Governance is split deliberately into two layers: - -```text -candidate stage - -> GovernanceAgent - -> SQLPolicyEngine.evaluate(sql) - -> governance_report artifact - -execution boundary - -> ExecuteSqlNode - -> DatabaseTool.execute_sql(sql) - -> SQLPolicyEngine.evaluate(sql) again - -> SQLiteConnector (query_only connection) -``` - -`GovernanceAgent` in -[`queryforge/orchestration/agents/governance.py`](../queryforge/orchestration/agents/governance.py) -runs before normal execution. It: - -- requires an SQL candidate; -- evaluates the shared SQLGlot policy engine; -- writes `governance_report` with the full decision; -- blocks the candidate stage on policy denial or policy-engine failure; -- adds non-blocking warnings for high join count, unbounded scans, and - sensitive-looking columns. - -`SQLPolicyEngine` in -[`queryforge/domain/security/sql_policy.py`](../queryforge/domain/security/sql_policy.py) -enforces: - -- one parsable SQLite query AST; -- read-only query roots and forbidden AST nodes; -- no recursive CTE; -- dangerous function blacklist; -- table and column scope; -- required or maximum `LIMIT`; -- maximum tables and joins; -- optional CROSS JOIN denial. - -`DatabaseTool` in -[`queryforge/infrastructure/tools/database_tool.py`](../queryforge/infrastructure/tools/database_tool.py) -is the non-bypassable execution boundary. It applies the same policy again during -`execute_sql()` and uses a read-only SQLite connector with `PRAGMA query_only = ON`. - -### Why policy is checked twice - -The first check makes the orchestration decision observable and prevents unsafe SQL -from continuing into the normal execution stage. The second check is defense in depth: -any caller using `DatabaseTool`, including previews and transport resources, must pass -the policy even if it bypasses orchestration code by mistake. - -## 5. State and Failure Handling - -| Aspect | Old MVP | Current workflow | -| --- | --- | --- | -| State | In-memory `Context` only | `Context` plus persisted `TaskState` and artifacts | -| Failure | Stop at failed node | Stop, repair within budget when eligible, or emit `blocked`/`degraded` evidence | -| SQL errors | Execution failure ends request | Reflection chooses `SUCCESS`, `FIX_SQL`, `REGENERATE`, or human review | -| Policy failure | Basic validation error | Named AST rule, policy decision, Governance artifact, no execution | -| Session | None | Explicit opt-in structured session memory; no result rows | -| Delivery | CLI JSON | Shared JSON contract, reports, SSE progress, MCP tools/resources | - -## 6. What Was Intentionally Not Changed - -- SQLite remains the only formal execution backend. -- `WorkflowRunner`, node contracts, and `Context` remain the SQL execution core. -- Every generated formal SQL statement still runs through `DatabaseTool`. -- The default simple path remains bounded and avoids Tool Loop and multi-candidate - overhead. -- Legacy Python import shims remain for external callers during the modular-layout - transition. - -## 7. Practical Reading Order - -1. `application/agent_service.py`: transport-neutral request assembly. -2. `orchestration/agents/entry_router.py`: deterministic routing and complexity. -3. `orchestration/orchestrator/orchestrator.py`: stage lifecycle and artifacts. -4. `workflow/workflow.py`: reflective SQL loop. -5. `orchestration/agents/governance.py`: pre-execution Governance artifact. -6. `domain/security/sql_policy.py`: AST rules. -7. `infrastructure/tools/database_tool.py`: final execution boundary. diff --git a/docs/workflow_comparison.zh-CN.md b/docs/workflow_comparison.zh-CN.md deleted file mode 100644 index a3e3c6c..0000000 --- a/docs/workflow_comparison.zh-CN.md +++ /dev/null @@ -1,175 +0,0 @@ -# 新旧工作流代码对比 - -本文对比 QueryForge 最初 MVP 与当前受治理分析工作流。“旧工作流”指 -`docs/reproduction/vibe-coding-reproduce/` 所描述的固定 MVP,不是上游 -Datus-Agent 的完整实现。 - -## 工作流形态 - -### 旧 MVP - -```text -CLI --> WorkflowRunner --> SchemaLinkingNode --> GenSqlNode --> ExecuteSqlNode --> OutputNode -``` - -所有非空问题都作为同一种 NL2SQL 请求处理:生成一条 SQLite `SELECT`,执行并返回结果。 -任意节点失败即终止。 - -### 当前工作流 - -```text -CLI / REST-SSE / MCP / Gateway --> AgentService --> EntryRouterAgent --> OrchestratorAgent --> analysis -> candidate -> execution -> completion -> delivery --> WorkflowRunner / ReflectiveWorkflow -``` - -SQL 内核仍是节点化流程: - -```text -范围确定 -> 日期/Schema/Skill/指标上下文 --> 可选 Tool Loop 或并发候选 --> SQL 生成 --> Governance --> DatabaseTool 执行 --> 反思 / 有界修复 --> 输出 -``` - -五阶段是编排状态,不等于额外五次模型调用。默认简单请求仍为一次 SQL 生成加一次反思。 - -## 代码映射 - -| 关注点 | 旧 MVP | 当前实现 | 行为变化 | -| --- | --- | --- | --- | -| 入口 | `main.py` 直接创建 `WorkflowRunner` | `application/agent_service.py` | 所有传输层复用同一服务行为。 | -| 请求类型 | 只有隐式 NL2SQL | `orchestration/agents/entry_router.py` | 元数据与 SQL 审查无需执行模型 SQL。 | -| 编排 | `WorkflowRunner` 固定节点顺序 | `orchestration/orchestrator/` | 持久化阶段、artifact、门禁与交付。 | -| SQL 循环 | 单次生成、执行、输出 | `workflow/workflow.py:ReflectiveWorkflow` | 支持反思、修复、重生成、Tool Loop、候选选择。 | -| Schema 上下文 | SQLite 物理 Schema | `SchemaLinkingNode` + 语义层 + Subject Tree | 支持业务指标、Join Path、粒度和 fan-out 约束。 | -| 执行 | 只读校验后调用 connector | `ExecuteSqlNode -> DatabaseTool -> SQLiteConnector` | 语义 Join Guard、策略决策记录、执行时复核。 | -| 输出 | SQL、解释、结果行 | `OutputNode`、artifact、报告/SSE/MCP | 稳定响应之外可按需提供审计和交付。 | - -## Router 的具体变化 - -### 旧实现 - -没有 Router 模块。CLI 的每个问题都会进入固定工作流,因此不存在任务分类、复杂度评估、 -扩展路由或按任务类型跳过 SQL 执行。 - -### 当前实现 - -[`EntryRouterAgent`](../queryforge/orchestration/agents/entry_router.py) 是不依赖模型、 -数据库、`WorkflowRunner` 或 SQL 工具的确定性组件,因此它本身不能生成或执行 SQL。 - -它完成三项工作: - -1. 按 marker 分类: - `ask_sql`、`sql_review`、`troubleshoot_sql`、`metadata_query`、 - `explain_result`、`build_report`、`unknown`。 -2. 按跨表、指标、趋势比较、排名、多维分组、多条件过滤和问题长度计算 - `simple` / `complex` 复杂度。 -3. 通过 `TaskRoute` 与 `register_pipeline()` 支持部署侧注册新任务类型。 - -`AgentService._run()` 根据复杂度配置执行策略: - -```text -simple -> 单候选,不启用 Tool Loop -complex -> 有界 Tool Loop + 至少两个并发候选 -``` - -路由结果会写入 `routing_decision.json`,并出现在 `agent_team` 响应元数据中。当前对外 -流程统一为: - -| 任务类型 | 阶段流程 | -| --- | --- | -| `ask_sql`、`troubleshoot_sql`、`explain_result`、`build_report`、`unknown` | `analysis -> candidate -> execution -> completion -> delivery` | -| `sql_review` | `analysis -> candidate -> review -> completion -> delivery` | -| `metadata_query` | `analysis -> delivery` | - -Router 不是 LLM Planner,而是低成本、可测试、可解释的准入与执行配置决策。 - -## Governance 的具体变化 - -### 旧实现 - -旧 MVP 的 `DatabaseTool` 在执行前做基础只读检查:空 SQL、非 `SELECT`、多语句和明显 -DDL/DML 被拒绝。没有独立 Governance artifact,也没有表列白名单、危险函数、递归 CTE、 -查询形状预算或候选阶段门禁。 - -### 当前实现 - -当前治理刻意分为两层: - -```text -candidate 阶段 --> GovernanceAgent --> SQLPolicyEngine.evaluate(sql) --> governance_report artifact - -execution 边界 --> ExecuteSqlNode --> DatabaseTool.execute_sql(sql) --> SQLPolicyEngine.evaluate(sql) 再次校验 --> SQLiteConnector(query_only) -``` - -[`GovernanceAgent`](../queryforge/orchestration/agents/governance.py) 在正式执行前: - -- 要求存在 SQL candidate; -- 调用共享 SQLGlot 策略引擎; -- 写入完整 `governance_report`; -- 在策略拒绝或引擎不可用时阻断候选阶段; -- 对高 Join 数、无 WHERE/LIMIT、敏感列名产生非阻断风险告警。 - -[`SQLPolicyEngine`](../queryforge/domain/security/sql_policy.py) 当前强制: - -- 单一、可解析的 SQLite Query AST; -- 只读根节点和禁止 AST 节点; -- 禁止递归 CTE; -- 危险函数黑名单; -- 表和列访问范围; -- 必须/最大 `LIMIT`; -- 最大表数、最大 Join 数与 CROSS JOIN 控制。 - -[`DatabaseTool`](../queryforge/infrastructure/tools/database_tool.py) 是不可绕过的正式执行 -边界。`execute_sql()` 会再次执行同一策略,连接器还设置 `PRAGMA query_only = ON`。 - -双重校验的目的不同:候选阶段检查提供可审计的编排决策;执行阶段复核确保 preview、 -资源接口或未来调用方即使错误绕过编排,也不能绕过策略。 - -## 状态与失败处理 - -| 方面 | 旧 MVP | 当前工作流 | -| --- | --- | --- | -| 状态 | 内存 `Context` | `Context` + 持久化 `TaskState` + artifact | -| 节点失败 | 直接停止 | 可在预算内修复;否则输出 `blocked` / `degraded` 证据 | -| SQL 错误 | 执行失败即结束 | 反思选择 `SUCCESS`、`FIX_SQL`、`REGENERATE` 或人工审查 | -| 策略失败 | 基础校验错误 | 命名 AST 规则、策略决策、Governance artifact、禁止执行 | -| 会话 | 无 | 显式 opt-in 结构化记忆,不保存结果行 | -| 交付 | CLI JSON | 共享 JSON、报告、SSE 进度、MCP 资源与工具 | - -## 未改变的核心约束 - -- SQLite 仍是唯一正式执行后端。 -- `WorkflowRunner`、节点契约和 `Context` 仍是 SQL 执行内核。 -- 任何正式 SQL 仍必须经过 `DatabaseTool`。 -- 默认简单路径仍不会启用 Tool Loop 和多候选开销。 -- 旧 Python import 路径仍通过兼容 shim 保留。 - -## 推荐阅读顺序 - -1. `application/agent_service.py`:统一请求装配。 -2. `orchestration/agents/entry_router.py`:路由与复杂度。 -3. `orchestration/orchestrator/orchestrator.py`:五阶段生命周期与 artifact。 -4. `workflow/workflow.py`:反思式 SQL 循环。 -5. `orchestration/agents/governance.py`:执行前治理 artifact。 -6. `domain/security/sql_policy.py`:AST 安全规则。 -7. `infrastructure/tools/database_tool.py`:最终执行边界。 diff --git a/web/build/sites-vite-plugin.ts b/web/build/sites-vite-plugin.ts new file mode 100644 index 0000000..26563fd --- /dev/null +++ b/web/build/sites-vite-plugin.ts @@ -0,0 +1,45 @@ +import { access, cp, mkdir, rm } from "node:fs/promises"; +import { resolve } from "node:path"; +import type { Plugin } from "vite"; + +async function exists(path: string): Promise { + try { + await access(path); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + return false; + } + throw error; + } +} + +// Packages Sites metadata and migrations after Vite finishes compiling. +export function sites(): Plugin { + let root = process.cwd(); + + return { + name: "sites", + apply: "build", + configResolved(config) { + root = config.root; + }, + async closeBundle() { + const outputDirectory = resolve(root, "dist", ".openai"); + const hostingConfig = resolve(root, ".openai", "hosting.json"); + const drizzleSource = resolve(root, "drizzle"); + + await rm(outputDirectory, { recursive: true, force: true }); + await mkdir(outputDirectory, { recursive: true }); + + if (await exists(hostingConfig)) { + await cp(hostingConfig, resolve(outputDirectory, "hosting.json")); + } + if (await exists(drizzleSource)) { + await cp(drizzleSource, resolve(outputDirectory, "drizzle"), { + recursive: true, + }); + } + }, + }; +}