idempotent-file-replace
하는 일
이 스킬은 파일을 교체하기 전에 읽고 비교하도록 AI 에이전트에게 알려 줍니다. 불필요한 쓰기로 빌드나 버전 기록이 흔들리면 안 되는 사람을 위한 스킬입니다.
사용하는 경우
- ✓특정 내용으로 파일을 완전히 교체해 달라고 요청할 때.
- ✓불필요한 파일 변경이 재빌드나 핫 리로드를 일으킬 때.
- ✓빈 차이 없이 깔끔한 버전 기록을 원할 때.
스킬 링크
https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/idempotent-file-replace/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“설정 파일을 이 내용으로 교체해 주세요. 다만 파일 내용이 실제로 다를 때만 저장해 주세요.”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
에이전트는 먼저 현재 파일을 읽은 다음 원하는 내용과 비교합니다. 두 내용이 다를 때만 쓰며, 무엇이 바뀌는지 설명하도록 diff를 보여 줄 수도 있습니다.
기술 내용 (원본 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
- 업데이트
- 2026. 11. 1.
댓글
- …
이 저장소의 다른 스킬
agentpilot
7.8k작업을 준비하고 AgentPilot 루프를 실행해 변경을 제안, 테스트, 점수화하면서 프로젝트를 단계적으로 개선하도록 돕습니다.
openspace
7.8k에이전트 스킬을 저장하고 가져오는 도구인 OpenSpace를 설정하고, MCP를 통해 AI 앱에 연결하도록 돕습니다.
rsi-arena
7.8kAIME나 Terminal-Bench 같은 표준 AI 벤치마크 테스트를 설정하고 실행해 서로 다른 개선 방법을 비교하도록 돕습니다.
experiment-guide
7.8k프로그램을 개선하는 방법을 조사하면서 작은 실험을 계획하고, 결과를 읽고, 발견 사항을 기록하도록 돕습니다.