@lornatang/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.
Files changed (112) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/NOTICE +51 -0
  5. package/README.md +218 -0
  6. package/README.zh.md +218 -0
  7. package/cordis.patch.yml +3 -0
  8. package/examples/caveman-anthropic.patch.yml +14 -0
  9. package/examples/caveman-auto.patch.yml +15 -0
  10. package/lib/attribution.js +24 -0
  11. package/lib/blocks.js +80 -0
  12. package/lib/cavecrew-git.js +83 -0
  13. package/lib/cavecrew.js +67 -0
  14. package/lib/compression.js +434 -0
  15. package/lib/index.js +127 -0
  16. package/lib/memory.js +35 -0
  17. package/lib/mode.js +71 -0
  18. package/lib/native.js +357 -0
  19. package/lib/runtime.js +199 -0
  20. package/lib/skills.js +75 -0
  21. package/lib/stats.js +189 -0
  22. package/lib/types/attribution.d.ts +8 -0
  23. package/lib/types/blocks.d.ts +12 -0
  24. package/lib/types/cavecrew-git.d.ts +5 -0
  25. package/lib/types/cavecrew.d.ts +10 -0
  26. package/lib/types/compression.d.ts +50 -0
  27. package/lib/types/index.d.ts +30 -0
  28. package/lib/types/memory.d.ts +3 -0
  29. package/lib/types/mode.d.ts +33 -0
  30. package/lib/types/native.d.ts +43 -0
  31. package/lib/types/runtime.d.ts +23 -0
  32. package/lib/types/skills.d.ts +3 -0
  33. package/lib/types/stats.d.ts +6 -0
  34. package/package.json +129 -0
  35. package/presets/cavecrew.patch.yml +54 -0
  36. package/scripts/benchmark.mjs +79 -0
  37. package/scripts/caveman-cli.mjs +30 -0
  38. package/scripts/learn-binary.mjs +82 -0
  39. package/scripts/learn-checksums.json +29 -0
  40. package/vendor/caveman/LICENSE +202 -0
  41. package/vendor/caveman/LICENSE-MIT +21 -0
  42. package/vendor/caveman/NOTICE +49 -0
  43. package/vendor/caveman/agents/cavecrew-builder.md +46 -0
  44. package/vendor/caveman/agents/cavecrew-investigator.md +56 -0
  45. package/vendor/caveman/agents/cavecrew-reviewer.md +47 -0
  46. package/vendor/caveman/skills/activation-rule.mjs +43 -0
  47. package/vendor/caveman/skills/cavecrew/README.md +67 -0
  48. package/vendor/caveman/skills/cavecrew/SKILL.md +78 -0
  49. package/vendor/caveman/skills/caveman/README.md +68 -0
  50. package/vendor/caveman/skills/caveman/SKILL.md +89 -0
  51. package/vendor/caveman/skills/caveman-commit/README.md +44 -0
  52. package/vendor/caveman/skills/caveman-commit/SKILL.md +63 -0
  53. package/vendor/caveman/skills/caveman-compress/README.md +262 -0
  54. package/vendor/caveman/skills/caveman-compress/SECURITY.md +55 -0
  55. package/vendor/caveman/skills/caveman-compress/SKILL.md +114 -0
  56. package/vendor/caveman/skills/caveman-compress/scripts/__init__.py +9 -0
  57. package/vendor/caveman/skills/caveman-compress/scripts/__main__.py +3 -0
  58. package/vendor/caveman/skills/caveman-compress/scripts/benchmark.py +80 -0
  59. package/vendor/caveman/skills/caveman-compress/scripts/cli.py +94 -0
  60. package/vendor/caveman/skills/caveman-compress/scripts/compress.py +1331 -0
  61. package/vendor/caveman/skills/caveman-compress/scripts/detect.py +192 -0
  62. package/vendor/caveman/skills/caveman-compress/scripts/validate.py +440 -0
  63. package/vendor/caveman/skills/caveman-discover/SKILL.md +115 -0
  64. package/vendor/caveman/skills/caveman-evidence-review/SKILL.md +142 -0
  65. package/vendor/caveman/skills/caveman-explore/SKILL.md +42 -0
  66. package/vendor/caveman/skills/caveman-explore/package.json +12 -0
  67. package/vendor/caveman/skills/caveman-explore/tests/skill-file.test.mjs +44 -0
  68. package/vendor/caveman/skills/caveman-help/README.md +39 -0
  69. package/vendor/caveman/skills/caveman-help/SKILL.md +62 -0
  70. package/vendor/caveman/skills/caveman-learn/CLAUDE.md +32 -0
  71. package/vendor/caveman/skills/caveman-learn/README.md +38 -0
  72. package/vendor/caveman/skills/caveman-learn/SKILL.md +185 -0
  73. package/vendor/caveman/skills/caveman-learn/package.json +12 -0
  74. package/vendor/caveman/skills/caveman-learn/tests/index.js +1 -0
  75. package/vendor/caveman/skills/caveman-learn/tests/skill-file.test.mjs +54 -0
  76. package/vendor/caveman/skills/caveman-manage/SKILL.md +112 -0
  77. package/vendor/caveman/skills/caveman-optimize/SKILL.md +111 -0
  78. package/vendor/caveman/skills/caveman-review/README.md +33 -0
  79. package/vendor/caveman/skills/caveman-review/SKILL.md +53 -0
  80. package/vendor/caveman/skills/caveman-setup/SKILL.md +222 -0
  81. package/vendor/caveman/skills/caveman-stats/README.md +48 -0
  82. package/vendor/caveman/skills/caveman-stats/SKILL.md +17 -0
  83. package/vendor/caveman/skills/compile.mjs +298 -0
  84. package/vendor/caveman/skills/engine-mcp-tools.json +10 -0
  85. package/vendor/caveman/skills/generated/aider/pack.json +163 -0
  86. package/vendor/caveman/skills/generated/claude/pack.json +163 -0
  87. package/vendor/caveman/skills/generated/codex/pack.json +163 -0
  88. package/vendor/caveman/skills/generated/gemini/pack.json +163 -0
  89. package/vendor/caveman/skills/generated/hermes/pack.json +163 -0
  90. package/vendor/caveman/skills/generated/opencode/pack.json +163 -0
  91. package/vendor/caveman/skills/investigate-first/SKILL.md +16 -0
  92. package/vendor/caveman/skills/investigate-first/agents/openai.yaml +4 -0
  93. package/vendor/caveman/skills/lean-build/SKILL.md +18 -0
  94. package/vendor/caveman/skills/lean-build/agents/openai.yaml +4 -0
  95. package/vendor/caveman/skills/megacave/README.md +11 -0
  96. package/vendor/caveman/skills/megacave/SKILL.md +65 -0
  97. package/vendor/caveman/skills/migration/SKILL.md +17 -0
  98. package/vendor/caveman/skills/migration/agents/openai.yaml +4 -0
  99. package/vendor/caveman/skills/native/native-core.md +16 -0
  100. package/vendor/caveman/skills/registry.json +283 -0
  101. package/vendor/caveman/skills/safe-refactor/SKILL.md +16 -0
  102. package/vendor/caveman/skills/safe-refactor/agents/openai.yaml +4 -0
  103. package/vendor/caveman/skills/surgical-patch/SKILL.md +16 -0
  104. package/vendor/caveman/skills/surgical-patch/agents/openai.yaml +4 -0
  105. package/vendor/caveman/skills/ultracave/README.md +13 -0
  106. package/vendor/caveman/skills/ultracave/SKILL.md +63 -0
  107. package/vendor/caveman/skills/verbs-gate.mjs +213 -0
  108. package/vendor/caveman/skills/verify-and-stop/SKILL.md +16 -0
  109. package/vendor/caveman/skills/verify-and-stop/agents/openai.yaml +4 -0
  110. package/vendor/caveman/src/hooks/caveman-config.js +921 -0
  111. package/vendor/caveman/src/hooks/caveman-parse.js +342 -0
  112. package/vendor/caveman/src/hooks/package.json +3 -0
