Перейти к содержанию
Skillpedia
Код в целом7.8k · #13056

idempotent-file-replace

Что он делает

Этот скилл велит ИИ-агенту прочитать файл и сравнить его, прежде чем заменить. Он нужен тем, чьи сборки или история версий нарушаются лишней записью.

Когда использовать

  • ✓Когда вы просите агента полностью заменить файл определенным содержимым.
  • ✓Когда изменения файла без причины запускают пересборку или горячую перезагрузку.
  • ✓Когда нужна чистая история версий без пустых различий.

Ссылка на скилл

https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/idempotent-file-replace/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/idempotent-file-replace/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Замени файл конфигурации этим содержимым, но записывай его, только если файл действительно отличается.”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Агент сначала читает текущий файл, затем сравнивает его с нужным содержимым. Он записывает файл, только если они различаются, и может показать различия, чтобы объяснить, что изменится.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с 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.

Частые вопросы

Что если файла еще нет?

Скилл считает текущее содержимое пустым и создает новый файл.

Важны ли пробелы?

Скилл сравнивает содержимое строго, но есть опция игнорировать различие в одном завершающем переводе строки.

Почему это помогает сборкам?

Пропуск ненужной записи сохраняет время изменения файлов, поэтому наблюдатели и кеши не срабатывают.

Подробности

Оригинальное описание автора

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

Популярность

Звёзды на GitHub
7.8k
Место в рейтинге
#13056
Лицензия
MIT
Обновлён
01.11.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы