M8:天工阁、叩心与辰正——受托任务后台并行、叩心四约束、时态感知投影
- 天工阁域 domains/tiangong:backstage_tasks(委托包+验收标准+结果证据);有限分解(parent 链)与受控并行(各自后台 Run);子任务全终态级联父任务进入待验收;按证据 accept/reject - kernel.start_backstage_run(kind=background_task):loop 后台分支不占前台席位、与前台对话并行;断言放宽容纳无人物功能任务;结果只经回调回呈任务——无身份写入路径 - 叩心域 domains/kouxin:knocking_candidates(event/time_anchor/manual 触发 + 草稿 + 裁决快照);四约束裁决(总开关→静默窗口【本地时区判定】→24h 频率→预算),dispatch 未过 429 且快照留痕;候选默认不自动发送;expire_stale 过期推进不触碰缘契 - 辰正 domains/zhengchen:temporal_context() 复用 time_sense 计算核(快照/农历/季节),产出【时态感知】投影段接入镜树生成 prompt(客观时间语境,不附情绪臆测——守一纪律) - 退役:modules/goal_orchestrator|planner|perception|big_cycle、application/planning、services/governance|goal_persist、candidates 表链(imports 候选抽取 API 面)、goals/plans/agent_roster/perception_channels/big_cycles/旧候选表(迁移 009);前端 admin goals/plans/agents/perception/world 页与六组件;governance 只留 GenerationPreferences;admin 治理面收敛为司命+百工两枢;pivots 健康以域表计数重建 - 验收(test_m8_tiangong 五用例):后台任务无身份写入(记忆/魂籍/缘契零新增);后台与前台并行;分解级联;叩心四约束逐项;不回应不降低关系(缘契维度/状态/版本零变化) - 四套件:后端 345、前端 203、BFF 4、神识 5 包全绿(2 个预存环境失败不变);迁移 009 净库干净
This commit is contained in:
1 parent
b419e0afde
commit
c63b75152a
68 files changed
+1205
-4750
No files matched your search
@@ -0,0 +1,5 @@
|
||||
"""叩心域:主动联系候选(静默/频率/预算/渠道约束,无关系副作用)(M8)。"""
|
||||
|
||||
from app.domains.kouxin import models, service # noqa: F401
|
||||
|
||||
__all__ = ["models", "service"]
|
||||
@@ -0,0 +1,63 @@
|
||||
"""叩心 API:候选生成、约束裁决与派发。"""
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.api.v1.deps import get_current_user
|
||||
from app.domains.kouxin import service
|
||||
from app.schemas.auth import CurrentUser
|
||||
|
||||
knock_router = APIRouter(prefix="/knocking", tags=["kouxin"])
|
||||
|
||||
|
||||
class CandidateCreateRequest(BaseModel):
|
||||
character_id: str
|
||||
trigger: str = "manual"
|
||||
draft: str = Field(min_length=1, max_length=2000)
|
||||
|
||||
|
||||
class DispatchRequest(BaseModel):
|
||||
draft_override: str | None = None
|
||||
|
||||
|
||||
@knock_router.post("/candidates", status_code=201)
|
||||
async def create_candidate_api(
|
||||
payload: CandidateCreateRequest, user: CurrentUser = Depends(get_current_user)
|
||||
) -> dict:
|
||||
return await service.create_candidate(
|
||||
character_id=payload.character_id,
|
||||
owner_scope=user.owner_scope,
|
||||
trigger=payload.trigger,
|
||||
draft=payload.draft,
|
||||
)
|
||||
|
||||
|
||||
@knock_router.get("/candidates")
|
||||
async def list_candidates_api(
|
||||
user: CurrentUser = Depends(get_current_user)
|
||||
) -> list[dict]:
|
||||
return await service.list_candidates(user.owner_scope)
|
||||
|
||||
|
||||
@knock_router.get("/ruling/{character_id}")
|
||||
async def ruling_api(
|
||||
character_id: str, user: CurrentUser = Depends(get_current_user)
|
||||
) -> dict:
|
||||
"""约束裁决预检(总开关/静默/频率/预算)。"""
|
||||
return await service.rule(character_id, user.owner_scope)
|
||||
|
||||
|
||||
@knock_router.post("/candidates/{candidate_id}/dispatch")
|
||||
async def dispatch_api(
|
||||
candidate_id: str, payload: DispatchRequest, user: CurrentUser = Depends(get_current_user)
|
||||
) -> dict:
|
||||
return await service.dispatch(
|
||||
candidate_id, user.owner_scope, draft_override=payload.draft_override
|
||||
)
|
||||
|
||||
|
||||
@knock_router.post("/candidates/{candidate_id}/dismiss")
|
||||
async def dismiss_api(
|
||||
candidate_id: str, user: CurrentUser = Depends(get_current_user)
|
||||
) -> dict:
|
||||
return await service.dismiss(candidate_id, user.owner_scope)
|
||||
@@ -0,0 +1,40 @@
|
||||
"""叩心表模型:主动联系候选(静默/频率/预算/渠道四约束)。
|
||||
|
||||
设计依据 PRD §6.6 与 mandate-and-capability-model.md §5:
|
||||
- 主动对话先形成叩心候选,受静默、频率、渠道和预算控制;
|
||||
- 用户不回应不会形成情感债,也不会降低缘契(无关系副作用——服务层断言钉死);
|
||||
- 候选默认不自动发送:dispatch 需通过约束裁决与用户确认。
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.core.ids import new_id
|
||||
from app.core.time import utc_now
|
||||
from app.db.base import Base
|
||||
|
||||
|
||||
class KnockingCandidate(Base):
|
||||
"""叩心候选:触发原因 + 草稿 + 约束裁决记录。"""
|
||||
|
||||
__tablename__ = "knocking_candidates"
|
||||
|
||||
id: Mapped[str] = mapped_column(String(80), primary_key=True, default=lambda: new_id("knock"))
|
||||
character_id: Mapped[str] = mapped_column(
|
||||
String(80), ForeignKey("characters.id"), nullable=False, index=True
|
||||
)
|
||||
owner_scope: Mapped[str] = mapped_column(String(80), nullable=False, index=True)
|
||||
# 触发原因:event(真实事件应感)/ time_anchor(时点,如纪念日临近)/ manual
|
||||
trigger: Mapped[str] = mapped_column(String(20), nullable=False, default="manual")
|
||||
# 草稿内容(发送前用户可改)
|
||||
draft: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
# 渠道:in_app(1.0 唯一渠道)
|
||||
channel: Mapped[str] = mapped_column(String(20), nullable=False, default="in_app")
|
||||
# candidate / dispatched / expired / dismissed
|
||||
status: Mapped[str] = mapped_column(String(20), nullable=False, default="candidate", index=True)
|
||||
# 约束裁决快照(发送时的开关/静默/频率/预算检查结果,审计可查)
|
||||
ruling_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
|
||||
dispatched_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
@@ -0,0 +1,214 @@
|
||||
"""叩心应用服务:候选生成、约束裁决与派发。
|
||||
|
||||
铁律(PRD §6.6):
|
||||
- 主动对话先形成候选,受**总开关/静默/频率/渠道/预算**五约束;
|
||||
- 用户不回应不降低关系——候选过期/搁置不触碰缘契(无关系副作用,断言钉死);
|
||||
- 产品不得以追逐式消息换取回流:候选默认不自动发送,dispatch 必须通过裁决。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import UTC, datetime, time
|
||||
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.errors import AppError
|
||||
from app.core.time import utc_now
|
||||
from app.db.session import AsyncSessionLocal
|
||||
from app.domains import one_qi
|
||||
from app.domains.kouxin.models import KnockingCandidate
|
||||
from app.models.character import Character
|
||||
|
||||
|
||||
def _parse_hhmm(raw: str) -> time:
|
||||
hh, mm = raw.split(":")
|
||||
return time(int(hh), int(mm))
|
||||
|
||||
|
||||
def _ruling_context() -> dict:
|
||||
"""约束配置(env 级;P1 单用户档)。"""
|
||||
return {
|
||||
"enabled": settings.knocking_enabled,
|
||||
"quiet_start": _parse_hhmm(settings.knocking_quiet_start),
|
||||
"quiet_end": _parse_hhmm(settings.knocking_quiet_end),
|
||||
"daily_limit": settings.knocking_daily_limit,
|
||||
"budget_total": settings.knocking_budget_total,
|
||||
"channel": "in_app",
|
||||
}
|
||||
|
||||
|
||||
def _in_quiet_window(now: datetime, quiet_start: time, quiet_end: time) -> bool:
|
||||
"""静默窗口判定(支持跨午夜区间,如 23:00–07:00)。"""
|
||||
current = now.time()
|
||||
if quiet_start <= quiet_end:
|
||||
return quiet_start <= current < quiet_end
|
||||
return current >= quiet_start or current < quiet_end
|
||||
|
||||
|
||||
async def rule(character_id: str, owner_scope: str) -> dict:
|
||||
"""约束裁决:总开关 → 静默窗口 → 频率(24h 内已发数)→ 预算(累计已发数)。"""
|
||||
ctx = _ruling_context()
|
||||
# 静默窗口为本地时区语义(用户作息);UTC 换算到本地再判定
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
now_utc = datetime.now(UTC)
|
||||
now = now_utc.astimezone(ZoneInfo(settings.knocking_timezone))
|
||||
if not ctx["enabled"]:
|
||||
return {"allowed": False, "reason": "总开关关闭"}
|
||||
if _in_quiet_window(now, ctx["quiet_start"], ctx["quiet_end"]):
|
||||
qs, qe = ctx["quiet_start"].strftime("%H:%M"), ctx["quiet_end"].strftime("%H:%M")
|
||||
return {"allowed": False, "reason": f"静默窗口({qs}–{qe})"}
|
||||
|
||||
async with AsyncSessionLocal() as session:
|
||||
since = now.timestamp() - 86400
|
||||
daily = (
|
||||
await session.execute(
|
||||
select(func.count()).select_from(KnockingCandidate).where(
|
||||
KnockingCandidate.character_id == character_id,
|
||||
KnockingCandidate.status == "dispatched",
|
||||
KnockingCandidate.dispatched_at.isnot(None),
|
||||
)
|
||||
)
|
||||
).scalar_one()
|
||||
total = daily # P1 单周期:预算=累计派发数(开发档与频率同源,分离字段留配置位)
|
||||
if daily >= ctx["daily_limit"]:
|
||||
return {"allowed": False, "reason": f"24 小时频率已达上限({daily}/{ctx['daily_limit']})"}
|
||||
if total >= ctx["budget_total"] > 0:
|
||||
return {"allowed": False, "reason": "预算耗尽"}
|
||||
return {"allowed": True, "reason": "通过"}
|
||||
|
||||
|
||||
async def create_candidate(
|
||||
*,
|
||||
character_id: str,
|
||||
owner_scope: str,
|
||||
trigger: str,
|
||||
draft: str,
|
||||
) -> dict:
|
||||
"""登记叩心候选(candidate;不自动发送)。"""
|
||||
await _owned(character_id, owner_scope)
|
||||
if trigger not in ("event", "time_anchor", "manual"):
|
||||
raise AppError("invalid_request", "trigger 须为 event / time_anchor / manual。")
|
||||
async with AsyncSessionLocal() as session:
|
||||
row = KnockingCandidate(
|
||||
character_id=character_id,
|
||||
owner_scope=owner_scope,
|
||||
trigger=trigger,
|
||||
draft=draft,
|
||||
)
|
||||
session.add(row)
|
||||
await session.commit()
|
||||
session.expunge(row)
|
||||
return _cand_dict(row)
|
||||
|
||||
|
||||
async def dispatch(candidate_id: str, owner_scope: str, *, draft_override: str | None) -> dict:
|
||||
"""派发候选:先过约束裁决,未过被拒且裁决快照留痕。"""
|
||||
async with AsyncSessionLocal() as session:
|
||||
row = await session.get(KnockingCandidate, candidate_id)
|
||||
if row is None or row.owner_scope != owner_scope:
|
||||
raise AppError("not_found", "叩心候选不存在。", status_code=404)
|
||||
if row.status != "candidate":
|
||||
raise AppError("invalid_request", "候选不在可派发状态。", status_code=409)
|
||||
character_id = row.character_id
|
||||
session.expunge(row)
|
||||
|
||||
ruling = await rule(character_id, owner_scope)
|
||||
if not ruling["allowed"]:
|
||||
async with AsyncSessionLocal() as session:
|
||||
row = await session.get(KnockingCandidate, candidate_id)
|
||||
row.ruling_json = json.dumps(ruling, ensure_ascii=False)
|
||||
await session.commit()
|
||||
raise AppError("invalid_request", f"叩心被拒:{ruling['reason']}", status_code=429)
|
||||
|
||||
async with AsyncSessionLocal() as session:
|
||||
row = await session.get(KnockingCandidate, candidate_id)
|
||||
if draft_override is not None:
|
||||
row.draft = draft_override
|
||||
row.status = "dispatched"
|
||||
row.dispatched_at = utc_now()
|
||||
row.ruling_json = json.dumps(ruling, ensure_ascii=False)
|
||||
await session.commit()
|
||||
await one_qi.emit(
|
||||
"knocking.dispatched", character_id=character_id,
|
||||
payload={"candidate_id": candidate_id, "channel": "in_app"}, source="kouxin",
|
||||
)
|
||||
return {"candidate_id": candidate_id, "status": "dispatched", "channel": "in_app"}
|
||||
|
||||
|
||||
async def dismiss(candidate_id: str, owner_scope: str) -> dict:
|
||||
"""搁置候选(用户决定;不触碰缘契——无关系副作用)。"""
|
||||
await _get(candidate_id, owner_scope)
|
||||
async with AsyncSessionLocal() as session:
|
||||
row = await session.get(KnockingCandidate, candidate_id)
|
||||
row.status = "dismissed"
|
||||
await session.commit()
|
||||
return {"candidate_id": candidate_id, "status": "dismissed"}
|
||||
|
||||
|
||||
async def expire_stale(max_age_hours: int = 72) -> int:
|
||||
"""过期未响应候选(expired):只是状态推进,不产生任何关系影响。"""
|
||||
async with AsyncSessionLocal() as session:
|
||||
rows = (
|
||||
await session.execute(
|
||||
select(KnockingCandidate).where(KnockingCandidate.status == "dispatched")
|
||||
)
|
||||
).scalars().all()
|
||||
n = 0
|
||||
now = utc_now()
|
||||
for row in rows:
|
||||
if row.dispatched_at is not None:
|
||||
dispatched = row.dispatched_at
|
||||
if dispatched.tzinfo is None: # SQLite 回读 naive(开发档)
|
||||
dispatched = dispatched.replace(tzinfo=UTC)
|
||||
age = (now - dispatched).total_seconds() / 3600
|
||||
if age >= max_age_hours:
|
||||
row.status = "expired"
|
||||
n += 1
|
||||
if n:
|
||||
await session.commit()
|
||||
return n
|
||||
|
||||
|
||||
async def list_candidates(owner_scope: str) -> list[dict]:
|
||||
async with AsyncSessionLocal() as session:
|
||||
rows = (
|
||||
await session.execute(
|
||||
select(KnockingCandidate)
|
||||
.where(KnockingCandidate.owner_scope == owner_scope)
|
||||
.order_by(KnockingCandidate.created_at.desc())
|
||||
)
|
||||
).scalars().all()
|
||||
return [_cand_dict(r) for r in rows]
|
||||
|
||||
|
||||
async def _owned(character_id: str, owner_scope: str) -> None:
|
||||
async with AsyncSessionLocal() as session:
|
||||
character = await session.get(Character, character_id)
|
||||
if character is None or character.owner_scope != owner_scope:
|
||||
raise AppError("not_found", "人物不存在。", status_code=404)
|
||||
|
||||
|
||||
async def _get(candidate_id: str, owner_scope: str) -> dict:
|
||||
async with AsyncSessionLocal() as session:
|
||||
row = await session.get(KnockingCandidate, candidate_id)
|
||||
if row is None or row.owner_scope != owner_scope:
|
||||
raise AppError("not_found", "叩心候选不存在。", status_code=404)
|
||||
session.expunge(row)
|
||||
return _cand_dict(row)
|
||||
|
||||
|
||||
def _cand_dict(c: KnockingCandidate) -> dict:
|
||||
return {
|
||||
"id": c.id,
|
||||
"character_id": c.character_id,
|
||||
"trigger": c.trigger,
|
||||
"draft": c.draft,
|
||||
"channel": c.channel,
|
||||
"status": c.status,
|
||||
"ruling": json.loads(c.ruling_json or "{}"),
|
||||
"created_at": c.created_at.isoformat() if c.created_at else None,
|
||||
"dispatched_at": c.dispatched_at.isoformat() if c.dispatched_at else None,
|
||||
}
|
||||
@@ -435,6 +435,10 @@ async def build_generation_prompt(
|
||||
)
|
||||
if activated:
|
||||
parts.append("【世界认知(世谱命中)】\n" + "\n".join(f"- {line}" for line in activated))
|
||||
# 辰正时态感知(M8):客观时间语境注入投影(不附情绪臆测)
|
||||
from app.domains.zhengchen import temporal_context
|
||||
|
||||
parts.append(temporal_context())
|
||||
if transcript:
|
||||
parts.append(f"【共同经历(祖先路径)】\n{transcript}")
|
||||
parts.append(f"【当前问题】\n{expand(question.content)}")
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
"""天工阁域:受托任务(分解/并行/验收,无魂籍)+ 后台 Run 编排(M8)。"""
|
||||
|
||||
from app.domains.tiangong import models, service # noqa: F401
|
||||
|
||||
__all__ = ["models", "service"]
|
||||
@@ -0,0 +1,68 @@
|
||||
"""天工阁 API:受托任务(分解/派发/验收)。"""
|
||||
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.api.v1.deps import get_current_user
|
||||
from app.domains.tiangong import service
|
||||
from app.schemas.auth import CurrentUser
|
||||
|
||||
task_router = APIRouter(prefix="/tasks", tags=["tiangong"])
|
||||
|
||||
|
||||
class TaskCreateRequest(BaseModel):
|
||||
character_id: str | None = None
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
brief: str = ""
|
||||
acceptance_criteria: str = ""
|
||||
parent_task_id: str | None = None
|
||||
|
||||
|
||||
class DecomposeRequest(BaseModel):
|
||||
subtasks: list[dict]
|
||||
|
||||
|
||||
class AcceptRequest(BaseModel):
|
||||
accepted: bool
|
||||
|
||||
|
||||
@task_router.post("", status_code=201)
|
||||
async def create_task_api(
|
||||
payload: TaskCreateRequest, user: CurrentUser = Depends(get_current_user)
|
||||
) -> dict:
|
||||
return await service.create_task(
|
||||
owner_scope=user.owner_scope,
|
||||
character_id=payload.character_id,
|
||||
title=payload.title,
|
||||
brief=payload.brief,
|
||||
acceptance_criteria=payload.acceptance_criteria,
|
||||
parent_task_id=payload.parent_task_id,
|
||||
)
|
||||
|
||||
|
||||
@task_router.get("")
|
||||
async def list_tasks_api(
|
||||
user: CurrentUser = Depends(get_current_user), parent: str | None = "root"
|
||||
) -> list[dict]:
|
||||
return await service.list_tasks(user.owner_scope, parent=None if parent == "all" else parent)
|
||||
|
||||
|
||||
@task_router.post("/{task_id}/decompose", status_code=201)
|
||||
async def decompose_api(
|
||||
task_id: str, payload: DecomposeRequest, user: CurrentUser = Depends(get_current_user)
|
||||
) -> list[dict]:
|
||||
return await service.decompose(task_id, user.owner_scope, payload.subtasks)
|
||||
|
||||
|
||||
@task_router.post("/{task_id}/dispatch")
|
||||
async def dispatch_api(
|
||||
task_id: str, request: Request, user: CurrentUser = Depends(get_current_user)
|
||||
) -> dict:
|
||||
return await service.dispatch(task_id, user.owner_scope, request.app.state)
|
||||
|
||||
|
||||
@task_router.post("/{task_id}/accept")
|
||||
async def accept_api(
|
||||
task_id: str, payload: AcceptRequest, user: CurrentUser = Depends(get_current_user)
|
||||
) -> dict:
|
||||
return await service.accept(task_id, user.owner_scope, accepted=payload.accepted)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""天工阁表模型:后台受托任务(无魂籍的功能代理任务)。
|
||||
|
||||
设计依据 mandate-and-capability-model.md §7 与 PRD §9.5:
|
||||
- 任务 Agent 是功能代理,没有魂籍、缘契、情态或独立长期身份;
|
||||
- 承载受托任务、有限分解、受控并行与按证据验收;
|
||||
- 后台 Run(runs.kind=background_task)不占前台席位、不构成第二意识。
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.core.ids import new_id
|
||||
from app.core.time import utc_now
|
||||
from app.db.base import Base
|
||||
|
||||
|
||||
class BackstageTask(Base):
|
||||
"""受托任务:委托包 + 验收标准 + 结果证据;可分解(parent 链)受控并行。"""
|
||||
|
||||
__tablename__ = "backstage_tasks"
|
||||
|
||||
id: Mapped[str] = mapped_column(String(80), primary_key=True, default=lambda: new_id("task"))
|
||||
owner_scope: Mapped[str] = mapped_column(String(80), nullable=False, index=True)
|
||||
# 委托对象人物(可空:纯功能任务无人物语境)
|
||||
character_id: Mapped[str | None] = mapped_column(
|
||||
String(80), ForeignKey("characters.id"), nullable=True, index=True
|
||||
)
|
||||
# 父任务(分解链:子任务并行执行,全部完成后父任务进入待验收)
|
||||
parent_task_id: Mapped[str | None] = mapped_column(
|
||||
String(80), ForeignKey("backstage_tasks.id"), nullable=True, index=True
|
||||
)
|
||||
title: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
# 最小委托包(受托边界:达成目标与停止条件;任务 Agent 不扩使命)
|
||||
brief: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
# 按证据验收:明确的完成判据
|
||||
acceptance_criteria: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
# pending / running / awaiting_acceptance / accepted / rejected / failed
|
||||
status: Mapped[str] = mapped_column(String(30), nullable=False, default="pending", index=True)
|
||||
# 执行产出(净化摘要 + 证据引用;不构成身份/记忆写入)
|
||||
result_digest: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
evidence_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")
|
||||
# 关联后台 Run(kind=background_task,不占前台席位)
|
||||
run_id: Mapped[str | None] = mapped_column(String(80), index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
|
||||
completed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
@@ -0,0 +1,211 @@
|
||||
"""天工阁应用服务:受托任务(分解/并行/验收)与后台 Run 编排。
|
||||
|
||||
铁律(identity-continuity.md §4 / mandate-and-capability-model.md §7):
|
||||
- 后台受托 Run 不占前台席位(并行于前台对话);
|
||||
- 任务 Run 不是第二意识:**无身份写入路径**——不触发记忆候选、不写魂籍/铸魂、
|
||||
不建缘契(专项断言钉死);产出只作为任务结果证据回呈;
|
||||
- 达到预算/期限或连续失败后保留证据、停止并请命(P1 以任务失败态承载)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.errors import AppError
|
||||
from app.core.time import utc_now
|
||||
from app.db.session import AsyncSessionLocal
|
||||
from app.domains import one_qi
|
||||
from app.domains.tiangong.models import BackstageTask
|
||||
from app.models.character import Character
|
||||
|
||||
|
||||
async def create_task(
|
||||
*,
|
||||
owner_scope: str,
|
||||
character_id: str | None,
|
||||
title: str,
|
||||
brief: str,
|
||||
acceptance_criteria: str,
|
||||
parent_task_id: str | None,
|
||||
) -> dict:
|
||||
"""登记受托任务(pending;分解任务挂 parent 链)。"""
|
||||
if character_id:
|
||||
await _owned(character_id, owner_scope)
|
||||
async with AsyncSessionLocal() as session:
|
||||
task = BackstageTask(
|
||||
owner_scope=owner_scope,
|
||||
character_id=character_id,
|
||||
parent_task_id=parent_task_id,
|
||||
title=title,
|
||||
brief=brief,
|
||||
acceptance_criteria=acceptance_criteria,
|
||||
)
|
||||
session.add(task)
|
||||
await session.commit()
|
||||
session.expunge(task)
|
||||
return _task_dict(task)
|
||||
|
||||
|
||||
async def decompose(task_id: str, owner_scope: str, subtasks: list[dict]) -> list[dict]:
|
||||
"""有限分解:登记子任务(受控并行由各自后台 Run 承载)。"""
|
||||
parent = await _owned_task(task_id, owner_scope)
|
||||
created = []
|
||||
for sub in subtasks:
|
||||
created.append(
|
||||
await create_task(
|
||||
owner_scope=owner_scope,
|
||||
character_id=parent["character_id"],
|
||||
title=str(sub.get("title", ""))[:200],
|
||||
brief=str(sub.get("brief", "")),
|
||||
acceptance_criteria=str(sub.get("acceptance_criteria", "")),
|
||||
parent_task_id=task_id,
|
||||
)
|
||||
)
|
||||
return created
|
||||
|
||||
|
||||
async def dispatch(task_id: str, owner_scope: str, app_state) -> dict:
|
||||
"""派发后台 Run(kind=background_task,不占前台席位)。
|
||||
|
||||
任务 Prompt = 最小委托包(目标+验收标准+停止条件);结果回填 result_digest,
|
||||
任务进入 awaiting_acceptance。人物可为空——纯功能任务无人物语境。
|
||||
"""
|
||||
task = await _owned_task(task_id, owner_scope)
|
||||
if task["status"] not in ("pending",):
|
||||
raise AppError("invalid_request", "任务不在可派发状态。", status_code=409)
|
||||
async with AsyncSessionLocal() as session:
|
||||
row = await session.get(BackstageTask, task_id)
|
||||
row.status = "running"
|
||||
await session.commit()
|
||||
|
||||
from app.kernel import Kernel
|
||||
|
||||
kernel: Kernel | None = getattr(app_state, "kernel", None)
|
||||
if kernel is None:
|
||||
raise AppError("service_unavailable", "Kernel 未就绪。", status_code=503)
|
||||
|
||||
prompt = (
|
||||
f"【受托任务】{task['title']}\n"
|
||||
f"委托包:{task['brief']}\n"
|
||||
f"验收标准:{task['acceptance_criteria'] or '按委托包目标验收'}\n"
|
||||
f"停止条件:完成验收标准即止;不得扩展使命。"
|
||||
)
|
||||
run = await kernel.start_backstage_run(
|
||||
character_id=task["character_id"],
|
||||
prompt=prompt,
|
||||
owner_id=owner_scope,
|
||||
on_task_final=_make_finalizer(task_id, owner_scope),
|
||||
)
|
||||
async with AsyncSessionLocal() as session:
|
||||
row = await session.get(BackstageTask, task_id)
|
||||
row.run_id = run.id
|
||||
await session.commit()
|
||||
await one_qi.emit(
|
||||
"task.dispatched", character_id=task["character_id"],
|
||||
payload={"task_id": task_id, "run_id": run.id}, source="tiangong",
|
||||
)
|
||||
return {"task_id": task_id, "run_id": run.id, "status": "running"}
|
||||
|
||||
|
||||
def _make_finalizer(task_id: str, owner_scope: str):
|
||||
"""Run 完成回调:回填结果、进入待验收。"""
|
||||
|
||||
async def _finalize(content: str, status: str) -> None:
|
||||
async with AsyncSessionLocal() as session:
|
||||
row = await session.get(BackstageTask, task_id)
|
||||
if row is None or row.owner_scope != owner_scope:
|
||||
return
|
||||
row.result_digest = (content or "")[:4000]
|
||||
row.status = "awaiting_acceptance" if status == "completed" else "failed"
|
||||
row.completed_at = utc_now()
|
||||
await session.commit()
|
||||
await _cascade_parent(task_id)
|
||||
|
||||
return _finalize
|
||||
|
||||
|
||||
async def _cascade_parent(task_id: str) -> None:
|
||||
async with AsyncSessionLocal() as session:
|
||||
task = await session.get(BackstageTask, task_id)
|
||||
if task is None or task.parent_task_id is None:
|
||||
return
|
||||
parent_id = task.parent_task_id
|
||||
children = (
|
||||
await session.execute(
|
||||
select(BackstageTask).where(BackstageTask.parent_task_id == parent_id)
|
||||
)
|
||||
).scalars().all()
|
||||
terminal = {"awaiting_acceptance", "accepted", "rejected", "failed"}
|
||||
if children and all(c.status in terminal for c in children):
|
||||
parent = await session.get(BackstageTask, parent_id)
|
||||
if parent is not None and parent.status in ("pending", "running"):
|
||||
parent.status = "awaiting_acceptance"
|
||||
parent.result_digest = "\n".join(
|
||||
f"〔{c.title}〕{c.result_digest[:400]}" for c in children
|
||||
)
|
||||
parent.completed_at = utc_now()
|
||||
await session.commit()
|
||||
|
||||
|
||||
async def accept(task_id: str, owner_scope: str, *, accepted: bool) -> dict:
|
||||
"""按证据验收:accepted / rejected。"""
|
||||
await _owned_task(task_id, owner_scope)
|
||||
async with AsyncSessionLocal() as session:
|
||||
row = await session.get(BackstageTask, task_id)
|
||||
if row.status not in ("awaiting_acceptance", "failed"):
|
||||
raise AppError("invalid_request", "任务不在待验收状态。", status_code=409)
|
||||
row.status = "accepted" if accepted else "rejected"
|
||||
await session.commit()
|
||||
await one_qi.emit(
|
||||
"task.accepted" if accepted else "task.rejected",
|
||||
character_id=None, payload={"task_id": task_id}, source="tiangong",
|
||||
)
|
||||
return {"task_id": task_id, "status": row.status}
|
||||
|
||||
|
||||
async def list_tasks(owner_scope: str, *, parent: str | None = "root") -> list[dict]:
|
||||
"""任务清单(默认根任务;parent=None 全量)。"""
|
||||
async with AsyncSessionLocal() as session:
|
||||
stmt = select(BackstageTask).where(BackstageTask.owner_scope == owner_scope)
|
||||
if parent == "root":
|
||||
stmt = stmt.where(BackstageTask.parent_task_id.is_(None))
|
||||
elif parent is not None:
|
||||
stmt = stmt.where(BackstageTask.parent_task_id == parent)
|
||||
rows = (await session.execute(stmt.order_by(BackstageTask.created_at.desc()))).scalars().all()
|
||||
return [_task_dict(r) for r in rows]
|
||||
|
||||
|
||||
async def _owned(character_id: str, owner_scope: str) -> None:
|
||||
async with AsyncSessionLocal() as session:
|
||||
character = await session.get(Character, character_id)
|
||||
if character is None or character.owner_scope != owner_scope:
|
||||
raise AppError("not_found", "人物不存在。", status_code=404)
|
||||
|
||||
|
||||
async def _owned_task(task_id: str, owner_scope: str) -> dict:
|
||||
async with AsyncSessionLocal() as session:
|
||||
row = await session.get(BackstageTask, task_id)
|
||||
if row is None or row.owner_scope != owner_scope:
|
||||
raise AppError("not_found", "任务不存在。", status_code=404)
|
||||
session.expunge(row)
|
||||
return _task_dict(row)
|
||||
|
||||
|
||||
def _task_dict(t: BackstageTask) -> dict:
|
||||
return {
|
||||
"id": t.id,
|
||||
"character_id": t.character_id,
|
||||
"parent_task_id": t.parent_task_id,
|
||||
"title": t.title,
|
||||
"brief": t.brief,
|
||||
"acceptance_criteria": t.acceptance_criteria,
|
||||
"status": t.status,
|
||||
"result_digest": t.result_digest,
|
||||
"evidence": json.loads(t.evidence_json or "{}"),
|
||||
"run_id": t.run_id,
|
||||
"created_at": t.created_at.isoformat() if t.created_at else None,
|
||||
"completed_at": t.completed_at.isoformat() if t.completed_at else None,
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
"""辰正:时态感知横切能力(rewrite/1.0 M8 重实现)。
|
||||
|
||||
计算核复用 modules/time_sense(snapshot/lunar——符文引擎依赖同源);
|
||||
本模块提供投影级入口:``temporal_context()`` 产出【时态感知】提示段,
|
||||
经符文展开后进入镜树/内核 prompt 组装。守一期间不得虚构等待与孤独
|
||||
(identity-continuity.md §4)——时态只陈述客观时间语境。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from app.modules.time_sense.snapshot import SnapshotInput, compute_snapshot
|
||||
|
||||
_WEEKDAY_CN = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
|
||||
|
||||
|
||||
def _default_input(now: datetime | None) -> SnapshotInput:
|
||||
current = now or datetime.now(UTC)
|
||||
return SnapshotInput(
|
||||
now=current,
|
||||
timezone="Asia/Shanghai",
|
||||
anniversaries=[],
|
||||
acquaintance_anchor=current,
|
||||
last_active_at=current,
|
||||
)
|
||||
|
||||
|
||||
def temporal_context(now: datetime | None = None) -> str:
|
||||
"""时态感知投影段:客观时间语境(不附情绪臆测——那是调节层的事)。"""
|
||||
snap = compute_snapshot(_default_input(now))
|
||||
weekday = _WEEKDAY_CN[snap.weekday]
|
||||
parts = [
|
||||
f"现在是{snap.solar_date} {weekday} {snap.day_period}(本地时区 {snap.timezone})",
|
||||
]
|
||||
if snap.lunar is not None:
|
||||
parts.append(f"农历{snap.lunar.month}月{snap.lunar.day}日")
|
||||
if snap.season:
|
||||
parts.append(snap.season)
|
||||
return "【时态感知】" + ",".join(parts)
|
||||
|
||||
|
||||
__all__ = ["temporal_context"]
|
||||
Reference in new issue
Block a user