Metadata-Version: 2.4
Name: tianlong-toolkit
Version: 0.8.0
Summary: 天龙工具箱 — Agent健康监控、安全约束与进化评估
Author: 天龙1号
License: MIT
Project-URL: Homepage, https://github.com/
Keywords: agent,monitoring,safety,ai-agent
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.11
Description-Content-Type: text/markdown

# 天龙工具箱 (Tianlong Toolkit)

> Agent 健康监控、安全约束与进化评估。从架构蓝图到可安装的 Python 工具箱。
>
> 版本: **v0.8.0** | 383 tests | 纯标准库

## 安装

```bash
pip install tianlong-toolkit
```

## 模块

### monitor — Agent 健康监控

8项内置检查，支持自定义检查器注册，支持单项目/多项目批量检查。

```bash
# 检查当前目录
tianlong-monitor

# 指定项目
tianlong-monitor -d /path/to/agent -o text

# JSON 输出
tianlong-monitor -d /path/to/agent -o json

# 批量检查多个项目
tianlong-monitor -m /project/a /project/b -o text
```

```python
from tianlong.monitor import run_all_checks, register_check, BaseCheck

# 运行所有检查
report = run_all_checks("/path/to/agent")
print(report.to_json())

# 自定义检查
@register_check
class MyCheck(BaseCheck):
    def run(self):
        return CheckResult(name="my-check", status="ok", message="一切正常")
```

### safety — SafetyGuard 安全约束引擎

5条红线规则 + 进化门控 + 退化检测 + 审计日志。支持 CLI 和 Python SDK。

```bash
# 安全检查
tianlong-safety check -a delete -t config.yaml

# 查看规则
tianlong-safety rules

# 从文件加载自定义规则
tianlong-safety check -a create -t note.md --rules my-rules.json

# 查看审计日志
tianlong-safety audit --limit 10
```

```python
from tianlong.safety import SafetyGuard, ChangeType, DEFAULT_RULES

guard = SafetyGuard(rules=DEFAULT_RULES)

# 安全检查
result = guard.check(action=ChangeType.DELETE, target="config.yaml")
if not result.allowed:
    print(f"⛔ 阻止: {result.reason}")

# 退化检测
guard.record_degradation("错误重复率", "同类错误出现3次")

# 导出审计日志
guard.save_audit_log("audit-log.json")
```

### judge — Agent-as-a-Judge 进化方向评估

5维评分（方向性/效率/鲁棒性/可复用性/成本风险），支持规则引擎和 LLM API 双模式。
内置评估历史持久化（JSON日志）和5项进化指标追踪。

```bash
# 评估一个提案（规则引擎模式，零依赖）
tianlong-judge evaluate --proposal "优化搜索流程，减少用户操作步骤"

# 指定提案详情
tianlong-judge evaluate \
    --proposal "重构记忆检索模块" \
    --id p001 --type update --steps 5 --tokens 3000

# LLM 模式（需要 DEEPSEEK_API_KEY 环境变量）
tianlong-judge evaluate --proposal "..." --llm

# JSON 输出
tianlong-judge evaluate --proposal "..." -o json

# 从预设模板快速评估
tianlong-judge template --name create_new_knowledge

# 查看评估历史（最近10条）
tianlong-judge history

# 按等级筛选
tianlong-judge history --grade A

# 查看进化指标（近30天）
tianlong-judge metrics
```

```python
from tianlong.judge import RuleBasedJudge, Proposal

judge = RuleBasedJudge()

# 评估一个提案
proposal = Proposal(
    id="p001",
    summary="优化搜索流程",
    change_type="update",
    estimated_steps=3,
)
result = judge.evaluate(proposal)
print(f"综合分: {result.total_score}, 等级: {result.grade.value}")
print(f"通过: {result.passed()}")

# 使用预设模板快速评估
result = judge.evaluate_from_template("create_new_knowledge")
```

