caveman-compress
Compress a memory file such as CLAUDE.md or a todo list into caveman format to save input tokens, keeping a readable backup. Trigger: /caveman-compress.
1How It Works & Mechanism
This is a rare skill in this batch that contains 'real code': SKILL.md has only one core instruction—execute `python3 -m scripts <absolute_path>` within the directory where SKILL.md resides, with all compression logic implemented in the bundled Python package.
The compression scripts live in `scripts/` (adjacent to this SKILL.md). If the path is not immediately available, search for `scripts/__main__.py` next to this SKILL.md. 2. From the directory containing this SKILL.md, run: python3 -m scripts <absolute_filepath>
The compression action sends the file body to Claude: it prefers the Anthropic SDK (requires ANTHROPIC_API_KEY) and falls back to a local `claude --print` CLI subprocess (using desktop user authentication).
api_key = os.environ.get("ANTHROPIC_API_KEY") if api_key: try: import anthropic client = anthropic.Anthropic(api_key=api_key, timeout=CLAUDE_CALL_TIMEOUT_SECONDS) msg = client.messages.create( model=os.environ.get("CAVEMAN_MODEL", "claude-sonnet-4-5"),
Code blocks are replaced with opaque markers before being sent to the model, and are restored afterward under the rule that 'each marker must appear exactly once'; otherwise, writing is rejected entirely—a core mechanism to prevent compression from corrupting commands.
def restore_code_blocks(text: str, blocks: List[Tuple[str, str]]) -> str: """Restore markers exactly; fail closed if model removed, copied, or altered one."""
Writing does not mean completion: a dedicated structural validator (validate.py) compares headers, code blocks, URLs, paths, bullet points, and inline code between the original and compressed texts; if it fails, it asks Claude to 'fix only the listed errors' and retries up to 2 times.
validate_headings(orig, comp, result) validate_code_blocks(orig, comp, result) validate_urls(orig, comp, result) validate_paths(orig, comp, result) validate_bullets(orig, comp, result) validate_inline_codes(orig, comp, result)
Writing follows a chain of 'backup first, read-back verification, atomic replacement, and preserving permission bits & line-ending styles', with many details engineered to fix past data loss incidents.
write_bytes_atomic(backup_path, original_raw) if backup_path.read_bytes() != original_raw: print(f"❌ Backup write verification failed: {backup_path}")
Hard input gates exist: files >500KB are rejected, file names suspected of being credentials/keys are rejected, empty files are rejected, and existing backups cause an abort (to prevent overwrites).
MAX_FILE_SIZE = 500_000 # 500KB
Concurrency uses OS-native file locks (POSIX fcntl.flock / Windows msvcrt.locking), with lock keys derived from the first 16 characters of the backup path's sha256; filesystems that do not support locks degrade to uncoordinated execution, and symlinks encountered in lock directories/files are strictly rejected.
return _state_base_dir("locks") / f"{digest}.lock"
Non-expansion invariant: the compressed output, evaluated on body text excluding frontmatter, must be strictly shorter, otherwise execution aborts without touching the original file; this rule also holds for repair runs.
if not _is_smaller_than_body(compressed_body, body): print(" Original file is untouched (no backup created).") return False
Compressible scope is governed by detect.py extension allowlists/denylists plus content sniffing solely for extensionless files; .original.md backups are never re-compressed.
COMPRESSIBLE_EXTENSIONS = {".md", ".mdc", ".txt", ".markdown", ".rst", ".typ", ".typst", ".tex"}
2Core Capabilities
3External Dependencies
| Kind | Dependency / Endpoint |
|---|---|
| api | Anthropic Messages API(经 anthropic Python SDK) |
| cli | claude CLI(Claude Code / Claude desktop 认证) |
| package | anthropic(Python SDK,可选) |
| package | tiktoken(可选,仅 benchmark.py) |
| cli | python3(运行时不带第三方依赖;仅标准库 contextlib/errno/hashlib/os/re/shutil/stat/subprocess/tempfile/time/pathlib,Windows 用 msvcrt、POSIX 用 fcntl) |
4Recommended Governance & Evidence
- scripts/: Executes local script or command: python3 -m scripts <absolute_filepath> (the sole execution mechanism specified in SKILL.md)
- 网络端点: Declares external network access: Anthropic API via anthropic SDK (client.messages.create), active when ANTHROPIC_API_KEY is present
- 本地工作目录: File I/O and artifact output: modifies the target file directly (in-place overwrite with compressed content)
5Second-Pass Verification
- [ok] SKILL.md 提到的脚本路径与运行方式 — `python3 -m scripts <file>` 成立:scripts/__main__.py 导入 cli.main 并调用;cli.py 校验参数个数与文件存在/类型后执行 compress_file。SKILL.md 提示的 'search for scripts/__main__.py' 与实际文件名一致。
- [ok] Anthropic 为唯一网络出口 — 六个脚本中无 urllib/requests/socket/curl/wget 命中;网络仅经 anthropic SDK client.messages.create 或 claude CLI 子进程。SDK 端点在源码中未硬编码,故 external_deps.endpoint 留空(不臆测)。
- [ok] 「subprocess 无 shell 注入」这一说法 — subprocess.run([claude_bin, "--print", "--setting-sources", "", "--strict-mcp-config"], input=prompt, ...) 为列表参数 + stdin,无 shell=True;SECURITY.md 亦声明 'Does not use shell=True or string interpolation in subprocess calls'。
- [ok] 「备份在源目录之外」是否属实(SKILL.md / Purpose 段) — backup_dir_for() 返回 _state_base_dir("backups")/filepath.parent.name,其中 _state_base_dir 为 $XDG_DATA_HOME/caveman-compress 或 ~/.local/share/caveman-compress(Windows 用 %LOCALAPPDATA%),确实不在源文件旁;注释给出理由(skill auto-loader 会二次读入 .original.md)。
- [ok] 敏感文件拒绝覆盖面的自评(第一遍称「覆盖 .env/credentials/密钥」) — 逐条核对 SENSITIVE_BASENAME_REGEX 与 SENSITIVE_PATH_COMPONENTS/SENSITIVE_NAME_TOKENS:.env*、.netrc、credentials*、secret(s)*、password(s)*、id_rsa/dsa/ecdsa/ed25519(.pub)、authorized_keys、known_hosts、*.pem|key|p12|pfx|crt|cer|jks|keystore|asc|gpg;路径组件含 .ssh/.aws/.gnupg/.kube/.docker 与 credential(s)/secret(s);名字 token 含 secret/credential/password/passwd/apikey/accesskey/token/privatekey。属启发式 denylist(可被改名绕过),已在 analysis 注记,未夸大。
- [ok] 固定大小上限 500KB — compress_file 内 MAX_FILE_SIZE = 500_000 且在任何 API 调用之前检查;SECURITY.md 亦声明 'Files larger than 500KB are rejected before any API call is made'。
- [ok] 「校验不过则原文件不动」 — 压缩候选先写 <file>.caveman-staged 并对其跑 validate;只有 is_valid 才 _write_target(filepath, ...),两次重试用尽后 unlink 暂存与备份并打印 'Failed after retries: original left untouched'。
- [ok] SKILL.md 压缩规则 vs 脚本提示词是否一致(有无文档吹牛) — SKILL.md 的 Remove/Preserve/Compress 规则与 build_compress_prompt 的 STRICT RULES 同向(保代码块、保行内代码、保 URL、保标题、保路径命令),脚本还把「不要给整体套一层 ```markdown 围栏」写进提示词,并有 strip_llm_wrapper 兜底剥离。无夸大。
6Verdict & Scenarios
52e12dda463f9c55…