gunk-dev/the-valley

prose-format.sh

sourceac8c5f17256cmain's published tip history
12.6 KiB
1# shellcheck shell=bash
2# Paths and fixtures come from the derivation environment.
3# shellcheck disable=SC2154
4# The flags are one string so the formatter app and this check cannot
5# drift; split it back into argv.
6read -ra fmtArgs <<< "$proseFmtArgs"
7
8# The tree the check reads: the markdown files and prettier's configuration,
9# and the link targets that are neither, each an empty file or directory at
10# its path.
11tree="$TMPDIR/tree"
12cp -r "$markdown" "$tree"
13chmod -R u+w "$tree"
14cd "$tree" || exit 1
15while IFS= read -r path; do
16 case "$path" in
17 */) mkdir -p "$path" ;;
18 *)
19 mkdir -p "$(dirname "$path")"
20 touch "$path"
21 ;;
22 esac
23done < "$linkTargetsPath"
24find . -name '*.md' -print0 | xargs -0 --no-run-if-empty \
25 prettier "${fmtArgs[@]}" --check
26
27python3 - <<'PY'
28import glob
29import os
30import re
31import sys
32
33LINK = re.compile(r"\]\(\s*([^)\s]+)(?:\s+\"[^\"]*\")?\s*\)")
34INLINE_CODE = re.compile(r"(`+)[^`\n]*?\1")
35FENCE_OPEN = re.compile(r"^\s*(`{3,}|~{3,})")
36HEADING = re.compile(r"^#{1,6}\s+(.*?)\s*#*?\s*$")
37MD_LINK_IN_HEADING = re.compile(r"\[([^\]]*)\]\([^)]*\)")
38NOT_IN_SLUG = re.compile(r"[^\w\s-]")
39EXTERNAL = re.compile(r"^[a-zA-Z][a-zA-Z0-9+.-]*:")
40
41
42def outside_fences(lines):
43 fence = None
44 for number, line in enumerate(lines, start=1):
45 if fence is None:
46 m = FENCE_OPEN.match(line)
47 if m:
48 fence = m.group(1)
49 else:
50 yield number, line
51 else:
52 if re.match(rf"^\s*{fence[0]}{{{len(fence)},}}\s*$", line):
53 fence = None
54
55
56def anchors(path, cache):
57 if path in cache:
58 return cache[path]
59 found, counts = set(), {}
60 with open(path, encoding="utf-8") as handle:
61 for _, line in outside_fences(handle.read().splitlines()):
62 heading = HEADING.match(line)
63 if not heading:
64 continue
65 title = MD_LINK_IN_HEADING.sub(r"\1", heading.group(1))
66 title = title.replace("`", "").lower()
67 slug = NOT_IN_SLUG.sub("", title).strip().replace(" ", "-")
68 counts[slug] = counts.get(slug, 0) + 1
69 found.add(slug if counts[slug] == 1 else f"{slug}-{counts[slug] - 1}")
70 cache[path] = found
71 return found
72
73
74findings = []
75cache = {}
76documents = [p for p in ["README.md", "AGENTS.md"] if os.path.exists(p)] + sorted(
77 glob.glob("docs/*.md")
78)
79
80for path in documents:
81 with open(path, encoding="utf-8") as handle:
82 lines = handle.read().splitlines()
83 for number, line in outside_fences(lines):
84 prose = INLINE_CODE.sub(" ", line)
85 for target in LINK.findall(prose):
86 if EXTERNAL.match(target):
87 continue
88 relative, has_hash, anchor = target.partition("#")
89 if not relative:
90 resolved = path
91 else:
92 resolved = os.path.normpath(
93 os.path.join(os.path.dirname(path), relative)
94 )
95 if resolved == ".." or resolved.startswith("../"):
96 findings.append(
97 f"{path}:{number}: {target} points outside the repository"
98 )
99 continue
100 if not os.path.exists(resolved):
101 findings.append(f"{path}:{number}: {target} does not exist")
102 continue
103 if has_hash:
104 if not anchor:
105 findings.append(
106 f"{path}:{number}: {target} has an empty heading anchor"
107 )
108 elif not os.path.isfile(resolved) or not resolved.endswith(".md"):
109 findings.append(
110 f"{path}:{number}: {target} names a heading in non-markdown target {resolved}"
111 )
112 elif anchor not in anchors(resolved, cache):
113 findings.append(
114 f"{path}:{number}: {target} names no heading in {resolved}"
115 )
116
117if findings:
118 print(
119 f"prose-format: {len(findings)} broken link(s) or anchor(s):",
120 file=sys.stderr,
121 )
122 for item in findings:
123 print(f" {item}", file=sys.stderr)
124 sys.exit(1)
125PY
126
127# The style lint: the rules of AGENTS.md's style section that a pattern can
128# catch. It prints one finding per rule broken on a line, as
129# file:line: rule: what it found, and exits 1 if it printed any. A line
130# allows one rule with the marker <!-- prose-allow: rule --> outside inline
131# code, and a marker that allows nothing is itself a finding.
132cat > "$TMPDIR/style.awk" <<'AWK'
133BEGIN {
134 split("line-number narration vocabulary", names, " ")
135 for (i in names) rules[names[i]]
136 marker = "<!--[[:space:]]*prose-allow:[^>]*-->"
137 # A source path is one with a directory, or a file name with an
138 # extension of a source file in this tree. A host and port or a
139 # timestamp is neither.
140 seg = "[[:alnum:]_.-]+"
141 path = seg "(/" seg ")+|" seg "\\.(go|sh|bash|nix|cue|py|md|txt|json|ya?ml|toml)"
142 cite = "(^|[^[:alnum:]_./-])(" path "):[0-9]+(-[0-9]+)?([^0-9]|$)"
143}
144
145function finding(rule, message) {
146 if (rule in allowed) {
147 used[rule]
148 return
149 }
150 printf "%s:%d: %s: %s\n", FILENAME, FNR, rule, message
151 failed = 1
152}
153
154# The start of the first match of re in s that ends after its first skip
155# characters, which are the end of the line before, or 0. RLENGTH is the
156# match's length.
157function find(s, re, skip, start) {
158 for (start = 0; match(substr(s, start + 1), re); start += RSTART)
159 if (start + RSTART + RLENGTH - 1 > skip)
160 return start + RSTART
161 return 0
162}
163
164# A word rule, matched case-insensitively when fold is set.
165function word(rule, re, why, fold, at) {
166 if (at = find(fold ? low : s, re, skip))
167 finding(rule, "\"" substr(s, at, RLENGTH) "\": " why)
168}
169
170FNR == 1 { fence = ""; tail = "" }
171
172{
173 delete allowed
174 delete used
175 code = $0
176 gsub(/`[^`]*`/, "", code)
177 while (match(code, marker)) {
178 rule = substr(code, RSTART, RLENGTH)
179 code = substr(code, RSTART + RLENGTH)
180 sub(/^<!--[[:space:]]*prose-allow:[[:space:]]*/, "", rule)
181 sub(/[[:space:]]*-->$/, "", rule)
182 if (rule in rules)
183 allowed[rule]
184 else
185 finding("allowance", "prose-allow names no rule \"" rule "\"; the rules are line-number, narration and vocabulary")
186 }
187 if (match($0, "^[[:space:]]*(([-*+>]|[0-9]+[.)])[[:space:]]+)?" marker))
188 finding("allowance", "a marker that begins a line begins an HTML block; put it after a word")
189 text = $0
190 gsub(marker, " ", text)
191
192 infence = fence != ""
193 if (!infence && match($0, /^[[:space:]]*(```+|~~~+)/)) {
194 fence = substr($0, RSTART, RLENGTH)
195 sub(/^[[:space:]]*/, "", fence)
196 infence = 1
197 } else if (infence && $0 ~ ("^[[:space:]]*" substr(fence, 1, 1) "{" length(fence) ",}[[:space:]]*$"))
198 fence = ""
199
200 if (match(text, cite)) {
201 found = substr(text, RSTART, RLENGTH)
202 sub(/^[^[:alnum:]_.\/-]/, "", found)
203 sub(/[^0-9]$/, "", found)
204 finding("line-number", "\"" found "\": cite the file or a name in it, not a line")
205 }
206
207 # Fenced code is exempt from the word rules. A phrase may wrap, so each
208 # line is read after the last two words of the line before it.
209 if (!infence) {
210 s = text
211 sub(/^[[:space:]]+/, "", s)
212 s = tail " " s
213 skip = length(tail) + 1
214 low = tolower(s)
215 word("vocabulary", "\\<ow(e|es|ed)\\>", "a change requires checks", 1)
216 word("vocabulary", "\\<pull requests?\\>", "a valley change is a change", 1)
217 word("vocabulary", "\\<PRs?\\>", "a valley change is a change", 0)
218 word("vocabulary", "\\<knowledge[ -]?bases?\\>", "a plan item is a knot in the plan graph", 1)
219 word("vocabulary", "\\<tickets?\\>", "a plan item is a knot in the plan graph", 1)
220 word("narration", "\\<(no longer|previously|was changed to|has been replaced|is now)\\>", "describe what HEAD does today", 1)
221 word("narration", "\\<((it|this|that|these|those|they|we|which|who) used to|used to be)\\>", "describe what HEAD does today", 1)
222 }
223 tail = ""
224 if (!infence && match(text, /([^[:space:]]+[[:space:]]+)?[^[:space:]]+[[:space:]]*$/)) {
225 tail = substr(text, RSTART, RLENGTH)
226 sub(/[[:space:]]+$/, "", tail)
227 }
228
229 for (i = 1; i in names; i++)
230 if (names[i] in allowed && !(names[i] in used))
231 finding("allowance", "allows " names[i] ", but nothing on this line breaks it")
232}
233
234END { exit failed }
235AWK
236style() { gawk -f "$TMPDIR/style.awk" "$@"; }
237
238# The lint's own fixtures. A doc that breaks each rule fails with exactly
239# these findings, and the same doc with an allowance on each line passes.
240fixtures="$TMPDIR/style"
241mkdir -p "$fixtures"
242cd "$fixtures" || exit 1
243cat > broken.md <<'EOF'
244A change never owes a check, and nothing is owed.
245Open a PR, or a Pull Request, against main.
246Track it in the knowledgebase as a ticket.
247The rule is in status/ready.go:146-165.
248The verb is at `bin/valley:57`.
249See [the hook](../valleyhook/policy.go:12) for the rest.
250The hook no longer reads the tree.
251It previously read it, and it is now a script.
252The verb was changed to print JSON.
253The flag has been replaced.
254The check used to be slow, and it used to time out.
255- A phrase can wrap: the hook is no
256 longer a script.
257
258```sh
259valley checks # see status/ready.go:146
260```
261EOF
262cat > broken.want <<'EOF'
263broken.md:1: vocabulary: "owes": a change requires checks
264broken.md:2: vocabulary: "Pull Request": a valley change is a change
265broken.md:2: vocabulary: "PR": a valley change is a change
266broken.md:3: vocabulary: "knowledgebase": a plan item is a knot in the plan graph
267broken.md:3: vocabulary: "ticket": a plan item is a knot in the plan graph
268broken.md:4: line-number: "status/ready.go:146-165": cite the file or a name in it, not a line
269broken.md:5: line-number: "bin/valley:57": cite the file or a name in it, not a line
270broken.md:6: line-number: "../valleyhook/policy.go:12": cite the file or a name in it, not a line
271broken.md:7: narration: "no longer": describe what HEAD does today
272broken.md:8: narration: "previously": describe what HEAD does today
273broken.md:9: narration: "was changed to": describe what HEAD does today
274broken.md:10: narration: "has been replaced": describe what HEAD does today
275broken.md:11: narration: "used to be": describe what HEAD does today
276broken.md:13: narration: "no longer": describe what HEAD does today
277broken.md:16: line-number: "status/ready.go:146": cite the file or a name in it, not a line
278EOF
279if style broken.md > broken.got; then
280 echo "prose-format: the style lint passed a doc that breaks every rule" >&2
281 exit 1
282fi
283diff -u broken.want broken.got >&2 || {
284 echo "prose-format: the style lint's findings on broken.md are not the expected ones" >&2
285 exit 1
286}
287# allowed.md is broken.md with a marker for each rule a line breaks.
288gawk -F': ' '
289 NR == FNR {
290 split($1, at, ":")
291 if (!((at[2], $2) in seen))
292 allow[at[2]] = allow[at[2]] " <!-- prose-allow: " $2 " -->"
293 seen[at[2], $2]
294 next
295 }
296 { print $0 allow[FNR] }' broken.want broken.md > allowed.md
297style allowed.md >&2 || {
298 echo "prose-format: the style lint failed broken.md with an allowance on each line" >&2
299 exit 1
300}
301
302# What the rules must pass: the words and the narration in a fenced code
303# block, a marker quoted in inline code, an address, a timestamp, a hash,
304# and "used to" that is not narration.
305cat > clean.md <<'EOF'
306Allow a word with `<!-- prose-allow: vocabulary -->` on its line.
307The bus listens on nats://127.0.0.1:4222, and the run began at 2026-10-14T21:30.
308A version is git-sha1:2222222222222222222222222222222222222222.
309The verifier keys used to verify a landing are the integrator's.
310
311~~~
312A PR owes a ticket, and the hook no longer reads the tree.
313~~~
314EOF
315style clean.md >&2 || {
316 echo "prose-format: the style lint failed clean.md, which breaks no rule" >&2
317 exit 1
318}
319
320# A marker that allows a rule the line does not break, names no rule, or
321# begins a line is a finding of its own.
322cat > markers.md <<'EOF'
323A change requires checks. <!-- prose-allow: vocabulary -->
324A change has a version. <!-- prose-allow: words -->
325<!-- prose-allow: vocabulary --> A PR is a change.
326EOF
327cat > markers.want <<'EOF'
328markers.md:1: allowance: allows vocabulary, but nothing on this line breaks it
329markers.md:2: allowance: prose-allow names no rule "words"; the rules are line-number, narration and vocabulary
330markers.md:3: allowance: a marker that begins a line begins an HTML block; put it after a word
331EOF
332if style markers.md > markers.got; then
333 echo "prose-format: the style lint passed a marker that allows nothing" >&2
334 exit 1
335fi
336diff -u markers.want markers.got >&2 || {
337 echo "prose-format: the style lint's findings on markers.md are not the expected ones" >&2
338 exit 1
339}
340
341# The tree's own docs: the same documents the link check reads.
342cd "$tree" || exit 1
343style README.md AGENTS.md docs/*.md > "$TMPDIR/style.got" || {
344 echo "prose-format: $(wc -l < "$TMPDIR/style.got") style finding(s):" >&2
345 sed 's/^/ /' "$TMPDIR/style.got" >&2
346 exit 1
347}
348
349touch "$out"