ln-810-performance-optimizer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
Paths: File paths (
shared/
,
references/
,
../ln-*
) 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
shared/
is missing, fetch files via WebFetch from
https://raw.githubusercontent.com/levnikolaevich/claude-code-skills/master/{path}
.
路径说明: 文件路径(
shared/
references/
../ln-*
)均相对于技能仓库根目录。如果在当前工作目录(CWD)中未找到,请定位到本SKILL.md所在目录,再向上一级即为仓库根目录。若
shared/
目录缺失,可通过WebFetch从
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

概述

AspectDetails
Input
target
(endpoint/function/pipeline) +
observed_metric
(e.g., "6300ms response time") + optional
target_metric
+ optional
max_cycles
(default 3)
OutputOptimized code with verification proof, or diagnostic report with recommendations
Workersln-811 (profiler) → ln-812 (researcher) → ln-813 (plan validator) → ln-814 (executor)
FlowPhases 0-1 once, then Phases 2-8 loop up to
max_cycles
times, Phases 9-11 once

维度详情
输入
target
(端点/函数/流水线) +
observed_metric
(例如:"6300ms响应时间") + 可选
target_metric
+ 可选
max_cycles
(默认值3)
输出附带验证依据的优化后代码,或包含建议的诊断报告
协作组件ln-811(性能分析器)→ ln-812(调研器)→ ln-813(方案验证器)→ ln-814(执行器)
流程阶段0-1仅执行一次,随后阶段2-8循环执行最多
max_cycles
次,阶段9-11仅执行一次

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:预检查

CheckRequiredAction if Missing
Target identifiableYesBlock: "specify file, endpoint, or pipeline to optimize"
Observed metric providedYesBlock: "specify what metric is slow (e.g., response time, throughput)"
Git clean stateYesBlock: "commit or stash changes first"
Test infrastructureYesBlock: "tests required for safe optimization"
Stack detectionYesDetect via ci_tool_detection.md
Service topologyNoDetect multi-service architecture (see below)
State fileNoIf
.optimization/{slug}/state.json
exists → resume from last completed gate
MANDATORY READ: Load
shared/references/ci_tool_detection.md
for test/build detection.
检查项是否必填缺失时操作
目标可识别阻断:"请指定要优化的文件、端点或流水线"
提供观测指标阻断:"请指定性能缓慢的指标(例如:响应时间、吞吐量)"
Git工作区干净阻断:"请先提交或暂存更改"
测试基础设施存在阻断:"安全优化需要测试支持"
技术栈检测通过ci_tool_detection.md进行检测
服务拓扑检测多服务架构(见下文)
状态文件
.optimization/{slug}/state.json
存在 → 从最后完成的阶段恢复
必读要求: 加载
shared/references/ci_tool_detection.md
以检测测试/构建工具。

Service Topology Detection

服务拓扑检测

Detect if optimization target spans multiple services with accessible code:
SignalHow to DetectResult
Git submodules
git submodule status
— non-empty output
List of service paths
Monorepo
ls
for
services/
,
packages/
,
apps/
directories with independent package files
List of service paths
Docker Compose
docker-compose.yml
/
compose.yml
— map service names to build contexts
List of service paths + ports
Workspace config
pnpm-workspace.yaml
, Cargo workspace, Go workspace
List of module paths
Output:
service_topology
— map of service names to code paths. Pass to ln-811 for cross-service tracing.
If single-service (no signals):
service_topology = null
— standard single-codebase profiling.
检测优化目标是否跨多个可访问代码的服务:
信号检测方式结果
Git子模块
git submodule status
— 输出非空
服务路径列表
单体仓库查看是否存在
services/
packages/
apps/
目录及独立包文件
服务路径列表
Docker Compose
docker-compose.yml
/
compose.yml
— 映射服务名称到构建上下文
服务路径列表+端口
工作区配置
pnpm-workspace.yaml
、Cargo工作区、Go工作区
模块路径列表
输出:
service_topology
— 服务名称到代码路径的映射,传递给ln-811用于跨服务追踪。
若为单服务(无上述信号):
service_topology = null
— 采用标准单代码库性能分析。

State Persistence

状态持久化

