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/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/evals/README.md b/evals/README.md index 0cc0e25..bcfb22c 100644 --- a/evals/README.md +++ b/evals/README.md @@ -2,11 +2,11 @@ One case per row of the dispatch table in `skills/km/SKILL.md`, plus a negative case. Each case scaffolds a brain with `km init` from this checkout (`lib/brain.sh`), so run with `--scaffold`; the write and shell cases need `--allow-tools Bash Write Edit`, and every shell command then runs in Claude Code's sandbox inside the fixture brain. That sandbox has no network and gives the run its own empty home, so `lib/brain.sh` installs a uv-managed Python with `bin/km`'s PyYAML pin into that home before the session (this step needs uv and network): `bin/km` then starts offline on its first call. Without it, a run spends its turns getting km to start. The step stands in for what a user's first run fetches from the network, so a passing eval does not show that `bin/km` starts in a sandbox without network. -Each case whose row names a reference file has a `reads-reference` grader (that file was read); `help` and `save content` name only the core, so they have none. `save-cites` is a second case of the save row: a note that links a SharePoint file with a synced copy at hand, which the save flow cites with `km cite add` before the commit. `save-generated` is a third: a note with an SVG plotted from a local measurement export, which the save flow commits together with the script that draws it and a line on how to regenerate it. Its fixture brain lacks the rule in CONVENTIONS.md, like a brain set up before it, so the case measures the skill alone; the model mostly keeps the script without the plugin too (baseline 0.67 and 1.00 in two runs), so it guards against a regression rather than showing a lift. `save-owner` and `save-owner-named` are two more cases of the save row, in a team brain (`team_brain` in `lib/brain.sh`): a note saved without naming an owner gets `owner:` the author's initials, one where the user names someone else gets theirs and keeps the author, and the reply says who owns it; the graders read the doc the run leaves at the path the prompt names. `promote-owner` and `promote-owner-off-roster` are cases of the `promote` row in a team brain with an `owners:` roster: an author on it becomes the promoted doc's owner (the grader reads the file the run leaves); an author off it makes `km promote` refuse, and the run must then pass an `--owner` from the roster or ask whom to name, never edit the roster or write the doc by hand (an `llm` grader on the trace, and the roster line is checked to be unchanged); `promote-owner` also has a `reads-reference` grader, the off-roster case none, since a run may ask before it reads further. Measured without the plugin (3 runs each): `save-owner` 0.67 and `promote-owner` 0.22 against 1.00 with it; `save-owner-named` and `promote-owner-off-roster` pass either way (the model follows a named owner, and reads the roster and asks), so those two guard against a regression rather than show a lift. `lookup-all-brains` is a second case of the question row: a brain with two mounted brains (`brain_with_two_peers` in `lib/brain.sh`) and a fact only in the second mount's merged doc, asked without `@`; it checks that the run starts with `km search` (a `regex` on the trace for its coverage or result line), answers the fact with a `[gamma@]` citation, and (an `llm` grader) names the open pull requests as not searched (the fixture's brains have no GitHub remote, so km search reports them NOT SEARCHED) rather than saying nothing is in review. `lookup-question` allows Bash so that it can run `km search` too. `review-restated-value` is a second case of the review row (link, don't restate): a brain whose accepted `docs/pump-controller.md` states two values of the pump controller, and two docs in review that restate them without a link: a note with one value right and the other off by one digit, and a `type: decision` that quotes the rating it was based on, which differs. It checks that the run searches with `km search` (the `regex` on the trace that `lookup-all-brains` uses; it checks the method, since the rule names `km search`, and fails a run that finds the home with grep), that the reply names the home's file and line and tags a finding with its origin (`regex` graders), and (`llm` graders) that the disagreeing figure is blocking, the matching one is a non-blocking request to link, and the decision, which the reply must cover, is not blocked on its figure. `pr-review-comments` is a second case of the `pr` row: an open PR whose unresolved review threads the user saved to a file, which the flow verifies, fixes, folds and answers, with replies and resolves to post after the push. The threads come from a file because a stand-in `gh` cannot be put in front of the real one: the session keeps the operator's PATH, and neither a `gh` in the run's home nor a PATH in the workspace's `.claude/settings.json` got ahead of it. Without the plugin the model works the threads well enough too (two of its three `llm` graders pass in the baseline); `folds-the-fix` is the one the skill decides. It measures neither posting nor the OK-before-posting rule: nothing is posted. Every case has one grader on the flow's key step (the `km` command it runs, the file it writes, the line it answers). Graders are `tool_used` and `regex`, except the `llm` graders in `fix-in-mounted-brain`, `lookup-all-brains`, `review-restated-value`, `save-generated`, `pr-review-comments` and `promote-owner-off-roster` (those of the latter two judge the trace, not the reply). +Each case whose row names a reference file has a `reads-reference` grader (that file was read); `help` and `save content` name only the core, so they have none. `save-cites` is a second case of the save row: a note that links a SharePoint file with a synced copy at hand, which the save flow cites with `km cite add` before the commit. `save-generated` is a third: a note with an SVG plotted from a local measurement export, which the save flow commits together with the script that draws it and a line on how to regenerate it. Its fixture brain lacks the rule in CONVENTIONS.md, like a brain set up before it, so the case measures the skill alone; the model mostly keeps the script without the plugin too (baseline 0.67 and 1.00 in two runs), so it guards against a regression rather than showing a lift. `save-owner` and `save-owner-named` are two more cases of the save row, in a team brain (`team_brain` in `lib/brain.sh`): a note saved without naming an owner gets `owner:` the author's initials, one where the user names someone else gets theirs and keeps the author, and the reply says who owns it; the graders read the doc the run leaves at the path the prompt names. `promote-owner` and `promote-owner-off-roster` are cases of the `promote` row in a team brain with an `owners:` roster: an author on it becomes the promoted doc's owner (the grader reads the file the run leaves); an author off it makes `km promote` refuse, and the run must then pass an `--owner` from the roster or ask whom to name, never edit the roster or write the doc by hand (an `llm` grader on the trace, and the roster line is checked to be unchanged); `promote-owner` also has a `reads-reference` grader, the off-roster case none, since a run may ask before it reads further. Measured without the plugin (3 runs each): `save-owner` 0.67 and `promote-owner` 0.22 against 1.00 with it; `save-owner-named` and `promote-owner-off-roster` pass either way (the model follows a named owner, and reads the roster and asks), so those two guard against a regression rather than show a lift. `lookup-all-brains` is a second case of the question row: a brain with two mounted brains (`brain_with_two_peers` in `lib/brain.sh`, its ownership table generated with the mounts) and a fact only in the second mount's merged doc, asked without `@`; it checks that the run starts with `km search` (a `regex` on the trace for its coverage or result line), answers the fact with a `[gamma@]` citation, and (an `llm` grader) names the open pull requests as not searched (the fixture's brains have no GitHub remote, so km search reports them NOT SEARCHED) rather than saying nothing is in review. `lookup-question` allows Bash so that it can run `km search` too. `review-restated-value` is a second case of the review row (link, don't restate): a brain whose accepted `docs/pump-controller.md` states two values of the pump controller, and two docs in review that restate them without a link: a note with one value right and the other off by one digit, and a `type: decision` that quotes the rating it was based on, which differs. It checks that the run searches with `km search` (the `regex` on the trace that `lookup-all-brains` uses; it checks the method, since the rule names `km search`, and fails a run that finds the home with grep), that the reply names the home's file and line and tags a finding with its origin (`regex` graders), and (`llm` graders) that the disagreeing figure is blocking, the matching one is a non-blocking request to link, and the decision, which the reply must cover, is not blocked on its figure. `review-ownership-table` is a third case of the review row: the `review-restated-value` brain plus `docs/pump-controller-ratings.md`, which a hand-written row of the `## Ownership` table in CONVENTIONS.md names as the home of the pump controller's ratings, while `docs/pump-controller.md`, which `km search` also finds, states them too; `/km review` of the wiring note must read CONVENTIONS.md, name the table's home with its line (`names-the-table-home`, a `regex`) and the Ownership row it took it from (`names-the-ownership-row`: CONVENTIONS.md with a line, or the words ownership table, row or section), and tag the finding with its origin. `pr-review-comments` is a second case of the `pr` row: an open PR whose unresolved review threads the user saved to a file, which the flow verifies, fixes, folds and answers, with replies and resolves to post after the push. The threads come from a file because a stand-in `gh` cannot be put in front of the real one: the session keeps the operator's PATH, and neither a `gh` in the run's home nor a PATH in the workspace's `.claude/settings.json` got ahead of it. Without the plugin the model works the threads well enough too (two of its three `llm` graders pass in the baseline); `folds-the-fix` is the one the skill decides. It measures neither posting nor the OK-before-posting rule: nothing is posted. Every case has one grader on the flow's key step (the `km` command it runs, the file it writes, the line it answers). Graders are `tool_used` and `regex`, except the `llm` graders in `brains-list-remove`, `fix-in-mounted-brain`, `lookup-all-brains`, `review-restated-value`, `save-generated`, `pr-review-comments` and `promote-owner-off-roster` (those of the latter two and of `brains-list-remove` judge the trace, not the reply). A grader on a `km` command (`runs-km-*`) checks that km ran, not how the model typed it: it is a `regex` on the `trace` that matches a line km itself prints (`repin: pins ...`, `km doctor: `, `ERRORS: `, ...) at the start of a line of a tool result. The model calls km as `km`, as the full path to `bin/km` or through a variable it set (`$KM repin`), and the command text also turns up in descriptions, commit messages and `echo`s, so a match on the Bash input passes when km never started and fails when it ran. Where a command prints several lines, the pattern accepts more than one of them (`km doctor:` or its closing line, `ERRORS:` or `WARNINGS:`), so output cut by `| head` or `| tail` usually still passes. A run whose output was thrown away (`>/dev/null`, `km sync --quiet` with nothing to do, a `| tail` that keeps only the findings under `WARNINGS:`) fails the grader, and so does a refused edit, promote or stub that forwards km validate's report: that is not a validate run of its own. A change to what one of these commands prints changes its grader too, and so does a change to how `claude plugin eval` writes a tool result into the trace (`"tool_use_result":` followed by the output as a JSON string, or by an object whose `stdout` comes first). -The git steps are graded by what git did too. `finds-the-branch-docs` (`pr`) matches a line git prints about the branch's doc, `inbox/thermal-derating.md`: its `--stat` line, its `diff --git` header, or its `--name-status`, `--numstat` or `--raw` line; it depends on the trace format like the `runs-km-*` graders. A bare path is not accepted, since `git ls-files`, `ls` and `grep -l` print it too, so a run that only used `git diff --name-only` fails. `removes-the-submodule` (`brains-list-remove`) checks the state the run leaves behind: `.git/index` no longer holds `brains/peer`. A removal passes however its output was handled (`-q`, a redirect, a pipe); a `git rm -n`, a `deinit` alone or a failed `git rm` fails. It relies on the index keeping full paths (index format 2 or 3, as `git init` writes it; format 4 or a split index would let it pass on any run). +The git steps are graded by what git did too. `finds-the-branch-docs` (`pr`) matches a line git prints about the branch's doc, `inbox/thermal-derating.md`: its `--stat` line, its `diff --git` header, or its `--name-status`, `--numstat` or `--raw` line; it depends on the trace format like the `runs-km-*` graders. A bare path is not accepted, since `git ls-files`, `ls` and `grep -l` print it too, so a run that only used `git diff --name-only` fails. `stages-conventions` (`brains-list-remove`, an `llm` grader on the trace) checks that the run regenerates the mounted-repositories table in CONVENTIONS.md after `git rm` and stages it with the removal, for one commit (`brain_with_peer` generates the row in the mount commit, so the table starts fresh). A run whose sandbox refuses to write `.gitmodules` cannot commit the removal; it passes when both are staged and the reply says why it stopped. `removes-the-submodule` (`brains-list-remove`) checks the state the run leaves behind: `.git/index` no longer holds `brains/peer`. A removal passes however its output was handled (`-q`, a redirect, a pipe); a `git rm -n`, a `deinit` alone or a failed `git rm` fails. It relies on the index keeping full paths (index format 2 or 3, as `git init` writes it; format 4 or a split index would let it pass on any run). Run from the plugin root: `claude plugin eval . --scaffold --no-publish --ablation none --allow-tools Bash Write Edit`; `--tag batch2` selects the nine dispatch cases, and the no-plugin baseline (`--ablation with-without`) is worth its cost only when a grader changes. `results/` is ignored. diff --git a/evals/brains-list-remove/graders/stages-conventions.md b/evals/brains-list-remove/graders/stages-conventions.md new file mode 100644 index 0000000..e19b1d9 --- /dev/null +++ b/evals/brains-list-remove/graders/stages-conventions.md @@ -0,0 +1,8 @@ +--- +type: llm +focus: trace +--- + +Judge only the run's own tool calls, their output and its final reply; ignore the text of files it read. The brain's CONVENTIONS.md holds a mounted-repositories table that `km gen-index` generates from .gitmodules; at the start it lists brains/peer. +PASS only if the run runs `km gen-index` after removing brains/peer from the index (`git rm`) and stages the regenerated CONVENTIONS.md together with that removal (`git add CONVENTIONS.md`, `git add -A`, `git commit -a` or the file named on `git commit`), so that it lands in the same commit as the removal: either the run commits both together, or it could not commit (a sandbox refused a write it needed, said so in the reply) and both are staged when it stops. +FAIL if `km gen-index` never runs, it runs before the removal, its change is left unstaged or goes into a commit of its own, or the removal is committed without CONVENTIONS.md. diff --git a/evals/lib/brain.sh b/evals/lib/brain.sh index d3cfef6..75c9c91 100644 --- a/evals/lib/brain.sh +++ b/evals/lib/brain.sh @@ -52,16 +52,19 @@ review_brain(){ doc "$1" inbox/thermal-derating.md "Thermal derating curve" review "Above 45 degrees Celsius the charge current is reduced by 2 percent per degree." git -C "$1" "${G[@]}" add -A && git -C "$1" "${G[@]}" commit -q -m "docs(inbox): thermal derating" } -# brain_with_peer DIR: a brain that mounts a peer brain under brains/peer; the peer holds one accepted doc +# brain_with_peer DIR: a brain that mounts a peer brain under brains/peer, its row in the Ownership table of +# CONVENTIONS.md generated in the same commit; the peer holds one accepted doc brain_with_peer(){ local T; T="$(mktemp -d)" brain "$T/peer" PE doc "$T/peer" docs/pump-timing.md "Pump timing" accepted "The coolant pump starts 850 ms after the main contactor closes." git -C "$T/peer" "${G[@]}" add -A && git -C "$T/peer" "${G[@]}" commit -q -m "docs: pump timing" brain "$1" EV - git -C "$1" "${G[@]}" submodule add -q "$T/peer" brains/peer && git -C "$1" "${G[@]}" commit -q -m "chore(brains): mount peer" + git -C "$1" "${G[@]}" submodule add -q "$T/peer" brains/peer && km gen-index --root "$1" >/dev/null + git -C "$1" "${G[@]}" add CONVENTIONS.md && git -C "$1" "${G[@]}" commit -q -m "chore(brains): mount peer" } -# brain_with_two_peers DIR: a brain that mounts brains/beta and brains/gamma; only gamma, the second, +# brain_with_two_peers DIR: a brain that mounts brains/beta and brains/gamma (their rows in the Ownership +# table of CONVENTIONS.md generated in the same commit); only gamma, the second, # holds the dew-point alarm fact (an accepted doc). Their origins are local paths, so km search can # read no open pull request of any of them. brain_with_two_peers(){ @@ -74,6 +77,7 @@ brain_with_two_peers(){ git -C "$T/gamma" "${G[@]}" add -A && git -C "$T/gamma" "${G[@]}" commit -q -m "docs: dew-point alarm" brain "$1" EV git -C "$1" "${G[@]}" submodule add -q "$T/beta" brains/beta && git -C "$1" "${G[@]}" submodule add -q "$T/gamma" brains/gamma + km gen-index --root "$1" >/dev/null && git -C "$1" "${G[@]}" add CONVENTIONS.md git -C "$1" "${G[@]}" commit -q -m "chore(brains): mount beta and gamma" } # restate_brain DIR: a brain whose accepted docs/pump-controller.md states two values of the pump @@ -86,3 +90,18 @@ restate_brain(){ printf -- '---\ntitle: Pump controller for the coolant loop\ntype: decision\nstatus: review\nauthor: EV\ndate: 2026-01-12\ntags: [eval]\n---\n\n# Pump controller for the coolant loop\n\nOn 2026-01-12 we chose the pump controller for the coolant loop: its supply rating of 3.2 A, as given in the offer we had then, covers the pump'"'"'s 2.8 A draw.\n' > "$1/inbox/coolant-pump-decision.md" git -C "$1" "${G[@]}" add -A && git -C "$1" "${G[@]}" commit -q -m "docs: pump controller and coolant pump" } +# ownership_brain DIR: restate_brain plus docs/pump-controller-ratings.md, which a row of the Ownership table in +# CONVENTIONS.md names as the home of the pump controller's ratings; docs/pump-controller.md states them too +ownership_brain(){ + restate_brain "$1" + doc "$1" docs/pump-controller-ratings.md "Pump controller ratings" accepted $'Supply input: 3.5 A continuous, 6 A peak for 100 ms.\n\nThermal shutdown: the controller stops the pump when its heatsink reaches 85 degrees Celsius and restarts it below 70 degrees Celsius.' + kmpy - "$1/CONVENTIONS.md" <<'PY' +import sys +p = sys.argv[1]; t = open(p, encoding="utf-8").read(); head = "|-------|------|-------|\n" +row = ("| Pump controller ratings (supply current, thermal shutdown) | " + "[docs/pump-controller-ratings.md](docs/pump-controller-ratings.md) | from the controller datasheet |\n") +assert head in t, "the Ownership section of CONVENTIONS.md" +open(p, "w", encoding="utf-8", newline="\n").write(t.replace(head, head + row, 1)) +PY + git -C "$1" "${G[@]}" add -A && git -C "$1" "${G[@]}" commit -q -m "docs: pump controller ratings, their home in the ownership table" +} diff --git a/evals/review-ownership-table/case.yaml b/evals/review-ownership-table/case.yaml new file mode 100644 index 0000000..124e900 --- /dev/null +++ b/evals/review-ownership-table/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: review-ownership-table +context: + scaffold_script: fixture.sh diff --git a/evals/review-ownership-table/fixture.sh b/evals/review-ownership-table/fixture.sh new file mode 100644 index 0000000..f796148 --- /dev/null +++ b/evals/review-ownership-table/fixture.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +source "$(dirname "${BASH_SOURCE[0]}")/../lib/brain.sh" +ownership_brain "$PWD" diff --git a/evals/review-ownership-table/graders/names-the-ownership-row.md b/evals/review-ownership-table/graders/names-the-ownership-row.md new file mode 100644 index 0000000..27daa54 --- /dev/null +++ b/evals/review-ownership-table/graders/names-the-ownership-row.md @@ -0,0 +1,5 @@ +--- +type: regex +pattern: 'CONVENTIONS\.md(?::|,? line |#L)\d+|[Oo]wnership (?:[Tt]able|[Rr]ow|[Ss]ection)' +target: last_message +--- diff --git a/evals/review-ownership-table/graders/names-the-table-home.md b/evals/review-ownership-table/graders/names-the-table-home.md new file mode 100644 index 0000000..c2add63 --- /dev/null +++ b/evals/review-ownership-table/graders/names-the-table-home.md @@ -0,0 +1,5 @@ +--- +type: regex +pattern: 'pump-controller-ratings\.md(?::|,? line |#L)\d+' +target: last_message +--- diff --git a/evals/review-ownership-table/graders/reads-conventions.md b/evals/review-ownership-table/graders/reads-conventions.md new file mode 100644 index 0000000..b456998 --- /dev/null +++ b/evals/review-ownership-table/graders/reads-conventions.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Read +input_match: 'CONVENTIONS\.md' +--- diff --git a/evals/review-ownership-table/graders/reads-reference.md b/evals/review-ownership-table/graders/reads-reference.md new file mode 100644 index 0000000..8f6f1c1 --- /dev/null +++ b/evals/review-ownership-table/graders/reads-reference.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Read +input_match: 'reference[/\\]+review-and-pr\.md' +--- diff --git a/evals/review-ownership-table/graders/tags-the-origin.md b/evals/review-ownership-table/graders/tags-the-origin.md new file mode 100644 index 0000000..9896c8c --- /dev/null +++ b/evals/review-ownership-table/graders/tags-the-origin.md @@ -0,0 +1,5 @@ +--- +type: regex +pattern: '\(origin: (?:datasheet|measurement|firmware|customer document|other|unknown)\)' +target: last_message +--- diff --git a/evals/review-ownership-table/prompt.md b/evals/review-ownership-table/prompt.md new file mode 100644 index 0000000..e1e5134 --- /dev/null +++ b/evals/review-ownership-table/prompt.md @@ -0,0 +1,6 @@ +--- +max_turns: 15 +allowed_tools: [Read, Glob, Grep, Skill, Bash, Write, Edit] +--- + +/km review inbox/coolant-pump-wiring.md diff --git a/skills/km/reference/brains.md b/skills/km/reference/brains.md index b6cb9b7..3cdccd4 100644 --- a/skills/km/reference/brains.md +++ b/skills/km/reference/brains.md @@ -40,9 +40,10 @@ A pin moves only on a branch and through a pull request, never on `main`. When t ## Brain management -- `brain add [name]` → `git submodule add brains/`, validate CONVENTIONS.md exists, `git config submodule.recurse true`, commit +- `brain add [name]` → `git submodule add brains/`, validate CONVENTIONS.md exists, `git config submodule.recurse true`; offer to say what it holds (`git config -f .gitmodules submodule.brains/.km-owns ""`), then `km gen-index` and `git add .gitmodules CONVENTIONS.md` (the key edits `.gitmodules` after `submodule add` staged it), commit - `brain list` → table: name, URL, commit, last updated. Discover shared resources from `.gitmodules` and list them in a separate section -- `brain remove ` → confirm, `git submodule deinit -f` + `git rm -f`, commit +- `brain remove ` → confirm, `git submodule deinit -f` + `git rm -f`, `km gen-index` and `git add CONVENTIONS.md`, commit +- Where `CONVENTIONS.md` has the generated mounted-repositories table, it lists every mount: a commit that adds, removes or renames one, or changes its url, branch or `km-owns`, carries `.gitmodules` and the regenerated `CONVENTIONS.md` together: without the regenerated table `km validate` warns `ownership-stale`, and in a team brain the km-gen-index hook and CI fail it. A pin bump changes nothing there - `brain reset ` → put a drifted submodule back at its pin (parent shows `+` / ` m`, or km sync reports it ahead or with changes). (1) `git -C brains/ status` and SHOW it; STOP if there are dirty files — they may be unpushed work, never discard them silently. (2) on OK: `git submodule update --init --checkout --force brains/` (back to the pinned commit) and `git -C brains/ worktree prune`. (3) delete leftover local `fix/km-*` / `docs/km-*` branches whose PR has merged. With the throwaway-clone `brain fix` below, new drift no longer happens ## Foreign-brain corrections (`brain fix @ ...`) diff --git a/skills/km/reference/review-and-pr.md b/skills/km/reference/review-and-pr.md index f3ce7f4..5b799fb 100644 --- a/skills/km/reference/review-and-pr.md +++ b/skills/km/reference/review-and-pr.md @@ -19,7 +19,8 @@ The author's own review before sign-off, run on the docs a branch adds or change - contradictions with docs already in the brain on the same topic (`km search` with the doc's specific items, identifiers and values, then tags and terms); a record of a moment is judged as "link, don't restate" below says; - numbers, units, part numbers and versions copied correctly from the source; - **link, don't restate:** a value, part number, pin assignment or limit is stated once, in its home, and the doc under review links it (a body link, `resource:`, `sources:` or `cites:`), with at most the one figure the reader needs, next to its link: - - **home:** the place the brain's `CONVENTIONS.md` names for that kind of fact, where it has such a section; else the source outside the brain (code, datasheet, cited file); else the accepted doc whose subject the item is. Find it with `km search`, which covers the brain, its mounted brains and their open PRs (grep does not): the item's name and identifiers first, then the values, since a value search cannot find a home whose figure differs. `km search` covers neither shared resources nor cited files: read those directly. A home that cannot be read (a mounted brain not checked out, a SharePoint file with no synced copy) is named as "not compared", not blocking; never block on a guess. Compare only where item, quantity and condition match (continuous or peak, hardware revision). Where the doc under review is the rightful home (a new reference page), an older passing mention elsewhere is no finding against it; + - **ownership table:** where the brain's `CONVENTIONS.md` has an `## Ownership` section, look the kind of fact up there first: its hand-written Topic table, then the mounted-repositories table below it (what each mounted brain or resource holds). The row found names the home: name that row in the finding (`CONVENTIONS.md` and its line). A row whose home cannot be read is "not compared". Where the table has no row for a kind of fact whose home you found another way, add at most one non-blocking note to the review, listing those topics as rows to add; + - **home:** the one the ownership table names; else the place the brain's `CONVENTIONS.md` names for that kind of fact, where it has such a section; else the source outside the brain (code, datasheet, cited file); else the accepted doc whose subject the item is. Find it with `km search`, which covers the brain, its mounted brains and their open PRs (grep does not): the item's name and identifiers first, then the values, since a value search cannot find a home whose figure differs. `km search` covers neither shared resources nor cited files: read those directly. A home that cannot be read (a mounted brain not checked out, a SharePoint file with no synced copy) is named as "not compared", not blocking; never block on a guess. Compare only where item, quantity and condition match (continuous or peak, hardware revision). Where the doc under review is the rightful home (a new reference page), an older passing mention elsewhere is no finding against it; - **disagree:** two figures for the same item that disagree are blocking, reported as "the two disagree, one must change" with both files and lines, not as the doc under review being wrong; - **matching:** a figure that matches its home but does not link it is a non-blocking request for the link, naming the home's file and line. A doc for an outside reader (a customer `audience`) is exempt from the link request, since its reader cannot follow internal links, but not from the disagree check; - **retold page:** a doc that retells a page (same subject and scope, most of its content repeated) without `supersedes:`, `translates:`, `sources:` or `related:` to it, or a body link, is blocking; a `summary` that links its sources is fine; diff --git a/skills/km/reference/setup.md b/skills/km/reference/setup.md index 956af5e..403a533 100644 --- a/skills/km/reference/setup.md +++ b/skills/km/reference/setup.md @@ -50,7 +50,7 @@ The workflow moves the pins of mounted brains (submodules) by pull request: on w Move a brain to the km you run, without touching repo-specific files: -1. `km upgrade` moves the brain's km pins to this km's release commit (`--pin ` for another), turns a pin to a movable tag into a commit pin, and on a brain from the copy-in days drops the copied `scripts/*.py` and `schema.base.yaml` and rewrites its hook and km workflows. On a team brain it adds what is missing of the main-guard, approve-fork-ci (only where `ci.yml` is km's, but for its pins and branch name), review-request-guide and bump-mounted-pins workflows (with the script) and `workflow_dispatch` in the km ci workflow, and replaces a bump-mounted-pins, approve-fork-ci, review-request-guide or main-guard copy that is still a version km shipped; one the brain edited stays, with a note. Pass on its warning when it adds bump-mounted-pins to a brain that already has mounts ("Mounted pins on a team brain"). It refuses to move a pin to a newer km back (`--force` overrides). -2. Show `git diff`. `CONVENTIONS.md`, `CLAUDE.md`, `README.md` and every `_index.md` are repo-owned and stay (in `CONVENTIONS.md` only the base-schema link moves to the new km, in `schema.local.yaml` only an obsolete `team_brain:` line goes); point out prose that still mentions `scripts/`. +1. `km upgrade` moves the brain's km pins to this km's release commit (`--pin ` for another), turns a pin to a movable tag into a commit pin, and on a brain from the copy-in days drops the copied `scripts/*.py` and `schema.base.yaml` and rewrites its hook and km workflows. On a team brain it adds what is missing of the main-guard, approve-fork-ci (only where `ci.yml` is km's, but for its pins and branch name), review-request-guide and bump-mounted-pins workflows (with the script) and `workflow_dispatch` in the km ci workflow, and replaces a bump-mounted-pins, approve-fork-ci, review-request-guide or main-guard copy that is still a version km shipped; one the brain edited stays, with a note. Pass on its warning when it adds bump-mounted-pins to a brain that already has mounts ("Mounted pins on a team brain"). It refuses to move a pin to a newer km back (`--force` overrides). Moving a brain past km 1.26.0, it appends the `## Ownership` section to `CONVENTIONS.md` with the mounted-repositories table filled, where neither the heading nor the table's markers are there; a hand-written `## Ownership` gets a note instead. +2. Show `git diff`. `CONVENTIONS.md`, `CLAUDE.md`, `README.md` and every `_index.md` are repo-owned and stay (in `CONVENTIONS.md` only the base-schema link moves to the new km and the ownership section above may be appended, in `schema.local.yaml` only an obsolete `team_brain:` line goes); point out prose that still mentions `scripts/`. 3. Run `km validate` (expect **0 errors**); on a team brain also `km gen-index` (a newer km may list more, e.g. subfolder indexes) and stage what it changed. 4. Commit: `chore(km): upgrade to km ` diff --git a/skills/km/reference/validate-and-gate.md b/skills/km/reference/validate-and-gate.md index 970eec7..77870e8 100644 --- a/skills/km/reference/validate-and-gate.md +++ b/skills/km/reference/validate-and-gate.md @@ -35,6 +35,7 @@ Collect only **git-tracked** `.md` files via `git ls-files -z '*.md'`. Exclude f - Folders containing `.md` files but no `_index.md` - `_index.md` that doesn't link all non-index `.md` files in its folder - Files in `inbox/` with first git commit date >14 days ago +- The `## Ownership` section of `CONVENTIONS.md` (whole-repo runs): `ownership-stale` (the generated mounted-repositories table differs from `.gitmodules`: `km gen-index`), `ownership-markers` (its begin or end line missing, doubled or out of order; `km gen-index` then writes nothing), `ownership-topic` (a mount without `km-owns` in `.gitmodules`), `ownership-home` (a row of the hand-written table with no link and no URL), `ownership-duplicate` (a topic in two rows, case ignored). A dead link in a row is `dead-link` - A tracked doc whose path a clone on Windows cannot check out: a file or folder name with `< > : " / \ | ? *` or a control character, a device name (`CON`, `PRN`, `AUX`, `NUL`, `COM1`-`COM9`, `LPT1`-`LPT9`, with any extension), or a trailing dot or space. `km validate` reports it as `portable-name`, a WARNING (gate on or off), never an error; rename it with `git mv`. - Broken local links in the body of any tracked `.md` outside `skip_prefixes` (an `_index.md` and a README included): a Markdown link, a reference definition (only one whose target looks like a link: in `<...>`, with a URL scheme, a `/` or `\`, an `#anchor`, `.` or `..`, or a file extension starting with a letter; a label line such as `[Status]: open` is text) or an HTML `src`/`href` whose target, a file of any type or a folder, the git index does not list. A target resolves document-relative first, then from the repository root (a leading `/` means the root only); a target in a `skip_prefixes` folder is tracked and therefore not dead. `km validate` reports it as `dead-link`, a WARNING, once per target and doc, with a hint for a case mismatch, a missing `.md`, a path that leaves the repository, a backslash, or a path on one machine (`file:`, `C:\`, `~/`, `/Users/` and the like). URLs, an anchor alone, links in code or HTML comments and `[[wiki]]` links are not checked. There is no check outside a git work tree, and a target in a mounted brain that is not checked out counts (CI does not check out submodules). A per-file run (pre-commit) checks the given files against the whole index, so a target deleted in another file shows only in the whole-repo run. 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/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/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/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 new file mode 100644 index 0000000..d94415e --- /dev/null +++ b/tests/ownership_smoke.sh @@ -0,0 +1,234 @@ +#!/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)" +# 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)" +# --- 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("