feat: 技能收藏与常驻(always-on)支持

- 新增 skill_favorites / skill_always_on 迁移与持久化模型字段
- skills 路由、存储、前端设置页支持收藏与常驻
- 调整摘要中间件与 lead agent 提示词
- 同步岗位 position_sync 及相关配置清理

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
吉鑫升andClaude Opus 4.8 committed 2026-06-16 16:37:43 +08:00
1 parent 5ebbb82d66
commit 5182ea5d11
19 files changed
+472 -107

No files matched your search

@@ -0,0 +1,54 @@
"""我的技能 (skill favorites) table.
New table ``skill_favorites`` — the per-user "我的技能" collection, mirroring
``agent_favorites``. A 岗位 (position) materializes its skill tag bindings into
this table (``origin='position'``) so granted skills land in the member's 我的
list while the browse-all 广场 stays complete.
Note: the running app also auto-creates this table via ``create_all`` on
startup (new tables are always created, even on existing DBs); this migration
keeps the alembic history consistent per the repo convention (see
backend/CLAUDE.md → Schema Migrations).
Revision ID: 20260616_02
Revises: 20260616_01
Create Date: 2026-06-16
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260616_02"
down_revision = "20260616_01"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
return table_name in inspect(op.get_bind()).get_table_names()
def upgrade() -> None:
if not _has_table("skill_favorites"):
op.create_table(
"skill_favorites",
sa.Column("id", sa.String(64), primary_key=True),
sa.Column("user_id", sa.String(64), nullable=False),
sa.Column("skill_name", sa.String(64), nullable=False),
sa.Column("origin", sa.String(16), nullable=False, server_default="user"),
sa.Column("position_id", sa.String(64), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint("user_id", "skill_name", name="uq_skill_favorites_user_skill"),
)
op.create_index("ix_skill_favorites_user_id", "skill_favorites", ["user_id"])
op.create_index("ix_skill_favorites_skill_name", "skill_favorites", ["skill_name"])
op.create_index("ix_skill_favorites_position_id", "skill_favorites", ["position_id"])
def downgrade() -> None:
if _has_table("skill_favorites"):
op.drop_table("skill_favorites")
@@ -0,0 +1,45 @@
"""Add always_on (常驻/免压缩) column to skills table.
Revision ID: 20260616_03
Revises: 20260616_02
Create Date: 2026-06-16
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260616_03"
down_revision = "20260616_02"
branch_labels = None
depends_on = None
def _has_table(table_name: str) -> bool:
inspector = inspect(op.get_bind())
return table_name in inspector.get_table_names()
def _has_column(table_name: str, column_name: str) -> bool:
if not _has_table(table_name):
return False
inspector = inspect(op.get_bind())
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
def upgrade() -> None:
# ``skills`` may not exist yet on a brand-new DB — create_all handles that
# case with the column already present, so only patch existing tables.
if _has_table("skills") and not _has_column("skills", "always_on"):
op.add_column(
"skills",
sa.Column("always_on", sa.Boolean(), nullable=False, server_default="0"),
)
def downgrade() -> None:
if _has_column("skills", "always_on"):
op.drop_column("skills", "always_on")
@@ -60,7 +60,7 @@ from deerflow.persistence.scheduled_tasks.model import (
ScheduledTaskSubscriptionRow,
SchedulerThreadRow,
)
from deerflow.persistence.skills.model import SkillDisplayAdapterRow, SkillRow
from deerflow.persistence.skills.model import SkillDisplayAdapterRow, SkillFavoriteRow, SkillRow
from deerflow.persistence.tags.model import TagAssignmentRow, TagRow
from deerflow.persistence.thread_meta.model import ThreadMetaRow
from deerflow.persistence.embed_sessions.model import EmbedSessionRow
@@ -110,6 +110,7 @@ __all__ = [
"SchedulerThreadRow",
"SkillRow",
"SkillDisplayAdapterRow",
"SkillFavoriteRow",
"TagAssignmentRow",
"TagRow",
"EmbedSessionRow",
@@ -85,3 +85,23 @@ class SkillStore(ABC):
DB round-trip per candidate skill.
"""
raise NotImplementedError
@abstractmethod
async def list_always_on_names(self) -> set[str]:
"""Return the set of skill names marked 常驻(免压缩) (``always_on = True``).
Batch query used by the prompt builder to decide which skills bypass
skill compression — one query instead of a per-skill round-trip.
"""
raise NotImplementedError
@abstractmethod
async def list_favorite_skill_names(self, user_id: str) -> set[str]:
"""Return the skill names in ``user_id``'s "我的技能" collection.
These are skills the user does not own but that landed in their list —
currently only via their 岗位 (position) sync (``origin='position'``).
Owned skills are NOT included here (the caller detects those via
``owner_user_id``).
"""
raise NotImplementedError
@@ -20,12 +20,15 @@ def _copy(record: dict[str, Any] | None) -> dict[str, Any] | None:
def _with_derived(record: dict[str, Any]) -> dict[str, Any]:
out = dict(record)
out["builtin"] = out.get("owner_user_id") is None
out.setdefault("always_on", False)
return out
class MemorySkillStore(SkillStore):
def __init__(self) -> None:
self._skills: dict[str, dict[str, Any]] = {}
# user_id -> {skill_name}
self._favorites: dict[str, set[str]] = {}
@staticmethod
def _is_visible(record: dict[str, Any], user_id: str) -> bool:
@@ -71,6 +74,7 @@ class MemorySkillStore(SkillStore):
"published": bool(data.get("published", False)),
"detail": data.get("detail"),
"name_zh": data.get("name_zh"),
"always_on": bool(data.get("always_on", False)),
"square_id": str(data.get("square_id") or ""),
"created_at": _now(),
"updated_at": _now(),
@@ -107,6 +111,8 @@ class MemorySkillStore(SkillStore):
record["detail"] = data["detail"]
if "name_zh" in data:
record["name_zh"] = data["name_zh"]
if "always_on" in data:
record["always_on"] = bool(data["always_on"])
if "square_id" in data:
record["square_id"] = str(data["square_id"] or "")
record["updated_at"] = _now()
@@ -124,6 +130,8 @@ class MemorySkillStore(SkillStore):
record["detail"] = data["detail"]
if "name_zh" in data:
record["name_zh"] = data["name_zh"]
if "always_on" in data:
record["always_on"] = bool(data["always_on"])
if "square_id" in data:
record["square_id"] = str(data["square_id"] or "")
record["updated_at"] = _now()
@@ -153,3 +161,13 @@ class MemorySkillStore(SkillStore):
async def list_published_names(self) -> set[str]:
return {name for name, record in self._skills.items() if record.get("published")}
async def list_always_on_names(self) -> set[str]:
return {name for name, record in self._skills.items() if record.get("always_on")}
async def list_favorite_skill_names(self, user_id: str) -> set[str]:
return set(self._favorites.get(user_id, set()))
# test helper — not part of the abstract API
def add_favorite(self, user_id: str, skill_name: str) -> None:
self._favorites.setdefault(user_id, set()).add(skill_name)
@@ -10,10 +10,11 @@ from __future__ import annotations
from datetime import UTC, datetime
from sqlalchemy import Boolean, DateTime, String, Text
from sqlalchemy import Boolean, DateTime, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from deerflow.persistence.base import Base
from deerflow.persistence.types import BeijingDateTime
class SkillRow(Base):
@@ -33,6 +34,10 @@ class SkillRow(Base):
# the on-disk SKILL.md) so it can be set for built-in skills too, and so the
# shared source file is never rewritten.
name_zh: Mapped[str | None] = mapped_column(String(128), nullable=True, default=None)
# 常驻(免压缩):开启技能压缩后,标记此项的技能仍以全文形式注入系统提示词,而非
# 降级为索引 + search_skills 检索。存 DB(而非 extensions_config.json),内置技能
# 也能标记,且避免在某些部署里回写源码目录下的配置文件导致报错。
always_on: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default="0", index=True)
# Publish square (发布广场) this skill is filed under once published. Pure
# organizational category, no access control. Empty string = unassigned →
# the listing layer resolves it to the default square. One square per skill.
@@ -41,6 +46,32 @@ class SkillRow(Base):
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC))
class SkillFavoriteRow(Base):
"""A user's "我的技能" membership for a skill they don't own.
Mirrors :class:`deerflow.persistence.agents.model.AgentFavoriteRow`: lets a
skill land in a user's "我的" list without the user owning it. Skills are
keyed by ``name`` (the on-disk folder / DB primary key), so this row
references ``skill_name`` rather than an opaque id. One row per
(user, skill); the unique constraint makes the grant idempotent.
"""
__tablename__ = "skill_favorites"
__table_args__ = (UniqueConstraint("user_id", "skill_name", name="uq_skill_favorites_user_skill"),)
id: Mapped[str] = mapped_column(String(64), primary_key=True)
user_id: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
skill_name: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
# ``"user"`` = the user added it themselves (reserved for a future favorite
# button); ``"position"`` = auto-granted by the user's 岗位 (position) via
# the subscription sync engine. Sync only ever adds/removes ``"position"``
# rows, so a user's own picks are never clobbered.
origin: Mapped[str] = mapped_column(String(16), nullable=False, default="user", server_default="user")
# The position that granted this favorite (only set when ``origin='position'``).
position_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
created_at: Mapped[datetime] = mapped_column(BeijingDateTime(), nullable=False, default=lambda: datetime.now(UTC))
class SkillDisplayAdapterRow(Base):
__tablename__ = "skill_display_adapters"
@@ -9,7 +9,7 @@ from sqlalchemy import func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from deerflow.persistence.skills.base import SkillStore
from deerflow.persistence.skills.model import SkillRow
from deerflow.persistence.skills.model import SkillFavoriteRow, SkillRow
def _row_to_dict(row: SkillRow) -> dict[str, Any]:
@@ -65,6 +65,7 @@ class SkillRepository(SkillStore):
published=bool(data.get("published", False)),
detail=data.get("detail"),
name_zh=data.get("name_zh"),
always_on=bool(data.get("always_on", False)),
square_id=str(data.get("square_id") or ""),
created_at=now,
updated_at=now,
@@ -110,6 +111,8 @@ class SkillRepository(SkillStore):
row.detail = data["detail"]
if "name_zh" in data:
row.name_zh = data["name_zh"]
if "always_on" in data:
row.always_on = bool(data["always_on"])
if "square_id" in data:
row.square_id = str(data["square_id"] or "")
row.updated_at = datetime.now(UTC)
@@ -130,6 +133,8 @@ class SkillRepository(SkillStore):
row.detail = data["detail"]
if "name_zh" in data:
row.name_zh = data["name_zh"]
if "always_on" in data:
row.always_on = bool(data["always_on"])
if "square_id" in data:
row.square_id = str(data["square_id"] or "")
row.updated_at = datetime.now(UTC)
@@ -171,3 +176,15 @@ class SkillRepository(SkillStore):
async with self._sf() as session:
result = await session.execute(stmt)
return {row[0] for row in result.all()}
async def list_always_on_names(self) -> set[str]:
stmt = select(SkillRow.name).where(SkillRow.always_on.is_(True))
async with self._sf() as session:
result = await session.execute(stmt)
return {row[0] for row in result.all()}
async def list_favorite_skill_names(self, user_id: str) -> set[str]:
stmt = select(SkillFavoriteRow.skill_name).where(SkillFavoriteRow.user_id == user_id)
async with self._sf() as session:
result = await session.execute(stmt)
return {row[0] for row in result.all()}