Save
.optimization/{slug}/state.json
after each phase completion. Enables resume on interruption.
json
{
  "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:
pending
running
done
|
failed
Update state BEFORE and AFTER each phase. For Agent-delegated phases (7, 8): set
running
before launch,
done
/
failed
after Agent returns.
On startup: if
.optimization/{slug}/state.json
exists, ask user: "Resume from cycle {current_cycle}, phase {last incomplete}?" or "Start fresh?"
Phases are per-cycle — reset at each cycle boundary.
current_cycle
+ phases tells the exact resumption point.

每个阶段完成后保存
.optimization/{slug}/state.json
,支持中断后恢复。
json
{
  "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" }
  }
}
阶段状态值:
pending
running
done
|
failed
每个阶段执行前后都要更新状态。对于Agent委托的阶段(7、8):启动前设为
running
,Agent返回后设为
done
/
failed
启动时:若
.optimization/{slug}/state.json
存在,询问用户:"是否从第{current_cycle}轮、未完成的{last incomplete}阶段恢复?" 或 "是否重新开始?"
阶段为每轮循环专属 —— 循环边界时重置阶段状态。
current_cycle
+ 阶段信息可确定准确的恢复点。

Cycle Management

循环管理

ParameterDefaultDescription
max_cycles3Maximum optimization cycles
plateau_threshold5Minimum 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_cycles3最大优化循环次数
plateau_threshold5进入下一轮循环所需的最小性能提升百分比
每轮循环:性能分析 → 校验 → 调研 → 设定目标 → 编写上下文 → 验证方案 → 执行优化。 遵循Amdahl's law,每轮循环会自然发现不同的瓶颈(解决主要瓶颈后,下一个瓶颈会显现)。

Stop Conditions (evaluated after each cycle)

停止条件(每轮循环后评估)

ConditionAction
target_met
STOP — target reached
improvement <
plateau_threshold
%
STOP — plateau detected
cycle == max_cycles
STOP — budget exhausted
ln-812 returns 0 hypothesesSTOP — no further optimization found
条件操作
target_met
停止 — 已达成目标
性能提升 <
plateau_threshold
%
停止 — 已进入性能瓶颈期
cycle == max_cycles
停止 — 已用尽循环次数
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 cycle
If 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:
FieldSourceExample
targetUser-specified
src/api/alignment.py::align_endpoint
,
/api/v1/align
,
alignment pipeline
observed_metricUser-specified
{ value: 6300, unit: "ms", type: "response_time" }
target_metricUser-specified OR Phase 5
{ value: 500, unit: "ms" }
or null
max_cyclesUser-specified OR default3
audit_reportOptionalPath to ln-650 output (additional hints for profiler)
If
target_metric
not provided by user, defer to Phase 5 (after research establishes industry benchmark).
将用户输入解析为结构化问题描述:
字段来源示例
target用户指定
src/api/alignment.py::align_endpoint
,
/api/v1/align
,
alignment pipeline
observed_metric用户指定
{ value: 6300, unit: "ms", type: "response_time" }
target_metric用户指定 或 阶段5生成
{ value: 500, unit: "ms" }
或 null
max_cycles用户指定 或 默认值3
audit_report可选ln-650输出路径(为性能分析器提供额外提示)
若用户未提供
target_metric
,则推迟到阶段5(调研确定行业基准后)处理。

Generate slug

生成slug

Derive
{slug}
from target for per-task isolation: sanitize to
[a-z0-9_-]
, max 50 chars.
TargetSlug
src/api/alignment.py::align_endpoint
align-endpoint
test_idml_structure_preserved
test-idml-structure-preserved
/api/v1/translate
api-v1-translate
All artifacts go to
.optimization/{slug}/
:
context.md
,
state.json
,
ln-814-log.tsv
,
profile_test.sh
.

从target生成
{slug}
以实现任务隔离:清理为
[a-z0-9_-]
格式,最长50字符。
TargetSlug
src/api/alignment.py::align_endpoint
align-endpoint
test_idml_structure_preserved
test-idml-structure-preserved
/api/v1/translate
api-v1-translate
所有产物存储到
.optimization/{slug}/
context.md
state.json
ln-814-log.tsv
profile_test.sh

