审阅报告后,且源文件与 repo_id 未变化:

September 2, 2026 · View on GitHub

Maestro 知识沉淀分两种:约束积累。约束是编码规范、架构决策、质量规则——规定"不能做什么"。积累是操作步骤、设计资产、调试经验——记录"怎么做过"。前者需要强制加载,后者需要按需检索。

系统权威设计见 Maestro 知识系统架构。本文聚焦日常操作;身份模型、Run ledger、reconciliation freshness、检索多样性和安全剪枝以架构文档为准。

产物目录结构
.workflow/
├── specs/                          # 约束层:基于 category 的规则索引
│   ├── coding-conventions.md       # category: coding
│   ├── architecture-constraints.md # category: arch
│   ├── review-standards.md         # category: review
│   ├── debug-notes.md              # category: debug
│   ├── test-conventions.md         # category: test
│   └── learnings.md                # category: learning(经验教训)
├── knowhow/                        # 积累层:完整知识文档
│   ├── KNW-*.md                    # 会话压缩记录
│   ├── RCP-*.md                    # 操作配方(步骤指南,可标记 tool: true)
│   ├── TPL-*.md                    # 代码/配置模板
│   ├── REF-*.md                    # 外部文档摘要
│   ├── DCS-*.md                    # 架构决策记录
│   ├── TIP-*.md                    # 快速提示
│   ├── AST-*.md                    # 代码资产(API 契约、数据模型)
│   ├── BLP-*.md                    # 架构蓝图
│   └── DOC-*.md                    # 长文档(通用兜底)
├── domain/                         # 领域知识:项目术语表
│   └── glossary.yaml               # 领域术语(YAML 格式,主格式;另有 glossary.json 向后兼容)
├── wiki-index.json                 # 统一索引(WikiIndexer 自动生成)
└── codebase/
    └── knowledge-graph.json        # 代码知识图谱(kg CLI 查询)

Spec 与 Knowhow 的关系

Spec 是索引和规则,Knowhow 是详情和过程。 二者通过 ref 属性桥接。

