NeurIPS 2026Coming to NeurIPS?Explore papers, orals & directions

Refactoring Code Through Library Design

Žiga Kovačič, Justin T Chiu, Celine Lee, Wenting Zhao, Kevin EllisNeurIPS 2026

TL;DR

AI coding agents are brilliant at solving isolated programming puzzles, right up until their myopic, file-by-file view turns your codebase into a tangled mess of duplicated logic. This paper introduces LIBRARIAN, a method that teaches AI to step back, discover shared abstractions across multiple files, and refactor real-world code into clean, reusable libraries. Better yet, the authors discover that measuring how "unsurprising" code is to a language model predicts human-preferred, generalizable software design far better than traditional software engineering metrics.

What Problem Does This Paper Address?

Writing software is mostly rewriting software, and poor rewrites incur up to $2 trillion in global technical debt annually. As LLMs write more of our code, this problem threatens to snowball: constrained by context windows and one-off prompts, coding agents excel at local fixes while remaining blind to the broader architecture, spawning redundant, overly specialized code.

Prior academic work in "library learning" tried to automate code reuse, but mostly operated on toy programs written in constrained, esoteric languages like $\lambda$-calculus. Scaling this to messy, real-world Python raises two big questions: How do you mathematically define a "good, natural" refactoring? And how do you get an LLM to redesign multiple large files without blowing past its context limit or breaking existing functionality?

Methods

The authors introduce LIBRARIAN, an algorithm that combines a divide-and-conquer strategy with sample-and-rerank search:

Figure 1: A refactoring task comprises a set of files. We refactor the files by designing a new library. Candidate refactorings are evaluated based on a refactoring objective, and are expected to maintain correctness of the original code sources (pass rate). We explore several refactoring objectives.
  1. Divide-and-Conquer Clustering: You can't stuff the Linux kernel into a single prompt. Instead of grouping files by their problem descriptions (as prior work did, assuming similar problems yield similar code), LIBRARIAN prompts an LLM to summarize the actual code in each file, embeds those summaries, and uses agglomerative clustering to group structurally related files into bite-sized chunks.
  2. Sample-and-Rerank: For each cluster, a backend coding model (like o4-mini or Claude Code) samples $K$ candidate refactorings—generating both a new shared library and the rewritten source files. Any candidate failing the original unit or integration tests is immediately tossed out.
  3. The Objective Function (MDL): How do we crown the winner among passing candidates? The authors test classic software engineering metrics—Cyclomatic Complexity (CC) and Maintainability Index (MI)—against raw token counts and a neural Minimum Description Length (MDL). Here, MDL is computed as the negative log-probability (perplexity) of the library and refactored code under a reference language model (Qwen-2.5-3B), measuring both compression and how idiomatic or "natural" the code looks.

Datasets

To bridge classic program synthesis and production software engineering, the authors evaluate LIBRARIAN across three tiers of benchmarks:

  • Logo & Date: Classic, small-scale library learning benchmarks (averaging 10–14 lines of code) involving graphics generation and string manipulation, borrowed from prior state-of-the-art work (REGAL) for head-to-head comparison.
  • CodeContests: 300 competitive programming solutions across 10 tasks (~87 lines of code per file), representing quick, one-off human solutions ripe for consolidation.
  • HuggingFace Transformers & Diffusers: A newly compiled, high-stakes benchmark featuring 32 production-scale Python files (~690–745 lines of code each) implementing popular ML models (like LLaMA, Qwen2, and Stable Diffusion UNets), backed by 75 to 181 rigorous integration tests per file.

Key Insights and Ideas

  • Language models beat classic software metrics at judging code quality: Both human judges (in a 14-person study) and downstream code-reuse tests favored MDL-optimized libraries over traditional metrics like Maintainability Index and Cyclomatic Complexity, which completely lost signal on smaller programs.
  • MDL avoids the "Perl Golf" trap: Minimizing raw token counts rewards deleting helpful comments and cramming logic into unreadable one-liners. Because MDL optimizes for predictability under a language model, it naturally rewards clean comments and modular helper functions—even single-use ones—if they make the subsequent code easier to read and predict.
  • MDL drives generalization to unseen code: While raw token minimization and MDL perform similarly on the files being refactored, MDL-optimized libraries prove significantly more reusable when refactoring new, unseen holdout files.
Figure 3: Metrics of library reuse for HuggingFace Transformers/Diffusers on unseen holdout sources.
  • Even top coding agents need explicit search and objectives: Simply asking Claude Code in a single pass to "extract shared code into a library" falls well short of LIBRARIAN. Wrapping agents in clustering and MDL-guided test-time search more than doubles the extracted library functions and boosts their reuse—plateauing nicely around just $K=5$ to $10$ samples.

Key Results

  • Real-World Production Code: On HuggingFace Transformers, LIBRARIAN extracts shared ML components (like Attention, RoPE helpers, and Decoder layers) via inheritance and direct class reuse while passing 100% of integration tests. It reduces MDL by 32.8%—matching concurrent real-world refactorings by HuggingFace's own engineers (33.5%) and the paper's authors (38%). Compared to single-pass Claude Code, LIBRARIAN extracts 15 library definitions vs. 7, increasing total library uses from 41 to ~100.
Figure 4: Representative result for refactoring HuggingFace Transformers using LIBRARIAN
  • Competitive Programming: On CodeContests, LIBRARIAN nearly halves MDL (0.53 ratio) and cuts token counts to 0.66, building libraries averaging 10.3 functions called 5.17 times each.
  • Program Synthesis: On the challenging Logo benchmark, learning a library with LIBRARIAN (K=5) boosts downstream problem-solving pass rates from 49.3% (prior SOTA, REGAL) to 69.9%, and from 90.2% to 94.7% on Date.

Limitations and Future Work

  • Scale and Cost: LIBRARIAN operates on multi-file clusters, not entire repositories. Running agentic refactoring at production scale is also slow, taking ~30 minutes per HuggingFace candidate to generate and run integration suites (though this is a one-time upfront cost).
  • File-Level Granularity: The clustering algorithm groups whole files together; it cannot yet slice apart giant, monolithic files that mix unrelated concerns.
  • Reliance on Existing Tests: Correctness relies entirely on pre-existing test suites. Automatically synthesizing new unit tests for freshly minted library abstractions remains an open avenue for future work.

Summary updated

BibTeX
@inproceedings{kovacic2026refactoring,
  author = {Žiga Kovačič and Justin T Chiu and Celine Lee and Wenting Zhao and Kevin Ellis},
  title = {{Refactoring Code Through Library Design}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2026},
  url = {https://openreview.net/forum?id=dOkgsUfJSn},
}
Figure