CYCLE 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).
VerdictConditionAction
PROCEED
wrong_tool_indicators
empty, measurements stable
Continue to Phase 4 (research)
CONCERNSMeasurement variance > 20% OR baseline unstable OR partial metrics onlyContinue with warning — note uncertainty in context file
BLOCK
external_service_no_alternative
OR
infrastructure_bound
OR
already_optimized
OR
within_industry_norm
See below
WAIVEDUser explicitly overrides BLOCK ("try anyway")Continue despite indicators — log user override
使用结构化结论评估性能分析器结果(改编自ln-500质量门模型)。
结论条件操作
继续
wrong_tool_indicators
为空,测量结果稳定
进入阶段4(调研)
需注意测量方差>20% 或 基准不稳定 或 仅获取部分指标继续执行,但在上下文文件中记录不确定性
阻断
external_service_no_alternative
infrastructure_bound
already_optimized
within_industry_norm
见下文
豁免用户明确覆盖阻断("无论如何尝试")忽略指标继续执行 —— 记录用户覆盖操作

BLOCK on Cycle 2+

第2轮及以后的阻断

On cycle 2+,
already_optimized
or
within_industry_norm
is a SUCCESS signal — previous cycles brought performance to acceptable level. Break the cycle loop and proceed to Phase 9 (Final Report).
第2轮及以后,
already_optimized
within_industry_norm
成功信号 —— 前几轮循环已将性能提升到可接受水平。终止循环,进入阶段9(最终报告)。

BLOCK Diagnostics

阻断诊断信息

IndicatorDiagnostic Message
external_service_no_alternative
"Bottleneck is {service} latency ({X}ms). Recommend: negotiate SLA / switch provider / add cache layer."
within_industry_norm
"Current performance ({X}ms) is within industry norm ({Y}ms). No optimization needed."
infrastructure_bound
"Bottleneck is infrastructure ({detail}). Recommend: scaling / caching / CDN."
already_optimized
"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.

指标诊断消息
external_service_no_alternative
"瓶颈为{service}延迟({X}ms)。建议:协商SLA/切换提供商/添加缓存层。"
within_industry_norm
"当前性能({X}ms)处于行业正常范围({Y}ms),无需优化。"
infrastructure_bound
"瓶颈为基础设施({detail})。建议:扩容/缓存/CDN。"
already_optimized
"代码已使用最优模式,考虑基础设施扩容。"
输出格式: 无论结论如何,始终提供包含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:
"Previously applied hypotheses (exclude from research): {list with descriptions}. Research NEW bottlenecks only."
This is natural Skill() conversation, not structural coupling — ln-812 remains standalone-invocable.
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
observed_metric
(what user complained about).
FOR ln-812返回的target_metrics中的每个指标:
  IF 用户提供了该指标的目标 → 使用用户提供的目标
  ELIF ln-812 target_metrics[metric].confidence为[HIGH, MEDIUM] → 使用该目标
  ELSE → 基准值 × 0.5(默认提升50%)
主指标(用于停止条件)=
observed_metric
中的指标类型(用户抱怨的性能问题类型)。

Backwards-Compatible Single Target

兼容单目标的回退方案

SituationAction
User provided
target_metric
Use as primary target
User did not provide; ln-812 found target_metricsUse
target_metrics.{primary_metric_type}
Neither availableSet to 50% improvement as default target

场景操作
用户提供了
target_metric
作为主目标
用户未提供,但ln-812找到了target_metrics使用
target_metrics.{primary_metric_type}
两者都未提供默认设为性能提升50%

Phase 6: Write Optimization Context

阶段6:编写优化上下文

Serialize diagnostic results from Phases 2-5 into structured context.
  • Normal mode: write
    .optimization/{slug}/context.md
    in project root — input for ln-813/ln-814
  • 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
