@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,192 @@
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. `.mdc` is a Cursor
9
+ # rule: prose with YAML frontmatter, the same shape as a SKILL.md, and the
10
+ # format caveman's own `--with-init` writes to `.cursor/rules/caveman.mdc`.
11
+ # Content sniffing below runs only for EXTENSIONLESS files, so an extension
12
+ # that is on neither list falls through to `unknown` and is never compressed.
13
+ COMPRESSIBLE_EXTENSIONS = {".md", ".mdc", ".txt", ".markdown", ".rst", ".typ", ".typst", ".tex"}
14
+
15
+ # Extensions that are code/config and should be skipped
16
+ SKIP_EXTENSIONS = {
17
+ ".py", ".js", ".ts", ".tsx", ".jsx", ".json", ".yaml", ".yml",
18
+ ".toml", ".env", ".lock", ".css", ".scss", ".html", ".xml",
19
+ ".sql", ".sh", ".bash", ".zsh", ".go", ".rs", ".java", ".c",
20
+ ".cpp", ".h", ".hpp", ".rb", ".php", ".swift", ".kt", ".lua",
21
+ ".dockerfile", ".makefile", ".csv", ".ini", ".cfg",
22
+ }
23
+
24
+ # Well-known build/config files that carry no (or a misleading) extension —
25
+ # `Dockerfile` has no suffix so `.dockerfile` above never matches it, and
26
+ # `CMakeLists.txt` would ride the compressible `.txt` rule. Checked by
27
+ # basename before any extension rule.
28
+ KNOWN_CODE_FILENAMES = {
29
+ "dockerfile", "containerfile", "makefile", "gnumakefile", "jenkinsfile",
30
+ "vagrantfile", "rakefile", "gemfile", "justfile", "procfile", "brewfile",
31
+ "earthfile", "fastfile", "podfile",
32
+ "cmakelists.txt",
33
+ }
34
+
35
+ # Dotfiles whose entire name sits where pathlib expects a suffix, so
36
+ # `Path(".cursorrules").suffix` is `""` just as it is for `.env`. These are the
37
+ # prose ones — Cursor's and its imitators' legacy single-file rule formats —
38
+ # and the only bare dotfiles that may be compressed. Everything else is
39
+ # treated as config; see the dotfile branch in `detect_file_type`.
40
+ PROSE_DOTFILES = {
41
+ ".cursorrules", ".windsurfrules", ".clinerules", ".aiderrules",
42
+ ".goosehints", ".augmentrules",
43
+ }
44
+
45
+ # Extensions on SKIP_EXTENSIONS that are data/config rather than program text.
46
+ CONFIG_EXTENSIONS = {".json", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".env"}
47
+
48
+ # Patterns that indicate a line is code
49
+ CODE_PATTERNS = [
50
+ re.compile(r"^\s*(import |from .+ import |require\(|const |let |var )"),
51
+ re.compile(r"^\s*(def |class |function |async function |export )"),
52
+ re.compile(r"^\s*(if\s*\(|for\s*\(|while\s*\(|switch\s*\(|try\s*\{)"),
53
+ re.compile(r"^\s*[\}\]\);]+\s*$"), # closing braces/brackets
54
+ re.compile(r"^\s*@\w+"), # decorators/annotations
55
+ re.compile(r'^\s*"[^"]+"\s*:\s*'), # JSON-like key-value
56
+ re.compile(r"^\s*\w+\s*=\s*[{\[\(\"']"), # assignment with literal
57
+ ]
58
+
59
+
60
+ def _is_code_line(line: str) -> bool:
61
+ """Check if a line looks like code."""
62
+ return any(p.match(line) for p in CODE_PATTERNS)
63
+
64
+
65
+ def _is_json_content(text: str) -> bool:
66
+ """Check if content is valid JSON."""
67
+ try:
68
+ json.loads(text)
69
+ return True
70
+ except (json.JSONDecodeError, ValueError):
71
+ return False
72
+
73
+
74
+ def _is_yaml_content(lines: list[str]) -> bool:
75
+ """Heuristic: check if content looks like YAML."""
76
+ yaml_indicators = 0
77
+ for line in lines[:30]:
78
+ stripped = line.strip()
79
+ if stripped.startswith("---"):
80
+ yaml_indicators += 1
81
+ elif re.match(r"^\w[\w\s]*:\s", stripped):
82
+ yaml_indicators += 1
83
+ elif stripped.startswith("- ") and ":" in stripped:
84
+ yaml_indicators += 1
85
+ # If most non-empty lines look like YAML
86
+ non_empty = sum(1 for l in lines[:30] if l.strip())
87
+ return non_empty > 0 and yaml_indicators / non_empty > 0.6
88
+
89
+
90
+ def detect_file_type(filepath: Path) -> str:
91
+ """Classify a file as 'natural_language', 'code', 'config', or 'unknown'.
92
+
93
+ Returns:
94
+ One of: 'natural_language', 'code', 'config', 'unknown'
95
+ """
96
+ ext = filepath.suffix.lower()
97
+ name = filepath.name.lower()
98
+
99
+ # Known code filenames win over any extension rule
100
+ if name in KNOWN_CODE_FILENAMES:
101
+ return "code"
102
+
103
+ # A bare dotfile carries its whole name where pathlib expects a suffix, so
104
+ # `Path(".env").suffix` is `""` and every table below was skipped. The file
105
+ # then reached the extensionless content sniffer, which only recognises
106
+ # brace-and-quote code — so `.env`, `.gitignore` and `.editorconfig` all
107
+ # came back `natural_language` and `/caveman-compress .gitignore` shipped
108
+ # the bytes to the configured provider and rewrote the file in place.
109
+ # Resolve the name against the tables, and treat anything unrecognised as
110
+ # config rather than prose: a dotfile is an rc/config file by convention,
111
+ # and guessing wrong is destructive in both directions at once. Guessing
112
+ # "config" only costs a `Skipping` line on a file that is left untouched.
113
+ if not ext and name.startswith(".") and name not in {".", ".."}:
114
+ if name in PROSE_DOTFILES or name in COMPRESSIBLE_EXTENSIONS:
115
+ return "natural_language"
116
+ if name in SKIP_EXTENSIONS:
117
+ ext = name # fall through to the shared config/code split below
118
+ else:
119
+ return "config"
120
+
121
+ # Extension-based classification
122
+ if ext in COMPRESSIBLE_EXTENSIONS:
123
+ return "natural_language"
124
+ if ext in SKIP_EXTENSIONS:
125
+ return "code" if ext not in CONFIG_EXTENSIONS else "config"
126
+
127
+ # Extensionless files (like CLAUDE.md, TODO) — check content
128
+ if not ext:
129
+ try:
130
+ text = filepath.read_text(encoding="utf-8", errors="ignore")
131
+ except (OSError, PermissionError):
132
+ return "unknown"
133
+
134
+ lines = text.splitlines()[:50]
135
+
136
+ # Shebang means executable script, never prose
137
+ if text.startswith("#!"):
138
+ return "code"
139
+
140
+ if _is_json_content(text[:10000]):
141
+ return "config"
142
+ if _is_yaml_content(lines):
143
+ return "config"
144
+
145
+ code_lines = sum(1 for l in lines if l.strip() and _is_code_line(l))
146
+ non_empty = sum(1 for l in lines if l.strip())
147
+ if non_empty > 0 and code_lines / non_empty > 0.4:
148
+ return "code"
149
+
150
+ return "natural_language"
151
+
152
+ return "unknown"
153
+
154
+
155
+ def should_compress(filepath: Path) -> bool:
156
+ """Return True if the file is natural language and should be compressed."""
157
+ if not filepath.is_file():
158
+ return False
159
+ # Skip backup files
160
+ if filepath.name.endswith(".original.md"):
161
+ return False
162
+ if is_generated(filepath):
163
+ return False
164
+ return detect_file_type(filepath) == "natural_language"
165
+
166
+
167
+ GENERATED_MARKER_RE = re.compile(r"\bgenerated by\b|@generated\b", re.IGNORECASE)
168
+
169
+
170
+ def is_generated(filepath: Path) -> bool:
171
+ """True when line 1 says the file is generated. Its generator rewrites it,
172
+ so compressing it only spends tokens on text about to be replaced (#1350)."""
173
+ try:
174
+ with filepath.open(encoding="utf-8", errors="replace") as handle:
175
+ first_line = handle.readline(512)
176
+ except OSError:
177
+ return False
178
+ return bool(GENERATED_MARKER_RE.search(first_line))
179
+
180
+
181
+ if __name__ == "__main__":
182
+ import sys
183
+
184
+ if len(sys.argv) < 2:
185
+ print("Usage: python detect.py <file1> [file2] ...")
186
+ sys.exit(1)
187
+
188
+ for path_str in sys.argv[1:]:
189
+ p = Path(path_str).resolve()
190
+ file_type = detect_file_type(p)
191
+ compress = should_compress(p)
192
+ print(f" {p.name:30s} type={file_type:20s} compress={compress}")
@@ -0,0 +1,440 @@
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)`]+") # a backtick is never part of a URL
7
+ FENCE_OPEN_REGEX = re.compile(r"^(\s{0,3})(`{3,}|~{3,})(.*)$")
8
+
9
+ # A line that is nothing but a fence marker plus an optional info string, at ANY
10
+ # indentation. Used ONLY to scrub leaked markers before inline-code pairing (see
11
+ # extract_inline_codes) — never for block extraction.
12
+ #
13
+ # Widening FENCE_OPEN_REGEX itself to `\s*` looks like the obvious fix for #820
14
+ # and is a net regression: a lone indented ``` (the natural way to SHOW a fence
15
+ # inside prose) then opens a block that runs to EOF, swallowing real code blocks
16
+ # and silently removing their inline spans from validation. That turns a
17
+ # false-failure bug into a false-PASS bug, and a false PASS overwrites the
18
+ # user's file with unvalidated output.
19
+ FENCE_MARKER_LINE_REGEX = re.compile(r"^\s*(?:`{3,}|~{3,})[^`~]*$")
20
+
21
+ # Cap on how much of a lost/added span is echoed in an error message. Unpaired
22
+ # backticks can make a "span" hundreds of characters of prose; printing it whole
23
+ # is what made #820's failures undiagnosable.
24
+ MAX_REPORTED_SPAN = 60
25
+ HEADING_REGEX = re.compile(r"^(#{1,6})\s+(.*)", re.MULTILINE)
26
+ BULLET_REGEX = re.compile(r"^\s*[-*+]\s+", re.MULTILINE)
27
+ # Any list item, ordered or not. Four spaces inside a list item is the item's
28
+ # content indentation, never an indented code block.
29
+ LIST_ITEM_REGEX = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s")
30
+
31
+ # crude but effective path detection
32
+ # Requires either a path prefix (./ ../ / or drive letter) or a slash/backslash within the match
33
+ PATH_REGEX = re.compile(r"(?:\./|\.\./|/|[A-Za-z]:\\)[\w\-/\\\.]+|[\w\-\.]+[/\\][\w\-/\\\.]+")
34
+
35
+ # PATH_REGEX is crude on purpose and also matches ordinary prose pairs —
36
+ # "pros/cons", "Node/browser", "state/lifecycle". Caveman prose ADDS those
37
+ # constructions freely and dropping one breaks nothing, so only an unambiguous
38
+ # path — a leading ./ ../ / or drive letter, or a dotted filename in the last
39
+ # component — is treated as a hard loss.
40
+ DEFINITE_PATH_REGEX = re.compile(r"^(?:\./|\.\./|/|[A-Za-z]:\\)|[^/\\]*\.[A-Za-z0-9]{1,8}$")
41
+
42
+
43
+ class ValidationResult:
44
+ def __init__(self):
45
+ self.is_valid = True
46
+ self.errors = []
47
+ self.warnings = []
48
+
49
+ def add_error(self, msg):
50
+ self.is_valid = False
51
+ self.errors.append(msg)
52
+
53
+ def add_warning(self, msg):
54
+ self.warnings.append(msg)
55
+
56
+
57
+ def read_file(path: Path) -> str:
58
+ return path.read_text(encoding="utf-8")
59
+
60
+
61
+ # ---------- Extractors ----------
62
+
63
+
64
+ def extract_headings(text):
65
+ return [(level, title.strip()) for level, title in HEADING_REGEX.findall(text)]
66
+
67
+
68
+ def extract_code_blocks(text):
69
+ """Line-based fenced code block extractor.
70
+
71
+ Handles ``` and ~~~ fences with variable length (CommonMark: closing
72
+ fence must use same char and be at least as long as opening). Supports
73
+ nested fences (e.g. an outer 4-backtick block wrapping inner 3-backtick
74
+ content).
75
+
76
+ Merges fenced and indented blocks by their DOCUMENT POSITION, not by
77
+ type. validate_code_blocks compares this list positionally (c1 != c2),
78
+ so a type-grouped return (all fenced, then all indented) makes two
79
+ blocks that swapped RELATIVE order in the document produce the same
80
+ list on both sides: the comparison passes while the invariant it
81
+ exists to check (block order preserved) has actually been violated.
82
+ """
83
+ blocks = []
84
+ lines = text.split("\n")
85
+ i = 0
86
+ n = len(lines)
87
+ while i < n:
88
+ m = FENCE_OPEN_REGEX.match(lines[i])
89
+ if not m:
90
+ i += 1
91
+ continue
92
+ start = i
93
+ fence_char = m.group(2)[0]
94
+ fence_len = len(m.group(2))
95
+ open_line = lines[i]
96
+ block_lines = [open_line]
97
+ i += 1
98
+ closed = False
99
+ while i < n:
100
+ close_m = FENCE_OPEN_REGEX.match(lines[i])
101
+ if (
102
+ close_m
103
+ and close_m.group(2)[0] == fence_char
104
+ and len(close_m.group(2)) >= fence_len
105
+ and close_m.group(3).strip() == ""
106
+ ):
107
+ block_lines.append(lines[i])
108
+ closed = True
109
+ i += 1
110
+ break
111
+ block_lines.append(lines[i])
112
+ i += 1
113
+ if closed:
114
+ blocks.append((start, "\n".join(block_lines)))
115
+ # Unclosed fences are silently skipped — they indicate malformed markdown
116
+ # and including them would cause false-positive validation failures.
117
+ ordered = sorted(blocks + extract_indented_code_blocks(text), key=lambda pair: pair[0])
118
+ return [block_text for _, block_text in ordered]
119
+
120
+
121
+ def extract_indented_code_blocks(text):
122
+ """CommonMark indented code blocks — 4-space-indented runs outside any fence.
123
+
124
+ Without these, ` kubectl delete pod --all -n prod` was prose to the
125
+ validator: "code blocks preserved exactly" compared empty to empty and
126
+ PASSED while the compressor rewrote the command to
127
+ `kubectl delete pod -n dev`. A clean pass on a mutated destructive command
128
+ is the worst failure this tool has, because it overwrites the user's file.
129
+
130
+ Deliberately conservative about lists: inside a list item, four spaces are
131
+ the item's content indentation, not code, and nested bullets are ordinary
132
+ prose the compressor SHOULD rewrite. A run is only treated as code when the
133
+ document is not inside a list and the run is preceded by a blank line — so
134
+ this adds detections, it never turns existing passes into false failures.
135
+
136
+ Returns (start_line, text) pairs rather than bare text: extract_code_blocks
137
+ needs each block's document position to merge it with fenced blocks in
138
+ order (see that function's docstring).
139
+ """
140
+ blocks = []
141
+ lines = text.split("\n")
142
+ fenced = set()
143
+ for block in extract_fenced_spans(lines):
144
+ fenced.update(block)
145
+ in_list = False
146
+ previous_blank = True
147
+ i = 0
148
+ n = len(lines)
149
+ while i < n:
150
+ line = lines[i]
151
+ stripped = line.strip()
152
+ if i in fenced:
153
+ in_list, previous_blank = in_list, False
154
+ i += 1
155
+ continue
156
+ if not stripped:
157
+ previous_blank = True
158
+ i += 1
159
+ continue
160
+ indent = len(line) - len(line.lstrip(" \t"))
161
+ if LIST_ITEM_REGEX.match(line):
162
+ in_list = True
163
+ elif indent == 0:
164
+ in_list = False
165
+ if not in_list and previous_blank and indent >= 4:
166
+ start = i
167
+ run = []
168
+ while i < n and i not in fenced:
169
+ current = lines[i]
170
+ if not current.strip():
171
+ # A blank line continues an indented block only if more
172
+ # indented content follows.
173
+ lookahead = i + 1
174
+ while lookahead < n and not lines[lookahead].strip():
175
+ lookahead += 1
176
+ if lookahead < n and lookahead not in fenced and \
177
+ len(lines[lookahead]) - len(lines[lookahead].lstrip(" \t")) >= 4:
178
+ run.extend(lines[i:lookahead])
179
+ i = lookahead
180
+ continue
181
+ break
182
+ if len(current) - len(current.lstrip(" \t")) < 4:
183
+ break
184
+ run.append(current)
185
+ i += 1
186
+ if run:
187
+ blocks.append((start, "\n".join(run)))
188
+ previous_blank = False
189
+ continue
190
+ previous_blank = False
191
+ i += 1
192
+ return blocks
193
+
194
+
195
+ def extract_fenced_spans(lines):
196
+ """Line-index ranges covered by fenced blocks, so indented-code detection
197
+ never reaches inside one."""
198
+ spans = []
199
+ i = 0
200
+ n = len(lines)
201
+ while i < n:
202
+ m = FENCE_OPEN_REGEX.match(lines[i])
203
+ if not m:
204
+ i += 1
205
+ continue
206
+ fence_char = m.group(2)[0]
207
+ fence_len = len(m.group(2))
208
+ start = i
209
+ i += 1
210
+ while i < n:
211
+ close_m = FENCE_OPEN_REGEX.match(lines[i])
212
+ if (
213
+ close_m
214
+ and close_m.group(2)[0] == fence_char
215
+ and len(close_m.group(2)) >= fence_len
216
+ and close_m.group(3).strip() == ""
217
+ ):
218
+ i += 1
219
+ break
220
+ i += 1
221
+ spans.append(range(start, i))
222
+ return spans
223
+
224
+
225
+ # Sentence punctuation right after a URL or path ("see docs/a.md.") is matched
226
+ # by both regexes but is not part of it; compression often moves it.
227
+ TRAILING_PUNCTUATION = ".,;:!?"
228
+
229
+
230
+ def extract_urls(text):
231
+ return {url.rstrip(TRAILING_PUNCTUATION) for url in URL_REGEX.findall(text)}
232
+
233
+
234
+ def extract_paths(text):
235
+ return {path.rstrip(TRAILING_PUNCTUATION) for path in PATH_REGEX.findall(text)}
236
+
237
+
238
+ def count_bullets(text):
239
+ return len(BULLET_REGEX.findall(text))
240
+
241
+
242
+ def extract_inline_codes(text):
243
+ """Backtick-delimited inline spans, with fenced code blocks stripped first.
244
+
245
+ Previously used a column-0-anchored regex to strip fences, which misses
246
+ fences indented 1-3 spaces (valid CommonMark). Reuse extract_code_blocks
247
+ (FENCE_OPEN_REGEX-based, indentation-aware) instead so an indented fence's
248
+ body backticks don't leak into inline-code pairing.
249
+
250
+ Any fence-marker line that survives that pass is then blanked (#820). A
251
+ fence indented 4+ spaces — what you get from showing an example inside a
252
+ bullet — is not matched by FENCE_OPEN_REGEX, so extract_code_blocks does
253
+ not remove it and its OWN backticks used to leak in and shift the pairing
254
+ of every following span, making the file permanently uncompressible.
255
+ Blanking just the marker lines fixes that without removing any prose, and
256
+ cannot run away the way a widened fence opener does.
257
+
258
+ The span pattern deliberately still spans newlines. CommonMark permits a
259
+ line ending inside a code span and hard-wrapped markdown produces them, so
260
+ a single-line pattern silently drops real spans — which downgrades a
261
+ deleted or mutated span from error to PASS. Long/garbled spans are a
262
+ presentation problem, handled by truncating in the error message instead.
263
+ """
264
+ text_without_fences = text
265
+ for block in extract_code_blocks(text):
266
+ text_without_fences = text_without_fences.replace(block, "", 1)
267
+ text_without_fences = "\n".join(
268
+ "" if FENCE_MARKER_LINE_REGEX.match(line) else line
269
+ for line in text_without_fences.split("\n")
270
+ )
271
+ # Run-aware pairing (CommonMark): a span opens with a backtick run and
272
+ # closes with an equal-length run. A mid-line ``` in prose ("inside a
273
+ # ```diff fence") has no equal closer, so it matches nothing — instead of
274
+ # its trailing backtick shifting the pairing of every following span.
275
+ # The opener is the WHOLE run (a lookahead refuses one more backtick), so a lone ``` can never
276
+ # shrink to a single backtick and pair with the next span. The content may
277
+ # hold a run of a different length (``a`b``), so it is "anything, lazily"
278
+ # up to the first equal run, not "anything but a backtick"; DOTALL keeps
279
+ # hard-wrapped spans in the comparison set.
280
+ return [
281
+ m.group(2)
282
+ # \x60 is a backtick: spelled out so no "!" sits before a literal one.
283
+ for m in re.finditer(r"(?<!\x60)(\x60+)(?!\x60)(.+?)(?<!\x60)\1(?!\x60)", text_without_fences, re.DOTALL)
284
+ ]
285
+
286
+
287
+ # ---------- Validators ----------
288
+
289
+
290
+ def validate_headings(orig, comp, result):
291
+ h1 = extract_headings(orig)
292
+ h2 = extract_headings(comp)
293
+
294
+ # Changed heading TEXT is an error, not a warning. Every in-document anchor
295
+ # link points at a heading's slug, so renaming "# Configuration Options" to
296
+ # "# Config" silently breaks all of them — and SKILL.md and CLAUDE.md both
297
+ # state headings are preserved. Only counts used to gate the overwrite, so
298
+ # a run that renamed every heading reported "Validation passed". A level-only
299
+ # change keeps every slug intact and stays a warning.
300
+ if len(h1) != len(h2):
301
+ result.add_error(f"Heading count mismatch: {len(h1)} vs {len(h2)}")
302
+ return
303
+
304
+ t1 = [text for _, text in h1]
305
+ t2 = [text for _, text in h2]
306
+ if t1 != t2:
307
+ lost = [t for t in t1 if t not in t2]
308
+ added = [t for t in t2 if t not in t1]
309
+ result.add_error(f"Heading text/order changed: lost={lost}, added={added}")
310
+ elif h1 != h2:
311
+ # Same text, different level. The outline moved but no anchor broke —
312
+ # slugs come from the text, so links still resolve.
313
+ result.add_warning("Heading levels changed")
314
+
315
+
316
+ def validate_code_blocks(orig, comp, result):
317
+ c1 = extract_code_blocks(orig)
318
+ c2 = extract_code_blocks(comp)
319
+
320
+ if c1 != c2:
321
+ result.add_error("Code blocks not preserved exactly")
322
+
323
+
324
+ def validate_urls(orig, comp, result):
325
+ u1 = extract_urls(orig)
326
+ u2 = extract_urls(comp)
327
+
328
+ if u1 != u2:
329
+ result.add_error(f"URL mismatch: lost={u1 - u2}, added={u2 - u1}")
330
+
331
+
332
+ def validate_paths(orig, comp, result):
333
+ """File paths are preserved — an error, never a warning.
334
+
335
+ This validator never called add_error at all, so a compressed file that had
336
+ dropped `src/hooks/caveman-config.js` still reported "Validation passed" and
337
+ the in-place overwrite stood. SKILL.md and CLAUDE.md both promise paths
338
+ survive compression; nothing enforced it.
339
+ """
340
+ p1 = extract_paths(orig)
341
+ p2 = extract_paths(comp)
342
+ lost = p1 - p2
343
+ added = p2 - p1
344
+
345
+ definite = {p for p in lost if DEFINITE_PATH_REGEX.search(p)}
346
+ if definite:
347
+ result.add_error(f"File paths lost: {sorted(definite)}")
348
+ if (lost - definite) or added:
349
+ result.add_warning(f"Path mismatch: lost={sorted(lost)}, added={sorted(added)}")
350
+
351
+
352
+ def validate_bullets(orig, comp, result):
353
+ b1 = count_bullets(orig)
354
+ b2 = count_bullets(comp)
355
+
356
+ if b1 == 0:
357
+ return
358
+
359
+ diff = abs(b1 - b2) / b1
360
+
361
+ if diff > 0.15:
362
+ result.add_warning(f"Bullet count changed too much: {b1} -> {b2}")
363
+
364
+
365
+ def validate_inline_codes(orig, comp, result):
366
+ def _render_spans(spans):
367
+ """Render spans for an error message, truncated and newline-escaped.
368
+
369
+ A span may legitimately contain newlines, and an unpaired backtick can
370
+ make one hundreds of characters of prose. Printing those whole is what
371
+ made #820's failures undiagnosable — but the fix belongs here, in
372
+ presentation, not in what counts as a span.
373
+ """
374
+ out = []
375
+ for span in sorted(spans):
376
+ flat = span.replace("\n", "\\n")
377
+ if len(flat) > MAX_REPORTED_SPAN:
378
+ flat = flat[:MAX_REPORTED_SPAN] + "…"
379
+ out.append(repr(flat))
380
+ return "{" + ", ".join(out) + "}"
381
+
382
+ c1 = Counter(extract_inline_codes(orig))
383
+ c2 = Counter(extract_inline_codes(comp))
384
+
385
+ if c1 != c2:
386
+ lost = set(c1.keys()) - set(c2.keys())
387
+ added = set(c2.keys()) - set(c1.keys())
388
+ for code, count in c1.items():
389
+ if code in c2 and c2[code] < count:
390
+ lost.add(f"{code} (lost {count - c2[code]} of {count} occurrences)")
391
+ if lost:
392
+ result.add_error(f"Inline code lost: {_render_spans(lost)}")
393
+ if added:
394
+ result.add_warning(f"Inline code added: {_render_spans(added)}")
395
+
396
+
397
+ # ---------- Main ----------
398
+
399
+
400
+ def validate(original_path: Path, compressed_path: Path) -> ValidationResult:
401
+ result = ValidationResult()
402
+
403
+ orig = read_file(original_path)
404
+ comp = read_file(compressed_path)
405
+
406
+ validate_headings(orig, comp, result)
407
+ validate_code_blocks(orig, comp, result)
408
+ validate_urls(orig, comp, result)
409
+ validate_paths(orig, comp, result)
410
+ validate_bullets(orig, comp, result)
411
+ validate_inline_codes(orig, comp, result)
412
+
413
+ return result
414
+
415
+
416
+ # ---------- CLI ----------
417
+
418
+ if __name__ == "__main__":
419
+ import sys
420
+
421
+ if len(sys.argv) != 3:
422
+ print("Usage: python validate.py <original> <compressed>")
423
+ sys.exit(1)
424
+
425
+ orig = Path(sys.argv[1]).resolve()
426
+ comp = Path(sys.argv[2]).resolve()
427
+
428
+ res = validate(orig, comp)
429
+
430
+ print(f"\nValid: {res.is_valid}")
431
+
432
+ if res.errors:
433
+ print("\nErrors:")
434
+ for e in res.errors:
435
+ print(f" - {e}")
436
+
437
+ if res.warnings:
438
+ print("\nWarnings:")
439
+ for w in res.warnings:
440
+ print(f" - {w}")