本文へスキップ
Skillpedia
一般的なプログラミング7.8k · #13056

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がスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/idempotent-file-replace/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

AIへの頼み方の例

“この内容で設定ファイルを置き換えてください。ただし、ファイルの内容が実際に違う場合だけ書き込んでください。”

毎週5つの新しいスキル。1分で読めます。

仕組み

エージェントは、まず現在のファイルを読み、希望する内容と比較します。2つが違う場合だけ書き込み、どこが変わるかを説明するために差分を表示することもできます。

技術的な内容(元の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.

よくある質問

ファイルがまだない場合はどうしますか?

現在の内容を空とみなし、新しいファイルを書き込みます。

空白は重要ですか?

スキルは内容を厳密に比較しますが、末尾の改行が1つ違うだけなら無視するオプションもあります。

なぜこれがビルドに役立つのですか?

変更のない書き込みを省くと、ファイルの時刻が安定し、ウォッチャーやキャッシュが動かなくなるからです。

詳細

作者による元の説明

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

このスキルは役に立ちますか?

0

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル