Communitygithub.com

內容雜湊快取模式

使用 SHA-256 內容雜湊快取昂貴的檔案處理結果(如 PDF 解析、文字萃取、圖片分析),快取鍵與路徑無關,能自動失效。適合在重複處理相同檔案且處理成本高昂時使用。

內容雜湊快取模式 是什麼?

此技能提供一個基於 SHA-256 內容雜湊的檔案快取模式,用於快取昂貴的檔案處理結果。與傳統的基於路徑的快取不同,這種方法在檔案移動或重新命名時仍然能命中快取,且當檔案內容變更時會自動使快取失效。它支援 Python 語言,並可應用於 CLI 工具,透過 `--cache/--no-cache` 參數控制。核心模式包括:使用區塊讀取計算檔案雜湊、凍結資料類別(frozen dataclass)儲存快取條目、以 `{hash}.json` 格式進行 O(1) 查詢的檔案式快取儲存,以及將快取邏輯與純處理函式分離的服務層包裝器。此模式可大幅減少重複處理時間,並提升開發效率。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/content-hash-cache-pattern

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

內容雜湊檔案快取模式

使用 SHA-256 內容雜湊作為快取鍵,快取昂貴的檔案處理結果(PDF 解析、文字萃取、圖片分析)。與基於路徑的快取不同,此方法在檔案移動或重新命名時仍能命中快取,並在內容變更時自動失效。

啟動時機

  • 建構檔案處理管線(PDF、圖片、文字萃取)
  • 處理成本高昂,且相同檔案會重複處理
  • 需要提供 --cache/--no-cache CLI 選項
  • 希望為現有的純函式加入快取功能,而不修改函式本身

核心模式

1. 基於內容雜湊的快取鍵

使用檔案內容(而非路徑)作為快取鍵:

import hashlib
from pathlib import Path

_HASH_CHUNK_SIZE = 65536  # 大檔案以 64KB 區塊讀取

def compute_file_hash(path: Path) -> str:
    """計算檔案內容的 SHA-256 雜湊(針對大檔案進行區塊讀取)。"""
    if not path.is_file():
        raise FileNotFoundError(f"找不到檔案:{path}")
    sha256 = hashlib.sha256()
    with open(path, "rb") as f:
        while True:
            chunk = f.read(_HASH_CHUNK_SIZE)
            if not chunk:
                break
            sha256.update(chunk)
    return sha256.hexdigest()

為何使用內容雜湊? 檔案重新命名或移動 = 快取命中。內容變更 = 自動失效。不需要索引檔案。

2. 凍結資料類別(Frozen Dataclass)儲存快取條目

from dataclasses import dataclass

@dataclass(frozen=True, slots=True)
class CacheEntry:
    file_hash: str
    source_path: str
    document: ExtractedDocument  # 快取的處理結果

3. 基於檔案的快取儲存

每個快取條目儲存為 {hash}.json — 透過雜湊值進行 O(1) 查詢,不需要索引檔案。

import json
from typing import Any

def write_cache(cache_dir: Path, entry: CacheEntry) -> None:
    cache_dir.mkdir(parents=True, exist_ok=True)
    cache_file = cache_dir / f"{entry.file_hash}.json"
    data = serialize_entry(entry)
    cache_file.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")

def read_cache(cache_dir: Path, file_hash: str) -> CacheEntry | None:
    cache_file = cache_dir / f"{file_hash}.json"
    if not cache_file.is_file():
        return None
    try:
        raw = cache_file.read_text(encoding="utf-8")
        data = json.loads(raw)
        return deserialize_entry(data)
    except (json.JSONDecodeError, ValueError, KeyError):
        return None  # 將損毀視為快取未命中

4. 服務層包裝器(單一職責原則)

保持處理函式純淨。將快取作為獨立的服務層加入。

def extract_with_cache(
    file_path: Path,
    *,
    cache_enabled: bool = True,
    cache_dir: Path = Path(".cache"),
) -> ExtractedDocument:
    """服務層:檢查快取 → 萃取 → 寫入快取。"""
    if not cache_enabled:
        return extract_text(file_path)  # 純函式,不了解快取

    file_hash = compute_file_hash(file_path)

    # 檢查快取
    cached = read_cache(cache_dir, file_hash)
    if cached is not None:
        logger.info("快取命中:%s(雜湊=%s)", file_path.name, file_hash[:12])
        return cached.document

    # 快取未命中 → 萃取 → 儲存
    logger.info("快取未命中:%s(雜湊=%s)", file_path.name, file_hash[:12])
    doc = extract_text(file_path)
    entry = CacheEntry(file_hash=file_hash, source_path=str(file_path), document=doc)
    write_cache(cache_dir, entry)
    return doc

關鍵設計決策

決策理由
SHA-256 內容雜湊與路徑無關,內容變更時自動失效
{hash}.json 檔案命名O(1) 查詢,不需要索引檔案
服務層包裝器單一職責原則:萃取保持純淨,快取是獨立關注點
手動 JSON 序列化完整控制凍結資料類別的序列化過程
損毀時回傳 None優雅降級,下次執行重新處理
cache_dir.mkdir(parents=True)首次寫入時懶建立目錄

最佳實踐

  • 雜湊內容,而非路徑 — 路徑會變,內容身份不變
  • 處理大檔案時進行區塊讀取 — 避免將整個檔案載入記憶體
  • 保持處理函式純淨 — 它們不應該知道快取的存在
  • 記錄快取命中/未命中,並使用截斷的雜湊以利除錯
  • 優雅處理損毀 — 將無效的快取條目視為未命中,絕不崩潰

應避免的反模式

# 錯誤:基於路徑的快取(檔案移動/重新命名時會失效)
cache = {"/path/to/file.pdf": result}

# 錯誤:將快取邏輯放入處理函式內部(違反單一職責原則)
def extract_text(path, *, cache_enabled=False, cache_dir=None):
    if cache_enabled:  # 現在這個函式有兩個職責
        ...

# 錯誤:對巢狀凍結資料類別使用 dataclasses.asdict()
# (複雜的巢狀型別可能導致問題)
data = dataclasses.asdict(entry)  # 應使用手動序列化

使用時機

  • 檔案處理管線(PDF 解析、OCR、文字萃取、圖片分析)
  • 受益於 --cache/--no-cache 選項的 CLI 工具
  • 批次處理中,相同檔案在不同執行之間重複出現
  • 為現有的純函式加入快取功能,而不修改函式本身

不應使用時機

  • 資料必須永遠保持最新(即時資料流)
  • 快取條目會非常龐大(應考慮串流處理)
  • 結果依賴於檔案內容以外的參數(例如不同的萃取設定)

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

相關技能