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