@kulapard/pi-caveman 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,341 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Caveman Memory Compression Orchestrator
4
-
5
- Usage:
6
- python scripts/compress.py <filepath>
7
- """
8
-
9
- import os
10
- import re
11
- import shutil
12
- import subprocess
13
- import sys
14
- from pathlib import Path
15
-
16
- OUTER_FENCE_REGEX = re.compile(
17
- r"\A\s*(`{3,}|~{3,})[^\n]*\n(.*)\n\1\s*\Z", re.DOTALL
18
- )
19
-
20
- # YAML frontmatter: starts at file start with --- on its own line, ends with --- on its own line.
21
- # Captures the entire block (including delimiters and trailing newline) and the body after.
22
- FRONTMATTER_REGEX = re.compile(
23
- r"\A(---\r?\n.*?\r?\n---\r?\n)(.*)", re.DOTALL
24
- )
25
-
26
-
27
- def split_frontmatter(text: str):
28
- """Split YAML frontmatter from body. Returns (frontmatter, body).
29
-
30
- Memory files (and many other markdown docs) start with a YAML frontmatter
31
- block delimited by `---` lines. The compression LLM has a habit of stripping
32
- or rewriting these despite preserve-structure rules in the prompt — so we
33
- surgically remove the frontmatter before compression and prepend it back
34
- verbatim to the output. Files without frontmatter pass through unchanged.
35
- """
36
- m = FRONTMATTER_REGEX.match(text)
37
- if m:
38
- return m.group(1), m.group(2)
39
- return "", text
40
-
41
- # Filenames and paths that almost certainly hold secrets or PII. Compressing
42
- # them ships raw bytes to the Anthropic API — a third-party data boundary that
43
- # developers on sensitive codebases cannot cross. detect.py already skips .env
44
- # by extension, but credentials.md / secrets.txt / ~/.aws/credentials would
45
- # slip through the natural-language filter. This is a hard refuse before read.
46
- SENSITIVE_BASENAME_REGEX = re.compile(
47
- r"(?ix)^("
48
- r"\.env(\..+)?"
49
- r"|\.netrc"
50
- r"|credentials(\..+)?"
51
- r"|secrets?(\..+)?"
52
- r"|passwords?(\..+)?"
53
- r"|id_(rsa|dsa|ecdsa|ed25519)(\.pub)?"
54
- r"|authorized_keys"
55
- r"|known_hosts"
56
- r"|.*\.(pem|key|p12|pfx|crt|cer|jks|keystore|asc|gpg)"
57
- r")$"
58
- )
59
-
60
- SENSITIVE_PATH_COMPONENTS = frozenset({".ssh", ".aws", ".gnupg", ".kube", ".docker"})
61
-
62
- SENSITIVE_NAME_TOKENS = (
63
- "secret", "credential", "password", "passwd",
64
- "apikey", "accesskey", "token", "privatekey",
65
- )
66
-
67
-
68
- def backup_dir_for(filepath: Path) -> Path:
69
- """Resolve the out-of-tree backup directory for a given source file.
70
-
71
- Backups must live OUTSIDE the source directory so skill auto-loaders
72
- (Claude Code rules/, opencode instructions/, etc.) stop re-ingesting the
73
- `.original.md` copies as live files. Base dir is platform-aware:
74
- - Windows: %LOCALAPPDATA%\\caveman-compress\\backups
75
- - else: $XDG_DATA_HOME/caveman-compress/backups if set,
76
- else ~/.local/share/caveman-compress/backups
77
-
78
- The source file's parent-dir name is mirrored under the base to reduce
79
- cross-project collisions (e.g. two `task.md` files in different repos).
80
- """
81
- if os.name == "nt" or sys.platform == "win32":
82
- local_appdata = os.environ.get("LOCALAPPDATA")
83
- base = Path(local_appdata) if local_appdata else Path.home() / "AppData" / "Local"
84
- base = base / "caveman-compress" / "backups"
85
- else:
86
- xdg = os.environ.get("XDG_DATA_HOME")
87
- base = Path(xdg) if xdg else Path.home() / ".local" / "share"
88
- base = base / "caveman-compress" / "backups"
89
- return base / filepath.parent.name
90
-
91
-
92
- def is_sensitive_path(filepath: Path) -> bool:
93
- """Heuristic denylist for files that must never be shipped to a third-party API."""
94
- name = filepath.name
95
- if SENSITIVE_BASENAME_REGEX.match(name):
96
- return True
97
- lowered_parts = {p.lower() for p in filepath.parts}
98
- if lowered_parts & SENSITIVE_PATH_COMPONENTS:
99
- return True
100
- # Normalize separators so "api-key" and "api_key" both match "apikey".
101
- lower = re.sub(r"[_\-\s.]", "", name.lower())
102
- return any(tok in lower for tok in SENSITIVE_NAME_TOKENS)
103
-
104
-
105
- def strip_llm_wrapper(text: str) -> str:
106
- """Strip outer ```markdown ... ``` fence when it wraps the entire output."""
107
- m = OUTER_FENCE_REGEX.match(text)
108
- if m:
109
- return m.group(2)
110
- return text
111
-
112
- from .detect import should_compress
113
- from .validate import validate
114
-
115
- MAX_RETRIES = 2
116
-
117
-
118
- # ---------- Claude Calls ----------
119
-
120
-
121
- def call_claude(prompt: str) -> str:
122
- """Send a prompt to Claude.
123
-
124
- Prefers the Anthropic SDK when ANTHROPIC_API_KEY is set; otherwise falls
125
- back to the ``claude --print`` CLI (which handles desktop auth).
126
-
127
- On Windows the CLI subprocess decoding defaults to the system codepage
128
- (cp1251 / cp1252) and crashes on UTF-8 output — see issue #152. Pinning
129
- ``encoding="utf-8"`` with ``errors="replace"`` matches the CLI's actual
130
- native I/O and prevents the UnicodeDecodeError before validation can
131
- report. Windows users with non-ASCII content can also set
132
- ``ANTHROPIC_API_KEY`` to route through the SDK and skip the subprocess.
133
- """
134
- api_key = os.environ.get("ANTHROPIC_API_KEY")
135
- if api_key:
136
- try:
137
- import anthropic
138
-
139
- client = anthropic.Anthropic(api_key=api_key)
140
- msg = client.messages.create(
141
- model=os.environ.get("CAVEMAN_MODEL", "claude-sonnet-4-5"),
142
- max_tokens=8192,
143
- messages=[{"role": "user", "content": prompt}],
144
- )
145
- return strip_llm_wrapper(msg.content[0].text.strip())
146
- except ImportError:
147
- pass # anthropic not installed, fall back to CLI
148
- # Fallback: use claude CLI (handles desktop auth).
149
- # Resolve binary via shutil.which so Windows .cmd/.bat shims (e.g.
150
- # %APPDATA%\npm\claude.CMD) work without shell=True. On POSIX,
151
- # shutil.which returns the same absolute path as the implicit lookup,
152
- # so this is a no-op there. Falls back to bare "claude" if not found
153
- # on PATH so subprocess raises a clear FileNotFoundError.
154
- claude_bin = shutil.which("claude") or "claude"
155
- try:
156
- result = subprocess.run(
157
- [claude_bin, "--print"],
158
- input=prompt,
159
- text=True,
160
- capture_output=True,
161
- check=True,
162
- encoding="utf-8",
163
- errors="replace",
164
- )
165
- return strip_llm_wrapper(result.stdout.strip())
166
- except subprocess.CalledProcessError as e:
167
- raise RuntimeError(f"Claude call failed:\n{e.stderr}")
168
-
169
-
170
- def build_compress_prompt(original: str) -> str:
171
- return f"""
172
- Compress this markdown into caveman format.
173
-
174
- STRICT RULES:
175
- - Do NOT modify anything inside ``` code blocks
176
- - Do NOT modify anything inside inline backticks
177
- - Preserve ALL URLs exactly
178
- - Preserve ALL headings exactly
179
- - Preserve file paths and commands
180
- - Return ONLY the compressed markdown body — do NOT wrap the entire output in a ```markdown fence or any other fence. Inner code blocks from the original stay as-is; do not add a new outer fence around the whole file.
181
-
182
- Only compress natural language.
183
-
184
- TEXT:
185
- {original}
186
- """
187
-
188
-
189
- def build_fix_prompt(original: str, compressed: str, errors: list[str]) -> str:
190
- errors_str = "\n".join(f"- {e}" for e in errors)
191
- return f"""You are fixing a caveman-compressed markdown file. Specific validation errors were found.
192
-
193
- CRITICAL RULES:
194
- - DO NOT recompress or rephrase the file
195
- - ONLY fix the listed errors — leave everything else exactly as-is
196
- - The ORIGINAL is provided as reference only (to restore missing content)
197
- - Preserve caveman style in all untouched sections
198
-
199
- ERRORS TO FIX:
200
- {errors_str}
201
-
202
- HOW TO FIX:
203
- - Missing URL: find it in ORIGINAL, restore it exactly where it belongs in COMPRESSED
204
- - Code block mismatch: find the exact code block in ORIGINAL, restore it in COMPRESSED
205
- - Heading mismatch: restore the exact heading text from ORIGINAL into COMPRESSED
206
- - Do not touch any section not mentioned in the errors
207
-
208
- ORIGINAL (reference only):
209
- {original}
210
-
211
- COMPRESSED (fix this):
212
- {compressed}
213
-
214
- Return ONLY the fixed compressed file. No explanation.
215
- """
216
-
217
-
218
- # ---------- Core Logic ----------
219
-
220
-
221
- def compress_file(filepath: Path) -> bool:
222
- # Resolve and validate path
223
- filepath = filepath.resolve()
224
- MAX_FILE_SIZE = 500_000 # 500KB
225
- if not filepath.exists():
226
- raise FileNotFoundError(f"File not found: {filepath}")
227
- if filepath.stat().st_size > MAX_FILE_SIZE:
228
- raise ValueError(f"File too large to compress safely (max 500KB): {filepath}")
229
-
230
- # Refuse files that look like they contain secrets or PII. Compressing ships
231
- # the raw bytes to the Anthropic API — a third-party boundary — so we fail
232
- # loudly rather than silently exfiltrate credentials or keys. Override is
233
- # intentional: the user must rename the file if the heuristic is wrong.
234
- if is_sensitive_path(filepath):
235
- raise ValueError(
236
- f"Refusing to compress {filepath}: filename looks sensitive "
237
- "(credentials, keys, secrets, or known private paths). "
238
- "Compression sends file contents to the Anthropic API. "
239
- "Rename the file if this is a false positive."
240
- )
241
-
242
- print(f"Processing: {filepath}")
243
-
244
- if not should_compress(filepath):
245
- print("Skipping (not natural language)")
246
- return False
247
-
248
- original_text = filepath.read_text(errors="ignore")
249
- # Store backup outside the source directory so skill auto-loaders don't
250
- # re-ingest the `.original.md` copy as a live file. Mirror the source's
251
- # parent-dir name + stem under a platform-aware base to reduce collisions.
252
- backup_dir = backup_dir_for(filepath)
253
- backup_dir.mkdir(parents=True, exist_ok=True)
254
- backup_path = backup_dir / (filepath.stem + ".original.md")
255
-
256
- if not original_text.strip():
257
- print("❌ Refusing to compress: file is empty or whitespace-only.")
258
- return False
259
-
260
- # Check if backup already exists to prevent accidental overwriting
261
- if backup_path.exists():
262
- print(f"⚠️ Backup file already exists: {backup_path}")
263
- print("The original backup may contain important content.")
264
- print("Aborting to prevent data loss. Please remove or rename the backup file if you want to proceed.")
265
- return False
266
-
267
- # Split YAML frontmatter off before compression. Claude tends to strip or
268
- # rewrite frontmatter despite preserve-structure rules; we keep it verbatim
269
- # by removing it from the input and re-prepending it to the output.
270
- frontmatter, body = split_frontmatter(original_text)
271
- if frontmatter:
272
- print(f"Detected YAML frontmatter ({len(frontmatter)} chars) — preserving verbatim")
273
-
274
- if not body.strip():
275
- print("❌ Refusing to compress: body is empty after frontmatter removal.")
276
- return False
277
-
278
- # Step 1: Compress (body only, frontmatter excluded)
279
- print("Compressing with Claude...")
280
- compressed_body = call_claude(build_compress_prompt(body))
281
-
282
- if compressed_body is None or not compressed_body.strip():
283
- print("❌ Compression aborted: Claude returned an empty response.")
284
- print(" Original file is untouched (no backup created).")
285
- return False
286
-
287
- # Compare the BODY (not the whole file) — frontmatter is preserved verbatim
288
- # and would never change, so identity must be judged on the compressible part.
289
- if compressed_body.strip() == body.strip():
290
- print("❌ Compression aborted: output is identical to input.")
291
- print(" Likely causes: Claude refused, returned the prompt verbatim, or the file is")
292
- print(" already in caveman form. Original file is untouched (no backup created).")
293
- return False
294
-
295
- # Reassemble: frontmatter (verbatim) + compressed body
296
- compressed = frontmatter + compressed_body
297
-
298
- # Save original as backup, then verify the backup readback before
299
- # touching the input file. If the filesystem dropped bytes (encoding,
300
- # antivirus, disk full), unlink the bad backup and abort instead of
301
- # leaving the user with a corrupt backup + compressed primary.
302
- backup_path.write_text(original_text)
303
- backup_readback = backup_path.read_text(errors="ignore")
304
- if backup_readback != original_text:
305
- print(f"❌ Backup write verification failed: {backup_path}")
306
- print(" In-memory original differs from on-disk backup. Aborting before touching the input file.")
307
- try:
308
- backup_path.unlink()
309
- except OSError:
310
- pass
311
- return False
312
- filepath.write_text(compressed)
313
-
314
- # Step 2: Validate + Retry
315
- for attempt in range(MAX_RETRIES):
316
- print(f"\nValidation attempt {attempt + 1}")
317
-
318
- result = validate(backup_path, filepath)
319
-
320
- if result.is_valid:
321
- print("Validation passed")
322
- break
323
-
324
- print("❌ Validation failed:")
325
- for err in result.errors:
326
- print(f" - {err}")
327
-
328
- if attempt == MAX_RETRIES - 1:
329
- # Restore original on failure
330
- filepath.write_text(original_text)
331
- backup_path.unlink(missing_ok=True)
332
- print("❌ Failed after retries — original restored")
333
- return False
334
-
335
- print("Fixing with Claude...")
336
- compressed = call_claude(
337
- build_fix_prompt(original_text, compressed, result.errors)
338
- )
339
- filepath.write_text(compressed)
340
-
341
- return True
@@ -1,169 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Detect whether a file is natural language (compressible) or code/config (skip)."""
3
-
4
- import json
5
- import re
6
- from pathlib import Path
7
-
8
- # Extensions that are natural language and compressible
9
- COMPRESSIBLE_EXTENSIONS = {".md", ".txt", ".markdown", ".rst", ".typ", ".typst", ".tex"}
10
-
11
- # Extensions that are code/config and should be skipped
12
- SKIP_EXTENSIONS = {
13
- ".py", ".js", ".ts", ".tsx", ".jsx", ".json", ".yaml", ".yml",
14
- ".toml", ".env", ".lock", ".css", ".scss", ".html", ".xml",
15
- ".sql", ".sh", ".bash", ".zsh", ".go", ".rs", ".java", ".c",
16
- ".cpp", ".h", ".hpp", ".rb", ".php", ".swift", ".kt", ".lua",
17
- ".dockerfile", ".makefile", ".csv", ".ini", ".cfg",
18
- }
19
-
20
- # The subset of SKIP_EXTENSIONS that is configuration (not source code). Used to
21
- # decide whether a skipped file reports as "config" vs "code". Must stay a subset
22
- # of SKIP_EXTENSIONS (asserted below) so the two sets cannot silently drift.
23
- CONFIG_EXTENSIONS = {
24
- ".json", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".env",
25
- }
26
- assert CONFIG_EXTENSIONS <= SKIP_EXTENSIONS, (
27
- "CONFIG_EXTENSIONS must be a subset of SKIP_EXTENSIONS: "
28
- f"{CONFIG_EXTENSIONS - SKIP_EXTENSIONS} not in SKIP_EXTENSIONS"
29
- )
30
-
31
- # Real-world extensionless config/build filenames whose classification is NOT
32
- # already covered by the SKIP_EXTENSIONS fallback below. These have an empty
33
- # `Path.suffix`, so the SKIP_EXTENSIONS check never matches them and they would
34
- # otherwise be content-sniffed as natural language and offered up for
35
- # compression to a third-party API. Map the lowercased full filename to its
36
- # classification so a bare `Dockerfile`/`Makefile`/`.gitignore` is handled like
37
- # its dotted-extension cousins would be.
38
- #
39
- # Names that are themselves SKIP_EXTENSIONS entries (e.g. ".env") are
40
- # deliberately omitted here: the `name in SKIP_EXTENSIONS` fallback in
41
- # detect_file_type already classifies them identically, so listing them in both
42
- # places would be redundant and require hand-syncing.
43
- SKIP_FILENAMES = {
44
- "dockerfile": "code",
45
- "makefile": "code",
46
- "gnumakefile": "code",
47
- ".gitignore": "config",
48
- ".gitattributes": "config",
49
- ".dockerignore": "config",
50
- ".editorconfig": "config",
51
- ".npmrc": "config",
52
- ".prettierrc": "config",
53
- ".eslintrc": "config",
54
- ".babelrc": "config",
55
- }
56
-
57
- # Patterns that indicate a line is code
58
- CODE_PATTERNS = [
59
- re.compile(r"^\s*(import |from .+ import |require\(|const |let |var )"),
60
- re.compile(r"^\s*(def |class |function |async function |export )"),
61
- re.compile(r"^\s*(if\s*\(|for\s*\(|while\s*\(|switch\s*\(|try\s*\{)"),
62
- re.compile(r"^\s*[\}\]\);]+\s*$"), # closing braces/brackets
63
- re.compile(r"^\s*@\w+"), # decorators/annotations
64
- re.compile(r'^\s*"[^"]+"\s*:\s*'), # JSON-like key-value
65
- re.compile(r"^\s*\w+\s*=\s*[{\[\(\"']"), # assignment with literal
66
- ]
67
-
68
-
69
- def _is_code_line(line: str) -> bool:
70
- """Check if a line looks like code."""
71
- return any(p.match(line) for p in CODE_PATTERNS)
72
-
73
-
74
- def _is_json_content(text: str) -> bool:
75
- """Check if content is valid JSON."""
76
- try:
77
- json.loads(text)
78
- return True
79
- except (json.JSONDecodeError, ValueError):
80
- return False
81
-
82
-
83
- def _is_yaml_content(lines: list[str]) -> bool:
84
- """Heuristic: check if content looks like YAML."""
85
- yaml_indicators = 0
86
- for line in lines[:30]:
87
- stripped = line.strip()
88
- if stripped.startswith("---"):
89
- yaml_indicators += 1
90
- elif re.match(r"^\w[\w\s]*:\s", stripped):
91
- yaml_indicators += 1
92
- elif stripped.startswith("- ") and ":" in stripped:
93
- yaml_indicators += 1
94
- # If most non-empty lines look like YAML
95
- non_empty = sum(1 for line in lines[:30] if line.strip())
96
- return non_empty > 0 and yaml_indicators / non_empty > 0.6
97
-
98
-
99
- def detect_file_type(filepath: Path) -> str:
100
- """Classify a file as 'natural_language', 'code', 'config', or 'unknown'.
101
-
102
- Returns:
103
- One of: 'natural_language', 'code', 'config', 'unknown'
104
- """
105
- ext = filepath.suffix.lower()
106
-
107
- # Extension-based classification
108
- if ext in COMPRESSIBLE_EXTENSIONS:
109
- return "natural_language"
110
- if ext in SKIP_EXTENSIONS:
111
- return "config" if ext in CONFIG_EXTENSIONS else "code"
112
-
113
- # Extensionless files (like CLAUDE.md, TODO) — check content.
114
- if not ext:
115
- # Leading-dot / build files (".env", "Dockerfile", "Makefile",
116
- # ".gitignore") have an empty suffix, so the SKIP_EXTENSIONS check above
117
- # never matched them and they would be content-sniffed as natural
118
- # language. Classify them by full filename first so they are never
119
- # offered up for compression to a third-party API.
120
- name = filepath.name.lower()
121
- if name in SKIP_FILENAMES:
122
- return SKIP_FILENAMES[name]
123
- if name in SKIP_EXTENSIONS:
124
- return "config" if name in CONFIG_EXTENSIONS else "code"
125
-
126
- try:
127
- text = filepath.read_text(errors="ignore")
128
- except (OSError, PermissionError):
129
- return "unknown"
130
-
131
- lines = text.splitlines()[:50]
132
-
133
- if _is_json_content(text[:10000]):
134
- return "config"
135
- if _is_yaml_content(lines):
136
- return "config"
137
-
138
- code_lines = sum(1 for line in lines if line.strip() and _is_code_line(line))
139
- non_empty = sum(1 for line in lines if line.strip())
140
- if non_empty > 0 and code_lines / non_empty > 0.4:
141
- return "code"
142
-
143
- return "natural_language"
144
-
145
- return "unknown"
146
-
147
-
148
- def should_compress(filepath: Path) -> bool:
149
- """Return True if the file is natural language and should be compressed."""
150
- if not filepath.is_file():
151
- return False
152
- # Skip backup files
153
- if filepath.name.endswith(".original.md"):
154
- return False
155
- return detect_file_type(filepath) == "natural_language"
156
-
157
-
158
- if __name__ == "__main__":
159
- import sys
160
-
161
- if len(sys.argv) < 2:
162
- print("Usage: python detect.py <file1> [file2] ...")
163
- sys.exit(1)
164
-
165
- for path_str in sys.argv[1:]:
166
- p = Path(path_str).resolve()
167
- file_type = detect_file_type(p)
168
- compress = should_compress(p)
169
- print(f" {p.name:30s} type={file_type:20s} compress={compress}")