gunk-dev/the-valley

prose-format.sh

sourced2a8f94f1870main's published tip history
17.5 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 a finding for each pattern a line breaks, 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 provenance 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 # Where a passage came from: a date, a knot, a change or a commit
144 # given as its reason, or a person's view given as the project's. A
145 # date may carry a time.
146 date = "\\<[0-9]{4}-[0-9]{2}-[0-9]{2}(T[0-9:.]+Z?)?\\>"
147 knot = "\\<(oc|bd|ida|qn|dcr)-[0-9a-f]{7}\\>"
148 change = "\\<[k-z]{32}\\>"
149 short = "[^[:alnum:]_./:-][0-9a-f]{7,12}([^[:alnum:]_/-]|$)"
150 who = "(operator|user|maintainer|reviewer|author|planner|owner)s?"
151 some = "(the |an? )?([[:alnum:]'’]+ )?"
152 opinion = "\\<the ([[:alnum:]'’]+ )?(human )?operators? (said|says|wants|wanted|asked|decided|prefers|preferred|insisted|chose)\\>"
153 quote = "(\"|“|”)"
154 speech = "\\<(" who " (says|asks|writes)|said|asked|wrote|put it)[,:]?[[:space:]]*" quote "|" quote "[,.]?[[:space:]]+(said|says|asked|wrote|writes) " some who "\\>|\\<in " some who "'s words\\>"
155}
156
157function finding(rule, message) {
158 if (rule in allowed) {
159 used[rule]
160 return
161 }
162 printf "%s:%d: %s: %s\n", FILENAME, FNR, rule, message
163 failed = 1
164}
165
166# The start of the first match of re in s that ends after its first skip
167# characters, which are the end of the line before, or 0. RLENGTH is the
168# match's length.
169function find(s, re, skip, start) {
170 for (start = 0; match(substr(s, start + 1), re); start += RSTART)
171 if (start + RSTART + RLENGTH - 1 > skip)
172 return start + RSTART
173 return 0
174}
175
176# A word rule, matched case-insensitively when fold is set.
177function word(rule, re, why, fold, at) {
178 if (at = find(fold ? low : s, re, skip))
179 finding(rule, "\"" substr(s, at, RLENGTH) "\": " why)
180}
181
182# A short commit hash: seven to twelve hex digits, a digit and a letter
183# among them, which "defaced" and "1234567" lack. A curve name such as
184# ed25519 is not one. The space before s stands for the start of a line.
185function hash(rule, why, t, start, h) {
186 t = " " s
187 for (start = 0; match(substr(t, start + 1), short); start += RSTART) {
188 h = substr(t, start + RSTART + 1, RLENGTH - 1)
189 sub(/[^0-9a-f]$/, "", h)
190 if (start + RSTART + RLENGTH - 2 > skip && h ~ /[0-9]/ && h ~ /[a-f]/ && h !~ /^ed[0-9]+$/) {
191 finding(rule, "\"" h "\": " why)
192 return
193 }
194 }
195}
196
197# The line t as the word rules read it, after prev, the last two words of
198# the line before it.
199function reading(t, prev) {
200 s = t
201 sub(/^[[:space:]]+/, "", s)
202 s = prev " " s
203 skip = length(prev) + 1
204 low = tolower(s)
205}
206
207# The last two words of t.
208function last(t, w) {
209 if (!match(t, /([^[:space:]]+[[:space:]]+)?[^[:space:]]+[[:space:]]*$/))
210 return ""
211 w = substr(t, RSTART, RLENGTH)
212 sub(/[[:space:]]+$/, "", w)
213 return w
214}
215
216FNR == 1 { fence = ""; tail = ""; bareTail = "" }
217
218{
219 delete allowed
220 delete used
221 code = $0
222 gsub(/`[^`]*`/, "", code)
223 while (match(code, marker)) {
224 rule = substr(code, RSTART, RLENGTH)
225 code = substr(code, RSTART + RLENGTH)
226 sub(/^<!--[[:space:]]*prose-allow:[[:space:]]*/, "", rule)
227 sub(/[[:space:]]*-->$/, "", rule)
228 if (rule in rules)
229 allowed[rule]
230 else
231 finding("allowance", "prose-allow names no rule \"" rule "\"; the rules are line-number, narration, provenance and vocabulary")
232 }
233 if (match($0, "^[[:space:]]*(([-*+>]|[0-9]+[.)])[[:space:]]+)?" marker))
234 finding("allowance", "a marker that begins a line begins an HTML block; put it after a word")
235 text = $0
236 gsub(marker, " ", text)
237 # Inline code quotes a value, such as a schema's cutoff date, an
238 # example knot ID or a digest, so the provenance rules read the line
239 # without it.
240 bare = text
241 gsub(/`[^`]*`/, " ", bare)
242
243 infence = fence != ""
244 if (!infence && match($0, /^[[:space:]]*(```+|~~~+)/)) {
245 fence = substr($0, RSTART, RLENGTH)
246 sub(/^[[:space:]]*/, "", fence)
247 infence = 1
248 } else if (infence && $0 ~ ("^[[:space:]]*" substr(fence, 1, 1) "{" length(fence) ",}[[:space:]]*$"))
249 fence = ""
250
251 if (match(text, cite)) {
252 found = substr(text, RSTART, RLENGTH)
253 sub(/^[^[:alnum:]_.\/-]/, "", found)
254 sub(/[^0-9]$/, "", found)
255 finding("line-number", "\"" found "\": cite the file or a name in it, not a line")
256 }
257
258 # Fenced code is exempt from the word rules. A phrase may wrap, so each
259 # line is read after the last two words of the line before it.
260 if (!infence) {
261 reading(text, tail)
262 word("vocabulary", "\\<ow(e|es|ed)\\>", "a change requires checks", 1)
263 word("vocabulary", "\\<pull requests?\\>", "a valley change is a change", 1)
264 word("vocabulary", "\\<PRs?\\>", "a valley change is a change", 0)
265 word("vocabulary", "\\<knowledge[ -]?bases?\\>", "a plan item is a knot in the plan graph", 1)
266 word("vocabulary", "\\<tickets?\\>", "a plan item is a knot in the plan graph", 1)
267 word("narration", "\\<(no longer|previously|was changed to|has been replaced|is now)\\>", "describe what HEAD does today", 1)
268 word("narration", "\\<((it|this|that|these|those|they|we|which|who) used to|used to be)\\>", "describe what HEAD does today", 1)
269 word("narration", "\\<((was|were|has been|have been) (added|introduced)|we (added|introduced))\\>", "describe what HEAD does today", 1)
270 word("narration", "\\<(anymore|now that)\\>", "describe what HEAD does today", 1)
271 word("narration", "\\<since (commit|release|v[0-9])", "describe what HEAD does today", 1)
272 reading(bare, bareTail)
273 word("provenance", date, "a date belongs in a commit message or a knot", 0)
274 word("provenance", knot, "state the reason itself; the knot belongs in a commit message", 0)
275 word("provenance", change, "state the reason itself; the change belongs in a commit message", 0)
276 hash("provenance", "state the reason itself; the commit belongs in a commit message")
277 word("provenance", opinion, "state the position as the project's own", 1)
278 word("provenance", speech, "state the position as the project's own, not as a quote", 1)
279 }
280 tail = infence ? "" : last(text)
281 bareTail = infence ? "" : last(bare)
282
283 for (i = 1; i in names; i++)
284 if (names[i] in allowed && !(names[i] in used))
285 finding("allowance", "allows " names[i] ", but nothing on this line breaks it")
286}
287
288END { exit failed }
289AWK
290style() { gawk -f "$TMPDIR/style.awk" "$@"; }
291
292# The lint's own fixtures. A doc that breaks each rule fails with exactly
293# these findings, and the same doc with an allowance on each line passes.
294fixtures="$TMPDIR/style"
295mkdir -p "$fixtures"
296cd "$fixtures" || exit 1
297cat > broken.md <<'EOF'
298A change never owes a check, and nothing is owed.
299Open a PR, or a Pull Request, against main.
300Track it in the knowledgebase as a ticket.
301The rule is in status/ready.go:146-165.
302The verb is at `bin/valley:57`.
303See [the hook](../valleyhook/policy.go:12) for the rest.
304The hook no longer reads the tree.
305It previously read it, and it is now a script.
306The verb was changed to print JSON.
307The flag has been replaced.
308The check used to be slow, and it used to time out.
309- A phrase can wrap: the hook is no
310 longer a script.
311The flag was added for speed.
312The verb was introduced with it.
313We added a check, so it is not slow anymore.
314Now that the hook reads refs, the cap holds since v2.
315The cap is 64 since commit 4ae651e.
316It landed on 2026-11-05 (knot oc-03b6f8c).
317It fixes [the bug](../archive/.the-valley/bugs/bd-75c8721-replace-refs.md).
318Change kqxmrvtzkqxmrvtzkqxmrvtzkqxmrvtz was the fix.
319The operator wants one worker, and the operator
320decided to keep it.
321As the reviewer wrote, "keep it small".
322"Keep it small," said the author.
323
324```sh
325valley checks # see status/ready.go:146
326```
327EOF
328cat > broken.want <<'EOF'
329broken.md:1: vocabulary: "owes": a change requires checks
330broken.md:2: vocabulary: "Pull Request": a valley change is a change
331broken.md:2: vocabulary: "PR": a valley change is a change
332broken.md:3: vocabulary: "knowledgebase": a plan item is a knot in the plan graph
333broken.md:3: vocabulary: "ticket": a plan item is a knot in the plan graph
334broken.md:4: line-number: "status/ready.go:146-165": cite the file or a name in it, not a line
335broken.md:5: line-number: "bin/valley:57": cite the file or a name in it, not a line
336broken.md:6: line-number: "../valleyhook/policy.go:12": cite the file or a name in it, not a line
337broken.md:7: narration: "no longer": describe what HEAD does today
338broken.md:8: narration: "previously": describe what HEAD does today
339broken.md:9: narration: "was changed to": describe what HEAD does today
340broken.md:10: narration: "has been replaced": describe what HEAD does today
341broken.md:11: narration: "used to be": describe what HEAD does today
342broken.md:13: narration: "no longer": describe what HEAD does today
343broken.md:14: narration: "was added": describe what HEAD does today
344broken.md:15: narration: "was introduced": describe what HEAD does today
345broken.md:16: narration: "We added": describe what HEAD does today
346broken.md:16: narration: "anymore": describe what HEAD does today
347broken.md:17: narration: "Now that": describe what HEAD does today
348broken.md:17: narration: "since v2": describe what HEAD does today
349broken.md:18: narration: "since commit": describe what HEAD does today
350broken.md:18: provenance: "4ae651e": state the reason itself; the commit belongs in a commit message
351broken.md:19: provenance: "2026-11-05": a date belongs in a commit message or a knot
352broken.md:19: provenance: "oc-03b6f8c": state the reason itself; the knot belongs in a commit message
353broken.md:20: provenance: "bd-75c8721": state the reason itself; the knot belongs in a commit message
354broken.md:21: provenance: "kqxmrvtzkqxmrvtzkqxmrvtzkqxmrvtz": state the reason itself; the change belongs in a commit message
355broken.md:22: provenance: "The operator wants": state the position as the project's own
356broken.md:23: provenance: "the operator decided": state the position as the project's own
357broken.md:24: provenance: "wrote, "": state the position as the project's own, not as a quote
358broken.md:25: provenance: "" said the author": state the position as the project's own, not as a quote
359broken.md:28: line-number: "status/ready.go:146": cite the file or a name in it, not a line
360EOF
361if style broken.md > broken.got; then
362 echo "prose-format: the style lint passed a doc that breaks every rule" >&2
363 exit 1
364fi
365diff -u broken.want broken.got >&2 || {
366 echo "prose-format: the style lint's findings on broken.md are not the expected ones" >&2
367 exit 1
368}
369# allowed.md is broken.md with a marker for each rule a line breaks.
370gawk -F': ' '
371 NR == FNR {
372 split($1, at, ":")
373 if (!((at[2], $2) in seen))
374 allow[at[2]] = allow[at[2]] " <!-- prose-allow: " $2 " -->"
375 seen[at[2], $2]
376 next
377 }
378 { print $0 allow[FNR] }' broken.want broken.md > allowed.md
379style allowed.md >&2 || {
380 echo "prose-format: the style lint failed broken.md with an allowance on each line" >&2
381 exit 1
382}
383
384# What the rules must pass: the words and the narration in a fenced code
385# block, a marker quoted in inline code, an address, a timestamp, a hash,
386# "used to" that is not narration, the operator named as the role that
387# acts, a curve name, values quoted in inline code, and a quote that is
388# what a page shows.
389cat > clean.md <<'EOF'
390Allow a word with `<!-- prose-allow: vocabulary -->` on its line.
391The bus listens on nats://127.0.0.1:4222, and the run began at `2026-10-14T21:30`.
392A version is git-sha1:2222222222222222222222222222222222222222.
393The verifier keys used to verify a landing are the integrator's.
394The operator approves a change, and the operator's key signs it.
395An ed25519 key signs a note created after `2026-08-05`.
396A knot ID looks like `oc-1234567`, and a digest like `88a4e1f0`.
397The page says "The file is longer" when nothing has moved since the last read.
398
399~~~
400A PR owes a ticket, and the hook no longer reads the tree.
401~~~
402EOF
403style clean.md >&2 || {
404 echo "prose-format: the style lint failed clean.md, which breaks no rule" >&2
405 exit 1
406}
407
408# A marker that allows a rule the line does not break, names no rule, or
409# begins a line is a finding of its own.
410cat > markers.md <<'EOF'
411A change requires checks. <!-- prose-allow: vocabulary -->
412A change has a version. <!-- prose-allow: words -->
413<!-- prose-allow: vocabulary --> A PR is a change.
414EOF
415cat > markers.want <<'EOF'
416markers.md:1: allowance: allows vocabulary, but nothing on this line breaks it
417markers.md:2: allowance: prose-allow names no rule "words"; the rules are line-number, narration, provenance and vocabulary
418markers.md:3: allowance: a marker that begins a line begins an HTML block; put it after a word
419EOF
420if style markers.md > markers.got; then
421 echo "prose-format: the style lint passed a marker that allows nothing" >&2
422 exit 1
423fi
424diff -u markers.want markers.got >&2 || {
425 echo "prose-format: the style lint's findings on markers.md are not the expected ones" >&2
426 exit 1
427}
428
429# The tree's own docs: the same documents the link check reads.
430cd "$tree" || exit 1
431style README.md AGENTS.md docs/*.md > "$TMPDIR/style.got" || {
432 echo "prose-format: $(wc -l < "$TMPDIR/style.got") style finding(s):" >&2
433 sed 's/^/ /' "$TMPDIR/style.got" >&2
434 exit 1
435}
436
437touch "$out"