包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。 排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。 Co-Authored-By: Claude Code <[email protected]>
213 lines
8.2 KiB
Python
213 lines
8.2 KiB
Python
"""
|
||
任务模板服务
|
||
============
|
||
|
||
【功能说明】常用开发/修复模板管理,一键复用到任务提交。
|
||
【实现思路】模板存 SQLite,支持 CRUD + 分类 + 标签。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
import sqlite3
|
||
import uuid
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
from typing import Optional
|
||
|
||
from app.store.sqlite_util import open_connection
|
||
|
||
logger = logging.getLogger("agent.template")
|
||
|
||
|
||
class TaskTemplate:
|
||
"""任务模板"""
|
||
|
||
def __init__(
|
||
self,
|
||
id: str,
|
||
name: str,
|
||
category: str,
|
||
content: str,
|
||
description: str,
|
||
tags: list[str],
|
||
created_at: str,
|
||
updated_at: str,
|
||
):
|
||
self.id = id
|
||
self.name = name
|
||
self.category = category
|
||
self.content = content
|
||
self.description = description
|
||
self.tags = tags
|
||
self.created_at = created_at
|
||
self.updated_at = updated_at
|
||
|
||
|
||
class TemplateStore:
|
||
"""任务模板存储"""
|
||
|
||
def __init__(self, db_path: Path) -> None:
|
||
self._db_path = Path(db_path)
|
||
self._init_schema()
|
||
self._seed_defaults()
|
||
|
||
def _conn(self):
|
||
"""
|
||
获取一个短连接(用完自动提交/回滚并关闭)。
|
||
|
||
【修复】原先只返回裸 sqlite3 连接、用完从不 close,连接泄漏到 GC
|
||
(Windows 文件锁 / 句柄增长)。改为委托 app.store.sqlite_util.open_connection,
|
||
提交/回滚语义不变,额外保证 close。
|
||
"""
|
||
return open_connection(self._db_path)
|
||
|
||
def _init_schema(self) -> None:
|
||
ddl = """
|
||
CREATE TABLE IF NOT EXISTS task_template (
|
||
id TEXT PRIMARY KEY,
|
||
name TEXT NOT NULL,
|
||
category TEXT NOT NULL DEFAULT '通用',
|
||
content TEXT NOT NULL,
|
||
description TEXT DEFAULT '',
|
||
tags TEXT DEFAULT '[]',
|
||
created_at TEXT NOT NULL,
|
||
updated_at TEXT NOT NULL
|
||
);
|
||
"""
|
||
with self._conn() as conn:
|
||
conn.execute(ddl)
|
||
conn.commit()
|
||
|
||
def _seed_defaults(self) -> None:
|
||
"""首次初始化默认模板。"""
|
||
defaults = [
|
||
{
|
||
"name": "修复空指针异常",
|
||
"category": "Bug修复",
|
||
"content": "修复 {文件名} 中的空指针异常:当 {变量/参数} 为 null 时,应抛出 IllegalArgumentException 并给出明确错误信息,而不是 NPE。",
|
||
"description": "Java NPE 修复模板",
|
||
"tags": ["Java", "NPE", "异常处理"],
|
||
},
|
||
{
|
||
"name": "新增 REST API 接口",
|
||
"category": "功能开发",
|
||
"content": "在 {Controller} 中新增 {接口名} 接口:路径 /api/{path},方法 {GET/POST/PUT/DELETE},入参 {参数说明},返回 {返回结构}。遵循项目现有编码规范,添加中文注释。",
|
||
"description": "RESTful 接口开发模板",
|
||
"tags": ["API", "REST", "Controller"],
|
||
},
|
||
{
|
||
"name": "数据库表结构变更",
|
||
"category": "数据库",
|
||
"content": "在表 {表名} 中新增字段 {字段名}({类型},{约束}),并更新对应的 Entity/DTO/Mapper/Service 各层代码。确保兼容现有数据,添加默认值。",
|
||
"description": "数据库变更模板",
|
||
"tags": ["数据库", "DDL", "MyBatis"],
|
||
},
|
||
{
|
||
"name": "单元测试生成",
|
||
"category": "测试",
|
||
"content": "为 {类名/方法名} 生成完整的单元测试,覆盖正常场景、边界条件、异常场景。使用 JUnit 5 + Mockito,测试方法命名遵循 test_{方法名}_{场景} 规范。",
|
||
"description": "单元测试生成模板",
|
||
"tags": ["测试", "JUnit", "Mockito"],
|
||
},
|
||
{
|
||
"name": "代码重构优化",
|
||
"category": "重构",
|
||
"content": "重构 {类名/模块}:识别重复代码、过长方法、过大类,提取公共方法、应用设计模式(如策略/工厂),保持功能不变、测试通过。",
|
||
"description": "代码重构模板",
|
||
"tags": ["重构", "设计模式", "代码质量"],
|
||
},
|
||
]
|
||
with self._conn() as conn:
|
||
count = conn.execute("SELECT COUNT(*) FROM task_template").fetchone()[0]
|
||
if count == 0:
|
||
for item in defaults:
|
||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||
conn.execute(
|
||
"INSERT INTO task_template (id, name, category, content, description, tags, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",
|
||
(f"tpl_{uuid.uuid4().hex[:12]}", item["name"], item["category"], item["content"], item["description"], str(item["tags"]), now, now),
|
||
)
|
||
conn.commit()
|
||
|
||
def _row_to_obj(self, row: sqlite3.Row) -> TaskTemplate:
|
||
import json as json_mod
|
||
tags = []
|
||
try:
|
||
tags = json_mod.loads(row["tags"] or "[]")
|
||
except Exception:
|
||
pass
|
||
return TaskTemplate(
|
||
id=row["id"],
|
||
name=row["name"],
|
||
category=row["category"],
|
||
content=row["content"],
|
||
description=row["description"] or "",
|
||
tags=tags,
|
||
created_at=row["created_at"],
|
||
updated_at=row["updated_at"],
|
||
)
|
||
|
||
def list_all(self, category: str = "") -> list[TaskTemplate]:
|
||
sql = "SELECT * FROM task_template"
|
||
params = []
|
||
if category:
|
||
sql += " WHERE category = ?"
|
||
params.append(category)
|
||
sql += " ORDER BY updated_at DESC"
|
||
with self._conn() as conn:
|
||
rows = conn.execute(sql, params).fetchall()
|
||
return [self._row_to_obj(r) for r in rows]
|
||
|
||
def get(self, tpl_id: str) -> Optional[TaskTemplate]:
|
||
with self._conn() as conn:
|
||
row = conn.execute("SELECT * FROM task_template WHERE id = ?", (tpl_id,)).fetchone()
|
||
return self._row_to_obj(row) if row else None
|
||
|
||
def create(self, name: str, category: str, content: str, description: str = "", tags: list[str] | None = None) -> TaskTemplate:
|
||
import json as json_mod
|
||
|
||
tpl_id = f"tpl_{uuid.uuid4().hex[:12]}"
|
||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||
with self._conn() as conn:
|
||
conn.execute(
|
||
"INSERT INTO task_template (id, name, category, content, description, tags, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",
|
||
(tpl_id, name, category, content, description, json_mod.dumps(tags or [], ensure_ascii=False), now, now),
|
||
)
|
||
conn.commit()
|
||
return self.get(tpl_id)
|
||
|
||
def update(self, tpl_id: str, **kwargs) -> Optional[TaskTemplate]:
|
||
import json as json_mod
|
||
|
||
allowed = {"name", "category", "content", "description", "tags"}
|
||
updates = {k: v for k, v in kwargs.items() if k in allowed and v is not None}
|
||
if not updates:
|
||
return self.get(tpl_id)
|
||
if "tags" in updates:
|
||
updates["tags"] = json_mod.dumps(updates["tags"], ensure_ascii=False)
|
||
updates["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||
set_clause = ", ".join(f"{k} = ?" for k in updates)
|
||
values = list(updates.values()) + [tpl_id]
|
||
with self._conn() as conn:
|
||
conn.execute(f"UPDATE task_template SET {set_clause} WHERE id = ?", values)
|
||
conn.commit()
|
||
return self.get(tpl_id)
|
||
|
||
def delete(self, tpl_id: str) -> bool:
|
||
with self._conn() as conn:
|
||
cursor = conn.execute("DELETE FROM task_template WHERE id = ?", (tpl_id,))
|
||
conn.commit()
|
||
return cursor.rowcount > 0
|
||
|
||
|
||
# 全局单例
|
||
_store: TemplateStore | None = None
|
||
|
||
|
||
def get_template_store() -> TemplateStore:
|
||
global _store
|
||
if _store is None:
|
||
settings = __import__("app.config.settings", fromlist=["load_settings"]).load_settings()
|
||
_store = TemplateStore(settings.sqlite_db_path)
|
||
return _store
|