# 1495 2026 02 02 Sanitize Canonical Cache 7ac05060

> Cache Canonical Messages in Cleanup Loop

- Skill: `tools-only/1495-2026-02-02-sanitize-canonical-cache-7ac05060` (Agent Skill, multi-file: 3 files)
- Install (CLI): `npx skillmds@latest add tools-only/1495-2026-02-02-sanitize-canonical-cache-7ac05060`
- Raw SKILL.md: https://api.skillmd.com/api/skills/tools-only/1495-2026-02-02-sanitize-canonical-cache-7ac05060/raw
- Safety review: pending (external: skill-scanner PASS, skillspector PASS)
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: tools-only (https://skillmd.com/u/tools-only)
- Updated: 2026-09-22
- Page: https://skillmd.com/skills/tools-only/1495-2026-02-02-sanitize-canonical-cache-7ac05060

---


# Cache Canonical Messages in Cleanup Loop

## Summary

The sanitize cleanup loop re-canonicalized messages multiple times per iteration. We now cache canonical messages per iteration, recomputing only after mutations, and remove the double conversion inside `find_dangling_tool_calls()`.

## Context

- Files: `src/tunacode/core/agents/resume/sanitize.py`, `src/tunacode/utils/messaging/adapter.py`
- Symptom: redundant `to_canonical()` calls during cleanup iterations.

## Root Cause

Canonicalization was happening in each cleanup helper (and twice per message in `find_dangling_tool_calls()`), so a single iteration performed multiple full conversions of the same message list.

## Changes

- Converted each message once inside `find_dangling_tool_calls()` by reusing a single canonical instance.
- Cached canonical messages at the start of each cleanup iteration and recomputed only after mutations.
- Added canonical cache passthroughs to `remove_empty_responses()` and `remove_consecutive_requests()`.
- Added a unit test to verify 1N conversions in a no-mutation iteration.

## Behavioral Impact

- Cleanup iterations now run with fewer canonicalization passes (1N without mutations, 2N when deletions occur).
- Cleanup behavior and tool-call pruning logic remain unchanged.

## Related Cards

- [[message-history]]
- [[sanitize-loop]]

