胖鱼 PEtFiSh 技术白皮书PEtFiSh Technical Whitepaper
v0.6.2 · 2026-05
目录 / Contents
- 定位与设计哲学Positioning & Design Philosophy
- 架构总览Architecture Overview
- Companion Gateway(常伴层)Companion Gateway (Always-Present Layer)
- 上下文治理(守护层)Context Governance (Guarding Layer)
- 质量门禁(可信层)Quality Gates (Trust Layer)
- TrustSkills治理引擎TrustSkills Governance Engine
- 反迎合校准(秉正层)Anti-Sycophancy Calibration (No-Compromise Layer)
- 平台适配层Platform Adaptation Layer
- Pack体系Pack System
- Companion内核Companion Core
- 关键技术决策Key Technical Decisions
A. 定位与设计哲学A. Positioning & Design Philosophy
胖鱼的定位是AI伙伴,不是工具集。PEtFiSh is positioned as an AI companion, not a toolbox.
工具的特征是被动等待调用。伙伴的特征是始终在场、主动参与。这个区别决定了整个架构的设计方向:Tools wait passively for invocation. Companions are always present, actively participating. This distinction drives the entire architecture:
- 常伴:Companion Gateway在每条消息前自动执行,不需要用户主动触发Always-Present: Companion Gateway executes automatically before every message, no user trigger needed
- 守护:持续监测上下文状态和能力缺口,在问题累积之前介入Guarding: Continuously monitors context state and capability gaps, intervenes before problems accumulate
- 可信:推荐的每个能力单元都经过验证,信任链可追溯Verified Trust: Every recommended capability unit is validated, trust chain is traceable
- 秉正:在评审和裁决中不迎合,标准不因便利降格No Compromise: No sycophancy in reviews and judgments, standards don't bend for convenience
Skill管理(跨平台安装、生命周期治理)是实现这些承诺的技术手段,不是产品目的本身。Skill management (cross-platform install, lifecycle governance) is the technical means to deliver these promises, not the product goal itself.
B. 架构总览B. Architecture Overview
┌──────────────────────────────────────────────────────────────┐ │ 用户 / AI Agent │ │ │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ Companion Gateway (每条消息自动执行) │ │ │ │ ┌──────────────┐ ┌──────────────┐ │ │ │ │ │ Topic Detect │ │ Skill Sense │ │ │ │ │ │ (话题检测) │ │ (能力感知) │ │ │ │ │ └──────┬───────┘ └──────┬───────┘ │ │ │ │ └────────┬────────┘ │ │ │ └──────────────────┼──────────────────────────────────┘ │ │ ↓ │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ /petfish (14 subcommands) install.ps1 / .sh │ │ │ └──────────────────┬──────────────────────────────────┘ │ │ ↓ │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ Companion Core (10 skills) + Context Router (31 MCP)│ │ │ └──────────────────┬──────────────────────────────────┘ │ │ ↓ │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ Pack Layer (10 packs · pack-manifest.json schema) │ │ │ └──────────────────┬──────────────────────────────────┘ │ │ ↓ │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ Platform Adapter (platforms.json · 8 platforms) │ │ │ └──────────────────────────────────────────────────────┘ │ └──────────────────────────────────────────────────────────────┘
| 层Layer | 职责Responsibility | 关键文件Key Files |
|---|---|---|
| Gateway层Gateway Layer | 每条消息自动话题检测+能力感知Automatic topic detection + capability sensing per message | AGENTS.md Companion Gateway sectionCompanion Gateway section |
| 用户接口层User Interface Layer | /petfish 14个子命令 + 4个install脚本14 subcommands + 4 install scripts |
install.ps1/sh, remote-install.ps1/sh |
| Companion层Companion Layer | 10个内置skill + 31个MCP tools10 built-in skills + 31 MCP tools | packs/petfish-companion-skill/, packs/fish-trail/ |
| Pack层Pack Layer | 10个skill pack,按领域组织10 skill packs, organized by domain | packs/*/pack-manifest.json |
| 平台适配层Platform Adaptation Layer | 8平台路径映射、指令翻译、配置合并8-platform path mapping, instructions translation, config merge | platforms.json |
C. Companion Gateway(常伴层)C. Companion Gateway (Always-Present Layer)
Gateway是胖鱼"伙伴"特性的技术实现。它被注入到项目的instructions文件(AGENTS.md / CLAUDE.md等),在AI Agent处理每条用户消息之前强制执行。The Gateway is the technical implementation of PEtFiSh's companion nature. It's injected into the project's instructions file (AGENTS.md / CLAUDE.md etc.), forced to execute before the AI Agent processes each user message.
执行流程Execution Flow
用户消息 → Step 1: Topic Check → Step 2: Skill Sense → Step 3: 正常处理
↓ ↓
risk_level判定 三层缺口检测
low: 静默 Tier 1: 白名单
medium: 一行说明 Tier 2: 意图感知
high: 暂停+建议 Tier 3: 静默通过
Step 1: Topic Check
调用MCP tool topic_detect,传入用户消息和当前session。根据返回的risk_level执行对应行为:Calls MCP tool topic_detect with user message and current session. Executes behavior based on returned risk_level:
| risk_level | 行为Behavior |
|---|---|
| low (0-30) | 静默继续Silent continue |
| medium (31-60) | 回复开头一行说明上下文继承范围One-line note at reply start indicating context inheritance scope |
| high (61-100) | 暂停正常处理,说明话题变更风险,建议fork/switch/resetPause normal processing, explain topic-change risk, suggest fork/switch/reset |
Step 2: Skill Sense(三层检测模型)Step 2: Skill Sense (Three-Tier Detection)
Tier 1: 白名单匹配Tier 1: Keyword Whitelist
基于 catalog_query.py 中的TRIGGERS关键词表进行匹配。命中 + 未安装 + 本session未推荐 → 回复末尾附带一行推荐。Keyword whitelist matching based on TRIGGERS in catalog_query.py. Match + not installed + not recommended this session → one-line recommendation at reply end.
Tier 2: 意图感知Tier 2: Intent-Aware Detection
当Tier 1未命中时,判断用户消息是否暗示了当前环境无法满足的能力需求。必须同时满足三个条件才触发:When Tier 1 doesn't match, assess whether user message implies a capability need the environment can't satisfy. Must satisfy all three conditions to trigger:
- 需要外部集成或专项工具(API调用、邮件、消息推送、图表生成等)Needs external integration or specialized tools (API calls, email, messaging, chart generation, etc.)
- Agent原生能力不覆盖(超出代码编写、文件操作、git、搜索等内置能力)Agent native capabilities don't cover it (beyond coding, file ops, git, search, etc.)
- 当前已安装skill不覆盖Currently installed skills don't cover it
置信度低于70%时不触发。宁静默不打扰。Confidence below 70% → don't trigger. When in doubt, stay silent.
Tier 3: 无缺口Tier 3: No Gap
Tier 1和Tier 2均未命中 → 不输出任何推荐。Neither Tier 1 nor Tier 2 triggered → no output.
节制规则Restraint Rules
- 每个领域/关键词每session最多推荐1次Each domain/keyword recommended at most once per session
- 不确定是否为缺口时,倾向于不触发When uncertain whether it's a gap, default to not triggering
- MCP不可用时静默降级,不阻塞正常工作MCP unavailable → silent degradation, normal work not blocked
Debug Mode
配置 .petfish/fish-trail/config.yaml 中 debug: true 时,每次Gateway决策可见:When .petfish/fish-trail/config.yaml has debug: true, every Gateway decision is visible:
🐟 [gateway] topic: relation=continue, risk=12 (low), confidence=0.92 → silent 🐟 [gateway] skill: no gap → pass 🐟 [gateway] topic: relation=switch, risk=67 (high), confidence=0.85 → suggest fork 🐟 [gateway] skill: gap=deploy (detected "Docker部署") → recommend 🐟 [gateway] topic: relation=continue, risk=5 (low), confidence=0.95 → silent 🐟 [gateway] skill: tier2 gap detected (intent="发邮件通知", need="邮件服务集成") → suggest search
D. 上下文治理(守护层)D. Context Governance (Guarding Layer)
fish-trail pack通过本地MCP server提供话题感知的上下文治理。纯Python标准库实现,零外部依赖。fish-trail pack provides topic-aware context governance via local MCP server. Pure Python stdlib, zero external dependencies.
核心能力Core Capabilities
| 能力Capability | 说明Description |
|---|---|
| 话题检测Topic Detection | 自动识别用户消息所属话题,支持CJK文本,输出关系类型和风险等级Automatically identifies topic of user message, supports CJK text, outputs relation type and risk level |
| 污染评分Contamination Scoring | 量化跨话题上下文污染风险(0-100),高于60时主动提示Quantifies cross-topic context contamination risk (0-100), proactively alerts when above 60 |
| 上下文隔离Context Isolation | 按话题构建Context Package,隔离不同话题的文件引用、决策和成果Builds Context Package per topic, isolates file references, decisions, and artifacts across topics |
| 会话管理Session Management | 话题感知的会话绑定、跨会话恢复、多Agent归因、活动查询Topic-aware session binding, cross-session resume, multi-agent attribution, activity query |
7种话题关系类型7 Topic Relation Types
| 类型Type | 策略Strategy |
|---|---|
| continue | 完全继承当前上下文Fully inherit current context |
| fork | 从当前topic分叉,继承部分上下文Fork from current topic, inherit partial context |
| switch | 切换到已有topic,加载该topic的Context PackageSwitch to existing topic, load its Context Package |
| merge | 合并两个topic(需用户确认)Merge two topics (requires user confirmation) |
| archive | 归档当前topic,冻结上下文Archive current topic, freeze context |
| reset | 清空上下文,建立干净包Clear context, establish clean package |
| bridge | 两个topic间建立桥接,只继承交叉部分Bridge between two topics, inherit only the intersection |
31个 MCP Tools
| 组Group | 工具数Count | 典型工具Key Tools |
|---|---|---|
| 话题管理Topic Management | 8 | topic_detect, topic_create, topic_update, topic_merge |
| 上下文构建Context Building | 5 | context_build, context_get_active, contamination_score |
| 使用追踪Usage Tracking | 5 | track_file_reference, track_decision, track_artifact |
| 会话管理Session Management | 10 | session_bind, session_resume, session_query_activity |
E. 质量门禁(可信层)E. Quality Gates (Trust Layer)
skill目录
│
├─① Lint (skill-lint)
│ └─ Score ≥ 80/100? → Continue or FAIL
│
├─② Security Audit (skill-security-auditor)
│ └─ Risk ≤ 0.5? No CRITICAL? → Continue or FAIL
│
├─③ Metadata Validation
│ └─ name, version, description valid? → Continue or FAIL
│
└─④ Decision
├─ ✅ PASS → 允许发布
├─ ⚠️ CONDITIONAL → 需人工确认
└─ ❌ FAIL → 必须先修复
Lint评分规则(100分制)Lint Scoring (100-point scale)
起始100分,按finding扣分:error(-10)、warn(-5)、info(-1)。规则前缀:ST0xx结构完整性、FM0xx前置元数据、CT0xx内容质量、SC0xx安全模式、PY0xx Python脚本质量。40+条规则。Starts at 100, deducted per finding: error(-10), warn(-5), info(-1). Rule prefixes: ST0xx structural integrity, FM0xx front matter, CT0xx content quality, SC0xx security patterns, PY0xx Python script quality. 40+ rules.
Security Audit评分Security Audit Scoring
风险分 = Σ(finding权重),归一化到0.0-1.0。权重:info=0.0 / low=0.1 / medium=0.3 / high=0.6 / critical=1.0。检测类别:代码执行(subprocess/eval/exec)、硬编码凭证、网络调用、文件系统、markdown注入。Risk score = Σ(finding weights), normalized to 0.0-1.0. Weights: info=0.0 / low=0.1 / medium=0.3 / high=0.6 / critical=1.0. Detection categories: code execution (subprocess/eval/exec), hardcoded credentials, network calls, filesystem access, markdown injection.
F. TrustSkills治理引擎F. TrustSkills Governance Engine
质量门禁做静态模式匹配,快但浅。TrustSkills是另一层——按可执行行为分析。Quality gates do static pattern matching — fast but shallow. TrustSkills is another layer — behavioral analysis.
六个风险维度Six Risk Dimensions
| 维度Dimension | 权重Weight | 含义Meaning |
|---|---|---|
| shell | 0.25 | shell执行、子进程调用、高权限工具声明Shell execution, subprocess calls, high-privilege tool declarations |
| network | 0.25 | 网络访问、外部域名、远程通信Network access, external domains, remote communication |
| file_write | 0.15 | 文件写入能力、批量写、宽范围写入File write capability, bulk writes, broad-scope writes |
| sensitive_data | 0.15 | 接触密钥、凭证、敏感系统路径Access to keys, credentials, sensitive system paths |
| script_risk | 0.10 | 脚本内的file IO、subprocess、network行为证据Evidence of file IO, subprocess, network behavior inside scripts |
| persistence | 0.10 | 持久化副作用:服务安装、状态写入、配置驻留Persistent side effects: service install, state writes, config residency |
五级治理动作Five Governance Actions
| 级别Level | 阈值Threshold | 含义Meaning |
|---|---|---|
| allow | ≥ 0.00 | 直接放行Allow directly |
| allow_with_ask | ≥ 0.15 | 允许执行,先征得用户确认Allow with prior user confirmation |
| sandbox_required | ≥ 0.35 | 需要沙箱隔离执行Requires sandbox isolation |
| manual_review_required | ≥ 0.55 | 必须进入人工复核Must enter manual review |
| deny | 红线命中Red line hit | 硬拒绝,不走阈值计算Hard deny, bypasses threshold scoring |
四条红线规则Four Red Lines
| 红线Red Line | 含义Meaning |
|---|---|
| subprocess-network-combo | subprocess + network,可能形成download-and-exec路径subprocess + network, potential download-and-exec path |
| dangerous-system-paths | 读写/etc/passwd、~/.ssh/id_*等敏感路径Read/write to /etc/passwd, ~/.ssh/id_* and other sensitive paths |
| sudo-without-approval | 声明sudo/su但没有显式approval_requiredDeclares sudo/su without explicit approval_required |
| subprocess-os-combo | subprocess + os级操作,任意命令/高破坏面行为subprocess + OS-level ops, arbitrary commands / high-blast-radius behavior |
命中任何一条红线 → deny,不走分数阈值。Hitting any red line → deny. No score threshold.
G. 反迎合校准(秉正层)G. Anti-Sycophancy Calibration (No-Compromise Layer)
calibrate pack解决AI在评审、方案评估等判断型任务中倾向于顺着用户说的问题。The calibrate pack addresses AI tendency to agree with users in review, evaluation, and judgment tasks.
- 先中性化问题,再给结论——不直接顺着用户预设表态Neutralize the question first, then give conclusion — don't follow user's preset framing
- 先给评分维度,再做判断——至少补一个反方或替代方案Give evaluation dimensions first, then judge — include at least one counterpoint or alternative
- 结论与置信度分开表达——证据不足时明确降级Express conclusion and confidence separately — explicitly downgrade when evidence is insufficient
- 可与其他skill组合使用:
course-outline-design + calibrate、code-review + calibrateCan be combined with other skills:course-outline-design + calibrate,code-review + calibrate
触发条件:用户要求评审、评价、critique、feedback,或提出确认性问题("对吗?""是不是?""你同意吗?")。简单事实查询、翻译、排版默认不启用。Triggers: user requests review, evaluation, critique, feedback, or asks confirmation questions ("Is this right?", "Do you agree?"). Simple fact queries, translation, and formatting do not trigger by default.
H. 平台适配层H. Platform Adaptation Layer
核心数据源:platforms.jsonCore Data Source: platforms.json
platforms.json是平台适配的唯一数据源。每个平台定义:skills目录、commands目录、agents目录、配置文件、指令文件、检测标记、合并策略。platforms.json is the single source of truth for platform adaptation. Each platform defines: skills dir, commands dir, agents dir, config file, instructions file, detection marker, merge strategy.
8平台路径映射8-Platform Path Mapping
| 平台Platform | Skills目录Skills Dir | 指令文件Instructions File | 检测标记Detection Marker |
|---|---|---|---|
| OpenCode | .opencode/skills/ | AGENTS.md | .opencode/ |
| Claude Code | .claude/skills/ | CLAUDE.md | .claude/ |
| Codex | .agents/skills/ | AGENTS.md | .codex/ |
| Cursor | .cursor/skills/ | .cursor/rules/*.mdc | .cursor/ |
| GitHub Copilot | .github/skills/ | copilot-instructions.md | .github/copilot-* |
| Windsurf | .windsurf/skills/ | .windsurfrules | .windsurf/ |
| Antigravity | .agents/skills/ | AGENTS.md + GEMINI.md | GEMINI.md |
| Universal | .agents/skills/ | AGENTS.md | (fallback)(fallback) |
指令翻译机制Instructions Translation
| 方法Method | 适用Applies To | 行为Behavior |
|---|---|---|
| marker_based | OpenCode, Codex, Copilot, Windsurf, Antigravity, Universal | 用<!-- BEGIN/END pack -->标记合并,不覆盖已有内容Merge with <!-- BEGIN/END pack --> markers, preserves existing content |
| rename_with_header | Claude Code, Copilot, Windsurf | 复制内容,加平台特定头部Copy content with platform-specific header |
| wrap_as_mdc | Cursor | 包装为.mdc前置元数据格式Wrap as .mdc front matter format |
I. Pack体系I. Pack System
pack-manifest.json 统一schemaUnified Schema
{
"name": "petfish-companion-skill",
"version": "0.6.2",
"description": "AI Worker's Companion...",
"compatibility": "opencode, claude, codex, cursor, copilot, windsurf, antigravity, universal",
"skill_count": 10,
"command_count": 1,
"agent_count": 0,
"skills": ["petfish-companion", "marketplace-connector", ...],
"commands": ["petfish"],
"agents": []
}
10 个Pack定位Packs
| Pack | Alias | 承诺映射Promise Mapping | 规模Scale |
|---|---|---|---|
| petfish-companion-skill | companion | 常伴Always-Present | 10 skills, 1 cmd |
| fish-trail | context | 守护Guarding | 1 skill, 31 MCP |
| anti-sycophancy-calibration-pack | calibrate | 秉正No Compromise | 1 skill |
| trustskills-governance-pack | trust | 可信Verified Trust | 1 skill |
| project-initializer-skill | init | — | 1 skill, 1 cmd |
| opencode-course-skills-pack | course | — | 15 skills, 10 cmds, 8 agents |
| repo-deploy-ops-skill-pack | deploy | — | 7 skills |
| petfish-style-skill | petfish | — | 1 skill |
| opencode-skill-pack-testcases-usage-docs | testdocs | — | 2 skills |
| opencode-ppt-skills | ppt | — | 2 skills |
J. Companion内核:10个内置SkillJ. Companion Core: 10 Built-in Skills
mine → author → lint → audit → gate → optimize → eval ↓ ↓ ↓ ↓ ↓ ↓ ↓ 发现 创建 格式 安全 门禁 优化 评测 + marketplace-connector (跨市场搜索) + skill-usage-tracker (使用追踪) + petfish-companion (总控调度)
| Skill | 职责Responsibility |
|---|---|
| petfish-companion | 总控调度,动态读取pack-manifest.json,路由/petfish 14个子命令Orchestration, dynamically reads pack-manifest.json, routes /petfish 14 subcommands |
| marketplace-connector | 跨6来源搜索(胖鱼仓库、SkillKit、Smithery、Glama、anthropics/skills、GitHub)Search across 6 sources (PEtFiSh repo, SkillKit, Smithery, Glama, anthropics/skills, GitHub) |
| skill-author | 生成符合规范的skill脚手架Generate standards-compliant skill scaffold |
| skill-lint | 100分制格式检查,40+规则100-point format check, 40+ rules |
| repo-skill-miner | 分析GitHub仓库,提取可skill化模块Analyze GitHub repos, extract skill-able modules |
| skill-security-auditor | 静态安全分析,0.0-1.0风险评分Static security analysis, 0.0-1.0 risk score |
| quality-gate | 编排lint+audit,给出PASS/CONDITIONAL/FAILOrchestrates lint + audit, outputs PASS/CONDITIONAL/FAIL |
| skill-description-optimizer | 分析触发准确率和歧义度Analyze trigger accuracy and ambiguity |
| skill-trigger-evaluator | 用测试集跑precision/recallRun precision/recall against test sets |
| skill-usage-tracker | 记录使用频率和反馈评分Record usage frequency and feedback scores |
Catalog动态加载Catalog Dynamic Loading
catalog_query.py通过_find_packs_root()从脚本位置向上查找packs/目录遍历manifest。在用户机器上(无packs/目录),自动回退到installed-packs.json获取版本和skill_count信息。新pack只需放入packs/<name>/pack-manifest.json,不需修改代码。catalog_query.py uses _find_packs_root() to walk up from script location and traverse manifests in packs/. On user machines (no packs/ dir), automatically falls back to installed-packs.json for version and skill_count. New packs only need packs/<name>/pack-manifest.json — no code changes required.
K. 关键技术决策记录K. Key Technical Decisions
| 决策Decision | 选择Choice | 理由Rationale |
|---|---|---|
| 伙伴实现Companion implementation | Instructions注入 + MCPInstructions injection + MCP | Gateway注入instructions文件,确保每条消息都执行;MCP提供状态持久化Gateway injected into instructions file ensures execution per message; MCP provides state persistence |
| 能力感知Capability sensing | 三层模型Three-tier model | Tier 1快速匹配,Tier 2深度意图分析,Tier 3静默——平衡准确率和打扰度Tier 1 fast match, Tier 2 deep intent analysis, Tier 3 silent — balances accuracy and interruption |
| 平台配置Platform config | platforms.json单一数据源platforms.json single source of truth | 新平台只改一个文件Adding a new platform requires changing one file |
| Pack发现Pack discovery | 运行时遍历manifest + registry fallbackRuntime manifest traversal + registry fallback | 开发环境读packs/,用户机器读installed-packs.jsonDev env reads packs/, user machines read installed-packs.json |
| 安装脚本Install scripts | PowerShell + Bash双版本PowerShell + Bash dual versions | 覆盖Windows + macOS/LinuxCovers Windows + macOS/Linux |
| 指令合并Instructions merge | marker-based merge | 不覆盖用户已有内容,升级时替换first+去重Preserves existing user content, upgrades replace-first + dedup |
| Context Router MCP | 纯Python标准库Pure Python stdlib | 零依赖,任何环境可运行Zero dependencies, runs in any environment |
| 会话管理Session management | 话题绑定而非全局sessionTopic-bound rather than global session | 支持多话题并行、跨会话恢复Supports parallel topics and cross-session resume |
| 反迎合校准Anti-sycophancy calibration | 组合式skillComposable skill | 可叠加到任何评审类skill,不改变原skill逻辑Stackable onto any review skill without changing original skill logic |
| 平台检测fallbackPlatform detection fallback | universal + 环境报告environment report | 未检测到平台时报告OS/shell/runtimes,给出操作建议When no platform detected, reports OS/shell/runtimes and provides actionable suggestions |