state.json
and experiment log (
ln-814-log.tsv
).
Context file structure:
SectionSourceContent
Problem StatementPhase 1target, observed_metric, target_metric
Performance Mapln-811Full performance_map (real measurements: baseline, per-step metrics, bottleneck classification)
Suspicion Stackln-811Confirmed + dismissed suspicions with evidence
Industry Benchmarkln-812expected_range, source, recommended_target
Target Metricsln-812Structured per-metric targets with confidence
Hypothesesln-812Table: ID, description, bottleneck_addressed, expected_impact, complexity, risk, files_to_modify, conflicts_with
Dependencies/Conflictsln-812H2 requires H1; H3 conflicts with H1 (used by ln-814 for contested vs uncontested triage)
Local Codebase Findingsln-812Batch APIs, cache infra, connection pools found in code
Test Commandln-811Command used for profiling (reused for post-optimization measurement)
E2E Testln-811E2E safety test command + source (functional gate for executor)
Instrumented Filesln-811List of files with active instrumentation (ln-814 cleans up after strike)
Previous Cyclesstate.jsonPer-cycle summary: cycle number, bottleneck, improvement %, hypotheses applied
将阶段2-5的诊断结果序列化为结构化上下文。
  • 常规模式: 在项目根目录写入
    .optimization/{slug}/context.md
    —— 作为ln-813/ln-814的输入
  • 计划模式: 将相同结构写入计划文件(文件写入受限)→ 调用ExitPlanMode
上下文文件每轮循环覆盖一次 —— 是传递给协作组件的临时文件。循环历史存储在
state.json
和实验日志(
ln-814-log.tsv
)中。
上下文文件结构:
章节来源内容
问题描述阶段1target、observed_metric、target_metric
性能映射ln-811完整的performance_map(真实测量值:基准、分步指标、瓶颈分类)
疑点栈ln-811已确认/排除的疑点及证据
行业基准ln-812expected_range、来源、recommended_target
目标指标ln-812结构化的多指标目标及置信度
优化假设ln-812表格:ID、描述、解决的瓶颈、预期影响、复杂度、风险、需修改文件、冲突项
依赖/冲突ln-812H2依赖H1;H3与H1冲突(ln-814用于区分有争议/无争议假设)
本地代码库发现ln-812代码中发现的批量API、缓存基础设施、连接池
测试命令ln-811性能分析使用的命令(优化后测量复用)
E2E测试ln-811E2E安全测试命令 + 源码(执行器的功能门限)
插桩文件ln-811已插桩的文件列表(ln-814执行后会清理)
前序循环state.json每轮循环摘要:循环次数、瓶颈、性能提升百分比、已应用假设

Worker Delegation Strategy

协作组件委托策略

WorkerToolRationale
ln-811Skill()Needs problem_statement from conversation. First heavy worker — context clean
ln-812Skill()Needs performance_map from ln-811 conversation output. Context still manageable (~11K)
ln-813Agent()Reads ALL input from context.md on disk. Zero conversation dependency. Isolated context prevents degradation
ln-814Agent()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-811Skill()需要对话中的problem_statement,作为第一个重量级组件,上下文干净
ln-812Skill()需要ln-811对话输出中的performance_map,上下文仍可控(~11K)
ln-813Agent()从磁盘读取context.md的所有输入,无对话依赖,隔离上下文避免性能下降
ln-814Agent()从磁盘读取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
state.json
: set phase
7_validate
status to
running
before launch.
ln-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
.optimization/{slug}/context.md
for applied corrections. Update
state.json
: set phase
7_validate
to
done
or
failed
.
VerdictAction
GOProceed to Phase 8
GO_WITH_CONCERNSProceed with warnings logged
NO_GOPresent 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.json
:启动前将阶段
7_validate
状态设为
running
ln-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.md
以查看已应用的修正。更新
state.json
:将阶段
7_validate
设为
done
failed
结论操作
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
state.json
: set phase
8_execute
status to
running
before launch.
ln-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
.optimization/{slug}/ln-814-log.tsv
for experiment details. Update
state.json
: set phase
8_execute
to
done
or
failed
.

计划模式下: 跳过此阶段。阶段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.json
:启动前将阶段
8_execute
状态设为
running
ln-814会:读取上下文 → 创建工作树 → 批量应用优化 → 测试 → 测量 → 必要时二分排查 → 报告。
返回结果(来自Agent): branch、baseline、final、total_improvement_pct、target_met、strike_result、hypotheses_applied、hypotheses_removed、files_modified。
Agent返回后 —— 读取
.optimization/{slug}/ln-814-log.tsv
获取实验详情。更新
state.json
:将阶段
8_execute
设为
done
failed

Cycle Boundary (after Phase 8)

循环边界(阶段8后)

Step 1: Collect Cycle Results

