Chuyển đến nội dung
Skillpedia
Lập trình chung7.8k · #13056

idempotent-file-replace

Skill này làm gì

Skill này bảo AI agent đọc một file và so sánh trước khi thay thế nó. Nó dành cho những người mà việc build hoặc lịch sử phiên bản sẽ bị xáo trộn bởi các lần ghi không cần thiết.

Khi nào nên dùng

  • ✓Khi bạn yêu cầu agent thay thế hoàn toàn một file bằng nội dung cụ thể.
  • ✓Khi thay đổi file sẽ kích hoạt build lại hoặc hot reload không cần thiết.
  • ✓Khi bạn muốn lịch sử phiên bản sạch, không có diff rỗng.

Liên kết skill

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

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/idempotent-file-replace/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Thay thế file cấu hình bằng nội dung này, nhưng chỉ ghi nếu file thực sự khác.”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Agent đọc nội dung hiện tại trước, rồi so sánh với nội dung mong muốn. Nó chỉ ghi khi hai bên khác nhau, và có thể hiển thị diff để giải thích điều gì sẽ thay đổi.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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.

Câu hỏi thường gặp

Nếu file chưa tồn tại thì sao?

Skill coi nội dung hiện tại là rỗng và ghi file mới.

Khoảng trắng có quan trọng không?

Skill so sánh nội dung một cách nghiêm ngặt, với một tùy chọn bỏ qua khác biệt của một ký tự xuống dòng cuối.

Tại sao điều này giúp ích cho build?

Bỏ qua các lần ghi không đổi giữ thời gian file ổn định, nên các trình theo dõi và cache không bị kích hoạt.

Chi tiết

Mô tả gốc của tác giả

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

Độ phổ biến

Sao GitHub
7.8k
Vị trí xếp hạng
#13056
Giấy phép
MIT
Cập nhật
1/11/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự