Skill-as-Pseudocode: Refactoring Skill Libraries to Pseudocode for LLM Agents

agent 2605.27955
skill-librarytyped-contractpseudocode-conversiondeterministic-verificationretrieval-augmented-agent

Skill-as-Pseudocode: Refactoring Skill Libraries to Pseudocode for LLM Agents — L2 #

§1 TL;DR #

SaP 将 prose 格式的 markdown skill library 自动转换为 typed pseudocode(typed contract + concrete action template),经 4-check 确定性验证器把关后,在检索时以 substituted bundle 形式一次性交付给 agent。ALFWorld 134 games × 3 seeds:+74% 相对胜率(82 vs 47 wins,McNemar $p=8.2 \times 10^{-5}$),同时 −23% input tokens — 质量与成本同向改善,根因是打破了 prose 引发的 retrieval-action 反馈循环。


§2 痛点 / 方法 / 结果 #

Q1 痛点:prose 表征本身是瓶颈 #

Markdown skill library 不区分 skill 的输出语义(what it does)和调用语法(how to invoke it)。Agent 每次检索后必须从长文本中重新推导 input schema 和 action syntax,导致一个反复出现的退化循环:

Agent 发出 SkillRequest → 阅读 prose body → 输出近似但错误的 action(verb 不对、precondition 不满足、参数带括号) → 环境返回 "Nothing happens." → 重新检索同一 prose

这个循环是 ALFWorld 上 task 失败和 per-game LLM 调用成本的共同根因。关键论点:prose 表征本身——而非 factoring(跨文档去重)的缺失——是主要瓶颈。

Q2 方法:5-stage pipeline + 4-check 确定性验证 #

