ln-811-algorithm-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.
路径说明: 文件路径(
shared/
references/
../ln-*
)均相对于技能仓库根目录。如果在当前工作目录(CWD)未找到,请定位到本SKILL.md所在目录,再向上一级即为仓库根目录。

ln-811-algorithm-optimizer

ln-811-algorithm-optimizer

Type: L3 Worker Category: 8XX Optimization Parent: ln-810-performance-optimization-coordinator
Optimizes target function performance via autoresearch loop: establish baseline benchmark, research best practices, generate 3-7 hypotheses, apply each with keep/discard verification.

Type: L3 Worker Category: 8XX Optimization Parent: ln-810-performance-optimization-coordinator
通过自动研究循环优化目标函数性能:建立基准测试基线、研究最佳实践、生成3-7个优化假设、逐一验证并决定保留/丢弃方案。

Overview

概述

AspectDetails
Input
target_file
+
target_function
(or audit findings from ln-650)
OutputOptimized function with benchmark proof, optimization report
PatternAutoresearch: modify → benchmark → keep (≥10%) / discard

维度详情
输入
target_file
+
target_function
(或来自ln-650的审计结果)
输出附带基准测试证明的优化后函数、优化报告
模式自动研究循环:修改→基准测试→保留(提升≥10%)/丢弃

Workflow

工作流

Phases: Pre-flight → Baseline → Research → Hypothesize → Optimize Loop → Report

阶段: 前期检查→基准建立→研究分析→假设生成→优化循环→结果报告

Phase 0: Pre-flight Checks

阶段0:前期检查

CheckRequiredAction if Missing
Target file existsYesBlock optimization
Target function identifiableYesBlock optimization
Test infrastructureYesBlock optimization (see ci_tool_detection.md)
Test coverage for target functionYesBlock — no coverage = no safety net
Git clean stateYesBlock (need clean baseline for revert)
Benchmark infrastructureNoGenerate benchmark (see references)
MANDATORY READ: Load
shared/references/ci_tool_detection.md
— use Benchmarks + Test Frameworks sections.
检查项是否必填缺失时操作
目标文件存在阻止优化
目标函数可识别阻止优化
测试基础设施就绪阻止优化(参见ci_tool_detection.md)
目标函数有测试覆盖率阻止优化——无覆盖率=无安全保障
Git处于干净状态阻止优化(需要干净基线用于回滚)
基准测试基础设施就绪生成基准测试(参见参考文档)
必读内容: 加载
shared/references/ci_tool_detection.md
文档——使用其中的基准测试和测试框架章节内容。

Coverage Verification

测试覆盖率验证

Before starting optimization, verify target function has test coverage:
StepAction
1Grep test files for target function name / imports from target module
2If ≥1 test references target → PROCEED
3If 0 tests reference target → BLOCK with "no test coverage for {function}"
Without test coverage, benchmark improvements are meaningless — the optimized function may produce wrong results faster.
开始优化前,需验证目标函数是否有测试覆盖率:
步骤操作
1在测试文件中搜索目标函数名称/来自目标模块的导入语句
2如果≥1个测试用例引用目标函数→继续执行
3如果0个测试用例引用目标函数→阻止优化,提示“{function}无测试覆盖率”
没有测试覆盖率的话,基准测试的性能提升毫无意义——优化后的函数可能只是更快地输出错误结果。

Worktree & Branch Isolation

工作树与分支隔离

MANDATORY READ: Load
shared/references/git_worktree_fallback.md
— use ln-811 row.
All work (edits, benchmarks, KEEP commits) in worktree. Never modify main worktree.

必读内容: 加载
shared/references/git_worktree_fallback.md
文档——使用其中ln-811对应的行内容。
所有工作(编辑、基准测试、保留操作的提交)都在独立工作树中进行。严禁修改主工作树。

Phase 1: Establish Baseline

阶段1:建立基准基线

Step 1.1: Detect or Generate Benchmark

步骤1.1:检测或生成基准测试