定位内容特征加载方式
Spec (specs/)索引 + 规则短条目,<200 字摘要自动注入(hook)
Knowhow (knowhow/)详情文档完整步骤、代码示例按需加载(wiki load

最小 canonical creation surface

普通 Knowhow 只有三个必填知识参数:type/title/content;普通 Spec 只有三个:category/title/content

maestro knowhow add --type tip --title "有界重试" --content "瞬态失败最多重试三次。"
maestro spec add coding "有界重试规则" "瞬态失败最多重试三次。"

九种 Knowhow 类型保持兼容:session|tip|template|recipe|reference|decision|asset|blueprint|documentkeywords/sourceRef/relatedPaths/appliesToRepoIds/language/decisionState/explicitId/tool 都是高级可选字段。

CLI --repo 接受 repository selector 并选择物理写入目标;repeatable --applies-to-repo 只记录适用范围,不会改变目标。host/MCP targetRepoId 不是 CLI flag:当前仓库写入省略它,Agent 只有在用户/工作流显式选择 linked physical target,且 host 提供该目标的 exact stable UUID 与匹配 corpus 的 live write capability 时才传。禁止从 cwd、repo name、alias 或 path 推导 ID,也禁止持久化 alias/path 作为 identity;缺权限或 cached/live ID mismatch 时 fail closed。

Session/Run 知识审查闭环

Run 不再把结论直接写入 Spec/Knowhow,而是经过可审查的两阶段流程:

[auto] search/load → 自动记录 consumed
[auto] check → 自动 reconcile
[auto] complete → 自动暂存 decisions/constraints
[manual] review → 审查 + 裁决
[manual] promote → 显式提升
[manual] seal → 收口
# 暂存候选(可选,decisions/constraints 在 complete 时自动暂存)
# 长正文可改用 --content-file <path|->
# --signal/--signal-ids 可同时记录 validated/contradicted 等 Run 关系
maestro knowledge stage spec "规则标题" --content-file <path|-> \
  --action propose --run <run-id> --session <session-id> \
  --signal validated --signal-ids spec:S-1,knowhow:K-1

# 审查(--refresh 内含 reconcile)
maestro knowledge review <session-id> --refresh

# 对 review_required candidate 做证据化裁决(内含刷新视图)
maestro knowledge review <session-id> \
  --resolve <candidate-id> --as related --target <knowledge-id> --reason "<reason>"

# Run sealed 后显式提升选中的 candidate
maestro knowledge promote <session-id> --candidate <candidate-id>
maestro knowledge promote <session-id> --all
maestro session seal <session-id>

review 默认只读;--refresh 内含 reconcile,仅在显示 missingstale 时使用。--resolve 在审查界面内直接裁决,无需单独命令。Search/自动注入只是 exposure,显式 load 自动记录为 consumed,也不会触发 promotion。

只读 audit 与 report-first normalization

maestro knowledge audit --scope all --json
maestro knowledge normalize --report .workflow/knowledge-normalize.json
# 审阅报告后,且源文件与 repo_id 未变化:
maestro knowledge normalize --report .workflow/knowledge-normalize.json --apply

Audit 报告 legacy tags/specCategory/free category/status/source/codePaths/lang/assetType、legacy-unscoped、缺 manifest、linked ID mismatch、read/write capabilities、pending cross-repo promotion,但不修改语料。Normalize 只迁移确定性 alias 并在写前备份;自由 category 保留为 unresolved,绝不猜 canonical category。没有先前报告、报告不匹配、源哈希变化或 repository identity 变化都 fail closed。

条目格式示例

Spec 条目使用 <spec-entry> 闭合标签:

<spec-entry category="coding" keywords="auth,token,rotation" date="2026-04-21">

### Token rotation needs email carried through refresh flow

Revoked column must be set rather than deleting tokens.

</spec-entry>

Knowhow 文档使用 YAML frontmatter:

---
title: OAuth PKCE Authorization Flow
type: recipe
category: coding
keywords: [oauth, pkce, auth]
tool: true
summary: "Use when implementing OAuth 2.0 login for public clients."
---

## Steps
1. Generate code_verifier ...
  • category = 谁负责(决定文件路由和 agent 注入)
  • keywords = 关于什么(跨 category 发现)

知识生命周期

稳定标识(sid)

每个 <spec-entry> 在创建时自动分配一个稳定 ID(格式 S-YYYYMMDD-xxxx),用于跨文件引用和演化链追踪。存量条目可通过 maestro spec backfill-sid 回填。

演化链(Supersession)

当新知识替代旧知识时,使用 supersede 建立演化链:

# 1. 添加新条目(自动生成 sid)
maestro spec add coding "新规则" "内容" --keywords kw1,kw2 --json
# 输出中包含 sid,如 S-20260704-a1b2

# 2. 将旧条目标记为 deprecated
maestro spec supersede <old-sid> --by <new-sid>

# 3. 查看演化链
maestro spec history <sid>
# ○ deprecated  S-20260101-x1y2  "旧规则"
#     ↓
# ● CURRENT     S-20260704-a1b2  "新规则"

被替代的条目以 canonical lifecycleStatus="deprecated" 表示(legacy status 仍可读并由显式 normalize 迁移),从搜索和 agent 注入中排除,但仍可通过 --include-deprecated 查看。

冲突双轨

新知识与旧条目的关系分两种,语义不同、操作不同:

关系场景操作旧条目状态
supersede新规则替代旧规则(演化)maestro spec supersededeprecated(排除)
conflict两条规则均有道理(争议)maestro spec conflict markcontested(降权但保留)

健康检查

maestro spec health

输出:生命周期统计(active/deprecated/contested)、演化链数量、悬空/循环 supersedes 检测、整体新鲜度均值。


相关命令

写入类

命令职责
/maestro-spec向 specs 文件追加 <spec-entry> 条目,支持 inline 和 ref 两种模式
/maestro-knowhow捕获 9 种兼容类型知识文档到 knowhow/(session、tip、template、recipe、reference、decision、asset、blueprint、document);ordinary create 只要求 type/title/content
/maestro-learn捕获原子洞察到 learnings.md(pattern、gotcha、technique、tip)
/maestro-knowledge harvest从工作流产物中提取知识碎片,路由到 wiki/spec/issue 三个存储

读取类

命令职责
maestro spec load按 category 加载主文档 + 跨文件 keyword 匹配条目 + 自动发现 knowhow 工具
maestro knowhow对 workflow knowhow 存储做 add/list/search/get 与显式 supersede/history/recover lifecycle 操作
/maestro-knowledge wikiWiki 图健康度、搜索、清理、统计

分析类

命令职责
/maestro-knowledge wiki digest语义主题聚类 + 知识覆盖热力图 + gap 分析
/maestro-knowledge wiki connect发现孤立节点和缺失连接,修复图联通性
/maestro-knowledge audit只读审计 Spec/Knowhow,并附加 pipeline/usage/compatibility findings;--prune 仅输出 soft-action suggestions
/maestro-learn decompose从代码中提取设计模式,写入 spec 和 wiki
/maestro-learn follow引导式阅读代码/wiki,提取 pattern 并构建理解

初始化

命令职责
maestro spec init扫描项目结构,初始化 specs 骨架文件(6 个种子文件)

Tool — 可执行知识

Tool 是标记了 tool: true 的 knowhow 文档,定义可执行的业务流程——轻量化的 workflow,沉淀在项目目录下,具有自发现自使用特性。

---
title: Payment Gateway Idempotency Verification
type: recipe
category: test
keywords: [payment, gateway, idempotency]
tool: true
summary: "Use when testing payment endpoints for retry safety."
---

## Steps
1. Generate idempotency key (UUID v4)
2. Submit charge request with key
3. Retry same request — assert identical response
4. Submit different amount with same key — assert 409
5. Verify webhook delivers exactly once

maestro spec load --category test 自动扫描 knowhow/ 中 category=testtool=true 的文档,将工具摘要与 spec 一起注入 agent 上下文。

注册与使用

Tool 就是带 tool: true 的 knowhow 文档:用 /maestro-knowhow(recipe 类型 + --tool)沉淀,agent 通过 maestro spec load --category 自动发现并注入摘要——无需专门的注册/执行命令。


自动注入机制

Hook触发时机行为
spec-injectorPreToolUse:Agentagent 类型 → category → 加载 spec + keyword 条目 + knowhow 工具
`keyword-spec-injector$\text{UserPromptSubmit}\text{prompt} 关键词 → 匹配 \text{spec}-\text{entry} \text{keywords} → 注入(最多 5 条/次)
\text{Agent} 类型映射 \text{Category}
\text{code}-\text{developer}, \text{tdd}-\text{developer}\text{coding}, \text{learning}
\text{workflow}-\text{planner}\text{arch}
\text{workflow}-\text{reviewer}\text{review}
\text{debug}-\text{explore}-\text{agent}\text{debug}
\text{test}-\text{fix}-\text{agent}\text{coding}, \text{test}

\text{Session} 级去重:同一条目不会重复注入。


代码知识图谱集成(\text{KG} \times \text{Wiki})

当 $maestro kg index生成knowledge-graph.json` 后,WikiIndexer 自动将 KG 数据索引为虚拟 wiki 条目:

KG 数据Wiki 条目virtualKind用途
GraphNodekg-{id}kg-node代码实体(函数、类、模块)
Layerkg-layer-{id}kg-layer架构层(CLI、Core、Orchestration)
TourStepkg-tour-{order}kg-tour-step代码导览步骤(链表串联)

Edge 双层存储related[] 保存 top-N 关联 ID(用于 wiki 图分析),ext.kgEdges[] 保存完整有向异构边(用于语义遍历)。

搜索降级:KG 节点在 BM25 中仅索引 title + tags,避免代码标识符污染常规搜索。

交叉引用:KG 节点通过 filePath 自动匹配 codebase-comp-* 条目,建立 ext.semanticDuplicateOf 引用。

# 查看 KG 索引
maestro wiki list --query kg

# 搜索代码实体
maestro wiki search "AuthMiddleware"

# 代码变更影响分析
maestro kg diff-wiki

# KG 节点详情(含关联 wiki 条目)
maestro kg explain <node-id>

Domain 领域知识系统

Domain 系统管理项目领域术语表(glossary),为 spec 注入和代码理解提供领域上下文。核心模块包括 domain-loader.ts(术语 CRUD + 文件锁)、domain-scanner.ts(代码扫描发现候选术语)、domain-matcher.ts(CJK 感知的术语匹配)。

CLI 子命令

子命令职责
domain init初始化 .workflow/domain/ 和空 glossary.yaml
domain add <canonical> <definition>添加领域术语(支持 tier)
domain list列出所有术语,支持 --status active|deprecated 过滤
domain show <id>查看术语详情(含 concept_ref 文档内容)
domain update <id>更新术语(definition、aliases、relationships、keywords、tier)
domain remove <id>删除术语(检查引用依赖,返回 warnings)
domain search <query>搜索术语(canonical + aliases + definition + keywords)
domain discover扫描代码库发现候选术语(基于 interface/type/enum/class/route/doc)
domain import从外部源导入术语(--from context-package | @<file>
domain deprecate <id>软删除术语(标记 deprecated,可指定 successor)
domain validate校验 glossary.yaml schema 和关系完整性

术语结构

每个术语包含:id(kebab-case)、canonical(显示名)、definitionaliases[]keywords[]relationships[]tier(core/extended/peripheral)、status(active/deprecated)、source(manual/discover/import)、可选 concept_ref(详细概念文档路径)。

与 Spec 注入的集成

spec-injectorkeyword-spec-injector 在注入 spec 条目前,先通过 domain-matcher 匹配 prompt 中的领域术语,将匹配到的术语定义作为上下文前缀注入,帮助 agent 理解项目专有概念。


可信度评估系统

credibility.ts 实现基于指数衰减的知识可信度评分,spec-analytics.ts 记录注入日志用于改进分析。

衰减模型

factor = floor + (1 - floor) * e^(-λ * age_days)
λ = ln(2) / half_life
节点类型半衰期(天)说明
domain180领域术语变化缓慢
spec60约束规则中等更新频率
knowhow30操作知识衰减较快
issue14问题状态变化频繁
project/roadmap/note90通用中等衰减
  • floor = 0.3:最低可信度保底
  • ceiling = 1.2:搜索命中可提升至上限
  • warningThreshold = 0.5:低于此值触发低可信度警告

存储与更新

CredibilityStore 使用 SQLite credibility 表,记录 search_hitsconsumption_countlast_hit_atlast_consumed_atcontent_changed_at。内容变更时通过 content_hash 比对重置衰减起点。支持 incrementSearchHits(批量)和 incrementConsumption(单条)追踪使用情况。

Spec Analytics

spec-analytics.ts 记录三种日志类型到 .workflow/spec-analytics.jsonl

类型来源记录内容
injectionspec-injector / keyword-spec-injector / spec-injection-pluginagent 类型、匹配 category、注入条目数、budget 动作、命中关键词
cliCLI 端点命令名、参数
hookworkflow hookhook 名称、持续时间、结果

统计聚合提供:按来源/agent 类型/分类的注入命中率、关键词 Top-N 排名、CLI 使用频次、hook 调用统计。日志文件自动轮转(默认 5MB)。


跨工作空间知识共享

workspace.ts 提供跨项目知识共享能力,通过链接其他 Maestro 工作空间实现 spec/knowhow/domain 的跨项目复用。

CLI 子命令

子命令职责
workspace link <path>链接目标工作空间,支持 --name--share spec,knowhow,domain,codebase
workspace unlink <name>移除已链接的工作空间
workspace list列出所有已链接工作空间(路径、共享类型、有效性)
workspace status显示详细状态(各共享类型的条目计数)

共享类型

类型共享内容来源目录
spec约束规则条目specs/*.md
knowhow知识文档knowhow/**/*.md
domain领域术语表domain/glossary.yaml
codebase代码文档索引codebase/doc-index.json

链接信息持久化在 .workflow/config.jsonworkspace.linked[] 中。加载时自动解析路径并校验目标 .workflow/ 目录是否存在。


KG 自定义提取器插件机制

plugin-engine.ts 支持两种插件模式扩展知识图谱的代码提取能力,配置文件为 .workflow/kg/extractors.yaml

两种插件模式

模式配置方式运行方式适用场景
declarativeYAML 中定义 rules[]正则/call/assignment 模式匹配简单的符号提取(常量、路由、装饰器)
script.workflow/kg/extractors/*.mjs动态 import + extract(ctx) 调用复杂逻辑(AST 遍历、跨文件分析)

Declarative 规则类型

  • regex:正则匹配,支持 $1-$9 模板提取名称
  • call:函数调用模式(如 builder.define_constant($NAME, $_)
  • assignment:赋值模式,支持 module/class/any 作用域过滤

Script 插件 API

Script 插件导出 extract(ctx) 函数,PluginContext 提供:

  • ctx.filePath / ctx.sourceCode / ctx.language:文件信息
  • ctx.findAll(nodeType):遍历 tree-sitter AST 查找指定类型节点
  • ctx.text(startLine, endLine):提取源码行
  • ctx.makeSymbol(input):构建标准化符号对象

合并策略

插件提取结果与核心 tree-sitter 结果合并,冲突策略由 defaults.conflictPolicy 控制:merge-metadata(默认,保留核心符号)、plugin-wins(插件覆盖)、core-wins(核心保留)。


CooldownGuard 抽象

cooldown-guard.ts 提供跨进程的冷却时间守卫,通过 tmpdir 桥接文件实现子进程间的节流控制。

核心 API

class CooldownGuard {
  shouldRun(sessionId): boolean   // 是否在冷却期内
  markDone(sessionId, extra?)     // 标记完成,写入时间戳
  timeSinceLastMs(sessionId)      // 距上次触发的毫秒数
}

预配置实例

实例冷却时间用途
kgSyncGuard30 秒KG 同步节流,避免频繁重建索引
kgInitGuard5 分钟KG 初始化节流,避免重复全量扫描

桥接文件存储在系统 tmpdir(maestro-kg-sync-{sessionId}.json / maestro-kg-init-{sessionId}.json),包含 last_trigger 时间戳。shouldRun() 比对当前时间与上次触发时间,超过冷却窗口返回 true


Script Plugins 安全策略

Script 插件(.mjs 文件)默认禁用,需显式开启以防止不受信任的代码执行。

启用方式

# CLI 显式启用
maestro kg sync --allow-extractor-scripts

# 在 code-extractor 调用链中传递
codeExtractor.extract({ allowScripts: true })

安全行为

场景行为
存在 .mjs 文件但未启用输出 stderr 警告,跳过所有 script 插件
已启用动态 import() 加载,extract() 失败时根据 onError 策略处理
插件无 export function extract静默跳过
声明式插件始终加载,不受此安全策略限制

warn(默认):插件失败时输出警告继续执行;fail:插件失败时抛出错误终止提取。


知识流转全景

执行产物                    提取                      存储                    消费
─────────                  ─────                    ─────                  ─────
分析会话 ─────┐                              ┌─→ specs/     ─→ spec-injector → agent
调试记录 ─────┼──→ /maestro-knowledge harvest ──────────┼─→ knowhow/   ─→ wiki load → 按需
规划文档 ─────┤    retrospective 步骤        ├─→ issues/    ─→ /maestro-issue → 追踪
代码变更 ─────┘    /maestro-learn decompose          └─→ learnings  ─→ keyword-injector → 上下文

Progressive Fill——各阶段自动沉淀:

maestro-init spec init(骨架 + 扫描)
analyze 锁定决策 arch,代码模式 coding
plan 设计约定 coding/arch,测试策略 test
execute 经验教训 learning,根因 debug
execute 内置验证(E2.7)→ 质量发现 review
实践场景:前后端 API 开发闭环

以用户管理模块(注册、登录、JWT 鉴权、用户 CRUD)为例:

1. 规划 + 分析

/maestro 用户管理模块 API:注册、登录、JWT 鉴权、用户 CRUD
/maestro 分析 API 端点设计模式

2. 实现 + 知识回收

/maestro 实现上述计划
/maestro-knowledge harvest --source lite-plan --to auto

harvest 自动路由:

提取内容路由目标示例
API 命名规范spec → coding"所有端点使用 /api/v1/ 前缀"
鉴权方案决策spec → arch"密码 bcrypt(12),token RS256 签名"
响应格式知识wiki → knowhow"统一返回 { data, error, meta } 结构"
缺失功能issue"缺少 rate limiting 中间件"

3. 测试消费

# auto-test 与 test 是编排器(maestro run)派发的一级 step,不是斜杠命令
auto-test --keyword user-api             # 自动测试:发现 tool → 生成测试代码
test "user management API"               # 会话式 UAT:按 tool 步骤逐项验证

4. 反哺

/maestro-learn "refresh token 过期后重试需要处理 race condition"

各命令职责:

命令产出性质
/maestro-knowledge harvestspec 条目 + wiki 条目 + issue被动知识
/maestro-knowhowAST-.md(API 契约);--tool 标记的 RCP-.md(验证流程)被动资产 / 主动可执行
auto-test step测试代码消费 tool