SaP 将 prose → pseudocode 的转换实现为一个 5 阶段 pipeline + 2 个 LLM-aware 后验证 pass:

  1. Parser(确定性):将 markdown 按 heading 切分为 procedural units
  2. Candidate proposer(确定性):提取 frame tuple $(\text{verb}, \text{objects}, \text{code\_langs}, \text{linked\_scripts})$,text-embedding-3-small 编码后 single-linkage clustering(cosine $\geq 0.65$)
  3. Contract extractor(LLM):每个 candidate cluster 一次 gpt-4o-mini 调用,输出 strict-JSON typed contract $\kappa$
  4. Verifier(确定性,4 checks):Coverage → Binding → Replacement → Risk,输出 rejection profile $\phi(c, \kappa)$,三档决策 auto\_promote / review / reject
  5. Refactor(确定性 + LLM post-passes):检测 call-sites → Binding Extraction (BE) 确认并提取 per-input bindings → Rewrite Cleanup (RC) 修复残留冲突 → 输出 rewritten parent skeleton
  6. 检索时,agent 只检索 parent skills;promoted child contracts 通过 invoke(κ, ā) placeholder 内联到 substituted bundle 中,按顺序交付三个 content block:

    1. Concrete action templates(agent 直接执行的环境 action)
    2. Rewritten parent skeleton(invoke 在流程中的位置)
    3. Inlined child contract spec(trigger, I/O schema, pre/postconditions)
    4. 核心技术壁垒 #

      4-check 确定性验证器是最难复制的设计。每个 check 针对一类独立的失败模式:

      • Coverage:token recall 检测命名错误的 contract
      • Binding:input-parent overlap 检测过宽的 cluster
      • Replacement:syntactic substitutability 检测 control-flow entanglement
      • Risk:AST scan 检测 unsafe sinks(rm -rf、undeclared network egress)

      四层 rejection 近乎正交(binding 捕获 ~50%、coverage ~35%、risk ~15% 的首次失败),没有任何 single soft classifier 能替代这一组合。在 skills\_500 上,整个 calibration grid 均达到 0% FP(Table 6,13 个阈值点 × 30 synthetic negatives)。

      Q3 结果 #

      ALFWorld(134 games × 3 seeds,gpt-4o-mini,$T=0$,max\_steps=30):

      • 82/402 vs 47/402 wins(+74% relative;pooled McNemar exact $p=8.2 \times 10^{-5}$)
      • −22.8 ± 6.4% input tokens,−17.3 ± 5.1% output tokens,−14.5 ± 4.1% LLM calls per game
      • SaP 在每个 task type 上均超过 GoS baseline(Figure 3)

      SkillsBench(10-task subset,gpt-5-codex):

      • 3/10 vs 2/10 wins,−43% input tokens
      • 8/10 tasks 实现 token 减少(range −14% to −82%)

      Pipeline yield(skills\_500):

      • 5,709 units → 149 clusters → 80 auto-promoted contracts(0% FP)
      • BE 确认 1,475/2,105 call-sites(70%),drops 30% spurious
      • RC 成功改写 320/322 parents(99.4%)

      §3 架构 / 方法图 #

      Pipeline 总览 #

      Figure 1: SaP pipeline — verified refactoring from prose parents to typed pseudocode

      Paper Figure 1. Repeated prose spans in parent skills (A) feed the numbered pipeline (B): form candidate cluster, draft child contract κ, verify it, bind arguments, clean residual conflicts. The resulting representation (C) separates what the skill does (typed signature), what local arguments the parent supplies (grounded invoke), and how the environment is actually called (concrete action template).

      Pipeline 的核心设计选择是将 LLM 调用(Stage 3 contract extraction, BE, RC)与确定性验证交替排列:每次 LLM 生成都被视为一个假设,由下游确定性 check 验证。这种 "accept with a witness, reject with a named cause" 的纪律使得 pipeline 的 FP 率不依赖 LLM 的可靠性。

      检索时 substituted bundle #

      Figure 2: Retrieval-time substitution — three content blocks delivered per invoke placeholder

      Paper Figure 2. For each retrieved parent, SaP replaces an invoke placeholder with the content the agent needs to act: (1) concrete action templates with bindings in prefix position, (2) rewritten parent skeleton showing where the call fits, (3) inlined child contract for abstract guarantee.

      Bundle 的排版将 executable action templates 放在 prefix 位置(agent 首先读取的区域),高层 contract 抽象放在后面。这种布局利用了 LLM 对 context 前部的注意力偏向,避免了 "lost-in-the-middle" 问题(Liu et al., 2024a)。

      Pipeline 流程(结构化) #

      stateDiagram-v2 [*] --> Parser: 500 markdown docs Parser --> CandidateProposer: 5,709 procedural units CandidateProposer --> ContractExtractor: 149 candidate clusters ContractExtractor --> Verifier: 149 contract drafts (LLM) Verifier --> Refactor: 80 auto_promote / 69 reject state Verifier { [*] --> Coverage Coverage --> Binding Binding --> Replacement Replacement --> Risk Risk --> Decision: s(φ) ≥ τ_auto? } state Refactor { [*] --> CallSiteDetect: 2,105 sites (det.) CallSiteDetect --> BE: LLM confirms 1,475 (70%) BE --> RC: LLM cleans 320/322 parents RC --> [*]: rewritten library }

      §4 作者证明 #

      无形式化收敛证明 — 仅实证 + 一个决策方程。 Agent paper 典型模式:无 formal success guarantee,以 empirical sweep 代替。本文可以被形式化但未被形式化的量是:给定 skill library 质量和 agent backbone 能力,promotion score threshold 与 downstream reward 之间的 monotonicity(目前仅在 calibration grid 上实证观察到)。

      唯一 load-bearing 方程 #

      Promotion score:

      $$s(\phi) = w_b \cdot \text{binding} + w_c \cdot \text{coverage} + w_r \cdot \text{replacement} - w_s \cdot \text{risk}$$

      符号含义取值范围
      $w_b, w_c, w_r, w_s$per-check weights正实数,论文未公开具体值
      bindingcluster 内 input-parent overlap$[0, 1]$
      coveragecontract trigger/I-O 对 unit text 的 token recall$[0, 1]$
      replacementparents 中 unit 可被 invoke(κ) 替换的比例$[0, 1]$
      riskunsafe sink 的加权 AST scan 得分$[0, 1]$,hard-reject at $\geq 0.80$

      物理意义:线性组合 reward 高 coverage/binding/replacement,penalize risk。$s(\phi)$ 与两个阈值 $\tau_{\text{auto}}, \tau_{\text{rev}}$ 比较,产生三档决策。整个验证器的智能在 check 定义和阈值——没有任何学习组件。

      6 项验证 #

      #Check验证内容结果
      1方程边界行为risk=1 → $s(\phi)$ 大幅为负 → reject;all checks=1 except risk=0 → max promote score符合设计意图
      2统计显著性McNemar exact on 56 SaP-only vs 21 GoS-only discordant pairs$p=8.2 \times 10^{-5}$,单 seed $p=0.0043$
      3Pipeline yield149 candidates → 80 auto\_promote at calibrated point0% FP on 30 synthetic negatives (3 classes × 10)
      4Ablation(增量贡献)det-only → +RC → +BE+RC+5 pp / +5 pp 增量,各修复独立 failure mode
      5Retrieval pool hierarchy允许 children 进入 top-K retrievalreward 从 22.4% 降至 16.4%(−27%),确认 bundle 而非 factoring 驱动收益
      6Threshold 鲁棒性13 个 grid 点均 0% FP从 $(0.30, 0.10)$ 到 $(0.90, 0.70)$,promotion 数从 80 降至 0,FP 始终为 0

      Figure 4: Calibration operating curve on skills_500

      Paper Figure 4. Lowering $\tau_{\text{auto}}$ from 0.65 to 0.30 keeps FP at 0% while admitting 31 more real candidates (49 → 80). The wide 0% FP region demonstrates that the four verifier checks, not threshold tuning, provide the discrimination power.

      Agent-specific 补充 #

      • Failure mode classification:论文识别出一类主导 failure mode — 即 retrieval-action feedback loop("Nothing happens." → re-retrieve)。Lost games 的 SkillRequest 和 "Nothing happens." 是 won games 的 ~4×。SaP 的方法精确 targeting 该 failure class。
      • Success-rate model:纯实证,sweep 维度为 (retrieval mode × seed)。未做 (task difficulty × planning depth × backbone model) 的完整 sweep。
      • Latency budget:未单独分析。Per-game LLM calls 减少 14.5% 间接降低了延迟。

      §5 实验与数据 #

      主实验:ALFWorld 134-game(Table 1) #

      Table 1: Main result on ALFWorld unseen split + Table 2: SkillsBench + Table 3: Ablation

      Paper Tables 1, 2, and 3 (combined image). Table 1 (top): SaP simultaneously raises reward and saves tokens on every metric. Table 2 (bottom-left): SkillsBench 10-task subset confirms reward-up/token-down against GoS. Table 3 (bottom-right): each LLM-aware post-verifier pass adds +5 pp incrementally.

      核心数据点:

      对比维度GoSSaPΔ
      Wins / 402 pooled47 (11.7%)82 (20.4%)+74% relative
      Input tokens / game247.8k191.4k−22.8%
      LLM calls / game39.733.9−14.5%

      Reward 和 token 成本同向改善而非 trade-off — won games 提前结束 → 节省 tokens,因此更高 reward 导致更低 cost。all\_full(全库 mount)在 20-game pilot 中 0 wins,说明超出 gpt-4o-mini 的 context 处理能力时,更多信息 strictly hurts。

      Per-task-type 分布(Figure 3) #

      Figure 3: Per-task-type win rate comparison, seed=42

      Paper Figure 3. SaP beats GoS on every task type. Largest absolute gains on pick\_and\_place\_simple (+4) and pick\_cool\_then\_place (+3), both requiring multi-step navigate-take-(modify-)place sequences that benefit most from inlined concrete action templates.

      SaP 在需要多步 navigate-take-modify-place 序列的 task type 上获益最大,这与 bundle 中 action template 提供精确 verb-argument 模板的机制一致。

      机制证据:post-retrieval action correctness(Table 4) #

      Table 4: Post-retrieval next-action outcome

      Paper Table 4. SaP is 1.43× (1.57× on READ_SKILL) more likely to act successfully after retrieving a skill, and issues 31% fewer total retrieval events. This is the direct evidence that the substituted bundle breaks the retrieval-action loop.

      Post-retrieval action success rate: SaP 29.3% vs GoS 20.5%。在 READ\_SKILL 事件上差距更大:29.8% vs 19.0%(1.57×)。"Nothing happens." 占比从 54.8% 降至 43.7%。这直接支撑了 "bundle 的两个结构化信号 short-circuit 了 retrieval-action loop" 的机制解释。

      SkillsBench 泛化 #

      10-task subset 上 SaP 比 GoS 多赢 1 game(3 vs 2)但 token 减少 43%。Case study:GoS 的 citation-management skill 为 8,354 tokens,超过 gpt-5-codex 的 8K shell-output cap → agent 读到截断版 → 尝试重写 → 耗尽 budget。SaP 重构后 3,566 tokens,完整 fit,agent 正确完成。

      Ablation 要点 #

      • BE: drops 30% spurious call-sites(keyword 匹配产生的 false positive:Bundled Resources 列表提到 child name,Risk bullet 提到 file deletion)
      • RC: 修复 parent 中残留的 verb 冲突(put X in/on Ymove X to Y,对齐 ALFWorld parser 实际接受的语法)
      • Hierarchy ablation: 允许 children 作为 standalone retrieval results → reward −27%,因为 agent 读到脱离 parent context 的 contract spec

      §6 论证链 #

      StepClaim支撑证据论文链路
      1Prose 表征导致 retrieval-action 反馈循环lost games 的 SkillRequest/game 是 won games 的 ~4×;"Nothing happens." 同比 ~4×(Table 11/12)§1 → §6.1
      2Typed contract + concrete action template 可打破该循环Post-retrieval OK% 从 20.5 → 29.3(Table 4);trace idx\_36: 7 vs 22 steps,0 vs 3 syntax errors§3.5 → §6.1
      34-check 确定性验证器可在 0% FP 下 gate contract promotion30 synthetic negatives × 13 threshold grid points 全部 0% FP;四层 rejection 近乎正交(Table 7)§3.3–§3.4 → §5.6
      4BE 和 RC 各修复独立的 failure class+5 pp / +5 pp 增量(Table 3);BE drops 30% spurious sites,RC 修复 verb conflicts§3.2 → §5.4 → §6.2
      5收益来自 parent-side bundle 而非 cross-parent factoring打破 hierarchy → reward −27%(§5.5);children 出现在 top-K 的 ~8% games 中,agent 丢失 action template context§3.5 → §5.5
      6SaP 实现 reward + token 同向改善+74% wins at −23% tokens(Table 1);won games 提前结束 → token 节省是 reward gain 的结果而非 trade-off§5.2

      §7 实现 cross-reference #

      代码可用性 #

      论文声明完整开源:6 个 sequential CLI scripts(parser → candidate proposer → contract extractor → verifier → calibrate policy → refactor library)+ build_refactored_skillset.py + evaluation/alfworld_run.py

      [实现声明已开源 — CLI pipeline + refactored library + 全部评估输出;但 L1 未包含 repo URL,截至读取时无法验证具体 commit]

      核心技术壁垒(展开) #

      4-check 确定性验证器的复制难点在于 check 定义的粒度选择:Coverage 需要选择正确的 token recall 计算方式(trigger/I-O strings vs full contract text),Binding 需要定义 "input name overlap" 的精确语义(是字符串包含还是 embedding similarity),Replacement 需要实现 markdown-aware syntactic substitution(保留 heading 结构),Risk 需要维护 unsafe sink 的 AST pattern 列表。论文在 Appendix F 给出了 Contract IR schema,但 4 个 check 的具体实现逻辑仅有自然语言描述,无伪代码。

      关键实现细节 #

      1. BE 的 should\_invoke 判断:BE 对每个 call-site 询问 gpt-4o-mini "is this unit a genuine instance of κ?" + 提取 per-input bindings。确定性 post-check drops empty/non-overlapping bindings。这一步过滤了 30% 的 false-positive call-sites,说明关键字匹配级别的 procedure identification 根本不可靠——必须有语义判断。
        1. Hierarchical-only retrieval pool 是 load-bearing 的:设计时看似可选的 hierarchy 约束(children 不进入 top-K)实际贡献了 27% 的 reward。原因是 child contract 脱离 parent context 后缺少 action template,agent 获得 "what" 但丢失 "how",退回到 prose 循环。