SituationAction
Existing benchmark foundUse as-is
No benchmark existsGenerate minimal benchmark (see benchmark_generation.md)
场景操作
找到现有基准测试直接使用
无现有基准测试生成最小化基准测试(参见benchmark_generation.md

Step 1.2: Run Baseline

步骤1.2:运行基准测试

ParameterValue
Runs5
MetricMedian execution time
Warm-up1 discarded run
Output
baseline_median
,
baseline_p95
Save baseline result — all improvements measured against this.

参数取值
运行次数5
衡量指标执行时间中位数
预热次数丢弃1次预热运行结果
输出结果
baseline_median
,
baseline_p95
保存基准测试结果——所有性能提升都将以此为参照。

Phase 2: Research Best Practices

阶段2:研究最佳实践

MANDATORY READ: Load
shared/references/research_tool_fallback.md
for MCP tool chain.
必读内容: 加载
shared/references/research_tool_fallback.md
文档以获取MCP工具链信息。

Research Strategy

研究策略

PriorityToolQuery Template
1mcp__context7__query-docs
"{language} {algorithm_type} optimization techniques"
2mcp__Ref__ref_search_documentation
"{language} {function_name} performance best practices"
3WebSearch
"{algorithm_type} optimization {language} benchmark {current_year}"
优先级工具查询模板
1mcp__context7__query-docs
"{language} {algorithm_type} optimization techniques"
2mcp__Ref__ref_search_documentation
"{language} {function_name} performance best practices"
3WebSearch
"{algorithm_type} optimization {language} benchmark {current_year}"

Research Output

研究输出

Collect optimization techniques applicable to the target function. For each technique note:
  • Name and description
  • Expected improvement category (algorithmic complexity, memory, cache, parallelism)
  • Applicability conditions (data size, structure, language features)

收集适用于目标函数的优化技术。对于每种技术,需记录:
  • 技术名称与描述
  • 预期提升类别(算法复杂度、内存、缓存、并行化)
  • 适用条件(数据规模、结构、语言特性)

Phase 3: Generate Hypotheses (3-7)

阶段3:生成优化假设(3-7个)

Hypothesis Sources

假设来源

MANDATORY READ: Load optimization_categories.md for category checklist.
SourcePriority
Research findings (Phase 2)1
Optimization categories checklist2
Code analysis (anti-patterns in target)3
必读内容: 加载optimization_categories.md文档获取优化类别清单。
来源优先级
阶段2的研究成果1
优化类别清单2
代码分析(目标函数中的反模式)3

Hypothesis Format

假设格式

FieldDescription
idH1, H2, ... H7
categoryFrom optimization_categories.md
descriptionWhat to change
expected_impactEstimated improvement %
riskLow / Medium / High
dependenciesOther hypotheses this depends on
字段描述
idH1, H2, ... H7
category来自optimization_categories.md
description需修改的内容
expected_impact预估提升百分比
riskLow / Medium / High
dependencies依赖的其他假设

Ordering

排序规则

Sort by:
expected_impact DESC, risk ASC
. Independent hypotheses first (no dependencies).

排序依据:
预期影响降序,风险升序
。优先处理独立假设(无依赖项)。

Phase 4: Optimize Loop (Keep/Discard)

阶段4:优化循环(保留/丢弃)

Per-Hypothesis Cycle

单假设循环流程

FOR each hypothesis (H1..H7):
  1. APPLY: Edit target function (surgical change, function body only)
  2. VERIFY: Run tests
     IF tests FAIL (assertion) → DISCARD (revert) → next hypothesis
     IF tests CRASH (runtime error, OOM, import error):
       IF fixable (typo, missing import) → fix & re-run ONCE
       IF fundamental (design flaw, incompatible API) → DISCARD + log "crash: {reason}"
  3. BENCHMARK: Run 5 times, take median
  4. COMPARE: improvement = (baseline - new) / baseline * 100
     IF improvement >= 10% → KEEP:
       git add {target_file}
       git commit -m "perf(H{N}): {description} (+{improvement}%)"
       new baseline = new median
     IF improvement < 10%  → DISCARD (revert edit)
  5. LOG: Record result to experiment log + report
FOR each hypothesis (H1..H7):
  1. APPLY: Edit target function (surgical change, function body only)
  2. VERIFY: Run tests
     IF tests FAIL (assertion) → DISCARD (revert) → next hypothesis
     IF tests CRASH (runtime error, OOM, import error):
       IF fixable (typo, missing import) → fix & re-run ONCE
       IF fundamental (design flaw, incompatible API) → DISCARD + log "crash: {reason}"
  3. BENCHMARK: Run 5 times, take median
  4. COMPARE: improvement = (baseline - new) / baseline * 100
     IF improvement >= 10% → KEEP:
       git add {target_file}
       git commit -m "perf(H{N}): {description} (+{improvement}%)"
       new baseline = new median
     IF improvement < 10%  → DISCARD (revert edit)
  5. LOG: Record result to experiment log + report

Safety Rules

安全规则

RuleDescription
ScopeOnly target function body; no signature changes
DependenciesNo new package installations
Revert
git checkout -- {target_file}
on discard
Time budget30 minutes total for all hypotheses
CompoundEach KEEP becomes new baseline for next hypothesis
TraceabilityEach KEEP = separate git commit with hypothesis ID in message
IsolationAll work in isolated worktree; never modify main worktree
规则描述
Scope仅修改目标函数体;不修改函数签名
Dependencies禁止安装新依赖包
Revert丢弃时执行
git checkout -- {target_file}
Time budget所有假设的总时间预算为30分钟
Compound每次保留的优化将作为下一个假设的新基准
Traceability每次保留操作对应独立的Git提交,提交信息中包含假设ID
Isolation所有工作在独立工作树中进行;严禁修改主工作树

Keep/Discard Decision

保留/丢弃决策

ConditionDecisionAction
Tests failDISCARDRevert, log reason
Improvement ≥ 10%KEEPUpdate baseline
Improvement 10-20% BUT complexity increaseREVIEWLog as "marginal + complex", prefer DISCARD
Improvement < 10%DISCARDRevert, log as "insufficient gain"
Regression (slower)DISCARDRevert, log regression amount
Simplicity criterion (per autoresearch): If improvement is marginal (10-20%) and change significantly increases code complexity (>50% more lines, deeply nested logic, hard-to-read constructs), prefer DISCARD. Simpler code at near-equal performance wins.

条件决策操作
测试失败DISCARD回滚,记录原因
性能提升≥10%KEEP更新基准基线
性能提升10-20%但代码复杂度增加REVIEW记录为“提升有限+复杂度高”,优先选择丢弃
性能提升<10%DISCARD回滚,记录为“提升幅度不足”
性能退化(运行更慢)DISCARD回滚,记录退化幅度
简洁性准则(自动研究循环要求): 如果性能提升幅度有限(10-20%)且修改导致代码复杂度显著增加(代码行数增加>50%、深层嵌套逻辑、难以阅读的结构),则优先选择丢弃。在性能接近的情况下,更简洁的代码更优。

Phase 5: Report Results

阶段5:报告结果

Report Schema

报告模板

FieldDescription
targetFile path + function name
baselineOriginal median benchmark
finalFinal median after all kept optimizations
total_improvementPercentage improvement
hypotheses_testedTotal count
hypotheses_keptCount of kept optimizations
hypotheses_discardedCount + reasons
optimizations[]Per-kept: id, category, description, improvement%
字段描述
target文件路径+函数名称
baseline原始基准测试中位数
final所有保留优化后的最终中位数
total_improvement总提升百分比
hypotheses_tested测试的假设总数
hypotheses_kept保留的优化假设数量
hypotheses_discarded丢弃的数量+原因
optimizations[]每个保留项的:id、类别、描述、提升百分比

Experiment Log

实验日志

Write to
{project_root}/.optimization/ln-811-log.tsv
:
ColumnDescription
timestampISO 8601
hypothesis_idH1..H7
categoryFrom optimization_categories.md
descriptionWhat changed
baseline_msBaseline median before this hypothesis
result_msNew median after change
improvement_pctPercentage change
statuskeep / discard / crash
commitGit commit hash (if kept)
Append to existing file if present (enables tracking across multiple runs).
写入至
{project_root}/.optimization/ln-811-log.tsv
列名描述
timestampISO 8601格式时间戳
hypothesis_idH1..H7
category来自optimization_categories.md
description修改内容
baseline_ms本次假设前的基准中位数(毫秒)
result_ms修改后的新中位数(毫秒)
improvement_pct提升百分比
statuskeep / discard / crash
commitGit提交哈希(若保留)
如果文件已存在则追加内容(支持跨多次运行的跟踪)。

Cleanup

清理操作

ActionWhen
Remove generated benchmarkIf benchmark was auto-generated AND no kept optimizations
Keep generated benchmarkIf any optimization was kept (proof of improvement)

操作执行时机
删除自动生成的基准测试当基准测试为自动生成且无保留的优化方案时
保留自动生成的基准测试当有任何优化方案被保留时(作为性能提升的证明)

Configuration

配置项

yaml
Options:
  # Target
  target_file: ""
  target_function: ""

  # Benchmark
  benchmark_runs: 5
  improvement_threshold: 10    # percent
  warmup_runs: 1

  # Hypotheses
  max_hypotheses: 7
  min_hypotheses: 3

  # Safety
  time_budget_minutes: 30
  allow_new_deps: false
  scope: "function_body"       # function_body | module

  # Verification
  run_tests: true
  run_lint: false

yaml
Options:
  # Target
  target_file: ""
  target_function: ""

  # Benchmark
  benchmark_runs: 5
  improvement_threshold: 10    # percent
  warmup_runs: 1

  # Hypotheses
  max_hypotheses: 7
  min_hypotheses: 3

  # Safety
  time_budget_minutes: 30
  allow_new_deps: false
  scope: "function_body"       # function_body | module

  # Verification
  run_tests: true
  run_lint: false

Error Handling

错误处理

ErrorCauseSolution
No benchmark frameworkStack not in ci_tool_detection.mdGenerate inline benchmark
All hypotheses discardedNo effective optimization foundReport "no improvements found"
Benchmark noise too highInconsistent timingIncrease runs to 10, use p50
Test flakeNon-deterministic testRe-run once; if flakes again, skip hypothesis

错误类型原因解决方案
无基准测试框架技术栈未在ci_tool_detection.md中列出生成内置基准测试
所有假设均被丢弃未找到有效优化方案报告“未找到可提升的优化点”
基准测试结果波动过大计时结果不一致将运行次数增加至10次,使用p50值
测试用例不稳定测试结果非确定性重新运行一次;若仍不稳定,跳过该假设

References

参考文档

  • benchmark_generation.md
  • optimization_categories.md
  • shared/references/ci_tool_detection.md
    (Benchmarks section)
  • shared/references/research_tool_fallback.md

  • benchmark_generation.md
  • optimization_categories.md
  • shared/references/ci_tool_detection.md
    (基准测试章节)
  • shared/references/research_tool_fallback.md

Definition of Done

完成标准

  • Test coverage for target function verified before optimization
  • Target function identified and baseline benchmark established (5 runs, median)
  • Research completed via MCP tool chain (Context7/Ref/WebSearch)
  • 3-7 hypotheses generated, ordered by expected impact
  • Each hypothesis tested: apply → tests → benchmark → keep/discard
  • Each kept optimization = separate git commit with hypothesis ID
  • Kept optimizations compound (each becomes new baseline)
  • Marginal gains (10-20%) with complexity increase reviewed via simplicity criterion
  • Tests pass after all kept optimizations
  • Experiment log written to
    .optimization/ln-811-log.tsv
  • Report returned with baseline, final, improvement%, per-hypothesis results
  • Generated benchmark cleaned up if no optimizations kept
  • All changes on isolated branch, pushed to remote

Version: 1.0.0 Last Updated: 2026-03-08
  • 优化前已验证目标函数的测试覆盖率
  • 已识别目标函数并建立基准测试基线(5次运行,取中位数)
  • 通过MCP工具链完成研究分析
  • 已生成3-7个优化假设,按预期影响和风险排序
  • 每个假设均已完成测试:修改→测试→基准测试→保留/丢弃
  • 每次保留的优化对应独立的Git提交,提交信息包含假设ID
  • 保留的优化将作为后续假设的新基准
  • 对提升幅度有限(10-20%)且增加代码复杂度的优化已按简洁性准则评估
  • 所有保留优化完成后测试通过
  • 实验日志已写入
    .optimization/ln-811-log.tsv
  • 已返回包含基线、最终结果、总提升、各假设结果的报告
  • 若无优化被保留,已清理自动生成的基准测试
  • 所有修改均在独立分支完成并推送至远程仓库

Version: 1.0.0 Last Updated: 2026-03-08