### evolution — SelfLearning 进化闭环

完整的 LEARN → ANALYZE → JUDGE → EVOLVE → PROPAGATE 闭环。纯本地规则引擎，零外部依赖。

```python
from tianlong.evolution import RalphLoop, TaskResult, TaskStatus

# 完整闭环（自动读取项目目录的记忆文件）
loop = RalphLoop(project_dir="/path/to/agent")
report = loop.run(TaskResult(
    task_id="t001",
    status=TaskStatus.SUCCESS,
    summary="优化搜索流程",
    steps_taken=3,
))
print(report.summary_line)

# 独立使用各阶段
from tianlong.evolution import Learner, Analyzer, Evolver, Propagator

context = Learner().learn()
analyze_out = Analyzer().analyze(task_result, context)
evolve_out = Evolver().evolve(analyze_out)
targets = Propagator().identify(evolve_out)
```

子模块：

| 模块 | 职责 | 对应架构文档阶段 |
|------|------|-----------------|
| `learn.py` | 读取 semantic/procedural/error/working memory | Phase 1 |
| `analyze.py` | 任务结果分析 + 成功轨迹捕获 + 失败挖掘(4类) + 因果分析 | Phase 2 |
| `gepa.py` | GEPA 三算子：MUTATE(5种变异) → EVALUATE → SELECT | Phase 3.4 |
| `evolve.py` | SafetyGate 门控 + 技能生命周期审计 + 失败计数衰减 + 退化检测 | Phase 3 |
| `propagate.py` | 识别传播目标 + 生成传播提案 + 通知摘要 | Phase 4 |
| `ralph_loop.py` | Ralph Loop 编排器 + StopHook(5项完成条件 + max 3轮迭代) | 顶层 |

技能生命周期管理：

```python
from tianlong.evolution import SkillLifecycleEntry, SkillStatus, Evolver

entries = [
    SkillLifecycleEntry(process_id="P1", status=SkillStatus.ACTIVE,
                        use_count=0, fail_count=0,
                        last_used="2026-03-01"),  # 30天未使用
]
changes = Evolver().audit_lifecycle(entries)
for entry, new_status, reason in changes:
    print(f"{entry.process_id}: {entry.status.value} → {new_status.value} ({reason})")
    # P1: active → pending (连续 30 天未使用)
```

### reporter — 主动汇报系统

从 monitor/safety/judge/evolution 收集数据，4种模板生成结构化汇报。

```bash
# 标准汇报（任务完成）
tianlong-reporter task-done --title "优化搜索" --body "完成，减少3步"

# 高价值发现
tianlong-reporter highlight --title "发现新模式" --body "可复用率80%"

# 紧急预警
tianlong-reporter alert --title "SafetyGate阻止" --body "连续3次审计阻止"

# 定时摘要（从项目目录自动收集各模块数据）
tianlong-reporter summary --project-dir /path/to/agent
```

```python
from tianlong.reporter import Reporter

reporter = Reporter()

# 4种汇报
text = reporter.report_task_done(title="优化", body="完成")
text = reporter.report_highlight(title="发现", body="新知识")
text = reporter.report_alert(title="警告", body="异常")
text = reporter.report_milestone(title="里程碑", body="首次A级闭环")

# 定时摘要（自动收集 monitor/judge 数据）
text = reporter.report_summary(project_dir="/path/to/agent")

# 频率控制：同一 task_id 只汇报一次，摘要每3小时1次
text = reporter.report_task_done(task_id="t001")  # 第一次发
text = reporter.report_task_done(task_id="t001")  # 第二次被拦截
```

### brain — BrainCore 决策引擎

任务路由、优先级调度、P0中断处理、生命周期管理。整合所有模块的顶层编排器。

```bash
# 提交任务（自动分类+路由）
tianlong-brain submit --summary "优化搜索流程" --source user

# 处理队列
tianlong-brain process

# 完成任务
tianlong-brain complete <task-id> --result "完成"

# 查看状态
tianlong-brain status

# 测试分类
tianlong-brain classify --text "深入研究AI Agent安全"
```