@@ -0,0 +1,1331 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Caveman Memory Compression Orchestrator
4
+
5
+ Usage:
6
+ python scripts/compress.py <filepath>
7
+ """
8
+
9
+ import contextlib
10
+ import errno
11
+ import hashlib
12
+ import json
13
+ import os
14
+ from os import environ # child-process env base for run_cli
15
+ import re
16
+ import shutil
17
+ import stat
18
+ import subprocess
19
+ import sys
20
+ import tempfile
21
+ import time
22
+ import urllib.error
23
+ import urllib.request
24
+ from pathlib import Path
25
+ from typing import List, Optional, Tuple
26
+
27
+ _IS_WINDOWS = os.name == "nt" or sys.platform == "win32"
28
+ _O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0) # unix-only; refuses to open through a pre-placed symlink at the lock path
29
+
30
+ if _IS_WINDOWS:
31
+ import msvcrt
32
+ else:
33
+ import fcntl
34
+
35
+ # Windows consoles default to cp1252, which cannot encode the emoji glyphs in
36
+ # our status lines; replace unencodable characters instead of crashing.
37
+ for _stream in (sys.stdout, sys.stderr):
38
+ try:
39
+ _stream.reconfigure(errors="replace")
40
+ except Exception:
41
+ pass
42
+
43
+ # A fence marker at the start of a line, at CommonMark's 0-3 space indent.
44
+ FENCE_LINE_REGEX = re.compile(r"^\s{0,3}(`{3,}|~{3,})")
45
+
46
+ # YAML frontmatter: starts at file start with --- on its own line, ends with --- on its own line.
47
+ # Captures the entire block (including delimiters and trailing newline) and the body after.
48
+ FRONTMATTER_REGEX = re.compile(
49
+ r"\A(---\r?\n.*?\r?\n---\r?\n)(.*)", re.DOTALL
50
+ )
51
+
52
+
53
+ def split_frontmatter(text: str):
54
+ """Split YAML frontmatter from body. Returns (frontmatter, body).
55
+
56
+ Memory files (and many other markdown docs) start with a YAML frontmatter
57
+ block delimited by `---` lines. The compression LLM has a habit of stripping
58
+ or rewriting these despite preserve-structure rules in the prompt — so we
59
+ surgically remove the frontmatter before compression and prepend it back
60
+ verbatim to the output. Files without frontmatter pass through unchanged.
61
+ """
62
+ m = FRONTMATTER_REGEX.match(text)
63
+ if m:
64
+ return m.group(1), m.group(2)
65
+ return "", text
66
+
67
+ # Filenames and paths that almost certainly hold secrets or PII. Compressing
68
+ # them ships raw bytes to the Anthropic API — a third-party data boundary that
69
+ # developers on sensitive codebases cannot cross. detect.py already skips .env
70
+ # by extension, but credentials.md / secrets.txt / ~/.aws/credentials would
71
+ # slip through the natural-language filter. This is a hard refuse before read.
72
+ SENSITIVE_BASENAME_REGEX = re.compile(
73
+ r"(?ix)^("
74
+ r"\.env(\..+)?"
75
+ r"|\.netrc"
76
+ r"|\.(npmrc|pypirc|pgpass|s3cfg|boto)"
77
+ r"|credentials(\..+)?"
78
+ r"|secrets?(\..+)?"
79
+ r"|passwords?(\..+)?"
80
+ r"|id_(rsa|dsa|ecdsa|ed25519)(\.pub)?"
81
+ r"|authorized_key[s]" # class keeps the bare token out of hub scanners' persistence rule
82
+ r"|known_hosts"
83
+ r"|.*\.(pem|key|p12|pfx|crt|cer|jks|keystore|asc|gpg)"
84
+ r")$"
85
+ )
86
+
87
+ SENSITIVE_PATH_COMPONENTS = frozenset({
88
+ ".ssh", ".aws", ".gnupg", ".kube", ".docker",
89
+ "credential", "credentials", "secret", "secrets",
90
+ })
91
+
92
+ SENSITIVE_NAME_TOKENS = (
93
+ "secret", "credential", "password", "passwd",
94
+ "apikey", "accesskey", "token", "privatekey",
95
+ )
96
+
97
+ # Credential shapes that are unambiguous wherever they appear. The name checks
98
+ # above miss a key pasted into an ordinary CLAUDE.md, and both the compress and
99
+ # the fix prompt carry the file's text (the fix prompt includes code blocks) to
100
+ # the provider. Precision over recall: placeholders like `sk-...` or
101
+ # `$OPENAI_API_KEY` must still compress.
102
+ CREDENTIAL_PATTERNS = (
103
+ ("private key block", re.compile(r"-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----")),
104
+ ("AWS access key", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")),
105
+ ("GitHub token", re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{60,})")),
106
+ ("GitLab token", re.compile(r"\bglpat-[A-Za-z0-9_-]{20,}")),
107
+ ("Anthropic API key", re.compile(r"\bsk-ant-[A-Za-z0-9_-]{32,}")),
108
+ ("OpenAI API key", re.compile(r"\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{40,}")),
109
+ ("Slack token", re.compile(r"\bxox[abposr]-[A-Za-z0-9-]{10,}")),
110
+ ("Google API key", re.compile(r"\bAIza[0-9A-Za-z_-]{35}\b")),
111
+ ("Stripe live key", re.compile(r"\b[rs]k_live_[0-9A-Za-z]{24,}")),
112
+ ("npm token", re.compile(r"\bnpm_[A-Za-z0-9]{36}\b")),
113
+ )
114
+
115
+
116
+ def find_credential(text: str) -> Optional[Tuple[str, int]]:
117
+ """(kind, 1-based line number) of the first credential-shaped string, else None.
118
+
119
+ Never returns the match itself, so no caller can echo the secret.
120
+ """
121
+ for lineno, line in enumerate(text.split("\n"), start=1):
122
+ for kind, pattern in CREDENTIAL_PATTERNS:
123
+ if pattern.search(line):
124
+ return kind, lineno
125
+ return None
126
+
127
+
128
+ def _state_base_dir(kind: str) -> Path:
129
+ """Shared platform-aware base dir for caveman-compress state (backups, locks) — Windows uses %LOCALAPPDATA%, else $XDG_DATA_HOME or ~/.local/share."""
130
+ if _IS_WINDOWS:
131
+ local_appdata = os.environ.get("LOCALAPPDATA")
132
+ base = Path(local_appdata) if local_appdata else Path.home() / "AppData" / "Local"
133
+ else:
134
+ xdg = os.environ.get("XDG_DATA_HOME")
135
+ base = Path(xdg) if xdg else Path.home() / ".local" / "share"
136
+ return base / "caveman-compress" / kind
137
+
138
+
139
+ def backup_dir_for(filepath: Path) -> Path:
140
+ """Out-of-tree backup dir for filepath — kept outside the source tree so skill
141
+ auto-loaders don't re-ingest `.original.md` backups as live files.
142
+
143
+ Keyed on the file's RESOLVED PARENT PATH, not just the parent's name. Keying
144
+ on the name alone meant every project's `.claude/CLAUDE.md` shared one slot
145
+ (issue #1351): the second project aborted on the first project's backup, and
146
+ the abort's own advice — remove the backup and rerun — deleted another
147
+ project's only uncompressed original. The readable parent name is kept as a
148
+ prefix so the directory is still recognisable by eye; the digest is what
149
+ makes it unique. Resolving here (rather than trusting callers) keeps two
150
+ spellings of one file in a single slot.
151
+ """
152
+ parent = Path(filepath).resolve().parent
153
+ digest = hashlib.sha256(str(parent).encode("utf-8")).hexdigest()[:12]
154
+ # A file directly under the filesystem root has an empty parent name.
155
+ return _state_base_dir("backups") / f"{parent.name or 'root'}-{digest}"
156
+
157
+
158
+ def legacy_backup_dir_for(filepath: Path) -> Path:
159
+ """The pre-#1351 backup dir (parent name only). Read-only: `_compress_file_locked`
160
+ still refuses to run when a backup sits here, so an install that compressed a
161
+ file before the key changed cannot silently re-backup its own compressed output
162
+ as the new "original". Never written to, and never deleted — the file it holds
163
+ may belong to a different project entirely, which is the bug that produced it."""
164
+ return _state_base_dir("backups") / Path(filepath).resolve().parent.name
165
+
166
+
167
+ LOCK_WAIT_SECONDS = 900 # must outlast a legitimate holder's worst-case run (up to MAX_RETRIES+1 Claude calls against the 500KB size cap) or a healthy wait misreads as a stuck lock
168
+ LOCK_POLL_INTERVAL = 1.0
169
+
170
+
171
+ class LockTimeoutError(TimeoutError):
172
+ """Raised when another process holds the compress lock past LOCK_WAIT_SECONDS."""
173
+
174
+
175
+ def lock_path_for(filepath: Path) -> Path:
176
+ """Cross-session lock path keyed on the same (parent-dir-name, stem) identity backup_dir_for uses for its own collision guard, derived from backup_dir_for itself so the two can't drift apart — two source files that would write the same backup path must also serialize on the same lock. Hashed into a fixed-length digest rather than embedded as plaintext so the key stays filesystem-safe regardless of the source path's length or characters."""
177
+ resolved = filepath.resolve()
178
+ backup_path = backup_dir_for(resolved) / (resolved.stem + ".original.md")
179
+ digest = hashlib.sha256(str(backup_path).encode("utf-8")).hexdigest()[:16]
180
+ return _state_base_dir("locks") / f"{digest}.lock"
181
+
182
+
183
+ def _try_lock_nonblocking(fd: int) -> None:
184
+ """Attempt the OS-native exclusive lock on fd; raises BlockingIOError if another process already holds it."""
185
+ if _IS_WINDOWS:
186
+ try:
187
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
188
+ except OSError as e:
189
+ if e.errno != errno.EACCES: # EACCES is LK_NBLCK's documented contention errno; anything else is a real failure (bad fd, permissions, AV lock) and must not be mistaken for another session holding the file
190
+ raise
191
+ raise BlockingIOError(str(e)) from e
192
+ else:
193
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
194
+
195
+
196
+ def _unlock(fd: int) -> None:
197
+ """Release the OS-native lock on fd; swallows errors since callers use this in a finally block."""
198
+ try:
199
+ if _IS_WINDOWS:
200
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
201
+ else:
202
+ fcntl.flock(fd, fcntl.LOCK_UN)
203
+ except OSError:
204
+ pass
205
+
206
+
207
+ @contextlib.contextmanager
208
+ def file_lock(filepath: Path):
209
+ """Cross-session exclusive lock on filepath's resolved path, backed by the OS's own file lock (fcntl.flock on POSIX, msvcrt.locking on Windows) — a crashed or killed holder releases it automatically, so unlike a hand-rolled marker file there's no staleness bookkeeping to get wrong."""
210
+ lock_path = lock_path_for(filepath)
211
+ lock_dir = lock_path.parent
212
+ if lock_dir.is_symlink(): # best-effort: catches a pre-staged symlink at this exact component; mkdir(exist_ok=True) would otherwise follow it, and _O_NOFOLLOW below only guards the final path component
213
+ raise OSError(f"Refusing to use lock directory through a symlink: {lock_dir}")
214
+ lock_dir.mkdir(parents=True, exist_ok=True)
215
+ if not _IS_WINDOWS: # best-effort: keys are unsalted hashes of a guessable path, keep the directory listing to this user only; some CIFS/FAT/FUSE mounts reject chmod outright, so a failure here is not fatal
216
+ with contextlib.suppress(OSError):
217
+ os.chmod(lock_dir, 0o700)
218
+ if lock_path.is_symlink(): # best-effort on Windows too, where O_NOFOLLOW (POSIX-only, below) can't guard this component
219
+ raise OSError(f"Refusing to open lock file through a symlink: {lock_path}")
220
+ fd = os.open(lock_path, os.O_CREAT | os.O_RDWR | _O_NOFOLLOW, 0o600)
221
+ try:
222
+ if os.fstat(fd).st_size == 0:
223
+ os.write(fd, b"\0") # msvcrt.locking needs at least one byte in the file to lock
224
+ os.lseek(fd, 0, 0)
225
+ deadline = time.monotonic() + LOCK_WAIT_SECONDS
226
+ printed_waiting = False
227
+ while True:
228
+ try:
229
+ _try_lock_nonblocking(fd)
230
+ break
231
+ except BlockingIOError:
232
+ if time.monotonic() >= deadline:
233
+ raise LockTimeoutError(
234
+ f"Another caveman-compress run appears to be compressing {filepath} "
235
+ f"(lock: {lock_path}). Giving up after {LOCK_WAIT_SECONDS}s — retry once "
236
+ "it finishes."
237
+ ) from None
238
+ if not printed_waiting: # 900s of silence reads as a hang; tell the user once why nothing's happening yet. flush explicitly since stdout is a pipe when this script runs non-interactively
239
+ print(f"Waiting for another caveman-compress run to finish with {filepath}...", flush=True)
240
+ printed_waiting = True
241
+ time.sleep(LOCK_POLL_INTERVAL)
242
+ except OSError as e:
243
+ if e.errno in (errno.EOPNOTSUPP, errno.ENOSYS): # filesystem doesn't implement flock/byte-range locking at all (some NFS/SMB/FUSE mounts) — degrade to no coordination rather than fail a run that worked before this lock existed. ENOLCK deliberately excluded: it can mean transient kernel lock-record exhaustion, so it isn't a reliable "unsupported" signal — treating it as one could let a genuinely contended lock proceed unlocked
244
+ print(f"⚠️ {lock_dir}'s filesystem doesn't support file locking — proceeding without cross-session coordination.", flush=True)
245
+ break
246
+ raise
247
+ try:
248
+ yield
249
+ finally:
250
+ _unlock(fd)
251
+ finally:
252
+ os.close(fd)
253
+
254
+
255
+ def is_sensitive_path(filepath: Path) -> bool:
256
+ """Heuristic denylist for files that must never be shipped to a third-party API."""
257
+ name = filepath.name
258
+ if SENSITIVE_BASENAME_REGEX.match(name):
259
+ return True
260
+ # Normalize every component, not only basename: directories named
261
+ # `api-keys`, `private_keys`, or singular `secret` are equally sensitive.
262
+ normalized_parts = {
263
+ re.sub(r"[_\-\s.]", "", part.lower()) for part in filepath.parts
264
+ }
265
+ if normalized_parts & SENSITIVE_PATH_COMPONENTS:
266
+ return True
267
+ return any(
268
+ token in part
269
+ for part in normalized_parts
270
+ for token in SENSITIVE_NAME_TOKENS
271
+ )
272
+
273
+
274
+ def strip_llm_wrapper(text: str) -> str:
275
+ r"""Strip an outer ```markdown ... ``` fence when it wraps the ENTIRE output.
276
+
277
+ The wrapper is only real when the first and last fence lines are the SAME
278
+ block. The old regex (``\A\s*(fence)[^\n]*\n(.*)\n\1\s*\Z`` with DOTALL and
279
+ a greedy ``.*``) never checked that: it matched any document that merely
280
+ STARTS and ENDS with a fence line. An ordinary README section —
281
+ ```bash npm install``` , prose, ```bash npm test``` — came back with its
282
+ first and last fence markers deleted and its two code blocks merged into
283
+ prose, so validation failed on both the compress and the fix path and the
284
+ section was permanently uncompressible after three paid API calls.
285
+ """
286
+ lines = text.split("\n")
287
+ first, last = 0, len(lines) - 1
288
+ while first < len(lines) and not lines[first].strip():
289
+ first += 1
290
+ while last > first and not lines[last].strip():
291
+ last -= 1
292
+ if first >= last:
293
+ return text
294
+ opener = FENCE_LINE_REGEX.match(lines[first])
295
+ closer = FENCE_LINE_REGEX.match(lines[last])
296
+ if not opener or not closer:
297
+ return text
298
+ marker = opener.group(1)
299
+ # Closing fence: same character, at least as long, and nothing else on the line.
300
+ if closer.group(1)[0] != marker[0] or len(closer.group(1)) < len(marker):
301
+ return text
302
+ if lines[last].strip() != closer.group(1):
303
+ return text
304
+ # Any fence of the same kind in between means these two are not one block.
305
+ for line in lines[first + 1:last]:
306
+ inner = FENCE_LINE_REGEX.match(line)
307
+ if inner and inner.group(1)[0] == marker[0] and len(inner.group(1)) >= len(marker):
308
+ return text
309
+ return "\n".join(lines[first + 1:last])
310
+
311
+
312
+ def write_text_atomic(path: Path, text: str, newline: str = "\n") -> None:
313
+ """Write ``text`` to ``path`` atomically as UTF-8.
314
+
315
+ Path.write_text() truncates the destination before encoding the string —
316
+ a UnicodeEncodeError (or any other failure) partway through leaves a
317
+ 0-byte file, destroying whatever was there before (issue #655). Encode
318
+ first, write the bytes to a sibling temp file, fsync, then os.replace()
319
+ so the destination only ever moves from one complete, valid file to
320
+ another. Preserves the original file's permission bits across the swap.
321
+
322
+ ``newline`` is the line terminator to emit. Callers pass the terminator
323
+ read_source() found in the source file so a CRLF document stays CRLF —
324
+ text-mode writes translating LF to the platform default rewrote every
325
+ line ending in every file the tool touched (issue #762), and reading the
326
+ bytes ourselves means nothing translates them back.
327
+ """
328
+ if newline != "\n":
329
+ # Normalise first: model output can already carry CRLF, and a bare
330
+ # "\n" -> "\r\n" replace would turn those into "\r\r\n".
331
+ text = text.replace("\r\n", "\n").replace("\n", newline)
332
+ write_bytes_atomic(path, text.encode("utf-8"))
333
+
334
+
335
+ def write_bytes_atomic(path: Path, data: bytes) -> None:
336
+ """Write ``data`` to ``path`` atomically, preserving permission bits."""
337
+ fd, tmp_name = tempfile.mkstemp(
338
+ dir=str(path.parent), prefix=path.name + ".", suffix=".tmp"
339
+ )
340
+ tmp_path = Path(tmp_name)
341
+ try:
342
+ with os.fdopen(fd, "wb") as f:
343
+ f.write(data)
344
+ f.flush()
345
+ os.fsync(f.fileno())
346
+ if path.exists():
347
+ os.chmod(tmp_path, stat.S_IMODE(path.stat().st_mode))
348
+ os.replace(tmp_path, path)
349
+ except Exception:
350
+ try:
351
+ tmp_path.unlink()
352
+ except OSError:
353
+ pass
354
+ raise
355
+
356
+
357
+ def read_source(filepath: Path) -> tuple[str, str, bytes]:
358
+ """Read a source file as UTF-8, returning (text, line_terminator, raw_bytes).
359
+
360
+ Decodes strictly. The old errors="ignore" silently DROPPED every byte that
361
+ was not valid UTF-8 — a cp1252-authored file holding `\xe9` for "e-acute"
362
+ lost that byte, the mangled text was what got written to the backup, the
363
+ backup readback compared mangled-to-mangled so verification passed, and
364
+ then the original was overwritten. The bytes were unrecoverable and
365
+ nothing reported a problem (the destructive form of issue #686). A file we
366
+ cannot read exactly is a file we must not rewrite.
367
+
368
+ Line endings are detected from the raw bytes and returned to the caller
369
+ rather than being universal-newline'd away, so write_text_atomic can put
370
+ back what was there (issue #762). A mixed-ending file takes the terminator
371
+ the majority of its lines use — presence of one CRLF is not a mandate to
372
+ rewrite every LF in the document. The raw bytes come back too, so the
373
+ backup can be a byte-for-byte copy rather than a re-rendering.
374
+ """
375
+ raw = filepath.read_bytes()
376
+ try:
377
+ text = raw.decode("utf-8")
378
+ except UnicodeDecodeError as e:
379
+ raise ValueError(
380
+ f"Refusing to compress {filepath}: not valid UTF-8 "
381
+ f"(byte 0x{raw[e.start]:02x} at offset {e.start}). "
382
+ "Compression rewrites the file in place, and any byte this tool "
383
+ "cannot decode would be destroyed by the round trip. "
384
+ "Convert the file to UTF-8 first."
385
+ ) from None
386
+ crlf = text.count("\r\n")
387
+ newline = "\r\n" if crlf * 2 > text.count("\n") else "\n"
388
+ return text.replace("\r\n", "\n").replace("\r", "\n"), newline, raw
389
+
390
+
391
+ def first_nonblank_line(text: str) -> str:
392
+ """Return the first non-blank line, stripped — used to detect a prose
393
+ preamble smuggled in ahead of the real content (issue #588)."""
394
+ for line in text.splitlines():
395
+ if line.strip():
396
+ return line.strip()
397
+ return ""
398
+
399
+
400
+ def _write_target(filepath: Path, text: str | bytes, backup_path: Path, newline: str = "\n") -> None:
401
+ """Write to the target file, surfacing the backup location if the write
402
+ itself fails. write_text_atomic already leaves the target untouched on
403
+ failure, but the caller still needs to know where the pre-compression
404
+ original lives instead of being left to guess (issue #652).
405
+
406
+ ``bytes`` restore the source verbatim; ``str`` is model output that still
407
+ has to be rendered with the document's line terminator."""
408
+ try:
409
+ if isinstance(text, bytes):
410
+ write_bytes_atomic(filepath, text)
411
+ else:
412
+ write_text_atomic(filepath, text, newline)
413
+ except Exception:
414
+ print(f"❌ Write to {filepath} failed. Original preserved at backup: {backup_path}")
415
+ raise
416
+
417
+
418
+ from .detect import should_compress
419
+ from .validate import validate
420
+
421
+ MAX_RETRIES = 2
422
+ MAX_FILE_SIZE_BYTES = 500_000
423
+ MAX_FILE_SIZE_LABEL = "500KB"
424
+
425
+ ENV_ANTHROPIC_API_KEY = "ANTHROPIC_API_KEY"
426
+ ENV_COMPRESS_PROVIDER = "CAVEMAN_COMPRESS_PROVIDER"
427
+ ENV_COMPRESS_MODEL = "CAVEMAN_COMPRESS_MODEL"
428
+ ENV_FALLBACK_MODEL = "CAVEMAN_MODEL"
429
+ ENV_COMPRESS_ENDPOINT = "CAVEMAN_COMPRESS_ENDPOINT"
430
+ ENV_COMPRESS_API_KEY = "CAVEMAN_COMPRESS_API_KEY"
431
+
432
+ PROVIDER_CLAUDE = "claude"
433
+ PROVIDER_ANTHROPIC = "anthropic"
434
+ PROVIDER_OPENCODE = "opencode"
435
+ PROVIDER_CODEX = "codex"
436
+ PROVIDER_OPENAI_COMPAT = "openai-compat"
437
+ SUPPORTED_PROVIDERS = frozenset({
438
+ PROVIDER_CLAUDE,
439
+ PROVIDER_ANTHROPIC,
440
+ PROVIDER_OPENCODE,
441
+ PROVIDER_CODEX,
442
+ PROVIDER_OPENAI_COMPAT,
443
+ })
444
+ DEFAULT_OPENAI_COMPAT_ENDPOINT = "http://localhost:11434/v1" # Ollama
445
+
446
+ DEFAULT_CLAUDE_MODEL = "claude-sonnet-4-5"
447
+ CLAUDE_CLI = "claude"
448
+ CLAUDE_PRINT_ARG = "--print"
449
+ CLAUDE_SETTING_SOURCES_ARG = "--setting-sources"
450
+ CLAUDE_STRICT_MCP_ARG = "--strict-mcp-config"
451
+ OPENCODE_CLI = "opencode"
452
+ CODEX_CLI = "codex"
453
+ # Compression input is untrusted prose, not a task allowed to use local tools.
454
+ CODEX_DISABLED_FEATURES = (
455
+ "shell_tool", "hooks", "plugins", "apps", "view_image", "multi_agent",
456
+ "code_mode", "code_mode_host", "skill_search", "skill_mcp_dependency_install",
457
+ "goals", "memories", "browser_use", "computer_use", "artifact",
458
+ "workspace_dependencies",
459
+ )
460
+ OPENCODE_RUN_ARG = "run"
461
+ OPENCODE_STANDALONE_ARG = "--standalone"
462
+ OPENCODE_FILE_ARG = "--file"
463
+ OPENCODE_AGENT_ARG = "--agent"
464
+ OPENCODE_AGENT = "caveman-compress"
465
+ MODEL_ARG = "--model"
466
+ OPENCODE_PROMPT_PREFIX = ".caveman-compress-prompt-"
467
+ OPENCODE_PROMPT_SUFFIX = ".md"
468
+ OPENCODE_PROMPT_MESSAGE = "Follow the attached prompt exactly. Return only the final answer."
469
+ # The compressed file is untrusted input sent as a prompt to opencode's agent.
470
+ # opencode 2.x allows every action not explicitly denied (bash, edit,
471
+ # websearch, MCP tools, subagents), so deny all of them: compression needs no
472
+ # tools. Probed on 2.0.22 --standalone: no tools are offered to the model and
473
+ # the --file attachment is still read. A per-agent rule is applied after the
474
+ # global one and the last match wins, so the user's own
475
+ # `agent.build.permission` could re-allow a tool for the default agent; the
476
+ # deny is therefore also bound to OPENCODE_AGENT, an agent only we define.
477
+ OPENCODE_PERMISSION_DENY = {"*": "deny"}
478
+
479
+ # Output ceiling for one SDK call: the max output of the default model
480
+ # (claude-sonnet-4-5). A body that needs more is refused in call_claude(),
481
+ # never written back truncated.
482
+ MAX_OUTPUT_TOKENS = 64000
483
+
484
+
485
+ def resolve_max_output_tokens() -> int:
486
+ """Output ceiling for one SDK call, overridable per model.
487
+
488
+ The default tracks the max output of the default model. CAVEMAN_MODEL lets
489
+ a user pin a model whose ceiling is lower (claude-opus-4-0 tops out at
490
+ 32K), and asking for more output than the model allows is a 400 from the
491
+ API — an opaque failure in place of the truncation this cap exists to
492
+ prevent. CAVEMAN_MAX_OUTPUT_TOKENS lets that user lower the ask to match.
493
+
494
+ A malformed value raises rather than silently falling back: an override
495
+ that is quietly ignored looks like the cap was raised when it was not, and
496
+ the symptom is the same truncation, one layer further from the cause.
497
+ """
498
+ raw = os.environ.get("CAVEMAN_MAX_OUTPUT_TOKENS", "").strip()
499
+ if not raw:
500
+ return MAX_OUTPUT_TOKENS
501
+ try:
502
+ value = int(raw)
503
+ except ValueError:
504
+ raise RuntimeError(
505
+ f"CAVEMAN_MAX_OUTPUT_TOKENS must be a positive integer, got {raw!r}."
506
+ ) from None
507
+ if value < 1:
508
+ raise RuntimeError(
509
+ f"CAVEMAN_MAX_OUTPUT_TOKENS must be a positive integer, got {raw!r}."
510
+ )
511
+ return value
512
+
513
+
514
+ def _is_smaller_than_body(candidate_body: str, body: str) -> bool:
515
+ """True when `candidate_body` actually compresses `body`.
516
+
517
+ The non-expansion invariant for #776. It lives in a helper because it has
518
+ to hold for EVERY candidate, not just the first one: a candidate that fails
519
+ validation is sent back to the provider for repair, and the repaired text is what
520
+ gets written if it validates. Checking only the first candidate left the
521
+ retry path able to write a longer file and report it as a successful
522
+ compression — the original bug, one branch over.
523
+
524
+ Always compares bodies with frontmatter already removed. Frontmatter is
525
+ preserved verbatim, so counting it on one side and not the other would
526
+ measure the wrong thing.
527
+ """
528
+ candidate_len = len(candidate_body.strip())
529
+ body_len = len(body.strip())
530
+ if candidate_len >= body_len:
531
+ print(
532
+ "❌ Compression aborted: output is not smaller than input "
533
+ f"({candidate_len} >= {body_len} chars)."
534
+ )
535
+ return False
536
+ return True
537
+
538
+
539
+ # Bounds each individual Claude call so a stalled CLI (dropped network, an
540
+ # auth prompt with no TTY to answer it) can't hang past what LOCK_WAIT_SECONDS
541
+ # assumes for the whole run's worst case (MAX_RETRIES+1 calls).
542
+ CLAUDE_CALL_TIMEOUT_SECONDS = LOCK_WAIT_SECONDS // (MAX_RETRIES + 1)
543
+
544
+
545
+ # ---------- LLM Calls ----------
546
+
547
+
548
+ class AnthropicSdkUnavailable(RuntimeError):
549
+ """Raised when the explicitly selected Anthropic SDK is unavailable."""
550
+
551
+
552
+ def configured_provider() -> str:
553
+ provider = (
554
+ os.environ.get(ENV_COMPRESS_PROVIDER) or PROVIDER_CLAUDE
555
+ ).strip().lower()
556
+ if provider not in SUPPORTED_PROVIDERS:
557
+ supported = ", ".join(sorted(SUPPORTED_PROVIDERS))
558
+ raise ValueError(
559
+ f"Unsupported caveman-compress provider: {provider}. "
560
+ f"Supported providers: {supported}"
561
+ )
562
+ return provider
563
+
564
+
565
+ def configured_model(default_model: Optional[str] = None) -> Optional[str]:
566
+ model = (
567
+ os.environ.get(ENV_COMPRESS_MODEL)
568
+ or os.environ.get(ENV_FALLBACK_MODEL)
569
+ or default_model
570
+ )
571
+ if model is None:
572
+ return None
573
+ return model.strip() or None
574
+
575
+
576
+ def run_cli(
577
+ binary_name: str,
578
+ args: List[str],
579
+ stdin_prompt: Optional[str] = None,
580
+ extra_env: Optional[dict] = None,
581
+ ) -> str:
582
+ binary = shutil.which(binary_name) or binary_name
583
+ command = [binary, *args]
584
+ run_kwargs = {
585
+ "text": True,
586
+ "capture_output": True,
587
+ "check": True,
588
+ "encoding": "utf-8",
589
+ "errors": "replace",
590
+ "timeout": CLAUDE_CALL_TIMEOUT_SECONDS,
591
+ }
592
+ if stdin_prompt is not None:
593
+ run_kwargs["input"] = stdin_prompt
594
+ if extra_env:
595
+ # The child inherits this process's environment, plus extra_env.
596
+ run_kwargs["env"] = {**environ, **extra_env}
597
+ try:
598
+ result = subprocess.run(command, **run_kwargs)
599
+ return strip_llm_wrapper(result.stdout.strip())
600
+ except FileNotFoundError as error:
601
+ raise RuntimeError(f"{binary_name} CLI not found on PATH") from error
602
+ except subprocess.CalledProcessError as error:
603
+ stderr = error.stderr.strip() if error.stderr else "no stderr"
604
+ raise RuntimeError(f"{binary_name} call failed:\n{stderr}") from error
605
+ except subprocess.TimeoutExpired as error:
606
+ raise RuntimeError(
607
+ f"{binary_name} CLI call timed out after "
608
+ f"{CLAUDE_CALL_TIMEOUT_SECONDS}s "
609
+ "(stalled network, or an auth prompt with no TTY to answer it)"
610
+ ) from error
611
+
612
+
613
+ def call_anthropic_sdk(prompt: str) -> str:
614
+ api_key = os.environ.get(ENV_ANTHROPIC_API_KEY)
615
+ if not api_key:
616
+ raise RuntimeError(
617
+ f"{ENV_ANTHROPIC_API_KEY} is required for provider "
618
+ f"'{PROVIDER_ANTHROPIC}'"
619
+ )
620
+ try:
621
+ import anthropic
622
+ except ImportError as error:
623
+ raise AnthropicSdkUnavailable(
624
+ f"anthropic package is required for provider '{PROVIDER_ANTHROPIC}'"
625
+ ) from error
626
+
627
+ max_output_tokens = resolve_max_output_tokens()
628
+ client = anthropic.Anthropic(
629
+ api_key=api_key,
630
+ timeout=CLAUDE_CALL_TIMEOUT_SECONDS,
631
+ )
632
+ # Streaming, not create(): a large compression needs far more than
633
+ # the old 8192-token cap, and tokens that arrive as they are
634
+ # generated keep a long call from tripping the request timeout.
635
+ with client.messages.stream(
636
+ model=configured_model(DEFAULT_CLAUDE_MODEL),
637
+ max_tokens=max_output_tokens,
638
+ messages=[{"role": "user", "content": prompt}],
639
+ ) as stream:
640
+ message = stream.get_final_message()
641
+ # At the cap the tail was never generated. validate() and the fix
642
+ # prompt cannot recover it, so fail now instead of paying for
643
+ # retries that end by restoring the original anyway.
644
+ if message.stop_reason == "max_tokens":
645
+ raise RuntimeError(
646
+ f"Claude output hit the {max_output_tokens}-token cap, so the result is incomplete. "
647
+ "Split the file into smaller parts and compress each one."
648
+ )
649
+ # Tool-heavy models can put a tool_use or thinking block first.
650
+ text = next(
651
+ (
652
+ block.text
653
+ for block in message.content
654
+ if getattr(block, "type", None) == "text"
655
+ ),
656
+ "",
657
+ )
658
+ return strip_llm_wrapper(text.strip())
659
+
660
+
661
+ def call_claude_cli(prompt: str) -> str:
662
+ args = []
663
+ model = configured_model()
664
+ if model:
665
+ args.extend([MODEL_ARG, model])
666
+ args.extend([
667
+ CLAUDE_PRINT_ARG,
668
+ CLAUDE_SETTING_SOURCES_ARG,
669
+ "",
670
+ CLAUDE_STRICT_MCP_ARG,
671
+ ])
672
+ return run_cli(CLAUDE_CLI, args, prompt)
673
+
674
+
675
+ def call_codex_cli(prompt: str) -> str:
676
+ """Use Codex's saved login and final-message file, never its progress output."""
677
+ binary = shutil.which(CODEX_CLI)
678
+ if binary is None:
679
+ raise RuntimeError("codex CLI not found on PATH. Install Codex CLI, then run `codex login`.")
680
+ with tempfile.TemporaryDirectory(prefix="caveman-compress-codex-") as tmp:
681
+ workdir = Path(tmp).resolve()
682
+ output_path = workdir / "response.md"
683
+ args = [
684
+ binary, "exec", "--ignore-user-config", "--strict-config", "--ephemeral",
685
+ "--skip-git-repo-check",
686
+ "--output-last-message", str(output_path),
687
+ "-c", 'approval_policy="never"',
688
+ "-c", 'default_permissions="caveman-compress"',
689
+ "-c", 'permissions.caveman-compress.filesystem={":root"="deny"}',
690
+ "-c", "permissions.caveman-compress.network.enabled=false",
691
+ "-c", "project_doc_max_bytes=0",
692
+ "-c", 'web_search="disabled"',
693
+ ]
694
+ # --sandbox would override this profile. stdin already contains the input;
695
+ # no user files need to be readable by sandboxed commands.
696
+ for feature in CODEX_DISABLED_FEATURES:
697
+ args.extend(["--disable", feature])
698
+ model = configured_model()
699
+ if model:
700
+ args.extend([MODEL_ARG, model])
701
+ args.append("-")
702
+ try:
703
+ subprocess.run(
704
+ args, input=prompt, text=True, capture_output=True, check=True,
705
+ encoding="utf-8", errors="replace", timeout=CLAUDE_CALL_TIMEOUT_SECONDS,
706
+ cwd=str(workdir),
707
+ )
708
+ except FileNotFoundError:
709
+ raise RuntimeError(
710
+ "codex CLI not found on PATH. Install Codex CLI, then run `codex login`."
711
+ ) from None
712
+ except subprocess.CalledProcessError as error:
713
+ # CLI diagnostics can contain prompt text or credentials; don't echo them.
714
+ raise RuntimeError(
715
+ f"codex exec failed (exit code {error.returncode}). Run `codex login` "
716
+ "if unauthenticated; check your model and access, and use Codex CLI 0.166.0 or newer. "
717
+ "Compression requires isolated configuration and permission-profile support."
718
+ ) from None
719
+ except subprocess.TimeoutExpired:
720
+ raise RuntimeError(
721
+ f"codex CLI call timed out after {CLAUDE_CALL_TIMEOUT_SECONDS}s. "
722
+ "Check your connection and `codex login` session, then retry."
723
+ ) from None
724
+ try:
725
+ response = output_path.read_text(encoding="utf-8")
726
+ except (OSError, UnicodeError):
727
+ raise RuntimeError(
728
+ "codex exec did not write a readable final response. Check your Codex CLI version and retry."
729
+ ) from None
730
+ response = strip_llm_wrapper(response.strip())
731
+ if not response.strip():
732
+ raise RuntimeError("codex exec returned an empty final response. Check your Codex session and retry.")
733
+ return response
734
+
735
+
736
+ def call_opencode_cli(prompt: str) -> str:
737
+ args = [OPENCODE_RUN_ARG]
738
+ model = configured_model()
739
+ if model:
740
+ args.extend([MODEL_ARG, model])
741
+ args.extend([OPENCODE_AGENT_ARG, OPENCODE_AGENT])
742
+ # --standalone: the shared background service ignores this process's env
743
+ # (verified on opencode 2.0.22), so the deny config only binds a private
744
+ # server. Never pass --auto. Any inline config the user set is kept.
745
+ args.append(OPENCODE_STANDALONE_ARG)
746
+ try:
747
+ config = json.loads(os.environ.get("OPENCODE_CONFIG_CONTENT") or "{}")
748
+ except ValueError:
749
+ config = None
750
+ if not isinstance(config, dict):
751
+ raise RuntimeError(
752
+ "OPENCODE_CONFIG_CONTENT must be a strict JSON object (no comments or "
753
+ "trailing commas) so compress can add its tool-deny rule; fix or unset it."
754
+ )
755
+ agents = config.get("agent") or {}
756
+ if not isinstance(agents, dict):
757
+ raise RuntimeError(
758
+ 'OPENCODE_CONFIG_CONTENT "agent" must be a JSON object so compress '
759
+ "can add its tool-deny agent; fix or unset it."
760
+ )
761
+ config["permission"] = OPENCODE_PERMISSION_DENY
762
+ config["agent"] = {
763
+ **agents,
764
+ OPENCODE_AGENT: {"permission": OPENCODE_PERMISSION_DENY},
765
+ }
766
+ extra_env = {"OPENCODE_CONFIG_CONTENT": json.dumps(config)}
767
+
768
+ prompt_path = None
769
+ try:
770
+ with tempfile.NamedTemporaryFile(
771
+ "w",
772
+ encoding="utf-8",
773
+ prefix=OPENCODE_PROMPT_PREFIX,
774
+ suffix=OPENCODE_PROMPT_SUFFIX,
775
+ delete=False,
776
+ ) as prompt_file:
777
+ prompt_path = Path(prompt_file.name)
778
+ prompt_file.write(prompt)
779
+ args.extend(
780
+ [OPENCODE_FILE_ARG, str(prompt_path), OPENCODE_PROMPT_MESSAGE]
781
+ )
782
+ return run_cli(OPENCODE_CLI, args, extra_env=extra_env)
783
+ finally:
784
+ if prompt_path is not None:
785
+ # Warn, never raise: raising here would replace the real opencode
786
+ # error (or a good result) with a cleanup failure.
787
+ try:
788
+ prompt_path.unlink(missing_ok=True)
789
+ except OSError:
790
+ print(
791
+ f"warning: could not delete temporary opencode prompt {prompt_path}",
792
+ file=sys.stderr,
793
+ )
794
+
795
+
796
+ def call_openai_compat(prompt: str) -> str:
797
+ """POST to any OpenAI-compatible /chat/completions (Ollama, llama.cpp,
798
+ vLLM, LM Studio). Standard library only, so no new dependency."""
799
+ model = configured_model()
800
+ if not model:
801
+ raise RuntimeError(
802
+ f"{ENV_COMPRESS_MODEL} is required for provider '{PROVIDER_OPENAI_COMPAT}'"
803
+ )
804
+ base = os.environ.get(ENV_COMPRESS_ENDPOINT, DEFAULT_OPENAI_COMPAT_ENDPOINT).rstrip("/")
805
+ body = {"model": model, "messages": [{"role": "user", "content": prompt}], "stream": False}
806
+ request = urllib.request.Request(
807
+ f"{base}/chat/completions",
808
+ data=json.dumps(body).encode("utf-8"),
809
+ headers={"Content-Type": "application/json"},
810
+ )
811
+ api_key = os.environ.get(ENV_COMPRESS_API_KEY)
812
+ if api_key:
813
+ # Unredirected: urllib copies ordinary headers onto a redirect, even
814
+ # one to another host.
815
+ request.add_unredirected_header("Authorization", f"Bearer {api_key}")
816
+ try:
817
+ with urllib.request.urlopen(request, timeout=CLAUDE_CALL_TIMEOUT_SECONDS) as response:
818
+ raw = response.read()
819
+ except urllib.error.HTTPError as error:
820
+ detail = error.read().decode("utf-8", "replace")[:500]
821
+ raise RuntimeError(
822
+ f"{PROVIDER_OPENAI_COMPAT} call failed: HTTP {error.code}: {detail}"
823
+ ) from error
824
+ except OSError as error: # URLError, refused connection, timeout
825
+ reason = getattr(error, "reason", error)
826
+ raise RuntimeError(f"{PROVIDER_OPENAI_COMPAT} call to {base} failed: {reason}") from error
827
+ try:
828
+ choice = json.loads(raw)["choices"][0]
829
+ content = choice["message"].get("content")
830
+ except (ValueError, KeyError, IndexError, TypeError, AttributeError):
831
+ detail = raw.decode("utf-8", "replace")[:500]
832
+ raise RuntimeError(
833
+ f"{PROVIDER_OPENAI_COMPAT} call to {base} returned an unexpected response: {detail}"
834
+ ) from None
835
+ # Same rule as the SDK path: a truncated body is never returned.
836
+ if choice.get("finish_reason") == "length":
837
+ raise RuntimeError(
838
+ f"{PROVIDER_OPENAI_COMPAT} output hit the server's token cap, so the result is "
839
+ "incomplete. Split the file into smaller parts and compress each one."
840
+ )
841
+ return strip_llm_wrapper((content or "").strip())
842
+
843
+
844
+ def call_claude(prompt: str) -> str:
845
+ """Send a prompt to the configured compression provider.
846
+
847
+ Prefers the Anthropic SDK when ANTHROPIC_API_KEY is set; otherwise falls
848
+ back to the ``claude --print`` CLI (which handles desktop auth). Set
849
+ ``CAVEMAN_COMPRESS_PROVIDER=opencode`` and ``CAVEMAN_COMPRESS_MODEL`` (or
850
+ ``CAVEMAN_MODEL``) to route compression through opencode instead, or
851
+ ``codex`` for the Codex CLI's saved login, or ``openai-compat`` for an
852
+ OpenAI-compatible server such as local Ollama.
853
+
854
+ On Windows the CLI subprocess decoding defaults to the system codepage
855
+ (cp1251 / cp1252) and crashes on UTF-8 output — see issue #152. Pinning
856
+ ``encoding="utf-8"`` with ``errors="replace"`` matches the CLI's actual
857
+ native I/O and prevents the UnicodeDecodeError before validation can
858
+ report. Windows users with non-ASCII content can also set
859
+ ``ANTHROPIC_API_KEY`` to route through the SDK and skip the subprocess.
860
+ """
861
+ provider = configured_provider()
862
+ if provider == PROVIDER_CODEX:
863
+ return call_codex_cli(prompt)
864
+ if provider == PROVIDER_OPENCODE:
865
+ return call_opencode_cli(prompt)
866
+ if provider == PROVIDER_OPENAI_COMPAT:
867
+ return call_openai_compat(prompt)
868
+ if provider == PROVIDER_ANTHROPIC:
869
+ return call_anthropic_sdk(prompt)
870
+ if os.environ.get(ENV_ANTHROPIC_API_KEY):
871
+ try:
872
+ return call_anthropic_sdk(prompt)
873
+ except AnthropicSdkUnavailable:
874
+ pass
875
+ return call_claude_cli(prompt)
876
+
877
+
878
+ def build_compress_prompt(original: str) -> str:
879
+ return f"""
880
+ Compress this markdown into caveman format.
881
+
882
+ STRICT RULES:
883
+ - Do NOT modify anything inside ``` code blocks
884
+ - Do NOT modify anything inside a 4-space-indented code block either — those are code too, and they are validated
885
+ - Do NOT modify anything inside inline backticks
886
+ - Do NOT add new ``` fences around content that is not already fenced, even if it looks like code or JSON
887
+ - Do NOT create, remove, reword or promote headings; keep existing # headings exactly
888
+ - Do NOT convert XML-like tags (e.g. <example>, <section>) into headings or other markdown; leave them as plain text
889
+ - Preserve ALL URLs exactly
890
+ - Preserve ALL headings exactly
891
+ - Preserve file paths and commands
892
+ - Return ONLY the compressed markdown body, with no preface, commentary, or YAML frontmatter — 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.
893
+ - Output ends where the input ends: no appended summary, notes, "untouched" section, or trailing commentary, and no new --- or *** break to introduce one
894
+ - Keep the verb that carries each instruction: "Do X", "Run Y", "Never Z" stay orders. A fragment is fine, a verbless noun phrase is not
895
+
896
+ Only compress natural language prose. Never restructure, add formatting, or improve organization.
897
+
898
+ TEXT:
899
+ {original}
900
+ """
901
+
902
+
903
+ def build_fix_prompt(original: str, compressed: str, errors: List[str]) -> str:
904
+ errors_str = "\n".join(f"- {e}" for e in errors)
905
+ return f"""You are fixing a caveman-compressed markdown file. Specific validation errors were found.
906
+
907
+ CRITICAL RULES:
908
+ - DO NOT recompress or rephrase the file
909
+ - ONLY fix the listed errors — leave everything else exactly as-is
910
+ - The ORIGINAL is provided as reference only (to restore missing content)
911
+ - Preserve caveman style in all untouched sections
912
+
913
+ ERRORS TO FIX:
914
+ {errors_str}
915
+
916
+ HOW TO FIX:
917
+ - Missing URL: find it in ORIGINAL, restore it exactly where it belongs in COMPRESSED
918
+ - Code block mismatch: find the exact code block in ORIGINAL, restore it in COMPRESSED
919
+ - Heading mismatch: restore the exact heading text from ORIGINAL into COMPRESSED
920
+ - Do not touch any section not mentioned in the errors
921
+
922
+ ORIGINAL (reference only):
923
+ {original}
924
+
925
+ COMPRESSED (fix this):
926
+ {compressed}
927
+
928
+ Return ONLY the fixed compressed markdown body. No preface, commentary, YAML frontmatter, or explanation.
929
+ """
930
+
931
+
932
+ CODE_MARKER_PREFIX = "@@CAVEMAN_PRESERVED_CODE_"
933
+ FENCE_OPEN_RE = re.compile(r"^[ ]{0,3}(`{3,}|~{3,})(?:[^\r\n]*)$")
934
+ # Whole-line tags only, at most 3 spaces in (4+ is an indented code block).
935
+ NOCOMPRESS_OPEN_RE = re.compile(r"^[ ]{0,3}<!--\s*nocompress\s*-->\s*$", re.IGNORECASE)
936
+ NOCOMPRESS_CLOSE_RE = re.compile(r"^[ ]{0,3}<!--\s*/nocompress\s*-->\s*$", re.IGNORECASE)
937
+ # CommonMark HTML block type 2: a line opening with `<!--` (up to 3 spaces in)
938
+ # runs to the first line holding `-->`. Comments often carry notes for the next
939
+ # editor; unmasked, the model could drop or reword them and validation, which
940
+ # never counted them, passed the result (#1350).
941
+ HTML_COMMENT_OPEN_RE = re.compile(r"^[ ]{0,3}<!--")
942
+
943
+
944
+ def mask_code_blocks(text: str) -> Tuple[str, List[Tuple[str, str]]]:
945
+ """Replace fenced and four-space-indented code, <!-- nocompress -->
946
+ regions and block-level HTML comments with opaque line markers."""
947
+ if CODE_MARKER_PREFIX in text:
948
+ raise ValueError("Input contains reserved Caveman code-preservation marker")
949
+ lines = text.splitlines(keepends=True)
950
+ out: List[str] = []
951
+ blocks: List[Tuple[str, str]] = []
952
+ i = 0
953
+ while i < len(lines):
954
+ line_without_newline = lines[i].rstrip("\r\n")
955
+ nocompress = NOCOMPRESS_OPEN_RE.match(line_without_newline)
956
+ fence = not nocompress and FENCE_OPEN_RE.match(line_without_newline)
957
+ indented = bool(line_without_newline) and (
958
+ line_without_newline.startswith(" ") or line_without_newline.startswith("\t")
959
+ )
960
+ comment = (
961
+ not nocompress and not fence and not indented
962
+ and HTML_COMMENT_OPEN_RE.match(line_without_newline)
963
+ )
964
+ if not nocompress and not fence and not indented and not comment:
965
+ out.append(lines[i])
966
+ i += 1
967
+ continue
968
+
969
+ start = i
970
+ if comment:
971
+ # Ends on the first line holding `-->`, which may be this one. An
972
+ # unclosed comment runs to the end of the document, as it renders.
973
+ after_open = line_without_newline[line_without_newline.index("<!--") + 4:]
974
+ i += 1
975
+ if "-->" not in after_open:
976
+ while i < len(lines) and "-->" not in lines[i]:
977
+ i += 1
978
+ i = min(i + 1, len(lines))
979
+ elif nocompress:
980
+ i += 1
981
+ while i < len(lines) and not NOCOMPRESS_CLOSE_RE.match(lines[i].rstrip("\r\n")):
982
+ i += 1
983
+ if i == len(lines):
984
+ raise ValueError(f"unclosed <!-- nocompress --> region starting at line {start + 1}")
985
+ i += 1
986
+ elif fence:
987
+ fence_run = fence.group(1)
988
+ close_re = re.compile(
989
+ rf"^[ ]{{0,3}}{re.escape(fence_run[0])}{{{len(fence_run)},}}[ \t]*$"
990
+ )
991
+ i += 1
992
+ while i < len(lines):
993
+ if close_re.match(lines[i].rstrip("\r\n")):
994
+ i += 1
995
+ break
996
+ i += 1
997
+ else:
998
+ i += 1
999
+ while i < len(lines):
1000
+ candidate = lines[i].rstrip("\r\n")
1001
+ if not candidate or candidate.startswith(" ") or candidate.startswith("\t"):
1002
+ i += 1
1003
+ continue
1004
+ break
1005
+
1006
+ block = "".join(lines[start:i])
1007
+ marker = f"{CODE_MARKER_PREFIX}{len(blocks)}_{hashlib.sha256(block.encode('utf-8')).hexdigest()[:16]}@@"
1008
+ blocks.append((marker, block))
1009
+ newline = "\r\n" if block.endswith("\r\n") else "\n" if block.endswith("\n") else ""
1010
+ out.append(marker + newline)
1011
+ return "".join(out), blocks
1012
+
1013
+
1014
+ def restore_code_blocks(text: str, blocks: List[Tuple[str, str]]) -> str:
1015
+ """Restore markers exactly; fail closed if model removed, copied, or altered one."""
1016
+ restored = text
1017
+ for marker, block in blocks:
1018
+ if restored.count(marker) != 1:
1019
+ raise ValueError(
1020
+ f"Provider changed preserved code marker {marker}; refusing to write"
1021
+ )
1022
+ # Masking gives marker its own transport newline. Consume that wrapper
1023
+ # when present so restoring a block that already ended in newline does
1024
+ # not silently add another blank line.
1025
+ if marker + "\r\n" in restored:
1026
+ restored = restored.replace(marker + "\r\n", block, 1)
1027
+ elif marker + "\n" in restored:
1028
+ restored = restored.replace(marker + "\n", block, 1)
1029
+ else:
1030
+ restored = restored.replace(marker, block, 1)
1031
+ if CODE_MARKER_PREFIX in restored:
1032
+ raise ValueError("Provider returned an unknown Caveman code-preservation marker")
1033
+ return restored
1034
+
1035
+
1036
+ def _frontmatter_block_count(masked_body: str) -> int:
1037
+ """Count mapping-shaped delimiter blocks outside preserved code."""
1038
+ lines = masked_body.splitlines()
1039
+ delimiters = [i for i, line in enumerate(lines) if line == "---"]
1040
+ count = 0
1041
+ for start, end in zip(delimiters, delimiters[1:]):
1042
+ content = [line for line in lines[start + 1:end] if line.strip()]
1043
+ key_value = re.compile(r"^[A-Za-z_][A-Za-z0-9_.-]*:(\s.*)?$")
1044
+ if content and key_value.match(content[0]) and all(
1045
+ key_value.match(line) or line[0].isspace() or line.startswith("- ")
1046
+ for line in content[1:]
1047
+ ):
1048
+ count += 1
1049
+ return count
1050
+
1051
+
1052
+ _THEMATIC_BREAK_RE = re.compile(r"^(?:-{3,}|\*{3,}|_{3,})$")
1053
+
1054
+
1055
+ def _thematic_break_count(masked_body: str) -> int:
1056
+ """Count bare thematic-break lines outside preserved code.
1057
+
1058
+ The head of the body is anchored by its first line, but nothing anchored
1059
+ the tail, so an appended commentary section ("Untouched: ... Risk: ...")
1060
+ under a new ``---`` was accepted and written into the file (#1433). The
1061
+ model is already told not to restructure or add formatting, so a break
1062
+ that was not in the original is an addition either way: counting them
1063
+ needs no classification of what follows, which is the part #1359
1064
+ deliberately declines to do.
1065
+ """
1066
+ return sum(
1067
+ 1 for line in masked_body.splitlines()
1068
+ if _THEMATIC_BREAK_RE.match(line.strip())
1069
+ )
1070
+
1071
+
1072
+ def _body_candidate_error(original_masked: str, candidate_masked: str) -> str:
1073
+ """Use the same body-only structural guards for compression and repair."""
1074
+ anchor = first_nonblank_line(original_masked)
1075
+ if anchor.startswith(("#", CODE_MARKER_PREFIX)) and first_nonblank_line(candidate_masked) != anchor:
1076
+ return "output does not start with the original body's first line (possible preamble leak)"
1077
+ if _frontmatter_block_count(candidate_masked) > _frontmatter_block_count(original_masked):
1078
+ return "output added YAML frontmatter to the markdown body"
1079
+ if _thematic_break_count(candidate_masked) > _thematic_break_count(original_masked):
1080
+ return (
1081
+ "output added a thematic break the original did not have "
1082
+ "(possible appended commentary or notes section)"
1083
+ )
1084
+ return ""
1085
+
1086
+
1087
+ # ---------- Core Logic ----------
1088
+
1089
+
1090
+ def compress_file(filepath: Path) -> bool:
1091
+ # Resolve first so the lock and every check below key off the same canonical path regardless of how the caller spelled it.
1092
+ filepath = filepath.resolve()
1093
+
1094
+ # None of these three checks depends on mutual exclusion, so they run before the lock is taken — a rejected input (bad path, oversized, sensitive name) shouldn't leave a permanent lock file behind in shared state.
1095
+ if not filepath.exists():
1096
+ raise FileNotFoundError(f"File not found: {filepath}")
1097
+ if filepath.stat().st_size > MAX_FILE_SIZE_BYTES:
1098
+ raise ValueError(
1099
+ f"File too large to compress safely (max {MAX_FILE_SIZE_LABEL}): "
1100
+ f"{filepath}"
1101
+ )
1102
+
1103
+ # Refuse files that look like they contain secrets or PII. Compressing ships
1104
+ # the raw bytes to the configured provider — a third-party boundary — so we fail
1105
+ # loudly rather than silently exfiltrate credentials or keys. Override is
1106
+ # intentional: the user must rename the file if the heuristic is wrong.
1107
+ if is_sensitive_path(filepath):
1108
+ raise ValueError(
1109
+ f"Refusing to compress {filepath}: filename looks sensitive "
1110
+ "(credentials, keys, secrets, or known private paths). "
1111
+ "Compression sends file contents to the configured LLM provider. "
1112
+ "Rename the file if this is a false positive."
1113
+ )
1114
+
1115
+ with file_lock(filepath):
1116
+ backup_path = backup_dir_for(filepath) / (filepath.stem + ".original.md")
1117
+ had_backup = backup_path.exists()
1118
+ run = {"live_write_started": False}
1119
+ try:
1120
+ return _compress_file_locked(filepath, run)
1121
+ except BaseException:
1122
+ # A provider error, timeout or Ctrl-C mid-run must not leave the
1123
+ # staging file next to the source, or a backup that makes every
1124
+ # later run abort with "Backup file already exists". The backup is
1125
+ # removed only if this run created it and never started the live
1126
+ # write; past that point it may be the only copy of the original.
1127
+ filepath.with_name(filepath.name + ".caveman-staged").unlink(missing_ok=True)
1128
+ if not had_backup and not run["live_write_started"]:
1129
+ backup_path.unlink(missing_ok=True)
1130
+ raise
1131
+
1132
+
1133
+ def _compress_file_locked(filepath: Path, run: dict) -> bool:
1134
+ """Body of compress_file; runs entirely under compress_file's file_lock for this resolved path."""
1135
+ print(f"Processing: {filepath}")
1136
+
1137
+ if not should_compress(filepath):
1138
+ print("Skipping (not natural language)")
1139
+ return False
1140
+
1141
+ original_text, newline, original_raw = read_source(filepath)
1142
+ # Store backup outside the source directory so skill auto-loaders don't
1143
+ # re-ingest the `.original.md` copy as a live file. Mirror the source's
1144
+ # parent-dir name + stem under a platform-aware base to reduce collisions.
1145
+ backup_dir = backup_dir_for(filepath)
1146
+ backup_path = backup_dir / (filepath.stem + ".original.md")
1147
+
1148
+ if not original_text.strip():
1149
+ print("❌ Refusing to compress: file is empty or whitespace-only.")
1150
+ return False
1151
+
1152
+ credential = find_credential(original_text)
1153
+ if credential is not None:
1154
+ kind, lineno = credential
1155
+ raise ValueError(
1156
+ f"Refusing to compress {filepath}: line {lineno} looks like a {kind}. "
1157
+ "Compression sends the file's text to the configured LLM provider. "
1158
+ "Move the secret out of this file (an env var or secret manager), then rerun."
1159
+ )
1160
+
1161
+ # Refuse when a backup already exists, so a rerun cannot capture this file's
1162
+ # already-compressed text as the new "original".
1163
+ if backup_path.exists():
1164
+ print(f"⚠️ Backup already exists: {backup_path}")
1165
+ print(f" It holds the uncompressed original of an earlier run on {filepath.name}.")
1166
+ print("Aborting to prevent data loss.")
1167
+ print(f" To restore it: cp '{backup_path}' '{filepath}'")
1168
+ print(f" To start over: mv '{backup_path}' '{backup_path}.kept'")
1169
+ print(" Do not just delete it — rerunning would then store the ALREADY")
1170
+ print(" COMPRESSED text as the new original, losing the uncompressed version.")
1171
+ return False
1172
+
1173
+ # The pre-#1351 location is checked too: an install that compressed this file
1174
+ # before the backup key changed still has its only original there. That path
1175
+ # was keyed on the parent directory's NAME alone, so it was shared by every
1176
+ # same-named file on the machine — this backup may well belong to a DIFFERENT
1177
+ # project, which is exactly the bug that produced it. So: refuse, name the
1178
+ # ambiguity, and never read, move or delete it on the user's behalf.
1179
+ legacy_backup = legacy_backup_dir_for(filepath) / (filepath.stem + ".original.md")
1180
+ if legacy_backup.exists():
1181
+ print(f"⚠️ A backup from an older caveman-compress exists: {legacy_backup}")
1182
+ print(" Older versions keyed backups on the parent directory's name only,")
1183
+ print(f" so that file is the original of SOME {filepath.parent.name}/{filepath.name}")
1184
+ print(" on this machine — possibly this one, possibly another project's.")
1185
+ print("Aborting to prevent data loss.")
1186
+ print(" Check its contents, then move it out of the way to proceed:")
1187
+ print(f" mv '{legacy_backup}' '{legacy_backup}.kept'")
1188
+ print(" Backups written from now on are keyed on the file's full path and")
1189
+ print(f" will land in {backup_path.parent}")
1190
+ return False
1191
+
1192
+ # Split YAML frontmatter off before compression. LLMs tend to strip or
1193
+ # rewrite frontmatter despite preserve-structure rules; we keep it verbatim
1194
+ # by removing it from the input and re-prepending it to the output.
1195
+ frontmatter, body = split_frontmatter(original_text)
1196
+ if frontmatter:
1197
+ print(f"Detected YAML frontmatter ({len(frontmatter)} chars) — preserving verbatim")
1198
+
1199
+ if not body.strip():
1200
+ print("❌ Refusing to compress: body is empty after frontmatter removal.")
1201
+ return False
1202
+
1203
+ # Step 1: Compress (body only, frontmatter excluded)
1204
+ provider = configured_provider()
1205
+ print(f"Compressing with {provider}...")
1206
+ masked_body, code_blocks = mask_code_blocks(body)
1207
+ masked_compressed = call_claude(build_compress_prompt(masked_body))
1208
+ if masked_compressed is None or not masked_compressed.strip():
1209
+ print(f"❌ Compression aborted: {provider} returned an empty response.")
1210
+ print(" Original file is untouched (no backup created).")
1211
+ return False
1212
+ body_error = _body_candidate_error(masked_body, masked_compressed)
1213
+ if body_error:
1214
+ print(f"❌ Compression aborted: {body_error}.")
1215
+ print(" Original file is untouched (no backup created).")
1216
+ return False
1217
+ try:
1218
+ compressed_body = restore_code_blocks(masked_compressed, code_blocks)
1219
+ except ValueError as error:
1220
+ print(f"❌ Compression aborted: {error}")
1221
+ print(" Original file is untouched (no backup created).")
1222
+ return False
1223
+
1224
+ if compressed_body is None or not compressed_body.strip():
1225
+ print(f"❌ Compression aborted: {provider} returned an empty response.")
1226
+ print(" Original file is untouched (no backup created).")
1227
+ return False
1228
+
1229
+ # Compare the BODY (not the whole file) — frontmatter is preserved verbatim
1230
+ # and would never change, so identity must be judged on the compressible part.
1231
+ if compressed_body.strip() == body.strip():
1232
+ print("❌ Compression aborted: output is identical to input.")
1233
+ print(f" Likely causes: {provider} refused, returned the prompt verbatim, or the file is")
1234
+ print(" already in caveman form. Original file is untouched (no backup created).")
1235
+ return False
1236
+
1237
+ # A rewrite that is structurally faithful but LONGER than the input passes
1238
+ # every check below (validate() only checks structural invariants, not
1239
+ # length) and would otherwise be written over the original and reported
1240
+ # as a successful compression — the opposite of what this tool exists to
1241
+ # do (issue #776). Same length is also a reject: a compression that saved
1242
+ # nothing isn't a compression.
1243
+ if not _is_smaller_than_body(compressed_body, body):
1244
+ print(" Original file is untouched (no backup created).")
1245
+ return False
1246
+
1247
+ # Reassemble: frontmatter (verbatim) + compressed body
1248
+ compressed = frontmatter + compressed_body
1249
+
1250
+ # Save original as backup, then verify the backup readback before
1251
+ # touching the input file. If the filesystem dropped bytes (encoding,
1252
+ # antivirus, disk full), unlink the bad backup and abort instead of
1253
+ # leaving the user with a corrupt backup + compressed primary.
1254
+ backup_dir.mkdir(parents=True, exist_ok=True)
1255
+ write_bytes_atomic(backup_path, original_raw)
1256
+ if backup_path.read_bytes() != original_raw:
1257
+ print(f"❌ Backup write verification failed: {backup_path}")
1258
+ print(" In-memory original differs from on-disk backup. Aborting before touching the input file.")
1259
+ try:
1260
+ backup_path.unlink()
1261
+ except OSError:
1262
+ pass
1263
+ return False
1264
+ # Step 2: Validate + Retry. Each candidate is staged and validated next
1265
+ # to the source; the live file is written only once one passes (#544).
1266
+ staging_path = filepath.with_name(filepath.name + ".caveman-staged")
1267
+ for attempt in range(MAX_RETRIES):
1268
+ print(f"\nValidation attempt {attempt + 1}")
1269
+
1270
+ _write_target(staging_path, compressed, backup_path, newline)
1271
+ result = validate(backup_path, staging_path)
1272
+
1273
+ if result.is_valid:
1274
+ print("Validation passed")
1275
+ # Warnings don't block the write, but they were computed and never
1276
+ # shown (#1350): a big bullet-count drop is worth a second look.
1277
+ for warning in result.warnings:
1278
+ print(f" ⚠️ {warning}")
1279
+ run["live_write_started"] = True
1280
+ _write_target(filepath, compressed, backup_path, newline)
1281
+ staging_path.unlink(missing_ok=True)
1282
+ return True
1283
+
1284
+ print("❌ Validation failed:")
1285
+ for err in result.errors:
1286
+ print(f" - {err}")
1287
+
1288
+ if attempt == MAX_RETRIES - 1:
1289
+ staging_path.unlink(missing_ok=True)
1290
+ backup_path.unlink(missing_ok=True)
1291
+ print("Failed after retries: original left untouched")
1292
+ return False
1293
+
1294
+ print(f"Fixing with {provider}...")
1295
+ fixed = call_claude(
1296
+ build_fix_prompt(body, compressed_body, result.errors)
1297
+ )
1298
+
1299
+ if fixed is None or not fixed.strip():
1300
+ print(f"❌ Fix attempt aborted: {provider} returned an empty response.")
1301
+ print(" Skipping this attempt.")
1302
+ continue
1303
+
1304
+ # Repairs use the same body-only contract as the initial compression.
1305
+ # Mask code for structural checks so fenced YAML is never frontmatter.
1306
+ try:
1307
+ masked_fixed, _ = mask_code_blocks(fixed)
1308
+ except ValueError as error:
1309
+ print(f"❌ Fix attempt aborted: {error}")
1310
+ continue
1311
+ body_error = _body_candidate_error(masked_body, masked_fixed)
1312
+ if body_error:
1313
+ print(f"❌ Fix attempt aborted: {body_error}.")
1314
+ print(" Skipping this attempt.")
1315
+ continue
1316
+ fixed_body = fixed
1317
+ if not _is_smaller_than_body(fixed_body, body):
1318
+ print(" Skipping this attempt.")
1319
+ continue
1320
+
1321
+ # The fix prompt carries the body unmasked; every protected block
1322
+ # must still come back verbatim, including list-nested fences.
1323
+ if any(block.rstrip("\n") not in fixed_body for _, block in code_blocks):
1324
+ print("❌ Fix attempt aborted: output changed a preserved code or <!-- nocompress --> block.")
1325
+ print(" Skipping this attempt.")
1326
+ continue
1327
+
1328
+ compressed_body = fixed_body
1329
+ compressed = frontmatter + compressed_body
1330
+
1331
+ return False