From dd44b7797aeb300dfbf24232c9029ecad002efb8 Mon Sep 17 00:00:00 2001 From: "knowledge-sync[bot]" Date: Thu, 19 Nov 2026 00:02:51 +0000 Subject: [PATCH 1/3] security(sidecar): sync copies and skills pin from v0.69.2 --- .../PULL_REQUEST_TEMPLATE/knowledge-sync.md | 1 + .lokf/justfile | 10 +- .lokf/m365/ktl-docent-m365.md | 4 +- .lokf/pyproject.toml | 2 +- .lokf/scripts/knowledge-apply.py | 216 ++++++++++++++++-- .lokf/scripts/knowledge-conventions.py | 203 ++++++++++++---- .lokf/scripts/knowledge-conventions.sh | 177 ++++++++------ .lokf/scripts/knowledge-feedback.sh | 36 ++- .lokf/scripts/knowledge-preflight.sh | 11 +- .lokf/scripts/knowledge-provenance.sh | 108 ++++++--- .lokf/scripts/knowledge-report.sh | 195 +++++++++++----- .lokf/scripts/knowledge-sync.sh | 2 + .lokf/uv.lock | 10 +- CHANGELOG.md | 4 + website/.gitignore | 2 +- website/assets/css/site.css | 22 +- website/assets/js/graph.js | 2 + website/assets/js/site.js | 71 ++++-- website/content/_content.gotmpl | 14 ++ website/content/knowledge/_content.gotmpl | 9 + website/hugo.toml | 50 ++-- .../layouts/_markup/render-blockquote.html | 4 +- .../_markup/render-codeblock-mermaid.html | 2 +- website/layouts/_markup/render-heading.html | 2 +- website/layouts/_markup/render-link.html | 2 +- website/layouts/_partials/gendoc.html | 9 +- website/layouts/_partials/heroes.html | 8 +- website/layouts/_partials/icon.html | 3 +- website/layouts/_partials/markdown-file.html | 11 +- website/layouts/_partials/nav-key.html | 5 +- website/layouts/_partials/own.html | 9 + website/layouts/_partials/route.html | 12 +- website/layouts/_partials/schema-file.html | 21 +- website/layouts/_partials/sidebar.html | 9 +- website/layouts/_partials/spec.html | 4 + website/layouts/_partials/tools.html | 7 +- website/layouts/_partials/vendor.html | 27 ++- website/layouts/baseof.html | 4 +- website/layouts/health.html | 5 + website/layouts/home.badge.json | 14 +- website/layouts/home.llms.txt | 4 +- website/layouts/page.atom.xml | 5 +- website/layouts/page.html | 2 +- website/layouts/schema/section.html | 7 +- website/pyproject.toml | 7 +- website/scripts/build.sh | 8 +- website/scripts/check-svg.py | 99 ++++++++ website/scripts/clean-html.py | 86 ++++--- website/scripts/lokf-export.py | 30 +++ website/scripts/prepare.sh | 133 +++++++---- website/scripts/site-values.py | 46 ++++ website/scripts/uv-env.sh | 39 ++++ website/scripts/vendor.sh | 43 ++++ website/uv.lock | 26 +-- 54 files changed, 1402 insertions(+), 440 deletions(-) create mode 100644 website/layouts/_partials/own.html create mode 100644 website/layouts/_partials/spec.html create mode 100644 website/scripts/check-svg.py create mode 100644 website/scripts/lokf-export.py create mode 100644 website/scripts/site-values.py create mode 100644 website/scripts/uv-env.sh create mode 100644 website/scripts/vendor.sh diff --git a/.github/PULL_REQUEST_TEMPLATE/knowledge-sync.md b/.github/PULL_REQUEST_TEMPLATE/knowledge-sync.md index c193739..66c80ff 100644 --- a/.github/PULL_REQUEST_TEMPLATE/knowledge-sync.md +++ b/.github/PULL_REQUEST_TEMPLATE/knowledge-sync.md @@ -6,4 +6,5 @@ - [ ] `.lokf/pyproject.toml` changes on the `ktl` line alone, to the release, and `.lokf/uv.lock` on the `ktl` entry alone. - [ ] Any workflow changes held above are read and applied on this branch, or left for the next sync on purpose. - [ ] You read the [release notes of Knowledge Trust Ladder](https://w3id.org/ktl/changelog/) for a step the sync cannot do, such as setting a new variable or secret. If there is one, you do it in this pull request or straight after the merge. +- [ ] Where the gate fails on a convention the release adds or tightens, such as rule 16's one `excerpt` for each source `id`, the bundle is fixed through the pen in a pull request of its own, and this one runs again once that merges. - [ ] `CHANGELOG.md` has the entry under `## [Unreleased]` and `### Security`, and the title carries `security(sidecar):`, so the merge releases. diff --git a/.lokf/justfile b/.lokf/justfile index 56458fd..3e677d4 100644 --- a/.lokf/justfile +++ b/.lokf/justfile @@ -46,11 +46,15 @@ lokf-serve: # outside base_iri alone, since `source` and `definedBy` take an external # resource. --check-excerpts (lokf 0.9.0 or later) finds each # `sources[].excerpt` in its local file, and counts an excerpt on a URL -# without fetching it. +# without fetching it. --shacl checks the projected graph against LOKF's +# SHACL shapes, such as a relation's target class and one excerpt per source +# node. It runs where uv.lock holds pyshacl, so a broken install fails +# rather than skipping the shapes; without it the recipe says so. # -# Audit: every typed-relation target must resolve to a concept, and every local excerpt must match its file +# Audit: every typed-relation target must resolve to a concept, every local excerpt must match its file, and the graph must keep LOKF's shapes lokf-check-refs: - uv run lokf validate {{ _schema }} --check-refs --check-excerpts {{ bundle }} + @grep -qx 'name = "pyshacl"' uv.lock 2>/dev/null || echo "SHACL shapes not checked: give lokf the shacl extra in pyproject.toml, then run uv lock" + uv run lokf validate {{ _schema }} --check-refs --check-excerpts $(grep -qx 'name = "pyshacl"' uv.lock 2>/dev/null && echo --shacl) {{ bundle }} # The knowledge_bundle doorway shows the bundle under a visible name at the # host root, for tools that hide dot-folders: folder pickers, file managers diff --git a/.lokf/m365/ktl-docent-m365.md b/.lokf/m365/ktl-docent-m365.md index 80117a6..34b5a81 100644 --- a/.lokf/m365/ktl-docent-m365.md +++ b/.lokf/m365/ktl-docent-m365.md @@ -45,9 +45,9 @@ This is the Microsoft 365 Copilot build of the ktl-docent skill from [knowledge- A bare `verified: { by, at }` counts as one event. Absent `status` means stable. Give each concept's labels on one line, in the order and form below. The repository's report script prints them the same way, so a reader sees the same words in Copilot and in the repository. -- Label a *retired* concept *retired*, and give it no other label. Add *replaced by* and the path when its newest `**Deprecation**` line in `log.md` links the concept that replaced it. +- Label a *retired* concept *retired*, and give it no other label. Add *replaced by* and the path of the concept that replaced it: the first that its `isReplacedBy` names, or else the one its newest `**Deprecation**` line in `log.md` links. - Otherwise, start with the first of *edited since a person last confirmed it*, *confirmed by a person*, *checked by automation only* and *nobody has checked this yet* that applies. Add *still a draft*, then *past its review date*, where they apply. -- After *confirmed by a person*, give the date of the latest `human:` event. When that event carries a `revision`, add "against" and the revision: a commit hash cut to its first seven characters, or an ETag or digest as written. +- After *confirmed by a person*, give the date of the latest `human:` event. When that event carries a `revision`, add "against" and the revision: a commit hash cut to its first seven characters, a `sha256:` digest cut to the seven after `sha256:`, or an ETag as written. - *Edited since a person last confirmed it* takes the place of *confirmed by a person*, because the person confirmed an earlier text. Give both dates, as in "(confirmed 2026-09-01, edited 2026-09-20)", or both full times when they fall on one day. Compare `generated.at` with the latest `human:` `verified[].at` whole, as strings, never cut to the day: an edit at 14:00 follows a confirmation at 10:00 the same day. Use the v0.1 `timestamp` where `generated.at` is missing. A concept with neither cannot carry this label. - After *past its review date*, give the `stale_after` date in brackets. Compare it with today's date, not the snapshot's: a concept can pass its review date after the snapshot was built. diff --git a/.lokf/pyproject.toml b/.lokf/pyproject.toml index e4bb6f2..848e444 100644 --- a/.lokf/pyproject.toml +++ b/.lokf/pyproject.toml @@ -12,7 +12,7 @@ description = "LOKF knowledge-bundle tooling for SLSA." # Keep in sync with the `lokf` toolkit's own requires-python floor. requires-python = ">=3.11" dependencies = [ - "ktl==0.66.0", + "ktl==0.69.2", "lokf[build]>=0.9.0", "rust-just==1.59.0", ] diff --git a/.lokf/scripts/knowledge-apply.py b/.lokf/scripts/knowledge-apply.py index e35af94..b3f9aed 100755 --- a/.lokf/scripts/knowledge-apply.py +++ b/.lokf/scripts/knowledge-apply.py @@ -23,7 +23,9 @@ # too, when the sidecar's .venv holds the toolkit, and says when it cannot # check them; that check also refuses a `sources[].excerpt` its local file # does not hold; -# - refuses an excerpt that is empty or longer than 500 characters. +# - refuses an excerpt that is empty or longer than 500 characters, and a +# sources id the patch gives another resource or excerpt than another +# concept gives it, since the id is one node in the graph. # # Every concept it writes keeps a person's record as it was: each `human:` # event and each note in a person's name, as knowledge-provenance.sh @@ -73,6 +75,7 @@ import copy import datetime as dt import difflib +import json import os import re import shutil @@ -85,21 +88,28 @@ import yaml -RESERVED = {"index.md", "log.md", "diataxis.md"} +RESERVED = {"index.md", "log.md"} # in every folder; a concept path names a folder, so never the root map PATH_RE = re.compile(r"[a-z0-9][a-z0-9-]*(/[a-z0-9][a-z0-9-]*)+\.md") # matched whole, so no line break can follow it EVENT_RE = re.compile(r"^\s*-?\s*by:\s*human:") # a line the provenance gates read as a person's event NOTE_RE = re.compile(r"^\s*-\s*\d{4}-\d{2}-\d{2},\s*human:") # a line the curator reads as a person's note KEPT_NOTE_RE = re.compile(r"^- \d{4}-\d{2}-\d{2}, *human:") # a person's note as knowledge-provenance.sh --unattended reads one CURATOR_NOTE_RE = re.compile(r"^- \d{4}-\d{2}-\d{2}, *process:ktl-curator:") # a curator's send-back recorded with no authenticated login (review-session.md) -# A person's note in any spelling a Markdown reader shows as one: another -# bullet mark, an indent, a tab or two spaces after the comma. The gates read -# the strict shape above, so no program counts these, and a person does. -LOOSE_NOTE_RE = re.compile(r"^\s*[-*+]\s+\d{4}-\d{2}-\d{2}\s*,\s*human:") +# A person's note in the spellings a Markdown reader shows as one: another +# bullet mark or a numbered item, an indent, a quote mark or a task box in +# front, a tab or two spaces after the comma, an escaped colon. The gates +# read the strict shape above, so no program counts these, and a person does. +LOOSE_NOTE_RE = re.compile(r"^[\s>]*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?\d{4}-\d{2}-\d{2}\s*,\s*human\\?:") +# The labels of the two log lines ktl-curator writes for a person. The report +# reads a retired concept's successor from the second. +CURATOR_LABELS = {"curation", "deprecation"} # A person's note as knowledge-report.sh lists one, under an open-questions heading outside a code fence. SEEN_NOTE_RE = re.compile(r"^- \d{4}-\d{2}-\d{2}, human:[^ ]*: ") -ACTOR_RE = re.compile(r"process:\S+") +# A patch's actor is `process:` and a login's characters, so no Markdown or +# colon reaches the stamps and bullets the patch writes. +ACTOR_RE = re.compile(r"process:[A-Za-z0-9][A-Za-z0-9._-]*") # The curator's actor, which stands for a person who could not sign in. A -# patch under it would write that person's send-back and events. +# patch under it, or under an actor that starts with it, would write notes +# that read as that person's. CURATOR_ACTOR = "process:ktl-curator" # Matched case-insensitively, and including the event-internal keys, so a # patch cannot write a top-level `by: human:...` or a `Verified:` that a line @@ -108,6 +118,8 @@ # so they belong to the script and the curator like the rest. DENIED_SET = {"id", "type", "generated", "verified", "revised", "refuted", "status", "stale_after", "timestamp", "by", "at", "revision"} DENIED_CREATE = {"generated", "verified", "revised", "refuted", "status", "stale_after", "timestamp", "by", "at", "revision"} +# Where knowledge-report.sh reads a retired concept's successor, which ktl-curator writes on a person's word. +SUCCESSOR_KEYS = {"isreplacedby", "relations"} RELATED_START, RELATED_END = "", "" OPEN_Q = "## Open questions" # The longest `sources[].excerpt` the pen writes, counted with each run of @@ -250,11 +262,24 @@ "endpoint", "documentation", "license", "author", "publisher", "generated", "verified", "status", "base_iri", "context", "stale_after", "timestamp", "genre", "definition", "version", } -NOT_CONCEPTS = {"index.md", "log.md", "diataxis.md"} +# An index and a log are no concept in any folder, and KTL Registrar's map is +# none at the bundle's root. The pen writes none of the three. +NOT_CONCEPTS = {"index.md", "log.md"} +ROOT_MAP = "diataxis.md" SCHEME = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*:") WHOLE_IRI = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*:\S+") +def material(value): + """A resource as rule 16 compares it, as `lokf validate` does: `./docs/a.md`, `docs/a.md` and `docs/a.md/` name one material.""" + if not isinstance(value, str) or not value.strip(): + return None + key = value.strip() + while key.startswith("./"): + key = key[2:] + return key.rstrip("/") or key + + def relation_targets(fm: dict) -> set: """Each (field, target) a concept's frontmatter relates it to, in any spelling the schema reads. @@ -349,7 +374,9 @@ class Dumper(yaml.SafeDumper): def choose_scalar_style(self): style = super().choose_scalar_style() - return '"' if style == "'" else style + # A value holding a double quote, such as an ETag, keeps single quotes: + # double quotes would need a backslash escape, which the gate reads as unreadable. + return '"' if style == "'" and '"' not in self.event.value else style def increase_indent(self, flow=False, indentless=False): # PyYAML writes a list under a key with its dashes at the key's @@ -360,11 +387,11 @@ def increase_indent(self, flow=False, indentless=False): class Quoted(str): - """A commit hash, written in double quotes whatever it holds. Unquoted, a short hash such as 1234e56 reads as a number to a YAML 1.2 reader, and the bundle quotes every `revision` so that none does.""" + """A revision, always quoted: a short hash such as 1234e56 reads as a number to a YAML 1.2 reader unquoted. Double quotes, or single quotes round an ETag's own double quotes.""" Dumper.add_representer(Plain, lambda dumper, text: dumper.represent_scalar(text.tag, str(text))) -Dumper.add_representer(Quoted, lambda dumper, text: dumper.represent_scalar("tag:yaml.org,2002:str", str(text), style='"')) +Dumper.add_representer(Quoted, lambda dumper, text: dumper.represent_scalar("tag:yaml.org,2002:str", str(text), style="'" if '"' in text else '"')) def quote_revisions(value): @@ -404,10 +431,11 @@ def shown(text: str) -> str: def human_events(value, slot: str): - """Each mapping under one frontmatter key whose `by` names a person, at any depth, as (slot, by, at, revision).""" + """Each mapping under one frontmatter key whose `by` names a person, at any depth, as (slot, by, at, revision, the other keys). The other keys are an exclusion's `resource` and `reason`, so neither changes under a person's name.""" if isinstance(value, dict): if str(value.get("by", "")).startswith("human:"): - yield (slot, str(value.get("by")), str(value.get("at", "")), str(value.get("revision", ""))) + rest = {str(k): v for k, v in value.items() if k not in ("by", "at", "revision")} + yield (slot, str(value.get("by")), str(value.get("at", "")), str(value.get("revision", "")), json.dumps(rest, sort_keys=True, default=str)) for inner in value.values(): yield from human_events(inner, slot) elif isinstance(value, list): @@ -445,9 +473,22 @@ def person_record(text: str | None) -> Counter: for key, value in fm.items(): for event in human_events(value, str(key)): record[event] += 1 - for line in text.split("\n"): - if KEPT_NOTE_RE.match(line) or LOOSE_NOTE_RE.match(line): + lines = text.split("\n") + kept = [] + for i, line in enumerate(lines): + if KEPT_NOTE_RE.match(line) or LOOSE_NOTE_RE.match(line) or CURATOR_NOTE_RE.match(line): record[("note", line.rstrip())] += 1 + kept.append(line.rstrip()) + # The indented lines under a note are part of it to a reader. + under = [] + for more in lines[i + 1:]: + if not more.strip() or not more[0] in " \t": + break + under.append(more.rstrip()) + if under: + record[("under", line.rstrip(), "\n".join(under))] += 1 + if kept: + record[("order", "\n".join(kept))] += 1 for line in seen_notes(split[1] if split else text): record[("seen", line)] += 1 return record @@ -457,8 +498,18 @@ def record_findings(path: str, was: Counter, now: Counter) -> list: """One line for each way a patch would change a person's record in one concept, naming the actor and the day and never the words.""" findings = [] gone = {e[1] for e in was - now if e[0] == "note"} + came = {e[1] for e in now - was if e[0] == "note"} for what, entry in [("remove", e) for e in sorted(was - now)] + [("add", e) for e in sorted(now - was)]: - if entry[0] == "seen": + if entry[0] == "order": + # The same notes in another order: the curator quotes the first. + if what == "add" and not gone and not came and any(e[0] == "order" for e in was): + findings.append(f"{path}: this patch would put the notes people left in another order; leave the {OPEN_Q} section as it stands") + elif entry[0] == "under": + if entry[1] not in gone and entry[1] not in came: + who = re.match(r"^[\s>]*\S+\s+(?:\[[ xX]\]\s+)?(\d{4}-\d{2}-\d{2})\s*,\s*(human\\?:[^ :]*|process:ktl-curator)", entry[1]) + name = f"{who.group(2)}, {who.group(1)}" if who else "a person" + findings.append(f"{path}: this patch would {'take lines from' if what == 'remove' else 'add lines to'} a note a person left ({name}); only ktl-curator changes one, on that person's word") + elif entry[0] == "seen": # A note that left the file is reported as removed. One still in # the file that the report no longer lists was hidden: a second # heading above it, or a fence opened and never closed. @@ -469,7 +520,7 @@ def record_findings(path: str, was: Counter, now: Counter) -> list: f"add no second {OPEN_Q} heading, and close every code fence the new text opens" ) elif entry[0] == "note": - who = re.match(r"^- (\d{4}-\d{2}-\d{2}), *(human:[^ :]*)", entry[1]) + who = re.match(r"^- (\d{4}-\d{2}-\d{2}), *(human:[^ :]*|process:ktl-curator)", entry[1]) name = f"{who.group(2)}, {who.group(1)}" if who else "a person" if what == "remove": findings.append(f"{path}: this patch would remove a note a person left ({name}); only ktl-curator clears one, on that person's word, and a rewrite carries the {OPEN_Q} section over only when its own body has none") @@ -608,6 +659,10 @@ def authored_by_person(self) -> bool: def confirmed_by_person(self) -> bool: return any(str(e.get("by", "")).startswith("human:") for e in self.events()) + def retired(self) -> bool: + """`status: deprecated`, which only the curator writes, on a person's word.""" + return str(self.fm.get("status", "")).strip().lower() == "deprecated" + def noted_by_person(self) -> bool: q = questions_span(self.body) if q is None: @@ -765,6 +820,9 @@ def set_frontmatter(self, c: Concept, sets) -> None: denied = sorted(k for k in sets if k.lower() in DENIED_SET) if denied: raise Refused(f"{c.path}: set may not touch {', '.join(denied)}; those belong to the script, the curator or the schema") + successor = sorted(k for k in sets if k.lower() in SUCCESSOR_KEYS) + if successor and c.retired(): + raise Refused(f"{c.path}: a person retired this concept, so set may not touch {', '.join(successor)}: its successor is that person's word; name it in the hand-off instead") for k, v in sets.items(): if k in ("title", "description"): v = one_line(v, f"{c.path}: {k}") @@ -860,6 +918,8 @@ def rewrite(self, op: dict) -> None: def question(self, op: dict) -> None: path = op["path"] c = self.concept(path, must_exist=True) + if c.retired(): + raise Refused(f"{path}: a person retired this concept, so question is refused: it would set the status back to draft; name the concept in the hand-off instead") text = autolinked(shown(one_line(op.get("text"), f"{path}: question text"))) if not text: raise Refused(f"{path}: question text has no visible characters") @@ -935,6 +995,8 @@ def delete(self, op: dict) -> None: raise Refused(f"{path}: a person left a note on this concept, so delete is refused; add a question saying the source is gone, and the curator retires it") if c.noted_by_curator(): raise Refused(f"{path}: the curator left a send-back on this concept, so delete is refused; re-derive it and leave the note for the curator") + if c.retired(): + raise Refused(f"{path}: a person retired this concept, so delete is refused; a retired concept stays for links and history") self.guard_writable(c, "delete") if not isinstance(op.get("log"), str) or not op["log"].strip(): raise Refused(f"{path}: delete needs a log line saying why") @@ -976,7 +1038,7 @@ def relation_findings(self) -> list: before, after, standing = {}, {}, {} for file in sorted(self.knowledge.rglob("*.md")): path = file.relative_to(self.knowledge).as_posix() - if file.name in NOT_CONCEPTS or ".obsidian" in path.split("/"): + if file.name in NOT_CONCEPTS or path == ROOT_MAP or ".obsidian" in path.split("/"): continue try: split = split_frontmatter(file.read_text(encoding="utf-8")) @@ -1006,6 +1068,59 @@ def relation_findings(self) -> list: findings.append(f"{path}: {field} still names {named}, which this patch deletes; drop or repoint the relation in this patch, or add a question to the concept if a person wrote it") return findings + def source_findings(self) -> list: + """Rule 16 across the bundle, for the `sources` entries this patch adds or changes: one id names one resource and one excerpt. + + A clash the patch did not make is left to the gate. + """ + def entries(fm) -> set: + found = fm.get("sources") if isinstance(fm, dict) else None + found = [found] if isinstance(found, dict) else found if isinstance(found, list) else [] + return {(str(e["id"]), material(e.get("resource")), e.get("excerpt") if isinstance(e.get("excerpt"), str) else None) + for e in found if isinstance(e, dict) and e.get("id") is not None} + + added = {path: entries(c.fm) - entries(getattr(c, "fm_read", {})) for path, c in self.concepts.items() if c.touched and not c.deleted} + added = {path: found for path, found in added.items() if found} + if not added: + return [] + uses: dict = {} + for path, fm in self.standing().items(): + for label, resource, excerpt in entries(fm): + uses.setdefault(label, []).append((path, resource, excerpt)) + findings = [] + for path, found in sorted(added.items()): + for label, resource, excerpt in sorted(found, key=str): + for other, theirs, quoted in sorted(uses.get(label, []), key=str): + if other == path: + continue + if theirs != resource: + findings.append(f"{path}: sources id {label} names {resource} here and {theirs} in {other}; one id names one resource across the bundle, so give this entry an id of its own and use it in the footnote") + elif excerpt is not None and quoted is not None and quoted != excerpt: + findings.append(f"{path}: sources id {label} quotes another passage in {other}; one id is one source node across the bundle, which holds one excerpt, so give this entry an id named after its passage and use it in the footnote") + else: + continue + break + return findings + + def standing(self) -> dict: + """Each concept's frontmatter as the bundle would hold it after this patch, by path.""" + standing = {} + for file in sorted(self.knowledge.rglob("*.md")): + path = file.relative_to(self.knowledge).as_posix() + if path in self.concepts or file.name in NOT_CONCEPTS or path == ROOT_MAP or ".obsidian" in path.split("/"): + continue + try: + split = split_frontmatter(file.read_text(encoding="utf-8")) + fm = read_yaml(split[0]) if split else None + except (OSError, UnicodeDecodeError, yaml.YAMLError): + continue # a concept this script cannot read is refused when an operation names it + if isinstance(fm, dict): + standing[path] = fm + for path, c in self.concepts.items(): + if not c.deleted: + standing[path] = c.fm + return standing + # ---- index, log, feedback ------------------------------------------- def index_text(self, file: Path, default: str) -> str: if file not in self.indexes: @@ -1052,7 +1167,10 @@ def place_bullet(text: str, link: str, bullet, path: str, where: str, section=No del lines[k] if 0 < k < len(lines) and lines[k - 1] == "" and lines[k] == "": del lines[k] # the blank line on either side of it, now two in a row - return Bundle.joined([Bundle.unlink(line, link, path, where) if ref.search(line) else line for line in lines]) + lines = [Bundle.unlink(line, link, path, where) if ref.search(line) else line for line in lines] + if section is not None: + lines = Bundle.drop_empty_section(lines, section[0]) + return Bundle.joined(lines) if mine: for k in mine: lines[k] = bullet @@ -1078,6 +1196,53 @@ def place_bullet(text: str, link: str, bullet, path: str, where: str, section=No lines.insert(last + 3, "") return Bundle.joined(lines) + @staticmethod + def drop_empty_section(lines: list, name: str) -> list: + """The lines without the heading named after a folder when nothing but blank lines is left under it.""" + heads = Bundle.headings(lines) + for i, (k, level, text) in enumerate(heads): + if i == 0 or text.lower() != name.lower(): + continue + end = next((k2 for k2, level2, _ in heads[i + 1 :] if level2 <= level), len(lines)) + if any(line.strip() for line in lines[k + 1 : end]): + continue + while k > 0 and lines[k - 1] == "": + k -= 1 + lines = lines[:k] + ([""] if end < len(lines) and k > 0 else []) + lines[end:] + break + return lines + + def index_writes(self) -> list: + """Each index.md this patch changed, with None for a folder's index left holding only its heading, no concept beside it and no link to it.""" + out = [] + for file, text in self.indexes.items(): + if file != self.knowledge / "index.md" and len([line for line in text.split("\n") if line.strip()]) == 1 and HEADING_RE.match(text.strip()): + folder = file.parent.relative_to(self.knowledge).as_posix() + left = {f.relative_to(self.knowledge).as_posix() for f in file.parent.rglob("*.md") if f != file} + left -= {p for p, c in self.concepts.items() if c.deleted} + left |= {p for p, c in self.concepts.items() if not c.deleted and p.startswith(folder + "/")} + if not left and not self.linked_from_an_index(file): + text = None + out.append((file, text)) + return out + + def linked_from_an_index(self, folder_index: Path) -> bool: + """Whether another index.md, as this patch leaves it, links to the folder or its index.md.""" + others = set(self.knowledge.rglob("index.md")) | set(self.indexes) + for other in sorted(others): + if other == folder_index or ".obsidian" in other.relative_to(self.knowledge).parts: + continue + text = self.indexes.get(other) + if text is None: + try: + text = other.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + continue + rel = Path(os.path.relpath(folder_index.parent, other.parent)).as_posix() + if re.search(r"\]\((?:\./)?" + re.escape(rel) + r"(?:/(?:index\.md)?)?(?:#[^)]*)?\)", text): + return True + return False + @staticmethod def joined(lines: list) -> str: return "\n".join(lines).rstrip("\n") + "\n" @@ -1253,7 +1418,7 @@ def ledger_text(self) -> str | None: def check_path(path) -> str: if not isinstance(path, str) or not PATH_RE.fullmatch(path) or ".." in path or path.rsplit("/", 1)[-1] in RESERVED: - raise Refused(f"path {path!r} is not a concept path: lowercase a-z, 0-9 and hyphens, at least one folder, .md, and not a reserved name") + raise Refused(f"path {path!r} is not a concept path: lowercase a-z, 0-9 and hyphens, at least one folder, .md, and not index.md or log.md") if path.startswith("knowledge/"): raise Refused(f"path {path!r} starts with knowledge/; paths are relative to .lokf/knowledge/") return path @@ -1264,6 +1429,9 @@ def log_line(text, what: str, label: str = "Changed") -> str: text = shown(one_line(text, what)) if not text: raise Refused(f"{what} line has no visible characters") + own = re.match(r"[*_]{2}\s*([^*_]*?)\s*[*_]{2}", text) + if own and own.group(1).strip(" :").lower() in CURATOR_LABELS: + raise Refused(f"{what} line starts with **{own.group(1)}**, a line only ktl-curator writes, for a person") return text if text.startswith("**") else f"**{label}**: {text}" @@ -1434,7 +1602,7 @@ def main(argv: list[str]) -> int: findings: list[str] = [] if not isinstance(by, str) or not ACTOR_RE.fullmatch(by): findings.append(f"by must be a process: actor, not {by!r}") - elif by == CURATOR_ACTOR: + elif by.startswith(CURATOR_ACTOR): findings.append(f"by may not be {CURATOR_ACTOR}: that actor stands for a person in a curator's session, and only ktl-curator writes under it") handoff: list = [] try: @@ -1474,6 +1642,7 @@ def main(argv: list[str]) -> int: if c.touched: findings.extend(record_findings(path, c.record, Counter() if c.deleted else person_record(c.text()))) findings.extend(bundle.relation_findings()) + findings.extend(bundle.source_findings()) for line in findings: print(line) if findings: @@ -1484,8 +1653,7 @@ def main(argv: list[str]) -> int: if not c.touched: continue writes.append((bundle.knowledge / path, None if c.deleted else c.text())) - for file, text in bundle.indexes.items(): - writes.append((file, text)) + writes.extend(bundle.index_writes()) try: log_text = bundle.log_text() except (OSError, UnicodeDecodeError) as exc: diff --git a/.lokf/scripts/knowledge-conventions.py b/.lokf/scripts/knowledge-conventions.py index ec122f1..f66fc9b 100755 --- a/.lokf/scripts/knowledge-conventions.py +++ b/.lokf/scripts/knowledge-conventions.py @@ -16,7 +16,7 @@ # Rules 15, 16 and 17 join the frontmatter to the body and to log.md. Rule # 4, a body rule, is checked with them. # -# Usage: knowledge-conventions.py [--since ] +# Usage: knowledge-conventions.py [--since [--head ]] # # Same contract as the shell half: one line per finding on stdout, exit 1 if # any; "OK" and exit 0 if none. The shell half runs it with the sidecar's @@ -28,8 +28,8 @@ # uv applies an `exclude-newer` date and the index serves no upload times, # the shell half lifts the date but keeps the version. The .venv holds what # uv.lock pins, by hash, which a person reviewed too. -# Move the version and the date together, here and in knowledge-apply.py: -# the skills repository's contract holds the two equal. +# Move the version here and in knowledge-apply.py together: the skills +# repository's contract holds the two equal. from __future__ import annotations @@ -42,7 +42,10 @@ import yaml -RESERVED = {"index.md", "log.md", "diataxis.md"} +# An index and a log are no concept in any folder, as the toolkit reads them, +# and KTL Registrar's diataxis.md is none at the bundle's root. +RESERVED = {"index.md", "log.md"} +ROOT_ONLY = {"diataxis.md"} OPEN_QUESTION = re.compile(r"^- \d{4}-\d{2}-\d{2}, (human|process):[^ :]+: ") # An index bullet in the shape knowledge-apply.sh writes: the title linked to # the concept, then its description. A line that lists two concepts is @@ -82,6 +85,8 @@ # Rule 16's shape for a `sources[].id`: what rule 8 allows in a path segment, # since the id becomes the IRI of the source's node under the bundle base. SOURCE_ID = re.compile(r"[a-z0-9][a-z0-9._-]*") +# A frontmatter delimiter as LOKF section 5 reads one. +LOKF_DELIMITER = re.compile(r"---[ \t]*") # A footnote reference, and a definition line, which Markdown reads at the # start of a line with at most three spaces before it. FOOTNOTE = re.compile(r"\[\^([^\]\s]+)\]") @@ -97,6 +102,11 @@ AFTER_TITLE = ",.:; " +def reserved(path: Path, bundle: Path) -> bool: + """Whether a file under the bundle is one of its own and no concept.""" + return path.name in RESERVED or (path.name in ROOT_ONLY and path.parent.resolve() == bundle.resolve()) + + def plain_spellings(fm_text: str) -> list[str]: """Rule 10: what a line reader could not read the way a parser does. @@ -136,6 +146,8 @@ def comment_after(ev) -> bool: findings.append(f"an alias (*{ev.anchor}) at {at(ev)}") elif getattr(ev, "anchor", None): findings.append(f"an anchor (&{ev.anchor}) at {at(ev)}") + if isinstance(ev, (yaml.MappingStartEvent, yaml.SequenceStartEvent)) and ev.tag is not None: + findings.append(f"a tag ({ev.tag}) on a collection at {at(ev)}") if isinstance(ev, yaml.ScalarEvent): if ev.tag is not None: findings.append(f"a tag on '{ev.value}' at {at(ev)}") @@ -144,6 +156,11 @@ def comment_after(ev) -> bool: if ev.value == "<<" and ev.style is None: findings.append(f"a merge key at {at(ev)}") if ev.value in GATE_FIELDS | EVENT_KEYS: + # Parsers settle a repeated key in different ways, and a + # line reader takes whichever line it meets. + if ev.value in top["keys"]: + findings.append(f"a second {ev.value} key at {at(ev)}") + top["keys"].add(ev.value) if ev.style is not None: findings.append(f"a quoted key ({ev.value}) at {at(ev)}") elif "?" in lines[row][: ev.start_mark.column]: @@ -187,6 +204,7 @@ def comment_after(ev) -> bool: stack.append( { "kind": "map" if isinstance(ev, yaml.MappingStartEvent) else "seq", + "keys": set(), "expect_key": True, "key": None, "key_row": None, @@ -344,6 +362,17 @@ def git(cwd: Path, *args: str) -> str | None: return done.stdout if done.returncode == 0 else None +TOPS: dict[Path, Path | None] = {} + + +def top_of(folder: Path) -> Path | None: + """The top of the work tree a folder sits in, asked of git once per folder, or None outside git.""" + if folder not in TOPS: + top = git(folder, "rev-parse", "--show-toplevel") + TOPS[folder] = Path(top.strip()).resolve() if top else None + return TOPS[folder] + + def base_iri(text: str | None) -> str: """The `base_iri` in the frontmatter of a bundle's root index.md, or ''.""" found = parsed(text) if text else None @@ -358,13 +387,13 @@ def unstamped_edit(path: Path, frontmatter: dict, body: str, bundle: Path) -> st and claims() says what counts as an edit. The text the person confirmed is the concept at the newest commit that - recorded the time of that confirmation, so the rule can miss an edit but - never flags a concept the person saw. Parsed values are compared, since - knowledge-apply.sh writes the whole frontmatter back: a requoted value - is no change. A move of the bundle's `base_iri` is no edit: the ids and - relation targets it carries along are compared by their paths under the - base each commit held. Outside git, or before that commit exists, - nothing is said. + put that confirmation into its frontmatter, which recorded_in finds, so + the rule can miss an edit but never flags a concept the person saw. + Parsed values are compared, since knowledge-apply.sh writes the whole + frontmatter back: a requoted value is no change. A move of the bundle's + `base_iri` is no edit: the ids and relation targets it carries along are + compared by their paths under the base each commit held. Outside git, or + before that commit exists, nothing is said. """ if frontmatter.get("status") == "deprecated": return None @@ -383,25 +412,24 @@ def unstamped_edit(path: Path, frontmatter: dict, body: str, bundle: Path) -> st if stamp > confirmed_at: return None # it already reads as edited since that confirmation real = path.resolve() - found = git(real.parent, "log", "--format=%H", "-S" + written, "--", real.name) - commit = found.split("\n", 1)[0].strip() if found else "" - if not commit: - return None - then = git(real.parent, "show", f"{commit}:./{real.name}") - split = split_frontmatter(then.lstrip("\ufeff").replace("\r\n", "\n").replace("\r", "\n")) if then else None - if split is None: + top_path = top_of(real.parent) + if top_path is None: return None try: - frontmatter_then = yaml.safe_load(split[0]) - except yaml.YAMLError: + name = real.relative_to(top_path).as_posix() + except ValueError: return None - if not isinstance(frontmatter_then, dict) or claims(frontmatter_then, split[1]) == claims(frontmatter, body): + where = recorded_in(top_path, name, (by, str(written))) + if where is None: + return None + commit, (frontmatter_then, body_then) = where + if claims(frontmatter_then, body_then) == claims(frontmatter, body): return None index = bundle.resolve() / "index.md" base_now = base_iri(index.read_text(encoding="utf-8", errors="replace")) if index.is_file() else "" base_then = base_iri(git(index.parent, "show", f"{commit}:./index.md")) if base_now and base_then and base_now != base_then: - if claims(frontmatter_then, split[1], base_then) == claims(frontmatter, body, base_now): + if claims(frontmatter_then, body_then, base_then) == claims(frontmatter, body, base_now): return None return ( f"{path}: changed since {by} confirmed it ({confirmed_at[:10]}, in {commit[:7]}), and `generated` was not " @@ -435,20 +463,80 @@ def parsed(text: str | None) -> tuple[dict, str] | None: return (frontmatter, split[1]) if isinstance(frontmatter, dict) else None -def verdict_edits(bundle: Path, since: str) -> list[str]: +def before_in(top: Path, parent: str, commit: str, name: str, ident) -> tuple[str, tuple[dict, str] | None]: + """The concept as a parent of a commit holds it: its path there, and what it says, or None. + + With no file at the same path, a file the commit deletes that has the + same id is the concept before a rename. + """ + text = git(top, "show", f"{parent}:{name}") + if text is not None: + return name, parsed(text) + if not isinstance(ident, str) or not ident: + return name, None + gone = git(top, "diff-tree", "--no-commit-id", "--name-only", "-r", "--diff-filter=D", parent, commit) or "" + for old in gone.splitlines(): + if not old.endswith(".md"): + continue + found = parsed(git(top, "show", f"{parent}:{old}")) + if found is not None and found[0].get("id") == ident: + return old, found + return name, None + + +def recorded_in(top: Path, name: str, event: tuple[str, str]) -> tuple[str, tuple[dict, str]] | None: + """The newest commit that put a person's event into a concept's frontmatter, and the concept as that commit holds it. + + `git log -S` also names a commit that repeats the event's time in the + body, so each candidate is parsed: the answer is the commit whose + frontmatter holds the event and whose parents' do not. The search + follows a rename to the concept's earlier path. + """ + start = "HEAD" + for _ in range(64): # one round per rename of the concept + moved = None + for line in (git(top, "log", "--format=%H %P", "-S" + event[1], start, "--", name) or "").splitlines(): + commit, *parents = line.split() + now = parsed(git(top, "show", f"{commit}:{name}")) + if now is None or event not in human_events(now[0]): + continue + holders = [] + for parent in parents: + old, earlier = before_in(top, parent, commit, name, now[0].get("id")) + if earlier is not None and event in human_events(earlier[0]): + holders.append((parent, old)) + if not holders: + return commit, now + renamed = [held for held in holders if held[1] != name] + if renamed: + moved = renamed[0] + break + if moved is None: + return None + start, name = moved + return None + + +def verdict_edits(bundle: Path, since: str, head: str = "HEAD") -> list[str]: """Rule 14: a commit that records a person's confirmation changes the verdict, not what the concept says. Rule 13 compares with the commit that recorded the confirmation, so an edit made in that same commit would read as confirmed. Each commit after - `since` that touches the bundle is read against every parent, as the - provenance job reads one. One that adds a `human:` event no parent holds + `since`, up to `head`, that touches the bundle is read against every + parent, as the provenance job reads one. The gate names the pull + request's last commit as `head`: its checkout is a merge into the base, + and HEAD would add the commits the base gained since. One that adds a `human:` event no parent holds may change the concept's claims only when `generated.by` names that same person, which is how Correct now records an edit the person made. A merge that brings in a confirmation made elsewhere adds nothing new, so - it is never read as one. Outside git nothing is said. + it is never read as one. A renamed concept is read against the file it + was, which before_in finds by its id, so a rename alone claims nothing. + Outside git nothing is said. """ if not COMMIT.fullmatch(since): return [f"rule 14: '{since}' is not a commit - pass the base the pull request was opened against"] + if not COMMIT.fullmatch(head): + return [f"rule 14: '{head}' is not a commit - pass the last commit of the pull request"] real = bundle.resolve() top = git(real, "rev-parse", "--show-toplevel") if top is None: @@ -456,21 +544,23 @@ def verdict_edits(bundle: Path, since: str) -> list[str]: top_path = Path(top.strip()) if git(top_path, "rev-parse", "--verify", "--quiet", since + "^{commit}") is None: return [f"rule 14: the base commit {since} is not in this clone's history - check out the full history"] + if git(top_path, "rev-parse", "--verify", "--quiet", head + "^{commit}") is None: + return [f"rule 14: the head commit {head} is not in this clone's history - check out the full history"] rel = real.relative_to(top_path.resolve()).as_posix() findings: list[str] = [] - for commit in (git(top_path, "rev-list", "--reverse", f"{since}..HEAD", "--", rel) or "").split(): + for commit in (git(top_path, "rev-list", "--reverse", f"{since}..{head}", "--", rel) or "").split(): parents = (git(top_path, "rev-list", "--parents", "-n", "1", commit) or "").split()[1:] names: set[str] = set() for parent in parents or [""]: against = [parent, commit] if parent else ["--root", commit] out = git(top_path, "diff-tree", "--no-commit-id", "--name-only", "-r", "--diff-filter=AM", *against, "--", rel) - names.update(n for n in (out or "").splitlines() if n.endswith(".md") and Path(n).name not in RESERVED) + names.update(n for n in (out or "").splitlines() if n.endswith(".md") and not reserved(top_path / n, real)) for name in sorted(names): now = parsed(git(top_path, "show", f"{commit}:{name}")) if now is None: continue frontmatter, body = now - before = [parsed(git(top_path, "show", f"{parent}:{name}")) for parent in parents] + before = [before_in(top_path, parent, commit, name, frontmatter.get("id"))[1] for parent in parents] held: set[tuple[str, str]] = set() for earlier in before: if earlier is not None: @@ -488,7 +578,8 @@ def verdict_edits(bundle: Path, since: str) -> list[str]: return findings -def footnotes(path: Path, frontmatter: dict, body: str, source_ids: dict[str, dict[str, list[Path]]]) -> list[str]: +def footnotes(path: Path, frontmatter: dict, body: str, source_ids: dict[str, dict[str, list[Path]]], + source_quotes: dict[str, dict[str, list[Path]]]) -> list[str]: """Rule 16: each footnote in the body joins a claim to one of the concept's `sources` entries, by that entry's `id`. A reference `[^label]` and a definition line `[^label]: text` each use @@ -498,8 +589,9 @@ def footnotes(path: Path, frontmatter: dict, body: str, source_ids: dict[str, di the footnote cannot drift from its entry. A footnote mark in a code fence or a code span is an example, not a reference. OKF v0.2 section 5.1 says a footnote whose label equals `id` attributes the claim to that - entry. Each id is recorded in `source_ids` with its resource, for the - check across the bundle in main: one id names one resource. + entry. Each id is recorded in `source_ids` with its resource, and in + `source_quotes` with its excerpt, for the checks across the bundle in + main: one id names one resource and one excerpt. """ findings: list[str] = [] sources = frontmatter.get("sources") @@ -520,6 +612,9 @@ def footnotes(path: Path, frontmatter: dict, body: str, source_ids: dict[str, di # One material however it is written: `./docs/a.md` and `docs/a.md` # are one resource, as rule 18 reads them. source_ids.setdefault(label, {}).setdefault(same_material(resource) or resource, []).append(path) + # Compared as lokf compares them: the exact text, and only where given. + if isinstance(entry.get("excerpt"), str): + source_quotes.setdefault(label, {}).setdefault(entry["excerpt"], []).append(path) referenced: set[str] = set() defined: dict[str, str] = {} fenced = False @@ -674,6 +769,7 @@ def check_file( entries: dict[Path, tuple[str, str]], titles: set[str], source_ids: dict[str, dict[str, list[Path]]], + source_quotes: dict[str, dict[str, list[Path]]], ) -> list[str]: findings: list[str] = [] raw = path.read_bytes() @@ -688,6 +784,17 @@ def check_file( if len(block) == 3 and "\r" in block[1].replace("\r\n", ""): findings.append(f"{path}: frontmatter uses a bare carriage return - write it plainly, so a line reader reads what a parser reads") + # LOKF section 5 also reads a block after blank lines, and ends it at + # `---` with spaces or tabs after it. The line readers here read neither. + lines = text.split("\n") + lead = next((i for i, line in enumerate(lines) if line.strip()), 0) + if LOKF_DELIMITER.fullmatch(lines[lead]): + if lead: + findings.append(f"{path}: blank lines stand before the frontmatter block - LOKF reads past them and the line readers here do not; delete them") + return findings + if any(lines[i] != "---" for i in [i for i, line in enumerate(lines) if LOKF_DELIMITER.fullmatch(line)][:2]): + findings.append(f"{path}: a frontmatter delimiter has spaces or tabs after '---' - LOKF ends the block there and the line readers here do not; delete them") + return findings split = split_frontmatter(text) if split is None: findings.append( @@ -695,10 +802,10 @@ def check_file( ) return findings fm_text, body = split - # The toolkit ends the block at the first `---` it meets, in a line or not, - # so it would read less of this block than every script here reads. + # lokf before 0.10.0 ends the block at the first `---`, in a line or not, + # and a host keeps its own floor. if "---" in fm_text: - findings.append(f"{path}: frontmatter holds '---', where the toolkit ends the block - write the value another way") + findings.append(f"{path}: frontmatter holds '---', where lokf before 0.10.0 ends the block - write the value another way") try: frontmatter = yaml.safe_load(fm_text) @@ -805,17 +912,19 @@ def check_file( ) # 16. each footnote joins a claim to a `sources` entry by its id. - findings.extend(footnotes(path, frontmatter, body, source_ids)) + findings.extend(footnotes(path, frontmatter, body, source_ids, source_quotes)) return findings def main(argv: list[str]) -> int: - args, since = argv[1:], "" - if len(args) == 3 and args[1] == "--since": + args, since, head = argv[1:], "", "HEAD" + if len(args) == 5 and args[1] == "--since" and args[3] == "--head": + args, since, head = args[:1], args[2], args[4] + elif len(args) == 3 and args[1] == "--since": args, since = args[:1], args[2] if len(args) != 1: - print("usage: knowledge-conventions.py [--since ]", file=sys.stderr) + print("usage: knowledge-conventions.py [--since [--head ]]", file=sys.stderr) return 2 bundle = Path(args[0]) if not bundle.is_dir(): @@ -827,6 +936,7 @@ def main(argv: list[str]) -> int: entries: dict[Path, tuple[str, str]] = {} titles: set[str] = set() source_ids: dict[str, dict[str, list[Path]]] = {} + source_quotes: dict[str, dict[str, list[Path]]] = {} # 9. the toolkit reads a link as the file it points at, and the gates read # it as the path it names, so its events would go unseen. for path in sorted(bundle.rglob("*")): @@ -836,9 +946,9 @@ def main(argv: list[str]) -> int: for path in sorted(bundle.rglob("*.md")): if path.is_symlink() or not path.is_file(): continue - if ".obsidian" in path.parts or path.name in RESERVED: + if ".obsidian" in path.parts or reserved(path, bundle): continue - findings.extend(check_file(path, bundle, ids, entries, titles, source_ids)) + findings.extend(check_file(path, bundle, ids, entries, titles, source_ids, source_quotes)) # 12. an index bullet that names a concept says what the concept says. # ktl-docent chooses what to open from the bullets alone, so a bullet @@ -874,12 +984,21 @@ def main(argv: list[str]) -> int: f"id {label} names more than one resource: {where} - " "one id names one resource across the bundle, since the id mints one source node under the bundle base" ) + # ... and one excerpt: the node holds every excerpt given under its id, + # and LOKF's SHACL shapes allow it one (LOKF 0.10.0, section 9). + for label, by_quote in sorted(source_quotes.items()): + if len(by_quote) > 1: + where = "; ".join(f"{json.dumps(quote[:40] + ('...' if len(quote) > 40 else ''))} in {' '.join(str(p) for p in paths)}" for quote, paths in by_quote.items()) + findings.append( + f"id {label} carries more than one excerpt: {where} - " + "one id is one source node across the bundle, which holds one excerpt; give each other passage an id of its own" + ) # 14. only with a base, which the registrar's gate sets to the pull # request's: on a branch's whole history a squash merge folds an edit # and a later confirmation into one commit. if since: - findings.extend(verdict_edits(bundle, since)) + findings.extend(verdict_edits(bundle, since, head)) # 17. logged writes, read since the base when one is given. findings.extend(logged_writes(bundle, titles, since)) diff --git a/.lokf/scripts/knowledge-conventions.sh b/.lokf/scripts/knowledge-conventions.sh index 02788e1..e682643 100755 --- a/.lokf/scripts/knowledge-conventions.sh +++ b/.lokf/scripts/knowledge-conventions.sh @@ -5,77 +5,91 @@ # on these rules, and knowledge-conventions.py gives the detail of each rule # it checks: # -# 1. log.md has one `## YYYY-MM-DD` heading per day: the bare ISO date, -# newest first, no duplicates. OKF §9 makes the date form a MUST, and the -# KTL Curator plugin finds today's section by that exact heading. -# 2. Every `at:` is a quoted string, and a UTC time to the second, as -# `date -u +%Y-%m-%dT%H:%M:%SZ` writes it. +# 1. The bundle's root log.md has one `## YYYY-MM-DD` heading per day: the +# bare ISO date, newest first, no duplicates. OKF §9 makes the date form a +# MUST, and the KTL Curator plugin finds today's section by that exact +# heading. +# 2. Every `at:` is a quoted string, and a UTC time to the second, as `date +# -u +%Y-%m-%dT%H:%M:%SZ` writes it. # 3. `verified` is a list, never a bare `{ by, at }` mapping, and carries at # most one `process:ktl-librarian` event: the librarian replaces its own. -# 4. A bullet under `## Open questions` is `- YYYY-MM-DD, : ...`, the -# shape the curator and both plugins write and read. The curator quotes -# the first bullet, so a trailing signature would become the question. -# 5. Every `resource:` that is not a URL names a file or directory that -# exists, relative to the repository root: the nearest directory holding -# `.lokf/`, or else the bundle's parent. URLs are never fetched. -# 6. A commit-shaped `revision` (lokf 0.9.0 and later) on a `generated` or -# `verified` event names a commit in this repository that holds the -# concept's local `resource`. ETags, digests and version labels pin URLs -# and are not checked. The rule needs the full history: outside git it -# is skipped, and a shallow clone is reported. +# 4. A bullet under `## Open questions` is `- YYYY-MM-DD, : ...`, with +# a `human:` or `process:` actor: the shape the curator and both plugins +# write and read. The curator quotes the first bullet, so a trailing +# signature would become the question. +# 5. Every `resource:`, an exclusion's too, that names no URL and no other +# scheme, such as `urn:` or `doi:`, names a file or directory that exists, +# relative to the repository root: the nearest directory holding `.lokf/`, +# or else the bundle's parent. URLs are never fetched. +# 6. A commit-shaped `revision` (lokf 0.9.0 and later), seven or more +# lower-case hex characters on any event, names a commit in the history of +# HEAD that holds the concept's local `resource`. With `--since ` +# it names no commit made after that base: a squash merge or a rebase +# replaces such a commit, and a `sha256:` digest pins the file instead. A +# `revision` of any other shape, such as an ETag or a digest, is not +# checked. The rule needs the full history: outside git it is skipped, and +# a shallow clone is reported. # 7. One file per `id`. A sync client's conflict copy or a pasted duplicate # passes `lokf validate` and silently merges into the original in the # graph. -# 8. Every path in the bundle is lowercase: a-z, 0-9, `.`, `_`, `-`. Two -# paths that differ only by case collide on Windows, macOS and -# SharePoint, and sync clients name a conflict copy with a space, a -# parenthesis or an upper-case host name. +# 8. Every Markdown file's path in the bundle is lowercase: each segment +# starts with a letter or a digit and holds a-z, 0-9, `.`, `_`, `-`. Two +# paths that differ only by case collide on Windows, macOS and SharePoint, +# and sync clients name a conflict copy with a space, a parenthesis or an +# upper-case host name. # 9. Every concept is a file, not a symbolic link, and starts with a `---` -# frontmatter block that closes, with no byte order mark in front of it -# and no `---` inside it. A BOM or a file with no block would otherwise -# pass this script unread. +# frontmatter block that closes. No byte order mark or blank line stands +# in front of it, no space or tab follows a `---` delimiter, and no other +# `---` sits inside it. Otherwise LOKF, or lokf before 0.10.0, reads more +# or less of the file as frontmatter than this script does. # 10. The fields the provenance gates read line by line are spelt so that a -# line reader and a parser read the same thing, since both gates refuse -# an event they cannot read. They are `id`, `verified`, `generated`, and -# `by`, `at` and `revision` on an event. They carry no quoted or explicit -# key, space before the colon, escape or block scalar. No value spans -# lines or sits below its key, and no comment sits beside one or inside -# a flow form. `resource` keeps the same spellings, though a comment may -# stand beside it, and `sources` and `exclusions` hold no flow form. -# The whole block holds no tag, anchor, alias or merge key, on any field: -# a line reader resolves none of them, and an alias can stand in for an -# event or a source wherever it sits. The block is not indented whole or -# one flow mapping, and holds no line break but a line feed. -# 11. No `at:` is later than the commit that first recorded it, or, before -# it is committed, than now. A time ahead of the clock, such as local -# time labelled `Z` or a round placeholder, sorts after the edits and +# line reader and a parser read the same thing. They are `id`, `verified`, +# `generated`, and `by`, `at` and `revision` at any depth. Each carries no +# quoted or explicit key, space before the colon, escape or block scalar, +# and none is given twice in one mapping. No value spans lines or sits +# below its key, and no comment sits beside one, inside a flow form or +# between the events of a list. `resource` keeps the same spellings, +# though a comment may stand beside it, and `sources` and `exclusions` +# hold no flow form. The whole block holds no tag, anchor, alias or merge +# key, on any field or collection. The block is not indented whole or one +# flow mapping, and holds no line break but a line feed. +# 11. No `at:` is later than the commit that first recorded it, or, before it +# is committed, than now. A time ahead of the clock, such as local time +# labelled `Z` or a round placeholder, sorts after the edits and # confirmations that followed it, so a concept reads as edited since it -# was confirmed when it was not. A rename or a shallow clone can only -# make that commit look later, so the rule can miss a bad time but never -# flags a good one. A time with an offset other than `Z` is not -# compared. Outside git the rule is skipped. +# was confirmed when it was not. A rename or a shallow clone can only make +# that commit look later, so the rule can miss a bad time but never flags +# a good one. A time with an offset other than `Z` is not compared. +# Outside git the rule is skipped. # 12. An index bullet that names a concept carries that concept's title and # description, in the folder's index.md and in the root's. A concept no # index lists is not a finding. # 13. A concept labelled confirmed by a person still says what that person # confirmed: an edit to its claims after the commit that recorded the -# latest confirmation must move `generated.at` past that confirmation. +# latest confirmation must move `generated.at` past that confirmation. Its +# claims are its body and its frontmatter, less the open questions, KTL +# Registrar's `lokf:related` block, and `generated`, `verified`, `status`, +# `stale_after`, `timestamp` and `usage_window`. A retired concept is not +# read, and outside git the rule is skipped. # 14. A commit that records a person's confirmation changes the verdict, not -# what the concept says, unless `generated.by` names that same person. -# The rule reads the commits after `--since `, and is skipped -# without it. +# what the concept says, unless `generated.by` names that same person. The +# rule reads the commits after `--since `, up to `--head ` +# or else HEAD, and is skipped without `--since`. # 15. Every concept names where it came from: a top-level `resource`, or a # `sources` list with an entry. -# 16. A footnote joins a claim to a source: each footnote in a body uses the -# `id` of one of the concept's `sources` entries, each id is cited and -# defined, and one id names one resource across the bundle. +# 16. A footnote joins a claim to a source. Each footnote in a body uses the +# `id` of one of the concept's `sources` entries, and each id is cited +# and defined. Its definition line holds that entry's `resource`. Across +# the bundle one id is one source node: it names one resource and at most +# one excerpt. An id holds what rule 8 allows in a path segment. # 17. A logged write has a file behind it: each `**Added**` and -# `**Deprecation**` bullet in log.md names a concept the bundle holds. -# The rule reads the bullets added since `--since `, or without -# it those under the newest day heading. +# `**Deprecation**` bullet in log.md names a concept the bundle holds. The +# rule reads the bullets added since `--since `, or without it +# those under the newest day heading. A `**Removal**` bullet under the +# same or a newer day that names the same concept excuses one. # 18. Each `exclusions` entry (lokf 0.9.0 and later) gives a `reason` that is -# not blank, and no material is both a source and an exclusion of one -# concept. +# not blank, and no material is both a `sources` entry and an exclusion of +# one concept. # # Rules 2, 3, 8, 10 and 18 are house rules, stricter than the format: OKF # permits an unquoted datetime, a bare `verified` mapping, any file name and @@ -102,26 +116,33 @@ # sidecar's `.lokf/.gitattributes` keeps tracked files on LF; rule 9 still # reports a BOM, because other readers do not strip it. # -# Usage: knowledge-conventions.sh [bundle-dir] [--since ] [--strict] +# Usage: knowledge-conventions.sh [bundle-dir] [--since [--head ]] [--strict] # (default: knowledge, i.e. run from .lokf/). Exit 1 with one line per # finding; nothing else is written. Exit 2 when the Python half could not # run, or under --strict when it was skipped, with the reason on stderr. -[ -n "${BASH_VERSION:-}" ] || { echo "run this with bash: bash ${0##*/} [bundle-dir] [--since ] [--strict]" >&2; exit 2; } +# +# `--since` names the base of a pull request, and rules 6, 14 and 17 read +# what came after it. `--head` names the pull request's last commit where +# HEAD is a merge of it into the base, as a gate checks out, so that rules 6 +# and 14 leave out the commits the base gained since. +[ -n "${BASH_VERSION:-}" ] || { echo "run this with bash: bash ${0##*/} [bundle-dir] [--since [--head ]] [--strict]" >&2; exit 2; } set -euo pipefail -usage() { echo "usage: ${0##*/} [bundle-dir] [--since ] [--strict]" >&2; exit 2; } +usage() { echo "usage: ${0##*/} [bundle-dir] [--since [--head ]] [--strict]" >&2; exit 2; } # The bundle directory may be a link, on a host that keeps the real folder as # a visible knowledge_bundle/. Handed a link bare, find never enters it, so # the trailing slash below is what makes it read the files. -bundle=""; since=""; strict=0 +bundle=""; since=""; head=""; strict=0 while [ $# -gt 0 ]; do case "$1" in --since) { [ $# -ge 2 ] && [ -n "$2" ]; } || usage; since="$2"; shift 2 ;; + --head) { [ $# -ge 2 ] && [ -n "$2" ]; } || usage; head="$2"; shift 2 ;; --strict) strict=1; shift ;; -*) usage ;; *) [ -z "$bundle" ] || usage; bundle="$1"; shift ;; esac done +{ [ -z "$head" ] || [ -n "$since" ]; } || usage bundle="${bundle:-knowledge}"; bundle="${bundle%/}" [ -d "$bundle" ] || { echo "no bundle directory at $bundle" >&2; exit 2; } fail=0 @@ -270,9 +291,9 @@ hold() { # # For rule 5, a URL, an identifier with a scheme such as urn:ietf:rfc:9110 # or doi:10.1000/182 (two characters at least, so a Windows drive letter is # still a path), a fragment and the quotes are cut from a value. For rule 6, -# a revision with a character outside [0-9a-f] pins a URL and is skipped, as -# is every revision on a concept whose top-level `resource` is a URL, an -# absolute path or absent. +# a revision with a character outside [0-9a-f] names no commit and is +# skipped, as is every revision on a concept whose top-level `resource` is a +# URL, an absolute path or absent. # shellcheck disable=SC2016 # awk's own $0, not the shell's fields=' # The same flowvals as in the rule11 program above. @@ -293,7 +314,7 @@ function scheme(v) { return v ~ /^[A-Za-z][A-Za-z0-9+.-]+:/ } function local(v) { if (v ~ /:\/\//) return "" sub(/^["'"'"']/, "", v); if (scheme(v)) return "" - sub(/#.*/, "", v); v = unquote(v); sub(/[ \t]+$/, "", v) + sub(/#.*/, "", v); sub(/[ \t]+$/, "", v); v = unquote(v); sub(/[ \t]+$/, "", v) return v } BEGIN { @@ -306,7 +327,7 @@ BEGIN { sub(/^\//, "", rel) # BSD find prints the start point slash, then its own if (rel !~ /^([a-z0-9][a-z0-9._-]*\/)*[a-z0-9][a-z0-9._-]*$/) print "P\t" k "\t" f base = f; sub(/.*\//, "", base) - if (base == "index.md" || base == "log.md" || base == "diataxis.md" || (f in link)) next + if (base == "index.md" || base == "log.md" || rel == "diataxis.md" || (f in link)) next n = 0; top = ""; nr = 0 while ((getline l < f) > 0) { n++; gsub(/\r/, "", l) @@ -369,12 +390,30 @@ if [ "$read_all" != 1 ]; then echo "the bundle could not be read to its end, so rules 5, 6, 8 and 11 were not checked - the error above names the file" >&2 exit 2 fi -# Rule 6's answers, from one git call: a line for each question, in order, -# that ends in "missing" when the commit or the path in it is not there. +# Rule 6's answers, a line for each question, in order. One git call says +# whether the commit holds the path: its line ends in "missing" when the +# commit or the path in it is not there. A second gives each commit whole. +# Two walks then list the pinned commits that the history of HEAD holds, and +# those made after the base. if [ -n "$asks" ]; then - while IFS=$'\t' read -r n f rev res answer; do - case "$answer" in *" missing"|*" ambiguous"|"") hold "$n" 2 "$f: revision $rev does not hold $res - no such commit, or the path was absent in it" ;; esac - done < <(paste <(printf '%s' "$askers") <(printf '%s' "$asks" | git -C "$root" cat-file --batch-check 2>/dev/null || true)) + printf '%s' "$asks" | git -C "$root" cat-file --batch-check > "$tmp/holds" 2>/dev/null || true + printf '%s' "$askers" | cut -f3 | sed 's/$/^{commit}/' | git -C "$root" cat-file --batch-check='%(objectname)' > "$tmp/whole" 2>/dev/null || true + grep -E '^[0-9a-f]+$' "$tmp/whole" | sort -u > "$tmp/pins" || true + : > "$tmp/inhead"; : > "$tmp/after" + if [ -s "$tmp/pins" ]; then + git -C "$root" rev-list HEAD 2>/dev/null | grep -Fxf "$tmp/pins" > "$tmp/inhead" || true + case "$since:${head:-HEAD}" in + :*|-*|*:-*) ;; + *) git -C "$root" rev-list "$since..${head:-HEAD}" 2>/dev/null | grep -Fxf "$tmp/pins" > "$tmp/after" || true ;; + esac + fi + while IFS=$'\t' read -r n finding; do + hold "$n" 2 "$finding" + done < <(paste <(printf '%s' "$askers") "$tmp/holds" "$tmp/whole" | awk -F'\t' -v inhead="$tmp/inhead" -v after="$tmp/after" ' + BEGIN { while ((getline l < inhead) > 0) H[l] = 1; while ((getline l < after) > 0) A[l] = 1 } + $5 == "" || $5 ~ / (missing|ambiguous)$/ { print $1 "\t" $2 ": revision " $3 " does not hold " $4 " - no such commit, or the path was absent in it"; next } + !($6 in H) { print $1 "\t" $2 ": revision " $3 " is not in the history of HEAD - a squash merge or a rebase has replaced that commit, or another branch holds it"; next } + $6 in A { print $1 "\t" $2 ": revision " $3 " names a commit made after the base, which a squash merge or a rebase replaces - pin the content of " $4 " instead, as a sha256: digest" }') fi # 11. from one walk through the history of the bundle, oldest first. if [ -n "$gitroot" ] && [ -s "$tmp/ats" ]; then @@ -437,9 +476,9 @@ fi if [ -n "$runner" ]; then rc=0 if [ "$runner" = uv ]; then - out="$(uv run --quiet ${uvflags[@]+"${uvflags[@]}"} "$py" "$bundle" ${since:+--since "$since"} 2>&1)" || rc=$? + out="$(uv run --quiet ${uvflags[@]+"${uvflags[@]}"} "$py" "$bundle" ${since:+--since "$since"} ${head:+--head "$head"} 2>&1)" || rc=$? else - out="$("$runner" "$py" "$bundle" ${since:+--since "$since"} 2>&1)" || rc=$? + out="$("$runner" "$py" "$bundle" ${since:+--since "$since"} ${head:+--head "$head"} 2>&1)" || rc=$? fi # The Python half exits 1 for findings. Any other failure is the runner's, # or a usage error, and says nothing about the bundle. diff --git a/.lokf/scripts/knowledge-feedback.sh b/.lokf/scripts/knowledge-feedback.sh index 6d6a49d..b04b3a1 100755 --- a/.lokf/scripts/knowledge-feedback.sh +++ b/.lokf/scripts/knowledge-feedback.sh @@ -38,9 +38,9 @@ # Exit: # 0 recorded; # 2 the call was wrong, and nothing was written; -# 1 the file could not be written (a read-only .lokf/, most often, or -# another run holding it), and the caller should tell the reader the gap -# out loud instead. +# 1 the file could not be written (a read-only .lokf/, most often, another +# run holding it, or a symbolic link where the script writes), and the +# caller should tell the reader the gap out loud instead. [ -n "${BASH_VERSION:-}" ] || { echo "run this with bash: bash ${0##*/} [--root ] [--for ] " >&2; exit 2; } set -u # A-Z, a-z and 0-9 in a case glob mean the ASCII letters and digits, not @@ -95,7 +95,8 @@ if [ -n "$concept" ]; then echo "--concept takes a concept's path in the bundle, in lowercase with no '..' or '.' segment, such as services/orders-api.md, not '$concept'" >&2; exit 2 ;; esac case "$concept" in *.md) ;; *) echo "--concept takes the concept's file, ending in .md, not '$concept'" >&2; exit 2 ;; esac - case "${concept##*/}" in index.md|log.md|diataxis.md) echo "--concept takes a concept, not the bundle's $concept" >&2; exit 2 ;; esac + [ "$concept" != diataxis.md ] || { echo "--concept takes a concept, not the bundle's $concept" >&2; exit 2; } + case "${concept##*/}" in index.md|log.md) echo "--concept takes a concept, not the bundle's $concept" >&2; exit 2 ;; esac fi # One entry is one line. Collapse every whitespace run, drop control @@ -126,8 +127,9 @@ if [ -n "$concept" ] && [ ! -f "$root/.lokf/knowledge/$concept" ]; then echo "--concept names no concept in this bundle: $concept - record the Disagreement without it" >&2; exit 2 fi -file="$root/.lokf/feedback.md" -tmp="$file.$$" +dir="$root/.lokf" +file="$dir/feedback.md" +tmp="" lock="$file.lock" today="$(date -u +%Y-%m-%d)" entry="- **$kind**${concept:+ (on \`$concept\`)} - $text - docent${asker:+, for human:$asker}" @@ -137,9 +139,22 @@ readonly_bundle() { echo "cannot write $file - if .lokf/ is read-only, say the gap out loud to the reader instead" >&2 exit 1 } +# Refuse a symbolic link at the folder, the file or the lock, which a +# repository can commit: a write through one changes another file, and a +# read copies it into feedback.md. +for place in "$dir" "$file" "$lock"; do + if [ -L "$place" ]; then + echo "$place is a symbolic link, which this script neither reads nor writes through - say the gap out loud to the reader instead" >&2 + exit 1 + fi +done +if [ -e "$file" ] && [ ! -f "$file" ]; then + echo "$file is not a regular file - say the gap out loud to the reader instead" >&2 + exit 1 +fi # The rewrite below writes a temporary file beside this one, so the directory # has to be writable even when the file itself already is. -[ -w "$root/.lokf" ] || readonly_bundle +[ -w "$dir" ] || readonly_bundle # Two runs at once would each read the file, and the second mv would drop the # first entry. A directory is the one lock that every platform here creates @@ -156,10 +171,15 @@ until mkdir "$lock" 2>/dev/null; do fi sleep 1 done -trap 'rmdir "$lock" 2>/dev/null; rm -f "$tmp"' EXIT +trap 'rmdir "$lock" 2>/dev/null; [ -z "$tmp" ] || rm -f "$tmp"' EXIT trap 'exit 130' INT trap 'exit 143' TERM +# mktemp picks a name a committed link cannot already hold, unlike $$. +# Its file is owner-only, so chmod gives it the mode a new file takes here. +tmp="$(mktemp "$dir/feedback.md.XXXXXX" 2>/dev/null)" || { tmp=""; readonly_bundle; } +chmod "$(printf '%o' $((0666 & ~$(umask))))" "$tmp" 2>/dev/null || : + # feedback.md is not knowledge and has no frontmatter; it appears the first # time a reader's agent records a gap, which may be this call. if [ ! -s "$file" ]; then diff --git a/.lokf/scripts/knowledge-preflight.sh b/.lokf/scripts/knowledge-preflight.sh index 6a901a2..59d6b99 100755 --- a/.lokf/scripts/knowledge-preflight.sh +++ b/.lokf/scripts/knowledge-preflight.sh @@ -77,7 +77,7 @@ esac # it is handed bare: it would count zero concepts and say nothing. bundle="$root/.lokf/knowledge" if [ -d "$bundle" ]; then - n="$(find "$bundle/" -name '*.md' -not -path '*/.obsidian/*' -not -name index.md -not -name log.md -not -name diataxis.md | wc -l | tr -d ' ')" + n="$(find "$bundle/" -name '*.md' -not -path '*/.obsidian/*' -not -name index.md -not -name log.md -not -path "$bundle/diataxis.md" | wc -l | tr -d ' ')" door="$root/knowledge_bundle" if [ -L "$door" ]; then doorway="knowledge_bundle -> $(readlink "$door")" elif [ -d "$door" ]; then doorway="knowledge_bundle is a folder or junction" @@ -234,7 +234,7 @@ fi index="${index:-https://pypi.org/simple}" ihost="$(hostof "$index")" if have uv; then - floor="$(sed -n 's/.*"lokf\[build\]>=\([0-9.]*\)".*/\1/p' "$root/.lokf/pyproject.toml" 2>/dev/null | head -n 1)" + floor="$(sed -n 's/.*"lokf\[[a-z, ]*\]>=\([0-9.]*\)".*/\1/p' "$root/.lokf/pyproject.toml" 2>/dev/null | head -n 1)" if [ -d "$root/.lokf/.venv" ]; then installed="$(cd "$root/.lokf" && uv run --no-sync lokf --version 2>/dev/null | sed -n 's/^lokf //p')" ok toolkit "uv $(uv --version 2>/dev/null | sed 's/^uv //'); lokf ${installed:-unknown} installed (floor >=${floor:-?})" @@ -246,8 +246,13 @@ if have uv; then # The recipes pass --check-excerpts, and --schema to convert and serve, # which lokf 0.8.0 does not take. case "${floor:-}" in - 0.[0-8]|0.[0-8].*) warn toolkit "the floor is >=$floor and the justfile's recipes need lokf 0.9.0 - raise it to \"lokf[build]>=0.9.0\" in .lokf/pyproject.toml and run uv lock there" ;; + 0.[0-8]|0.[0-8].*) warn toolkit "the floor is >=$floor and the justfile's recipes need lokf 0.9.0 - raise it to \"lokf[build,shacl]>=0.10.0\" in .lokf/pyproject.toml and run uv lock there" ;; esac + # The gate's recipe checks LOKF's SHACL shapes only where uv.lock holds + # lokf's shacl extra. + if [ -f "$root/.lokf/uv.lock" ] && ! grep -qx 'name = "pyshacl"' "$root/.lokf/uv.lock"; then + warn toolkit "uv.lock holds no pyshacl, so just lokf-check-refs skips LOKF's SHACL shapes - write \"lokf[build,shacl]\" in .lokf/pyproject.toml and run uv lock there" + fi # A domain vocabulary imports the copy of LOKF core beside it, and the gate # runs the lokf that uv.lock pins. A copy from another release can reject a # concept that lokf reads. A copy sits in .lokf/schema/, or at the root of diff --git a/.lokf/scripts/knowledge-provenance.sh b/.lokf/scripts/knowledge-provenance.sh index d23bb9a..a6d6a04 100755 --- a/.lokf/scripts/knowledge-provenance.sh +++ b/.lokf/scripts/knowledge-provenance.sh @@ -189,17 +189,24 @@ sig_format() { # commit -> pgp | ssh | none # frontmatter only, so an example in a body code fence is no claim. It reads # a block list in any key order, a flow-style item, a flow sequence and a # bare mapping, and gives whatever else it meets the actor (unreadable). An -# event is keyed by the `id` of its concept, so a renamed concept keeps its -# events and a confirmation copied into another concept does not. +# event is keyed by the `id` of its concept, and events_in adds its place. human_events() { # path -> events, reading the concept on stdin awk -v path="$1" ' - function val(s) { sub(/^[^:]*:[[:space:]]*/, "", s); gsub(/["'"'"']/, "", s); sub(/[[:space:]]+$/, "", s); return s } + # Returns the value after the key, less one pair of enclosing quotes, and sets + # `strange` on an unclosed or inner quote, a `\` escape, a trailing comment or + # a leading indicator, which a parser reads another way. + function val(s, q, n) { sub(/^[^:]*:[[:space:]]*/, "", s); sub(/[[:space:]]+$/, "", s); q = substr(s, 1, 1); n = length(s) + if (q == "\"" || q == "'"'"'") { if (n < 2 || substr(s, n) != q) { strange = 1; return s } + s = substr(s, 2, n - 2); if (index(s, q) || (q == "\"" && index(s, "\\"))) strange = 1; return s } + if (s ~ /[[:space:]]#/ || s ~ /^[!&*|>@`%#]/) strange = 1 + return s } # The schema gives an event only `by`, `at` and `revision`, so another key # (a quoted `by`, a merge, an alias) is a spelling this reader cannot # follow. Such an event, and one with an actor the schema does not allow, # gets the actor (unreadable), which is no login, so each gate refuses it. - function kv(l, k) { k = l; sub(/:.*/, "", k); sub(/^[[:space:]]+/, "", k) - if (k == "by") by = val(l); else if (k == "at") at = val(l); else if (k == "revision") rev = val(l); else odd = 1 } + function kv(l, k) { k = l; sub(/:.*/, "", k); sub(/^[[:space:]]+/, "", k); strange = 0 + if (k == "by") by = val(l); else if (k == "at") at = val(l); else if (k == "revision") rev = val(l); else odd = 1 + if (strange) odd = 1 } function actor(a) { return a !~ /\\/ && (a ~ /^(human|process):[^[:space:]]+$/ || a ~ "^[^[:space:]/]+/[^[:space:]/]+$") } # Any edit a parser could read must change the output, so an unreadable # file gives one line that holds everything up to the closing delimiter, @@ -245,7 +252,9 @@ human_events() { # path -> events, reading the concept on stdin # a quoted key, `? key`, `<<:` or a flow mapping, can each hold an event. !seen && /[^[:space:]]/ && !/^[[:space:]]*#/ { seen = 1; if (/^[[:space:]]/) unread() } /^["'"'"'?{[]/ || /^(verified|generated)[[:space:]]+:/ { emit(); inv = 0; unread(); next } - /^id:/ { cid = val($0) } + # The id keys every event of the concept: a strange id, or a second `id` + # line, makes the file unreadable. + /^id:/ { strange = 0; cid = val($0); if (strange || ++ids > 1) unread() } /^(verified|generated):/ { emit(); inv = 1; kind = $0; sub(/:.*/, "", kind); rest = $0; sub(/^(verified|generated):[[:space:]]*/, "", rest); sub(/[[:space:]]+$/, "", rest) if (rest ~ /^\{/) { flowseq = 0; flowbuf = rest; inv = 0; if (index(rest, "}")) flushflow(); else inflow = 1 } else if (rest ~ /^\[/) { flowseq = 1; flowbuf = rest; inv = 0; if (index(rest, "]")) flushflow(); else inflow = 1 } @@ -262,9 +271,23 @@ human_events() { # path -> events, reading the concept on stdin inv && /^[[:space:]]+[^[:space:]#]/ { inev = 1; odd = 1; next } END { if (plain && dashes >= 2 && path !~ /(^|\/)log\.md$/) unread(); emit(); printf "%s", out; if (bad) { printf "%s\t(unreadable)\t\t", cid ? cid : path; for (i = 1; i <= NR; i++) if (i in raw) printf "%s\001", raw[i]; printf "\tverified\n" } }' } -events_in() { # ref, paths on stdin -> the human events of those paths at that ref, sorted +# Each event is prefixed with its place: the concept's path, or `-` when the +# other ref has no file there. An event moved or copied between two concepts +# is one removal and one addition; a rename has `-` on both sides, so its +# events match by id. Duplicates are kept, so a second copy is an addition. +# Matches knowledge-registrar.yaml. +placed() { # place, events on stdin -> the events with that place before each + PLACE="$1" awk '{ print ENVIRON["PLACE"] "\t" $0 }' +} +events_in() { # ref, the refs it is compared with..., paths on stdin -> the human events of those paths at that ref, sorted + ref="$1"; shift while IFS= read -r f; do - git show "$1:$f" 2>/dev/null | human_events "$f" + git cat-file -e "$ref:$f" 2>/dev/null || continue + place="-" + for other in "$@"; do + if git cat-file -e "$other:$f" 2>/dev/null; then place="$f"; break; fi + done + git show "$ref:$f" 2>/dev/null | human_events "$f" | placed "$place" done | sort } # The paths a commit changes against any of its parents, which git lists for @@ -282,8 +305,8 @@ changed_paths() { # commit, pathspecs... -> paths, one per line # concept no longer holds one by a person. removed_from() { # events-before file, events-now file -> the removed events that need their person comm -23 "$1" "$2" | awk -F'\t' -v now="$2" ' - BEGIN { while ((getline line < now) > 0) { split(line, f, "\t"); if (f[5] == "generated") kept[f[1]] = 1 } } - $5 == "verified" || !($1 in kept)' + BEGIN { while ((getline line < now) > 0) { split(line, f, "\t"); if (f[6] == "generated") kept[f[2]] = 1 } } + $6 == "verified" || !($2 in kept)' } # The toolkit follows a symbolic link and git does not, so a link onto a file @@ -334,10 +357,11 @@ if [ "$unattended" -eq 1 ]; then : > "$home/was.events"; : > "$home/now.events"; : > "$home/was.notes"; : > "$home/now.notes" while IFS= read -r f; do case "$f" in *.md) ;; *) continue ;; esac - git show "HEAD:$f" > "$home/was.file" 2>/dev/null || : > "$home/was.file" - if [ -f "$f" ]; then cat "$f" > "$home/now.file"; else : > "$home/now.file"; fi - human_events "$f" < "$home/was.file" >> "$home/was.events" - human_events "$f" < "$home/now.file" >> "$home/now.events" + was_place="-"; now_place="-" + if git show "HEAD:$f" > "$home/was.file" 2>/dev/null; then now_place="$f"; else : > "$home/was.file"; fi + if [ -f "$f" ]; then cat "$f" > "$home/now.file"; was_place="$f"; else : > "$home/now.file"; fi + human_events "$f" < "$home/was.file" | placed "$was_place" >> "$home/was.events" + human_events "$f" < "$home/now.file" | placed "$now_place" >> "$home/now.events" notes_of "$f" < "$home/was.file" >> "$home/was.notes" notes_of "$f" < "$home/now.file" >> "$home/now.notes" if [ -f "$f" ] && human_events "$f" < "$home/was.file" | awk -F'\t' '$5 == "generated" { found = 1 } END { exit !found }' \ @@ -360,15 +384,16 @@ if [ "$unattended" -eq 1 ]; then say "$new: a person wrote this text, which an unattended change rewrites under a new name (was $old)" fi done < <(git -c core.quotePath=false diff --name-status -M HEAD -- "$bundle" "$doorway" 2>/dev/null | grep -E '^R' || true) - for kind in events notes; do sort -u "$home/was.$kind" -o "$home/was.$kind"; sort -u "$home/now.$kind" -o "$home/now.$kind"; done - while IFS="$(printf '\t')" read -r id by at _; do + # Each list keeps its repeats: a second copy of an event or of a note is an addition. + for kind in events notes; do sort "$home/was.$kind" -o "$home/was.$kind"; sort "$home/now.$kind" -o "$home/now.$kind"; done + while IFS="$(printf '\t')" read -r _ id by at _; do [ -n "$id" ] || continue case "$by" in "(unreadable)") say "$id: an unattended change writes frontmatter this gate cannot read - spell it as conventions rule 10 asks" ;; *) say "$id: an unattended change adds or changes a confirmation by human:$by ($at)" ;; esac done < <(comm -13 "$home/was.events" "$home/now.events") - while IFS="$(printf '\t')" read -r id by at _; do + while IFS="$(printf '\t')" read -r _ id by at _; do [ -n "$id" ] || continue case "$by" in "(unreadable)") say "$id: an unattended change removes frontmatter this gate could not read, which may have held a person's record" ;; @@ -395,9 +420,10 @@ commits="$(git rev-list --reverse "$base..$head" 2>/dev/null)" || { echo "cannot # branch, which brings in a key added in a reviewed change of its own, adds # no key file that the base lacks. rekeyed="" -for f in $(git -c core.quotePath=false diff --no-renames --name-only "$base" "$head" -- "$curators" 2>/dev/null); do +while IFS= read -r f; do + [ -n "$f" ] || continue f="${f##*/}"; rekeyed="$rekeyed ${f%.*}" -done +done < <(git -c core.quotePath=false diff --no-renames --name-only "$base" "$head" -- "$curators" 2>/dev/null) rekeyed_said="" checked=0 @@ -418,25 +444,29 @@ for sha in $commits; do fi files="$(printf '%s\n' "$listed" | grep '\.md$' || true)" [ -n "$files" ] || continue - # An event in this commit and in no parent is new or changed, and its actor - # must sign: a re-dated `at` or a moved `revision` counts too. So a merge - # that brings in a confirmation from one side claims nothing. every.events - # holds what every parent holds, so a merge that lacks what one side never - # had removes nothing, and a root commit removes nothing. - : > "$home/every.events"; first=1 - for p in $(git rev-parse "$sha^@" 2>/dev/null); do - printf '%s\n' "$files" | events_in "$p" | sort -u > "$home/one.events" - if [ "$first" -eq 1 ]; then cp "$home/one.events" "$home/every.events"; first=0 - else comm -12 "$home/every.events" "$home/one.events" > "$home/every.tmp"; mv "$home/every.tmp" "$home/every.events"; fi - cat "$home/one.events" - done | sort -u > "$home/parent.events" - printf '%s\n' "$files" | events_in "$sha" | sort -u > "$home/sha.events" - added="$(comm -13 "$home/parent.events" "$home/sha.events" | cut -f2 | sort -u)" - gone="$(removed_from "$home/every.events" "$home/sha.events" | cut -f2 | sort -u)" + # An event in this commit and in no parent is added, a re-dated `at` or a + # moved `revision` included, and its actor must sign. parent.events holds + # each event as often as the parent with most copies of it, and + # every.events what every parent holds. So a merge claims nothing it took + # from one side, and a root commit removes nothing. + parents=() + while IFS= read -r p; do [ -z "$p" ] || parents+=("$p"); done < <(git rev-parse "$sha^@" 2>/dev/null) + : > "$home/every.events"; : > "$home/parent.events"; first=1 + for p in ${parents[@]+"${parents[@]}"}; do + printf '%s\n' "$files" | events_in "$p" "$sha" > "$home/one.events" + if [ "$first" -eq 1 ]; then cp "$home/one.events" "$home/every.events"; cp "$home/one.events" "$home/parent.events"; first=0 + else + comm -12 "$home/every.events" "$home/one.events" > "$home/every.tmp"; mv "$home/every.tmp" "$home/every.events" + { cat "$home/parent.events"; comm -13 "$home/parent.events" "$home/one.events"; } | sort > "$home/parent.tmp"; mv "$home/parent.tmp" "$home/parent.events" + fi + done + printf '%s\n' "$files" | events_in "$sha" ${parents[@]+"${parents[@]}"} > "$home/sha.events" + added="$(comm -13 "$home/parent.events" "$home/sha.events" | cut -f3 | sort -u)" + gone="$(removed_from "$home/every.events" "$home/sha.events" | cut -f3 | sort -u)" ids="$(printf '%s\n%s\n' "$added" "$gone" | sed '/^$/d' | sort -u)" [ -n "$ids" ] || continue # One concept and one person count once, however many events of theirs it holds. - touched="$({ comm -13 "$home/parent.events" "$home/sha.events"; removed_from "$home/every.events" "$home/sha.events"; } | cut -f1,2 | sort -u | grep -c . || true)" + touched="$({ comm -13 "$home/parent.events" "$home/sha.events"; removed_from "$home/every.events" "$home/sha.events"; } | cut -f2,3 | sort -u | grep -c . || true)" checked=$((checked + touched)) format="$(sig_format "$sha")" status=""; signer="" @@ -444,7 +474,9 @@ for sha in $commits; do status="$(GNUPGHOME="$home" git verify-commit --raw "$sha" 2>&1 || true)" signer="$(printf '%s\n' "$status" | awk '/^\[GNUPG:\] VALIDSIG/ {print $3; exit}')" fi - for id in $ids; do + # Each id is read whole: one that holds `*` or `?` names no file here. + while IFS= read -r id; do + [ -n "$id" ] || continue # What this commit does with that person's record, for the finding's wording. does="adds or changes" printf '%s\n' "$added" | grep -qxF -- "$id" || does="removes" @@ -509,7 +541,9 @@ for sha in $commits; do fi fi ;; esac - done + done <..] one line per concept, in the shape of ktl-docent's footer +# knowledge-report.sh questions every open question, with its day, who asked, and its text # knowledge-report.sh worklist where ktl-librarian starts: paths and dates only # knowledge-report.sh quiet exit 0 when nothing waits for the librarian, 1 when work does # knowledge-report.sh changes what the working tree does to the record, against HEAD @@ -25,8 +26,9 @@ # # The labels, in the words ktl-curator and ktl-docent use: # confirmed by a person a `verified` event whose actor starts human: -# edited since a person last `generated.at` is later than the latest such -# confirmed it event, the two times compared whole; such a +# edited since a person last `generated.at`, or a later `revised.at`, is +# confirmed it later than the latest such event, the two +# times compared whole; such a # concept is counted here and not as confirmed, # since the person confirmed an earlier text # checked by automation only `verified` holds events, none a person's @@ -42,8 +44,9 @@ # concept waits in .lokf/feedback.md # retired `status: deprecated`; no other label applies, # and it names the concept that replaced it -# when the newest **Deprecation** line in -# log.md links one +# when its isReplacedBy names one, or else +# the newest **Deprecation** line in log.md +# links one # # The whole report also prints the queue of ktl-curator, Worth ten minutes # today, and what ranks it: review dates due within 30 days, confirmed @@ -153,7 +156,7 @@ # `quiet` exits 1 when work waits, and `coverage --strict` when a file is # named by nobody or the count could not be made. `sample` exits 2 on a host # with no tool to compute a digest. -[ -n "${BASH_VERSION:-}" ] || { echo "run this with bash: bash ${0##*/} [--root ] [health|labels|worklist|quiet|changes|retrieval|coverage|sample|evidence] [...]" >&2; exit 2; } +[ -n "${BASH_VERSION:-}" ] || { echo "run this with bash: bash ${0##*/} [--root ] [health|labels|questions|worklist|quiet|changes|retrieval|coverage|sample|evidence] [...]" >&2; exit 2; } set -u # Byte-oriented awk and sort, so that the BOM and CRLF strips and every # comparison read raw bytes in any awk and locale: under UTF-8, gawk reads @@ -162,7 +165,7 @@ set -u export LC_ALL=C usage() { - echo "usage: ${0##*/} [--root ] [health | labels [...] | worklist | quiet | changes | retrieval --prompt | retrieval | isolated | coverage [--strict] [...] | coverage --why ... | sample [--seed ] [--independent ] [--automation ] | evidence]" >&2 + echo "usage: ${0##*/} [--root ] [health | labels [...] | questions | worklist | quiet | changes | retrieval --prompt | retrieval | isolated | coverage [--strict] [...] | coverage --why ... | sample [--seed ] [--independent ] [--automation ] | evidence]" >&2 exit 2 } @@ -207,7 +210,7 @@ trap 'rm -rf "$tmp"' EXIT # C path title status stale_after generated.by generated.at # latest human verified.at human events verified events latest verified.at open questions # that human time as written the later of generated.at and verified.at as written -# the revision that human event carries, a commit hash cut to seven characters +# the revision that human event carries, a commit hash cut to seven characters and a digest to seven after `sha256:` # the revision of the event the work list compares with, and that of the human event, whole # I path id type resource one per concept: its `id`, its `type`, and its top `resource`, else its first source # R path resource one per `resource:` line, the concept's own and each source's @@ -288,6 +291,7 @@ function emit( n) { if (inev) { n = norm(at) if (kind == "generated") { gen_by = by; gen_at = n; gen_raw = at; gen_rev = rev; hasgen = 1 } + else if (kind == "revised") { if (n > rvd_at) { rvd_at = n; rvd_raw = at; rvd_rev = rev } } else { vn++; eby[vn] = by; eat[vn] = n; eraw[vn] = at; erev[vn] = rev if (n > check_at) { check_at = n; check_raw = at; check_rev = rev } if (by ~ /^human:/) { hn++; if (n > human_at) { human_at = n; human_raw = at; human_rev = rev } } } @@ -343,7 +347,7 @@ function mention(f, l, n, items, i, w) { sub(/^[ \t]*(-[ \t]+)*/, "", l) function reset() { title = ""; status = ""; stale = ""; tstamp = ""; cid = ""; ctype = ""; topres = ""; firstres = "" fm = 0; body = 0; started = 0; skip = 0; top = ""; inv = 0; inev = 0; kind = ""; by = ""; at = ""; rev = "" - gen_by = ""; gen_at = ""; gen_raw = ""; gen_rev = ""; hasgen = 0; vn = 0; hn = 0; hm = 0 + gen_by = ""; gen_at = ""; gen_raw = ""; gen_rev = ""; hasgen = 0; vn = 0; hn = 0; hm = 0; rvd_at = ""; rvd_raw = ""; rvd_rev = "" check_at = ""; check_raw = ""; check_rev = ""; human_at = ""; human_raw = ""; human_rev = ""; human_full = "" inflow = 0; flowbuf = ""; flowseq = 0; sidx = -1; kcol = 0; sres = ""; shas = 0; sid = 0; skey = 0 rel = ""; rp = ""; rt = ""; inrels = 0; fence = 0; inq = 0; qn = 0 @@ -386,8 +390,8 @@ fm { if (r != "" && top == "exclusions" && $0 !~ /^resource:/) print "X\t" path "\t" r else if (r != "") { print "R\t" path "\t" r; if ($0 ~ /^resource:/) topres = r; else if (firstres == "") firstres = r } } - if ($0 ~ /^(verified|generated):/) { - relend(); emit(); inv = 1; kind = $0; sub(/:.*/, "", kind); rest = $0; sub(/^(verified|generated):[ \t]*/, "", rest) + if ($0 ~ /^(verified|generated|revised):/) { + relend(); emit(); inv = 1; kind = $0; sub(/:.*/, "", kind); rest = $0; sub(/^(verified|generated|revised):[ \t]*/, "", rest) if (rest ~ /^\{/) { flowseq = 0; flowbuf = rest; inv = 0; if (index(rest, "}")) flushflow(); else inflow = 1 } else if (rest ~ /^\[/) { flowseq = 1; flowbuf = rest; inv = 0; if (index(rest, "]")) flushflow(); else inflow = 1 } next @@ -449,6 +453,11 @@ function finish() { relend() emit() if (gen_at == "" && tstamp != "") { gen_at = norm(tstamp); gen_raw = tstamp } + # LOKF 0.9.0 lets a producer record a later edit as `revised` and leave + # `generated` alone. The last change is the later of the two times, and + # the evidence row keeps what `generated` itself says. + made_at = gen_at; made_raw = gen_raw; made_rev = gen_rev + if (rvd_at > gen_at) { gen_at = rvd_at; gen_raw = rvd_raw; gen_rev = rvd_rev } # A review date is read by its day: in UTC where the value carries an # offset, else as the day its first ten characters name, as the website # reads it. The specification makes a concept stale from that instant on, @@ -456,6 +465,7 @@ function finish() { st = norm(stale); if (st != "") st = substr(st, 1, 10); else if (stale ~ /^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]/) st = substr(stale, 1, 10) human_full = human_rev if (human_rev ~ /^[0-9a-f]+$/ && length(human_rev) > 7) human_rev = substr(human_rev, 1, 7) + else if (human_rev ~ /^sha256:[0-9a-f]+$/ && length(human_rev) > 14) human_rev = substr(human_rev, 1, 14) printf "C\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%d\t%d\t%s\t%d\t%s\t%s\t%s\t%s\t%s\n", path, (title == "" ? path : title), status, st, gen_by, gen_at, human_at, hn, vn, check_at, qn, human_raw, (gen_at > check_at ? gen_raw : check_raw), human_rev, (gen_at > check_at ? gen_rev : check_rev), human_full printf "I\t%s\t%s\t%s\t%s\n", path, cid, ctype, (topres != "" ? topres : firstres) for (i = 1; i <= vn; i++) if (eby[i] ~ /^human:/ && eraw[i] != "") print "H\t" path "\t" eraw[i] @@ -470,11 +480,13 @@ function finish() { for (i = 1; i <= hm; i++) chk[hum[i]] = (i == 1 ? "first" : (eby[hum[i]] == eby[hum[1]] ? "same-person" : "second-person")) for (i = 2; i <= vn; i++) { k = ord[i]; j = i - 1; while (j > 0 && shown[ord[j]] > shown[k]) { ord[j + 1] = ord[j]; j-- } ord[j + 1] = k } head = "V\t" cell(path) "\t" cell(ctype) "\t" cell(status) "\t" cell(st != "" ? st : stale) "\t" cell(topres != "" ? topres : firstres) "\t" - if (hasgen) print head "generated\t" cell(gen_by) "\t" cell(gen_at != "" ? gen_at : gen_raw) "\t" cell(gen_rev) "\t" + if (hasgen) print head "generated\t" cell(gen_by) "\t" cell(made_at != "" ? made_at : made_raw) "\t" cell(made_rev) "\t" for (i = 1; i <= vn; i++) { k = ord[i]; print head "verified\t" cell(eby[k]) "\t" cell(shown[k]) "\t" cell(erev[k]) "\t" chk[k] } if (!hasgen && vn == 0) print head "\t\t\t\t" }' +# An index and a log are no concept in any folder, and KTL Registrar's +# diataxis.md is none at the bundle's root only. facts() { # every concept in the bundle -> the lines in the table above, V only when `rows` is 1 # One awk reads them all. A path from find is absolute, so awk never takes # it for an assignment. The shell leaves out a folder whose name ends in @@ -482,7 +494,9 @@ facts() { # every concept in the bundle -> the lines in the table above, V only # the exit status of awk, so a read that stopped early never passes for a # smaller bundle. find "$bundle/" -name '*.md' -not -path '*/.obsidian/*' | LC_ALL=C sort \ - | awk '{ n = $0; sub(/.*\//, "", n) } n != "index.md" && n != "log.md" && n != "diataxis.md"' \ + | KR_BUNDLE="$bundle" awk 'BEGIN { root = ENVIRON["KR_BUNDLE"]; sub(/\/+$/, "", root) } + { n = $0; sub(/.*\//, "", n); d = $0; sub(/\/+[^\/]*$/, "", d) } + n != "index.md" && n != "log.md" && !(n == "diataxis.md" && d == root)' \ | while IFS= read -r p; do [ -d "$p" ] || printf '%s\n' "$p"; done > "$tmp/files" [ -s "$tmp/files" ] || return 0 KR_LIST="$tmp/files" KR_BUNDLE="$bundle" awk -v SQ="'" -v rows="${rows:-0}" "$extract" < /dev/null @@ -591,6 +605,10 @@ quotes_load() { # A change in that recording commit, as a squash merge makes, is no move. An # event not yet committed is newer than any commit, and one that git cannot # find is skipped, so a moved source may be missed but is never invented. +# A `revision` on the event pins the resource of the concept alone. One that +# names a commit in this history takes the place of the recording commit. +# One that is a `sha256:` digest is compared with the file as HEAD holds it, +# so a change in the recording commit is a move too. # # For the work list, a source that a question of the librarian covers is in # `M a path list`, one that a closed pull request had before it in a `D` @@ -613,11 +631,12 @@ moved() { sources_load history_load revisions_load + digests_load round=0 while :; do round=$((round + 1)) : > "$tmp/need"; : > "$tmp/notes.next" - { printf '%s\n' "$all"; cat "$tmp/sources" "$tmp/hist" "$tmp/revs" "$tmp/anc" "$tmp/bodies" + { printf '%s\n' "$all"; cat "$tmp/sources" "$tmp/hist" "$tmp/revs" "$tmp/digs" "$tmp/anc" "$tmp/bodies" awk -F'\t' '{ print "ZT\t" $1 "\t" $2 " " $3 " " $4 }' "$tmp/touched" 2>/dev/null awk -F'\t' '{ print "ZQ\t" $1 "\t" $3 }' "$tmp/quoted" awk -F'\t' '{ print "ZG\t" $1 "\t" $2 }' "$tmp/quote_gone" @@ -806,6 +825,34 @@ revisions_load() { fi } +# The digest of each file that a compared event pins as `sha256:`, as `ZD +# resource digest`. The bytes are those HEAD holds, so a checkout that +# converts line endings gives the same digest. One git call writes each file +# out, and one call of the digest tool reads them all. A folder gets no +# line, and neither does any file on a host with no digest tool: the work +# list then compares with the recording commit. +digests_load() { + local res p i=0 + : > "$tmp/digs" + can_digest || return 0 + printf '%s\n' "$all" | awk -F'\t' ' + $1 == "I" { main[$2] = $5; next } + $1 == "C" && ($16 ~ /^sha256:[0-9a-f]+$/ || $17 ~ /^sha256:[0-9a-f]+$/) { want[$2] = 1 } + END { for (p in want) if (main[p] != "") print main[p] }' | LC_ALL=C sort -u > "$tmp/digq" + [ -s "$tmp/digq" ] || return 0 + awk -F'\t' -v want="$tmp/digq" 'BEGIN { while ((getline r < want) > 0) w[r] = 1 } + ($1 in w) && $2 == 1 && $3 == "P" { print $1 "\t" $4 }' "$tmp/res.top" > "$tmp/digp" + mkdir -p "$tmp/dig"; : > "$tmp/dign" + while IFS=$'\t' read -r res p; do + i=$((i + 1)) + if git -C "$top" cat-file blob "HEAD:$p" > "$tmp/dig/$i" 2>/dev/null; then printf '%s\t%s\n' "$i" "$res" >> "$tmp/dign"; else rm -f "$tmp/dig/$i"; fi + done < "$tmp/digp" + [ -s "$tmp/dign" ] || return 0 + (cd "$tmp/dig" && sha256 ./*) 2>/dev/null | awk -v names="$tmp/dign" ' + BEGIN { while ((getline l < names) > 0) { split(l, a, "\t"); res[a[1]] = a[2] } } + { h = $1; sub(/^\\/, "", h); n = $NF; sub(/.*\//, "", n); if (n in res) print "ZD\t" res[n] "\t" h }' > "$tmp/digs" +} + # Whether one commit comes before another in history, for each pair moved_fn # asked about, as `ZA first second 1` or `... 0`. A commit with several pairs # asks git once for the commits after it up to HEAD, whose history holds the @@ -871,6 +918,7 @@ bodies_run() { # ZH each concept: its last commit and day; ZF the commit that first wrote # a text in it; ZY a concept not yet committed (history_load) # ZV a revision that names a commit (revisions_load) +# ZD the digest of a file that a revision pins (digests_load) # ZA the order of two commits (ancestry_run); ZB whether a body changed # (bodies_run) # ZT the closed pull request that touched a concept; ZQ a passage a @@ -912,6 +960,9 @@ function names(t, p, n, off, i, at, before, after, beyond) { } return 0 } +# A note counts as left by a person when its actor is human: or the +# curator, which records the send-back of a person with no login. +function person(a) { return a ~ /^human:/ || a == "process:ktl-curator" } # The commit that first held a question a process asked, or "new". function asked_at(p, i) { c = first(p, "- " qd[p, i] ", " qa[p, i] ": " qt[p, i]); return c == "" ? "new" : c } # A question a process asked, naming the source, with this state of it before @@ -920,7 +971,7 @@ function asked_at(p, i) { c = first(p, "- " qd[p, i] ", " qa[p, i] ": " qt[p, i] # order, so any question on file that names it covers it. function asked_since(p, state, h, path, i, c) { for (i = 1; i <= nq[p]; i++) { - if (qa[p, i] ~ /^human:/ || !names(qt[p, i], path)) continue + if (person(qa[p, i]) || !names(qt[p, i], path)) continue c = asked_at(p, i) if (c == "new") return 1 if (h == "") { if (state == "gone") return 1 } @@ -931,7 +982,7 @@ function asked_since(p, state, h, path, i, c) { # A question a process asked at or after the commit that changed the body. function asked_after(p, h, i, c) { for (i = 1; i <= nq[p]; i++) { - if (qa[p, i] ~ /^human:/) continue + if (person(qa[p, i])) continue c = asked_at(p, i) if (c == "new") return 1 if (h != "" && anc(h, c)) return 1 @@ -947,6 +998,7 @@ $1 == "ZH" { LAST[$2] = $3; LDAY[$2] = $4; next } $1 == "ZF" { FIRST[$2, $4] = $3; next } $1 == "ZY" { DIRTY[$2] = 1; next } $1 == "ZV" { VALID[$2] = $3; next } +$1 == "ZD" { DIG[$2] = $3; next } $1 == "ZA" { ANC[$2, $3] = $4; next } $1 == "ZB" { BODY[$2, $3] = $4; next } $1 == "ZT" { if (!($2 in DEC)) DEC[$2] = $3; next } @@ -975,6 +1027,9 @@ END { # recording commit still does not count, and each other source is # compared with the commit that recorded the stamp. base = ""; if ((rv in VALID) && anc(VALID[rv], head)) base = VALID[rv] + # A digest that the `revision` gives, of the resource of the concept + # only: the file moved when HEAD holds other bytes. + dg = (rv ~ /^sha256:[0-9a-f]+$/) ? substr(rv, 8) : "" out = ""; asked = ""; aside = ""; nohist = "" for (i = 1; i <= m; i++) { r = srt[i]; if (!(r in STATE)) continue @@ -983,6 +1038,7 @@ END { else if (st == "edited") { if (!dirty) out = add(out, r " (edited, not yet committed" quoted(p, r) ")") } else if (st == "clean") { if (base != "" && r == MAIN[p]) { if (h != rec && h != base && anc(base, h)) entry = r " (" DAY[r] quoted(p, r) ")" } + else if (dg != "" && r == MAIN[p] && (r in DIG)) { if (DIG[r] != dg) entry = r " (" DAY[r] quoted(p, r) ")" } else if (rec != "" && h != rec && anc(rec, h)) entry = r " (" DAY[r] quoted(p, r) ")" } else if (st == "nohist" && which == "w") nohist = add(nohist, r) @@ -1023,7 +1079,7 @@ END { dec = (p in DEC) ? DEC[p] : ""; split(dec, dd, " ") rec = ($14 != "" ? first(p, $14) : "") for (i = 1; i <= nq[p]; i++) { - if (qa[p, i] !~ /^human:/) continue + if (!person(qa[p, i])) continue if ($4 != "draft" && $8 != "" && qd[p, i] <= substr($8, 1, 10)) continue note = first(p, "- " qd[p, i] ", " qa[p, i] ": " qt[p, i]) if (note == "") print "new" > notefile @@ -1084,11 +1140,61 @@ health() { # [] END { printf "Confirmed by a person: %d of %d · Checked by automation only: %d · Nobody has checked: %d · Drafts: %d · Reopened: %d · Past review date: %d · Edited since confirmed: %d · Retired: %d%s\n", confirmed, n, auto, none, drafts, reop, past, was, retired, (unsigned != "" ? " · Not tied to a signed commit: " unsigned : "") }' } -# The concept that replaced a retired one, as Sretiredsuccessor: -# the link after "replaced by", in the `../` form that ktl-curator and the -# KTL Curator plugin write, in the newest **Deprecation** line of log.md that -# links the retired concept. A line with no such link names no successor. +# The base_iri of the root index.md, or nothing. +bundle_base() { + awk -v SQ="'" '{ sub(/\r$/, "") } NR == 1 { sub(/^\357\273\277/, "") } NR == 1 { if ($0 != "---") exit; next } $0 == "---" { exit } + /^base_iri:/ { v = $0; sub(/^base_iri:[ \t]*/, "", v); sub(/[ \t\r]+$/, "", v) + if (substr(v, 1, 1) == "\"" || substr(v, 1, 1) == SQ) v = substr(v, 2, length(v) - 2); print v; exit }' "$bundle/index.md" 2>/dev/null || true +} + +# A relation target resolved to the path of a concept, as the KTL Curator +# plugin resolves it: +# - an IRI under base_iri, by the path after it; +# - any other IRI, as written; +# - a relative path, from the root of the bundle and then from the folder +# of the citing concept. +# A concept's id is its `id`, or base_iri and its path without `.md`. The +# caller sets `base` and fills `order`, `nc` and `cid`, then calls ids(). +# shellcheck disable=SC2016 # awk's own fields, not the shell's +resolve_fn=' +function ids( i, p, id) { for (i = 1; i <= nc; i++) { p = order[i]; id = cid[p]; if (id == "") { id = p; sub(/\.md$/, "", id); id = base id }; byid[id] = p } } +function cut(v, i) { i = index(v, "#"); return i ? substr(v, 1, i - 1) : v } +function find(id) { return (id in byid) ? byid[id] : "" } +function resolve(v, from, d, r) { + if (v in byid) return byid[v] + if (v ~ /^[A-Za-z][A-Za-z0-9+.-]*:/) { + if (base == "" || index(v, base) != 1) return "" + v = cut(substr(v, length(base) + 1)); sub(/\.md$/, "", v) + return find(base v) + } + if (base == "") return "" + v = cut(v); sub(/^\//, "", v); sub(/\.md$/, "", v) + r = find(base v); if (r != "") return r + d = from; if (sub(/\/[^\/]*$/, "", d)) return find(base d "/" v) + return "" +}' + +# The concept that replaced a retired one, as Sretiredsuccessor. +# Its isReplacedBy decides: the first target, in the field or in `relations`, +# that names a concept of the bundle. ktl-curator writes it on Retire. Where +# it names none, the link after "replaced by" in the newest **Deprecation** +# line of log.md that links the retired concept, in the `../` form that +# ktl-curator and the KTL Curator plugin write; a retirement recorded before +# the slot has only that line. A line with no such link names no successor. +# The first S line for a concept is the one read. successors() { + printf '%s\n' "$all" | awk -F'\t' -v base="$(bundle_base)" "$resolve_fn"' + $1 == "C" { nc++; order[nc] = $2; st[$2] = $4 } + $1 == "I" { cid[$2] = $3 } + $1 == "L" && $3 == "isReplacedBy" { nl++; lp[nl] = $2; lt[nl] = $4 } + END { + ids() + for (i = 1; i <= nl; i++) { + p = lp[i]; if (st[p] != "deprecated" || (p in named)) continue + t = resolve(lt[i], p); if (t == "" || t == p) continue + named[p] = 1; print "S\t" p "\t" t + } + }' [ -f "$bundle/log.md" ] || return 0 awk ' function target(s, a, b) { @@ -1109,13 +1215,13 @@ successors() { # right after the kind, `- **Disagreement** (on ``) -`, where no text # of a reader can stand, and `disputed` reads nothing else of the entry. A # path counts only in the path spelling of the bundle, only while it names a -# concept, and never for an index, a log or diataxis.md. +# concept, and never for an index, a log or the diataxis.md at the root. disputed() { [ -f "$root/.lokf/feedback.md" ] || return 0 awk -v dir="$bundle" ' function held(p, line, there) { if (p !~ /^[a-z0-9][a-z0-9._\/-]*\.md$/ || p ~ /\.\./) return 0 - if (p ~ /(^|\/)(index|log|diataxis)\.md$/) return 0 + if (p ~ /(^|\/)(index|log)\.md$/ || p == "diataxis.md") return 0 there = (getline line < (dir "/" p)); close(dir "/" p); return there >= 0 } /^## [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]/ { day = substr($0, 4, 10); next } @@ -1191,7 +1297,7 @@ lists() { # mode END { if (mode == "questions" || mode == "worklist") { for (i = 1; i <= nq; i++) { - split(q[i], f, "\t"); p = f[2]; who = (f[4] ~ /^human:/ ? "person" : "process") + split(q[i], f, "\t"); p = f[2]; who = ((f[4] ~ /^human:/ || f[4] == "process:ktl-curator") ? "person" : "process") if (answered(p, f[3])) { na++; a = a "- " p " (" f[3] ", " f[4] "; a person confirmed the concept " day(human[p]) ")" (mode == "questions" ? ": " f[5] : "") "\n" } else if (who == "person") { nw++; w = w "- " p " (" f[3] ", " f[4] ")" (mode == "questions" ? ": " f[5] : "") "\n" } else { no++; o = o "- " p " (" f[3] ", " f[4] ")" (mode == "questions" ? ": " f[5] : "") "\n" } @@ -1252,13 +1358,7 @@ repeats() { # concepts the ledger names more than once: readers keep asking abo # ---- the curator's queue ----------------------------------------------------- # A relation is one of the fourteen fields, `relations`, or a whole IRI in a -# slot of a domain vocabulary. Its target is resolved as the KTL Curator -# plugin resolves it: -# - an IRI under base_iri, by the path after it; -# - any other IRI, as written; -# - a relative path, from the root of the bundle and then from the folder -# of the citing concept. -# A concept's id is its `id`, or base_iri and its path without `.md`. +# slot of a domain vocabulary, and resolve_fn resolves its target. # Each concept that names another counts once for it, never for itself, and # every list here leaves retired concepts out. `queue` prints Worth ten # minutes today, in the order that ktl-curator/references/trust-fields.md @@ -1270,27 +1370,10 @@ repeats() { # concepts the ledger names more than once: readers keep asking abo # work list, moving on by ten each month, or the counts for the report. ranked() { # queue | lists | isolated | isolated-worklist | isolated-count local base - base="$(awk -v SQ="'" '{ sub(/\r$/, "") } NR == 1 { sub(/^\357\273\277/, "") } NR == 1 { if ($0 != "---") exit; next } $0 == "---" { exit } - /^base_iri:/ { v = $0; sub(/^base_iri:[ \t]*/, "", v); sub(/[ \t\r]+$/, "", v) - if (substr(v, 1, 1) == "\"" || substr(v, 1, 1) == SQ) v = substr(v, 2, length(v) - 2); print v; exit }' "$bundle/index.md" 2>/dev/null || true)" - { printf '%s\n' "$all"; printf '%s\n' "$times"; } | awk -F'\t' -v mode="$1" -v today="$today" -v base="$base" "$label_fn"' + base="$(bundle_base)" + { printf '%s\n' "$all"; printf '%s\n' "$times"; } | awk -F'\t' -v mode="$1" -v today="$today" -v base="$base" "$label_fn$resolve_fn"' function jdn(d, y, m, a) { y = substr(d, 1, 4) + 0; m = substr(d, 6, 2) + 0; a = int((14 - m) / 12); y += 4800 - a; m += 12 * a - 3 return substr(d, 9, 2) + int((153 * m + 2) / 5) + 365 * y + int(y / 4) - int(y / 100) + int(y / 400) - 32045 } - function cut(v, i) { i = index(v, "#"); return i ? substr(v, 1, i - 1) : v } - function find(id) { return (id in byid) ? byid[id] : "" } - function resolve(v, from, d, r) { - if (v in byid) return byid[v] - if (v ~ /^[A-Za-z][A-Za-z0-9+.-]*:/) { - if (base == "" || index(v, base) != 1) return "" - v = cut(substr(v, length(base) + 1)); sub(/\.md$/, "", v) - return find(base v) - } - if (base == "") return "" - v = cut(v); sub(/^\//, "", v); sub(/\.md$/, "", v) - r = find(base v); if (r != "") return r - d = from; if (sub(/\/[^\/]*$/, "", d)) return find(base d "/" v) - return "" - } function also(s, t) { return s == "" ? t : s "; " t } function group(x) { while (up[x] != x) { up[x] = up[up[x]]; x = up[x] } return x } function relies(n) { return n == 1 ? "1 other concept relies on this" : n " other concepts rely on this" } @@ -1307,7 +1390,7 @@ ranked() { # queue | lists | isolated | isolated-worklist | isolated-count $1 == "M" && $2 == "c" { cmoved[$3] = 1 } $1 == "K" { held_back[$2] = 1 } END { - for (i = 1; i <= nc; i++) { p = order[i]; id = cid[p]; if (id == "") { id = p; sub(/\.md$/, "", id); id = base id }; byid[id] = p } + ids() for (i = 1; i <= nc; i++) { p = order[i]; $0 = row[p] if ($4 == "deprecated") continue @@ -1360,7 +1443,7 @@ ranked() { # queue | lists | isolated | isolated-worklist | isolated-count section("Due soon, a review date within 30 days", ns, soon) for (k = 1; k <= nd; k++) { a = dfrom[k]; b = dto[k] - if (conf[a] && gat[b] != "" && gat[b] > hat[a]) { nx++; drv = drv "- " a ": " b " (edited " day(gat[b]) ", confirmed " day(hat[a]) ")\n" } + if (conf[a] && hat[a] != "" && gat[b] != "" && gat[b] > hat[a]) { nx++; drv = drv "- " a ": " b " (edited " day(gat[b]) ", confirmed " day(hat[a]) ")\n" } } section("Confirmed by a person, and derived from a concept edited after that confirmation", nx, drv) m = 0 @@ -1493,7 +1576,8 @@ changes() { st="${line%%$'\t'*}"; path="${line#*$'\t'}" case "$path" in *.md) ;; *) continue ;; esac rel="${path#"$pfx"}"; rel="${rel#.lokf/knowledge/}"; rel="${rel#knowledge_bundle/}" - case "${rel##*/}" in index.md|log.md|diataxis.md) continue ;; esac + case "${rel##*/}" in index.md|log.md) continue ;; esac + [ "$rel" != diataxis.md ] || continue case "$st" in A*) added=$((added + 1)); continue ;; D*) removed=$((removed + 1)) ;; *) changed=$((changed + 1)) ;; esac was="$(git -C "$root" show "HEAD:$path" 2>/dev/null | awk -v path="$rel" -v SQ="'" "$extract" | awk -F'\t' "$label_fn$standing_fn")" case "$was" in ""|none) continue ;; esac @@ -1798,8 +1882,8 @@ as_number() { # -> the number without its leading zeros, which bash an } can_digest() { command -v sha256sum >/dev/null 2>&1 || command -v shasum >/dev/null 2>&1; } no_digest="Sample: not drawn here, since the pick needs sha256sum or shasum and this host has neither" -sha256() { # standard input -> its SHA-256 as hex, then what the tool prints after it - if command -v sha256sum >/dev/null 2>&1; then sha256sum; else shasum -a 256; fi +sha256() { # standard input, or each file named -> its SHA-256 as hex, then what the tool prints after it + if command -v sha256sum >/dev/null 2>&1; then sha256sum "$@"; else shasum -a 256 "$@"; fi } # The seed reaches printf and the digest as it was given, and never awk, # which would read a backslash in it as an escape. A list whose size is 0 is @@ -1994,6 +2078,7 @@ times="" case "$cmd" in health) [ $# -eq 0 ] || usage; health ;; labels) labels "$@" ;; + questions) [ $# -eq 0 ] || usage; lists questions ;; coverage) coverage "$@"; exit $? ;; isolated) [ $# -eq 0 ] || usage; ranked isolated ;; worklist) @@ -2046,7 +2131,7 @@ case "$cmd" in unconfirmed_successors echo "" echo "Reader feedback waiting: $(waiting_feedback)" - disputed | awk -F'\t' '{ n++; body = body "- " $2 " (" $3 ")\n" } END { print "Disputed by a reader, waiting for the librarian: " (n ? n : "none"); if (n) printf "%s", body }' + { printf '%s\n' "$all"; disputed; } | awk -F'\t' '$1 == "C" { st[$2] = $4; next } $1 == "G" && st[$2] != "deprecated" { n++; body = body "- " $2 " (" $3 ")\n" } END { print "Disputed by a reader, waiting for the librarian: " (n ? n : "none"); if (n) printf "%s", body }' repeats # The sample, only when the curation policy asks for one. ni="$(policy_size "independent re-check")"; na="$(policy_size "automation re-check")" diff --git a/.lokf/scripts/knowledge-sync.sh b/.lokf/scripts/knowledge-sync.sh index c9f0a56..85bea8b 100755 --- a/.lokf/scripts/knowledge-sync.sh +++ b/.lokf/scripts/knowledge-sync.sh @@ -550,6 +550,7 @@ main() { if [[ ! -f "$host/$dst" ]]; then mkdir -p "$(dirname "$host/$dst")" cat "$new_w/website/$rel" > "$host/$dst" + [[ ! -x "$new_w/website/$rel" ]] || chmod +x "$host/$dst" added+=("$dst (the site cannot build without it)") elif cmp -s "$new_w/website/$rel" "$host/$dst"; then same+=("$dst") @@ -560,6 +561,7 @@ main() { copied+=("$dst") fi cat "$new_w/website/$rel" > "$host/$dst" + [[ ! -x "$new_w/website/$rel" ]] || chmod +x "$host/$dst" fi done < <(cd "$new_w/website" && find . -type f ! -path '*/__pycache__/*' | sed 's#^\./##' | LC_ALL=C sort) local wsrc="github/knowledge-website.yaml" wdst=".github/workflows/knowledge-website.yaml" diff --git a/.lokf/uv.lock b/.lokf/uv.lock index 143e5d8..cae314d 100644 --- a/.lokf/uv.lock +++ b/.lokf/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.14'", @@ -796,11 +796,11 @@ wheels = [ [[package]] name = "ktl" -version = "0.66.0" +version = "0.69.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/fa/65/9094eb1e9f790d8da3853a6c8cb448d4adf268932415ff81b66f418d216a/ktl-0.66.0.tar.gz", hash = "sha256:df70a2b5b5b792a992edb64e5a1fdbe39a8f4d7b5e327a54cb4439573d6b2cad", size = 830226, upload-time = "2026-11-15T14:29:24.613Z" } +sdist = { url = "https://files.pythonhosted.org/packages/6f/f2/cb72906f948d1bf8cd0ddf36c6c7887b8d38501b5bb20a84d191a8864efd/ktl-0.69.2.tar.gz", hash = "sha256:60d2bb906f83bd0575ff4496042e226c2d511e1e5f68b0351887c0296d729784", size = 865055, upload-time = "2026-11-18T23:54:27.079Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/72/5e/5956bcb792858c3fda1dc8b0e24e0a0432575eb76e5a2563cb85b4668208/ktl-0.66.0-py3-none-any.whl", hash = "sha256:3bebc157f30b70d6b3406927007e51295140c997379611647bc7fa9b7dfbe720", size = 941260, upload-time = "2026-11-15T14:29:22.82Z" }, + { url = "https://files.pythonhosted.org/packages/e3/a5/006c3b870563f31ee2fb380addb9ef5a46cc2ca4aa91292a3dd8307a3ff5/ktl-0.69.2-py3-none-any.whl", hash = "sha256:dcf971f27d7487e74e4c4cd72296a000d0f0aab191d79693ddadb05d1c35acf4", size = 980702, upload-time = "2026-11-18T23:54:25.276Z" }, ] [[package]] @@ -2027,7 +2027,7 @@ dependencies = [ [package.metadata] requires-dist = [ - { name = "ktl", specifier = "==0.66.0" }, + { name = "ktl", specifier = "==0.69.2" }, { name = "lokf", extras = ["build"], specifier = ">=0.9.0" }, { name = "rust-just", specifier = "==1.59.0" }, ] diff --git a/CHANGELOG.md b/CHANGELOG.md index ad10205..b221c87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ The `v0.1.0` tag is a baseline, not a release: it marks where versioning starts ## [Unreleased] +### Security + +- **The sidecar copies and the skills pin are at Knowledge Trust Ladder [v0.69.2](https://github.com/noelmcloughlin/knowledge-trust-ladder/compare/v0.66.0...v0.69.2).** The release changed `.github/workflows/knowledge-registrar.yaml`, `.github/workflows/knowledge-librarian.yaml`, `.github/workflows/knowledge-release.yaml`, `.github/workflows/knowledge-sync.yaml`, `.github/PULL_REQUEST_TEMPLATE/knowledge-sync.md`, `.lokf/scripts/knowledge-conventions.sh`, `.lokf/scripts/knowledge-conventions.py`, `.lokf/scripts/knowledge-preflight.sh`, `.lokf/scripts/knowledge-provenance.sh`, `.lokf/scripts/knowledge-feedback.sh`, `.lokf/scripts/knowledge-apply.py`, `.lokf/scripts/knowledge-report.sh`, `.lokf/scripts/knowledge-sync.sh`, `.lokf/m365/ktl-docent-m365.md`, `.lokf/justfile`, `website/assets/css/site.css`, `website/assets/js/graph.js`, `website/assets/js/site.js`, `website/content/_content.gotmpl`, `website/content/knowledge/_content.gotmpl`, `website/.gitignore`, `website/hugo.toml`, `website/layouts/_markup/render-blockquote.html`, `website/layouts/_markup/render-codeblock-mermaid.html`, `website/layouts/_markup/render-heading.html`, `website/layouts/_markup/render-link.html`, `website/layouts/_partials/gendoc.html`, `website/layouts/_partials/heroes.html`, `website/layouts/_partials/icon.html`, `website/layouts/_partials/markdown-file.html`, `website/layouts/_partials/nav-key.html`, `website/layouts/_partials/route.html`, `website/layouts/_partials/schema-file.html`, `website/layouts/_partials/sidebar.html`, `website/layouts/_partials/tools.html`, `website/layouts/_partials/vendor.html`, `website/layouts/baseof.html`, `website/layouts/health.html`, `website/layouts/home.badge.json`, `website/layouts/home.llms.txt`, `website/layouts/page.atom.xml`, `website/layouts/page.html`, `website/layouts/schema/section.html`, `website/pyproject.toml`, `website/scripts/build.sh`, `website/scripts/clean-html.py`, `website/scripts/prepare.sh`, `website/uv.lock`, `.github/workflows/knowledge-website.yaml`, `website/layouts/_partials/own.html`, `website/layouts/_partials/spec.html`, `website/scripts/check-svg.py`, `website/scripts/lokf-export.py`, `website/scripts/site-values.py`, `website/scripts/uv-env.sh` and `website/scripts/vendor.sh` here. + ## [0.11.3] - 2026-11-16 ### Fixed diff --git a/website/.gitignore b/website/.gitignore index a0875db..95148ea 100644 --- a/website/.gitignore +++ b/website/.gitignore @@ -1,5 +1,5 @@ # Everything below is written by scripts/build.sh. The sources are the -# README, docs/, .assets/, the changelog, the schema and the bundle. +# README, SPEC.md, docs/, .assets/, the changelog, the schema and the bundle. .venv/ generated/ dist/ diff --git a/website/assets/css/site.css b/website/assets/css/site.css index 33b2fb6..193c6d6 100644 --- a/website/assets/css/site.css +++ b/website/assets/css/site.css @@ -3,9 +3,10 @@ the page follows the system's scheme, and the reader's choice in the Display menu overrides it by setting color-scheme alone. Every size is in rem, so the browser's own text size and the menu's Text size both scale the - whole page. Large is the size a reader gets before choosing one. The paper and ink are the Astro site's Catalogue style: one + whole page. Medium, the browser's own size, is the size a reader gets + before choosing one. The paper and ink are the site's Catalogue style: one warm hue, hsl(45), at each lightness, so the page reads as a museum's wall - and not a screen's white. The trust colours are the Astro site's too. + and not a screen's white. The trust colours are the site's own too. */ @font-face { font-family: "Atkinson Hyperlegible Next"; src: url("../fonts/atkinson-hyperlegible-next-latin-wght-normal.woff2") format("woff2"); font-weight: 200 800; font-display: swap; } @font-face { font-family: "Atkinson Hyperlegible Next"; src: url("../fonts/atkinson-hyperlegible-next-latin-wght-italic.woff2") format("woff2"); font-weight: 200 800; font-style: italic; font-display: swap; } @@ -35,8 +36,8 @@ } :root[data-theme="light"] { color-scheme: light; } :root[data-theme="dark"] { color-scheme: dark; } -:root { font-size: 112.5%; } -:root[data-size="medium"] { font-size: 100%; } +:root { font-size: 100%; } +:root[data-size="large"] { font-size: 112.5%; } :root[data-size="larger"] { font-size: 125%; } * { box-sizing: border-box; } body { margin: 0; background: var(--bg); color: var(--fg); font: 1rem/1.6 var(--sans); overflow-wrap: break-word; } @@ -89,6 +90,7 @@ main { min-width: 0; padding: 1.5rem 0 4rem; } .sidebar ul { list-style: none; margin: 0 0 .3rem; padding: 0; } .sidebar li a, .sidebar summary { display: block; padding: .28rem .5rem; border-radius: 6px; color: var(--fg); text-decoration: none; } .sidebar :is(li a, summary, .section--link):hover { background: color-mix(in srgb, var(--fg) 8%, transparent); } +.sidebar .nav-graph a { display: flex; gap: .45rem; align-items: center; margin: .15rem 0; background: color-mix(in srgb, var(--brand) 9%, transparent); color: var(--brand); font-weight: 600; } .sidebar a[aria-current] { background: var(--tint); box-shadow: inset 3px 0 var(--brand); font-weight: 600; } .sidebar summary { font-weight: 600; cursor: pointer; list-style: none; } .sidebar summary::-webkit-details-marker { display: none; } @@ -160,8 +162,9 @@ pre:hover .copy, .copy:focus-visible { opacity: 1; } .alert { margin: 1rem 0; padding: .4rem 1rem; border-left: 4px solid var(--accent); border-radius: 0 6px 6px 0; background: var(--panel); } .alert__title { margin: .3rem 0; font-weight: 600; } .alert--warning, .alert--caution { border-color: var(--chart-edited); } -/* The home page's five buttons, in one row of equal widths. One whose page the repository lacks keeps its place, greyed. */ -.actions { display: grid; grid-template-columns: repeat(auto-fit, minmax(8.5rem, 1fr)); gap: .6rem; margin: 0 0 1.5rem; } +/* The home page's buttons, as near equal in width as the longest label allows, wrapping on a narrow screen. One whose page the repository lacks keeps its place, greyed. */ +.actions { display: flex; flex-wrap: wrap; gap: .6rem; margin: 0 0 1.5rem; } +.actions > .button { flex: 1 1 0; max-width: 12rem; } .button { padding: .45rem .6rem; border: 1px solid var(--brand); border-radius: 999px; background: var(--brand); color: var(--bg); text-align: center; text-decoration: none; font-weight: 600; white-space: nowrap; } .button--secondary { background: none; color: var(--brand); } .button--missing { border-style: dashed; border-color: var(--rule); background: none; color: var(--muted); font-weight: 400; cursor: not-allowed; } @@ -212,7 +215,8 @@ a[data-preview]:is(:hover, :focus-visible)::after { content: attr(data-preview) .dot--nobody { border-style: dotted; } .dot--retired { border-style: dotted; opacity: .6; } .label, .chip { display: inline-block; padding: .1rem .6rem; border-radius: 999px; font-size: .85rem; } -.label { margin: 0; color: var(--nobody-fg); background: var(--nobody-bg); } +/* A long label, such as a successor's path, wraps inside its own width: a pill on one line, a rounded box on two. */ +.label { max-width: 100%; margin: 0; border-radius: 1.2em; overflow-wrap: break-word; color: var(--nobody-fg); background: var(--nobody-bg); } .label--person { color: var(--person-fg); background: var(--person-bg); } .label--edited { color: var(--edited-fg); background: var(--edited-bg); } .label--automation { color: var(--automation-fg); background: var(--automation-bg); } @@ -322,8 +326,8 @@ a[data-preview]:is(:hover, :focus-visible)::after { content: attr(data-preview) /* Narrower screens: first a concept's neighbours move under its words, then the navigation becomes a menu the header opens. A media query's rem is the - browser's own 16px, whatever the Text size, so each width is the one that - suits Large, the size a reader starts with. + browser's own 16px, whatever the Text size, so each width is one that still + suits Large. Medium, the size a reader starts with, has room to spare. */ @media (max-width: 84rem) { .layout, .layout:has(> .aside) { grid-template-columns: 16.5rem minmax(0, 1fr); } diff --git a/website/assets/js/graph.js b/website/assets/js/graph.js index e44e96d..a27f53e 100644 --- a/website/assets/js/graph.js +++ b/website/assets/js/graph.js @@ -89,6 +89,8 @@ addEventListener("DOMContentLoaded", async () => { } catch (error) { return say(`The graph could not be loaded: ${error.message}`); } + // With no concept there are no rings to lay out, so the page says so and draws nothing. + if (!graph.nodes?.length) return say(workspace ? "The workspace holds no concept yet." : "The bundle holds no concept yet."); // A concept of this bundle has the trust label the report script printed. // A workspace's concept has only the tier `lokf export` gave it, shown in diff --git a/website/assets/js/site.js b/website/assets/js/site.js index 780538f..8d33a19 100644 --- a/website/assets/js/site.js +++ b/website/assets/js/site.js @@ -4,7 +4,7 @@ // The reader's choices in the Display menu, kept in this browser. They are // applied before the page is drawn, so a dark page never flashes light. const root = document.documentElement; -const defaults = { theme: "auto", size: "large" }; +const defaults = { theme: "auto", size: "medium" }; const prefs = { ...defaults }; try { Object.assign(prefs, JSON.parse(localStorage.getItem("ktl-display") || "{}")); @@ -209,27 +209,56 @@ addEventListener("DOMContentLoaded", () => { }); } - // A diagram takes the page's own paper, ink and lines, in the scheme the reader chose. - if (typeof window.mermaid?.initialize === "function") { - const css = getComputedStyle(document.body); - const probe = document.body.appendChild(document.createElement("span")); - const color = (name) => { - probe.style.color = `var(${name})`; - return getComputedStyle(probe).color; + // Mermaid keeps the colours it started with, so each diagram's source is kept, and every diagram is drawn + // again when the Display menu or the system changes the scheme. + if (typeof window.mermaid?.initialize === "function" && typeof window.mermaid.run === "function") { + const diagrams = [...document.querySelectorAll(".prose .mermaid")].map((pre) => ({ pre, source: pre.textContent })); + const colours = () => { + const probe = document.body.appendChild(document.createElement("span")); + const color = (name) => { + probe.style.color = `var(${name})`; + return getComputedStyle(probe).color; + }; + const themeVariables = { + darkMode: matchMedia("(prefers-color-scheme: dark)").matches ? prefs.theme !== "light" : prefs.theme === "dark", + fontFamily: getComputedStyle(document.body).fontFamily, + background: color("--bg"), + primaryColor: color("--card"), + primaryTextColor: color("--fg"), + primaryBorderColor: color("--rule"), + secondaryColor: color("--panel"), + tertiaryColor: color("--panel"), + lineColor: color("--muted"), + textColor: color("--fg"), + }; + probe.remove(); + return themeVariables; }; - const themeVariables = { - darkMode: matchMedia("(prefers-color-scheme: dark)").matches ? prefs.theme !== "light" : prefs.theme === "dark", - fontFamily: css.fontFamily, - background: color("--bg"), - primaryColor: color("--card"), - primaryTextColor: color("--fg"), - primaryBorderColor: color("--rule"), - secondaryColor: color("--panel"), - tertiaryColor: color("--panel"), - lineColor: color("--muted"), - textColor: color("--fg"), + let drawn = ""; + const draw = async () => { + const themeVariables = colours(); + // The Display menu's Text size changes no colour, so the diagrams stay as they are. + if (JSON.stringify(themeVariables) === drawn) return; + drawn = JSON.stringify(themeVariables); + // A diagram open at full size goes back to its place first, and is drawn again there. + if (zoom?.open && view) { + view.put(); + view = null; + zoom.close(); + } + mermaid.initialize({ startOnLoad: false, theme: "base", themeVariables }); + for (const { pre, source } of diagrams) { + pre.removeAttribute("data-processed"); + pre.textContent = source; + } + await mermaid.run({ nodes: diagrams.map(({ pre }) => pre), suppressErrors: true }); }; - probe.remove(); - mermaid.initialize({ startOnLoad: true, theme: "base", themeVariables }); + // One drawing at a time, in the order asked for. The first waits for the page's fonts, which set each label's width. + let last = Promise.resolve(); + const redraw = () => (last = last.then(draw, draw)); + if (document.readyState === "complete") redraw(); + else addEventListener("load", redraw); + document.addEventListener("displaychange", redraw); + matchMedia("(prefers-color-scheme: dark)").addEventListener("change", redraw); } }); diff --git a/website/content/_content.gotmpl b/website/content/_content.gotmpl index eb84f2d..c908c1c 100644 --- a/website/content/_content.gotmpl +++ b/website/content/_content.gotmpl @@ -11,6 +11,20 @@ "params" (dict "repoPath" (path.Join (strings.Trim (site.Params.source | default "") "/") "README.md")) "content" (dict "value" (partial "literal.html" $body))) -}} {{- end -}} +{{- /* + A root SPEC.md becomes the specification's page, /spec/, as written. Its + title is the file's first `# ` heading, which stays the page's h1, and its + frontmatter is read as data, as the README's is. With no SPEC.md, no page + is added. +*/ -}} +{{- with resources.Get "spec/SPEC.md" -}} + {{- $body := .Content | replaceRE `(?s)\A---\r?\n.*?\r?\n---[ \t]*(?:\r?\n|\z)` "" -}} + {{- $title := "" -}} + {{- with findRESubmatch `(?m)^# +(.+?)\s*$` $body 1 }}{{ $title = index . 0 1 | replaceRE "[*`]" "" | replaceRE `\[([^\]]+)\]\([^)]*\)` "$1" }}{{ end -}} + {{- $.AddPage (dict "kind" "page" "path" "spec" "title" (or $title "Specification") + "params" (dict "repoPath" (path.Join (strings.Trim (site.Params.source | default "") "/") "SPEC.md")) + "content" (dict "value" (partial "literal.html" $body))) -}} +{{- end -}} {{- /* A page at each old address `params.redirects` names, which sends the browser to the page built from the repository file named. An entry such as diff --git a/website/content/knowledge/_content.gotmpl b/website/content/knowledge/_content.gotmpl index 42f80a3..c94e146 100644 --- a/website/content/knowledge/_content.gotmpl +++ b/website/content/knowledge/_content.gotmpl @@ -4,12 +4,21 @@ A concept's frontmatter goes under `params.concept` and never to Hugo's own keys, so a concept that sets `url`, `aliases`, `draft` or `layout` changes nothing here. A new group folder needs no line anywhere. + + Three names are not concepts, by the rule knowledge-report.sh follows, so + it prints no label for them. index.md and log.md are not in any folder, + since the lokf toolkit reserves them. diataxis.md is not at the bundle's + root, where the KTL Registrar plugin writes its map. A diataxis.md in a + folder is a concept like any other. A folder's log.md and the root's + diataxis.md get no page. Each is still served as Markdown, and a link to + one goes to GitHub. */ -}} {{- $files := resources.Match "bundle/**.md" -}} {{- $ids := slice -}} {{- range $files }}{{ $ids = $ids | append (.Name | strings.TrimPrefix "/bundle/" | strings.TrimSuffix ".md") }}{{ end -}} {{- range $files -}} {{- $rel := strings.TrimPrefix "/bundle/" .Name -}} + {{- if or (eq $rel "diataxis.md") (and (eq (path.Base $rel) "log.md") (ne $rel "log.md")) }}{{ continue }}{{ end -}} {{- $fm := dict -}} {{- $body := .Content -}} {{- with findRESubmatch `(?s)\A---\r?\n(.*?)\r?\n---[ \t]*(?:\r?\n|\z)(.*)\z` .Content 1 -}} diff --git a/website/hugo.toml b/website/hugo.toml index f8caaa0..2981ca1 100644 --- a/website/hugo.toml +++ b/website/hugo.toml @@ -7,9 +7,9 @@ # copies pages into content/. scripts/prepare.sh runs first, for `lokf # export`, the trust labels and the pages gen-doc writes for a LinkML schema. # -# A served file the browser would run as a page of the site's origin, which -# every project site of the owner shares, is never published: an HTML or XML -# document, and an SVG that prepare.sh finds a script in. +# Every project site of the owner shares the site's origin, so no file a +# browser runs as a page is served: the mounts below list the kinds they +# serve, and prepare.sh stops on an SVG that could run a script. locale = "en" disableKinds = ["taxonomy", "term", "rss"] enableRobotsTXT = true @@ -25,11 +25,16 @@ releaseTag = "v{version}" # Folders under docs/ that are not pages of the site: the templates and the # pages LinkML's gen-doc keeps there. The schema's pages are built afresh. docsExclude = ["templates-linkml", "elements"] +# The endings served from docs/ and .assets/; route.html sends a link to +# any other file to GitHub. Their mounts below repeat the list. +served = ["avif", "gif", "ico", "jpeg", "jpg", "pdf", "png", "svg", "webp"] # The libraries the graph page and Mermaid diagrams need. Hugo fetches each # once at build time, checks it against its hash and serves it from the site, # so no page calls a CDN. Where the CDN is blocked, give `url` a mirror's -# address in site.toml. +# address in site.toml, or keep a copy as assets/vendor/.js, which the +# build takes first and checks against the same hash. scripts/vendor.sh +# writes the copies from an npm registry. [params.vendor.cytoscape] url = "https://cdn.jsdelivr.net/npm/cytoscape@3.34.4/dist/cytoscape.min.js" sha256 = "081591ab735b2b6a3b31a3c60f8f3a3e2fee8c92939e0c7820ad1208571b6cd8" @@ -94,18 +99,21 @@ getenv = ["^HUGO_"] source = "content" target = "content" -# The README, the docs, the bundle and the changelog are read by the content -# adapters in content/, content/docs/, content/knowledge/ and -# content/changelog/, which write the home page and a page per file, per -# concept and per release. A file's own frontmatter is data there, so no key -# in it can move, hide or redirect a page. +# The README, a root SPEC.md, the docs, the bundle and the changelog are read +# by the content adapters in content/, content/docs/, content/knowledge/ and +# content/changelog/, which write the home page, the specification's page +# and a page per file, per concept and per release. A file's own frontmatter +# is data there, so no key in it can move, hide or redirect a page. [[module.mounts]] source = "../README.md" target = "assets/readme/README.md" [[module.mounts]] +source = "../SPEC.md" +target = "assets/spec/SPEC.md" +[[module.mounts]] source = "../docs" target = "assets/docs" -files = ["! .**", "! **/.**", "! **.{html,htm,xhtml,xht,xml,xsl,xslt,shtml,mht,mhtml}"] +files = ["! .**", "! **/.**"] [[module.mounts]] source = "assets" target = "assets" @@ -123,9 +131,9 @@ target = "assets/ingest/ingest.lock.yaml" # What the site shows only when the repository has it. A mount whose source # is missing mounts nothing, so neither needs a setting, and nor do the -# README, the docs, the changelog and the figures above and below. The first is the +# README, SPEC.md, the docs, the changelog and the figures above and below. The first is the # folder of pages prepare.sh has gen-doc write for a LinkML schema, or for -# LOKF core when the repository holds none. The second is the +# the bundle's domain vocabulary or LOKF core when the repository holds none. The second is the # workflow of a domain host, whose graph page offers the workspace that # workflow serves at workspace/. [[module.mounts]] @@ -135,25 +143,29 @@ target = "assets/gendoc" source = "../.github/workflows/knowledge-federation.yaml" target = "assets/host/knowledge-federation.yaml" -# Served as they are: the figures, each bundle file as raw Markdown beside -# its page, the other files of the docs folder, and the four export files. A -# docs page's Markdown is written by markdown-file.html, with full addresses. -# No file or folder whose name starts with a dot is served. +# Served as they are: the figures and PDF files of .assets/ and of the docs +# folder, each bundle file as raw Markdown beside its page, and the four +# export files. A docs page's Markdown is written by markdown-file.html, with +# full addresses. +# +# Hugo takes a mount's first matching pattern, so the `! ` patterns that +# leave out dot files come first, then the endings served, in either case. +# `**/` matches folders alone, so Hugo looks inside them. [[module.mounts]] source = "static" target = "static" [[module.mounts]] source = "../.assets" target = "static/assets" -files = ["! .**", "! **/.**", "! **.{html,htm,xhtml,xht,xml,xsl,xslt,shtml,mht,mhtml}"] +files = ["! .**", "! **/.**", "**.{avif,gif,ico,jpeg,jpg,pdf,png,svg,webp}", "**/"] [[module.mounts]] source = "../.lokf/knowledge" target = "static/knowledge" -files = ["! .**", "! **/.**", "! **.{html,htm,xhtml,xht,xml,xsl,xslt,shtml,mht,mhtml}"] +files = ["! .**", "! **/.**", "**.md", "**/"] [[module.mounts]] source = "../docs" target = "static/docs" -files = ["! .**", "! **/.**", "! **.md", "! **.{html,htm,xhtml,xht,xml,xsl,xslt,shtml,mht,mhtml}"] +files = ["! .**", "! **/.**", "**.{avif,gif,ico,jpeg,jpg,pdf,png,svg,webp}", "**/"] [[module.mounts]] source = "generated/knowledge" target = "static/knowledge" diff --git a/website/layouts/_markup/render-blockquote.html b/website/layouts/_markup/render-blockquote.html index 3d4b376..3191789 100644 --- a/website/layouts/_markup/render-blockquote.html +++ b/website/layouts/_markup/render-blockquote.html @@ -1,6 +1,6 @@ {{- if eq .Type "alert" -}} -
-

{{ .AlertTitle | default (.AlertType | strings.FirstUpper) }}

+
+

{{ .AlertTitle | default (.AlertType | strings.FirstUpper) }}

{{ .Text }}
{{- else -}} diff --git a/website/layouts/_markup/render-codeblock-mermaid.html b/website/layouts/_markup/render-codeblock-mermaid.html index c4194bc..092893c 100644 --- a/website/layouts/_markup/render-codeblock-mermaid.html +++ b/website/layouts/_markup/render-codeblock-mermaid.html @@ -1,2 +1,2 @@ -
{{ .Inner | htmlEscape | safeHTML }}
+
{{ .Inner | htmlEscape | safeHTML }}
{{- .Page.Store.Set "hasMermaid" true -}} diff --git a/website/layouts/_markup/render-heading.html b/website/layouts/_markup/render-heading.html index f13469f..06033ee 100644 --- a/website/layouts/_markup/render-heading.html +++ b/website/layouts/_markup/render-heading.html @@ -1,4 +1,4 @@ {{- /* A file with a frontmatter title starts its sections at `#`; the title is the page's one h1, so each heading moves down a level. */ -}} {{- $level := cond (.Page.Params.shift | default false) (math.Min 6 (add .Level 1)) .Level -}} -{{ .Text }}# +{{ .Text }}# {{- /**/ -}} diff --git a/website/layouts/_markup/render-link.html b/website/layouts/_markup/render-link.html index 79f3356..7f66493 100644 --- a/website/layouts/_markup/render-link.html +++ b/website/layouts/_markup/render-link.html @@ -1,5 +1,5 @@ {{- /* A link goes where route.html sends it. One that reaches a concept shows that concept's trust and definition on hover. */ -}} {{- $href := partial "route.html" (dict "from" (partial "repo-path.html" .Page) "url" .Destination) -}} {{- $concept := index (partialCached "concepts.html" "concepts").url (index (split $href "#") 0) -}} -{{ .Text }} +{{ .Text }} {{- /**/ -}} diff --git a/website/layouts/_partials/gendoc.html b/website/layouts/_partials/gendoc.html index 0093b1f..83fcc8b 100644 --- a/website/layouts/_partials/gendoc.html +++ b/website/layouts/_partials/gendoc.html @@ -2,9 +2,10 @@ One page gen-doc wrote, tidied for this site. gen-doc writes for mkdocs, so the mkdocs frontmatter and its search wrapper go. The title's line and the description under it are taken out and returned beside the body. A heading - over a table with no rows goes. Each
gets a summary, and the - blank lines that make the YAML inside it a code block. Takes the file as a - resource, and returns (dict "heading" "description" "body"). + over a table with no rows goes. Each
gets a summary, the blank + lines that make the YAML inside it a code block, and own.html's attribute, + so search still leaves it out once the page is cleaned. Takes the file as + a resource, and returns (dict "heading" "description" "body"). */ -}} {{- $body := .Content | replaceRE `(?s)\A---\n.*?\n---` "" | strings.TrimLeft " \t\r\n" -}} {{- $heading := "" -}} @@ -25,6 +26,6 @@ | replaceRE `
` "" | replaceRE `
\s*\z` "" | replaceRE `(?m)^#{2,3} [^\n]+\n+\|[^\n]*\|\n\|[ :|-]+\|\n(?:[ \t]*\n|\z)` "" - | replaceRE `(?m)^
[ \t]*$` "
\nYAML\n" + | replaceRE `(?m)^
[ \t]*$` (printf "
\nYAML\n" (partial "own.html" .)) | replaceRE `(?m)^
` "\n
" -}} {{- return (dict "heading" $heading "description" $description "body" $body) -}} diff --git a/website/layouts/_partials/heroes.html b/website/layouts/_partials/heroes.html index 12200c5..53dc9ff 100644 --- a/website/layouts/_partials/heroes.html +++ b/website/layouts/_partials/heroes.html @@ -4,7 +4,9 @@ quick start. None is set anywhere. Each is looked for among the site's pages, and one that is not there is greyed, with the reason on hover. The quick start is the filled button. On a site without one, the first button - found is filled instead. + found is filled instead. A sixth button, the specification's, follows the + architecture page's where the repository has a root SPEC.md, and is not + drawn where it has none. */ -}} {{- /* The quick start is a docs page of that name, or the first heading that says so: in the install page, then any docs page, then the README. */ -}} {{- $quick := "" -}} @@ -23,10 +25,12 @@ {{- range $key, $paths := dict "schema" (slice "/schema") "bundle" (slice "/knowledge") "architecture" (slice "/docs/architecture") "glossary" (slice "/knowledge/glossary" "/docs/glossary") -}} {{- range $paths }}{{ if not (index $link $key) }}{{ with site.GetPage . }}{{ $link = merge $link (dict $key .RelPermalink) }}{{ end }}{{ end }}{{ end -}} {{- end -}} +{{- with partialCached "spec.html" "spec" }}{{ $link = merge $link (dict "spec" .RelPermalink) }}{{ end -}} {{- $buttons := slice (dict "text" "The schema" "link" $link.schema "missing" "This repository holds no LinkML schema") (dict "text" "The bundle" "link" $link.bundle "missing" "This repository holds no knowledge bundle") (dict "text" "Architecture" "link" $link.architecture "missing" "This repository has no docs/architecture.md") + (dict "text" "Specification" "link" $link.spec) (dict "text" "Glossary" "link" $link.glossary "missing" "The bundle has no glossary group") (dict "text" "Quick start" "link" $quick "missing" "No docs page has a Quick start heading") -}} {{- $filled := "" -}} @@ -36,7 +40,7 @@ {{- range $buttons }} {{- if .link }} {{ .text }} - {{- else }} + {{- else if .missing }} {{ .text }} {{- end }} {{- end }} diff --git a/website/layouts/_partials/icon.html b/website/layouts/_partials/icon.html index 27da56d..54dbc19 100644 --- a/website/layouts/_partials/icon.html +++ b/website/layouts/_partials/icon.html @@ -1,8 +1,9 @@ -{{- /* A small line drawing for a heading of the navigation: "guide", "schema", "bundle", "data" or "changelog". */ -}} +{{- /* A small line drawing for a heading of the navigation: "guide", "schema", "bundle", "graph", "data" or "changelog". */ -}} {{- $d := index (dict "guide" "M12 6.5C10 5 7 4.5 4 5v13c3-.5 6 0 8 1.5 2-1.5 5-2 8-1.5V5c-3-.5-6 0-8 1.5Zm0 0v13" "schema" "M9 3h6v5H9zM3 16h6v5H3zM15 16h6v5h-6zM12 8v4M6 16v-4h12v4" "bundle" "M4 4h16v7H4zM4 13h16v7H4zM10 7.5h4M10 16.5h4" + "graph" "M8.2 7a2.2 2.2 0 1 1-4.4 0 2.2 2.2 0 1 1 4.4 0ZM20.2 6a2.2 2.2 0 1 1-4.4 0 2.2 2.2 0 1 1 4.4 0ZM14.6 17.5a2.6 2.6 0 1 1-5.2 0 2.6 2.6 0 1 1 5.2 0ZM8.2 6.8l7.6-.6M7.1 8.9l3.6 6.3M17 8l-3.8 7.2" "data" "M4 6c0-1.7 3.6-3 8-3s8 1.3 8 3-3.6 3-8 3-8-1.3-8-3Zm0 0v12c0 1.7 3.6 3 8 3s8-1.3 8-3V6M4 12c0 1.7 3.6 3 8 3s8-1.3 8-3" "changelog" "M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18ZM12 7.5V12l3 2") . -}} diff --git a/website/layouts/_partials/markdown-file.html b/website/layouts/_partials/markdown-file.html index c70a64a..e6a221a 100644 --- a/website/layouts/_partials/markdown-file.html +++ b/website/layouts/_partials/markdown-file.html @@ -1,8 +1,9 @@ {{- /* - A docs page, or the home page, as Markdown beside it, for a reader or a - model that wants the words without the site: at the path the repository - holds it under, docs/.md, or at index.md for the README. It is the - file from its # title down, with every address made full by markdown.html. + A docs page, the home page or the specification's page, as Markdown beside + it, for a reader or a model that wants the words without the site: at the + path the repository holds it under, docs/.md, at index.md for the + README, or at spec.md for a root SPEC.md. It is the file from its # title + down, with every address made full by markdown.html. Returns the published file, or false for any other page. Called cached by the page's address. */ -}} @@ -10,7 +11,7 @@ {{- $from := partial "repo-path.html" . -}} {{- $at := "" -}} {{- $rel := partial "site-path.html" $from -}} -{{- if and (hasPrefix $rel "docs/") (hasSuffix $rel ".md") }}{{ $at = $rel }}{{ else if and .IsHome (eq $rel "README.md") }}{{ $at = "index.md" }}{{ end -}} +{{- if and (hasPrefix $rel "docs/") (hasSuffix $rel ".md") }}{{ $at = $rel }}{{ else if and .IsHome (eq $rel "README.md") }}{{ $at = "index.md" }}{{ else if and (eq .Path "/spec") (eq $rel "SPEC.md") }}{{ $at = "spec.md" }}{{ end -}} {{- with $at -}} {{- $text := $.RawContent -}} {{- if $.Params.shift -}} diff --git a/website/layouts/_partials/nav-key.html b/website/layouts/_partials/nav-key.html index 509b0c3..a43a348 100644 --- a/website/layouts/_partials/nav-key.html +++ b/website/layouts/_partials/nav-key.html @@ -2,8 +2,9 @@ Where a page sits in the navigation: the heading of its docs group ("docs:
+ {{- end }}

Also counted

{{ partial "health-tiles.html" (dict "states" false) }} diff --git a/website/layouts/home.badge.json b/website/layouts/home.badge.json index ab41692..661a6b8 100644 --- a/website/layouts/home.badge.json +++ b/website/layouts/home.badge.json @@ -1,13 +1,15 @@ {{- /* The bundle's trust in one line, in the form a shields.io endpoint badge - reads: how many of its concepts a person confirmed, as "n of m", retired - ones aside, beside the Knowledge Trust Ladder's mark. A README shows it with - https://img.shields.io/endpoint?url=/badge.json and links it to the - site's health page. The colour is the site's own: a person's blue once one - concept is confirmed, and its grey before. + reads: how many of its concepts a person confirmed, as "n of m", beside the + Knowledge Trust Ladder's mark. m counts every concept, a retired one + included, as `knowledge-report.sh health` counts in "Confirmed by a person: + n of m" and as the health page does, so the three show one figure. A README + shows it with https://img.shields.io/endpoint?url=/badge.json and + links it to the site's health page. The colour is the site's own: a + person's blue once one concept is confirmed, and its grey before. */ -}} {{- $n := newScratch -}} -{{- range (partialCached "concepts.html" "concepts").id }}{{ if ne .trust.tone "retired" }}{{ $n.Add "all" 1 }}{{ $n.Add .trust.tone 1 }}{{ end }}{{ end -}} +{{- range (partialCached "concepts.html" "concepts").id }}{{ $n.Add "all" 1 }}{{ $n.Add .trust.tone 1 }}{{ end -}} {{- $all := $n.Get "all" | default 0 -}} {{- $person := $n.Get "person" | default 0 -}} {{- $message := cond (eq $all 0) "no concepts yet" (printf "%d of %d" $person $all) -}} diff --git a/website/layouts/home.llms.txt b/website/layouts/home.llms.txt index 85e8576..88902ae 100644 --- a/website/layouts/home.llms.txt +++ b/website/layouts/home.llms.txt @@ -16,12 +16,14 @@ {{ with partialCached "schema-file.html" "schema-file" -}} ## The schema -- [{{ (site.GetPage "/schema").Title }}]({{ .file.Permalink }}): {{ if .core }}LOKF core, the LinkML schema the knowledge bundle is written in{{ else }}the LinkML schema as the repository holds it{{ end }}. Its classes, enumerations, slots and types have a page each under {{ "schema/" | absURL }} +- [{{ (site.GetPage "/schema").Title }}]({{ .file.Permalink }}): {{ if .domain }}the domain vocabulary the knowledge bundle is written in, which adds to LOKF core{{ else if .core }}LOKF core, the LinkML schema the knowledge bundle is written in{{ else if .package }}the LinkML schema as the {{ .package }} package holds it{{ else }}the LinkML schema as the repository holds it{{ end }}. Its classes, enumerations, slots and types have a page each under {{ "schema/" | absURL }} {{ end -}} ## Docs {{ with site.Home }}{{ with partialCached "markdown-file.html" . .RelPermalink }} - [The home page]({{ .Permalink }}): the README{{ end }}{{ end }} +{{- with partialCached "spec.html" "spec" }}{{ $s := . }}{{ with partialCached "markdown-file.html" $s $s.RelPermalink }} +- [{{ $s.Title }}]({{ .Permalink }}){{ end }}{{ end }} {{- with site.GetPage "/docs" }}{{ $d := . }}{{ if .Params.docName }}{{ with partialCached "markdown-file.html" $d $d.RelPermalink }} - [{{ $d.Title }}]({{ .Permalink }}){{ end }}{{ end }}{{ end }} {{- range (partialCached "docs-groups.html" "docs").list }}{{ range $p := .pages }}{{ with partialCached "markdown-file.html" $p $p.RelPermalink }} diff --git a/website/layouts/page.atom.xml b/website/layouts/page.atom.xml index 7d467a8..9352660 100644 --- a/website/layouts/page.atom.xml +++ b/website/layouts/page.atom.xml @@ -1,6 +1,7 @@ {{- /* The bundle log as an Atom feed: an entry for each of its newest thirty - days, a day being a `## YYYY-MM-DD` section, each as the log page shows it. + days, a day being a `## YYYY-MM-DD` section, each as the log page shows it, + without the attribute own.html writes for the cleaning of that page. */ -}} {{- printf `` | safeHTML }} @@ -10,7 +11,7 @@ {{ site.Title }} {{- /* Each day's heading is preceded by a NUL, and its date by another, so the page splits into date and words by turns. */ -}} - {{- $parts := split (replaceRE `]*>.*?` "")) }}{{ end }}{{ end }} {{- range $i, $day := first 30 $days }} diff --git a/website/layouts/page.html b/website/layouts/page.html index 2b6d159..8e5af93 100644 --- a/website/layouts/page.html +++ b/website/layouts/page.html @@ -3,7 +3,7 @@ {{- if .Params.shift }}

{{ .Title }}

{{ end }} {{- if .Params.conceptId }}{{ partial "concept-card.html" . }}{{ end }} {{ partial "content.html" . }} - {{- with partial "repo-path.html" . }}{{ if hasPrefix (partial "site-path.html" .) "docs/" }} + {{- with partial "repo-path.html" . }}{{ $rel := partial "site-path.html" . }}{{ if or (hasPrefix $rel "docs/") (eq $rel "SPEC.md") }}

Edit this page

{{- end }}{{ end }} diff --git a/website/layouts/schema/section.html b/website/layouts/schema/section.html index 42ac36a..5732993 100644 --- a/website/layouts/schema/section.html +++ b/website/layouts/schema/section.html @@ -15,12 +15,15 @@

{{ .Title }}

{{ .Title }}

{{- with .Params.description }}

{{ partial "inline.html" . }}

{{ end }} {{- with partialCached "schema-file.html" "schema-file" }} - {{- if .core }} + {{- if .domain }} +

This repository holds no LinkML schema of its own, so the site shows the domain vocabulary its knowledge bundle is written in, which adds to LOKF {{ .core }}.

+ {{- else if .core }}

This repository holds no LinkML schema of its own, so the site shows the one its knowledge bundle is written in, LOKF {{ .core }}.

{{- end }}

Schema file: {{ path.Base .file.RelPermalink }}, from {{- if .path }} {{ .path }} - {{- else }} the lokf {{ .core }} package the sidecar installs + {{- else if eq .package "lokf" }} the lokf {{ .core }} package the sidecar installs + {{- else }} the {{ .package }} package {{- end }}

{{- end }} {{ partial "content.html" . }} diff --git a/website/pyproject.toml b/website/pyproject.toml index a903561..ee90da7 100644 --- a/website/pyproject.toml +++ b/website/pyproject.toml @@ -1,12 +1,13 @@ # The tools that build the site: Hugo and Pagefind, each from PyPI at one -# version. uv.lock holds every file's hash, so `uv run --frozen` installs -# exactly these, on Linux, macOS or Windows, from PyPI or a mirror of it. +# version. uv.lock holds every file's hash and its address on PyPI, so +# `uv run --frozen` installs exactly these, on Linux, macOS or Windows. +# Behind a mirror, scripts/uv-env.sh installs them from the mirror. [project] name = "knowledge-website" version = "0.0.0" description = "The tools that build the knowledge website." requires-python = ">=3.11" -dependencies = ["hugo==0.169.0", "pagefind[extended]==1.6.0"] +dependencies = ["hugo==0.170.0", "pagefind[extended]==1.6.0"] [tool.uv] package = false diff --git a/website/scripts/build.sh b/website/scripts/build.sh index 23f1aff..9b0947d 100755 --- a/website/scripts/build.sh +++ b/website/scripts/build.sh @@ -1,7 +1,8 @@ #!/usr/bin/env bash # Builds the knowledge website. Hugo and Pagefind come from PyPI through uv, # at the versions and hashes uv.lock holds, so the build needs bash, git and -# uv, and no Node.js. +# uv, and no Node.js. Behind a package mirror, scripts/uv-env.sh installs the +# same files from the index uv reads. # # scripts/build.sh dist/, with its raw HTML cleaned, the search # index, and every link between its pages checked @@ -17,13 +18,14 @@ set -euo pipefail here=$(cd "$(dirname "$0")/.." && pwd) cd "$here" -tool=(uv run --project "$here" --frozen --quiet) +mode=$(scripts/uv-env.sh "$here") +tool=(uv run --project "$here" "$mode" --quiet) # hugo.toml is the same on every site, and site.toml holds this repository's # own values, read second so that they win. # shellcheck disable=SC2054 # one --config value: Hugo takes the files as a comma-separated list port=${PORT:-1313} -if grep -qE '<(REPO|PROJ)_[A-Z]+>' site.toml; then +if grep -qE '<(REPO|PROJ|SITE)_[A-Z]+>' site.toml; then echo "build.sh: site.toml still holds a ; give it this repository's values first" >&2 exit 1 fi diff --git a/website/scripts/check-svg.py b/website/scripts/check-svg.py new file mode 100644 index 0000000..4852d0a --- /dev/null +++ b/website/scripts/check-svg.py @@ -0,0 +1,99 @@ +"""Names each SVG that could run a script on the site's address, and exits 1. + + python scripts/check-svg.py ... + +Reads each .svg under the folders as XML, as a browser does, and names one +that holds: + +- a script or foreignObject element under any prefix, or an XHTML element; +- an on* event handler; +- a value that starts with javascript: or another scheme that runs, or a + data: address a browser opens as a page, except a data: SVG in an image; +- a DOCTYPE or an xml-stylesheet instruction; +- text that is not well-formed XML. + +A .svgz is named unread. A missing folder is skipped. +""" + +from __future__ import annotations + +import os +import re +import sys +from pathlib import Path +from xml.parsers import expat + +XHTML = "http://www.w3.org/1999/xhtml" +ELEMENTS = {"script", "foreignobject"} +SCHEME = re.compile(r"^(?:javascript|vbscript|livescript):") +DATA = re.compile(r"^data:(?:text/html|application/xhtml\+xml|text/xml|application/xml|(image/svg\+xml))(?![\w+.-])") +SPACE = re.compile(r"[\x00-\x20]+") + + +class Found(Exception): + """What a file holds that could run.""" + + +def start(name: str, attributes: dict[str, str]): + # expat gives a name as its namespace, a space and its local name. + namespace, _, element = name.rpartition(" ") + if element.lower() in ELEMENTS: + raise Found(f"a {element} element") + if namespace == XHTML: + raise Found(f"an XHTML {element} element") + for key, value in attributes.items(): + attribute = key.rpartition(" ")[2] + if attribute.lower().startswith("on"): + raise Found(f"an event handler, {attribute}") + # An animation's values are a list, each of which can be an address. + for part in SPACE.sub("", value).lower().split(";"): + data = DATA.match(part) + if SCHEME.match(part) or (data and not (data.group(1) and element == "image")): + raise Found(f"an address that runs, in {attribute}") + + +def doctype(*_): + raise Found("a DOCTYPE") + + +def instruction(target: str, _data: str): + if target.lower() == "xml-stylesheet": + raise Found("an xml-stylesheet instruction") + + +def check(path: Path) -> str: + """What the file holds that could run, or "".""" + if path.suffix.lower() == ".svgz": + return "is compressed, so it is not read; keep the .svg" + parser = expat.ParserCreate(namespace_separator=" ") + parser.StartElementHandler = start + parser.StartDoctypeDeclHandler = doctype + parser.ProcessingInstructionHandler = instruction + try: + parser.Parse(path.read_bytes(), True) + except Found as found: + return f"holds {found}" + except (expat.ExpatError, ValueError, OSError) as error: + return f"is not XML the check can read ({error})" + return "" + + +def main(folders: list[str]) -> int: + named = [] + for folder in folders: + for parent, _, names in sorted(os.walk(folder)): + for name in sorted(names): + path = Path(parent, name) + if path.suffix.lower() in (".svg", ".svgz"): + reason = check(path) + if reason: + named.append(f"{path}: {reason}") + if named: + print("check-svg: these SVG files hold a script, an event handler, an address that runs or markup the check cannot read, and the site would serve them:", file=sys.stderr) + for line in named: + print(f" {line}", file=sys.stderr) + return 1 if named else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/website/scripts/clean-html.py b/website/scripts/clean-html.py index f0416c1..96dd9d0 100644 --- a/website/scripts/clean-html.py +++ b/website/scripts/clean-html.py @@ -5,14 +5,20 @@ Hugo writes the HTML each repository file renders to between two comments that carry the build's mark, which changes with every build, so no file can fake one. Within them, a tag GitHub allows in a README keeps the attributes -it allows, with the class, id, data-* and aria-* attributes the site's -Markdown rendering writes, and a style that only aligns a table's cell. An -address that is not http, https, mailto, a path or a fragment is dropped. -Any other markup is shown as text, so the reader sees it and nothing in it -runs, and each is named on the log. Comments are dropped. Every element is -closed, so nothing a file writes can reach the page around it. The page's -Content-Security-Policy stays as a second guard, and the script needs only -the Python standard library. +it allows, each written once, with an id and a style that only aligns a +table's cell. An address that is not http, https, mailto, a path or a +fragment is dropped. Any other markup is shown as text, so the reader sees +it and nothing in it runs, and each is named on the log. Comments are +dropped. Every element is closed, so nothing a file writes can reach the +page around it. + +A class or a data-* attribute stays only where the site's own rendering +wrote it: on an element whose data-site names the mark (own.html), or as a +footnote's or highlighted code's class. So a repository file cannot draw a +trust label, name itself in a search filter or word a link's preview. + +The page's Content-Security-Policy stays as a second guard, and the script +needs only the Python standard library. Exits 1 when a page holds a mark with no end, as it does when an unclosed comment or script swallowed the rest of the page, or when no page holds a @@ -35,17 +41,19 @@ "figcaption abbr bdo cite dfn mark small span time wbr picture source input".split() ) VOID = {"br", "hr", "img", "wbr", "source", "input"} -# The attributes GitHub keeps on any tag, less a form's, with those the -# site's rendering writes. +# The attributes GitHub keeps on any tag, less a form's, with id and loading. +# `name` stays on a link alone: on an image it would shadow a document +# property the site's script calls. ATTRIBUTES = set( "abbr align alt aria-describedby aria-hidden aria-label aria-labelledby axis border cellpadding cellspacing " "char charoff checked clear cols colspan color compact coords datetime dir disabled for frame headers height " - "hreflang hspace ismap label lang maxlength media multiple name nohref noshade nowrap open prompt readonly " + "hreflang hspace ismap label lang maxlength media multiple nohref noshade nowrap open prompt readonly " "rel rev role rows rowspan rules scope selected shape size span start summary tabindex target title type " - "usemap valign value vspace width itemprop class id loading".split() + "usemap valign value vspace width itemprop id loading".split() ) PER_TAG = { - "a": {"href"}, + "a": {"href", "name"}, + "code": {"data-lang"}, "img": {"src", "srcset", "longdesc"}, "source": {"srcset"}, "div": {"itemscope", "itemtype"}, @@ -55,6 +63,19 @@ "q": {"cite"}, } ADDRESSES = {"href", "src", "srcset", "longdesc", "cite"} +# The attribute own.html writes on an element of the site's own templates, +# and the data-* attributes such an element keeps. +OWN = "data-site" +SITE_DATA = {"data-pagefind-ignore", "data-preview"} +# The classes Goldmark writes for a footnote, and Chroma for highlighted +# code: its wrappers, its lines and line numbers, and each kind of token. +RENDERED = set( + "footnotes footnote-ref footnote-backref highlight chroma bg lntable lntd lnt ln lnlinks hl line cl " + "x err w k kc kd kn kp kr kt n na nb bp nc no nd ni ne nf fm py nl nn nx nt nv vc vg vi vm " # codespell:ignore nd + "l ld s sa sb sc dl sd s2 se sh si sx sr s1 ss m mb mf mh mi il mo o ow or p " + "c ch cm cp cpf c1 cs g gd ge gr gh gi go gp gs gu gt gl".split() +) +LANGUAGE = re.compile(r"^language-[\w+#.-]+$") SAFE = re.compile(r"^(?:https?:|mailto:|#|/|\.|[^:/?#]*(?:[/?#]|$))", re.I) ALIGN = re.compile(r"^\s*text-align:\s*(?:left|right|center)\s*;?\s*$", re.I) @@ -65,8 +86,9 @@ def safe_address(name: str, value: str) -> bool: class Cleaner(HTMLParser): - def __init__(self): + def __init__(self, mark: str): super().__init__(convert_charrefs=True) + self.mark = mark self.out, self.open, self.shown = [], [], [] def show(self, text: str): @@ -74,21 +96,31 @@ def show(self, text: str): self.shown.append(" ".join(text.split())[:80]) def handle_starttag(self, tag, attrs): - if tag not in TAGS or (tag == "input" and dict(attrs).get("type") != "checkbox"): + # A browser reads the first of an attribute written twice, so an input + # is a task list's checkbox only when every type it names is one. + types = [(value or "").strip().lower() for name, value in attrs if name == "type"] + if tag not in TAGS or (tag == "input" and (not types or any(kind != "checkbox" for kind in types))): self.show(self.get_starttag_text() or f"<{tag}>") return - kept = [] + own = any(name == OWN and value == self.mark for name, value in attrs) + kept = {} for name, value in attrs: value = value or "" + allowed = name in ATTRIBUTES or name in PER_TAG.get(tag, ()) if name == "style": - if not ALIGN.match(value): - continue - elif not (name in ATTRIBUTES or name in PER_TAG.get(tag, ()) or name.startswith(("data-", "aria-"))): - continue + allowed = bool(ALIGN.match(value)) + elif name == "class": + if not own: + value = " ".join(word for word in value.split() if word in RENDERED or (tag == "code" and LANGUAGE.match(word))) + allowed = bool(value) + elif name in SITE_DATA: + allowed = own if name in ADDRESSES and not safe_address(name, value): - continue - kept.append(f' {name}="{escape(value)}"') - self.out.append(f"<{tag}{''.join(kept)}>") + allowed = False + # Only the first of a name written twice counts, kept or not. + if name not in kept: + kept[name] = f' {name}="{escape(value)}"' if allowed else "" + self.out.append(f"<{tag}{''.join(kept.values())}>") if tag not in VOID: self.open.append(tag) @@ -133,20 +165,22 @@ def clean(self, html: str) -> str: def main(site: Path, mark: str) -> int: - region = re.compile(rf"(.*?)", re.S) + start, end = f"", f"" + region = re.compile(rf"{re.escape(start)}(.*?){re.escape(end)}", re.S) failed, regions = [], 0 for path in sorted(site.rglob("*.html")): text = path.read_text(encoding="utf-8") if mark not in text: continue found = list(region.finditer(text)) - if text.count(mark) != 2 * len(found): + # The site's own elements name the mark too, so each comment is counted whole. + if not text.count(start) == text.count(end) == len(found): failed.append(f"{path.relative_to(site)} holds a mark with no end: an unclosed comment, script or other element in its source swallowed the rest of the page") continue shown = [] def cleaned(match): - cleaner = Cleaner() + cleaner = Cleaner(mark) html = cleaner.clean(match.group(1)) shown.extend(cleaner.shown) return html diff --git a/website/scripts/lokf-export.py b/website/scripts/lokf-export.py new file mode 100644 index 0000000..242b0ec --- /dev/null +++ b/website/scripts/lokf-export.py @@ -0,0 +1,30 @@ +"""Runs `lokf export` with the diataxis.md at the bundle's root read as no concept. + + python scripts/lokf-export.py + +KTL Registrar keeps its map in that file, and the report script and the +site's pages read it as no concept. The toolkit reserves index.md and log.md +alone, so its export would write the map as a node. A diataxis.md in a +folder stays a concept. +""" + +from __future__ import annotations + +import sys + +import lokf.model +from lokf.cli import app + +stock = lokf.model.load_bundle + + +def load_bundle(path): + bundle = stock(path) + bundle.concepts = [c for c in bundle.concepts if c.concept_id != "diataxis"] + return bundle + + +if __name__ == "__main__": + lokf.model.load_bundle = load_bundle + sys.argv = ["lokf", "export", *sys.argv[1:]] + app() diff --git a/website/scripts/prepare.sh b/website/scripts/prepare.sh index bf11ae9..ba3a532 100755 --- a/website/scripts/prepare.sh +++ b/website/scripts/prepare.sh @@ -13,85 +13,140 @@ set -euo pipefail here=$(cd "$(dirname "$0")/.." && pwd) root=$(cd "$here/.." && pwd) out="$here/generated" -repo_url=$(sed -n 's/^repo = "\(.*\)"$/\1/p' "$here/site.toml") -[ -n "$repo_url" ] || { echo "prepare.sh: site.toml has no repo = \"...\" line" >&2; exit 1; } +# The site's own tools, as build.sh runs them, for the two checks below. +# uv-env.sh installs them, from a package mirror where uv reads one. +mode=$("$here/scripts/uv-env.sh" "$here") +tool=(uv run --project "$here" "$mode" --quiet) +# site.toml's values, read by a TOML parser as Hugo reads them, one +# `name=value` line each. A file the parser refuses stops the build here. +site=$("${tool[@]}" python -I "$here/scripts/site-values.py" "$here/site.toml") +value() { sed -n "s/^$1=//p" <<<"$site"; } +repo_url=$(value repo) +[ -n "$repo_url" ] || { echo "prepare.sh: site.toml has no repo = \"...\" line under [params]" >&2; exit 1; } [ -f "$root/.lokf/knowledge/index.md" ] || { echo "prepare.sh: no .lokf/knowledge/index.md under $root; the ktl-sidecar skill installs the bundle" >&2; exit 1; } # The commit of the build, or the branch where the folder is not under git. -branch=$(sed -n 's/^branch = "\(.*\)"$/\1/p' "$here/site.toml") +branch=$(value branch) ref=$(git -C "$root" rev-parse HEAD 2>/dev/null || echo "${branch:-main}") -# site.toml's source: the folder the README, docs/, the changelog and -# .assets/ come from, by the mounts in generated/source.toml. Its linkml: the -# folder whose src//schema/ holds the schema. -source=$(sed -n 's/^source = "\(.*\)"$/\1/p' "$here/site.toml"); source=${source%/} -linkml=$(sed -n 's/^linkml = "\(.*\)"$/\1/p' "$here/site.toml"); linkml=${linkml%/} +# site.toml's source: the folder the README, SPEC.md, docs/, the changelog +# and .assets/ come from, by the mounts in generated/source.toml. Its linkml: +# the folder whose src//schema/ holds the schema. +source=$(value source); source=${source%/} +linkml=$(value linkml); linkml=${linkml%/} src_root="$root${source:+/$source}" -# An SVG is served as a page of its own, so one that holds a script, an event -# handler or a javascript: address would run on the site's address. -if active=$(grep -rlEi --include='*.svg' '/dev/null); then - echo "prepare.sh: these SVG files hold a script, an event handler or a javascript: address, and the site would serve them:" >&2 - echo "$active" >&2 - exit 1 -fi +# Stop on an SVG that could run a script on the site's address. +"${tool[@]}" python -I "$here/scripts/check-svg.py" "$src_root/.assets" "$src_root/docs" "$root/.lokf/knowledge" "$here/static" rm -rf "$out" mkdir -p "$out/knowledge" -# hugo.toml's mounts with the README, docs/, the changelog and .assets/ read -# from the source folder. build.sh reads this file last, and Hugo then takes -# its mounts in place of hugo.toml's. +# hugo.toml's mounts with the README, SPEC.md, docs/, the changelog and +# .assets/ read from the source folder. build.sh reads this file last, and +# Hugo then takes its mounts in place of hugo.toml's. if [ -n "$source" ]; then [ -d "$src_root" ] || { echo "prepare.sh: site.toml's source names $source, which is no folder" >&2; exit 1; } sed -n '/^\[\[module\.mounts\]\]/,$p' "$here/hugo.toml" | sed \ -e "s#^source = \"\.\./README\.md\"#source = \"../$source/README.md\"#" \ + -e "s#^source = \"\.\./SPEC\.md\"#source = \"../$source/SPEC.md\"#" \ -e "s#^source = \"\.\./docs\"#source = \"../$source/docs\"#" \ -e "s#^source = \"\.\./CHANGELOG\.md\"#source = \"../$source/CHANGELOG.md\"#" \ -e "s#^source = \"\.\./\.assets\"#source = \"../$source/.assets\"#" >"$out/source.toml" fi -# The bundle's own tools: lokf, and the LinkML it is built on. -lokf=(uv run --project "$root/.lokf" --frozen --quiet) +# The bundle's own tools: lokf, and the LinkML it is built on, installed as +# the site's own are. +mode=$("$here/scripts/uv-env.sh" "$root/.lokf") +lokf=(uv run --project "$root/.lokf" "$mode" --quiet) # The domain vocabulary the sidecar's justfile names, so the export carries -# its classes as `just lokf-convert` does. +# its classes as `just lokf-convert` does. lokf-export.py runs `lokf export` +# with the root's diataxis.md read as no concept. schema=$(sed -n 's/^schema := "\(.*\)"$/\1/p' "$root/.lokf/justfile" 2>/dev/null || true) -"${lokf[@]}" lokf export ${schema:+--schema "$root/.lokf/$schema"} "$root/.lokf/knowledge" \ +"${lokf[@]}" python -I "$here/scripts/lokf-export.py" ${schema:+--schema "$root/.lokf/$schema"} "$root/.lokf/knowledge" \ --out-dir "$out/knowledge" \ --source-base "$repo_url/blob/$ref/.lokf/knowledge" -# A LinkML project's schema: src//schema/.yaml, in site.toml's -# linkml folder first, then at the root, then in the .linkml/ sidecar. gen-doc writes a page per class, slot, -# enumeration and type, each kind in a folder of its own, and gen-erdiagram -# writes the diagram the overview shows. The schema file is copied beside -# them, with its path in the repository. +# The schema: the file site.toml's schema names, or else a LinkML project's +# src//schema/.yaml, in site.toml's linkml folder first, then at +# the root, then in the .linkml/ sidecar. gen-doc writes a page per class, +# slot, enumeration and type, each kind in a folder of its own, and +# gen-erdiagram writes the diagram the overview shows. The schema file is +# copied beside them, and source.txt holds its path in the repository, or +# the pkg: name of one inside a package. gendoc() { # gen-doc prints a stray "None" when it ends. "${lokf[@]}" gen-doc --subfolder-type-separation --index-name _index -d "$out/schema" "$1" >/dev/null "${lokf[@]}" gen-erdiagram --format mermaid "$1" >"$out/schema/diagram.mmd" - cp "$1" "$out/schema/" + # Each local file it imports in turn goes beside it at the same relative + # path, so the served copy loads as the repository's does. An import from + # outside the schema's folder, or one named by a prefix, is not served. + "${lokf[@]}" python - "$1" "$out/schema" <<'PY' +import shutil, sys +from pathlib import Path +import yaml +top, out = Path(sys.argv[1]).resolve(), Path(sys.argv[2]) +todo, seen = [top], set() +while todo: + f = todo.pop() + if f in seen or not f.is_file() or not f.is_relative_to(top.parent): + continue + seen.add(f) + (out / f.relative_to(top.parent)).parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(f, out / f.relative_to(top.parent)) + for name in (yaml.safe_load(f.read_text(encoding="utf-8")) or {}).get("imports") or []: + if isinstance(name, str) and ":" not in name: + todo.append((f.parent / f"{name}.yaml").resolve()) +PY } +# site.toml's schema is a path from the root, or pkg:/ for a +# schema inside a package that the environment of the uv project +# schemaProject names holds. The package is found, never imported. +named=$(value schema) +if [ -n "$named" ]; then + case "$named" in + pkg:*) + project=$(value schemaProject) + model=$(uv run --project "$root/${project:-.}" --frozen --quiet python -I -c ' +import importlib.util, pathlib, sys +package, _, inner = sys.argv[1][4:].partition("/") +spec = importlib.util.find_spec(package) +if spec is None or not spec.submodule_search_locations: + sys.exit(f"prepare.sh: site.toml names the schema {sys.argv[1]}, and the environment of {sys.argv[2]} holds no package {package}") +print(pathlib.Path(list(spec.submodule_search_locations)[0], inner))' "$named" "${project:-the root}") ;; + *) model="$root/$named" ;; + esac + [ -f "$model" ] || { echo "prepare.sh: site.toml names the schema $named, which is no file" >&2; exit 1; } + gendoc "$model" + echo "$named" >"$out/schema/source.txt" +fi for model in ${linkml:+"$root/$linkml"/src/*/schema/*.yaml} "$root"/src/*/schema/*.yaml "$root"/.linkml/src/*/schema/*.yaml; do + [ ! -d "$out/schema" ] || break name=$(basename "$model" .yaml) [ -f "$model" ] && [ "$(basename "${model%/schema/*}")" = "$name" ] || continue gendoc "$model" echo "${model#"$root/"}" >"$out/schema/source.txt" - break done # With no schema of its own, the repository still has the one its bundle is -# written in: LOKF core, the copy in .lokf/schema/ that a domain vocabulary -# imports, or else the one in the lokf package the sidecar installs. -# core.txt holds its version, and source.txt the copy's path, when the -# repository has one. +# written in: the domain vocabulary in .lokf/schema/domain.yaml, on a host +# whose bundle federates others, or else LOKF core, the copy in .lokf/schema/ +# that a domain vocabulary imports, or else the one in the lokf package the +# sidecar installs. core.txt holds LOKF core's version, and source.txt the +# path of the file shown, when the repository has it. if [ ! -d "$out/schema" ]; then core="$root/.lokf/schema/lokf.yaml" + for model in "$root/.lokf/schema/domain.yaml" "$core"; do + [ -f "$model" ] || continue + gendoc "$model" + echo "${model#"$root/"}" >"$out/schema/source.txt" + break + done + if [ ! -d "$out/schema" ]; then + gendoc "$("${lokf[@]}" python -c 'import lokf, pathlib; print(next(pathlib.Path(lokf.__file__).parent.rglob("lokf.yaml")))')" + fi if [ -f "$core" ]; then - gendoc "$core" - echo ".lokf/schema/lokf.yaml" >"$out/schema/source.txt" sed -n 's/^version: *"\{0,1\}\([^"]*\)"\{0,1\}$/\1/p' "$core" | head -1 >"$out/schema/core.txt" else - core=$("${lokf[@]}" python -c 'import lokf, pathlib; print(next(pathlib.Path(lokf.__file__).parent.rglob("lokf.yaml")))') - gendoc "$core" "${lokf[@]}" python -c 'import importlib.metadata; print(importlib.metadata.version("lokf"))' >"$out/schema/core.txt" fi fi @@ -101,9 +156,9 @@ fi # the plugins' settings, which Datasette Lite never runs and which can hold a # credential. site.toml's browseBuild command writes the data when the folder # holds no database. Nothing else in the folder is served. -browse=$(sed -n 's/^browse = "\(.*\)"$/\1/p' "$here/site.toml") +browse=$(value browse) if [ -n "$browse" ]; then - build=$(sed -n 's/^browseBuild = "\(.*\)"$/\1/p' "$here/site.toml") + build=$(value browseBuild) databases() { find "$root/$browse" -maxdepth 1 -type f \( -name '*.sqlite' -o -name '*.sqlite3' -o -name '*.db' \) 2>/dev/null; } if [ -z "$(databases)" ]; then [ -n "$build" ] || { echo "prepare.sh: site.toml's browse names $browse, which holds no database, and no browseBuild writes it" >&2; exit 1; } diff --git a/website/scripts/site-values.py b/website/scripts/site-values.py new file mode 100644 index 0000000..8924543 --- /dev/null +++ b/website/scripts/site-values.py @@ -0,0 +1,46 @@ +"""Prints the values of site.toml that prepare.sh reads, as Hugo reads them. + + python scripts/site-values.py + +Prints `name=value` for each [params] key in KEYS that the file sets. Exits +on a file that is not TOML, two keys that differ only in case (Hugo reads +them as one), and a value that is not a string or holds a control +character, a line break among them. +""" + +from __future__ import annotations + +import sys +import tomllib +import unicodedata + +KEYS = ("repo", "branch", "source", "linkml", "schema", "schemaProject", "browse", "browseBuild") + + +def main(path: str) -> int: + try: + with open(path, "rb") as file: + params = tomllib.load(file).get("params", {}) + except (OSError, tomllib.TOMLDecodeError) as error: + sys.exit(f"site-values: {path} cannot be read as TOML: {error}") + if not isinstance(params, dict): + sys.exit(f"site-values: {path} sets params to a value, where a [params] table is expected") + lower: dict[str, str] = {} + for key in params: + if key.lower() in lower: + sys.exit(f"site-values: {path} sets both {lower[key.lower()]} and {key}, which Hugo reads as one key: keep one") + lower[key.lower()] = key + for name in KEYS: + if name.lower() not in lower: + continue + value = params[lower[name.lower()]] + if not isinstance(value, str): + sys.exit(f"site-values: {path} sets {name} to a value that is not a string") + if any(unicodedata.category(char) == "Cc" for char in value): + sys.exit(f"site-values: {path} sets {name} to a value that holds a line break or another control character") + print(f"{name}={value}") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1])) diff --git a/website/scripts/uv-env.sh b/website/scripts/uv-env.sh new file mode 100644 index 0000000..53a9229 --- /dev/null +++ b/website/scripts/uv-env.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# Installs the tools a uv project pins, and prints the option `uv run +# --project ` then takes: --frozen, or --no-sync. +# +# scripts/uv-env.sh +# +# uv fetches a locked file from the address uv.lock holds, PyPI's, whatever +# index it reads. So where UV_DEFAULT_INDEX, UV_INDEX_URL or UV_INDEX names +# an index, or the lock's addresses fail, the script exports the lock's pins +# and hashes and installs them into .venv from the index uv reads. uv.lock +# stays as it is. +set -euo pipefail +project=${1:?usage: scripts/uv-env.sh } +[ -f "$project/uv.lock" ] || { echo "uv-env.sh: $project holds no uv.lock; run uv lock in that folder and commit the file" >&2; exit 1; } + +from_index() { + local pins status=0 + pins=$(mktemp "${TMPDIR:-/tmp}/uv-env.XXXXXX") + { + uv export --project "$project" --frozen --no-emit-project --format requirements-txt --quiet --output-file "$pins" && + { [ -f "$project/.venv/pyvenv.cfg" ] || (cd "$project" && uv venv --quiet); } && + uv pip install --quiet --require-hashes --python "$project/.venv" --requirements "$pins" + } >&2 || status=$? + rm -f "$pins" + return "$status" +} + +if [ -n "${UV_DEFAULT_INDEX:-}${UV_INDEX_URL:-}${UV_INDEX:-}" ]; then + from_index || { echo "uv-env.sh: the index uv reads did not give the files $project/uv.lock pins, each checked against its hash there" >&2; exit 1; } + echo --no-sync +elif said=$(uv sync --project "$project" --frozen --inexact --quiet 2>&1); then + echo --frozen +elif from_index 2>/dev/null; then + echo --no-sync +else + printf '%s\n' "$said" >&2 + echo "uv-env.sh: uv installed $project's tools neither from the addresses in its uv.lock nor from the index it reads; set UV_DEFAULT_INDEX to a mirror of PyPI to see what that index answers" >&2 + exit 1 +fi diff --git a/website/scripts/vendor.sh b/website/scripts/vendor.sh new file mode 100644 index 0000000..1e07ee0 --- /dev/null +++ b/website/scripts/vendor.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Writes assets/vendor/.js for each library hugo.toml names under +# [params.vendor], from its npm package, for a network that blocks the CDN. +# +# scripts/vendor.sh cytoscape and mermaid +# scripts/vendor.sh mermaid one of them +# +# npm fetches the package from the registry it is set to read, in .npmrc or +# npm_config_registry. The package and version are the ones in the address +# hugo.toml names, and a file is kept only when its SHA-256 is the one +# hugo.toml holds. Commit the files: the build takes them before the address. +set -euo pipefail +here=$(cd "$(dirname "$0")/.." && pwd) +command -v npm >/dev/null 2>&1 || { echo "vendor.sh: npm not found; it fetches each package from the registry it reads" >&2; exit 1; } +mode=$("$here/scripts/uv-env.sh" "$here") +# name, package@version, path in the package and SHA-256, one line each. +tool=(uv run --project "$here" "$mode" --quiet) +wanted=$("${tool[@]}" python -I - "$here/hugo.toml" "$@" <<'PY' +import re, sys, tomllib +with open(sys.argv[1], "rb") as file: + vendor = tomllib.load(file)["params"]["vendor"] +for name in sys.argv[2:] or sorted(vendor): + if name not in vendor: + sys.exit(f"vendor.sh: hugo.toml names no library {name}; it names {', '.join(sorted(vendor))}") + found = re.fullmatch(r"https://cdn\.jsdelivr\.net/npm/((?:@[a-z0-9._-]+/)?[a-z0-9._-]+@[0-9][A-Za-z0-9.+-]*)/([A-Za-z0-9._/-]+)", vendor[name]["url"]) + if not found or ".." in found.group(2) or not re.fullmatch(r"[0-9a-f]{64}", vendor[name]["sha256"]): + sys.exit(f"vendor.sh: hugo.toml's address for {name} is not a jsDelivr npm address with a SHA-256") + print(name, found.group(1), found.group(2), vendor[name]["sha256"]) +PY +) +work=$(mktemp -d "${TMPDIR:-/tmp}/vendor.XXXXXX") +trap 'rm -rf "$work"' EXIT +mkdir -p "$here/assets/vendor" +while read -r name package path sha; do + [ -n "$name" ] || continue + mkdir "$work/$name" + (cd "$work/$name" && npm pack --silent --ignore-scripts "$package" >/dev/null) || { echo "vendor.sh: npm could not fetch $package from the registry it reads" >&2; exit 1; } + tar -xzf "$work/$name"/*.tgz -C "$work/$name" "package/$path" || { echo "vendor.sh: $package holds no $path" >&2; exit 1; } + got=$("${tool[@]}" python -I -c 'import hashlib, sys; print(hashlib.sha256(open(sys.argv[1], "rb").read()).hexdigest())' "$work/$name/package/$path") + [ "$got" = "$sha" ] || { echo "vendor.sh: $package's $path has SHA-256 $got, not the $sha that hugo.toml names; no file is written" >&2; exit 1; } + cp "$work/$name/package/$path" "$here/assets/vendor/$name.js" + echo "vendor.sh: wrote assets/vendor/$name.js from $package" +done <<<"$wanted" diff --git a/website/uv.lock b/website/uv.lock index 8dd2dc8..e9077db 100644 --- a/website/uv.lock +++ b/website/uv.lock @@ -1,22 +1,22 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.11" [[package]] name = "hugo" -version = "0.169.0" +version = "0.170.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/06/1d/0ea849ac0cdf763f28cff47ad07d35dbfe4ff46835dd360f51027e30d7d8/hugo-0.169.0.tar.gz", hash = "sha256:e0e06e3ec945798568c0e5b7bf2798ca7912ad5582b15f72e154b6a4997e1ca5", size = 4795089, upload-time = "2026-10-28T09:46:09.103Z" } +sdist = { url = "https://files.pythonhosted.org/packages/6e/1d/d61a7179fe65654e21a3904350ec7d195aedda64d7630fa4f7c3314d59bd/hugo-0.170.0.tar.gz", hash = "sha256:aabfbac8b9a51d686a74ffa5dbd1924806eefd06d7ed5064449997773888e966", size = 4750814, upload-time = "2026-11-14T15:54:18.415Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/10/29/8650fa2f5bca6fd5bc0cb52276d856ce6318d2c82a255319c430b8057521/hugo-0.169.0-py3-none-macosx_10_15_x86_64.whl", hash = "sha256:2d509d0aaae6a42f4df090f35f51e44842d7a1e81cdda35b232f6f56c0697d75", size = 30483480, upload-time = "2026-10-28T09:45:34.882Z" }, - { url = "https://files.pythonhosted.org/packages/dc/a9/e4b121fbb9188fb5abfcaad987fb6e707b8ebacc8b276189c4efe28e190f/hugo-0.169.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:32ef49488f8f29ea693621fd43b27aed8fd012f326d46d83a03930be5e57dddf", size = 28483966, upload-time = "2026-10-28T09:45:38.622Z" }, - { url = "https://files.pythonhosted.org/packages/54/ff/7b8ee5045ca7aec031f3b39cae16c8563df6b8081a745eafa30972a59fc7/hugo-0.169.0-py3-none-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:931e7e21d9591a674c64a405f2c9115a564a823b72d11f71a0d1a2cb448ab27c", size = 27699342, upload-time = "2026-10-28T09:45:42.393Z" }, - { url = "https://files.pythonhosted.org/packages/1f/9f/e78a20ef3ade05ab16db994f8be199365b4441889b2c55e8b19c35533386/hugo-0.169.0-py3-none-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:73dc1448b874f5f82327d5afaa1a21f5bbd0de65c4e761d6f168b93d118c46f3", size = 27580176, upload-time = "2026-10-28T09:45:46.257Z" }, - { url = "https://files.pythonhosted.org/packages/18/e7/4ef9316759248cae970616ea4d16328afab3dd21674b68cd0bc6492ef4f7/hugo-0.169.0-py3-none-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:7b3d7aed1c3b7e26beeea2364649c40f15aa2f27be0f4bdf3a095920dac4f61c", size = 29818100, upload-time = "2026-10-28T09:45:50.367Z" }, - { url = "https://files.pythonhosted.org/packages/23/d1/1bdd5d419dfc9392e787b17c1173f0f4351dd9960ada161ebfb892b237ea/hugo-0.169.0-py3-none-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a40232a2aafecafe0c8a343cd567a22e3462d790687bce7111e9a9c6d4669b15", size = 30406812, upload-time = "2026-10-28T09:45:54.412Z" }, - { url = "https://files.pythonhosted.org/packages/c0/1d/0ca1024f43cffe9cb505d2211742968e3aa4b4f182f936917892fde42500/hugo-0.169.0-py3-none-win32.whl", hash = "sha256:864efbc32fdd2f0d5e533d40c98502504d98b4d8f559379ad68c1c1518b4591a", size = 30108779, upload-time = "2026-10-28T09:45:58.591Z" }, - { url = "https://files.pythonhosted.org/packages/c3/85/ecc5451336112a0fd561e50e21312b28e45d4846983d89c3b48541642822/hugo-0.169.0-py3-none-win_amd64.whl", hash = "sha256:450c2906db4aeb2aa33108d8bb95c92c23f63c55ff4827abb533925fbaac43b6", size = 32120341, upload-time = "2026-10-28T09:46:02.599Z" }, - { url = "https://files.pythonhosted.org/packages/1d/51/ce87b75f105cd82c1827972e7e9a26e2eaf590b85364b8ea28d01fa9b475/hugo-0.169.0-py3-none-win_arm64.whl", hash = "sha256:3647b6bef324a8de3af39566ab7ced26a737be5ca2cd1eaa928c0c32ac77bbbe", size = 28851037, upload-time = "2026-10-28T09:46:06.391Z" }, + { url = "https://files.pythonhosted.org/packages/fd/41/d5b8f1609fc6a535d23b76e44b7ce3ad90aaa1cb762c6a702a8efba01568/hugo-0.170.0-py3-none-macosx_13_0_arm64.whl", hash = "sha256:c91e470053e01f16cad5ceaf38a8d2eb28deb4376b595f94cdb01bfcd842ddeb", size = 28623830, upload-time = "2026-11-14T15:53:53.64Z" }, + { url = "https://files.pythonhosted.org/packages/4d/aa/7e1ae40b132c7e2bb662ffe323760ff367b9531e3941727e59dd837ef8ba/hugo-0.170.0-py3-none-macosx_13_0_x86_64.whl", hash = "sha256:e9c031981ddd849080028dbfd3a4ec60a37548c1a0bf47b9fe7042195f74e085", size = 30555792, upload-time = "2026-11-14T15:53:56.366Z" }, + { url = "https://files.pythonhosted.org/packages/0f/8f/a1182630ffa695db7c28906e7339c01bbde3a2092a54c0d2f558deff308d/hugo-0.170.0-py3-none-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1c9eaa1c2939d05773dfd3deb03494700cf86207943918f497b43c5a6f68edcd", size = 29733343, upload-time = "2026-11-14T15:53:58.927Z" }, + { url = "https://files.pythonhosted.org/packages/a3/ac/d1ed27cd0eec03f8071542330e131794961f684346cc185bca91f3229fcc/hugo-0.170.0-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7653cd408e115a1fdb65d26ecff980518bc0f86479ed6ae366c61eb91d902534", size = 27103016, upload-time = "2026-11-14T15:54:02.141Z" }, + { url = "https://files.pythonhosted.org/packages/10/f6/1eb962c42d5c0702ed61658d9c8299ffee03127ed2242a0ce83dbde85613/hugo-0.170.0-py3-none-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8a9c10c4633a1ea7fffceb515c65229b486bcfb14ea9af9e538d5cbad335f7fc", size = 26811730, upload-time = "2026-11-14T15:54:05.135Z" }, + { url = "https://files.pythonhosted.org/packages/ad/4a/a98e516a41954c6841cba85321cf990a1c5cfcbe3e6fe25abef5b2557ad6/hugo-0.170.0-py3-none-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:957b08af77133a886a8244565e01cb03357636a09f9f61017fcc9447c1cb5714", size = 29079223, upload-time = "2026-11-14T15:54:07.808Z" }, + { url = "https://files.pythonhosted.org/packages/94/65/28c119c16baa3eb2bcfc8d922d33943b686c2b04eac262bdb1fb3d738a4a/hugo-0.170.0-py3-none-win32.whl", hash = "sha256:8ea4fcdac265d9abdd3dadbb45eb8a043999e4664b0135541efff977ee9b1334", size = 29331786, upload-time = "2026-11-14T15:54:10.517Z" }, + { url = "https://files.pythonhosted.org/packages/6e/53/1b522d1e02cb861893fe0099c9ef12c340bbd2df85f53eec207793a9dc4b/hugo-0.170.0-py3-none-win_amd64.whl", hash = "sha256:ab1ca5ecb5586d6a2be6837897e9f2b277f0f59b0e09a9beebb45dfe8129ea94", size = 31144183, upload-time = "2026-11-14T15:54:13.335Z" }, + { url = "https://files.pythonhosted.org/packages/81/e3/1a1fc39016f1af6c576e3ce413672693953ab9aa247a39c5950bc4ecea50/hugo-0.170.0-py3-none-win_arm64.whl", hash = "sha256:2ec207796615bf949cd7261771657cf50ce6e1c65880975b541303af5622b1b3", size = 28213636, upload-time = "2026-11-14T15:54:16.126Z" }, ] [[package]] @@ -30,7 +30,7 @@ dependencies = [ [package.metadata] requires-dist = [ - { name = "hugo", specifier = "==0.169.0" }, + { name = "hugo", specifier = "==0.170.0" }, { name = "pagefind", extras = ["extended"], specifier = "==1.6.0" }, ] From d01e4d88998229d0f166dbf83d9a108dde92dfcc Mon Sep 17 00:00:00 2001 From: "knowledge-sync[bot]" Date: Thu, 19 Nov 2026 00:59:34 +0000 Subject: [PATCH 2/3] security(sidecar): sync workflows from v0.69.2 --- .github/workflows/knowledge-librarian.yaml | 10 + .github/workflows/knowledge-registrar.yaml | 268 ++++++++++++++------- .github/workflows/knowledge-release.yaml | 7 +- .github/workflows/knowledge-sync.yaml | 38 ++- .github/workflows/knowledge-website.yaml | 41 ++-- 5 files changed, 260 insertions(+), 104 deletions(-) diff --git a/.github/workflows/knowledge-librarian.yaml b/.github/workflows/knowledge-librarian.yaml index 8b81ea6..8bfdaac 100644 --- a/.github/workflows/knowledge-librarian.yaml +++ b/.github/workflows/knowledge-librarian.yaml @@ -179,7 +179,12 @@ jobs: # trusts the wheels it unpacked there without hashing them again. So a # cache this job saved after the agent ran could be what the release # restores and packs. + # A runner that holds uv keeps its own; setup-uv fetches one from github.com. + - name: Find uv on the runner + id: uv + run: if command -v uv >/dev/null 2>&1; then echo "found=true" >> "$GITHUB_OUTPUT"; fi - name: Set up uv + if: steps.uv.outputs.found != 'true' uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: python-version: "3.12" @@ -431,7 +436,12 @@ jobs: # No uv cache, as in `refresh`, so nothing the agent's job unpacked is # what this job's checks run on. + # A runner that holds uv keeps its own; setup-uv fetches one from github.com. + - name: Find uv on the runner + id: uv + run: if command -v uv >/dev/null 2>&1; then echo "found=true" >> "$GITHUB_OUTPUT"; fi - name: Set up uv + if: steps.uv.outputs.found != 'true' uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: python-version: "3.12" diff --git a/.github/workflows/knowledge-registrar.yaml b/.github/workflows/knowledge-registrar.yaml index 885c559..34523c3 100644 --- a/.github/workflows/knowledge-registrar.yaml +++ b/.github/workflows/knowledge-registrar.yaml @@ -10,14 +10,16 @@ name: Knowledge Registrar # and runs no LLM or agent. An auditor can follow a run top to bottom: # # validate every run `lokf validate --check-refs`, which checks -# the schema and every relation target; then +# the schema, every relation target and, +# with lokf's shacl extra, LOKF's shapes; then # the conventions script, which checks dates, # event shape and open questions. # -# provenance pull requests for each new `human:` event in the diff: -# approved this pull request -> ok -# signed the commit, per GitHub -> ok -# neither -> unbacked +# provenance pull requests for each `human:` event the diff adds, +# changes or removes, that person: +# approved the concept as it stands -> ok +# signed the commit, per GitHub -> ok +# neither -> unbacked # With keys in .lokf/curators/, a second check # verifies the same signatures with plain git. # @@ -75,7 +77,12 @@ jobs: # No uv cache, as in the release's `pack` job, so this gate runs the # files .lokf/uv.lock names and not what another job left in a cache. + # A runner that holds uv keeps its own; setup-uv fetches one from github.com. + - name: Find uv on the runner + id: uv + run: if command -v uv >/dev/null 2>&1; then echo "found=true" >> "$GITHUB_OUTPUT"; fi - name: Set up uv + if: steps.uv.outputs.found != 'true' uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: python-version: "3.12" @@ -93,7 +100,8 @@ jobs: # A typed relation whose target is no concept in the bundle is still a # well-formed IRI, so schema validation alone passes it. --check-refs # resolves every target in the bundle's own namespace, taking the - # relation slots from the schema. It is part of `lokf validate`, so it + # relation slots from the schema, and the recipe adds --shacl where + # uv.lock holds lokf's shacl extra. It is part of `lokf validate`, so it # rides on this step rather than validating the same bundle twice. A # host with a domain vocabulary names it as `schema :=` in the justfile, and # the recipe passes it; the workflow runs the recipe so no host edits this line. @@ -113,11 +121,14 @@ jobs: # questions in the shape the curator reads. Each of them has been broken # by an agent that had the rule in prose. On a pull request, rule 14 # reads each of its commits too: one that records a person's - # confirmation changes only the verdict. The base is the merge-base of - # the pull request, as the provenance job uses, so a commit the base - # branch gained after the pull request opened is not read as the pull - # request's. The SHAs enter through env:, never interpolated, and a - # scheduled run has none, so it skips rule 14. + # confirmation changes only the verdict. Rule 6 reads them as well: a + # `revision` that names one would name nothing after a squash merge. + # The base is the merge-base of the pull request and the head its last + # commit, as the provenance job uses. This checkout is a merge of the + # pull request into its base, so without the head a commit the base + # branch gained after the pull request opened would be read as the + # pull request's. The SHAs enter through env:, never interpolated, and + # a scheduled run has none, so it skips rule 14. - name: Check the conventions lokf validate cannot see env: BASE_SHA: ${{ github.event.pull_request.base.sha }} @@ -125,7 +136,7 @@ jobs: run: | since="" if [ -n "$BASE_SHA" ]; then since="$(git merge-base "$BASE_SHA" "$HEAD_SHA")"; fi - bash scripts/knowledge-conventions.sh knowledge --strict ${since:+--since "$since"} + bash scripts/knowledge-conventions.sh knowledge --strict ${since:+--since "$since" --head "$HEAD_SHA"} working-directory: .lokf provenance: @@ -222,11 +233,11 @@ jobs: # entry, or the `generated` record the curator's Correct writes as # `human:`. It is read whole as # `\t\t\t\t`, whatever its YAML layout, - # and keyed by the concept's id so a rename keeps its events and a - # copy does not. An added line would not do: a re-dated `at`, a moved - # `revision` or a flow-style event adds no `by:` line, and a - # `by: human:` in a body code fence or a send-back note is not an - # event. + # and keyed by the concept's id and its place, so a rename keeps its + # events, and a copy or a move into another concept does not. An + # added line would not do: a re-dated `at`, a moved `revision` or a + # flow-style event adds no `by:` line, and a `by: human:` in a body + # code fence or a send-back note is not an event. # # Any event present at head and absent at base names an actor who # must stand behind it. So does a `verified` event present at base @@ -237,15 +248,23 @@ jobs: # below, never skipped. human_events() { awk -v path="$1" ' - function val(s) { sub(/^[^:]*:[[:space:]]*/, "", s); gsub(/["'"'"']/, "", s); sub(/[[:space:]]+$/, "", s); return s } + # Returns the value after the key, less one pair of enclosing quotes, and sets + # `strange` on an unclosed or inner quote, a `\` escape, a trailing comment or + # a leading indicator, which a parser reads another way. + function val(s, q, n) { sub(/^[^:]*:[[:space:]]*/, "", s); sub(/[[:space:]]+$/, "", s); q = substr(s, 1, 1); n = length(s) + if (q == "\"" || q == "'"'"'") { if (n < 2 || substr(s, n) != q) { strange = 1; return s } + s = substr(s, 2, n - 2); if (index(s, q) || (q == "\"" && index(s, "\\"))) strange = 1; return s } + if (s ~ /[[:space:]]#/ || s ~ /^[!&*|>@`%#]/) strange = 1 + return s } # Nothing this reader cannot follow is taken for no event. The schema gives # an event `by`, `at` and `revision` and no other key, so any other key is a # spelling it cannot follow: a quoted `by`, a merge, an alias. Such an event, # and one whose actor is outside the shape the schema allows, comes out as the actor # (unreadable), which is no login, so each gate refuses it as it refuses any # id it cannot check. - function kv(l, k) { k = l; sub(/:.*/, "", k); sub(/^[[:space:]]+/, "", k) - if (k == "by") by = val(l); else if (k == "at") at = val(l); else if (k == "revision") rev = val(l); else odd = 1 } + function kv(l, k) { k = l; sub(/:.*/, "", k); sub(/^[[:space:]]+/, "", k); strange = 0 + if (k == "by") by = val(l); else if (k == "at") at = val(l); else if (k == "revision") rev = val(l); else odd = 1 + if (strange) odd = 1 } function actor(a) { return a !~ /\\/ && (a ~ /^(human|process):[^[:space:]]+$/ || a ~ "^[^[:space:]/]+/[^[:space:]/]+$") } # Two revisions of a file must differ here whenever they differ in what a # parser could read, or an edit inside an unreadable block passes unseen. @@ -296,7 +315,9 @@ jobs: # a quoted key, `? key`, `<<:` or a flow mapping, can each hold an event. !seen && /[^[:space:]]/ && !/^[[:space:]]*#/ { seen = 1; if (/^[[:space:]]/) unread() } /^["'"'"'?{[]/ || /^(verified|generated)[[:space:]]+:/ { emit(); inv = 0; unread(); next } - /^id:/ { cid = val($0) } + # The id keys every event of the concept: a strange id, or a second `id` + # line, makes the file unreadable. + /^id:/ { strange = 0; cid = val($0); if (strange || ++ids > 1) unread() } /^(verified|generated):/ { emit(); inv = 1; kind = $0; sub(/:.*/, "", kind); rest = $0; sub(/^(verified|generated):[[:space:]]*/, "", rest); sub(/[[:space:]]+$/, "", rest) if (rest ~ /^\{/) { flowseq = 0; flowbuf = rest; inv = 0; if (index(rest, "}")) flushflow(); else inflow = 1 } else if (rest ~ /^\[/) { flowseq = 1; flowbuf = rest; inv = 0; if (index(rest, "]")) flushflow(); else inflow = 1 } @@ -311,61 +332,85 @@ jobs: inv && /^[[:space:]]+[^[:space:]#]/ { inev = 1; odd = 1; next } END { if (plain && dashes >= 2 && path !~ /(^|\/)log\.md$/) unread(); emit(); printf "%s", out; if (bad) { printf "%s\t(unreadable)\t\t", cid ? cid : path; for (i = 1; i <= NR; i++) if (i in raw) printf "%s\001", raw[i]; printf "\tverified\n" } }' } - paths="$(mktemp)" - listed="$(mktemp)" # every path git named under the bundle, quoted or not - now_events="$(mktemp)" - every_events="$(mktemp)" - events_in() { # ref, paths on stdin -> the human events of those paths at that ref, sorted - { while IFS= read -r f; do git show "$1:$f" 2>/dev/null | human_events "$f" || true; done | sort; } || true + work="$(mktemp -d)" + paths="$work/paths" + listed="$work/listed" # every path git named under the bundle, quoted or not + : > "$listed" + # Fail closed: an empty answer from a failed git, awk, sort or comm + # would read as no events, so each read below stops the job instead. + stop() { echo "unreadable: $1"; exit 1; } + + # Each event is prefixed with its place: the concept's path, or `-` + # when the other ref has no file there. An event moved or copied + # between two concepts is one removal and one addition; a rename has + # `-` on both sides, so its events match by id. Duplicates are kept, + # so a second copy is an addition. Matches knowledge-provenance.sh. + placed() { # place, events on stdin -> the events with that place before each + PLACE="$1" awk '{ print ENVIRON["PLACE"] "\t" $0 }' + } + events_in() { # ref, the refs it is compared with..., paths on stdin -> the human events of those paths at that ref, sorted + local ref="$1" f place other + shift + while IFS= read -r f; do + git cat-file -e "$ref:$f" 2>/dev/null || continue + place="-" + for other in "$@"; do + if git cat-file -e "$other:$f" 2>/dev/null; then place="$f"; break; fi + done + git show "$ref:$f" | human_events "$f" | placed "$place" || exit 1 + done | sort } # core.quotePath off: on, git C-quotes a name with a byte above # 0x7f, `.md$` missed it and its events went unread. Git still # quotes a name holding `"`, `\` or a control character, which no # line reader can hold; $listed keeps every name so a quoted one # is refused below rather than skipped. - changed_actors() { # base head -> actors of events at head that base does not hold - { git -c core.quotePath=false diff --name-only "$1" "$2" -- .lokf/knowledge knowledge_bundle | tee -a "$listed" | grep '\.md$' | sort -u > "$paths" - events_in "$2" < "$paths" | comm -13 <(events_in "$1" < "$paths") - | cut -f2; } || true - } - # Against every parent: a merge that brings in another curator's - # confirmation claims nothing, and one that adds an event neither - # side held is read like any other commit. Without -m, git lists no - # paths for a merge. - new_in_commit() { # sha -> actors of events at sha that none of its parents holds - { git -c core.quotePath=false diff-tree --no-commit-id --name-only -r -m "$1" -- .lokf/knowledge knowledge_bundle | tee -a "$listed" | grep '\.md$' | sort -u > "$paths" - events_in "$1" < "$paths" | comm -13 <(for p in $(git rev-parse "$1^@"); do events_in "$p" < "$paths"; done | sort -u) - | cut -f2; } || true + concepts_named() { # names on stdin -> $listed gains each name, and $paths holds the concepts among them + tee -a "$listed" | { grep '\.md$' || [ "$?" -eq 1 ]; } | sort -u > "$paths" } # A removal is a claim too. Of the events that went, a `verified` # one always needs its person. A person's `generated` record may # be replaced by another person's, the curator's Correct, whose - # actor is already checked above as an addition. So it counts only + # actor is already checked as an addition. So it counts only # when no person's `generated` record stands in its place. needs_its_person() { # removed events on stdin, the file of events that remain -> those whose actor must back the removal awk -F'\t' -v now="$1" ' - BEGIN { while ((getline line < now) > 0) { split(line, f, "\t"); if (f[5] == "generated") kept[f[1]] = 1 } } - $5 == "verified" || !($1 in kept)' - } - removed_actors() { # base head -> actors of events base holds that head does not - { git -c core.quotePath=false diff --name-only "$1" "$2" -- .lokf/knowledge knowledge_bundle | tee -a "$listed" | grep '\.md$' | sort -u > "$paths" - events_in "$2" < "$paths" > "$now_events" - events_in "$1" < "$paths" | comm -23 - "$now_events" | needs_its_person "$now_events" | cut -f2; } || true + BEGIN { while ((getline line < now) > 0) { split(line, f, "\t"); if (f[6] == "generated") kept[f[2]] = 1 } } + $6 == "verified" || !($2 in kept)' } - # Against every parent again: what a merge lacks because one side - # never held it is no removal, and a root commit removes nothing. - gone_in_commit() { # sha -> actors of events every parent holds that sha does not - { git -c core.quotePath=false diff-tree --no-commit-id --name-only -r -m "$1" -- .lokf/knowledge knowledge_bundle | tee -a "$listed" | grep '\.md$' | sort -u > "$paths" - events_in "$1" < "$paths" > "$now_events" - first=1 - for p in $(git rev-parse "$1^@"); do - if [ "$first" -eq 1 ]; then events_in "$p" < "$paths" > "$every_events"; first=0 - else events_in "$p" < "$paths" | comm -12 "$every_events" - > "$every_events.next"; mv "$every_events.next" "$every_events"; fi - done - [ "$first" -eq 1 ] || comm -23 "$every_events" "$now_events" | needs_its_person "$now_events" | cut -f2; } || true + # An event the ref holds and no earlier ref holds is added; one every + # earlier ref holds and the ref lacks is removed. With a merge's + # parents as the earlier refs, an event from one side is neither, and + # a root commit adds all it holds. + delta() { # name, ref, the refs before it... -> $work/.added and $work/.gone, from the concepts in $paths + local name="$1" ref="$2" p first=1 + shift 2 + : > "$work/any"; : > "$work/every" + events_in "$ref" "$@" < "$paths" > "$work/now" || return 1 + for p in "$@"; do + events_in "$p" "$ref" < "$paths" > "$work/one" || return 1 + if [ "$first" -eq 1 ]; then + cp "$work/one" "$work/any"; cp "$work/one" "$work/every"; first=0 + else + comm -12 "$work/every" "$work/one" > "$work/next" || return 1 + mv "$work/next" "$work/every" + { cat "$work/any"; comm -13 "$work/any" "$work/one"; } | sort > "$work/next" || return 1 + mv "$work/next" "$work/any" + fi + done + comm -13 "$work/any" "$work/now" > "$work/$name.added" || return 1 + comm -23 "$work/every" "$work/now" | needs_its_person "$work/now" > "$work/$name.gone" || return 1 } - base="$(git merge-base "$BASE_SHA" "$HEAD_SHA")" - - mapfile -t actors < <({ changed_actors "$base" "$HEAD_SHA"; removed_actors "$base" "$HEAD_SHA"; } | sed '/^$/d' | sort -u) + base="$(git merge-base "$BASE_SHA" "$HEAD_SHA")" || stop "this checkout does not hold the base of the pull request." + # --no-renames: a renamed concept is listed under both of its paths, + # so the events it held and the events it holds are both read. + git -c core.quotePath=false diff --no-renames --name-only "$base" "$HEAD_SHA" -- .lokf/knowledge knowledge_bundle > "$work/names" \ + || stop "git could not compare the pull request with its base." + concepts_named < "$work/names" || stop "the paths the pull request changes could not be listed." + cp "$paths" "$work/pr.paths" + delta pr "$HEAD_SHA" "$base" || stop "the events in the concepts this pull request changes could not be read." + mapfile -t actors < <(cut -f3 "$work/pr.added" "$work/pr.gone" | sed '/^$/d' | sort -u) if grep -q '^"' "$listed"; then echo "unreadable: git had to quote these bundle paths, so this gate cannot read them:" @@ -406,10 +451,27 @@ jobs: echo "unreadable: gh is not installed on this runner, and a person's confirmation is checked against GitHub's reviews and signatures with it." exit 1 fi - approvers="$( - gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}/reviews" --paginate \ - --jq '.[] | select(.state == "APPROVED") | .user.login' - )" + # Lists the reviews that approve, request changes or were dismissed, + # oldest first, with their commit. Only a person's last one counts. + gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}/reviews" --paginate \ + --jq '.[] | select(.state == "APPROVED" or .state == "CHANGES_REQUESTED" or .state == "DISMISSED") | [(.user.login // "-"), .state, (.commit_id // "-")] | @tsv' \ + > "$work/reviews" || stop "GitHub did not list the reviews of this pull request." + approved_at() { # login -> the commit their approval was given on, when the approval is their last word + awk -F'\t' -v who="$1" '$1 == who { state = $2; at = $3 } END { if (state == "APPROVED" && at ~ /^[0-9a-f]+$/) print at }' "$work/reviews" + } + # An approval backs a person only while each changed concept that + # carries their name is byte for byte as the approved commit held it. + concepts_of() { # login -> the concepts this pull request changes that hold an event of theirs, before or after + local f ref + while IFS= read -r f; do + for ref in "$base" "$HEAD_SHA"; do + git cat-file -e "$ref:$f" 2>/dev/null || continue + if git show "$ref:$f" | human_events "$f" | awk -F'\t' -v who="$1" '$2 == who { found = 1 } END { exit !found }'; then + printf '%s\n' "$f"; break + fi + done + done < "$work/pr.paths" + } # Signature status has to come from GitHub, not from `git log %G?`. # A runner has no GPG keyring and no `gpg.ssh.allowedSignersFile`, @@ -417,14 +479,35 @@ jobs: # matter how good it is. GitHub checks each signature against the # keys registered to an account, which is also what ties the # signature to a person, rather than merely proving one exists. - commits="$(mktemp)" + # + # The signer is the committer, whose keys GitHub checks: the author is + # a name anyone may type. GitHub signs a web-editor commit as + # `web-flow`, and there the author is the signed-in person. gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}/commits" --paginate \ - --jq '.[] | [.sha, (.commit.verification.verified | tostring), (.author.login // "-")] | @tsv' \ - > "$commits" - - mapfile -t bundle_shas < <( - git log --format='%H' "${base}..${HEAD_SHA}" -- .lokf/knowledge knowledge_bundle - ) + --jq '.[] | [.sha, (.commit.verification.verified | tostring), (.committer.login // "-"), (.author.login // "-")] | @tsv' \ + > "$work/commits" || stop "GitHub did not list the commits of this pull request." + + # Reads what each commit adds and removes against each parent. rev-list + # takes no path, since git would leave out a merge side whose paths + # end as the other side's. --root reads a parentless commit in full. + : > "$work/introduced" + git rev-list "$base..$HEAD_SHA" > "$work/shas" || stop "git could not list the commits of this pull request." + while IFS= read -r sha; do + git -c core.quotePath=false diff-tree --root --no-commit-id --name-only -r -m "$sha" -- .lokf/knowledge knowledge_bundle > "$work/names" \ + || stop "git could not list what commit ${sha:0:8} changes." + concepts_named < "$work/names" || stop "the paths commit ${sha:0:8} changes could not be listed." + [ -s "$paths" ] || continue + mapfile -t parents < <(git rev-parse "$sha^@") + delta commit "$sha" ${parents[@]+"${parents[@]}"} || stop "the events in commit ${sha:0:8} could not be read." + for way in added gone; do + cut -f2- "$work/commit.$way" | SHA="$sha" WAY="$way" awk '{ print ENVIRON["SHA"] "\t" ENVIRON["WAY"] "\t" $0 }' >> "$work/introduced" + done + done < "$work/shas" + if grep -q '^"' "$listed"; then + echo "unreadable: a commit of this pull request touches bundle paths git had to quote, so this gate cannot read them:" + grep '^"' "$listed" | sort -u | sed 's/^/ /' + exit 1 + fi unbacked=() for actor in "${actors[@]}"; do @@ -441,22 +524,25 @@ jobs: unbacked+=("$actor") continue fi - if printf '%s\n' "$approvers" | grep -qxF -- "$actor"; then - echo "ok: human:${actor} approved this pull request." - continue + at="$(approved_at "$actor")" + if [ -n "$at" ]; then + mapfile -t theirs < <(concepts_of "$actor") + if ! git cat-file -e "${at}^{commit}" 2>/dev/null; then + echo "stale: human:${actor} approved commit ${at:0:8}, which this pull request no longer holds." + elif [ "${#theirs[@]}" -gt 0 ] && git diff --quiet "$at" "$HEAD_SHA" -- "${theirs[@]}"; then + echo "ok: human:${actor} approved this pull request, and each concept that carries their name is as they approved it." + continue + else + echo "stale: human:${actor} approved commit ${at:0:8}, and a concept that carries their name has changed since. Ask them to approve again." + fi fi - # No approval from them. The remaining evidence is their own + # No approval of theirs stands. The remaining evidence is their own # signature on each commit that introduced or removed the event. # It is the only route when they opened the pull request # themselves, since GitHub will not let anyone approve their own # pull request. - introducing=() - for sha in "${bundle_shas[@]}"; do - if new_in_commit "$sha" | grep -qxF -- "$actor" || gone_in_commit "$sha" | grep -qxF -- "$actor"; then - introducing+=("$sha") - fi - done + mapfile -t introducing < <(awk -F'\t' -v who="$actor" '$4 == who { print $1 }' "$work/introduced" | sort -u) if [ "${#introducing[@]}" -eq 0 ]; then echo "unbacked: a confirmation by human:${actor} is added, changed or removed here, but no commit in this pull request does it." @@ -466,15 +552,27 @@ jobs: backed=yes for sha in "${introducing[@]}"; do - info="$(awk -v s="$sha" '$1 == s { print $2, $3 }' "$commits")" - verified="${info%% *}" - signer="${info##* }" + verified=""; committer=""; author="" + IFS="$(printf '\t')" read -r verified committer author < <(awk -F'\t' -v s="$sha" '$1 == s { print $2 "\t" $3 "\t" $4 }' "$work/commits") || true + signer="$committer" + if [ "$committer" = "web-flow" ]; then signer="$author"; fi if [ "$verified" = "true" ] && [ "$signer" = "$actor" ]; then continue fi backed=no echo "unbacked: commit ${sha:0:8} adds, changes or removes a confirmation by human:${actor} but GitHub reports it" \ - "verified=${verified:-unknown}, attributed to ${signer:-unknown}." + "verified=${verified:-unknown}, signed by ${signer:-unknown}." + done + + # Each event of theirs the pull request adds or removes must come + # from one of those commits; any other is unbacked. + for way in added gone; do + awk -F'\t' -v who="$actor" '$3 == who' "$work/pr.$way" | cut -f2- | sort -u > "$work/asked" + awk -F'\t' -v who="$actor" -v way="$way" '$2 == way && $4 == who' "$work/introduced" | cut -f3- | sort -u > "$work/found" + if [ -n "$(comm -23 "$work/asked" "$work/found")" ]; then + backed=no + echo "unbacked: this pull request leaves a confirmation by human:${actor} ${way/gone/removed} that no commit in it accounts for." + fi done if [ "$backed" = yes ]; then diff --git a/.github/workflows/knowledge-release.yaml b/.github/workflows/knowledge-release.yaml index 052390e..668303c 100644 --- a/.github/workflows/knowledge-release.yaml +++ b/.github/workflows/knowledge-release.yaml @@ -232,8 +232,13 @@ jobs: # .lokf/uv.lock. A cache is shared by every job on the default branch, # the librarian's agent job among them, and uv trusts the wheels it # unpacked there without hashing them again. - - name: Set up uv + # A runner that holds uv keeps its own; setup-uv fetches one from github.com. + - name: Find uv on the runner + id: uv if: steps.compare.outputs.changed == 'true' + run: if command -v uv >/dev/null 2>&1; then echo "found=true" >> "$GITHUB_OUTPUT"; fi + - name: Set up uv + if: steps.compare.outputs.changed == 'true' && steps.uv.outputs.found != 'true' uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: python-version: "3.12" diff --git a/.github/workflows/knowledge-sync.yaml b/.github/workflows/knowledge-sync.yaml index 047e135..7929478 100644 --- a/.github/workflows/knowledge-sync.yaml +++ b/.github/workflows/knowledge-sync.yaml @@ -89,10 +89,6 @@ on: permissions: {} # deny by default; each job requests only the scopes it needs -concurrency: - group: knowledge-sync - cancel-in-progress: false - jobs: earlier: name: Read the pin, the newest release and the last pull request (read-only) @@ -128,7 +124,12 @@ jobs: with: persist-credentials: false + # A runner that holds uv keeps its own; setup-uv fetches one from github.com. + - name: Find uv on the runner + id: uv + run: if command -v uv >/dev/null 2>&1; then echo "found=true" >> "$GITHUB_OUTPUT"; fi - name: Set up uv + if: steps.uv.outputs.found != 'true' uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: python-version: "3.12" @@ -295,7 +296,12 @@ jobs: with: persist-credentials: false # keep GITHUB_TOKEN off disk while the release is read + # A runner that holds uv keeps its own; setup-uv fetches one from github.com. + - name: Find uv on the runner + id: uv + run: if command -v uv >/dev/null 2>&1; then echo "found=true" >> "$GITHUB_OUTPUT"; fi - name: Set up uv + if: steps.uv.outputs.found != 'true' uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: python-version: "3.12" @@ -358,6 +364,11 @@ jobs: if: needs.sync.outputs.changed == 'true' runs-on: ${{ vars.KNOWLEDGE_RUNNER || 'ubuntu-latest' }} timeout-minutes: 10 + # The two jobs that push take turns. A run waiting for the review + # Environment holds no turn, so it blocks no later sync. + concurrency: + group: knowledge-sync + cancel-in-progress: false # KNOWLEDGE_SYNC_TOKEN belongs in this Environment, limited to the # default branch, so a workflow on any other branch cannot read it. It # records no deployment. @@ -386,7 +397,12 @@ jobs: name: knowledge-sync-patch path: ${{ runner.temp }} + # A runner that holds uv keeps its own; setup-uv fetches one from github.com. + - name: Find uv on the runner + id: uv + run: if command -v uv >/dev/null 2>&1; then echo "found=true" >> "$GITHUB_OUTPUT"; fi - name: Set up uv + if: steps.uv.outputs.found != 'true' uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: python-version: "3.12" @@ -607,6 +623,9 @@ jobs: needs: [earlier, publish, review] runs-on: ${{ vars.KNOWLEDGE_RUNNER || 'ubuntu-latest' }} timeout-minutes: 10 + concurrency: + group: knowledge-sync + cancel-in-progress: false environment: name: knowledge-sync deployment: false @@ -665,6 +684,17 @@ jobs: printf '%s\n' "$wrong" | sed '/^$/d; s/^/ /' exit 1 fi + # A pull request merged, closed or refreshed while the approval + # waited leaves these changes stale; the next sync carries them. + tip="$(git ls-remote "https://x-access-token:${SYNC_TOKEN}@${GITHUB_SERVER_URL#https://}/${GITHUB_REPOSITORY}.git" refs/heads/knowledge-sync | cut -f1)" + if [ -z "$tip" ]; then + echo "::warning::The knowledge-sync branch is gone: its pull request was merged or closed while this approval waited. Nothing is pushed; the next sync proposes any workflow change still missing." + exit 0 + fi + if [ "$tip" != "$LEASE" ]; then + echo "::error::The knowledge-sync branch moved from $LEASE to $tip while this approval waited, so these held changes are stale. Nothing is pushed; apply the ones the pull request lists now, or let the next sync propose them." + exit 1 + fi git apply --index "$held" git config user.name "knowledge-sync[bot]" git config user.email "knowledge-sync[bot]@users.noreply.github.com" diff --git a/.github/workflows/knowledge-website.yaml b/.github/workflows/knowledge-website.yaml index d76f0f8..a003acd 100644 --- a/.github/workflows/knowledge-website.yaml +++ b/.github/workflows/knowledge-website.yaml @@ -1,8 +1,8 @@ name: Knowledge website # Builds the site in website/ (or in ktl-website/, where website/ was another -# site's) from the knowledge bundle, the README, docs/, the figures, the -# changelog and a LinkML schema, each when the repository has it, and +# site's) from the knowledge bundle, the README, SPEC.md, docs/, the figures, +# the changelog and a LinkML schema, each when the repository has it, and # publishes the default branch's build to GitHub Pages. A pull request that # touches any of them gets the same build, link check included, and no # deployment. A weekly run rebuilds the site from the default branch. It @@ -33,6 +33,7 @@ on: - ".lokf/**" - "knowledge_bundle/**" - "README.md" + - "SPEC.md" - "docs/**" - ".assets/**" - "CHANGELOG.md" @@ -47,6 +48,7 @@ on: - ".lokf/**" - "knowledge_bundle/**" - "README.md" + - "SPEC.md" - "docs/**" - ".assets/**" - "CHANGELOG.md" @@ -88,7 +90,12 @@ jobs: persist-credentials: false fetch-depth: 0 + # A runner that holds uv keeps its own; setup-uv fetches one from github.com. + - name: Find uv on the runner + id: uv + run: if command -v uv >/dev/null 2>&1; then echo "found=true" >> "$GITHUB_OUTPUT"; fi - name: Set up uv + if: steps.uv.outputs.found != 'true' uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: enable-cache: true @@ -111,26 +118,32 @@ jobs: # runner the runner image lacks. Where .lokf/uv.lock pins rust-just, # the step links the copy uv checked by hash, alone, so the toolkit's # other commands stay off PATH; else it installs the same version by - # name. + # name. uv-env.sh installs what that lock pins, as the build does. The + # step reads site.toml through site-values.py, as prepare.sh does, so + # a file that is not TOML stops the run here. - name: Install just, when the site builds its data with it env: SITE_DIR: ${{ steps.site.outputs.dir }} run: | - if grep -q '^browseBuild = "just ' "$SITE_DIR/site.toml"; then - mkdir -p "$HOME/.local/bin" - if grep -qx 'name = "rust-just"' .lokf/uv.lock; then - uv sync --project .lokf --frozen --quiet - ln -sf "$PWD/.lokf/.venv/bin/just" "$HOME/.local/bin/just" - else - uv tool install rust-just==1.47.0 - fi - echo "$HOME/.local/bin" >> "$GITHUB_PATH" - fi + build="$(python3 -I "$SITE_DIR/scripts/site-values.py" "$SITE_DIR/site.toml" | sed -n 's/^browseBuild=//p')" + case "$build" in + "just "*) + mkdir -p "$HOME/.local/bin" + if grep -qx 'name = "rust-just"' .lokf/uv.lock; then + bash "$SITE_DIR/scripts/uv-env.sh" .lokf > /dev/null + ln -sf "$PWD/.lokf/.venv/bin/just" "$HOME/.local/bin/just" + else + uv tool install rust-just==1.47.0 + fi + echo "$HOME/.local/bin" >> "$GITHUB_PATH" ;; + esac # build.sh runs prepare.sh first, which runs `lokf export` and, for a # LinkML schema, gen-doc, both from the toolkit .lokf/uv.lock pins. Then # Hugo and Pagefind, from the site's own uv.lock, the cleaning of raw - # HTML, and the link check. + # HTML, and the link check. Behind a package mirror, scripts/uv-env.sh + # installs what each lock pins from it, checked against the lock's + # hashes. The site's README.md says what a blocked CDN needs. - name: Build the site and check its links env: SITE_DIR: ${{ steps.site.outputs.dir }} From 3e0fc02993580daddf52b7fd0804b29c58149112 Mon Sep 17 00:00:00 2001 From: noelmcloughlin Date: Thu, 19 Nov 2026 00:57:41 +0000 Subject: [PATCH 3/3] fix(website): keep the executable bit on uv-env.sh and vendor.sh, which build.sh runs directly --- website/scripts/uv-env.sh | 0 website/scripts/vendor.sh | 0 2 files changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 website/scripts/uv-env.sh mode change 100644 => 100755 website/scripts/vendor.sh diff --git a/website/scripts/uv-env.sh b/website/scripts/uv-env.sh old mode 100644 new mode 100755 diff --git a/website/scripts/vendor.sh b/website/scripts/vendor.sh old mode 100644 new mode 100755