ln-810-performance-optimizer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePaths: File paths (,shared/,references/) are relative to skills repo root. If not found at CWD, locate this SKILL.md directory and go up one level for repo root. If../ln-*is missing, fetch files via WebFetch fromshared/.https://raw.githubusercontent.com/levnikolaevich/claude-code-skills/master/{path}
路径说明: 文件路径(、shared/、references/)均相对于技能仓库根目录。如果在当前工作目录(CWD)中未找到,请定位到本SKILL.md所在目录,再向上一级即为仓库根目录。若../ln-*目录缺失,可通过WebFetch从shared/获取文件。https://raw.githubusercontent.com/levnikolaevich/claude-code-skills/master/{path}
ln-810-performance-optimizer
ln-810-performance-optimizer
Type: L2 Domain Coordinator
Category: 8XX Optimization
Iterative diagnostic pipeline for performance optimization. Profiles the full request stack, classifies bottlenecks, researches industry solutions, and tests optimization hypotheses in multiple cycles — each cycle discovers and addresses different bottlenecks as fixing the dominant one reveals the next (Amdahl's law).
类型: L2领域协调器
分类: 8XX优化类
用于性能优化的迭代诊断流程。对完整请求栈进行性能分析,分类瓶颈,调研行业解决方案,并通过多轮次循环测试优化假设——每一轮循环都会发现并解决不同的瓶颈,因为解决主要瓶颈后,下一个瓶颈会显现(遵循Amdahl's law)。
Overview
概述
| Aspect | Details |
|---|---|
| Input | |
| Output | Optimized code with verification proof, or diagnostic report with recommendations |
| Workers | ln-811 (profiler) → ln-812 (researcher) → ln-813 (plan validator) → ln-814 (executor) |
| Flow | Phases 0-1 once, then Phases 2-8 loop up to |
| 维度 | 详情 |
|---|---|
| 输入 | |
| 输出 | 附带验证依据的优化后代码,或包含建议的诊断报告 |
| 协作组件 | ln-811(性能分析器)→ ln-812(调研器)→ ln-813(方案验证器)→ ln-814(执行器) |
| 流程 | 阶段0-1仅执行一次,随后阶段2-8循环执行最多 |
Workflow
工作流
Phases: Pre-flight → Parse Input → CYCLE [ Profile → Wrong Tool Gate → Research → Set Target → Write Context → Validate Plan → Execute → Cycle Boundary ] → Collect → Report → Meta-Analysis
阶段: 预检查 → 解析输入 → 循环 [ 性能分析 → 工具适配校验 → 方案调研 → 设定目标 → 编写上下文 → 验证方案 → 执行优化 → 循环边界 ] → 结果汇总 → 生成报告 → 元分析
Phase 0: Pre-flight Checks
阶段0:预检查
| Check | Required | Action if Missing |
|---|---|---|
| Target identifiable | Yes | Block: "specify file, endpoint, or pipeline to optimize" |
| Observed metric provided | Yes | Block: "specify what metric is slow (e.g., response time, throughput)" |
| Git clean state | Yes | Block: "commit or stash changes first" |
| Test infrastructure | Yes | Block: "tests required for safe optimization" |
| Stack detection | Yes | Detect via ci_tool_detection.md |
| Service topology | No | Detect multi-service architecture (see below) |
| State file | No | If |
MANDATORY READ: Load for test/build detection.
shared/references/ci_tool_detection.md| 检查项 | 是否必填 | 缺失时操作 |
|---|---|---|
| 目标可识别 | 是 | 阻断:"请指定要优化的文件、端点或流水线" |
| 提供观测指标 | 是 | 阻断:"请指定性能缓慢的指标(例如:响应时间、吞吐量)" |
| Git工作区干净 | 是 | 阻断:"请先提交或暂存更改" |
| 测试基础设施存在 | 是 | 阻断:"安全优化需要测试支持" |
| 技术栈检测 | 是 | 通过ci_tool_detection.md进行检测 |
| 服务拓扑 | 否 | 检测多服务架构(见下文) |
| 状态文件 | 否 | 若 |
必读要求: 加载以检测测试/构建工具。
shared/references/ci_tool_detection.mdService Topology Detection
服务拓扑检测
Detect if optimization target spans multiple services with accessible code:
| Signal | How to Detect | Result |
|---|---|---|
| Git submodules | | List of service paths |
| Monorepo | | List of service paths |
| Docker Compose | | List of service paths + ports |
| Workspace config | | List of module paths |
Output: — map of service names to code paths. Pass to ln-811 for cross-service tracing.
service_topologyIf single-service (no signals): — standard single-codebase profiling.
service_topology = null检测优化目标是否跨多个可访问代码的服务:
| 信号 | 检测方式 | 结果 |
|---|---|---|
| Git子模块 | | 服务路径列表 |
| 单体仓库 | 查看是否存在 | 服务路径列表 |
| Docker Compose | | 服务路径列表+端口 |
| 工作区配置 | | 模块路径列表 |
输出: — 服务名称到代码路径的映射,传递给ln-811用于跨服务追踪。
service_topology若为单服务(无上述信号): — 采用标准单代码库性能分析。
service_topology = nullState Persistence
状态持久化
Save after each phase completion. Enables resume on interruption.
.optimization/{slug}/state.jsonjson
{
"target": "src/api/endpoint.py::handler",
"slug": "endpoint-handler",
"cycle_config": { "max_cycles": 3, "plateau_threshold": 5 },
"current_cycle": 1,
"cycles": [
{
"cycle": 1,
"status": "done",
"baseline": { "wall_time_ms": 6300 },
"final": { "wall_time_ms": 3800 },
"improvement_pct": 39.7,
"target_met": false,
"bottleneck": "I/O-Network: 13 sequential HTTP calls",
"hypotheses_applied": ["H1", "H2"],
"branch": "optimize/ln-814-align-endpoint-c1-20260315"
}
],
"phases": {
"0_preflight": { "status": "done", "ts": "2026-03-15T10:00:00Z" },
"2_profile": { "status": "done", "ts": "2026-03-15T10:05:00Z", "worker": "ln-811" },
"8_execute": { "status": "pending" }
}
}Phase status values: → → |
pendingrunningdonefailedUpdate state BEFORE and AFTER each phase. For Agent-delegated phases (7, 8): set before launch, / after Agent returns.
runningdonefailedOn startup: if exists, ask user: "Resume from cycle {current_cycle}, phase {last incomplete}?" or "Start fresh?"
.optimization/{slug}/state.jsonPhases are per-cycle — reset at each cycle boundary. + phases tells the exact resumption point.
current_cycle每个阶段完成后保存,支持中断后恢复。
.optimization/{slug}/state.jsonjson
{
"target": "src/api/endpoint.py::handler",
"slug": "endpoint-handler",
"cycle_config": { "max_cycles": 3, "plateau_threshold": 5 },
"current_cycle": 1,
"cycles": [
{
"cycle": 1,
"status": "done",
"baseline": { "wall_time_ms": 6300 },
"final": { "wall_time_ms": 3800 },
"improvement_pct": 39.7,
"target_met": false,
"bottleneck": "I/O-Network: 13 sequential HTTP calls",
"hypotheses_applied": ["H1", "H2"],
"branch": "optimize/ln-814-align-endpoint-c1-20260315"
}
],
"phases": {
"0_preflight": { "status": "done", "ts": "2026-03-15T10:00:00Z" },
"2_profile": { "status": "done", "ts": "2026-03-15T10:05:00Z", "worker": "ln-811" },
"8_execute": { "status": "pending" }
}
}阶段状态值: → → |
pendingrunningdonefailed每个阶段执行前后都要更新状态。对于Agent委托的阶段(7、8):启动前设为,Agent返回后设为/。
runningdonefailed启动时:若存在,询问用户:"是否从第{current_cycle}轮、未完成的{last incomplete}阶段恢复?" 或 "是否重新开始?"
.optimization/{slug}/state.json阶段为每轮循环专属 —— 循环边界时重置阶段状态。 + 阶段信息可确定准确的恢复点。
current_cycleCycle Management
循环管理
| Parameter | Default | Description |
|---|---|---|
| max_cycles | 3 | Maximum optimization cycles |
| plateau_threshold | 5 | Minimum improvement % to continue to next cycle |
Each cycle: Profile → Gate → Research → Target → Context → Validate → Execute.
Each cycle naturally discovers different bottlenecks (fixing dominant reveals next per Amdahl's law).
| 参数 | 默认值 | 描述 |
|---|---|---|
| max_cycles | 3 | 最大优化循环次数 |
| plateau_threshold | 5 | 进入下一轮循环所需的最小性能提升百分比 |
每轮循环:性能分析 → 校验 → 调研 → 设定目标 → 编写上下文 → 验证方案 → 执行优化。
遵循Amdahl's law,每轮循环会自然发现不同的瓶颈(解决主要瓶颈后,下一个瓶颈会显现)。
Stop Conditions (evaluated after each cycle)
停止条件(每轮循环后评估)
| Condition | Action |
|---|---|
| STOP — target reached |
improvement < | STOP — plateau detected |
| STOP — budget exhausted |
| ln-812 returns 0 hypotheses | STOP — no further optimization found |
| 条件 | 操作 |
|---|---|
| 停止 — 已达成目标 |
性能提升 < | 停止 — 已进入性能瓶颈期 |
| 停止 — 已用尽循环次数 |
| ln-812返回0个优化假设 | 停止 — 未发现进一步优化空间 |
Between Cycles
循环间操作
1. Collect cycle results (improvement, branch, hypotheses applied)
2. Merge cycle branch: git merge {cycle_branch} --no-edit
3. Record cycle summary in state.json
4. Run /compact to compress conversation context
5. Display: ═══ CYCLE {N}/{max} ═══ Previous: {bottleneck} → {improvement}%
6. Reset phase statuses in state.json for new cycleIf merge has conflicts → BLOCK: report partial results, user resolves manually.
1. 收集循环结果(性能提升、分支、已应用假设)
2. 合并循环分支:git merge {cycle_branch} --no-edit
3. 在state.json中记录循环摘要
4. 运行/compact压缩对话上下文
5. 显示:════ CYCLE {N}/{max} ═══ 上轮瓶颈:{bottleneck} → 性能提升{improvement}%
6. 在state.json中重置阶段状态以开启新循环若合并存在冲突 → 阻断:上报部分结果,由用户手动解决冲突。
Phase 1: Parse Input
阶段1:解析输入
Parse user input into structured problem statement:
| Field | Source | Example |
|---|---|---|
| target | User-specified | |
| observed_metric | User-specified | |
| target_metric | User-specified OR Phase 5 | |
| max_cycles | User-specified OR default | 3 |
| audit_report | Optional | Path to ln-650 output (additional hints for profiler) |
If not provided by user, defer to Phase 5 (after research establishes industry benchmark).
target_metric将用户输入解析为结构化问题描述:
| 字段 | 来源 | 示例 |
|---|---|---|
| target | 用户指定 | |
| observed_metric | 用户指定 | |
| target_metric | 用户指定 或 阶段5生成 | |
| max_cycles | 用户指定 或 默认值 | 3 |
| audit_report | 可选 | ln-650输出路径(为性能分析器提供额外提示) |
若用户未提供,则推迟到阶段5(调研确定行业基准后)处理。
target_metricGenerate slug
生成slug
Derive from target for per-task isolation: sanitize to , max 50 chars.
{slug}[a-z0-9_-]| Target | Slug |
|---|---|
| |
| |
| |
All artifacts go to : , , , .
.optimization/{slug}/context.mdstate.jsonln-814-log.tsvprofile_test.sh从target生成以实现任务隔离:清理为格式,最长50字符。
{slug}[a-z0-9_-]| Target | Slug |
|---|---|
| |
| |
| |
所有产物存储到:、、、。
.optimization/{slug}/context.mdstate.jsonln-814-log.tsvprofile_test.shCYCLE LOOP: Phases 2-8
循环流程:阶段2-8
FOR cycle = 1 to max_cycles:
IF cycle > 1:
1. Merge previous cycle branch: git merge {previous_branch} --no-edit
2. /compact — compress conversation context
3. Display cycle header:
═══ CYCLE {cycle}/{max_cycles} ═══
Previous: {bottleneck} → {improvement}% improvement
Remaining gap: {current_metric} vs target {target_metric}
4. Reset phases in state.json
5. Update current_cycle in state.json
Phase 2: Profile
Phase 3: Wrong Tool Gate
Phase 4: Research
Phase 5: Set Target (cycle 1 only — persists across cycles)
Phase 6: Write Context
Phase 7: Validate Plan
Phase 8: Execute
CYCLE BOUNDARY: evaluate stop conditions (see below)FOR cycle = 1 to max_cycles:
IF cycle > 1:
1. 合并上一轮循环分支:git merge {previous_branch} --no-edit
2. /compact — 压缩对话上下文
3. 显示循环头部:
═══ CYCLE {cycle}/{max_cycles} ═══
上轮:{bottleneck} → 性能提升{improvement}%
剩余差距:{current_metric} vs 目标{target_metric}
4. 在state.json中重置阶段状态
5. 在state.json中更新current_cycle
阶段2:性能分析
阶段3:工具适配校验
阶段4:方案调研
阶段5:设定目标(仅第1轮 —— 跨循环保留)
阶段6:编写优化上下文
阶段7:验证方案
阶段8:执行优化
循环边界:评估停止条件(见下文)Phase 2: Profile — DELEGATE to ln-811
阶段2:性能分析 —— 委托给ln-811
Do NOT trace code, read function bodies, or profile yourself. INVOKE the profiler skill.
Invoke:
Skill(skill: "ln-811-performance-profiler")Pass: problem statement from Phase 1 + audit_report path (if provided).
On cycle 2+: pass same problem statement. ln-811 re-profiles the now-optimized code — test_command is rediscovered, new baseline measured, new bottlenecks found.
ln-811 will: discover/create test → run baseline (multi-metric) → static analysis + suspicion stack → instrument → build performance map.
Receive: performance_map, suspicion_stack, optimization_hints, wrong_tool_indicators, e2e_test info.
请勿自行追踪代码、读取函数体或进行性能分析,请调用性能分析器技能。
调用方式:
Skill(skill: "ln-811-performance-profiler")传递参数: 阶段1生成的问题描述 + audit_report路径(若提供)。
第2轮及以后:传递相同的问题描述。ln-811会重新分析已优化的代码 —— 重新发现测试命令、测量新基准、找到新瓶颈。
ln-811会:发现/创建测试 → 运行基准测试(多指标)→ 静态分析 + 疑点栈 → 插桩 → 生成性能映射。
返回结果: performance_map、suspicion_stack、optimization_hints、wrong_tool_indicators、e2e_test信息。
Phase 3: Wrong Tool Gate (4-Level Verdict)
阶段3:工具适配校验(4级 verdict)
Evaluate profiler results using structured verdict (adapted from ln-500 quality gate model).
| Verdict | Condition | Action |
|---|---|---|
| PROCEED | | Continue to Phase 4 (research) |
| CONCERNS | Measurement variance > 20% OR baseline unstable OR partial metrics only | Continue with warning — note uncertainty in context file |
| BLOCK | | See below |
| WAIVED | User explicitly overrides BLOCK ("try anyway") | Continue despite indicators — log user override |
使用结构化结论评估性能分析器结果(改编自ln-500质量门模型)。
| 结论 | 条件 | 操作 |
|---|---|---|
| 继续 | | 进入阶段4(调研) |
| 需注意 | 测量方差>20% 或 基准不稳定 或 仅获取部分指标 | 继续执行,但在上下文文件中记录不确定性 |
| 阻断 | | 见下文 |
| 豁免 | 用户明确覆盖阻断("无论如何尝试") | 忽略指标继续执行 —— 记录用户覆盖操作 |
BLOCK on Cycle 2+
第2轮及以后的阻断
On cycle 2+, or is a SUCCESS signal — previous cycles brought performance to acceptable level. Break the cycle loop and proceed to Phase 9 (Final Report).
already_optimizedwithin_industry_norm第2轮及以后,或是成功信号 —— 前几轮循环已将性能提升到可接受水平。终止循环,进入阶段9(最终报告)。
already_optimizedwithin_industry_normBLOCK Diagnostics
阻断诊断信息
| Indicator | Diagnostic Message |
|---|---|
| "Bottleneck is {service} latency ({X}ms). Recommend: negotiate SLA / switch provider / add cache layer." |
| "Current performance ({X}ms) is within industry norm ({Y}ms). No optimization needed." |
| "Bottleneck is infrastructure ({detail}). Recommend: scaling / caching / CDN." |
| "Code already uses optimal patterns. Consider infrastructure scaling." |
Exit format: Always provide diagnostic report with performance_map — the profiling data is valuable regardless of verdict.
| 指标 | 诊断消息 |
|---|---|
| "瓶颈为{service}延迟({X}ms)。建议:协商SLA/切换提供商/添加缓存层。" |
| "当前性能({X}ms)处于行业正常范围({Y}ms),无需优化。" |
| "瓶颈为基础设施({detail})。建议:扩容/缓存/CDN。" |
| "代码已使用最优模式,考虑基础设施扩容。" |
输出格式: 无论结论如何,始终提供包含performance_map的诊断报告 —— 性能分析数据具有参考价值。
Phase 4: Research — DELEGATE to ln-812
阶段4:方案调研 —— 委托给ln-812
Do NOT research benchmarks or generate hypotheses yourself. INVOKE the researcher skill.
Invoke:
Skill(skill: "ln-812-optimization-researcher")Context available: performance_map from Phase 2 (in shared conversation).
On cycle 2+: provide in conversation context before invoking: This is natural Skill() conversation, not structural coupling — ln-812 remains standalone-invocable.
"Previously applied hypotheses (exclude from research): {list with descriptions}. Research NEW bottlenecks only."ln-812 will: competitive analysis → target metrics → bottleneck-specific research → local codebase check → generate hypotheses H1..H7.
Receive: industry_benchmark, target_metrics, hypotheses (H1..H7 with conflicts_with), local_codebase_findings, research_sources.
If ln-812 returns 0 hypotheses → STOP: no further optimization found. Proceed to Phase 9.
请勿自行调研基准或生成假设,请调用调研器技能。
调用方式:
Skill(skill: "ln-812-optimization-researcher")可用上下文: 阶段2生成的performance_map(在共享对话中)。
第2轮及以后:调用前在对话上下文中提供:"已应用的假设(调研时排除):{带描述的列表}。仅调研新瓶颈。" 这是Skill()的自然对话,而非结构耦合 —— ln-812仍可独立调用。
ln-812会:竞品分析 → 目标指标 → 瓶颈专项调研 → 本地代码库检查 → 生成假设H1..H7。
返回结果: industry_benchmark、target_metrics、假设(H1..H7及conflicts_with)、local_codebase_findings、research_sources。
若ln-812返回0个假设 → 停止:未发现进一步优化空间,进入阶段9。
Phase 5: Set Target Metric
阶段5:设定目标指标
Cycle 1 only. Target is set once and persists across all cycles. What changes between cycles is the baseline (each cycle's final becomes next cycle's baseline).
仅第1轮执行。目标设定一次后跨循环保留。循环间变化的是基准值(每轮循环的最终值成为下一轮的基准值)。
Multi-Metric Target Resolution
多指标目标确定
FOR each metric in target_metrics from ln-812:
IF user provided target for this metric → use
ELIF ln-812 target_metrics[metric].confidence in [HIGH, MEDIUM] → use
ELSE → baseline × 0.5 (50% default)Primary metric (for stop condition) = metric type from (what user complained about).
observed_metricFOR ln-812返回的target_metrics中的每个指标:
IF 用户提供了该指标的目标 → 使用用户提供的目标
ELIF ln-812 target_metrics[metric].confidence为[HIGH, MEDIUM] → 使用该目标
ELSE → 基准值 × 0.5(默认提升50%)主指标(用于停止条件)= 中的指标类型(用户抱怨的性能问题类型)。
observed_metricBackwards-Compatible Single Target
兼容单目标的回退方案
| Situation | Action |
|---|---|
User provided | Use as primary target |
| User did not provide; ln-812 found target_metrics | Use |
| Neither available | Set to 50% improvement as default target |
| 场景 | 操作 |
|---|---|
用户提供了 | 作为主目标 |
| 用户未提供,但ln-812找到了target_metrics | 使用 |
| 两者都未提供 | 默认设为性能提升50% |
Phase 6: Write Optimization Context
阶段6:编写优化上下文
Serialize diagnostic results from Phases 2-5 into structured context.
- Normal mode: write in project root — input for ln-813/ln-814
.optimization/{slug}/context.md - Plan mode: write same structure to plan file (file writes restricted) → call ExitPlanMode
Context file is overwritten each cycle — it is a transient handoff to workers. Cycle history lives in and experiment log ().
state.jsonln-814-log.tsvContext file structure:
| Section | Source | Content |
|---|---|---|
| Problem Statement | Phase 1 | target, observed_metric, target_metric |
| Performance Map | ln-811 | Full performance_map (real measurements: baseline, per-step metrics, bottleneck classification) |
| Suspicion Stack | ln-811 | Confirmed + dismissed suspicions with evidence |
| Industry Benchmark | ln-812 | expected_range, source, recommended_target |
| Target Metrics | ln-812 | Structured per-metric targets with confidence |
| Hypotheses | ln-812 | Table: ID, description, bottleneck_addressed, expected_impact, complexity, risk, files_to_modify, conflicts_with |
| Dependencies/Conflicts | ln-812 | H2 requires H1; H3 conflicts with H1 (used by ln-814 for contested vs uncontested triage) |
| Local Codebase Findings | ln-812 | Batch APIs, cache infra, connection pools found in code |
| Test Command | ln-811 | Command used for profiling (reused for post-optimization measurement) |
| E2E Test | ln-811 | E2E safety test command + source (functional gate for executor) |
| Instrumented Files | ln-811 | List of files with active instrumentation (ln-814 cleans up after strike) |
| Previous Cycles | state.json | Per-cycle summary: cycle number, bottleneck, improvement %, hypotheses applied |
将阶段2-5的诊断结果序列化为结构化上下文。
- 常规模式: 在项目根目录写入—— 作为ln-813/ln-814的输入
.optimization/{slug}/context.md - 计划模式: 将相同结构写入计划文件(文件写入受限)→ 调用ExitPlanMode
上下文文件每轮循环覆盖一次 —— 是传递给协作组件的临时文件。循环历史存储在和实验日志()中。
state.jsonln-814-log.tsv上下文文件结构:
| 章节 | 来源 | 内容 |
|---|---|---|
| 问题描述 | 阶段1 | target、observed_metric、target_metric |
| 性能映射 | ln-811 | 完整的performance_map(真实测量值:基准、分步指标、瓶颈分类) |
| 疑点栈 | ln-811 | 已确认/排除的疑点及证据 |
| 行业基准 | ln-812 | expected_range、来源、recommended_target |
| 目标指标 | ln-812 | 结构化的多指标目标及置信度 |
| 优化假设 | ln-812 | 表格:ID、描述、解决的瓶颈、预期影响、复杂度、风险、需修改文件、冲突项 |
| 依赖/冲突 | ln-812 | H2依赖H1;H3与H1冲突(ln-814用于区分有争议/无争议假设) |
| 本地代码库发现 | ln-812 | 代码中发现的批量API、缓存基础设施、连接池 |
| 测试命令 | ln-811 | 性能分析使用的命令(优化后测量复用) |
| E2E测试 | ln-811 | E2E安全测试命令 + 源码(执行器的功能门限) |
| 插桩文件 | ln-811 | 已插桩的文件列表(ln-814执行后会清理) |
| 前序循环 | state.json | 每轮循环摘要:循环次数、瓶颈、性能提升百分比、已应用假设 |
Worker Delegation Strategy
协作组件委托策略
| Worker | Tool | Rationale |
|---|---|---|
| ln-811 | Skill() | Needs problem_statement from conversation. First heavy worker — context clean |
| ln-812 | Skill() | Needs performance_map from ln-811 conversation output. Context still manageable (~11K) |
| ln-813 | Agent() | Reads ALL input from context.md on disk. Zero conversation dependency. Isolated context prevents degradation |
| ln-814 | Agent() | Reads ALL input from context.md on disk. Zero conversation dependency. Heaviest worker benefits most from fresh context |
Phase 6 (Write Context) is the natural handoff boundary: shared context → isolated context.
| 组件 | 工具 | 理由 |
|---|---|---|
| ln-811 | Skill() | 需要对话中的problem_statement,作为第一个重量级组件,上下文干净 |
| ln-812 | Skill() | 需要ln-811对话输出中的performance_map,上下文仍可控(~11K) |
| ln-813 | Agent() | 从磁盘读取context.md的所有输入,无对话依赖,隔离上下文避免性能下降 |
| ln-814 | Agent() | 从磁盘读取context.md的所有输入,无对话依赖,最重量级组件从新鲜上下文获益最多 |
阶段6(编写上下文)是自然的交接边界:共享上下文 → 隔离上下文。
Phase 7: Validate Plan — DELEGATE to ln-813 (Isolated Context)
阶段7:验证方案 —— 委托给ln-813(隔离上下文)
Do NOT validate the plan yourself. INVOKE the plan validator via Agent for context isolation.
Invoke:
Agent(description: "Validate optimization plan",
prompt: "Execute worker.
Step 1: Invoke worker:
Skill(skill: \"ln-813-optimization-plan-validator\")
CONTEXT:
{\"slug\": \"{slug}\", \"context_file\": \".optimization/{slug}/context.md\"}",
subagent_type: "general-purpose")Update : set phase status to before launch.
state.json7_validaterunningln-813 will: agent review (Codex + Gemini) + own feasibility check → GO/GO_WITH_CONCERNS/NO_GO.
Receive (from Agent return): verdict (GO/GO_WITH_CONCERNS/NO_GO), corrections_applied count, hypotheses_removed list, concerns.
After Agent returns — re-read for applied corrections. Update : set phase to or .
.optimization/{slug}/context.mdstate.json7_validatedonefailed| Verdict | Action |
|---|---|
| GO | Proceed to Phase 8 |
| GO_WITH_CONCERNS | Proceed with warnings logged |
| NO_GO | Present issues to user. Ask: proceed (WAIVE) or stop |
请勿自行验证方案,请通过Agent调用方案验证器以实现上下文隔离。
调用方式:
Agent(description: "Validate optimization plan",
prompt: "Execute worker.
Step 1: Invoke worker:
Skill(skill: \"ln-813-optimization-plan-validator\")
CONTEXT:
{\"slug\": \"{slug}\", \"context_file\": \".optimization/{slug}/context.md\"}",
subagent_type: "general-purpose")更新:启动前将阶段状态设为。
state.json7_validaterunningln-813会:Agent审核(Codex + Gemini)+ 可行性检查 → GO/GO_WITH_CONCERNS/NO_GO。
返回结果(来自Agent): verdict(GO/GO_WITH_CONCERNS/NO_GO)、corrections_applied数量、hypotheses_removed列表、concerns。
Agent返回后 —— 重新读取以查看已应用的修正。更新:将阶段设为或。
.optimization/{slug}/context.mdstate.json7_validatedonefailed| 结论 | 操作 |
|---|---|
| GO | 进入阶段8 |
| GO_WITH_CONCERNS | 继续执行,但记录警告 |
| NO_GO | 向用户展示问题,询问:是否继续(豁免)或停止 |
Phase 8: Execute — DELEGATE to ln-814 (Isolated Context)
阶段8:执行优化 —— 委托给ln-814(隔离上下文)
In Plan Mode: SKIP this phase. Context file from Phase 6 IS the plan. Call ExitPlanMode.
Do NOT implement optimizations yourself. INVOKE the executor via Agent for context isolation.
Invoke:
Agent(description: "Execute optimization strike",
prompt: "Execute worker.
Step 1: Invoke worker:
Skill(skill: \"ln-814-optimization-executor\")
CONTEXT:
{\"slug\": \"{slug}\", \"context_file\": \".optimization/{slug}/context.md\"}",
subagent_type: "general-purpose")Update : set phase status to before launch.
state.json8_executerunningln-814 will: read context → create worktree → strike-first (apply all) → test → measure → bisect if needed → report.
Receive (from Agent return): branch, baseline, final, total_improvement_pct, target_met, strike_result, hypotheses_applied, hypotheses_removed, files_modified.
After Agent returns — read for experiment details. Update : set phase to or .
.optimization/{slug}/ln-814-log.tsvstate.json8_executedonefailed计划模式下: 跳过此阶段。阶段6的上下文文件即为计划,调用ExitPlanMode。
请勿自行实现优化,请通过Agent调用执行器以实现上下文隔离。
调用方式:
Agent(description: "Execute optimization strike",
prompt: "Execute worker.
Step 1: Invoke worker:
Skill(skill: \"ln-814-optimization-executor\")
CONTEXT:
{\"slug\": \"{slug}\", \"context_file\": \".optimization/{slug}/context.md\"}",
subagent_type: "general-purpose")更新:启动前将阶段状态设为。
state.json8_executerunningln-814会:读取上下文 → 创建工作树 → 批量应用优化 → 测试 → 测量 → 必要时二分排查 → 报告。
返回结果(来自Agent): branch、baseline、final、total_improvement_pct、target_met、strike_result、hypotheses_applied、hypotheses_removed、files_modified。
Agent返回后 —— 读取获取实验详情。更新:将阶段设为或。
.optimization/{slug}/ln-814-log.tsvstate.json8_executedonefailedCycle Boundary (after Phase 8)
循环边界(阶段8后)
Step 1: Collect Cycle Results
步骤1:收集循环结果
Verify Agent workers completed successfully:
| Worker | Check | On failure |
|---|---|---|
| ln-813 | Agent returned text containing verdict keyword (GO/NO_GO/GO_WITH_CONCERNS) | Set phase |
| ln-814 | Agent returned text with baseline + final metrics | Set phase |
Extract from ln-814:
| Field | Description |
|---|---|
| branch | Worktree branch with optimizations |
| baseline | Original measurement |
| final | Measurement after optimizations |
| total_improvement_pct | Overall improvement |
| target_met | Whether target metric was reached |
| strike_result | |
| hypotheses_applied | IDs applied in strike |
| hypotheses_removed | IDs removed during bisect (with reasons) |
| contested_results | Per-group: alternatives tested, winner, measurement |
| files_modified | All changed files |
验证Agent组件是否成功完成:
| 组件 | 检查项 | 失败时操作 |
|---|---|---|
| ln-813 | Agent返回的文本包含verdict关键词(GO/NO_GO/GO_WITH_CONCERNS) | 将阶段 |
| ln-814 | Agent返回的文本包含baseline + final指标 | 将阶段 |
从ln-814提取:
| 字段 | 描述 |
|---|---|
| branch | 包含优化的工作树分支 |
| baseline | 原始测量值 |
| final | 优化后的测量值 |
| total_improvement_pct | 整体性能提升百分比 |
| target_met | 是否达成目标指标 |
| strike_result | |
| hypotheses_applied | 本次执行应用的假设ID |
| hypotheses_removed | 二分排查中移除的假设ID(及原因) |
| contested_results | 每组:测试的替代方案、最优方案、测量差值 |
| files_modified | 所有修改的文件 |
Step 2: Record Cycle Summary
步骤2:记录循环摘要
Save to :
state.json.cycles[]json
{
"cycle": 1,
"status": "done",
"baseline": { "wall_time_ms": 6300 },
"final": { "wall_time_ms": 3800 },
"improvement_pct": 39.7,
"target_met": false,
"bottleneck": "I/O-Network: 13 sequential HTTP calls",
"hypotheses_applied": ["H1", "H2"],
"branch": "optimize/ln-814-align-endpoint-c1-20260315"
}保存到:
state.json.cycles[]json
{
"cycle": 1,
"status": "done",
"baseline": { "wall_time_ms": 6300 },
"final": { "wall_time_ms": 3800 },
"improvement_pct": 39.7,
"target_met": false,
"bottleneck": "I/O-Network: 13 sequential HTTP calls",
"hypotheses_applied": ["H1", "H2"],
"branch": "optimize/ln-814-align-endpoint-c1-20260315"
}Step 3: Evaluate Stop Conditions
步骤3:评估停止条件
| Check | Result | Action |
|---|---|---|
| SUCCESS | Break → Phase 9 with "TARGET MET on cycle {N}" |
| PLATEAU | Break → Phase 9 with "PLATEAU on cycle {N}: {improvement}% < {threshold}%" |
| BUDGET | Break → Phase 9 with "MAX CYCLES reached ({N}/{max})" |
| None of the above | CONTINUE | Proceed to next cycle (merge → compact → Phases 2-8) |
| 检查项 | 结果 | 操作 |
|---|---|---|
| 成功 | 终止循环 → 进入阶段9,提示"第{N}轮已达成目标" |
| 性能提升 < plateau_threshold | 瓶颈期 | 终止循环 → 进入阶段9,提示"第{N}轮进入性能瓶颈期:{improvement}% < {threshold}%" |
| 用尽次数 | 终止循环 → 进入阶段9,提示"已达到最大循环次数({N}/{max})" |
| 以上都不满足 | 继续 | 进入下一轮循环(合并分支 → 压缩上下文 → 阶段2-8) |
Phase 9: Aggregate Results
阶段9:汇总结果
Collect results across ALL completed cycles from and .
state.json.cycles[]ln-814-log.tsvCompute:
- Total improvement:
(original_baseline - final_of_last_cycle) / original_baseline × 100 - Per-cycle gains: array of improvement percentages
- Cumulative hypotheses applied/removed across all cycles
从和收集所有已完成循环的结果。
state.json.cycles[]ln-814-log.tsv计算:
- 总性能提升:
(original_baseline - final_of_last_cycle) / original_baseline × 100 - 每轮循环的性能提升:性能提升百分比数组
- 所有循环中已应用/移除的假设总数
Phase 10: Final Report
阶段10:最终报告
Cycle Summary Table
循环摘要表
| Cycle | Bottleneck | Baseline | Final | Improvement | Hypotheses | Branch |
|-------|------------|----------|-------|-------------|------------|--------|
| 1 | I/O-Network (13 HTTP) | 6300ms | 3800ms | 39.7% | H1,H2 | opt/...-c1 |
| 2 | CPU (O(n^2) alignment) | 3800ms | 1200ms | 68.4% | H1,H3 | opt/...-c2 |
| 3 | I/O-File (temp files) | 1200ms | 480ms | 60.0% | H1 | opt/...-c3 |
| **Total** | | **6300ms** | **480ms** | **92.4%** | | |
Target: 500ms → Achieved: 480ms ✓ TARGET MET (cycle 3)| 循环轮次 | 瓶颈 | 基准值 | 最终值 | 性能提升 | 应用假设 | 分支 |
|-------|------------|----------|-------|-------------|------------|--------|
| 1 | I/O网络(13次HTTP调用) | 6300ms | 3800ms | 39.7% | H1,H2 | opt/...-c1 |
| 2 | CPU(O(n^2)对齐计算) | 3800ms | 1200ms | 68.4% | H1,H3 | opt/...-c2 |
| 3 | I/O文件(临时文件) | 1200ms | 480ms | 60.0% | H1 | opt/...-c3 |
| **总计** | | **6300ms** | **480ms** | **92.4%** | | |
目标:500ms → 实际达成:480ms ✓ 第3轮已达成目标Per-Cycle Detail
每轮循环详情
For each cycle, include:
| Section | Content |
|---|---|
| Problem | Original target + observed metric |
| Diagnosis | Bottleneck type + detail from profiler |
| Target | User-provided or research-derived (same across cycles) |
| Result | Final metric + improvement % + strike result |
| Optimizations Applied | Hypotheses applied: id, description |
| Optimizations Removed | Hypotheses removed during bisect: id, reason |
| Contested Alternatives | Per-group: alternatives tested, winner, measurement delta |
每轮循环包含:
| 章节 | 内容 |
|---|---|
| 问题 | 原始目标 + 观测指标 |
| 诊断 | 性能分析器给出的瓶颈类型 + 详情 |
| 目标 | 用户提供或调研得出的目标(跨循环一致) |
| 结果 | 最终指标 + 性能提升百分比 + 执行结果 |
| 已应用优化 | 已应用的假设:ID、描述 |
| 已移除优化 | 二分排查中移除的假设:ID、原因 |
| 备选方案对比 | 每组:测试的替代方案、最优方案、测量差值 |
If Target Not Met
未达成目标时
Include gap analysis from last cycle's ln-814:
- What was achieved (cumulative improvement %)
- Remaining bottlenecks from latest time map
- Infrastructure/architecture recommendations beyond code changes
- Stop reason: plateau / max_cycles / no hypotheses
包含最后一轮ln-814的差距分析:
- 已达成的成果(累计性能提升百分比)
- 最新时间映射中的剩余瓶颈
- 代码变更之外的基础设施/架构建议
- 停止原因:瓶颈期 / 最大循环次数 / 无优化假设
Branches
分支列表
List all cycle branches for user review. Final branch contains all optimizations.
列出所有循环分支供用户查看,最终分支包含所有优化。
Phase 11: Meta-Analysis
阶段11:元分析
MANDATORY READ: Load
shared/references/meta_analysis_protocol.mdSkill type: .
optimization-coordinator必读要求: 加载
shared/references/meta_analysis_protocol.md技能类型:。
optimization-coordinatorError Handling
错误处理
Per-Phase Errors
分阶段错误
| Phase | Error | Recovery |
|---|---|---|
| 2 (Profile) | Cannot trace target | Report "cannot identify code path for {target}" |
| 3 (Gate) | Wrong tool exit (cycle 1) | Report diagnosis + recommendations, do NOT proceed |
| 3 (Gate) | Wrong tool exit (cycle 2+, ALREADY_OPTIMIZED) | SUCCESS — break to Phase 9 |
| 4 (Research) | No solutions found | Report bottleneck but "no known optimization pattern for {type}" |
| 4 (Research) | 0 hypotheses (cycle 2+) | STOP — no further optimization. Proceed to Phase 9 |
| 7 (Validate) | NO_GO verdict | Present issues to user, offer WAIVE or stop |
| 8 (Execute) | All hypotheses fail | Report profiling + research as diagnostic value |
| 8 (Execute) | Worker timeout | Report partial results |
| Cycle boundary | Merge conflict | BLOCK: report partial results, list completed cycles |
| 阶段 | 错误 | 恢复方式 |
|---|---|---|
| 2(性能分析) | 无法追踪目标 | 报告"无法识别{target}的代码路径" |
| 3(校验) | 工具适配不通过(第1轮) | 报告诊断结果 + 建议,不继续执行 |
| 3(校验) | 工具适配不通过(第2轮及以后,ALREADY_OPTIMIZED) | 成功 —— 终止循环进入阶段9 |
| 4(调研) | 未找到解决方案 | 报告瓶颈,但"未找到针对{type}的已知优化模式" |
| 4(调研) | 0个假设(第2轮及以后) | 停止 —— 无进一步优化空间,进入阶段9 |
| 7(验证) | NO_GO结论 | 向用户展示问题,提供豁免或停止选项 |
| 8(执行) | 所有假设失败 | 报告性能分析 + 调研结果作为诊断参考 |
| 8(执行) | 组件超时 | 上报部分结果 |
| 循环边界 | 合并冲突 | 阻断:上报部分结果,列出已完成的循环 |
Fatal Errors
致命错误
| Error | Action |
|---|---|
| Target not resolvable | Block: "cannot find {target} in codebase" |
| No test infrastructure | Block: "tests required for safe optimization" |
| Dirty git state | Block: "commit or stash changes first" |
| 错误 | 操作 |
|---|---|
| 目标无法解析 | 阻断:"在代码库中无法找到{target}" |
| 无测试基础设施 | 阻断:"安全优化需要测试支持" |
| Git工作区未清理 | 阻断:"请先提交或暂存更改" |
Plan Mode Support: Phased Gate Pattern
计划模式支持:分阶段门限模式
Alternates between plan mode (approval gates) and execution.
GATE 1 — Plan profiling (cycle 1 only)
Plan Mode: Phase 0-1 (preflight, parse input)
→ Present: what will be profiled, which test, which metrics, max_cycles
→ ExitPlanMode (user approves profiling)
EXECUTE 1 — Run profiling (cycle 1)
Phase 2: Skill("ln-811") — runtime profiling (needs Bash)
Phase 3: Wrong Tool Gate (evaluate real measurements)
→ If wrong tool → EXIT with diagnostic
GATE 2 — Plan research & execution (cycle 1 only)
EnterPlanMode: present performance_map to user
Phase 4: Skill("ln-812") — research (read-only, runs in plan mode)
Phase 5: Set target metric (multi-metric)
Phase 6: Write context file
→ Present: hypotheses, target metrics, execution plan, max_cycles
→ ExitPlanMode (user approves strike + cycle loop)
EXECUTE 2+ — Validate + Execute + Loop
Phase 7: Agent("ln-813") — plan review in ISOLATED context (GO/NO_GO)
Phase 8: Agent("ln-814") — strike execution in ISOLATED context
[Cycle boundary → merge → /compact]
Phase 2-8 (cycle 2, auto-continue)
[Cycle boundary → merge → /compact]
Phase 2-8 (cycle 3, auto-continue)
Phase 9-11: Aggregate, report, meta-analysisCycles 2+ auto-continue — user already approved optimization goal. Stop conditions protect against waste.
在计划模式(审批门限)和执行模式间切换。
门限1 —— 计划性能分析(仅第1轮)
计划模式:阶段0-1(预检查、解析输入)
→ 展示:将分析的内容、测试用例、指标、最大循环次数
→ ExitPlanMode(用户批准性能分析)
执行1 —— 运行性能分析(第1轮)
阶段2:Skill("ln-811") —— 运行时性能分析(需要Bash)
阶段3:工具适配校验(评估真实测量结果)
→ 若工具适配不通过 → 退出并返回诊断结果
门限2 —— 计划调研与执行(仅第1轮)
进入计划模式:向用户展示performance_map
阶段4:Skill("ln-812") —— 调研(只读,在计划模式下运行)
阶段5:设定目标指标(多指标)
阶段6:编写上下文文件
→ 展示:假设、目标指标、执行计划、最大循环次数
→ ExitPlanMode(用户批准执行优化 + 循环)
执行2+ —— 验证 + 执行 + 循环
阶段7:Agent("ln-813") —— 隔离上下文审核方案(GO/NO_GO)
阶段8:Agent("ln-814") —— 隔离上下文执行优化
[循环边界 → 合并分支 → /compact]
阶段2-8(第2轮,自动继续)
[循环边界 → 合并分支 → /compact]
阶段2-8(第3轮,自动继续)
阶段9-11:汇总、报告、元分析第2轮及以后自动继续 —— 用户已批准优化目标。停止条件可避免无效操作。
References
参考资料
- (profiler worker)
../ln-811-performance-profiler/SKILL.md - (researcher worker)
../ln-812-optimization-researcher/SKILL.md - (plan validator worker)
../ln-813-optimization-plan-validator/SKILL.md - (executor worker)
../ln-814-optimization-executor/SKILL.md - (tool detection)
shared/references/ci_tool_detection.md - (meta-analysis)
shared/references/meta_analysis_protocol.md
- (性能分析器组件)
../ln-811-performance-profiler/SKILL.md - (调研器组件)
../ln-812-optimization-researcher/SKILL.md - (方案验证器组件)
../ln-813-optimization-plan-validator/SKILL.md - (执行器组件)
../ln-814-optimization-executor/SKILL.md - (工具检测)
shared/references/ci_tool_detection.md - (元分析)
shared/references/meta_analysis_protocol.md
Definition of Done
完成标准
- Input parsed into structured problem statement (target, metric, max_cycles)
- Multi-cycle loop executed (up to max_cycles or until stop condition)
- Each cycle: profiled → gated → researched → validated → executed
- Target metrics established from ln-812 research (multi-metric)
- Context compacted between cycles ()
/compact - Previous cycle branches merged before re-profiling
- Cycle summary table in final report (per-cycle + cumulative)
- All cycle branches listed for user review
- Stop condition documented (target_met / plateau / max_cycles / no hypotheses)
- Meta-analysis completed with cycle metrics
Version: 3.0.0
Last Updated: 2026-03-15
- 输入已解析为结构化问题描述(target、metric、max_cycles)
- 已执行多轮循环(最多max_cycles次,或触发停止条件)
- 每轮循环:已完成性能分析 → 校验 → 调研 → 验证 → 执行
- 已基于ln-812的调研结果设定目标指标(多指标)
- 循环间已压缩上下文()
/compact - 重新性能分析前已合并前序循环分支
- 最终报告包含循环摘要表(每轮 + 总计)
- 已列出所有循环分支供用户查看
- 已记录停止条件(target_met / 瓶颈期 / 最大循环次数 / 无假设)
- 已基于循环指标完成元分析
版本: 3.0.0
最后更新: 2026-03-15