From 35ac4e6e315b145c22d2554c4d42626302f38929 Mon Sep 17 00:00:00 2001 From: Roman PASSLER Date: Fri, 27 Nov 2026 20:19:40 +0100 Subject: [PATCH 1/6] feat(gen-index): generate the mounted-repositories table in CONVENTIONS.md CONVENTIONS.md may carry an ownership section whose mounted-repositories table sits between two marker lines. km gen-index fills it from .gitmodules alone: one row per submodule whose path the index holds as a gitlink, sorted by path, with its url (user info and .git dropped), its branch and what it holds (the optional submodule..km-owns key). No pin is listed, so a pin bump leaves the table fresh. Without markers the file is left alone; with broken ones nothing is written and the run exits 1. --check fails on a stale table, and under pre-commit a rewrite fails the commit. A CONVENTIONS.md or .gitmodules that is a symbolic link is neither read nor written through, with a note. Marker lines in fenced code are examples, and a marker line must close its comment. The file is compared with LF and written back in its own line ending. Bytes that do not decode become U+FFFD, and write_text encodes before it opens a file, so nothing can empty it halfway. Cells drop format characters and stop at 200 characters; mount, url and branch are code spans. A url loses user info (scp-style too), query and fragment; two names for one path give one row. The cases live in tests/ownership_smoke.sh, which CI runs on Linux and Windows. --- .github/workflows/test.yml | 5 + .pre-commit-hooks.yaml | 2 +- README.md | 2 +- src/km/cli.py | 2 +- src/km/gen_index.py | 22 ++- src/km/ownership.py | 273 +++++++++++++++++++++++++++++++++++++ src/km/paths.py | 5 +- tests/ownership_smoke.sh | 172 +++++++++++++++++++++++ 8 files changed, 475 insertions(+), 8 deletions(-) create mode 100644 src/km/ownership.py create mode 100644 tests/ownership_smoke.sh diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 8e14cf4..0638679 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -25,6 +25,7 @@ jobs: KM_REPO_URL="file://$GITHUB_WORKSPACE" /tmp/wheel/bin/km init /tmp/wheel-brain --team --name W --desc w --initials WW --folder d=D - run: bash tests/gate_smoke.sh - run: bash tests/index_smoke.sh + - run: bash tests/ownership_smoke.sh - run: bash tests/pins_smoke.sh - run: bash tests/cites_smoke.sh - run: bash tests/doctor_smoke.sh @@ -154,6 +155,10 @@ jobs: env: PYTHON: python run: bash tests/gate_smoke.sh + - name: the ownership table on Windows (gen-index, validate, upgrade; the symlink cases skip without symlinks) + env: + PYTHON: python + run: bash tests/ownership_smoke.sh - name: km search on Windows (the cases with a stand-in gh run on POSIX only, see GH_STANDIN) env: PYTHON: python diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index 33bf64b..bf09ac5 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -7,7 +7,7 @@ pass_filenames: true - id: km-gen-index name: km gen-index - description: Rewrite every '## Documents' list in _index.md and create a missing one; a commit that changed one fails, stage it and commit again. + description: Rewrite every '## Documents' list in _index.md, create a missing one, and rewrite the mounted-repositories table in CONVENTIONS.md; a commit that changed one fails, stage it and commit again. entry: km gen-index language: python always_run: true # every commit: one that only deletes a doc stages no file pre-commit would pass diff --git a/README.md b/README.md index 36c3a25..b1a3f25 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,7 @@ e2e/ end-to-end test on a sandbox team brain on GitHub (e2e/RE ## Development -The smoke tests need Python 3.11+, PyYAML and git: `bash tests/gate_smoke.sh`, `index_smoke.sh`, `team_smoke.sh`, `doctor_smoke.sh`, `sync_smoke.sh`, `list_smoke.sh`, `ready_smoke.sh` (`km ready` against a stand-in `gh`), `search_smoke.sh` (`km search` over a brain with two mounts, against a stand-in `gh`), `automerge_smoke.sh` (`km automerge`, each merge condition flipped alone, against a stand-in `gh`), `pins_smoke.sh`, `cites_smoke.sh`, `mounted_pins_smoke.sh` (the mounted-pins workflow and script a team brain gets, against a stand-in GitHub API), `action_smoke.sh` (the GitHub Action's install step, with stand-ins for setup-python's interpreter, one that starts only with its `lib` folder on `LD_LIBRARY_PATH`), `skill_smoke.sh` (the skill's core keeps its size limit, no Markdown line under `skills/` is long enough for the Read tool to cut, its reference paths resolve, every `/km` verb has a dispatch row), `hook_smoke.sh` (the plugin's edit guard; the pre-push hook too where pre-commit is installed) and `e2e_smoke.sh` (the e2e driver's seed generator, and its check that `e2e/` names no repository but km's). CI runs them plus the GitHub Action on every pull request (once in GitHub's tool cache, once in another), and `encoding_smoke.sh`, `doctor_smoke.sh`, `sync_smoke.sh`, `hook_smoke.sh`, `signoff_smoke.sh` and `gate_smoke.sh` on Windows (team_smoke runs the encoding test on macOS under non-UTF-8 locales). A release bumps `__version__` in `src/km/__init__.py`, `version` in `.claude-plugin/plugin.json` and the version in this README together; merging that to main is the release, CI tags `vX.Y.Z` once main is green. +The smoke tests need Python 3.11+, PyYAML and git: `bash tests/gate_smoke.sh`, `index_smoke.sh`, `ownership_smoke.sh` (the ownership table in CONVENTIONS.md: gen-index, validate, upgrade), `team_smoke.sh`, `doctor_smoke.sh`, `sync_smoke.sh`, `list_smoke.sh`, `ready_smoke.sh` (`km ready` against a stand-in `gh`), `search_smoke.sh` (`km search` over a brain with two mounts, against a stand-in `gh`), `automerge_smoke.sh` (`km automerge`, each merge condition flipped alone, against a stand-in `gh`), `pins_smoke.sh`, `cites_smoke.sh`, `mounted_pins_smoke.sh` (the mounted-pins workflow and script a team brain gets, against a stand-in GitHub API), `action_smoke.sh` (the GitHub Action's install step, with stand-ins for setup-python's interpreter, one that starts only with its `lib` folder on `LD_LIBRARY_PATH`), `skill_smoke.sh` (the skill's core keeps its size limit, no Markdown line under `skills/` is long enough for the Read tool to cut, its reference paths resolve, every `/km` verb has a dispatch row), `hook_smoke.sh` (the plugin's edit guard; the pre-push hook too where pre-commit is installed) and `e2e_smoke.sh` (the e2e driver's seed generator, and its check that `e2e/` names no repository but km's). CI runs them plus the GitHub Action on every pull request (once in GitHub's tool cache, once in another), and `encoding_smoke.sh`, `doctor_smoke.sh`, `sync_smoke.sh`, `hook_smoke.sh`, `signoff_smoke.sh`, `gate_smoke.sh` and `ownership_smoke.sh` on Windows (team_smoke runs the encoding test on macOS under non-UTF-8 locales). A release bumps `__version__` in `src/km/__init__.py`, `version` in `.claude-plugin/plugin.json` and the version in this README together; merging that to main is the release, CI tags `vX.Y.Z` once main is green. km started inside [dotclaude](https://github.com/pasrom/dotclaude) and was moved here with its history. diff --git a/src/km/cli.py b/src/km/cli.py index 523acde..8c854c8 100644 --- a/src/km/cli.py +++ b/src/km/cli.py @@ -29,7 +29,7 @@ COMMANDS = { "validate": ("km.validate", "check frontmatter, links, the gate and index completeness"), - "gen-index": ("km.gen_index", "regenerate the '## Documents' list in every _index.md, creating a missing one (--check for CI)"), + "gen-index": ("km.gen_index", "regenerate the '## Documents' list in every _index.md, creating a missing one, and the ownership table in CONVENTIONS.md (--check for CI)"), "demote": ("km.demote", "demote served docs past review_by (--apply to write)"), "serve": ("km.serve", "build the served bundle under dist/served/"), "promote": ("km.promote", "move a note into the brain as a review doc, or `promote stub`"), diff --git a/src/km/gen_index.py b/src/km/gen_index.py index d4da457..5ea99fc 100644 --- a/src/km/gen_index.py +++ b/src/km/gen_index.py @@ -13,6 +13,8 @@ (SEGMENT) gets none and still fails the run, and so does one with anything in the way. The km-gen-index pre-commit hook runs it at every commit, so a rewritten or created index fails the commit until it is staged too (the hook stages nothing: on `git commit ` that would land in a temporary index). +It also fills the generated mounted-repositories table in CONVENTIONS.md from .gitmodules (km.ownership), +where the file has its markers; with broken markers it writes nothing at all and exits 1. Run: km gen-index [--root DIR] [--check] """ @@ -25,6 +27,7 @@ from collections import defaultdict from pathlib import Path +from km import ownership from km.common import INDEX_SKIP, ROOT, SKIP, fm_text, folder_of, is_article, read, split_frontmatter, tracked_md from km.paths import git, write_text @@ -159,13 +162,26 @@ def regenerate(check: bool = False, create: bool = False, stage: bool = True) -> def main() -> int: ap = argparse.ArgumentParser(prog="km gen-index", allow_abbrev=False, - description="Regenerate the '## Documents' list in every _index.md, creating a missing one.") - ap.add_argument("--check", action="store_true", help="write nothing; exit 1 if an _index.md would change") + description="Regenerate the '## Documents' list in every _index.md, creating a missing one, and the " + "mounted-repositories table in CONVENTIONS.md.") + ap.add_argument("--check", action="store_true", help="write nothing; exit 1 if an _index.md or CONVENTIONS.md would change") check = ap.parse_args().check # under pre-commit, staging would go to the hook's temporary index on a `git commit `: the # commit fails instead, as on a rewritten list, and the next run takes the scaffold back hook = bool(os.environ.get("PRE_COMMIT")) + conv = ownership.read(ROOT) + for name in ownership.linked(ROOT): + print(f"km gen-index: {name} is a symbolic link: the ownership table in {ownership.FILE} is left alone") + if conv is not None and (why := ownership.marker_problem(conv)): + print(f"km gen-index: {ownership.FILE}: {why}") + return 1 changed, unindexed, created = regenerate(check, create=True, stage=not hook) + # the ownership table: a commit under the hook fails on its rewrite, like pre-commit on any modified file + owned = conv is not None and (new := ownership.render(conv, ROOT)) is not None and new != conv + if owned: + changed.append(ownership.FILE) + if not check: + ownership.write(ROOT, new) if created: print(f"km gen-index: created {'' if hook else 'and staged '}{len(created)}: {', '.join(created)}" f"{'; stage them and commit again' if hook else ''}; an intro above '## Documents' goes in a " @@ -186,7 +202,7 @@ def main() -> int: print(f"km gen-index: these folders have docs or a subfolder index to list but no _index.md; {fix}:") for u in unindexed: print(f" - {u}") - return 1 if (check and changed) or unindexed or (hook and created) else 0 + return 1 if (check and changed) or unindexed or (hook and (created or owned)) else 0 if __name__ == "__main__": diff --git a/src/km/ownership.py b/src/km/ownership.py new file mode 100644 index 0000000..455ce9e --- /dev/null +++ b/src/km/ownership.py @@ -0,0 +1,273 @@ +"""The ownership table in a brain's CONVENTIONS.md: where each kind of fact lives. + +The `## Ownership` section holds two tables. The first is written by hand (Topic | Home | Notes): the +doc, folder, mount or URL that is the home of a kind of fact. The second, under `### Mounted +repositories` between the lines BEGIN and END, is generated by `km gen-index` from .gitmodules alone +(Mount | Repository | Branch | Holds): one row per submodule whose path the git index holds as a +gitlink, sorted by path. Nothing is read from inside a mount and no pin is listed, so moving a pin +leaves the table as it is. Holds is `submodule..km-owns`, a key of km's that git ignores. +Without the markers the file is left alone; with broken ones `km gen-index` writes nothing. Marker lines +inside fenced code are examples, not markers, and each marker line closes its comment on that line. +The file is read with LF and written back with the line ending it has (CRLF where it has any); a +CONVENTIONS.md or .gitmodules that is a symbolic link is neither read nor written through. + +Every value from .gitmodules is made safe for one table cell: bytes that do not decode become U+FFFD, +format characters (zero-width, bidi) are dropped, whitespace (a newline too) collapses, control +characters and backticks become `?` (km.paths.printable), `|` is escaped, a cell holds at most +CELL_MAX characters. Mount, Repository and Branch are code spans; in Holds, plain text, `[` and `]` +become spaces and `<` is written `<`. A url loses its user info (a token), query, fragment and +trailing `.git`. Two submodule names for one path give one row. +""" +from __future__ import annotations + +import re +import unicodedata +from pathlib import Path + +from km.paths import command, git, printable, submodule_config, write_text + +FILE = "CONVENTIONS.md" +BEGIN = "" +# Matched as whole lines only: a value from .gitmodules never starts a line of the table. +_BEGIN = re.compile(r"(?m)^ + +{NONE} + +{END} +""" + + +def linked(root: Path) -> list[str]: + """CONVENTIONS.md and .gitmodules where either is a symbolic link, which km neither reads nor writes + through: it may point anywhere, outside the brain too.""" + return [n for n in (FILE, ".gitmodules") if (root / n).is_symlink()] + + +def read(root: Path) -> str | None: + """CONVENTIONS.md with its line endings as LF (as km reads every Markdown file), or None when there is + none, it is a symbolic link or no regular file, or it is not UTF-8.""" + path = root / FILE + if path.is_symlink() or not path.is_file(): + return None + try: + return path.read_bytes().decode("utf-8").replace("\r\n", "\n") + except (OSError, UnicodeDecodeError): + return None + + +def write(root: Path, text: str) -> None: + """Write CONVENTIONS.md (LF in `text`) with the line ending the file has: CRLF where it has any.""" + path = root / FILE + crlf = path.is_file() and b"\r\n" in path.read_bytes() + write_text(path, text.replace("\n", "\r\n") if crlf else text) + + +_FENCE = re.compile(r"(?m)^ {0,3}(`{3,}|~{3,})[^\n]*$") + + +def _fenced(text: str) -> list[tuple[int, int]]: + """The (start, end) offsets of each fenced code block; an unclosed fence runs to the end.""" + spans, pos = [], 0 + while mo := _FENCE.search(text, pos): + mark = mo.group(1) + if mark[0] == "`" and "`" in mo.group(0)[mo.end(1) - mo.start():]: + pos = mo.end() # a backtick in the info string: no fence + continue + close = re.compile(rf"(?m)^ {{0,3}}{re.escape(mark[0])}{{{len(mark)},}}[ \t]*$") + cm = close.search(text, mo.end()) + spans.append((mo.start(), cm.end() if cm else len(text))) + pos = cm.end() if cm else len(text) + return spans + + +def _unfenced(rx: re.Pattern, text: str) -> list[re.Match]: + """The matches of `rx` that start outside every fenced code block.""" + spans = _fenced(text) + return [m for m in rx.finditer(text) if not any(a <= m.start() < b for a, b in spans)] + + +def _markers(text: str) -> tuple[re.Match, re.Match] | str | None: + """The begin and end lines (outside fenced code), a problem with them, or None when there are none.""" + begins, ends = _unfenced(_BEGIN, text), _unfenced(_END, text) + if not begins and not ends: + return None + fix = "fix the marker lines by hand, then run `km gen-index`" + if open_ := [m for m in begins + ends if not m.group(0).rstrip().endswith("-->")]: + return f"a marker line of the generated ownership table does not close its comment on that line ({printable(open_[0].group(0)[:60])}): {fix}" + if len(begins) == 1 and len(ends) == 1 and begins[0].end() < ends[0].start(): + return begins[0], ends[0] + order = " (end above begin)" if len(begins) == 1 == len(ends) else "" + return (f"the generated ownership table needs one line starting `{BEGIN}` and, below it, one line " + f"`{END}`; found {len(begins)} and {len(ends)}{order}: {fix}") + + +def has_markers(text: str) -> bool: + """Whether the text has a marker line of the generated table outside fenced code, broken or not.""" + return _markers(text) is not None + + +def has_heading(text: str, rx: re.Pattern) -> bool: + """Whether a heading `rx` matches stands outside fenced code.""" + return bool(_unfenced(rx, text)) + + +def marker_problem(text: str) -> str | None: + """What is wrong with the marker lines, or None (both in place, or neither).""" + m = _markers(text) + return m if isinstance(m, str) else None + + +def _gitlinks(root: Path) -> frozenset[str] | None: + """The paths the git index holds as gitlinks (mounts), NFC-normalised; None outside a git work tree.""" + res = git("ls-files", "-z", "-s", cwd=root) + if res.returncode: + return None + return frozenset(unicodedata.normalize("NFC", path) for meta, _, path in + (rec.partition("\t") for rec in res.stdout.split("\0")) if meta.startswith("160000")) + + +def _clean(value: str) -> str: + """A value git printed, its undecodable bytes (kept as surrogates) as U+FFFD, so it can be written.""" + return value.encode("utf-8", "surrogateescape").decode("utf-8", "replace") + + +def rows(root: Path) -> list[tuple[str, str, str, str | None, str | None]] | None: + """(path, name, url, branch, km-owns) of each submodule in .gitmodules whose path is a gitlink in the + index, one per path, sorted by path; None outside a git work tree or where .gitmodules is a symbolic link.""" + links = _gitlinks(root) + if links is None or (root / ".gitmodules").is_symlink(): + return None + url, branch, owns = (submodule_config(root, k) for k in ("url", "branch", "km-owns")) + out: dict[str, tuple] = {} + for name, path in sorted(submodule_config(root, "path").items()): + path = path.strip("/") + if unicodedata.normalize("NFC", path) in links and path not in out: + out[path] = tuple(v if v is None else _clean(v) + for v in (path, name, url.get(name, ""), branch.get(name), owns.get(name))) + return sorted(out.values()) + + +CELL_MAX = 200 + + +def _cell(value: str, code: bool = False) -> str: + """`value` as one table cell, in a code span with `code`: format characters (zero-width, bidi) dropped, + link brackets made spaces outside a code span, whitespace collapsed, control characters and + backticks `?`, at most CELL_MAX characters.""" + v = "".join(c for c in value if unicodedata.category(c) != "Cf") + v = printable(" ".join((v if code else v.replace("[", " ").replace("]", " ")).split())) + if len(v) > CELL_MAX: + v = v[:CELL_MAX - 1].rstrip() + "\u2026" + v = v.replace("|", "\\|") + return f"`{v}`" if code else v.replace("<", "<") + + +def _url(url: str) -> str: + """A url without user info (a token or password), query, fragment and trailing .git; scp-style + `user@host:path` loses its user too. A local path is kept as it is, but for .git.""" + url = url.strip() + if mo := re.match(r"([A-Za-z][A-Za-z0-9+.-]*://)(?:[^/?#]*@)?([^?#]*)", url): + url = mo.group(1) + mo.group(2) + elif mo := re.match(r"[^/@:]+@([^/:]+:[^?#]*)", url): + url = mo.group(1) + return url[:-4] if url.endswith(".git") else url + + +def table(found: list) -> str: + """The generated block's content for rows() `found`.""" + if not found: + return NONE + lines = [HEADER] + for path, _name, url, branch, owns in found: + where = "default" if branch is None else "this brain's branch" if branch.strip() == "." else _cell(branch, code=True) + lines.append(f"| {_cell(path, code=True)} | {_cell(_url(url), code=True)} | {where} | {_cell(owns) if owns and owns.strip() else '_not stated_'} |") + return "\n".join(lines) + + +def render(text: str, root: Path) -> str | None: + """`text` with the generated table brought up to date, everything outside the markers kept byte + for byte; None where km leaves the file alone: no markers, broken ones (marker_problem), or no git + index to read the mounts from.""" + m = _markers(text) + found = rows(root) if isinstance(m, tuple) else None + return None if found is None else _fill(text, m, found) + + +def _fill(text: str, markers: tuple[re.Match, re.Match], found: list) -> str: + begin, end = markers + return text[:begin.end()] + "\n\n" + table(found) + "\n\n" + text[end.start():] + + +def _hand_rows(text: str) -> list[tuple[str, str]]: + """(topic, home) of each body row of a table headed Topic in the `## Ownership` section, outside the + generated block, HTML comments and fenced code.""" + for a, b in reversed(_fenced(text)): # fenced code, offsets kept: a blank line per line + text = text[:a] + "\n" * text.count("\n", a, b) + text[b:] + sec = _SECTION.search(text) + if not sec: + return [] + nxt = _H2.search(text, sec.end()) + body = text[sec.end():nxt.start() if nxt else len(text)] + body = re.sub(r"(?ms)^", "", body) + out: list[tuple[str, str]] = [] + block: list[list[str]] = [] + for line in [*body.splitlines(), ""]: + if line.lstrip().startswith("|"): + block.append([c.strip() for c in re.split(r"(? 2 and block[0][0].casefold() == "topic" and all(re.fullmatch(r":?-+:?", c) for c in block[1]): + out += [(r[0], r[1] if len(r) > 1 else "") for r in block[2:] if any(r)] + block = [] + return out + + +_HOME = re.compile(r"\]\(|\]\[|\[\[|<[A-Za-z][A-Za-z0-9+.-]*:|\b[A-Za-z][A-Za-z0-9+.-]*://", re.I) + + +def problems(text: str, root: Path) -> list[tuple[str, str]]: + """The ownership warnings for CONVENTIONS.md `text`, as (category, detail).""" + out: list[tuple[str, str]] = [] + m = _markers(text) + if isinstance(m, str): + out.append(("ownership-markers", m)) + elif m and (found := rows(root)) is not None: + if _fill(text, m, found) != text: + out.append(("ownership-stale", "the mounted-repositories table differs from .gitmodules: run `km gen-index` " + "and commit CONVENTIONS.md")) + for path, name, _url_, _branch, owns in found: + if not (owns and owns.strip()): + fix = command('git config -f .gitmodules {key} ""', key=f"submodule.{name}.km-owns") + out.append(("ownership-topic", f"the mount {printable(path)} does not say what it holds: set " + f"{fix or 'its km-owns key in .gitmodules'}, then `km gen-index`")) + seen: set[str] = set() + for topic, home in _hand_rows(text): + if not _HOME.search(home): + out.append(("ownership-home", f"the row {printable(topic)!r} names no home: link the doc, folder or mount " + f"that holds it, or give the URL of its source")) + key = " ".join(topic.casefold().split()) + if key in seen: + out.append(("ownership-duplicate", f"the topic {printable(topic)!r} has more than one row: keep one home per topic")) + seen.add(key) + return out diff --git a/src/km/paths.py b/src/km/paths.py index 9e14f24..108c70d 100644 --- a/src/km/paths.py +++ b/src/km/paths.py @@ -46,8 +46,9 @@ def sets_no_eol(repo: Path) -> bool: def write_text(path: Path, text: str) -> None: """Every file km writes: UTF-8 with LF, the bytes the repo holds, also where the default is a code - page and CRLF (Windows).""" - path.write_text(text, encoding="utf-8", newline="\n") + page and CRLF (Windows). Encoded before the file is opened, so text that cannot be written (a lone + surrogate from an undecodable name) raises without emptying the file.""" + path.write_bytes(text.encode("utf-8")) def git_path(root: Path, name: str) -> Path: diff --git a/tests/ownership_smoke.sh b/tests/ownership_smoke.sh new file mode 100644 index 0000000..977406a --- /dev/null +++ b/tests/ownership_smoke.sh @@ -0,0 +1,172 @@ +#!/usr/bin/env bash +# Smoke test for the ownership table in CONVENTIONS.md (km.ownership): km gen-index fills the +# mounted-repositories block from .gitmodules (only paths the index holds as gitlinks), km validate +# warns on it, km upgrade adds the section. Runs on Windows too. +# Run: bash tests/ownership_smoke.sh +set -u +source "$(dirname "$0")/lib.sh" +T="$(mktemp -d)" +trap 'rm -rf "$T" "${OW:-}" "${OS:-}" "${U:-}"' EXIT +doc(){ printf -- '---\ntype: note\ntitle: t\ntimestamp: 2026-08-26\nauthor: X\nstatus: draft\ntags: [t]\n---\nbody\n' > "$1"; } +idx(){ printf -- '---\ntype: reference\ntitle: idx\ntimestamp: 2026-08-26\nauthor: X\nstatus: draft\ntags: [t]\n---\n%b\n' "$2" > "$1"; } +has(){ echo "$out" | grep -q "$1"; } +conv(){ kmpy - "$OW/CONVENTIONS.md" "$1" <<'PY' # conv PYTHON-EXPR: rewrite CONVENTIONS.md as the expression of t (its text) gives it +import sys +p = sys.argv[1]; t = open(p, encoding="utf-8", newline="").read() +open(p, "w", encoding="utf-8", newline="").write(eval(sys.argv[2])) +PY +} + +OW="$(mktemp -d)"; OS="$(mktemp -d)" +for r in peer res other; do git init -q "$OS/$r" && doc "$OS/$r/x.md" && git -C "$OS/$r" add -A && git -C "$OS/$r" "${G[@]}" commit -qm one; done +printf -- '---\ntype: note\ntitle: t\ntimestamp: 2026-08-26\nauthor: X\nstatus: draft\ntags: [t]\n---\nsee [gone](nope.md)\n' > "$OS/peer/dead.md" +git -C "$OS/peer" add -A && git -C "$OS/peer" "${G[@]}" commit -qm dead +mkdir -p "$OW/docs"; doc "$OW/docs/pump.md"; idx "$OW/docs/_index.md" '# Docs\n\n## Documents\n\n- [t](pump.md)' +kmpy - "$OW/CONVENTIONS.md" <<'PY' +import sys +from km.ownership import SECTION +open(sys.argv[1], "w", encoding="utf-8", newline="\n").write("# Conventions\n\nIntro.\n\n" + SECTION + "\n## Next\n\nAfter.\n") +PY +cp "$OW/CONVENTIONS.md" "$T/conv.fresh" +git -C "$OW" init -q && git -C "$OW" add -A && git -C "$OW" "${G[@]}" commit -qm init +gi(){ out="$(cd "$OW" && km gen-index "$@" 2>&1)"; rc=$?; } +outside(){ kmpy - "$OW/CONVENTIONS.md" "$1" <<'PY' # the text outside the markers, of the file and of a copy, is the same +import re, sys +cut = lambda t: re.sub(r"(?s)(')" +gi; holds="$(grep '^| `brains/peer`' "$OW/CONVENTIONS.md")" +{ [ "$rc" = 0 ] && [ "${holds#*| default | }" = 'a\|b ?c? x (https://example.com) <!-- km:ownership:end --> |' ]; } \ + && ok "ownership: a value is escaped into one cell (pipe, backtick, newline, brackets, a marker)" || no "ownership escaping ($holds)" +gi; { [ "$rc" = 0 ] && has "up to date"; } && ok "ownership: gen-index is idempotent over an escaped value" || no "ownership idempotent ($rc: $out)" +out="$(cd "$OW" && km validate 2>&1)"; ! has "ownership-markers" && ok "ownership: a marker in a value does not break the markers" || no "ownership marker in value ($out)" +git -C "$OW" "${G[@]}" commit -qam escaped +# PRE_COMMIT: the rewrite fails the commit, nothing is staged +git -C "$OW" config -f .gitmodules submodule.brains/peer.km-owns "Pump timing" +out="$(cd "$OW" && PRE_COMMIT=1 km gen-index 2>&1)"; rc=$? +{ [ "$rc" = 1 ] && has "updated 1: CONVENTIONS.md; stage them and commit again" && [ -n "$(git -C "$OW" diff --name-only -- CONVENTIONS.md)" ] \ + && [ -z "$(git -C "$OW" diff --cached --name-only)" ]; } && ok "ownership: under pre-commit a rewrite fails the commit and stages nothing" || no "ownership PRE_COMMIT ($rc: $out)" +git -C "$OW" "${G[@]}" commit -qam fill +# broken markers: nothing written (no _index.md either), exit 1 with a fix line +doc "$OW/docs/new.md"; git -C "$OW" add -A +cp "$OW/CONVENTIONS.md" "$T/conv.ok"; printf '\n' >> "$OW/CONVENTIONS.md"; cp "$OW/CONVENTIONS.md" "$T/conv.bad" +gi; { [ "$rc" = 1 ] && has "fix the marker lines by hand" && cmp -s "$OW/CONVENTIONS.md" "$T/conv.bad" && ! grep -q new.md "$OW/docs/_index.md"; } \ + && ok "ownership: broken markers: gen-index writes nothing and exits 1 with a fix line" || no "ownership broken markers ($rc: $out)" +cp "$T/conv.ok" "$OW/CONVENTIONS.md" +# no markers: the file is left alone +sed -i.bak '/km:ownership:/d' "$OW/CONVENTIONS.md" && rm -f "$OW/CONVENTIONS.md.bak"; cp "$OW/CONVENTIONS.md" "$T/conv.none" +gi; { [ "$rc" = 0 ] && cmp -s "$OW/CONVENTIONS.md" "$T/conv.none"; } && ok "ownership: without markers CONVENTIONS.md is left alone" || no "ownership no markers ($rc: $out)" +# a symlinked CONVENTIONS.md is neither read nor written through, wherever it points +mv "$OW/CONVENTIONS.md" "$OS/conv.outside"; printf '\nstale\n\n' >> "$OS/conv.outside" +cp "$OS/conv.outside" "$T/conv.outside" +if ln -s "$OS/conv.outside" "$OW/CONVENTIONS.md" 2>/dev/null && [ -L "$OW/CONVENTIONS.md" ]; then + gi; { [ "$rc" = 0 ] && has "CONVENTIONS.md is a symbolic link" && cmp -s "$OS/conv.outside" "$T/conv.outside"; } \ + && ok "ownership: gen-index writes nothing through a symlinked CONVENTIONS.md, with a note" || no "ownership symlink ($rc: $out)" +else echo " skip: no symbolic links here"; fi +rm -f "$OW/CONVENTIONS.md" +cp "$T/conv.ok" "$OW/CONVENTIONS.md"; git -C "$OW" config -f .gitmodules submodule.tools/res.km-owns "Shared resources"; gi; git -C "$OW" add -A && git -C "$OW" "${G[@]}" commit -qm docs +# git and bump-mounted-pins ignore km-owns +out="$(git -C "$OW" "${G[@]}" submodule update --init 2>&1 && git -C "$OW" submodule status 2>&1)"; rc=$? +{ [ "$rc" = 0 ] && ! has "km-owns" && ! has warning; } && ok "ownership: git takes a .gitmodules with km-owns without a word" || no "ownership git and km-owns ($rc: $out)" +out="$(cd "$OW" && kmpy - "$REPO/src/km/templates/team/bump-mounted-pins.py" <<'PY' +import importlib.util, sys +spec = importlib.util.spec_from_file_location("bmp", sys.argv[1]); m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m) +subs = m.submodules() +print(subs) +sys.exit(not subs or any(set(s) != {"name", "path", "url", "branch", "slug"} for s in subs)) +PY +)"; [ $? = 0 ] && ok "ownership: bump-mounted-pins reads path, url and branch only" || no "ownership bump-mounted-pins ($out)" +# --- what .gitmodules or CONVENTIONS.md may hold: undecodable bytes, fenced examples, CRLF, odd urls, +# two names for one path, format characters, long values, a symlink --- +save(){ cp "$OW/CONVENTIONS.md" "$T/c.save"; cp "$OW/.gitmodules" "$T/g.save"; } +restore(){ rm -f "$OW/CONVENTIONS.md" "$OW/.gitmodules"; cp "$T/c.save" "$OW/CONVENTIONS.md"; cp "$T/g.save" "$OW/.gitmodules"; } +pyhas(){ kmpy - "$OW/CONVENTIONS.md" "$1" <<'PY' # pyhas PYTHON-EXPR: true when the expression of t (CONVENTIONS.md as bytes decoded) holds +import sys +b = open(sys.argv[1], "rb").read(); t = b.decode("utf-8") +sys.exit(not eval(sys.argv[2])) +PY +} +save +printf '\tkm-owns = Pr\xfcfst\xe4nde\n' >> "$OW/.gitmodules" # in the last section, tools/res: the last value wins +gi; { [ "$rc" = 0 ] && pyhas '"| Pr�fst�nde |" in t and t.startswith("# Conventions")'; } \ + && ok "ownership: a byte .gitmodules does not decode becomes U+FFFD, the file stays whole" || no "ownership undecodable byte ($rc: $out)" +gi; { [ "$rc" = 0 ] && has "up to date"; } && ok "ownership: and the next run finds it up to date" || no "ownership undecodable rerun ($rc: $out)" +restore; printf '\tkm-owns = Pr\xfcfst\xe4nde\n' >> "$OW/.gitmodules" +out="$(cd "$OW" && PRE_COMMIT=1 km gen-index 2>&1)"; rc=$? +{ [ "$rc" = 1 ] && pyhas '"Pr�fst" in t and "## Next" in t'; } && ok "ownership: under pre-commit too: the commit fails, the file is whole" || no "ownership undecodable PRE_COMMIT ($rc: $out)" +restore +# a fenced example of the markers is no marker: the real block is filled, the example and _index.md lists stay right +conv 't + "\n## Example\n\n```markdown\n\nexample text\n\n```\n"'; cp "$OW/CONVENTIONS.md" "$T/c.fenced" +git -C "$OW" config -f .gitmodules submodule.brains/peer.km-owns "Pump timing and flow"; doc "$OW/docs/fence.md"; git -C "$OW" add docs/fence.md +gi; { [ "$rc" = 0 ] && grep -q "fence.md" "$OW/docs/_index.md" && pyhas '"Pump timing and flow |" in t and "\n\nexample text\n\n```\n" in t'; } \ + && ok "ownership: markers in a fenced example are no markers: the real block is filled, the example kept, _index.md updated" || no "ownership fenced example ($rc: $out)" +git -C "$OW" rm -q -f docs/fence.md; gi >/dev/null +printf '# C\n\n```\n\nhand text\n\n```\n' > "$OW/CONVENTIONS.md"; cp "$OW/CONVENTIONS.md" "$T/c.only" +gi; { [ "$rc" = 0 ] && cmp -s "$OW/CONVENTIONS.md" "$T/c.only"; } && ok "ownership: a file whose only markers are in a fence is left alone" || no "ownership fence only ($rc: $out)" +printf '# C\n\n\n\nhand text\n\n\n' > "$OW/CONVENTIONS.md"; cp "$OW/CONVENTIONS.md" "$T/c.wrap" +gi; { [ "$rc" = 1 ] && has "does not close its comment on that line" && cmp -s "$OW/CONVENTIONS.md" "$T/c.wrap"; } \ + && ok "ownership: a begin comment wrapped onto two lines is a broken marker: nothing written, exit 1" || no "ownership wrapped begin ($rc: $out)" +restore +# CRLF: read as LF, compared as LF, written back with CRLF throughout +conv 't.replace("\n", "\r\n")' +gi --check; [ "$rc" = 0 ] && ok "ownership: a CRLF CONVENTIONS.md with a fresh table is up to date" || no "ownership CRLF fresh ($rc: $out)" +git -C "$OW" config -f .gitmodules submodule.brains/peer.km-owns "Pump timing and flow" +gi; { [ "$rc" = 0 ] && pyhas 'b.count(b"\n") == b.count(b"\r\n") and b"Pump timing and flow |\r\n" in b'; } \ + && ok "ownership: gen-index keeps CRLF throughout a CRLF file" || no "ownership CRLF write ($rc: $out)" +restore +# urls: scp-style user, query and fragment dropped, IPv6 brackets kept +url_row(){ git -C "$OW" config -f .gitmodules submodule.brains/peer.url "$1"; gi; grep -q "^| \`brains/peer\` | \`$2\` |" "$OW/CONVENTIONS.md"; } +url_row "git@example.com:acme/peer.git" "example.com:acme/peer" && ok "ownership: an scp-style url loses its user" || no "ownership scp url ($(grep brains/peer "$OW/CONVENTIONS.md"))" +url_row "https://example.com/acme/peer.git?token=s3cret#frag" "https://example.com/acme/peer" && ! grep -q s3cret "$OW/CONVENTIONS.md" \ + && ok "ownership: a url loses its query and fragment" || no "ownership url query ($(grep brains/peer "$OW/CONVENTIONS.md"))" +url_row "https://u:p@[::1]/acme/peer" 'https://\[::1\]/acme/peer' && ok "ownership: IPv6 brackets stay" || no "ownership IPv6 ($(grep brains/peer "$OW/CONVENTIONS.md"))" +restore +git -C "$OW" config -f .gitmodules submodule.zz-dup.path brains/peer; git -C "$OW" config -f .gitmodules submodule.zz-dup.url "$OS/other" +gi; [ "$(grep -c '^| `brains/peer`' "$OW/CONVENTIONS.md")" = 1 ] && ok "ownership: two names for one path give one row" || no "ownership duplicate path ($(grep brains/peer "$OW/CONVENTIONS.md"))" +restore +kmpy -c 'import subprocess, sys; subprocess.run(["git", "-C", sys.argv[1], "config", "-f", ".gitmodules", "submodule.brains/peer.km-owns", "A​B‮C" + "x" * 300], check=True)' "$OW" +gi; { [ "$rc" = 0 ] && pyhas 'any(l.startswith("| `brains/peer`") and l.split(" | ")[3] == "ABC" + "x" * 196 + "… |" for l in t.splitlines())'; } \ + && ok "ownership: format characters are dropped and a cell is cut at 200 characters" || no "ownership Cf and length ($(grep brains/peer "$OW/CONVENTIONS.md" | cut -c1-120))" +restore +mv "$OW/.gitmodules" "$OS/gitmodules.outside" +if ln -s "$OS/gitmodules.outside" "$OW/.gitmodules" 2>/dev/null && [ -L "$OW/.gitmodules" ]; then + git -C "$OW" config -f "$OS/gitmodules.outside" submodule.brains/peer.km-owns "Read through a link"; cp "$OW/CONVENTIONS.md" "$T/c.link" + gi; { [ "$rc" = 0 ] && has ".gitmodules is a symbolic link" && cmp -s "$OW/CONVENTIONS.md" "$T/c.link"; } \ + && ok "ownership: a symlinked .gitmodules is not read, with a note" || no "ownership .gitmodules symlink ($rc: $out)" +else echo " skip: no symbolic links here"; fi +restore +gi; git -C "$OW" add -A && git -C "$OW" "${G[@]}" commit -q --allow-empty -m restored; gi --check +[ "$rc" = 0 ] && ok "ownership: back to the committed state, fresh" || no "ownership restored ($rc: $out)" + +summary ownership-smoke || exit 1 From 2f4ee70932570876a7f7ecd45623acdf22e2232b Mon Sep 17 00:00:00 2001 From: Roman PASSLER Date: Fri, 27 Nov 2026 20:19:41 +0100 Subject: [PATCH 2/6] feat(validate): warn on a stale or malformed ownership table Whole-repo runs read the ownership section of CONVENTIONS.md and warn: ownership-stale (the generated table differs from .gitmodules), ownership-markers (a begin or end line missing, doubled or out of order), ownership-topic (a mount without km-owns), ownership-home (a hand row with no link and no URL) and ownership-duplicate (a topic in two rows). All are warnings; a dead link in a row stays dead-link. --- src/km/validate.py | 10 ++++++++++ tests/ownership_smoke.sh | 28 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/km/validate.py b/src/km/validate.py index d67e835..74151aa 100644 --- a/src/km/validate.py +++ b/src/km/validate.py @@ -54,6 +54,13 @@ links in code (indented and fenced blocks, code spans) or HTML comments, [[wiki]] links, and anything outside a git work tree. With FILEs, those files are checked against the whole index. +The `## Ownership` section of CONVENTIONS.md (km.ownership), in whole-repo runs only: `ownership-stale` +(the generated mounted-repositories table differs from .gitmodules), `ownership-markers` (its begin or +end line missing, doubled or out of order), `ownership-topic` (a mount without km-owns), +`ownership-home` (a row of the hand-written Topic table with no link and no URL) and +`ownership-duplicate` (a topic, case-folded, in two rows): all WARNINGS. A dead link in a row is +`dead-link`. + A served doc whose content changed since its approval (`approved_digest`, see km.common.DIGEST_FIELDS) is `approval-stale`: an ERROR with the gate on (a team brain), a WARNING without it. @@ -96,6 +103,7 @@ import yaml from km.common import APPROVAL_DEFAULT, APPROVAL_FIELDS, APPROVAL_LEVELS, EXEMPT, approval_default_of, approval_level, body_of, is_ai_approver, doc_at, OVERLAY, PIN, RETIRED_STATUS, ROOT, SCHEMA, approval_problem, approved_digest, colliding_keys, unquoted_scalars, as_list, brain_path, folder_of, fresh_run, known_file, pin_state, resolve_slug, submodule_prefixes, tracked_md, under, unportable_part, mount_paths, paths_by_lower, tracked_paths +from km import ownership from km.cites import opaque as cite_opaque, problems as cite_problems, uncited from km.paths import git from km.pins import movable_refs @@ -1259,6 +1267,8 @@ def main() -> int: if CHECK_INDEX and not given: # whole-repo lint only; skip on per-file (pre-commit) runs check_index_tree() + if not given and (_conv := ownership.read(ROOT)) is not None: # the ownership table, whole-repo only + warnings.extend((_c, ownership.FILE, _d) for _c, _d in ownership.problems(_conv, ROOT)) if not given: # code the brain runs from a movable ref instead of a commit (see km.pins) for _f, _what in movable_refs(ROOT): warnings.append(("movable-ref", _f, f"runs {_what}, a ref that can be moved; pin it by commit " diff --git a/tests/ownership_smoke.sh b/tests/ownership_smoke.sh index 977406a..fe3fd5b 100644 --- a/tests/ownership_smoke.sh +++ b/tests/ownership_smoke.sh @@ -168,5 +168,33 @@ else echo " skip: no symbolic links here"; fi restore gi; git -C "$OW" add -A && git -C "$OW" "${G[@]}" commit -q --allow-empty -m restored; gi --check [ "$rc" = 0 ] && ok "ownership: back to the committed state, fresh" || no "ownership restored ($rc: $out)" +# validate: the five warnings, each on its condition only; a dead row link is dead-link; exit 0 +vout(){ out="$(cd "$OW" && km validate 2>&1)"; rc=$?; } +vout; { [ "$rc" = 0 ] && ! has "ownership-" && ! has "nope.md"; } \ + && ok "ownership: a fresh table with every mount stated warns nothing; a mount's own dead links are not the brain's" || no "ownership validate clean ($rc: $out)" +kmpy - "$OW/CONVENTIONS.md" <<'PY' +import sys +p = sys.argv[1]; t = open(p, encoding="utf-8").read() +rows = ("| Pump ratings | [docs/pump.md](docs/pump.md) | datasheet |\n| Peer timing | [peer](brains/peer/) | |\n" + "| Resources | [res](tools/res2/) | |\n| Coil | https://example.com/coil | |\n\n\n") +open(p, "w", encoding="utf-8", newline="\n").write(t.replace("|-------|------|-------|\n", "|-------|------|-------|\n" + rows, 1)) +PY +git -C "$OW" "${G[@]}" commit -qam rows +vout; { [ "$rc" = 0 ] && ! has "ownership-" && ! has "dead-link"; } && ok "ownership: hand rows with links and URLs, one to a mount root, and a row in a comment warn nothing" || no "ownership hand rows ($rc: $out)" +git -C "$OW" submodule deinit -q -f tools/res2 +vout; ! has "dead-link" && ok "ownership: a link to a mount root not checked out is no dead link" || no "ownership unchecked mount ($out)" +kmpy - "$OW/CONVENTIONS.md" <<'PY' +import sys +p = sys.argv[1]; t = open(p, encoding="utf-8").read() +open(p, "w", encoding="utf-8", newline="\n").write(t.replace("| Coil | https://example.com/coil | |\n", + "| Coil | ask the bench team | |\n| pump RATINGS | [x](docs/gone.md) | |\n", 1)) +PY +git -C "$OW" config -f .gitmodules --unset submodule.brains/peer.km-owns; git -C "$OW" add -A +vout; { [ "$rc" = 0 ] && has "ownership-home" && has "'Coil' names no home" && has "ownership-duplicate" && has "'pump RATINGS' has more than one row" \ + && has "ownership-stale" && has "ownership-topic" && has "the mount brains/peer does not say what it holds" && has "links missing docs/gone.md" && ! has "ownership-markers"; } \ + && ok "ownership: home, duplicate, stale and topic warn on their condition, a dead row link is dead-link, exit 0" || no "ownership warnings ($rc: $out)" +printf '\n' >> "$OW/CONVENTIONS.md" +vout; { [ "$rc" = 0 ] && has "ownership-markers" && ! has "ownership-stale"; } && ok "ownership: a second begin line is ownership-markers, not stale too" || no "ownership markers ($rc: $out)" +out="$(cd "$OW" && km validate CONVENTIONS.md docs/pump.md 2>&1)"; ! has "ownership-" && ok "ownership: per-file runs skip the table" || no "ownership per-file ($out)" summary ownership-smoke || exit 1 From 7fa8cec1241e46d2b529c925a80354a78a6193da Mon Sep 17 00:00:00 2001 From: Roman PASSLER Date: Fri, 27 Nov 2026 20:19:41 +0100 Subject: [PATCH 3/6] feat(init): ownership section in the CONVENTIONS templates Both templates, personal and team, carry the ownership section: a header-only Topic | Home | Notes table to fill by hand, and the mounted-repositories table with its generated block empty, as km gen-index renders it with no mount. A fresh brain stays at zero warnings and gen-index --check passes. --- e2e/seed.py | 1 + src/km/templates/CONVENTIONS.template.md | 17 +++++++++++++++++ .../templates/team/CONVENTIONS.team.template.md | 17 +++++++++++++++++ tests/team_smoke.sh | 10 ++++++++++ 4 files changed, 45 insertions(+) diff --git a/e2e/seed.py b/e2e/seed.py index bf71b76..69e1378 100644 --- a/e2e/seed.py +++ b/e2e/seed.py @@ -295,6 +295,7 @@ def _build(b: Builder, out: Path, date: datetime.date, mount: tuple[str, str] | f"\turl = {url}\n", encoding="utf-8") (out / "mounted" / "notes").mkdir(parents=True) # an empty checkout: `git add -A` keeps the gitlink b.run("git", "update-index", "--add", "--cacheinfo", f"160000,{sha},mounted/notes") + b.km("gen-index") # its row in the ownership table of CONVENTIONS.md b.commit("chore(mount): mount the notes repository") b.run("git", "add", "-A") diff --git a/src/km/templates/CONVENTIONS.template.md b/src/km/templates/CONVENTIONS.template.md index 32963ac..3a2b15c 100644 --- a/src/km/templates/CONVENTIONS.template.md +++ b/src/km/templates/CONVENTIONS.template.md @@ -77,6 +77,23 @@ Obsolete/superseded documents are **never deleted** — they remain for historic | `topics/` | Cross-cutting themes | --> +## Ownership + +Where each kind of fact lives: a doc that states such a fact links its home instead of restating it, and `/km review` looks the home up here first. One row per topic; the home is a link to the doc, folder or mounted repository that holds it, or the URL of the source outside the brain. + +| Topic | Home | Notes | +|-------|------|-------| + +### Mounted repositories + +What each mounted brain or shared resource holds. `km gen-index` writes this table from `.gitmodules` and `km validate` reports it when stale: do not edit it here. To say what a mount holds, run `git config -f .gitmodules submodule..km-owns ""`, then `km gen-index`, and commit `.gitmodules` with `CONVENTIONS.md`. + + + +_None mounted._ + + + ## Generated Files An image or diagram made from a source that can be rerun (a script, a `.drawio` file, small input data) is committed with that source in the same folder, and the doc says how to regenerate it, so the next change edits the source instead of redrawing the output. A draw.io export with the diagram embedded is its own source (the doc says to edit it in draw.io); a screenshot or an instrument capture has none. Large input data, or data kept out of git on purpose, stays in an external store: the doc names where it is (`resource:`). diff --git a/src/km/templates/team/CONVENTIONS.team.template.md b/src/km/templates/team/CONVENTIONS.team.template.md index c042b2a..2a19317 100644 --- a/src/km/templates/team/CONVENTIONS.team.template.md +++ b/src/km/templates/team/CONVENTIONS.team.template.md @@ -21,6 +21,23 @@ This file defines the rules every person and AI assistant follows in the **.km-owns ""`, then `km gen-index`, and commit `.gitmodules` with `CONVENTIONS.md`. + + + +_None mounted._ + + + ## Frontmatter schema Every markdown file (except `CLAUDE.md`, `README.md`, `CONVENTIONS.md`, `SKILL.md`, and generated `_index.md`) has YAML frontmatter: diff --git a/tests/team_smoke.sh b/tests/team_smoke.sh index bc6d6c0..15b4573 100644 --- a/tests/team_smoke.sh +++ b/tests/team_smoke.sh @@ -261,6 +261,16 @@ git -C "$P" init -q && git -C "$P" add -A { grep -q '^| `notes/` | Loose notes |$' "$P/CONVENTIONS.md" && [ -f "$P/inbox/_index.md" ] && grep -q "$PINH" "$P/.pre-commit-config.yaml" \ && [ ! -e "$P/.github" ] && grep -q "eol=lf" "$P/.gitattributes"; } && ok "personal init: conventions, inbox, pinned hook, .gitattributes, no CI" || no "personal init: conventions, inbox, pinned hook, .gitattributes, no CI" out="$(km validate --root "$P" 2>&1)"; echo "$out" | grep -q "ERRORS: 0" && ok "personal brain validates clean" || no "personal brain validates clean ($out)" +cp -R "$P" "$F/pg" && git -C "$F/pg" init -q && git -C "$F/pg" add -A +out="$(cd "$F/pg" && km gen-index --check 2>&1 && km validate 2>&1)" +{ out_has "WARNINGS: 0" && out_has "ERRORS: 0"; } && ok "personal brain in git: its ownership table is fresh and validate warns nothing" || no "personal ownership table ($out)" +kmpy - "$REPO/src/km/templates" <<'PY' && ok "both CONVENTIONS templates carry km.ownership.SECTION verbatim, which render leaves as it is with no mount" || no "templates and SECTION" +import sys, pathlib, km.ownership as o +for name in ("CONVENTIONS.template.md", "team/CONVENTIONS.team.template.md"): + text = (pathlib.Path(sys.argv[1]) / name).read_text(encoding="utf-8") + assert text.count(o.SECTION) == 1, name +assert o.SECTION.endswith("\n\n" + o.table([]) + "\n\n" + o.END + "\n") +PY mkdir -p "$F/p2" && git -C "$F/p2" init -q && echo "# mine" > "$F/p2/CLAUDE.md" && printf '\xef\xbb\xbf*.bin binary\n' > "$F/p2/.gitattributes" out="$(km init "$F/p2" --initials PP 2>&1)" { grep -qx "# mine" "$F/p2/CLAUDE.md" && [ "$(cat "$F/p2/.gitattributes")" = $'\xef\xbb\xbf*.bin binary' ] && out_has "sets no line ending"; } \ From 852e9bf5c6996bfcf519a0ef42abe24b08cabb57 Mon Sep 17 00:00:00 2001 From: Roman PASSLER Date: Fri, 27 Nov 2026 20:19:41 +0100 Subject: [PATCH 4/6] feat(upgrade): add the ownership section when a brain crosses 1.26.0 km upgrade appends the ownership section to CONVENTIONS.md, its mounted-repositories table filled from .gitmodules, once: when the brain moves from a km at or below 1.26.0 to a later one, and only where the file has neither an Ownership heading nor the table's markers. A section of the brain's own gets a note and no change; a brain already past 1.26.0 is left alone. Headings and markers are found outside fenced code; the section is written in the file's line ending, and a 'Mounted repositories' heading of the brain's own gets a note. --- src/km/upgrade.py | 36 +++++++++++++++++++++++++++++++++++- tests/ownership_smoke.sh | 34 ++++++++++++++++++++++++++++++++++ tests/team_smoke.sh | 40 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 109 insertions(+), 1 deletion(-) diff --git a/src/km/upgrade.py b/src/km/upgrade.py index d5e4c71..599c2f6 100644 --- a/src/km/upgrade.py +++ b/src/km/upgrade.py @@ -42,6 +42,12 @@ list is left alone, its schema not read; `--force` back to an older km regenerates nothing. Like the digests it runs before the pins move, so a schema km cannot read stops the upgrade there and the run after the fix still does it. +- CONVENTIONS.md gets km's ownership section (km.ownership), once: when the brain moves from a km at + or below 1.26.0 to a later one, and only where it has neither an '## Ownership' heading nor the + table's markers (outside fenced code). Its mounted-repositories table is filled from .gitmodules, in + the file's line ending. A section of the brain's own gets a note and no change, a 'Mounted + repositories' heading of its own a note beside the new section; a brain already past 1.26.0 is left + as it is. - A team brain's km staleness workflow (one that pins km) whose checkout step sets no fetch-depth (km 1.3.0 and earlier wrote it so, and some brains dropped it) gets `fetch-depth: 0`: its run validates after demoting, and source pins need the full history. A checkout step this edit cannot @@ -116,6 +122,7 @@ KM_CI = {"4ab8b6e4f2ef1e22", "e97892ef9bb0d77f", "76dc97b57c9649e3", "0606bf55cf58761c", "a1f4566802ede1da", "2e8e021af1f8ada5", "27f59d74938e41ae"} DIGEST_AFTER = (1, 10, 1) # the last km release that does not record or check approved_digest INDEX_AFTER = (1, 11, 0) # the last km release whose gen-index writes a title as YAML reads it (1.10 as 1.1) +OWNERSHIP_AFTER = (1, 26, 0) # the last km release without the ownership section in CONVENTIONS.md def record_digests() -> tuple[list[str], list[str]]: @@ -178,6 +185,30 @@ def regenerate_indexes(root: Path) -> tuple[list[str], list[str]]: return regenerate()[:2] +def add_ownership(root: Path) -> list[str]: + """Append km's ownership section to CONVENTIONS.md, its mounted-repositories table filled, where the + file has neither an `## Ownership` heading nor a marker line of the table (outside fenced code): what + it did, or a note where it has its own section; nothing where it has the markers or is no regular + file (km.ownership.read).""" + from km import ownership + text = ownership.read(root) + if text is None or ownership.has_markers(text): + return [] + if ownership.has_heading(text, ownership._SECTION): + return [f"{ownership.FILE} has an '## Ownership' section of its own, without km's generated table: " + f"left as it is; to have km list the mounts there, add the table's two marker lines by hand " + f"(km's CONVENTIONS template shows them), then run `km gen-index`"] + notes = [] + if ownership.has_heading(text, ownership.MOUNTS_HEADING): + notes.append(f"{ownership.FILE} already has a 'Mounted repositories' heading of its own: km's table now " + f"lists the mounts in the new '## Ownership' section; remove the hand-written one or merge it there") + new = text.rstrip("\n") + "\n\n" + ownership.SECTION + ownership.write(root, ownership.render(new, root) or new) + return [f"added the '## Ownership' section to {ownership.FILE}, its mounted-repositories table generated " + f"from .gitmodules: fill in the topics table, and `km gen-index` keeps the mounts current; check `git diff`", + *notes] + + USES = re.compile(r"(?m)^([ \t]*(?:-[ \t]+)?uses:[ \t]*([^@\s]+)@)\S+.*$") # 1: up to the @, 2: the action @@ -430,7 +461,7 @@ def crosses(after: tuple[int, ...]) -> bool: """Whether this upgrade moves a pin at or below that release to a km past it (decided before the pins move).""" return (version_key(target) or ()) > after and any( (k := version_key(p.version)) and k <= after for ps in pins.values() for p in ps) - digest_crossing, index_crossing = crosses(DIGEST_AFTER), crosses(INDEX_AFTER) + digest_crossing, index_crossing, ownership_crossing = crosses(DIGEST_AFTER), crosses(INDEX_AFTER), crosses(OWNERSHIP_AFTER) if rewrites or not current: # decided before any write, so a failed lookup changes nothing values = pin_values(target, commit) else: # already on the release: still check it is the release's commit @@ -683,6 +714,9 @@ def crosses(after: tuple[int, ...]) -> bool: if unindexed: done.append(f"{', '.join(unindexed)} hold docs but no _index.md, which `km gen-index --check` fails on: " f"run `km gen-index`, which creates one, or write one by hand") + # once, when the brain crosses to a km with the ownership table: a brain that removed the section later keeps it out + if ownership_crossing: + done += add_ownership(root) if values and (not current or stray): sha = values[""] diff --git a/tests/ownership_smoke.sh b/tests/ownership_smoke.sh index fe3fd5b..d94415e 100644 --- a/tests/ownership_smoke.sh +++ b/tests/ownership_smoke.sh @@ -196,5 +196,39 @@ vout; { [ "$rc" = 0 ] && has "ownership-home" && has "'Coil' names no home" && h printf '\n' >> "$OW/CONVENTIONS.md" vout; { [ "$rc" = 0 ] && has "ownership-markers" && ! has "ownership-stale"; } && ok "ownership: a second begin line is ownership-markers, not stale too" || no "ownership markers ($rc: $out)" out="$(cd "$OW" && km validate CONVENTIONS.md docs/pump.md 2>&1)"; ! has "ownership-" && ok "ownership: per-file runs skip the table" || no "ownership per-file ($out)" +# --- km upgrade past 1.26.0 appends the section: over undecodable bytes, in a CRLF file, past a fenced heading, +# beside a mounts table of the brain's own --- +U="$(mktemp -d)"; fake_km_remote "$U/remote"; export KM_REPO_URL="file://$U/remote" +git -C "$U/remote" "${G[@]}" commit -q --allow-empty -m three && git -C "$U/remote" tag v1.99.0 +git -C "$U/remote" tag v1.11.0 "$(git -C "$U/remote" "${G[@]}" commit-tree -p v0.9.0 -m 1.11 'v0.9.0^{tree}')" +old_brain(){ # old_brain DIR: a personal brain pinned to km 1.11.0, its CONVENTIONS.md without the section + km init "$1" --initials UU --pin v1.11.0 >/dev/null && kmpy - "$1/CONVENTIONS.md" <<'PY' +import sys, km.ownership as o +p = sys.argv[1]; t = open(p, encoding="utf-8").read() +open(p, "w", encoding="utf-8", newline="\n").write(t.replace(o.SECTION + "\n", "", 1)) +PY + git -C "$1" init -q && git -C "$1" add -A && git -C "$1" "${G[@]}" commit -qm init; } +upg(){ out="$(km upgrade --root "$1" --pin v1.99.0 2>&1)"; rc=$?; } +upyhas(){ kmpy - "$1/CONVENTIONS.md" "$2" <<'PY' +import sys +b = open(sys.argv[1], "rb").read(); t = b.decode("utf-8") +sys.exit(not eval(sys.argv[2])) +PY +} +old_brain "$U/b1"; git -C "$U/b1" "${G[@]}" submodule add -q "$OS/peer" brains/peer && printf '\tkm-owns = Pr\xfcfst\xe4nde\n' >> "$U/b1/.gitmodules" +git -C "$U/b1" add -A && git -C "$U/b1" "${G[@]}" commit -qm mount +upg "$U/b1"; { [ "$rc" = 0 ] && upyhas "$U/b1" 't.startswith("# CONVENTIONS.md") and "\n## Ownership\n" in t and "| Pr�fst�nde |" in t and t.endswith("\n")'; } \ + && ok "ownership upgrade: a byte .gitmodules does not decode: the section is added whole, with U+FFFD" || no "ownership upgrade undecodable ($rc: $out)" +old_brain "$U/b2"; kmpy -c 'import sys; p = sys.argv[1]; t = open(p, "rb").read(); open(p, "wb").write(t.replace(b"\n", b"\r\n"))' "$U/b2/CONVENTIONS.md" +out="$(kmpy -c 'import sys, pathlib, km.upgrade as u; print(u.add_ownership(pathlib.Path(sys.argv[1])))' "$U/b2" 2>&1)" +upyhas "$U/b2" 'b.count(b"\n") == b.count(b"\r\n") and b"\r\n## Ownership\r\n" in b' \ + && ok "ownership upgrade: a CRLF CONVENTIONS.md gets the section in CRLF" || no "ownership upgrade CRLF ($out)" +upg "$U/b2"; { [ "$rc" = 0 ] && upyhas "$U/b2" 'b.count(b"\r\n") in (0, b.count(b"\n")) and t.count("## Ownership") == 1'; } \ + && ok "ownership upgrade: the whole upgrade of it leaves one line ending and one section" || no "ownership upgrade CRLF whole ($rc: $out)" +old_brain "$U/b3"; printf '\n```markdown\n## Ownership\n```\n\n## Mounted repositories\n\n| Name | Repo |\n|---|---|\n| peer | example |\n' >> "$U/b3/CONVENTIONS.md" +git -C "$U/b3" add -A && git -C "$U/b3" "${G[@]}" commit -qm own +upg "$U/b3"; { [ "$rc" = 0 ] && out_has "added the '## Ownership' section" && out_has "already has a 'Mounted repositories' heading of its own" \ + && upyhas "$U/b3" 't.count("