步骤1:收集循环结果

Verify Agent workers completed successfully:
WorkerCheckOn failure
ln-813Agent returned text containing verdict keyword (GO/NO_GO/GO_WITH_CONCERNS)Set phase
7_validate
to
failed
, report to user
ln-814Agent returned text with baseline + final metricsSet phase
8_execute
to
failed
, report partial results
Extract from ln-814:
FieldDescription
branchWorktree branch with optimizations
baselineOriginal measurement
finalMeasurement after optimizations
total_improvement_pctOverall improvement
target_metWhether target metric was reached
strike_result
clean
/
bisected
/
failed
hypotheses_appliedIDs applied in strike
hypotheses_removedIDs removed during bisect (with reasons)
contested_resultsPer-group: alternatives tested, winner, measurement
files_modifiedAll changed files
验证Agent组件是否成功完成:
组件检查项失败时操作
ln-813Agent返回的文本包含verdict关键词(GO/NO_GO/GO_WITH_CONCERNS)将阶段
7_validate
设为
failed
,向用户报告
ln-814Agent返回的文本包含baseline + final指标将阶段
8_execute
设为
failed
,上报部分结果
从ln-814提取:
字段描述
branch包含优化的工作树分支
baseline原始测量值
final优化后的测量值
total_improvement_pct整体性能提升百分比
target_met是否达成目标指标
strike_result
clean
/
bisected
/
failed
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:评估停止条件

CheckResultAction
target_met == true
SUCCESSBreak → Phase 9 with "TARGET MET on cycle {N}"
improvement_pct < plateau_threshold
PLATEAUBreak → Phase 9 with "PLATEAU on cycle {N}: {improvement}% < {threshold}%"
cycle == max_cycles
BUDGETBreak → Phase 9 with "MAX CYCLES reached ({N}/{max})"
None of the aboveCONTINUEProceed to next cycle (merge → compact → Phases 2-8)

检查项结果操作
target_met == true
成功终止循环 → 进入阶段9,提示"第{N}轮已达成目标"
性能提升 < plateau_threshold瓶颈期终止循环 → 进入阶段9,提示"第{N}轮进入性能瓶颈期:{improvement}% < {threshold}%"
cycle == max_cycles
用尽次数终止循环 → 进入阶段9,提示"已达到最大循环次数({N}/{max})"
以上都不满足继续进入下一轮循环(合并分支 → 压缩上下文 → 阶段2-8)

Phase 9: Aggregate Results

阶段9:汇总结果

Collect results across ALL completed cycles from
state.json.cycles[]
and
ln-814-log.tsv
.
Compute:
  • 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:
SectionContent
ProblemOriginal target + observed metric
DiagnosisBottleneck type + detail from profiler
TargetUser-provided or research-derived (same across cycles)
ResultFinal metric + improvement % + strike result
Optimizations AppliedHypotheses applied: id, description
Optimizations RemovedHypotheses removed during bisect: id, reason
Contested AlternativesPer-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.md
Skill type:
optimization-coordinator
.

必读要求: 加载
shared/references/meta_analysis_protocol.md
技能类型:
optimization-coordinator

Error Handling

错误处理

Per-Phase Errors

分阶段错误

PhaseErrorRecovery
2 (Profile)Cannot trace targetReport "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 foundReport 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 verdictPresent issues to user, offer WAIVE or stop
8 (Execute)All hypotheses failReport profiling + research as diagnostic value
8 (Execute)Worker timeoutReport partial results
Cycle boundaryMerge conflictBLOCK: 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

致命错误

ErrorAction
Target not resolvableBlock: "cannot find {target} in codebase"
No test infrastructureBlock: "tests required for safe optimization"
Dirty git stateBlock: "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-analysis
Cycles 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

参考资料

  • ../ln-811-performance-profiler/SKILL.md
    (profiler worker)
  • ../ln-812-optimization-researcher/SKILL.md
    (researcher worker)
  • ../ln-813-optimization-plan-validator/SKILL.md
    (plan validator worker)
  • ../ln-814-optimization-executor/SKILL.md
    (executor worker)
  • shared/references/ci_tool_detection.md
    (tool detection)
  • shared/references/meta_analysis_protocol.md
    (meta-analysis)

  • ../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