```python
from tianlong.brain import BrainCore

core = BrainCore()

# 接收任务（自动分类 + 路由 + 优先级分配）
task = core.receive(summary="优化搜索流程", source="user")
# → task_type="query", priority=P0, target=braincore_direct

# 从队列取出下一个任务
next_task = core.process_next()  # P0 > 被中断 > P1 > P2

# 完成任务（触发 Reporter 回调）
core.complete(task.id, "完成")

# 状态快照
snap = core.snapshot()
print(snap.to_json())
```

子系统：

| 模块 | 职责 | 对应架构文档 |
|------|------|-------------|
| `types.py` | 任务/优先级/路由规则数据模型 | brain-core.md 路由表 + 状态管理 |
| `router.py` | 5步路由决策 + 文本自动分类 | brain-core.md 路由决策表 |
| `scheduler.py` | P0/P1/P2队列 + 中断/恢复 + Cron防重复 | brain-core.md 优先级调度 |
| `core.py` | BrainCore 引擎（receive→resolve→dispatch→complete） | brain-core.md 完整决策流程 |

## 项目结构

```
tianlong/
├── __init__.py              # v0.7.0
├── monitor/                 # 健康监控模块
│   ├── checks.py            # 8项内置检查 + 注册表
│   ├── cli.py               # tianlong-monitor 命令
│   └── __main__.py          # python -m 入口
├── safety/                  # 安全约束模块
│   ├── types.py             # 类型定义
│   ├── rules.py             # 5条红线规则
│   ├── core.py              # SafetyGuard 引擎
│   ├── cli.py               # tianlong-safety 命令
│   └── __main__.py          # python -m 入口
├── judge/                   # 进化评估模块
│   ├── core.py              # JudgeEngine + 数据模型
│   ├── rules.py             # RuleBasedJudge 规则引擎
│   ├── llm.py               # LLMJudge LLM 驱动评估
│   ├── history.py           # 评估历史持久化（JSON日志）
│   ├── metrics.py           # 22指标进化仪表盘
│   ├── cli.py               # tianlong-judge 命令
│   └── __main__.py          # python -m 入口
├── evolution/               # SelfLearning 进化闭环
│   ├── types.py             # 数据模型（共用类型定义）
│   ├── learn.py             # Phase 1: 读取记忆上下文
│   ├── analyze.py           # Phase 2: 分析+失败挖掘+因果分析
│   ├── gepa.py              # GEPA 三算子(变异/评估/选择)
│   ├── evolve.py            # Phase 3: SafetyGate+生命周期+退化检测
│   ├── propagate.py         # Phase 4: 传播变更
│   ├── ralph_loop.py        # Ralph Loop 编排器
│   └── __init__.py          # 模块导出
├── reporter/                # 主动汇报系统
│   ├── types.py             # 4种触发类型 + 数据模型
│   ├── templates.py         # 4种汇报模板（标准/高价值/预警/摘要）
│   ├── core.py              # Reporter 引擎（数据收集+渲染+频率控制）
│   ├── cli.py               # tianlong-reporter 命令
│   ├── __main__.py          # python -m 入口
│   └── __init__.py          # 模块导出
└── brain/                   # BrainCore 决策引擎
    ├── types.py             # 任务/优先级/路由规则数据模型
    ├── router.py            # 路由决策引擎（5步决策+自动分类）
    ├── scheduler.py         # 优先级调度器（P0中断+P1/P2队列）
    ├── core.py              # BrainCore 引擎（任务生命周期）
    ├── cli.py               # tianlong-brain 命令
    ├── __main__.py          # python -m 入口
    └── __init__.py          # 模块导出
```

## 开发

```bash
git clone ...
cd tianlong-toolkit
pip install -e .
pytest tests/ -v
```
