idempotent-file-replace
Qué hace
Esta skill indica al agente de IA que lea un archivo y lo compare antes de reemplazarlo. Es para personas cuyas compilaciones o historial de versiones se ven alterados por escrituras innecesarias.
Cuándo usarla
- ✓Cuando pides al agente que reemplace por completo un archivo con un contenido concreto.
- ✓Cuando los cambios en un archivo provocarían recompilaciones o recargas en caliente sin motivo.
- ✓Cuando quieres un historial de versiones limpio, sin diferencias vacías.
Link de la skill
https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/idempotent-file-replace/SKILL.mdCópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.
Cómo usar
La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.
Mensaje listo para pegar
Para Claude Code, Codex o Cursor: ejecútalo en la carpeta del proyecto y la skill queda instalada.
Descarga el SKILL.md y ponlo en la carpeta de skills de tu agente.
Ejemplo de qué pedirle a la IA
“Reemplaza el archivo de configuración con este contenido, pero solo escríbelo si el archivo es realmente distinto.”
5 skills nuevas por semana. 1 minuto de lectura.
Cómo funciona
El agente lee primero el archivo actual y luego lo compara con el contenido deseado. Solo escribe si los dos son distintos, y puede mostrar un diff para explicar qué cambiaría.
Contenido técnico (SKILL.md original)
Texto original del autor, en inglés, directo de GitHub.
Idempotent File Replace
When tasked with completely replacing a file with specific content, always perform a read-and-compare step before writing. Only write when the file actually differs from the desired content.
Why This Matters
| Risk of blind writes | Benefit of idempotent check |
|---|---|
| Triggers filesystem watchers / hot-reload loops | No spurious rebuild when content is unchanged |
| Wastes a tool call on a no-op | One extra read saves a write + all downstream costs |
| Pollutes VCS history with empty diffs | Clean commit history |
| Breaks CI caching layers | Stable mtimes keep caches valid |
Procedure
Step 1 — Read the current file
Always read the file first, even when you are confident about the replacement.
read_file(path="<target_file>")
If the file does not yet exist, treat its current content as an empty string and proceed to Step 3.
Step 2 — Compare current content to desired content
Perform an exact string comparison (whitespace-sensitive).
current = <content returned by read_file>
desired = <full replacement content>
needs_write = (current.strip() != desired.strip())
# Use .strip() to tolerate a single trailing newline difference,
# or compare verbatim if byte-exact output is required.
Alternatively, a unified diff gives a human-readable explanation of what would change and is useful for logging:
import difflib, sys
diff = list(difflib.unified_diff(
current.splitlines(keepends=True),
desired.splitlines(keepends=True),
fromfile="current",
tofile="desired",
))
if not diff:
print("Files are identical — skipping write.")
needs_write = False
else:
print("Diff detected:\n" + "".join(diff))
needs_write = True
Step 3 — Conditional write
if needs_write:
write_file(path="<target_file>", content=desired)
print("File written.")
else:
# Report completion immediately — no write needed.
print("File already matches desired content. No action taken.")
Decision Flowchart
Task: "Replace <file> with <content>"
│
▼
read_file(<file>)
│
▼
content == desired?
┌────┴────┐
YES NO
│ │
▼ ▼
SKIP write_file(<file>, desired)
write │
│ ▼
└──► Report COMPLETE
Complete Example
TARGET = "src/components/Panel.ts"
DESIRED_CONTENT = """// Auto-generated — do not edit
export const Panel = () => { ... };
"""
# Step 1: read
current = read_file(path=TARGET) # tool call
# Step 2: compare
if current.strip() == DESIRED_CONTENT.strip():
print(f"{TARGET} already matches. Skipping write.")
# → COMPLETE
else:
# Step 3: write
write_file(path=TARGET, content=DESIRED_CONTENT) # tool call
print(f"{TARGET} updated.")
# → COMPLETE
Edge Cases
| Situation | Handling |
|---|---|
| File does not exist | read_file raises / returns empty → treat as "" → always write |
| Encoding differences | Normalize to UTF-8 before comparison |
| Line-ending differences (CRLF vs LF) | Normalize with .replace("\r\n", "\n") before comparing |
| Byte-exact requirement | Skip .strip() and compare verbatim |
| Large files | Compute SHA-256 hash of both strings for efficiency before full diff |
Key Principle
Never assume a file needs to be written. One cheap read prevents an expensive (and potentially harmful) write.
This pattern applies to any "replace entire file" task regardless of file type: source code, configuration, templates, lock files, generated assets, etc.
Preguntas frecuentes
¿Y si el archivo aún no existe?
La skill trata el contenido actual como vacío y escribe el archivo nuevo.
¿Importan los espacios en blanco?
La skill compara el contenido de forma estricta, con una opción para ignorar la diferencia de un solo salto de línea final.
¿Por qué esto ayuda a las compilaciones?
Omitir las escrituras sin cambios mantiene estables las fechas de los archivos, así que los observadores y las cachés no se activan.
Detalles
Descripción original del autor
Read-then-diff before writing a file to ensure the write is skipped when the content already matches, preventing unnecessary modifications and downstream side effects.
repo: HKUDS/AgentPilot
Popularidad
- Estrellas en GitHub
- 7,8 mil
- Posición en el ranking
- #13056
- Licencia
- MIT
- Actualizada
- 1/11/2026
Comentarios
- …
Más skills de este repositorio
agentpilot
7,8 milAyuda a tu agente a mejorar un proyecto paso a paso, preparando una tarea y ejecutando el bucle de AgentPilot que propone, prueba y puntúa cambios.
openspace
7,8 milAyuda a tu agente a configurar OpenSpace, una herramienta que guarda y recupera skills de agentes, y a conectarla a tu app de IA mediante MCP.
rsi-arena
7,8 milAyuda a tu agente a configurar y ejecutar pruebas de referencia de IA conocidas, como AIME y Terminal-Bench, para comparar distintos métodos de mejora.
experiment-guide
7,8 milAyuda a tu agente a planificar experimentos pequeños, leer sus resultados y anotar conclusiones mientras investiga cómo mejorar un programa.
Skills parecidas
diffs
394 milPermite que tu agente genere un diff real y compartible de los cambios, como enlace de visualización o archivo de imagen, en lugar de un resumen escrito a mano.
coding-agent
394 milAyuda a tu agente a pasar un trabajo de programación grande a Codex, Claude Code u OpenCode como trabajador en segundo plano, y después revisar su progreso.
gh-issues
394 milAyuda a tu agente a encontrar incidencias de GitHub, elegir cuáles trabajar y abrir pull requests con correcciones, incluido el seguimiento de los comentarios de revisión.