diff --git a/.claude/skills/refresh-trails/SKILL.md b/.claude/skills/refresh-trails/SKILL.md new file mode 100644 index 0000000..e8ba4b7 --- /dev/null +++ b/.claude/skills/refresh-trails/SKILL.md @@ -0,0 +1,55 @@ +--- +name: refresh-trails +description: Run the monthly refresh of the trail dataset. Checks every record against the pages it cites, re-checks the trails that were left out, searches for missing trails and routes, updates tracks and emblems, has everything reviewed independently, and applies what the owner accepts. Use when the owner asks to refresh or update all trails, or to verify the database against current published data. Pass `light` for the cheap version (verify and re-check only). +argument-hint: "[light]" +disable-model-invocation: true +--- + +# Refresh the trail dataset + +This is the runbook for the orchestrating agent. Once a month the whole dataset is checked against what its holders and authors publish now, and the web is searched for trails that should be in it. The work is done by many workers at once, each given one slice. They never edit the repository. They stage proposals in a directory that git ignores, a reviewer who did not write them checks them against the pages, the owner rules on what is borderline, and one worker applies what was accepted. You plan, dispatch, check and decide when to stop for the owner. + +Read these first, once: `rules.md` (what every worker must follow), `proposal-format.md` (the staged format that `tools/refresh.py` collects and applies), and the briefs in `briefs/` as you reach each phase. The mechanical steps are in `tools/refresh.py`; `python3 tools/refresh.py --help` lists them. + +## How to dispatch + +A worker starts with nothing from this session. Give it one line and let the brief carry the rest: "Read `.claude/skills/refresh-trails/briefs/.md` and follow it. Staging directory: ``. Worker name: ``. Slice: ``." Use the most capable model you have for searching, verifying and reviewing: those fail quietly when done fast, because a cheap worker opens one page, sees nothing wrong and gives up. Cheap fast models are fine for `slices`, `links` and `collect`, which need no model at all, and for the mechanical parts of `apply`. Review is done by a different model family from the one that wrote what it reviews. Send independent work out in one message so it runs at the same time; two workers that would both use Overpass do not run at the same time. Do not poll: wait for each to finish. + +## Modes + +- **Full**: phases 0 to 9. Worth it about quarterly, after a big addition, when many records were written in a hurry, or when a visitor or a holder reports that something is stale. +- **Light** (`/refresh-trails light`): phases 0, 1 and 2, with `slices --since 30` so that only records not verified in the last 30 days are taken. It finds drift and dead links cheaply. Run it in the months between full runs. Its changes still go through phases 6, 7 and 8. + +## Phases + +**0. Preflight.** Run `python3 tools/refresh.py preflight`. It checks that the tree is clean (work on a branch, never directly on `main`), runs the validator and the tools tests, and creates `refresh//`. Then `python3 tools/refresh.py links` fetches every address in every record and in `left-out.toml` once, politely, into `links.csv` (it takes a while: it waits between requests to one site; start it in the background). *Check yourself:* preflight ends `preflight OK`; `links.csv` exists; you know which hosts refused. Refusals are never worked around, and they go to the owner in phase 7 if a record rests on a refusing site. + +**1. Verify every record.** `python3 tools/refresh.py slices --n 6` (about 35 records each; `--since DAYS` keeps only records whose `hike.checked` is older than that). Dispatch one `briefs/verify-records.md` worker per `trails-NN` slice. Give each worker the rows of `links.csv` for its ids by telling it where the file is. *Check yourself:* `python3 tools/refresh.py collect` shows no problems; every id has a report row; ids marked `not-reached` go to a new worker; the warnings that a `verified` record's cited pages were not all opened are sent back to a worker, because a verification that skipped the cited pages is not one. + +**2. Re-check what was left out.** The same `slices` run made `left-out-NN` slices. Dispatch `briefs/recheck-left-out.md` workers, at the same time as phase 1. Entries with reason `waiting` are the ones most likely to have changed: they are checked against their `waiting_for`. *Check yourself:* every entry has a row; read each `candidate` the workers recommend, because it may become a record. + +**3. Search for missing trails and routes.** Split the continent into regions of five to eight states or provinces (for example US West, Mountain West, Central, Northeast, Southeast, Canada West, Canada East) and dispatch a `briefs/find-missing-trails.md` worker for each. Dispatch one or two `briefs/find-routes.md` workers for authors' routes. Run it at the same time as phases 1 and 2. *Check yourself:* for every region that reports `not-found`, or finds fewer than two candidates, send a second worker of a different model family, the same brief, with the first worker's list of places searched, and tell it that a quiet first pass is a reason to look harder. A search that finds nothing is common and is not proof. Every `not-found` row must say where it looked; `collect` refuses one that does not. + +**4. Tracks.** Gather the ids of official trails with no track (`source.line_file = ""` and no `kind = "route"`) and of records whose track source may have changed (the source's `discovery` field says how to tell). Dispatch one `briefs/tracks.md` worker for the work that uses Overpass, one request at a time, and a second for holder data and licence reading that uses no Overpass. These are existing records. A new record from phase 3 has no track yet and cannot be given one before it exists: after phase 8 has applied it, run this phase again for the new ids, review that, and apply once more. *Check yourself:* a track more than 15% off the published length has a `length_gap_note` that explains it with facts; a route's author's terms allowing it are quoted before any route track is staged; the licence on each is what the page says. + +**5. Emblems.** `grep -l 'status = "logo-not-found"' */trail.toml` lists records whose emblem was not found. Write their ids into slice files in the staging directory (about 10 to 20 each) and dispatch `briefs/emblems.md` workers. *Check yourself:* open three staged emblem files yourself or have the reviewer do it: one emblem, whole, not an organisation's lockup. + +**6. Independent review.** When the workers of phases 1 to 5 are done, run `collect`. Every `change`, `declined`, `new-record`, `left-out-add` and `left-out-remove` proposal goes to a `briefs/review.md` reviewer, with about one in ten of the `verified` records as a check on the verifiers. Split the list across reviewers by worker or by region, so none reviews its own area's writer. This is not optional: in the first run a reviewer found must-fix defects in about one new record in three. Workers whose proposals are rejected revise them and the reviewer reads the revision. Run `collect` again after each round. *Check yourself:* every proposal has a decision; the `must fix` list is empty or fixed; read the rejections yourself, because a reviewer that rejects everything is as useless as one that accepts everything. + +**7. Stop: the owner decides.** Put one list in front of the owner, with your recommendation on each item: borderline candidates (trails near the floor, partly built, networks, routes with thin author pages), the trails 40 to 50 miles that are well known, every `hold`, every record a verifier found closed, merged or no longer walkable (workers never propose removing one), every `declined` request and every change a holder might dispute, the changes that touch a length, an end or a track licence, and any track that is more than 15% off without a settled explanation. Decisions about what belongs are the owner's: the inclusion rule is in `README.md`, and the reasons already given are in `left-out.toml`. The owner's answers go into `/owner.csv`. An approved candidate is written up by a `briefs/find-missing-trails.md` worker, reviewed as in phase 6, and joins the list. Nothing is applied before this stop. + +**8. Apply and rebuild.** Dispatch one `briefs/apply.md` worker, and only one. It applies the accepted proposals by targeted edits with their history entries, runs `tools/elevation.py` for new tracks, adds the `SOURCES.md` rows, rebuilds the shared files with `tools/build_index.py`, and runs the validator, `tools/check_history.py`, `python3 -m unittest discover tools/tests` and the web tests, and it writes the `CHANGELOG.md` entry. *Check yourself:* `git diff --stat` matches the accepted list; read the hunks yourself for anything that touches a length, an end, a licence or a track; read the changelog entry and fix its wording; rerun the validator and the history check with your own hands; no `trail.toml` outside the accepted ids changed. A change to a fact with no history entry, or a ship with no changelog entry in the same commit, is not done. + +**9. Build, check, ship, follow up.** Build the site (`python3 web/build.py --out _site`) and read the built HTML for three trails that changed, one new trail, the "Considered and left out" page and the home page counts. Then commit on the branch, with the changelog entry in the same commit. Pushing to `main` starts the deploy, which publishes to the public. Ship only if the owner has said, in this run or as a standing instruction, that a finished refresh may go out; otherwise show them the branch and stop. Afterwards, go through the open issues on the project's tracker (https://github.com/swaits/longhikes/issues): answer those the refresh settled, warmly and without making the person do more work. A holder's or author's own statement in an issue is enough to rely on, quoted with its address. + +## Rules for you, with the reasons + +- Staging is `refresh//` at the top of the checkout, listed in `.gitignore`. It is inside the checkout so that a fresh session finds it by a relative path and every command defaults to the newest one, and ignored so nothing staged can reach a commit. A path outside the checkout would have to be told to every worker each time. +- Workers do not edit the repository, because many at once on one checkout is how work gets lost. Only phase 8 writes records. +- Every brief that may start a process says never to stop one by name or pattern. A worker once killed the owner's browser that way. +- A site that refuses automated reads is never worked around. The refusal is recorded and another source used. Requests use a plain User-Agent and carry no personal or project details. +- Overpass takes one request at a time from one worker, or it stops answering for everyone. +- The holder's or author's current page wins any disagreement, and a request that loses is recorded as `declined` in the history. +- A fact that changes needs a `[[history]]` entry and every ship needs a `CHANGELOG.md` entry in the same commit, so that the reason for a change can be found later. +- Workers propose; the owner decides what belongs. +- The staged format and every command are in `proposal-format.md` and `tools/refresh.py`. When a worker's output does not collect cleanly, send it back, rather than fixing it by hand. diff --git a/.claude/skills/refresh-trails/briefs/apply.md b/.claude/skills/refresh-trails/briefs/apply.md new file mode 100644 index 0000000..6db789c --- /dev/null +++ b/.claude/skills/refresh-trails/briefs/apply.md @@ -0,0 +1,29 @@ +# Apply the accepted proposals and rebuild + +Read `../rules.md` and `../proposal-format.md` first. You do this task yourself and start no subagents. This is the one brief that changes the repository: it is the only worker allowed to, and only one runs at a time. + +You receive a staging directory ``, on a branch the orchestrator has checked out, and a clean tree. You do not commit, push or switch branches. + +## What this is for + +Everything staged so far was written without touching the repository, so that many workers could run at once. This step brings the accepted proposals in, in one place, one by one, and leaves the repository in a state the orchestrator can commit: records changed, shared files rebuilt, every check green. Done means all accepted proposals are applied or reported as refused with the reason, the validator, all test suites and the history check pass, and `CHANGELOG.md` has an entry for the work. + +## Steps + +1. `python3 tools/refresh.py collect`, then read `/summary.md`. The count of proposals with status `accepted` must match what the orchestrator told you. Anything with the status `proposed`, `held`, `rejected` or `invalid` is not applied. +2. `python3 tools/refresh.py apply --dry-run`. Read what would be refused. A refusal means the record no longer says what the proposal expects (someone changed it, or two proposals touch the same field), and it is reported, not worked around. Never edit a record by hand to make a proposal fit. +3. `python3 tools/refresh.py apply`. It changes the named lines and adds the history entries. +4. For each new track (a proposal with a track file), `python3 tools/elevation.py `: it writes `elevation.json` from the track. For a replaced track, `--force`. +5. Add the rows named in `sources_md` fields to `SOURCES.md`, by hand, in the existing form and place. Where a record was removed or a track dropped, take the row's counts and lists with it. +6. `python3 tools/build_index.py` rebuilds `trails.csv`, `index.geojson` and the counts in `README.md`. Do not edit those files by hand. +7. `python3 tools/validate.py` must end `OK trails`. `python3 tools/check_history.py` must end `OK history`. A failure that names a record you changed is yours: find the cause, and if it is a proposal that was wrong, say so in your report and revert that record from git (`git checkout -- `, then apply the rest without it, by `--only`). A failure in a record you did not touch is reported. +8. Run all the test suites: `python3 -m unittest discover tools/tests` and `python3 -m unittest discover -s web/tests`. The web tests hold counts of trails, tracks and emblems; if one fails only because a count moved with the change, update that count. Any other failure is a real failure: stop and report it. +9. Write the entry at the top of `CHANGELOG.md`, in the voice of the entries already there (read the top two): a dated heading with a short title, then plain bullets saying what changed for contributors and, where a visitor can see it, what a visitor will see. State the counts that changed (trails, tracks, emblems). Say what was checked and left unchanged only where it matters. The orchestrator reads and edits it. + +## The hard part + +Order and exactness. A proposal applied against a record that changed in the meantime is the way a good record gets damaged, which is why `apply` refuses it; do not defeat that check. Rebuild the shared files after the last apply, not before. And the history check compares your work with the base branch, so run it with the base the orchestrator names (`--base REV`), not by guess. + +## Report + +Reply with under 200 words: the counts (applied, refused with reasons, already applied), the ids with a new or replaced track, the validator and test tails, and anything you did that the proposals did not say. diff --git a/.claude/skills/refresh-trails/briefs/emblems.md b/.claude/skills/refresh-trails/briefs/emblems.md new file mode 100644 index 0000000..fb3c40e --- /dev/null +++ b/.claude/skills/refresh-trails/briefs/emblems.md @@ -0,0 +1,53 @@ +# Find the trail's own emblem + +Read `../rules.md`, `../proposal-format.md` and `../records.md` first. You do this task yourself and start no subagents. + +You receive a staging directory ``, a worker name (for example `emblems-1`) and a slice file `/slices/.txt` of trail ids, one per line, normally records whose `shield.status` is `logo-not-found`. Stage your work in `/staged//`. + +## What this is for + +The site shows each trail's own emblem beside its name, and most long trails have a single crest-style marker. A record that says "emblem not found" is a gap the site shows to the reader. Earlier "not found" and "no emblem" verdicts were often reached without a real search, so do not trust them: search again. Done means that for every id there is either a clean emblem file that came from an allowed source, or a note that says exactly which pages were looked at and what marks were seen. + +## What counts as the emblem + +The trail's own crest, shield, badge, roundel, blaze-shaped marker or trail-sign symbol, alone. For a US National Scenic Trail, the official rounded-triangle trail marker; for a club trail, its blaze badge or roundel; for an author's route, the emblem the author uses for it, if there is one. + +Not wanted: the holding organisation's lockup (an emblem with the organisation's name set beside it as type), a wordmark alone, a banner, a photo, a map, or an agency's logo standing in for the trail (the Forest Service shield, the National Park Service arrowhead, the Parks Canada beaver, a state parks logo). If the emblem inside an organisation's lockup is the trail's crest, crop it out. If the only mark is the organisation's and it does not stand for the trail, the trail has no emblem of its own. Text that is part of the emblem (the trail's name around a roundel) is fine; a tagline or organisation name outside it is cropped off. + +## Where it may come from, in order + +1. The holder's or author's own site: page header, footer, about page, media or press kit, brand page, map PDFs. Look at the page source for the largest version: an SVG first, then the biggest PNG (check `srcset`, the media library path, linked "logo" or "brand" files). Photos of a trail marker on a tree are not acceptable; artwork files are. A favicon or touch icon is a last resort, and only if it is the emblem at 180 px or more. +2. The managing agency's official page for the trail. +3. Wikimedia Commons, only when the file's page identifies it as the trail's official emblem and gives its origin, and it matches what the holder's own site shows. Record the Commons page as the source. + +Never: social media, shops, apps (AllTrails, FarOut), fan redraws, stock sites, image-search thumbnails, or anything you cannot trace to the holder. + +## Making the file + +One file per trail, `shield.svg` (an SVG of the emblem alone, or one that can be reduced to it by deleting extra elements) or `shield.png`. Crop tight to the emblem with a small even margin. Trimming a uniform border is allowed; nothing else: no redrawing, recolouring, upscaling, sharpening, AI editing or background removal. Keep transparency if the source has it. Never enlarge; take the largest original and leave it at its size (reduce only if it is over 1024 px on the long side). ImageMagick (`magick`) is installed. After making the file, open it and look at it: one emblem, whole, legible, and not blank on a white page or on a dark page. If it is white-on-transparent or black-on-transparent, say so in the note. Aim for at least 256 px on the long side; smaller only when nothing larger exists at an allowed source, and the note says so. + +## For each id + +Read the record (name, holder or author, official site, the `[shield]` table and its note) and look at any existing file. Then decide: + +- `kept`: the existing file is already the emblem alone at 256 px or more. Stage nothing but a report row. +- `replaced`: you found the emblem alone, or a larger or cleaner version. +- `cropped`: the best art is a composite and you cropped the emblem out. +- `new`: the trail had no file and you found its emblem. +- `none-exists`: you looked at the holder's or author's site and the agency page, and the trail has no emblem of its own. Say what marks you did see and why they do not count. +- `logo-not-found`, reported as `not-found`: an emblem seems to exist (seen on a sign in a photo, mentioned in text) but no usable artwork is at an allowed source. Say where it was seen. +- `refused`: every allowed source refused automated reads. + +Staged, for every outcome except `kept`: the untouched download as `original.` in `/staged///`, the logo file for `replaced`, `cropped` and `new`, and a `change` proposal with edits for `shield.status` (`use-real-logo`, `no-logo-exists` or `logo-not-found`), `shield.logo_source` (the exact address the artwork was downloaded from), `shield.contact`, `shield.logo_file`, `shield.logo_owner` and `shield.note`, a `[[proposal.file]]` for the logo (with `old_sha256` when replacing an existing one), and `[proposal.history]`. The note says, in short plain sentences, what the emblem is, which page shows it in use, what was done to the file ("Cropped from the association's header logo; the wordmark beside the crest was cut off."), any terms the holder states about its logo, and for a trail with no file, every address you looked at. + +## The hard part + +Deciding what counts as the trail's own emblem when the holder shows only its organisation's mark, and finding the largest original rather than the page's thumbnail. When you are torn, say so in the report and describe both candidates; the owner decides. Do not take the quick answer from the first page: look at the page source and the media library for a larger file, and at the holder's map and brochure PDFs for the emblem in artwork form. + +## Time + +About 10 minutes per id; at most 90 minutes for a slice. Stop at the budget plus a third and mark the rest `not-reached`. + +## Report + +`report.csv` with a row per id: outcome, the file, its width and height in `remark`, the source address. Reply with under 120 words: staging path, counts by outcome, and any trail where you were torn. diff --git a/.claude/skills/refresh-trails/briefs/find-missing-trails.md b/.claude/skills/refresh-trails/briefs/find-missing-trails.md new file mode 100644 index 0000000..885baff --- /dev/null +++ b/.claude/skills/refresh-trails/briefs/find-missing-trails.md @@ -0,0 +1,40 @@ +# Search for trails the dataset is missing, by region + +Read `../rules.md`, `../proposal-format.md` and `../records.md` first. You do this task yourself and start no subagents. + +You receive a staging directory ``, a worker name (for example `region-us-west`) and a region: a group of states or provinces. Stage your work in `/staged//`. Your task may also say it is a second pass and give you the list of places the first pass searched. + +## What this is for + +The dataset should hold every trail that meets its inclusion rule. It was built from other sites' lists, and every earlier search by list missed trails that a plain look at a state agency's pages found. One such search for a whole country once reported nothing missing, and a second worker with a different approach found seven. Done means that for your region you have searched widely and deeply, every candidate is confirmed on its holder's page, and every place you looked is listed, including the places that gave nothing. + +## The inclusion rule, short + +A named long-distance walking trail or route in the US or Canada, 50 miles (80 km) or longer as one continuous walk. Loops count. A trail that is partly built counts if its holder publishes it as one trail and it can be walked through, with road links allowed. A trail has a holder (agency, association or club) that names it and states its length. A route was worked out by an author, and counts only if the author has a page or book of their own that describes it as a route with a stated length; one person's trip report is not a route. The full rule is in `README.md`. Left out on purpose: gravel rail trails and canal towpaths, paved greenways, trails mainly for horses, bikes, motor vehicles or paddling, mainly driving historic trails, networks that are not one continuous trail, trails closed for good, proposed trails with nothing on the ground. Everything already decided against is in `left-out.toml` with the reason: do not propose it again unless the page now shows that the deciding fact has changed. Trails between 40 and 50 miles are not candidates. + +## How to search + +- Go wide first. Use many varied words: "long trail", "long-distance trail", "thru-hike", "backpacking trail", "backpacking route", "multi-day", "100-mile", "end to end", "traverse", "high route", "loop", "wilderness trail", "footpath", "state trail", and in French "sentier de longue randonnée" where it applies. Combine each with every state or province, mountain range, national forest, national park, large state park or forest, river, lake shore, coast and desert in your region. +- Then go deep on the places that list trails officially: each state or provincial agency's trail pages and trail lists, the National Recreation Trails database, trail associations and hiking clubs, guidebook publishers' catalogues, regional hiking magazines, and articles on the best long trails of a place. +- Whole-country lists were already swept and are leads only for a single trail: Wikipedia's long-distance trail lists, ALDHA-West, The Trek, thru-hiking.com, Backpacking Routes, HikeBikeTravel and LongTrailsWiki. +- For every name, check the dataset before spending time: search `trails.csv`, the `name` and any other-name fields of `*/trail.toml`, and `left-out.toml`. Many trails are in under another spelling or inside a longer trail. +- A candidate counts only after you read its holder's or author's own page and saw the length stated there (or, failing that, a government page). Apps, forums, Reddit and wikis are leads, never evidence. + +## The hard part + +Searching is where cheap, quick attempts fail: a few queries, a page or two per state, and "nothing found". Do the dull part: walk each state's agency trail list to the end, not just the first search page. When a state seems empty, check it from a second direction (the national forests in it, its long-distance hiking club, its National Recreation Trails) before you say so. If this is a second pass, the places listed as already searched are not a reason to skip a state; use different questions and different sources, and treat a quiet first pass as a reason to look harder, not as evidence. + +## What to stage + +- For a candidate that clearly meets the rule: a `new-record` proposal, with the complete record staged as `staged///trail.toml` written as `../records.md` says. A new official trail gets no track now: write the honest absent reason ("No track has been added yet" in substance). Do not fetch any track and do not call Overpass: a later serial pass does that. If you can find the trail's OpenStreetMap route relation number through the openstreetmap.org search page or Nominatim (one light request per trail), put it in the record's `[osm]` note and in your report. +- For a candidate that is doubtful (length near the floor, partly built, a network or a loop of linked trails, a route with a thin author page, an owner who might dispute it): a `candidate` proposal with `borderline = true`, the length as stated, the page, and a recommendation (`add`, `owner` or `decline`) with the specific doubt in `summary`. +- Trails of 40 to 50 miles that are well known: a `candidate` proposal with `recommendation = "decline"` and `reason = "below-floor"`, so the owner can see them. +- `report.csv` with one row per state or province in your region: `found` (with the ids), or `not-found`, with `pages` listing every place you looked for that state: the agency pages, the lists, the queries by kind. "Not found" without where you looked is not accepted. + +## Time + +About 60 minutes for a region of 5 to 8 states or provinces. Stop at 80. + +## Report + +Reply with under 150 words: staging path, number of new records and candidates, the two or three strongest, and the states or provinces where you found nothing and how sure you are. diff --git a/.claude/skills/refresh-trails/briefs/find-routes.md b/.claude/skills/refresh-trails/briefs/find-routes.md new file mode 100644 index 0000000..0b5c7e2 --- /dev/null +++ b/.claude/skills/refresh-trails/briefs/find-routes.md @@ -0,0 +1,35 @@ +# Search for routes published by their authors + +Read `../rules.md`, `../proposal-format.md` and `../records.md` first. You do this task yourself and start no subagents. + +You receive a staging directory ``, a worker name (for example `routes-1`) and optionally a part of the country. Stage your work in `/staged//`. + +## What this is for + +Some of the best long walks are not designated trails. A hiker or a guidebook author worked a high route, a traverse or a loop of linked trails out and published it with a stated length. The dataset lists these as routes when the author has a page or book of their own that describes the route with a length. They are missed by agency searches, because no agency holds them, and they are easy to over-count, because a trip report looks like a route. Done means you have searched the places routes are published, and each route you found is confirmed on its author's page. + +## The rule, short + +A route counts when its author has their own page or a published book that describes it as a route and states its length, and the length is 50 miles (80 km) or more as one continuous walk (loops count). A trip report of one person's walk is not a route. The author's name is the author the page names. Check `trails.csv`, the `name` fields of the records (`kind = "route"` ones especially) and `left-out.toml` first: the dataset already holds many routes and has decided against others, and the same route often goes under two names or sits inside a longer one. + +## How to search + +Search for the kinds of things authors publish: "high route", "traverse", "alternate route", "thru-hiking route", "loop", "off-trail route", "link-up", "cross-country route", with each mountain range, wilderness area, national park, desert, island, coast and territory in the US and Canada (or in your part). Look at guidebook publishers (the regional mountaineering and outdoor presses), the authors' own sites, hiker association pages that link to routes, and regional hiking magazines. A guidebook's own publisher page counts as the author's page for a book route. Routes already in the dataset have their author, year and `[[guide]]` in the record: read two to see how they are described. + +## The hard part + +Telling a route from a trip report, and telling the author's page from someone's summary of it. Read the author's own page, find the stated length and the sentence that calls it a route, and note whether the track is free, sold, withheld or unsettled (the record needs `[route]` and `line_policy`). Never include a track for a route. If the author's page states terms that allow passing a track on, quote them; otherwise there is no track, and the record says so. A route whose length is only given in someone else's article is a lead, not a candidate. + +As with other searches, a quiet result needs a second look from another direction before you call a region empty, and "not found" must say where you looked. + +## What to stage + +The same as `find-missing-trails.md`: a `new-record` proposal with a staged `trail.toml` for each route that clearly meets the rule, `candidate` proposals for doubtful ones and for well-known routes under 50 miles, and a `report.csv`. Its rows are the mountain ranges, regions or sources you covered, each `found` (with ids) or `not-found` with the places looked. For a new route record, `kind = "route"`, `[route]` with the author and `line_policy`, at least one `[[guide]]`, and no track. + +## Time + +About 60 minutes. Stop at 80. + +## Report + +Reply with under 150 words: staging path, number of new records and candidates, the strongest, and where you found nothing. diff --git a/.claude/skills/refresh-trails/briefs/recheck-left-out.md b/.claude/skills/refresh-trails/briefs/recheck-left-out.md new file mode 100644 index 0000000..1dc5cfd --- /dev/null +++ b/.claude/skills/refresh-trails/briefs/recheck-left-out.md @@ -0,0 +1,37 @@ +# Re-check the trails that were left out + +Read `../rules.md`, `../proposal-format.md` and `../records.md` first. You do this task yourself and start no subagents. + +You receive a staging directory ``, a worker name (for example `left-out-01`) and a slice file `/slices/.txt` listing ids of entries in `left-out.toml`, one per line. Stage your work in `/staged//`. + +## What this is for + +`left-out.toml` lists trails that were looked at and left out, each with the specific fact that decided it. It is shown to the public as "Considered and left out", so that a trail is not suggested and argued over again from nothing. A decision can go stale: a trail that was too short gains miles, a proposed trail gets built, a National Scenic Trail is designated, a closed trail reopens, a page the decision rests on moves. Done means that for every entry in your slice you know whether the deciding fact still holds on the page, and every entry that has changed has a proposal. + +## What to do for each entry + +1. Read the entry (`left-out.toml`, found by `id`), and `docs/schema.md`, section "left-out.toml", for the reasons. Note `reason`, `note`, `source_url`, `decided`, and for `waiting` entries `waiting_for`. +2. Open `source_url`. Then open the holder's or author's current page for the trail, and one government page where there is one. Check that the deciding fact is still what the entry says it is: the length against the 50 mile floor, the surface, the owner or purpose, the state of construction, whether it can be walked through. +3. For an entry whose `reason` is `waiting`, `waiting_for` is the one condition that would change the decision. Look specifically for whether that has happened: a designation made, a length settled, a gap closed, a route published. Say what you found and where, even when nothing has changed. +4. A trail the dataset now lists (look in `trails.csv` by id and name) must not stay in this file. Report it. +5. Decide: + - Still holds: stage a `verified` proposal for the entry (`target = "left-out"`) with the pages opened. Nothing is applied for it; it records that the check happened. + - The page says something different but the decision stands: a `change` proposal with `target = "left-out"` and edits to `note`, `length_mi` and `length_km` (they must agree), `source_url`. `decided` is left alone because the decision has not changed. + - The fact that decided it no longer holds, or the `waiting_for` has happened: a `candidate` proposal with your recommendation (`add` if it now clearly meets the inclusion rule, otherwise `owner`) and the sentence that changed. Do not write the record and do not remove the entry. That is the owner's decision. + - The entry's page is gone and no other page shows the fact: `could-not-check`. + +## The hard part + +For `waiting` entries a quick look at the trail's home page is not enough. "Waiting for designation" is answered by the agency's page, not by the advocacy group's. "Waiting for a settled length" is answered by the holder's current length, which may be in a map, a PDF or a news release. Read the whole page and say where on it the fact sits. Treat a hopeful announcement (a bill introduced, a section planned, a ribbon cutting scheduled) as not yet meeting the condition, and quote it so the owner can judge. + +## What to stage + +Per entry, `/staged///proposal.toml`. For the slice, `/staged//report.csv` with a row for every id: `verified`, `changed`, `could-not-check`, `refused` or `not-reached`, with the pages opened. Entries you recommend to the owner have outcome `changed` and a `candidate` proposal. + +## Time + +About 5 minutes per entry; at most 90 minutes for a slice. Stop at the budget plus a third and mark the rest `not-reached`. + +## Report + +Reply with under 120 words: staging path, counts, and every entry where the deciding fact has changed. diff --git a/.claude/skills/refresh-trails/briefs/review.md b/.claude/skills/refresh-trails/briefs/review.md new file mode 100644 index 0000000..5502d3a --- /dev/null +++ b/.claude/skills/refresh-trails/briefs/review.md @@ -0,0 +1,44 @@ +# Review proposals and new records against their pages + +Read `../rules.md`, `../proposal-format.md` and `../records.md` first. You do this task yourself and start no subagents. + +You receive a staging directory ``, a reviewer name (for example `review-1`) and a list of proposal ids (`pid`) from `/summary.md`, or the name of a worker whose proposals you review. Your work is read-only: change nothing in the repository or in anyone's staged files. You write two files, `/review/.md` and `/review/.csv`. + +## What this is for + +The workers who wrote the proposals meant well and are sometimes wrong. A review of freshly written records by a second reader, opening the cited pages, once found seven must-fix defects in twenty-three records: facts that the cited page did not support, a wrong start point, allowed uses left out. A record goes to the public only after someone who did not write it has opened its pages. You are that reader, and a different one from the writer, ideally from a different model family. Done means every proposal you were given has a decision and the reasons are written down. + +## What to do + +For each proposal, read it in `summary.md` and in its `proposal.toml`, and for a new record read the whole staged `trail.toml`. Do not read the writer's conclusions first and then look for support. Open the pages and read them. For each edit or fact: + +1. Open the page named. Find the quote. Is it there, word for word, and does it say what the proposal says it does? +2. Is the page the right source? The holder's or author's own page beats everything else. If another page disagrees, which one is current? +3. Does the record, after the change, say anything the pages do not? Read every sentence of a new record's `summary`, `designation`, `length_note`, `caution` and `[route]` text for claims such as "the Forest Service describes it as" or "the association maintains it" that no cited page makes. The summary is our wording but not our invention. +4. The facts that hikers act on: the start and end (is the length the one that belongs to those ends?), allowed uses (every use the page lists is in the record), permits and fees, season, closures that affect walking through. +5. Is a cited address a page that opens and says what the record claims (not a redirect to a general page that never mentions the trail)? +6. Is the length source right: which figure belongs to which definition (built or planned, with or without side trails)? +7. Words: "track" and not "line", "author" and not "creator" in text, miles first, plain sentences, no dashes as punctuation, no private person's name, no marketing words. +8. History: is `[proposal.history]` present for every changed fact, with a role in `asked_by`, a basis and an address that does open? Was an earlier `declined` entry about the same field passed over? +9. Is the proposal narrower or wider than its summary says? Did the writer quietly drop a part of the task? +10. For a track: does the licence in `source.licence` match the terms on the page, is a route's track (`kind = "route"`) included without the author's stated terms? + +## The hard part + +Agreeing is easy and wrong. When a quote is there, check that the sentence is about this trail and this fact (a nearby trail, an older edition, a segment and not the whole). When the page cannot be opened, say it is unchecked; do not accept on trust and do not reject for it. Where you cannot tell which of two pages is right, say so and let the owner rule. + +## What to write + +`/review/.csv`, header `pid,digest,decision,note`, one row for every proposal you were given. `digest` is the one in `summary.md`. `decision` is `accept` (every fact supported, nothing to fix), `reject` (not supported, or wrong, with the fix described in the report), or `hold` (needs the owner: the holder might dispute it, the sources conflict, or it is a matter of what belongs). A proposal with a small fix is a `reject` and the fix is written out, so it comes back as a new proposal and is read again. `note` is the reason, with the page and the sentence. + +`/review/.md`, compact, no preamble, in this order: + +1. `## Must fix`: numbered; each names the trail id and the fields, what is wrong, the page and the sentence that shows it, and the exact replacement text. +2. `## Should fix`: the same for lesser defects. +3. `## Answers`: for each question you were asked, the evidence and the conclusion. +4. `## Checked and sound`: one line per proposal, saying what you confirmed (for example: "ends, 54.7 mi, uses, archive copy read"). +5. `## Could not check`: what you could not open or read, and why. + +## Report + +Reply with under 120 words: the two file paths, the number of accepts, rejects and holds, and the most serious defect. diff --git a/.claude/skills/refresh-trails/briefs/tracks.md b/.claude/skills/refresh-trails/briefs/tracks.md new file mode 100644 index 0000000..368e2a7 --- /dev/null +++ b/.claude/skills/refresh-trails/briefs/tracks.md @@ -0,0 +1,43 @@ +# Tracks: trails that have none, and tracks whose source has changed + +Read `../rules.md`, `../proposal-format.md` and `../records.md` first. You do this task yourself and start no subagents. + +You receive a staging directory ``, a worker name (for example `tracks-1`) and a list of trail ids in two groups: A, records that have no track, and B, records whose track source may have changed. Stage your work in `/staged//`. If your task has you using Overpass, you are the only worker that does. + +## What this is for + +A track is what lets a hiker see where a trail goes. A record without one says why (`source.line_absent_reason`), and often the reason has passed: a relation has since been added to OpenStreetMap, or the holder has published open data. A track that came from a source goes stale when the source is edited. Done means that for each id you either have a staged track with the figures that go with it, or an honest statement of why none can be included. + +## Group A: records with no track + +1. Read the record: `source.line_absent_reason`, `[osm]`, `kind`. A route worked out by an author (`kind = "route"`) never gets a track unless the author's own page states terms that allow passing it on; quote them if they exist, and otherwise move on. +2. Look for a track that may lawfully be included, in this order: the holder's own open data under a stated open licence (or a US federal government work), the holder's written permission (the holder's statement in the public issue tracker counts, quoted with its address), then an OpenStreetMap route relation (ODbL). Read the data source's terms. If they forbid redistribution or commercial use, do not use it, and say so. +3. For an OpenStreetMap relation, first run `python3 tools/osm_track.py --id --dry` and read the figures: the number of ways, the measured length, the parts. Compare with the published `length_km`. If it is within 15% and the ways are the trail (no other trail's name among them), run it again without `--dry`, with `--out /staged/`, so the files land beside your proposal. A way that carries another trail's name is excluded with `--exclude-name`, and the exclusion is said in the record. +4. Beyond 15%, find out why before staging anything: sum the length by way name, look at which parts are missing or extra, and write `source.length_gap_note` with facts. If the track is mostly another trail, or mostly unbuilt, do not stage it and say why. + +## Group B: tracks whose source has changed + +`source.discovery` says how to tell whether the source has a newer release. For an OpenStreetMap relation, read the relation's version and timestamp (`rel(ID); out meta;`) and compare with `release.txt` and `[osm]`. If it has not changed, stage a `verified` proposal. If it has, fetch it with `osm_track.py --force --out /staged/`, compare the new figures with the old (`verification.measured_km`, `parts`), and look at what moved: a track that has doubled or lost a third is more often an editing accident than a change in the trail. Stage a change only where the new track is the better description of the same trail. For a track from a holder, check that the holder's page and its terms still say what the record says. + +## What to stage + +For each track you propose, a `change` proposal for the record (or a `new-record` if it is staged with a new record) that has: + +- `[[proposal.file]]` entries for `line.geojson`, `alternates.geojson` where the tool wrote it, and `release.txt`, with `source_url` and, for a file that already exists, `old_sha256` (`sha256sum /line.geojson`). Do not stage `elevation.json`: it is computed from the track in the apply phase. +- edits for the fields the track changes: `source.status`, `source.licence`, `source.licence_text`, `source.attribution`, `source.osm_only`, `source.line_source`, `source.line_file`, `source.source_checked`, `source.redistributable`, `source.length_gap_note` where needed, `source.line_absent_reason` removed where a track now exists, `osm.relation` and `osm.note`, and the `[verification]` figures (`verified`, `date`, `measured_km`, `difference_percent`, `parts`, `note`) as the tool printed them. For a field the tool computes, `page` is the relation or data page and `quote` is the line of tool output. +- `[proposal.history]`, because a track change is a change to `source.line_file`. +- `sources_md`: the row `SOURCES.md` needs. + +Records are copied for form from existing ones with the same kind of track (`../records.md`). Report with `report.csv`: for each id `new` (a track is staged), `replaced` (a changed track), `verified`, `none-exists` (no lawful track is available, with the pages looked at), `refused`, `could-not-check` or `not-reached`. + +## The hard part + +Overpass overloads easily. `osm_track.py` tries several endpoints by itself, one request at a time. Never run two fetches at once, and do not start another tool that calls Overpass while one runs. If all endpoints are down, say so and stop the track work. Do not build a track by hand and do not trace one from an app or a map. A track you cannot source is a record with an honest absent reason, which is a perfectly good record. + +## Time + +About 10 minutes per id. Stop at the budget plus a third. + +## Report + +Reply with under 150 words: staging path, counts by outcome, any track beyond 15% of the published length and what explains it, and whether Overpass was down. diff --git a/.claude/skills/refresh-trails/briefs/verify-records.md b/.claude/skills/refresh-trails/briefs/verify-records.md new file mode 100644 index 0000000..1180ec5 --- /dev/null +++ b/.claude/skills/refresh-trails/briefs/verify-records.md @@ -0,0 +1,49 @@ +# Verify records against the pages they cite + +Read `../rules.md`, `../proposal-format.md` and `../records.md` first. You do this task yourself and start no subagents. + +You receive a staging directory ``, a worker name (the slice name, for example `trails-03`) and a slice file `/slices/.txt` listing trail ids, one per line. Stage your work in `/staged//`. + +## What this is for + +Trail pages change: a holder renames a trail, a section closes, a length is revised, a permit rule changes, a page moves. A record that was right when it was written drifts out of date, and a hiker who relies on it is the one who pays. Once a month every record is checked again against the pages it cites and against the holder's current site, so that what the dataset says is what the holder says today. Done means that for every id in your slice the record is either marked verified, with the pages you opened, or has proposals that say exactly what changed and where that is written. + +## What to do for each id + +1. Read `/trail.toml` whole, including its `[[history]]`. Note every earlier `declined` entry and every entry asked for by someone other than the dataset's own check: those are decisions you must not quietly reverse. +2. Open every page the record cites: each `[[hike.source]]` url, `hike.official_url`, `source.publisher_url`, `source.url` and `source.permission_url` where present, the `[[guide]]` pages, and the pages named in `short_name_url` and `length_note`. Then open the holder's or author's current official site for the trail, even if the record does not cite its current address, and follow a moved page to where it went. `links.csv` in the staging directory says which of the record's addresses are dead, redirected or refused; use it to find where to start, and still read the page itself. +3. Check each of these against what the pages say now: + - the name, and the holder or author + - the length, and what it counts (built or planned, with or without side trails) + - both ends (and for a loop the usual trailhead), by place name + - allowed uses: hiking, bicycles, horses, dogs, motor vehicles + - permits, reservations and fees for walking the whole trail + - the season and the usual time to walk it + - closures or reroutes that affect walking through (a loss of access the holder has reported in writing may be recorded; day to day conditions may not) + - the official links: do the record's addresses still reach the right page + - the track's source: is the source page still there, does it still state its terms, has the relation or layer been replaced? You do not fetch tracks here. Record only whether the source and its terms still say what the record says. + - `short_name`, if present: is it still the holder's own or established use? +4. Decide: + - Nothing changed: stage a `verified` proposal naming every page you opened. + - Something changed: stage a `change` proposal with one `[[proposal.edit]]` per field, each with the `page` and the `quote` that support it, a `[proposal.history]`, and also a `verified` proposal for what you checked and found unchanged. + - Pages disagree with each other, or with the record, and you cannot tell which is right: do not edit. Write a `could-not-check` proposal that says what disagrees and which pages say what. + - A request recorded in the history is contradicted by the holder's page: a `declined` proposal, not a change. + - The pages say the trail no longer exists, has been merged into another, or can no longer be walked through: never propose removing it. Stage a `could-not-check` proposal with the pages and sentences, because whether a trail still belongs is the owner's decision. + +## The hard part + +A cheap read finds nothing wrong. One page per trail, a glance at the length, and a verdict of "unchanged" is how drift survives. The checks above are meant to be done on pages you actually read to the end: the length is often in a paragraph, a table or a PDF, and the permit rule is often on a separate page from the trail page. When a page offers more than one figure, say which one you used and why in `quote`. Equally, never "fix" a record from a third-party page when the holder's own page disagrees. A hiking site, a map or an app that gives a different length is a lead. The holder's page decides. If the holder's page is missing or refuses automated reads, that is `could-not-check` for that fact, not a reason to take the third-party figure. + +The second trap is changing wording that is merely different. The record's wording is ours. Propose an edit only where a fact is different, not where the page words the same fact differently. + +## What to stage + +For each id: `/staged///proposal.toml` in the format of `../proposal-format.md`. For your slice: `/staged//report.csv` with a row for every id: `verified`, `changed`, `declined`, `could-not-check`, `refused` or `not-reached`, and in `pages` every address you opened. Do not touch the record. + +## Time + +About 6 to 8 minutes per record on average, and no more than an hour and a half for a slice of about 35. Stop at the budget plus a third and mark what is left `not-reached`. + +## Report + +Reply with under 150 words: your staging path, the count of each outcome, the three most important changes you propose, and any site that refused. diff --git a/.claude/skills/refresh-trails/proposal-format.md b/.claude/skills/refresh-trails/proposal-format.md new file mode 100644 index 0000000..5ab2dde --- /dev/null +++ b/.claude/skills/refresh-trails/proposal-format.md @@ -0,0 +1,126 @@ +# The staged proposal format + +Workers never edit the repository. They stage what they found as files in the staging directory, `tools/refresh.py collect` gathers and checks them, a reviewer and the owner decide, and `tools/refresh.py apply` makes the accepted changes. This file is the one place the format is defined; the briefs point here, and `collect` and `apply` enforce it. + +## Layout + +``` +refresh// the staging directory, ignored by git + slices/.txt ids for each slice, one per line (written by `slices`) + links.csv written by `links` + staged// one directory per worker; is the slice or region name + report.csv one row for every id (or region) the worker was given + /proposal.toml every proposal about that id + / staged files: a new record's trail.toml, tracks, an emblem + review/.csv a reviewer's decisions + owner.csv the owner's rulings + collected.toml, summary.md written by `collect` + apply-log.csv written by `apply` +``` + +`` is the slice name (`trails-03`, `left-out-01`) or, for work that is not sliced, a short name the orchestrator gives (`region-us-west`, `tracks-1`, `emblems-2`). Two workers never share a directory, so two workers can propose the same new trail without overwriting each other. `collect` reports the duplicate. + +## report.csv + +Header: `id,outcome,pages,remark`. One row for every id or region the worker was given, so that nothing is silently skipped. + +| Column | Content | +| --- | --- | +| `id` | The trail id, the left-out id, or the region searched. | +| `outcome` | One word from the list below. | +| `pages` | The addresses opened, or for a search the places looked, separated by semicolons. Required for `verified`, `not-found`, `none-exists`, `refused` and `could-not-check`. | +| `remark` | One plain sentence. Required for `could-not-check`, `refused` and `not-found`. | + +Outcomes: `verified` (every check passed; nothing to change), `changed` (at least one proposal; the pages are those opened), `declined` (a request was recorded as declined), `could-not-check` (say what and why), `refused` (every allowed source refused automated reads), `not-reached` (out of time), `found` and `not-found` (searches), `none-exists`, `kept`, `replaced`, `cropped`, `new` (emblems and tracks), `accepted` and `rejected` (review). + +A `verified` row needs a `verified` proposal as well, and the pages listed should include every page the record cites. `collect` warns for each cited page that was not listed. + +## proposal.toml + +A file holds one or more `[[proposal]]` tables. Strings and arrays stay on one line, because `apply` replaces whole lines. Every proposal has these fields: + +| Field | Meaning | +| --- | --- | +| `kind` | One of the kinds below. | +| `id` | The trail id (the directory name), or the left-out id. For a candidate, the id it would have. It must equal the directory `` the file sits in. | +| `target` | `"left-out"` to change an entry of `left-out.toml`. Omitted for a record. | +| `date` | `YYYY-MM-DD`, the day the pages were read. | +| `summary` | One plain sentence saying what is proposed. | + +### `verified` + +The record was checked against its pages and still says what they say. Fields: `pages` (array of addresses opened). `apply` sets `hike.checked` to `date` (for a record with no `[hike]`, `source.source_checked`). These are not facts, so no history entry is added. A trail with `change` proposals also gets a `verified` proposal: it says that everything not named in a change was checked and stands. + +```toml +[[proposal]] +kind = "verified" +id = "long-trail" +date = "2026-12-03" +summary = "Name, length, ends, uses, permit and season checked against the club's pages." +pages = ["https://www.greenmountainclub.org/the-long-trail/", "https://www.greenmountainclub.org/hike/"] +``` + +### `change` + +Changes fields of a record, or of a left-out entry (`target = "left-out"`). It holds any of `[[proposal.edit]]`, `[[proposal.append]]` and `[[proposal.file]]`, and a `[proposal.history]`. + +```toml +[[proposal]] +kind = "change" +id = "long-trail" +date = "2026-12-03" +summary = "The permit sentence changed." + +[[proposal.edit]] +field = "hike.permit" +old = "No permit is needed." +new = "A free permit is needed for groups of ten or more." +page = "https://www.greenmountainclub.org/hike/" +quote = "Groups of ten or more need a free permit." + +[proposal.history] +change = "The permit sentence now says groups of ten or more need a free permit." +basis = "The club's page says groups of ten or more need a free permit." +basis_url = "https://www.greenmountainclub.org/hike/" +asked_by = "the dataset's own check" +``` + +**`[[proposal.edit]]`** changes one field. `field` is named as `docs/schema.md` names it: `length_km`, `source.licence`, `hike.permit`. For an entry of an array of tables, add its position, counting from 0: `guide[0].price`, `hike.source[1].facts`. `old` is the current value, copied from the record as it stands when you read it; `apply` refuses if the record no longer has exactly that value. Leave `old` out to add a field that is absent. Leave `new` out to remove a field. `page` and `quote` are the page and the sentence on it that support the change. They are required for every edit. A number is copied as the page writes it, and `quote` is copied exactly. + +**`[[proposal.append]]`** adds an entry to `hike.source`, `guide` or `link`: `table`, `page`, `quote`, and a `[proposal.append.entry]` table holding the new entry's fields. It is added after the last entry of that table. An entry whose `url` is already there is refused. + +**`[[proposal.file]]`** puts a file into the record's directory: `to` (one of `line.geojson`, `alternates.geojson`, `line-.geojson`, `release.txt`, `elevation.json`, `shield.svg`, `shield.png`), `from` (a path inside the proposal's own directory), `source_url` (where the file came from), and `old_sha256` (required when `to` already exists; it must match, so a file that changed meanwhile is never overwritten). `remove = true` in place of `from` deletes `to`. Track files carry no `old` and `new`; the fields that describe them (`source.status`, `source.licence`, `source.line_file`, `verification.*`) are ordinary edits in the same proposal. + +**`[proposal.history]`** is the `[[history]]` entry `apply` appends: `change`, `basis`, `basis_url`, `asked_by`, and optionally `fields`. `date` is the day `apply` runs, and `outcome` is `applied`. Without `fields`, they are worked out from the edits (`hike.source[1].facts` becomes `hike.source.facts`; a track file becomes `source.line_file`; an emblem file `shield.logo_file`). The entry is required whenever a fact changes; `python3 tools/check_history.py --facts` lists what counts as a fact. `asked_by` is a role, never a person's name: `the dataset's own check`, `a hiker`, `the trail association's president`, `the route's author`. + +### `declined` + +A request, usually from the issue tracker, that the holder's or author's own current page contradicts. Nothing in the record changes except that a history entry with the outcome `declined` is added. It has no edits. `[proposal.history]` must name `fields`, and `basis` says which page wins and why. + +### `new-record` + +A new trail. The complete record is staged as `staged///trail.toml`, with its track files and emblem beside it. Its own first `[[history]]` entry has `fields = ["record"]`. Fields: `basis_url` (the page that shows the trail meets the inclusion rule). A new record is one the worker recommends adding; a doubtful one is a `candidate` instead. `sources_md` is one line for the `SOURCES.md` row that must change: publisher, source page, licence, and `track` or `record only`. `apply` copies the directory (without `proposal.toml`) into the repository and refuses if the id exists. If the trail is in `left-out.toml`, a `left-out-remove` proposal must accompany it. + +### `left-out-add`, `left-out-remove` + +Adds an entry to `left-out.toml` (a `[proposal.entry]` table with the fields in `docs/schema.md`; `apply` puts it in name order), or removes the entry for `id` (`why` says why; `basis_url` is the page). A change to an existing entry is a `change` with `target = "left-out"`; its edits name plain fields (`note`, `decided`, `reason`) without a table. + +### `candidate` + +A trail that might belong, for the owner to decide. It is never applied. Fields: `name`, `country`, `regions`, `length_mi`, `source_url` (the holder's or author's page where the length was read), `recommendation` (`add`, `owner` or `decline`), `reason` (the left-out reason when the recommendation is `decline`), `borderline` (true when it needs the owner), and `summary` (which says what is doubtful). + +### `could-not-check` + +Something that could not be checked: `what` and `why`, and `tried` (the pages opened). It is never applied and is listed in the summary, so the owner sees what was not verified. + +### `sources_md` + +Any proposal may carry `sources_md`, a one-line note about `SOURCES.md` (that file is written by hand): the id, the publisher, the page, the licence, and `track` or `record only`. `collect` lists them. + +## Decisions + +A reviewer writes `review/.csv`, and the owner `owner.csv`, with the header `pid,digest,decision,note`. `pid` and `digest` are the ones in `summary.md` for that proposal. `decision` is `accept`, `reject` or `hold`. An `accept` counts only if its `digest` matches the proposal as it is now, so a proposal that changed after review has to be reviewed again. The owner's row wins; otherwise a `reject` or `hold` from any reviewer blocks, and an `accept` from at least one reviewer accepts. `note` gives the reason: for a `reject`, the page and the sentence that do not support the proposal. + +## collected.toml and apply + +`collect` writes every proposal, with its `pid` (`::`), `digest`, `status` (`proposed`, `accepted`, `rejected`, `held`, `invalid`, or `info` for candidates and unchecked items) and the problems it found. Never edit it; record decisions in the CSV files and collect again. `apply` applies the `accepted` proposals only, by changing the named line, adding a line at the end of the field's table, or adding a block. It never re-serialises a record, so hand formatting and comments stay. It refuses a proposal whose `old` value no longer matches, whose staged file changed after `collect`, or whose target file changed (`sha256`), and it says so; `apply --dry-run` shows what would happen. Running it twice is safe: a proposal already applied is reported as such. diff --git a/.claude/skills/refresh-trails/records.md b/.claude/skills/refresh-trails/records.md new file mode 100644 index 0000000..7cc3a34 --- /dev/null +++ b/.claude/skills/refresh-trails/records.md @@ -0,0 +1,33 @@ +# Writing and changing records + +Read this when a brief has you propose a change to a record, or write a new one. `docs/schema.md` is the schema: read it whole before writing, because the validator is strict and unknown fields are errors. `CONTRIBUTING.md` explains the tracks and the history. + +## Copy an existing record of the same kind + +Open two or three records that match what you are writing, and copy their field names, wording patterns and the order of tables. At the time of writing, `tonto-trail` is an official trail with a track from OpenStreetMap, `black-canyon` an official trail with its holder's track, and `hayduke-trail` and `across-utah-route` are routes with no track. If any of them is gone, pick another of the same kind. + +## Rules that decide what a record may say + +- Every fact comes from a page you read, named in a source entry with the facts it supports (`[[hike.source]]` for the hiker facts). The holder's or author's page is first choice, then a government page, then an established hiking reference named as the publisher. Leave a field out rather than guess it. +- Where sources disagree on a length, the record gives the holder's or author's figure, and `length_note` says what the others give. `length_km` is the published length, not a measurement of the track. +- A route (`kind = "route"`) worked out by an author gets no track unless the author's own page states terms that allow passing it on. An official trail's track may come from its holder under a stated open licence, from a US federal government work, from the holder's written permission (`stated-permission`, see `CONTRIBUTING.md`), or from OpenStreetMap (ODbL) with `tools/osm_track.py`. Read a data source's terms before using it. If they forbid redistribution, do not use it, and say so in `source.line_absent_reason`. +- A track that differs from the published length by more than 15% needs `source.length_gap_note` that explains the difference with facts: which parts are missing or extra. Summing the length by way name usually shows where it sits. +- `short_name` only with prior art: the holder's or author's own use, or established use among hikers, with the page named in `short_name_url`. Never invent one. +- `start_lonlat` and `end_lonlat` for a trail with no track only from a source that gives or pins the place (a government place-name record, the land manager's trailhead page, the author's page), to three decimals. If you cannot source a point, leave it out. +- Allowed uses (hiking, bicycles, horses, dogs), permits, fees and seasons are facts hikers rely on. Where a page lists uses, the record must not leave one out. +- Words, as in `rules.md`: "track", never "line"; "author"; miles first; short plain sentences; no dashes as punctuation. + +## History + +Every changed fact needs a `[proposal.history]` (see `proposal-format.md`), and a new record has its own first `[[history]]` entry. Before you propose a change to a field, look at the record's `[[history]]`: an earlier `declined` entry about the same field, or one asked for by the holder, is a decision you must not quietly reverse. The holder's or author's current page wins; a request that loses is proposed as `declined`. + +## Shared files + +Do not edit `README.md`, `trails.csv`, `index.geojson`, `SOURCES.md`, anything under `web/`, `tools/` or `docs/`. The orchestrator rebuilds the shared files after the proposals are applied. Where `SOURCES.md` needs a row, put it in `sources_md` on the proposal. + +## Tools + +- `python3 tools/osm_track.py --id --dry` prints the figures for an OpenStreetMap route relation and writes nothing. Without `--dry` it writes `line.geojson`, `alternates.geojson` and `release.txt` into `//`. Use `--out /staged/` so they land beside your `proposal.toml`; the directory `/staged///` must exist first. Read `--help` and the header of the file. +- `python3 tools/gpx_track.py` does the same for a GPX file that a holder or hiker has sent. +- `python3 tools/elevation.py` writes `elevation.json` from a record's track inside the repository, so it runs in the apply phase and not in a worker's staging directory. +- `python3 tools/validate.py` checks the repository as it is, so it cannot check your staged work. To test a new record, copy it into a scratch copy of the repository (a plain `cp -r` into the temporary directory) and run the validator there. Errors that name your id are yours. Stale counts in shared files are not. diff --git a/.claude/skills/refresh-trails/rules.md b/.claude/skills/refresh-trails/rules.md new file mode 100644 index 0000000..e978de2 --- /dev/null +++ b/.claude/skills/refresh-trails/rules.md @@ -0,0 +1,49 @@ +# Rules for every worker + +You are a worker on the monthly refresh of this dataset. Do the task yourself and start no subagents. The orchestrator gives you a brief, a staging directory and a slice or region. Read this file and `proposal-format.md` first, then the brief. + +## What the work is for + +The dataset is a public list of long-distance hiking trails in the United States and Canada, one directory per trail with a `trail.toml`, and the site built from it (longhikes.org). Hikers read it critically and trail holders read it too. A record is worth having only if each fact in it can be checked on a page, so the whole refresh comes down to opening pages and writing down exactly what they say. + +## Where you may write + +Do not change anything in the repository, and do not commit, push or switch branches. Many workers run at the same time on one checkout, and edits to shared files collide. Read the repository freely. Everything you produce goes under `/staged//`, in the layout in `proposal-format.md`. The orchestrator names `` (a directory such as `refresh/2026-12-01`, which git ignores) and your `` name. Never write outside it, except scratch files under the temporary directory your session gives you. + +## Evidence + +- Every fact comes from a page you opened and read, not from a search result's snippet. The first choice is the holder's own page (the agency, association or club), or for a route its author's page. A government page comes next. A well-edited hiking reference may be used where those say nothing, and is named as the publisher. +- Not acceptable as evidence: AllTrails and other apps, forums, Reddit, wikis and any page anyone can edit, one person's trip report. They are leads that tell you where to look. +- Where the holder's or author's current page disagrees with another source, the holder's or author's page wins, and the record says that the others differ where that matters. Never change a record to match a third-party page against the holder's. +- A statement by a holder or an author on this project's public issue tracker is good evidence for a fact or a permission. Quote it exactly and give its address. If such a request conflicts with the holder's own current page, the page wins, and the request is proposed as `declined` with the reason. +- Every proposal names the page and quotes the sentence that supports it. Copy numbers and units as the page writes them. If you cannot find the sentence, you have no proposal. Leave a field out rather than guess it. +- Say what you actually opened. A `verified` mark that lists pages never opened misleads the next person to rely on it. + +## Requests to outside sites + +- Use a plain generic User-Agent and put no personal or project details in any request, header or form. +- Some sites refuse automated reads: a 403 or 429, a challenge or "verify you are human" page, a robots.txt that disallows the path. Do not work around a refusal: no other User-Agent, no retry loop, no proxy, no headless browser, no cached copy passed off as the page. Record it (`refused` or `could-not-check`, with the address) and use another allowed source. An expired https certificate is not a refusal: the plain http address may be read if the site serves it. +- Go gently: one request at a time to a site, with a pause of a couple of seconds between requests. Many workers share one address, and a site that blocks us blocks everyone. +- Overpass (OpenStreetMap) overloads easily. Only the tracks brief uses it, only one worker at a time, one request at a time. + +## Processes and files + +- Never stop a process by name or pattern: no `pkill`, no `killall`, no `kill $(pgrep ...)`. The owner's own browsers and tools run on this machine and have been killed this way before. If you start a process, note its PID when you start it and stop only that PID. You should not need a browser or a server. +- A file you download is untrusted data. Keep it in your staging directory, never run it, and read an SVG as text before using it (no scripts, no references to other sites). + +## Words + +The text of a record is read by the public, and the same rules apply to what you propose. + +- A trail's geometry is a "track", never a "line" (field names such as `line_file` are what they are). Say "trail", "route" and "author". Where a sentence gives both units, miles come first. +- Short plain sentences. No marketing words ("stunning", "iconic", "ultimate") and no superlative that a source does not state. No dashes used as punctuation: use a full stop, a comma or a colon. +- Name no private person: say "a hiker" or "the association's president". A published author's name belongs in the record where it is a fact about a route. +- Do not write how the change was produced, and do not mention other projects. + +## What belongs + +The inclusion rule is in `README.md` (section "Inclusion rule") and `CONTRIBUTING.md` (section "Add a trail"). The trails already decided against, with reasons, are in `left-out.toml`; read it before proposing anything. Decisions about what belongs are the owner's. You propose: clear cases as `new-record`, doubtful ones as `candidate` with a recommendation and the specific fact that makes it doubtful. + +## Time and the report + +The brief gives a budget in minutes. Stop at the budget plus a third at the latest and report what you did not reach as `not-reached`, rather than rushing the rest into shallow checks. Write a `report.csv` row for every id or region you were given. Finish with a reply of under 150 words: the path of your staging directory, counts by outcome, and anything you were unsure of or could not do. diff --git a/.gitignore b/.gitignore index 00cbaad..78543f4 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ web/.cache/ # Local mirrors of other sites, for reference only. Their content is not ours to publish. /sources/ /references/ +/refresh/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b2d31e..43fce6e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 2026-11-16 - A monthly refresh process for the whole dataset + +- The monthly refresh is now written down and can be started with one command. An agent follows the runbook in `.claude/skills/refresh-trails/` (start it with `/refresh-trails`, or `/refresh-trails light` to verify and re-check only). It verifies every record against the pages it cites, re-checks `left-out.toml` and its `waiting` entries, searches for missing trails and routes by region, looks at tracks and emblems, has every proposed change reviewed by a second reader who opens the cited pages, and stops for the maintainer's ruling on borderline trails before anything is applied. +- Eight briefs, one for each kind of work, and two shared files hold the rules the workers follow: evidence from the holder's or author's own page, no work around a site that refuses automated reads, no stopping a process by name, one Overpass request at a time. The staged proposal format is defined once, in `proposal-format.md`. +- A new tool, `tools/refresh.py`, does the mechanical parts with the standard library only. `slices` splits the trails and the left-out entries into balanced slices (`--since DAYS` takes only records whose `hike.checked` is older). `links` fetches every address in every record once, with a plain User-Agent, a delay per site and no retry of a refusal, into a CSV. `collect` gathers what the workers staged into one summary. `apply` makes the accepted proposals by targeted edits to the named fields, adds the `[[history]]` entry, and refuses a proposal whose old value no longer matches. It never rewrites a record. +- Staged work lives in `refresh//`, which `.gitignore` lists. Workers do not edit the repository; only the apply step does. +- `CONTRIBUTING.md` has a short section on the refresh. There is no change to any trail record or to the site. + ## 2026-11-16 - Emblems for 81 trails, a history on every record, and a page of what was left out - 81 trails now show an emblem, up from 41. Each is the trail's own crest, badge or roundel, alone. Where the holder only publishes a larger logo, the emblem was cropped out of it and the lettering or organisation name beside it was cut off. Where the emblem sat on a white surround that could be removed cleanly, the surround was made transparent. 72 are PNG and 9 are SVG. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a22a2cb..2f4ef52 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -65,6 +65,14 @@ To add one: 5. If the measured length differs from `length_km` by more than 15%, explain why in `source.length_gap_note` (for example: the trail is partly unbuilt, or the published length counts side trails). 6. Add a `[[history]]` entry saying the track was refreshed and from what. Run `python3 tools/build_index.py`, then `python3 tools/validate.py` and `python3 tools/check_history.py`. +## The monthly refresh + +About once a month the maintainer runs a refresh of the whole dataset. Every record is checked again against the pages it cites and against its holder's or author's current site, the trails in `left-out.toml` are checked against the reason they were left out, and the web is searched for trails and routes that are missing. Tracks whose source has changed and emblems that were not found are looked at again. Nothing it proposes reaches a record until a second reader has opened the cited pages and the maintainer has ruled on what belongs. + +It is run by an agent, started with `/refresh-trails` in Claude Code (`/refresh-trails light` for the short version that only verifies records and left-out entries). The runbook, the briefs given to each worker, the rules they follow and the format they stage proposals in are in `.claude/skills/refresh-trails/`. The mechanical steps are in `tools/refresh.py`: `preflight`, `slices`, `links`, `collect` and `apply`. Staged work lives in `refresh//`, which git ignores, so that none of it can reach a commit. + +You do not need any of this to report something. A trail's page has a "Report a problem" link, and a request from a holder or author on the issue tracker is read in the next refresh and sooner if it is simple. + ## Style - Plain, short English. No sales talk. diff --git a/tools/refresh.py b/tools/refresh.py new file mode 100644 index 0000000..dca0ad9 --- /dev/null +++ b/tools/refresh.py @@ -0,0 +1,1582 @@ +#!/usr/bin/env python3 +"""The mechanical parts of the monthly refresh. Python 3 standard library only. + +The process is described in .claude/skills/refresh-trails/SKILL.md; the staged proposal +format is in .claude/skills/refresh-trails/proposal-format.md. This tool does the parts +that need no judgement: + + python3 tools/refresh.py preflight clean tree, validator, tests, staging directory + python3 tools/refresh.py slices --n 6 split the trails and the left-out entries into slices + python3 tools/refresh.py slices --n 6 --since 30 + python3 tools/refresh.py links fetch every address once, politely, into links.csv + python3 tools/refresh.py collect gather the staged work into collected.toml and summary.md + python3 tools/refresh.py apply --dry-run apply the accepted proposals by targeted edits + python3 tools/refresh.py apply + +Staging lives in refresh// at the top of the checkout, which .gitignore lists, so +nothing staged can reach a commit. Every command takes --dir to name another directory; by +default it uses the newest one under refresh/. + +`slices --since DAYS` takes only trails whose last check is older than DAYS days. The last +check is `hike.checked` (the date the hiker facts were read, which every record with a +[hike] table carries). A record without [hike] falls back to `source.source_checked`. + +Records are never re-serialised. `apply` finds the line of the named field and replaces that +one line, adds a line at the end of its table, or adds a block at the end of the matching +array of tables, so hand formatting and comments stay as they are. +""" +import sys + +sys.dont_write_bytecode = True + +import argparse +import concurrent.futures +import csv +import datetime +import hashlib +import json +import os +import re +import shutil +import ssl +import subprocess +import threading +import time +import tomllib +import urllib.error +import urllib.parse +import urllib.request +import urllib.robotparser + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + +import trail_history as H # noqa: E402 + +ROOT = os.path.dirname(HERE) +STAGING = "refresh" +DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") +URL_RE = re.compile(r"^https?://[^\s/]+\S*$") +ID_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$") +URL_IN_TEXT = re.compile(r"https?://[^\s\"'<>\]\[]+") +USER_AGENT = "Mozilla/5.0 (compatible; link-checker/1.0)" + +KINDS = ("verified", "change", "declined", "new-record", "left-out-add", "left-out-remove", + "candidate", "could-not-check") +APPLIED_KINDS = ("verified", "change", "declined", "new-record", "left-out-add", + "left-out-remove") +OUTCOMES = ("verified", "changed", "declined", "could-not-check", "refused", "not-reached", + "found", "not-found", "none-exists", "kept", "replaced", "cropped", "new", + "not-found-emblem", "accepted", "rejected") +NEEDS_PAGES = ("verified", "not-found", "refused", "none-exists", "could-not-check") +REPORT_COLUMNS = ("id", "outcome", "pages", "remark") +DECISIONS = ("accept", "reject", "hold") +FILE_NAME_RE = re.compile(r"^(line\.geojson|alternates\.geojson|line-[a-z0-9-]+\.geojson|" + r"release\.txt|elevation\.json|shield\.svg|shield\.png)$") +APPEND_TABLES = ("hike.source", "guide", "link") +LEFT_OUT_FILE = "left-out.toml" + + +class RefreshError(Exception): + """A message for the person running the tool; no traceback.""" + + +# ----------------------------------------------------------------------------- helpers + +def today_str(args=None): + given = getattr(args, "today", None) if args else None + return given or datetime.date.today().isoformat() + + +def load_toml(path): + with open(path, "rb") as f: + return tomllib.load(f) + + +def trail_ids(root): + return sorted(d for d in os.listdir(root) + if os.path.isfile(os.path.join(root, d, "trail.toml"))) + + +def left_out_entries(root): + path = os.path.join(root, LEFT_OUT_FILE) + if not os.path.isfile(path): + return [] + return load_toml(path).get("trail", []) + + +def staging_dir(root, given=None, create=False, today=None, fresh=False): + """The staging directory: the one named, else the newest under refresh/. With `fresh` + (preflight), a run starts a new directory for today unless one is named.""" + if fresh and not given: + given = os.path.join(STAGING, today or datetime.date.today().isoformat()) + if given: + path = given if os.path.isabs(given) else os.path.join(root, given) + else: + base = os.path.join(root, STAGING) + dated = sorted(d for d in os.listdir(base) + if DATE_RE.match(d) and os.path.isdir(os.path.join(base, d))) \ + if os.path.isdir(base) else [] + path = os.path.join(base, dated[-1]) if dated else os.path.join( + base, today or datetime.date.today().isoformat()) + if not os.path.isdir(path): + if not create: + raise RefreshError(f"no staging directory at {path}; run `python3 tools/refresh.py " + "preflight` (or `slices`) first") + os.makedirs(path) + return path + + +def walk_strings(obj, path=""): + """Yield (field path, string) for every string in a parsed record.""" + if isinstance(obj, str): + yield path, obj + elif isinstance(obj, dict): + for k, v in obj.items(): + yield from walk_strings(v, f"{path}.{k}" if path else k) + elif isinstance(obj, list): + for i, v in enumerate(obj): + yield from walk_strings(v, f"{path}[{i}]") + + +def clean_url(url): + url = url.rstrip(".,;:'\"") + while url.endswith(")") and url.count("(") < url.count(")"): + url = url[:-1].rstrip(".,;:'\"") + return url + + +def urls_in(rec): + """Every http(s) address in a parsed record or entry, with the field it sits in.""" + found = [] + for path, text in walk_strings(rec): + for m in URL_IN_TEXT.finditer(text): + url = clean_url(m.group(0)) + if URL_RE.match(url): + found.append((url, path)) + return found + + +def sha256_file(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 16), b""): + h.update(block) + return h.hexdigest() + + +# ----------------------------------------------------------------------------- toml output + +def _scalar(value): + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, (int, float)): + return repr(value) + if isinstance(value, (datetime.date, datetime.datetime)): + return value.isoformat() + if isinstance(value, str): + return json.dumps(value, ensure_ascii=False) + if isinstance(value, (list, tuple)): + return "[" + ", ".join(_scalar(v) for v in value) + "]" + raise RefreshError(f"cannot write {value!r} as a TOML value") + + +def dump_toml(obj, prefix=""): + """Write a parsed TOML document back out (used for collected.toml and appended blocks). + + Scalars and arrays of scalars first, then sub-tables, then arrays of tables. + """ + lines = [] + tables, arrays = [], [] + for key, value in obj.items(): + if isinstance(value, dict): + tables.append((key, value)) + elif isinstance(value, list) and value and all(isinstance(v, dict) for v in value): + arrays.append((key, value)) + else: + lines.append(f"{key} = {_scalar(value)}") + out = "\n".join(lines) + ("\n" if lines else "") + for key, value in tables: + name = f"{prefix}.{key}" if prefix else key + out += f"\n[{name}]\n" + dump_toml(value, name) + for key, items in arrays: + name = f"{prefix}.{key}" if prefix else key + for item in items: + out += f"\n[[{name}]]\n" + dump_toml(item, name) + return out + + +def digest(obj): + blob = json.dumps(obj, sort_keys=True, ensure_ascii=False, default=str) + return hashlib.sha256(blob.encode("utf-8")).hexdigest()[:10] + + +# ----------------------------------------------------------------------------- slices + +def effective_check(rec): + """The date a record was last checked, and which field it came from.""" + hike = rec.get("hike") or {} + if hike.get("checked"): + return str(hike["checked"]), "hike.checked" + src = rec.get("source") or {} + if src.get("source_checked"): + return str(src["source_checked"]), "source.source_checked" + return None, None + + +def balance(items, n): + """items: [(name, weight)]. Greedy: heaviest first into the lightest slice.""" + n = max(1, min(n, len(items))) if items else 0 + slices = [[] for _ in range(n)] + loads = [0] * n + for name, weight in sorted(items, key=lambda x: (-x[1], x[0])): + i = loads.index(min(loads)) + slices[i].append(name) + loads[i] += weight + return [sorted(s) for s in slices] + + +def cmd_slices(args): + root = args.root + today = today_str(args) + d = staging_dir(root, args.dir, create=True, today=today) + sdir = os.path.join(d, "slices") + os.makedirs(sdir, exist_ok=True) + for old in os.listdir(sdir): + os.remove(os.path.join(sdir, old)) + cutoff = None + if args.since is not None: + cutoff = (datetime.date.fromisoformat(today) - datetime.timedelta(days=args.since)).isoformat() + items, skipped = [], [] + for tid in trail_ids(root): + rec = load_toml(os.path.join(root, tid, "trail.toml")) + when, _field = effective_check(rec) + if cutoff and when and when >= cutoff: + skipped.append(tid) + continue + items.append((tid, 1 + len({u for u, _ in urls_in(rec)}))) + trail_slices = balance(items, args.n) + entries = left_out_entries(root) + lo_items = [(e["id"], 3 if e.get("reason") == "waiting" else 1) for e in entries if e.get("id")] + lo_slices = balance(lo_items, args.left_out_n) + manifest = [] + for kind, parts in (("trails", trail_slices), ("left-out", lo_slices)): + for i, ids in enumerate(parts, 1): + name = f"{kind}-{i:02d}" + with open(os.path.join(sdir, name + ".txt"), "w", encoding="utf-8") as f: + f.write("".join(x + "\n" for x in ids)) + manifest.append((name, kind, len(ids))) + with open(os.path.join(sdir, "manifest.csv"), "w", newline="", encoding="utf-8") as f: + w = csv.writer(f) + w.writerow(("slice", "kind", "count")) + w.writerows(manifest) + print(f"staging directory: {d}") + if cutoff: + print(f"--since {args.since}: last check is hike.checked (source.source_checked where a " + f"record has no [hike]); records checked on or after {cutoff} are left out: " + f"{len(skipped)} skipped, {len(items)} taken") + for name, kind, count in manifest: + print(f" slices/{name}.txt {count} {'trails' if kind == 'trails' else 'left-out entries'}") + return 0 + + +# ----------------------------------------------------------------------------- preflight + +def run(cmd, cwd): + return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True) + + +def cmd_preflight(args): + root = args.root + problems = [] + status = run(["git", "status", "--porcelain"], root) + if status.returncode != 0: + problems.append("git status failed: " + status.stderr.strip()) + else: + dirty = [line for line in status.stdout.splitlines() + if not line[3:].startswith(STAGING + "/")] + if dirty: + problems.append("the working tree is not clean; commit or stash first:\n " + + "\n ".join(dirty[:10])) + d = staging_dir(root, args.dir, create=True, today=today_str(args), fresh=True) + ignored = run(["git", "check-ignore", "-q", os.path.relpath(d, root) + "/x"], root) + if ignored.returncode != 0: + problems.append(f"{os.path.relpath(d, root)} is not ignored by git; add /{STAGING}/ to .gitignore") + if not args.no_validate: + v = run([sys.executable, os.path.join(root, "tools", "validate.py")], root) + last = (v.stdout.strip().splitlines() or [""])[-1] + print("validate:", last) + if v.returncode != 0: + problems.append("tools/validate.py fails") + if not args.no_tests: + t = run([sys.executable, "-m", "unittest", "discover", "tools/tests"], root) + print("tests:", (t.stderr.strip().splitlines() or [""])[-1]) + if t.returncode != 0: + problems.append("tools tests fail") + print(f"staging directory: {d}") + if problems: + for p in problems: + print("PROBLEM:", p) + return 1 + print("preflight OK") + return 0 + + +# ----------------------------------------------------------------------------- links + +REFUSAL_STATUS = (401, 403, 429, 451) +CHALLENGE_MARKERS = ("just a moment", "attention required", "verify you are human", + "enable javascript and cookies", "captcha") + + +class Prober: + """Fetches addresses one at a time per host, with a delay, and never retries a refusal.""" + + def __init__(self, delay=2.0, timeout=20.0, user_agent=USER_AGENT): + self.delay, self.timeout, self.ua = delay, timeout, user_agent + self.robots = {} + self.blocked_hosts = {} + self.last = {} + self.lock = threading.Lock() + + def _request(self, url, method, size=4096): + req = urllib.request.Request(url, method=method, headers={"User-Agent": self.ua}) + try: + with urllib.request.urlopen(req, timeout=self.timeout) as r: + body = r.read(size) if method == "GET" else b"" + return r.status, r.geturl(), dict(r.headers), body, None + except urllib.error.HTTPError as e: + body = b"" + try: + body = e.read(size) if method == "GET" else b"" + except Exception: + pass + e.close() + return e.code, e.geturl() or url, dict(e.headers or {}), body, None + except Exception as e: # network, dns, timeout, certificate + return None, url, {}, b"", e + + def _wait(self, host): + with self.lock: + last = self.last.get(host, 0.0) + gap = self.delay - (time.monotonic() - last) + if gap > 0: + time.sleep(gap) + + def _stamp(self, host): + with self.lock: + self.last[host] = time.monotonic() + + def _robots_allows(self, url, host): + parts = urllib.parse.urlsplit(url) + key = f"{parts.scheme}://{parts.netloc}" + if key not in self.robots: + self._wait(host) + status, _final, _h, rbody, err = self._request(key + "/robots.txt", "GET", 200000) + self._stamp(host) + rp = urllib.robotparser.RobotFileParser() + if err is not None or status is None or status == 404 or status >= 500: + rp = None + elif status in (401, 403, 429): + rp = "refused" + elif status == 200: + rp.parse(rbody.decode("utf-8", "replace").splitlines()) + else: + rp = None + self.robots[key] = rp + rp = self.robots[key] + if rp == "refused": + return False, "robots.txt itself was refused" + if rp is None: + return True, "" + if rp.can_fetch(self.ua, url): + return True, "" + return False, "robots.txt disallows this path" + + @staticmethod + def is_challenge(headers, body): + low = {k.lower(): str(v).lower() for k, v in headers.items()} + if "cf-mitigated" in low: + return True + text = body.decode("utf-8", "replace").lower() + return any(m in text for m in CHALLENGE_MARKERS) + + def probe(self, url): + """Returns a dict with status, final_url, refused, note, error, method.""" + host = urllib.parse.urlsplit(url).netloc.lower() + row = {"url": url, "host": host, "status": "", "final_url": "", "refused": "", + "note": "", "error": "", "method": ""} + if host in self.blocked_hosts: + row.update(refused="host", note=f"not fetched: {self.blocked_hosts[host]}") + return row + allowed, why = self._robots_allows(url, host) + if not allowed: + row.update(refused="robots", note="not fetched: " + why) + return row + for method in ("HEAD", "GET"): + self._wait(host) + status, final, headers, body, err = self._request(url, method) + self._stamp(host) + row["method"] = method + if err is not None and isinstance(getattr(err, "reason", err), ssl.SSLError) \ + and url.startswith("https://"): + http_url = "http://" + url[len("https://"):] + self._wait(host) + status, final, headers, body, err2 = self._request(http_url, "GET") + self._stamp(host) + if err2 is None: + row["note"] = "https certificate error; read over http" + err = None + row["method"] = "GET" + if err is not None: + row["error"] = f"{type(err).__name__}: {err}"[:200] + if method == "HEAD": + continue + return row + row["status"] = status + row["final_url"] = final + if status in REFUSAL_STATUS or (method == "GET" and self.is_challenge(headers, body)): + row["refused"] = "yes" + if status == 429 or self.is_challenge(headers, body): + self.blocked_hosts[host] = "the host answered 429 or a challenge page" + row["note"] = (row["note"] + " " if row["note"] else "") + \ + "refused; host skipped from here on" + return row # never retry a refusal, with another method or otherwise + if method == "HEAD" and not (200 <= status < 400): + continue # some servers answer HEAD badly: ask once with GET + return row + return row + + +def redirect_kind(url, final): + if not final or final == url: + return "" + a, b = urllib.parse.urlsplit(url), urllib.parse.urlsplit(final) + if a.netloc.lower() != b.netloc.lower(): + if a.netloc.lower().removeprefix("www.") == b.netloc.lower().removeprefix("www."): + return "www" + return "host" + if a.scheme != b.scheme and a.path == b.path: + return "scheme" + if a.path.rstrip("/") == b.path.rstrip("/") and a.query == b.query: + return "slash" + return "path" + + +def collect_addresses(root): + """{url: [(owner, field path)]} for every record and every left-out entry.""" + found = {} + for tid in trail_ids(root): + rec = load_toml(os.path.join(root, tid, "trail.toml")) + for url, path in urls_in(rec): + found.setdefault(url, []).append((tid, path)) + for e in left_out_entries(root): + for url, path in urls_in(e): + found.setdefault(url, []).append(("left-out:" + str(e.get("id")), path)) + return found + + +def cmd_links(args): + root = args.root + d = staging_dir(root, args.dir, create=True, today=today_str(args)) + found = collect_addresses(root) + urls = sorted(found) + if args.only_prefix: + urls = [u for u in urls if u.startswith(args.only_prefix)] + if args.limit: + urls = urls[: args.limit] + by_host = {} + for u in urls: + by_host.setdefault(urllib.parse.urlsplit(u).netloc.lower(), []).append(u) + prober = Prober(delay=args.delay, timeout=args.timeout, user_agent=args.user_agent) + + def work(host): + return [prober.probe(u) for u in by_host[host]] + + rows = [] + with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, args.hosts)) as pool: + for part in pool.map(work, sorted(by_host)): + rows.extend(part) + rows.sort(key=lambda r: r["url"]) + path = os.path.join(d, "links.csv") + cols = ("url", "host", "status", "final_url", "redirect", "refused", "note", "error", + "method", "used_by") + with open(path, "w", newline="", encoding="utf-8") as f: + w = csv.writer(f) + w.writerow(cols) + for r in rows: + owners = sorted({o for o, _ in found[r["url"]]}) + w.writerow([r["url"], r["host"], r["status"], r["final_url"], + redirect_kind(r["url"], r["final_url"]), r["refused"], r["note"], + r["error"], r["method"], ";".join(owners[:12]) + ("…" if len(owners) > 12 else "")]) + ok = sum(1 for r in rows if isinstance(r["status"], int) and 200 <= r["status"] < 300) + refused = sum(1 for r in rows if r["refused"]) + bad = sum(1 for r in rows if isinstance(r["status"], int) and r["status"] >= 400 and not r["refused"]) + err = sum(1 for r in rows if r["error"] and not r["status"]) + print(f"{len(rows)} addresses on {len(by_host)} hosts: {ok} ok, {bad} error status, " + f"{refused} refused, {err} no answer. Written to {path}") + return 0 + + +# ----------------------------------------------------------------------------- proposals + +def read_csv(path): + with open(path, newline="", encoding="utf-8") as f: + return list(csv.DictReader(f)) + + +def slice_ids(d, name): + p = os.path.join(d, "slices", name + ".txt") + if not os.path.isfile(p): + return None + return [x.strip() for x in open(p, encoding="utf-8") if x.strip()] + + +def split_path(field): + """'hike.source[1].facts' -> ('hike.source', 1, 'facts'); 'source.url' -> ('source', None, 'url'); + 'length_km' -> ('', None, 'length_km').""" + m = re.match(r"^((?:[a-z_]+\.)*[a-z_]+)(?:\[(\d+)\])?\.([a-z_]+)$", field) + if m: + return m.group(1), (int(m.group(2)) if m.group(2) is not None else None), m.group(3) + if re.match(r"^[a-z_]+$", field): + return "", None, field + return None + + +def schema_path(field): + """The field as docs/schema.md names it: indexes removed.""" + return re.sub(r"\[\d+\]", "", field) + + +def validate_proposal(p, ctx): + """Return a list of problems with one staged proposal (a parsed [[proposal]]).""" + errs = [] + kind = p.get("kind") + if kind not in KINDS: + return [f"kind must be one of {', '.join(KINDS)}, not {kind!r}"] + pid = p.get("id") + if not isinstance(pid, str) or not ID_RE.match(pid): + errs.append("id must be a lower case id with hyphens") + target = p.get("target", "record") + if target not in ("record", "left-out"): + errs.append("target must be \"record\" or \"left-out\"") + if kind in ("left-out-add", "left-out-remove"): + target = "left-out" + if not isinstance(p.get("date"), str) or not DATE_RE.match(p.get("date", "")): + errs.append("date must be YYYY-MM-DD (the day the pages were read)") + if not isinstance(p.get("summary"), str) or not p.get("summary", "").strip(): + errs.append("summary is required: one plain sentence") + known = {"kind", "id", "target", "date", "summary", "edit", "append", "file", "history", + "pages", "remark", "entry", "name", "country", "regions", "length_mi", + "source_url", "recommendation", "reason", "what", "why", "tried", "quote", + "basis_url", "borderline", "sources_md"} + for k in p: + if k not in known: + errs.append(f"unknown field {k}") + + def need_url(obj, key, where): + v = obj.get(key) + if not isinstance(v, str) or not URL_RE.match(v): + errs.append(f"{where}: {key} must be an http(s) address") + + def need_text(obj, key, where): + v = obj.get(key) + if not isinstance(v, str) or not v.strip(): + errs.append(f"{where}: {key} is required") + + if kind == "verified": + pages = p.get("pages") + if not isinstance(pages, list) or not pages or not all( + isinstance(x, str) and URL_RE.match(x) for x in pages): + errs.append("verified needs pages: the http(s) addresses that were opened") + elif kind in ("change", "declined"): + edits, appends, files = p.get("edit", []), p.get("append", []), p.get("file", []) + if kind == "change" and not (edits or appends or files): + errs.append("a change needs at least one edit, append or file") + if kind == "declined" and (edits or appends or files): + errs.append("a declined proposal changes nothing: no edit, append or file") + seen = set() + for i, e in enumerate(edits, 1): + where = f"edit {i}" + for k in e: + if k not in ("field", "old", "new", "page", "quote"): + errs.append(f"{where}: unknown field {k}") + f = e.get("field") + if not isinstance(f, str): + errs.append(f"{where}: field is required") + continue + if f in seen: + errs.append(f"{where}: {f} is edited twice") + seen.add(f) + if f == "id" or f == "history" or f.startswith("history"): + errs.append(f"{where}: {f} is never edited") + if target == "record": + if split_path(f) is None or (schema_path(f) not in H.SCHEMA_FIELDS): + errs.append(f"{where}: {f!r} is not a field of the record (docs/schema.md)") + if "old" not in e and "new" not in e: + errs.append(f"{where}: give old, new or both") + if "old" in e and "new" in e and e["old"] == e["new"]: + errs.append(f"{where}: old and new are the same") + need_url(e, "page", where) + need_text(e, "quote", where) + for i, a in enumerate(appends, 1): + where = f"append {i}" + if a.get("table") not in APPEND_TABLES: + errs.append(f"{where}: table must be one of {', '.join(APPEND_TABLES)}") + if not isinstance(a.get("entry"), dict) or not a.get("entry"): + errs.append(f"{where}: entry (the new table's fields) is required") + need_url(a, "page", where) + need_text(a, "quote", where) + for i, fl in enumerate(files, 1): + where = f"file {i}" + to = fl.get("to") + if not isinstance(to, str) or not FILE_NAME_RE.match(to): + errs.append(f"{where}: to must be a track, release, elevation or shield file name") + if fl.get("remove") is True: + if "from" in fl: + errs.append(f"{where}: remove and from together") + else: + src = fl.get("from") + if not isinstance(src, str) or src.startswith("/") or ".." in src.split("/"): + errs.append(f"{where}: from must be a path inside the proposal's own directory") + elif ctx.get("pdir") and not os.path.isfile(os.path.join(ctx["pdir"], src)): + errs.append(f"{where}: staged file {src} does not exist") + need_url(fl, "source_url", where) + facts_touched = any( + target == "record" and isinstance(e.get("field"), str) + and H.is_fact(schema_path(e["field"])) for e in edits) + facts_touched = facts_touched or bool(appends and any( + a.get("table") in ("guide",) for a in appends)) or bool(files) + hist = p.get("history") + if target == "record" and (kind == "declined" or facts_touched): + if not isinstance(hist, dict): + errs.append("a change to a fact needs [proposal.history]: change, basis, " + "basis_url, asked_by (docs/schema.md, section [[history]])") + if isinstance(hist, dict): + for k in hist: + if k not in ("change", "basis", "basis_url", "asked_by", "fields"): + errs.append(f"history: unknown field {k}") + for k in ("change", "basis", "asked_by"): + need_text(hist, k, "history") + need_url(hist, "basis_url", "history") + for f in hist.get("fields", []): + if f not in H.SCHEMA_FIELDS: + errs.append(f"history: fields names {f!r}, which is not a field of the record") + if kind == "declined" and not hist.get("fields"): + errs.append("a declined proposal names the fields in history.fields") + elif kind == "new-record": + pdir = ctx.get("pdir") + rec_path = os.path.join(pdir, "trail.toml") if pdir else None + if rec_path is None or not os.path.isfile(rec_path): + errs.append("new-record needs the staged record, trail.toml, beside proposal.toml") + else: + try: + rec = load_toml(rec_path) + except tomllib.TOMLDecodeError as e: + errs.append(f"staged trail.toml does not parse: {e}") + else: + if rec.get("id") != pid: + errs.append(f"staged trail.toml has id {rec.get('id')!r}, not {pid!r}") + hist = rec.get("history") + if not hist or hist[0].get("fields") != ["record"]: + errs.append("staged trail.toml needs a first [[history]] entry with " + 'fields = ["record"]') + if ctx.get("trail_ids") is not None and pid in ctx["trail_ids"]: + errs.append(f"{pid} already exists in the repository") + need_url(p, "basis_url", "new-record") + elif kind == "left-out-add": + entry = p.get("entry") + if not isinstance(entry, dict): + errs.append("left-out-add needs [proposal.entry]: the new [[trail]] entry") + else: + for k in ("id", "name", "country", "regions", "reason", "note", "decided", "was_listed"): + if k not in entry: + errs.append(f"entry is missing {k}") + if entry.get("id") != pid: + errs.append("entry.id must equal the proposal id") + need_url(p, "basis_url", "left-out-add") + elif kind == "left-out-remove": + need_url(p, "basis_url", "left-out-remove") + need_text(p, "why", "left-out-remove") + elif kind == "candidate": + for k in ("name", "country", "source_url", "recommendation"): + if k not in p: + errs.append(f"candidate is missing {k}") + if p.get("recommendation") not in ("add", "owner", "decline"): + errs.append("recommendation must be add, owner or decline") + if "source_url" in p: + need_url(p, "source_url", "candidate") + elif kind == "could-not-check": + for k in ("what", "why"): + need_text(p, k, "could-not-check") + return errs + + +def read_staged(d, trail_set): + """Walk staged///proposal.toml. Returns (proposals, problems).""" + proposals, problems = [], [] + base = os.path.join(d, "staged") + if not os.path.isdir(base): + return proposals, problems + for worker in sorted(os.listdir(base)): + wdir = os.path.join(base, worker) + if not os.path.isdir(wdir): + continue + for pidname in sorted(os.listdir(wdir)): + pdir = os.path.join(wdir, pidname) + ppath = os.path.join(pdir, "proposal.toml") + if not os.path.isfile(ppath): + continue + where = f"staged/{worker}/{pidname}/proposal.toml" + try: + doc = load_toml(ppath) + except tomllib.TOMLDecodeError as e: + problems.append(f"{where}: does not parse: {e}") + continue + for k in doc: + if k != "proposal": + problems.append(f"{where}: unknown top-level key {k}; proposals are [[proposal]] tables") + for n, p in enumerate(doc.get("proposal", []), 1): + ctx = {"pdir": pdir, "trail_ids": trail_set} + errs = validate_proposal(p, ctx) + if p.get("id") and p.get("id") != pidname and p.get("kind") != "candidate": + errs.append(f"id {p.get('id')!r} does not match its directory {pidname!r}") + for e in errs: + problems.append(f"{where} proposal {n}: {e}") + item = dict(p) + item["pid"] = f"{worker}:{pidname}:{n}" + item["worker"] = worker + item["source_file"] = f"staged/{worker}/{pidname}/proposal.toml" + item["valid"] = not errs + item["digest"] = digest(p) + proposals.append(item) + return proposals, problems + + +def read_decisions(d): + """Review decisions: review/*.csv then owner.csv. Returns {pid: [(source, row)]}.""" + out = {} + files = [] + rdir = os.path.join(d, "review") + if os.path.isdir(rdir): + files += [(f"review/{n}", os.path.join(rdir, n)) for n in sorted(os.listdir(rdir)) if n.endswith(".csv")] + owner = os.path.join(d, "owner.csv") + if os.path.isfile(owner): + files.append(("owner.csv", owner)) + for label, path in files: + for row in read_csv(path): + out.setdefault((row.get("pid") or "").strip(), []).append((label, row)) + return out + + +def decide(p, decisions, warnings): + """The proposal's status from its decisions: owner wins; else any reject or hold; else accept.""" + rows = decisions.get(p["pid"], []) + valid = [] + for label, row in rows: + dec = (row.get("decision") or "").strip().lower() + if dec not in DECISIONS: + warnings.append(f"{label}: {p['pid']}: decision {dec!r} is not one of {', '.join(DECISIONS)}") + continue + if dec == "accept" and (row.get("digest") or "").strip() != p["digest"]: + warnings.append(f"{label}: {p['pid']}: accepted a different version " + f"({(row.get('digest') or '').strip() or 'no digest'}, now {p['digest']}); " + "the proposal changed after review, so it needs review again") + continue + valid.append((label, dec)) + if not valid: + return "proposed" + owner = [dec for label, dec in valid if label == "owner.csv"] + if owner: + return {"accept": "accepted", "reject": "rejected", "hold": "held"}[owner[-1]] + decs = [dec for _label, dec in valid] + if "reject" in decs: + return "rejected" + if "hold" in decs: + return "held" + return "accepted" + + +def norm_url(u): + parts = urllib.parse.urlsplit(u.strip()) + return (parts.netloc.lower().removeprefix("www.") + parts.path.rstrip("/") + + ("?" + parts.query if parts.query else "")) + + +def trunc(s, n=110): + s = str(s).replace("\n", " ") + return s if len(s) <= n else s[: n - 1] + "…" + + +def cmd_collect(args): + root = args.root + d = staging_dir(root, args.dir, create=False) + trail_set = set(trail_ids(root)) + left_ids = {e.get("id") for e in left_out_entries(root)} + proposals, problems = read_staged(d, trail_set) + warnings = [] + decisions = read_decisions(d) + known_pids = {p["pid"] for p in proposals} + for pid in decisions: + if pid and pid not in known_pids: + warnings.append(f"a decision names {pid}, which is not a staged proposal") + for p in proposals: + p["status"] = decide(p, decisions, warnings) if p["valid"] and p["kind"] in APPLIED_KINDS \ + else ("invalid" if not p["valid"] else "info") + + # reports + reports, report_rows = {}, [] + base = os.path.join(d, "staged") + if os.path.isdir(base): + for worker in sorted(os.listdir(base)): + rp = os.path.join(base, worker, "report.csv") + if not os.path.isfile(rp): + continue + rows = read_csv(rp) + if rows and set(REPORT_COLUMNS) - set(rows[0]): + problems.append(f"staged/{worker}/report.csv: columns must be {', '.join(REPORT_COLUMNS)}") + continue + reports[worker] = rows + for r in rows: + oc = (r.get("outcome") or "").strip() + r["worker"] = worker + if oc not in OUTCOMES: + problems.append(f"staged/{worker}/report.csv: {r.get('id')}: outcome {oc!r} is not " + f"one of {', '.join(OUTCOMES)}") + if oc in NEEDS_PAGES and not (r.get("pages") or "").strip(): + problems.append(f"staged/{worker}/report.csv: {r.get('id')}: outcome {oc} needs " + "pages (where it looked)") + if oc in ("could-not-check", "refused", "not-found") and not (r.get("remark") or "").strip(): + problems.append(f"staged/{worker}/report.csv: {r.get('id')}: outcome {oc} needs a remark") + report_rows.append(r) + sdir = os.path.join(d, "slices") + missing = [] + if os.path.isdir(sdir): + started = set(os.listdir(base)) if os.path.isdir(base) else set() + for fn in sorted(os.listdir(sdir)): + if not fn.endswith(".txt"): + continue + name = fn[:-4] + ids = slice_ids(d, name) + if name in reports: + got = {(r.get("id") or "").strip() for r in reports[name]} + lost = [i for i in ids if i not in got] + if lost: + missing.append((name, lost)) + elif name in started: # a worker staged something but wrote no report + missing.append((name, ids)) + verified_ids = {p["id"] for p in proposals if p["kind"] == "verified"} + for r in report_rows: + if (r.get("outcome") or "").strip() == "verified" and r["worker"].startswith(("trails", "verify")) \ + and r.get("id") and r["id"] not in verified_ids and r["id"] in trail_set: + warnings.append(f"{r['worker']}: {r['id']} is reported verified but has no `verified` proposal") + + # a record is verified against the pages it cites: say which cited pages were not opened + opened = {} + for r in report_rows: + if (r.get("outcome") or "").strip() in ("verified", "changed"): + opened.setdefault((r.get("id") or "").strip(), set()).update( + norm_url(u) for u in re.split(r"[;\s]+", r.get("pages") or "") if u) + for p in proposals: + if p["kind"] == "verified" and p["valid"]: + opened.setdefault(p["id"], set()).update(norm_url(u) for u in p.get("pages", [])) + for tid in sorted(opened): + if tid not in trail_set: + continue + rec = load_toml(os.path.join(root, tid, "trail.toml")) + hike = rec.get("hike") or {} + cited = {norm_url(x["url"]) for x in hike.get("source", []) if x.get("url")} + if hike.get("official_url"): + cited.add(norm_url(hike["official_url"])) + short = sorted(cited - opened[tid]) + if short: + warnings.append(f"{tid}: {len(short)} of {len(cited)} cited pages are not listed as opened " + f"(first: {short[0]})") + + # cross-checks between proposals + seen_fields = {} + for p in proposals: + if p["kind"] == "change" and p["valid"]: + for e in p.get("edit", []): + seen_fields.setdefault((p.get("target", "record"), p["id"], e["field"]), []).append(p["pid"]) + for key, pids in seen_fields.items(): + if len(pids) > 1: + warnings.append(f"{key[1]} {key[2]} is edited by more than one proposal: {', '.join(pids)}") + new_ids = {} + for p in proposals: + if p["kind"] == "new-record": + new_ids.setdefault(p["id"], []).append(p["pid"]) + for tid, pids in new_ids.items(): + if len(pids) > 1: + warnings.append(f"{tid} is proposed as a new record more than once: {', '.join(pids)}") + if tid in left_ids and not any(q["kind"] == "left-out-remove" and q["id"] == tid for q in proposals): + warnings.append(f"{tid} is a new record but is still in left-out.toml; it needs a " + "left-out-remove proposal") + for p in proposals: + if p["kind"] == "candidate" and p.get("id") in left_ids: + warnings.append(f"candidate {p['id']} is in left-out.toml; say what changed since it was decided") + + # write collected.toml + out = {"collected": {"date": today_str(args), "directory": os.path.relpath(d, root), + "proposals": len(proposals)}, + "proposal": []} + for p in proposals: + q = {k: v for k, v in p.items() if k not in ("valid",)} + out["proposal"].append(q) + with open(os.path.join(d, "collected.toml"), "w", encoding="utf-8") as f: + f.write("# Written by `python3 tools/refresh.py collect`. Do not edit: record decisions in\n" + "# review/*.csv and owner.csv (pid, digest, decision, note) and collect again.\n\n") + f.write(dump_toml(out)) + summary = render_summary(d, proposals, problems, warnings, reports, report_rows, missing) + with open(os.path.join(d, "summary.md"), "w", encoding="utf-8") as f: + f.write(summary) + counts = {} + for p in proposals: + counts[p["kind"]] = counts.get(p["kind"], 0) + 1 + print(f"{len(proposals)} proposals ({', '.join(f'{v} {k}' for k, v in sorted(counts.items())) or 'none'}), " + f"{len(problems)} problems, {len(warnings)} warnings, " + f"{sum(len(v) for _, v in missing)} ids not reported") + print(f"written: {os.path.join(d, 'collected.toml')} and {os.path.join(d, 'summary.md')}") + for pr in problems[:20]: + print("PROBLEM:", pr) + return 1 if problems else 0 + + +def render_summary(d, proposals, problems, warnings, reports, report_rows, missing): + L = [f"# Refresh summary, {os.path.basename(d)}", ""] + kinds = {} + for p in proposals: + kinds.setdefault(p["kind"], {}).setdefault(p["status"], 0) + kinds[p["kind"]][p["status"]] += 1 + L += ["## Counts", ""] + if proposals: + L += ["| Kind | Proposals | By status |", "| --- | ---: | --- |"] + for k in KINDS: + if k in kinds: + L.append(f"| {k} | {sum(kinds[k].values())} | " + + ", ".join(f"{n} {s}" for s, n in sorted(kinds[k].items())) + " |") + else: + L.append("No proposals are staged.") + outcomes = {} + for r in report_rows: + oc = (r.get("outcome") or "").strip() + outcomes[oc] = outcomes.get(oc, 0) + 1 + if outcomes: + L += ["", "Report rows by outcome: " + ", ".join(f"{n} {o}" for o, n in sorted(outcomes.items())) + "."] + L += ["", f"Reports read: {len(reports)}."] + if problems: + L += ["", "## Problems (fix before review)", ""] + [f"- {x}" for x in problems] + if warnings: + L += ["", "## Warnings", ""] + [f"- {x}" for x in warnings] + if missing: + L += ["", "## Ids not reported", ""] + for name, ids in missing: + L.append(f"- {name}: {len(ids)} not in the report: {', '.join(ids[:15])}{'…' if len(ids) > 15 else ''}") + chg = [p for p in proposals if p["kind"] in ("change", "declined") and p["valid"]] + if chg: + L += ["", "## Proposed changes", ""] + for p in chg: + L.append(f"### {p['id']}{' (left-out)' if p.get('target') == 'left-out' else ''}" + f" `{p['pid']}` {p['digest']} [{p['status']}]") + L.append(p["summary"]) + for e in p.get("edit", []): + old = trunc(json.dumps(e["old"], ensure_ascii=False)) if "old" in e else "(absent)" + new = trunc(json.dumps(e["new"], ensure_ascii=False)) if "new" in e else "(removed)" + L.append(f"- `{e['field']}`: {old} → {new}") + L.append(f" - page {e.get('page')}: \"{trunc(e.get('quote', ''), 160)}\"") + for a in p.get("append", []): + L.append(f"- add to `{a.get('table')}`: {trunc(json.dumps(a.get('entry'), ensure_ascii=False), 140)}") + L.append(f" - page {a.get('page')}: \"{trunc(a.get('quote', ''), 160)}\"") + for fl in p.get("file", []): + L.append(f"- file {'removed' if fl.get('remove') else 'set'}: {fl.get('to')} (source {fl.get('source_url')})") + h = p.get("history") + if h: + L.append(f"- history: {trunc(h.get('change', ''), 160)} Basis: {h.get('basis_url')}") + L.append("") + for kind, title in (("new-record", "New records"), ("left-out-add", "Entries to add to left-out.toml"), + ("left-out-remove", "Entries to remove from left-out.toml")): + sel = [p for p in proposals if p["kind"] == kind and p["valid"]] + if sel: + L += ["", f"## {title}", ""] + for p in sel: + L.append(f"- `{p['id']}` `{p['pid']}` {p['digest']} [{p['status']}]: {trunc(p['summary'], 160)}") + ver = [p for p in proposals if p["kind"] == "verified" and p["valid"]] + if ver: + L += ["", f"## Verified, nothing changed ({len(ver)})", ""] + L.append(", ".join(sorted(p["id"] for p in ver))) + cand = [p for p in proposals if p["kind"] == "candidate" and p["valid"]] + if cand: + L += ["", "## Candidates (for the owner where marked)", "", + "| Name | Where | Length | Recommendation | Borderline | Page |", "| --- | --- | --- | --- | --- | --- |"] + for p in cand: + L.append(f"| {p.get('name')} | {', '.join(p.get('regions', []))} {p.get('country', '')} | " + f"{p.get('length_mi', '')} | {p.get('recommendation')} | " + f"{'yes' if p.get('borderline') else ''} | {p.get('source_url')} |") + cnc = [p for p in proposals if p["kind"] == "could-not-check" and p["valid"]] + cnc_rows = [r for r in report_rows if (r.get("outcome") or "").strip() in ("could-not-check", "refused")] + if cnc or cnc_rows: + L += ["", "## Could not check", ""] + for p in cnc: + L.append(f"- {p['id']}: {p.get('what')}. {p.get('why')}" + + (f" Tried: {p['tried']}" if p.get("tried") else "")) + for r in cnc_rows: + L.append(f"- {r.get('id')} ({r['worker']}, {r.get('outcome')}): {trunc(r.get('remark', ''), 200)}") + srows = [p for p in proposals if p.get("sources_md") and p["valid"]] + if srows: + L += ["", "## SOURCES.md rows to change when these are applied", ""] + for p in srows: + L.append(f"- `{p['id']}` [{p['status']}]: {p['sources_md']}") + nf = [r for r in report_rows if (r.get("outcome") or "").strip() == "not-found"] + if nf: + L += ["", "## Searches that found nothing, and where they looked", ""] + for r in nf: + L.append(f"- {r.get('id')} ({r['worker']}): {trunc(r.get('pages', ''), 300)}") + return "\n".join(L) + "\n" + + +# ----------------------------------------------------------------------------- apply + +class Doc: + """A TOML file as lines, edited by targeted replacement. The file is never re-serialised.""" + + def __init__(self, text): + self.lines = text.split("\n") + if self.lines and self.lines[-1] == "": + self.lines.pop() + + def text(self): + return "\n".join(self.lines) + "\n" + + def data(self): + return tomllib.loads(self.text()) + + def _headers(self): + out = [] + for i, line in enumerate(self.lines): + m = re.match(r"^\s*(\[\[?)\s*([A-Za-z0-9_.\- ]+?)\s*\]\]?\s*(#.*)?$", line) + if m: + out.append((i, m.group(1) == "[[", m.group(2).replace(" ", ""))) + return out + + def span(self, table, index=None): + """(first line after the header, end) of a table. table '' is the top level. + For an array of tables, index picks the nth block.""" + heads = self._headers() + if table == "": + end = heads[0][0] if heads else len(self.lines) + return 0, end + matches = [(i, k) for k, (i, is_arr, name) in enumerate(heads) + if name == table and is_arr == (index is not None)] + if index is None: + if not matches: + raise RefreshError(f"the record has no [{table}] table") + i, k = matches[0] + else: + if index >= len(matches): + raise RefreshError(f"the record has no [[{table}]] number {index}") + i, k = matches[index] + end = heads[k + 1][0] if k + 1 < len(heads) else len(self.lines) + return i + 1, end + + def key_line(self, span, key): + start, end = span + for i in range(start, end): + m = re.match(r"^\s*" + re.escape(key) + r"\s*=(.*)$", self.lines[i]) + if m: + return i + return None + + @staticmethod + def _split_comment(rest, want): + """Split the text after '=' into (value text, trailing comment). The value must parse + to `want`; a '#' inside a string is not a comment.""" + for pos in [m.start() for m in re.finditer("#", rest)] + [len(rest)]: + candidate = rest[:pos] + try: + got = tomllib.loads("x = " + candidate)["x"] + except tomllib.TOMLDecodeError: + continue + if got == want and type(got) is type(want): + return candidate, rest[pos:] + return None, None + + def get_line(self, span, key, want): + i = self.key_line(span, key) + if i is None: + return None, None, None + rest = self.lines[i].split("=", 1)[1] + value, comment = self._split_comment(rest, want) + if value is None: + raise RefreshError(f"{key}: the line cannot be matched to the current value for a " + "targeted edit (a multi-line value?); change it by hand") + return i, value, comment + + def set_value(self, span, key, new, old, has_old): + if has_old: + i, _v, comment = self.get_line(span, key, old) + if i is None: + raise RefreshError(f"{key} is absent, but the proposal expects {trunc(json.dumps(old, ensure_ascii=False), 60)}") + self.lines[i] = f"{key} = {_scalar(new)}" + (" " + comment if comment else "") + else: + if self.key_line(span, key) is not None: + raise RefreshError(f"{key} is already present, but the proposal expects it absent") + start, end = span + last = start - 1 + for i in range(start, end): + if re.match(r"^\s*[A-Za-z0-9_\-\"]+\s*=", self.lines[i]): + last = i + self.lines.insert(last + 1, f"{key} = {_scalar(new)}") + + def remove_value(self, span, key, old): + i, _v, _c = self.get_line(span, key, old) + if i is None: + raise RefreshError(f"{key} is absent, but the proposal expects {trunc(json.dumps(old, ensure_ascii=False), 60)}") + del self.lines[i] + + def append_block(self, table, entry): + block = [f"[[{table}]]"] + [f"{k} = {_scalar(v)}" for k, v in entry.items()] + heads = self._headers() + same = [k for k, (i, is_arr, name) in enumerate(heads) if is_arr and name == table] + if same: + k = same[-1] + end = heads[k + 1][0] if k + 1 < len(heads) else len(self.lines) + # back up over blank lines and the comment lines that belong to the next block + pos = end + while pos > heads[k][0] + 1 and (self.lines[pos - 1].strip() == "" + or self.lines[pos - 1].lstrip().startswith("#")): + pos -= 1 + self.lines[pos:pos] = [""] + block + return + pos = len(self.lines) + for i, line in enumerate(self.lines): + if line.startswith("# History of this record") or re.match(r"^\[\[history\]\]", line): + pos = i + break + # sit before the comment lines that lead into the history + while pos > 0 and self.lines[pos - 1].lstrip().startswith("#"): + pos -= 1 + while pos > 0 and self.lines[pos - 1].strip() == "": + pos -= 1 + self.lines[pos:pos] = [""] + block + + def append_history(self, entry): + if self.lines and self.lines[-1].strip() != "": + self.lines.append("") + self.lines += ["[[history]]"] + [f"{k} = {_scalar(v)}" for k, v in entry.items()] + + +def navigate(data, table, index): + node = data + if table: + for part in table.split("."): + if not isinstance(node, dict) or part not in node: + return None + node = node[part] + if index is not None: + if not isinstance(node, list) or index >= len(node): + return None + node = node[index] + return node + + +def history_fields(p): + h = p.get("history", {}) + if h.get("fields"): + return list(h["fields"]) + out = [] + for e in p.get("edit", []): + out.append(schema_path(e["field"])) + for a in p.get("append", []): + out.append(a["table"]) + for fl in p.get("file", []): + out.append("shield.logo_file" if fl["to"].startswith("shield.") else "source.line_file") + seen = [] + for f in out: + if f not in seen: + seen.append(f) + return seen + + +def apply_record_edits(doc, p): + """Apply the edits and appends of one proposal to a Doc. Raises RefreshError.""" + skipped = 0 + for e in p.get("edit", []): + field = e["field"] + table, index, key = split_path(field) + data = doc.data() + node = navigate(data, table, index) + has_old, has_new = "old" in e, "new" in e + current_has = isinstance(node, dict) and key in node + if node is None: + raise RefreshError(f"{field}: the record has no {table or 'top level'}" + + (f" number {index}" if index is not None else "")) + if has_new and current_has and node[key] == e["new"] and type(node[key]) is type(e["new"]): + skipped += 1 + continue + if has_old and not current_has: + raise RefreshError(f"{field}: the record has no such field now, but the proposal expects " + f"{trunc(json.dumps(e['old'], ensure_ascii=False), 70)}") + if has_old and node[key] != e["old"]: + raise RefreshError(f"{field}: the current value is {trunc(json.dumps(node[key], ensure_ascii=False), 70)}, " + f"not the proposal's old value {trunc(json.dumps(e['old'], ensure_ascii=False), 70)}") + if not has_old and current_has: + raise RefreshError(f"{field}: is already set to {trunc(json.dumps(node[key], ensure_ascii=False), 70)}, " + "but the proposal expects it absent") + span = doc.span(table, index) + if has_new: + doc.set_value(span, key, e["new"], e.get("old"), has_old) + else: + doc.remove_value(span, key, e["old"]) + for a in p.get("append", []): + data = doc.data() + existing = data + for part in a["table"].split("."): + existing = existing.get(part, {}) if isinstance(existing, dict) else {} + urls = {x.get("url") for x in existing} if isinstance(existing, list) else set() + if a["entry"].get("url") and a["entry"]["url"] in urls: + raise RefreshError(f"{a['table']}: an entry with {a['entry']['url']} is already there") + doc.append_block(a["table"], a["entry"]) + if skipped and skipped == len(p.get("edit", [])) and not p.get("append"): + raise AlreadyApplied(p["id"]) + + +class AlreadyApplied(RefreshError): + pass + + +def check_files(root, d, p): + """Check the file operations of a proposal before anything is written.""" + tdir = os.path.join(root, p["id"]) + pdir = os.path.join(d, os.path.dirname(p["source_file"])) + plan = [] + for fl in p.get("file", []): + dest = os.path.join(tdir, fl["to"]) + exists = os.path.isfile(dest) + if exists: + want = fl.get("old_sha256") + if not want: + raise RefreshError(f"{fl['to']} exists; the proposal must give its old_sha256") + if sha256_file(dest) != want: + raise RefreshError(f"{fl['to']} has changed since the proposal was written (sha256 differs)") + elif fl.get("old_sha256"): + raise RefreshError(f"{fl['to']} is absent, but the proposal expects it to exist") + if fl.get("remove"): + if not exists: + raise RefreshError(f"{fl['to']} is absent; nothing to remove") + plan.append(("remove", dest, None)) + else: + src = os.path.normpath(os.path.join(pdir, fl["from"])) + if not src.startswith(os.path.normpath(pdir) + os.sep) or not os.path.isfile(src): + raise RefreshError(f"staged file {fl['from']} is missing") + plan.append(("copy", dest, src)) + return plan + + +def do_files(plan): + for op, dest, src in plan: + if op == "remove": + os.remove(dest) + else: + shutil.copyfile(src, dest) + + +def sort_key_name(name): + return " ".join(re.sub(r"[^a-z0-9]+", " ", str(name).lower()).split()) + + +def left_out_blocks(doc): + """[(start, end)] line ranges of each [[trail]] block in left-out.toml (end exclusive, + trailing blank lines excluded).""" + heads = [i for i, l in enumerate(doc.lines) if l.strip() == "[[trail]]"] + blocks = [] + for k, i in enumerate(heads): + end = heads[k + 1] if k + 1 < len(heads) else len(doc.lines) + while end > i + 1 and doc.lines[end - 1].strip() == "": + end -= 1 + blocks.append((i, end)) + return blocks + + +def left_out_block_for(doc, lid): + for i, end in left_out_blocks(doc): + for j in range(i + 1, end): + m = re.match(r'^id\s*=\s*"(.*)"\s*$', doc.lines[j]) + if m and m.group(1) == lid: + return i, end + return None + + +def apply_left_out(doc, p, today): + kind = p["kind"] + if kind == "left-out-add": + entry = p["entry"] + if left_out_block_for(doc, entry["id"]): + raise RefreshError(f"{entry['id']} is already in left-out.toml") + block = ["[[trail]]"] + [f"{k} = {_scalar(v)}" for k, v in entry.items()] + blocks = left_out_blocks(doc) + names = [] + for i, end in blocks: + nm = "" + for j in range(i + 1, end): + m = re.match(r'^name\s*=\s*"(.*)"\s*$', doc.lines[j]) + if m: + nm = m.group(1) + names.append(nm) + want = sort_key_name(entry["name"]) + pos = None + for (i, end), nm in zip(blocks, names): + if sort_key_name(nm) > want: + pos = i + break + if pos is None: + doc.lines += [""] + block + else: + doc.lines[pos:pos] = block + [""] + return + blk = left_out_block_for(doc, p["id"]) + if blk is None: + raise RefreshError(f"{p['id']} is not in left-out.toml") + i, end = blk + if kind == "left-out-remove": + start = i + # drop one blank line with it, and any comment lines directly above the block + stop = end + while stop < len(doc.lines) and doc.lines[stop].strip() == "": + stop += 1 + del doc.lines[start:stop] + if not doc.lines or doc.lines[-1].strip() != "": + pass + return + # change: edits inside the block, using the same line logic with a block span + for e in p.get("edit", []): + key = e["field"] + if not re.match(r"^[a-z_]+$", key): + raise RefreshError(f"{key}: a left-out edit names a plain field") + i, end = left_out_block_for(doc, p["id"]) + span = (i + 1, end) + node = tomllib.loads("\n".join(doc.lines[i:end]).replace("[[trail]]", "[t]", 1)).get("t", {}) + has_old, has_new = "old" in e, "new" in e + if has_old and node.get(key) != e["old"]: + raise RefreshError(f"{key}: the current value is {trunc(json.dumps(node.get(key), ensure_ascii=False), 70)}, " + f"not the proposal's old value") + if not has_old and key in node: + raise RefreshError(f"{key} is already set, but the proposal expects it absent") + if has_new: + doc.set_value(span, key, e["new"], e.get("old"), has_old) + else: + doc.remove_value(span, key, e["old"]) + + +def target_of(p): + if p["kind"] in ("left-out-add", "left-out-remove") or p.get("target") == "left-out": + return ("left-out", LEFT_OUT_FILE) + return ("record", p["id"]) + + +def cmd_apply(args): + root = args.root + d = staging_dir(root, args.dir, create=False) + cpath = os.path.join(d, "collected.toml") + if not os.path.isfile(cpath): + raise RefreshError("no collected.toml; run `python3 tools/refresh.py collect` first") + today = today_str(args) + coll = load_toml(cpath) + todo = [p for p in coll.get("proposal", []) if p.get("status") == "accepted" + and (not args.only or p["pid"] in args.only)] + log = [] + by_record = {} + for p in todo: + by_record.setdefault(target_of(p), []).append(p) + failures = 0 + + def refuse(p, why): + nonlocal failures + failures += 1 + log.append((p["pid"], "refused", why)) + print(f"REFUSED {p['pid']}: {why}") + + # left-out.toml first (one file, all its proposals), then records + for (target, name), props in sorted(by_record.items(), key=lambda kv: (kv[0][0] != "left-out", kv[0][1])): + if target == "left-out": + path = os.path.join(root, LEFT_OUT_FILE) + doc = Doc(open(path, encoding="utf-8").read()) + changed = False + for p in props: + if not verify_digest(d, p, refuse): + continue + trial = Doc(doc.text()) + try: + apply_left_out(trial, p, today) + trial.data() + except AlreadyApplied: + log.append((p["pid"], "already-applied", "")) + continue + except (RefreshError, tomllib.TOMLDecodeError) as e: + refuse(p, str(e)) + continue + doc, changed = trial, True + log.append((p["pid"], "applied" if not args.dry_run else "would-apply", "")) + print(("would apply " if args.dry_run else "applied ") + p["pid"]) + if changed and not args.dry_run: + write_text(path, doc.text()) + continue + tdir = os.path.join(root, name) + for p in props: + if p["kind"] == "new-record": + if not verify_digest(d, p, refuse): + continue + if os.path.exists(tdir): + refuse(p, f"{name}/ already exists") + continue + src = os.path.join(d, os.path.dirname(p["source_file"])) + if not os.path.isfile(os.path.join(src, "trail.toml")): + refuse(p, "the staged trail.toml is missing") + continue + if args.dry_run: + log.append((p["pid"], "would-apply", "")) + print("would apply " + p["pid"]) + continue + shutil.copytree(src, tdir, ignore=shutil.ignore_patterns("proposal.toml")) + log.append((p["pid"], "applied", "")) + print("applied " + p["pid"]) + rec_props = [p for p in props if p["kind"] != "new-record"] + if not rec_props: + continue + path = os.path.join(tdir, "trail.toml") + if not os.path.isfile(path): + for p in rec_props: + refuse(p, f"{name}/trail.toml does not exist") + continue + doc = Doc(open(path, encoding="utf-8").read()) + changed, pending_files = False, [] + for p in rec_props: + if not verify_digest(d, p, refuse): + continue + trial = Doc(doc.text()) + try: + plan = check_files(root, d, p) if p["kind"] == "change" else [] + if p["kind"] == "verified": + data = trial.data() + hike = data.get("hike") + field = "hike.checked" if hike is not None else "source.source_checked" + table, _i, key = split_path(field) + cur = navigate(data, table, None) + if cur is None or key not in cur: + raise RefreshError(f"{field} is absent; the record cannot take a verified date") + if str(cur[key]) >= p["date"]: + raise AlreadyApplied(field) + trial.set_value(trial.span(table), key, p["date"], str(cur[key]), True) + elif p["kind"] in ("change", "declined"): + apply_record_edits(trial, p) + if p["kind"] == "change" or p.get("history"): + pass + if p["kind"] in ("change", "declined") and p.get("history"): + h = p["history"] + last = (trial.data().get("history") or [{}])[-1].get("date", "") + entry = {"date": max(today, last), "change": h["change"], + "fields": history_fields(p), "basis": h["basis"], + "basis_url": h["basis_url"], "asked_by": h["asked_by"], + "outcome": "declined" if p["kind"] == "declined" else "applied"} + trial.append_history(entry) + trial.data() + except AlreadyApplied: + log.append((p["pid"], "already-applied", "")) + print(f"already applied {p['pid']}") + continue + except (RefreshError, tomllib.TOMLDecodeError) as e: + refuse(p, str(e)) + continue + doc, changed = trial, True + pending_files += plan + log.append((p["pid"], "applied" if not args.dry_run else "would-apply", "")) + print(("would apply " if args.dry_run else "applied ") + p["pid"]) + if changed and not args.dry_run: + write_text(path, doc.text()) + do_files(pending_files) + if not args.dry_run: + with open(os.path.join(d, "apply-log.csv"), "w", newline="", encoding="utf-8") as f: + w = csv.writer(f) + w.writerow(("pid", "result", "reason")) + w.writerows(log) + applied = sum(1 for _p, r, _w in log if r == "applied") + print(f"{applied} applied, {failures} refused. Next: tools/build_index.py, tools/validate.py, " + "tools/check_history.py, the test suites, CHANGELOG.md.") + else: + print(f"dry run: {sum(1 for _p, r, _w in log if r == 'would-apply')} would apply, {failures} refused") + return 1 if failures else 0 + + +def verify_digest(d, p, refuse): + """The staged proposal must still be the one that was collected and reviewed.""" + path = os.path.join(d, p["source_file"]) + if not os.path.isfile(path): + refuse(p, "the staged proposal file is missing") + return False + try: + doc = load_toml(path) + n = int(p["pid"].rsplit(":", 1)[1]) + now = digest(doc["proposal"][n - 1]) + except Exception as e: + refuse(p, f"the staged proposal cannot be read again: {e}") + return False + if now != p["digest"]: + refuse(p, "the staged proposal changed after it was collected; collect and review again") + return False + return True + + +def write_text(path, text): + tmp = path + ".tmp" + with open(tmp, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + os.replace(tmp, path) + + +# ----------------------------------------------------------------------------- main + +def build_parser(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--root", default=ROOT, help="the repository checkout (default: this one)") + ap.add_argument("--dir", help="the staging directory (default: the newest under refresh/)") + ap.add_argument("--today", help="today's date, YYYY-MM-DD (for tests)") + sub = ap.add_subparsers(dest="cmd", required=True) + p = sub.add_parser("preflight", help="clean tree, validator, tests, staging directory") + p.add_argument("--no-tests", action="store_true") + p.add_argument("--no-validate", action="store_true") + p.set_defaults(fn=cmd_preflight) + p = sub.add_parser("slices", help="split trail ids and left-out entries into balanced slices") + p.add_argument("--n", type=int, required=True, help="number of trail slices") + p.add_argument("--left-out-n", type=int, default=2, help="number of left-out slices (default 2)") + p.add_argument("--since", type=int, metavar="DAYS", + help="only trails whose last check (hike.checked, else source.source_checked) is " + "older than DAYS days") + p.set_defaults(fn=cmd_slices) + p = sub.add_parser("links", help="fetch every address once, politely, into links.csv") + p.add_argument("--delay", type=float, default=2.0, help="seconds between requests to one host") + p.add_argument("--timeout", type=float, default=20.0) + p.add_argument("--hosts", type=int, default=6, help="hosts fetched at the same time") + p.add_argument("--user-agent", default=USER_AGENT) + p.add_argument("--limit", type=int, help="only the first N addresses (a trial run)") + p.add_argument("--only-prefix", help="only addresses that start with this text") + p.set_defaults(fn=cmd_links) + p = sub.add_parser("collect", help="gather staged proposals and reports") + p.set_defaults(fn=cmd_collect) + p = sub.add_parser("apply", help="apply the proposals marked accepted in collected.toml") + p.add_argument("--dry-run", action="store_true") + p.add_argument("--only", nargs="+", metavar="PID") + p.set_defaults(fn=cmd_apply) + return ap + + +def main(argv=None): + args = build_parser().parse_args(argv) + try: + return args.fn(args) + except RefreshError as e: + print(f"refresh: {e}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/tests/test_refresh.py b/tools/tests/test_refresh.py new file mode 100644 index 0000000..812b94e --- /dev/null +++ b/tools/tests/test_refresh.py @@ -0,0 +1,1114 @@ +"""Tests for tools/refresh.py: slices, links, collect and apply. No internet: the link tests +talk to servers on 127.0.0.1, and the rest work on a small fixture repository in a temporary +directory. + +Run from the repository root: + python3 -m unittest discover tools/tests +""" +import contextlib +import csv +import http.server +import io +import os +import shutil +import sys +import tempfile +import threading +import tomllib +import unittest + +sys.dont_write_bytecode = True +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import refresh as R # noqa: E402 +import trail_history as H # noqa: E402 + +TODAY = "2026-12-01" + + +def record(tid, name, checked="2026-11-13", extra_hike="", hike=True): + text = f'''# Long-trail record. Field meanings: docs/schema.md in this repository. + +id = "{tid}" +name = "{name}" +country = "US" +regions = ["VT"] +length_km = 100 +length_note = "62 mi published" +tier = "regional" +designation = "Example Club" +wave = 1 + +[source] +status = "osm-only" +publisher = "Example Club" +url = "https://example.org/{tid}/data" +licence = "ODbL-1.0" +source_checked = "2026-11-10" +line_file = "" + +[osm] +relation = 0 +note = "Not searched." +''' + if hike: + text += f''' +[hike] +summary = "Runs north to south. See https://example.org/{tid}/about." +official_url = "https://example.org/{tid}/" +start = "North Gap" # as the club writes it +terrain = ["forest"] +permit = "No permit is needed." +checked = "{checked}" +{extra_hike} +[[hike.source]] +url = "https://example.org/{tid}/" +publisher = "Example Club" +facts = ["summary", "official_url", "start", "terrain", "permit"] + +[[hike.source]] +url = "https://example.org/{tid}/permits" +publisher = "Example Club" +facts = ["permit"] +''' + text += f''' +[[link]] +title = "{name}" +publisher = "Wiki" +url = "https://en.wikipedia.org/wiki/{tid}" + +# History of this record, oldest first. Add to it; never rewrite it. +# See docs/schema.md, section [[history]]. + +[[history]] +date = "2026-11-13" +change = "The record was added: {name}." +fields = ["record"] +basis = "The record's own source entry: Example Club." +asked_by = "the dataset's own check" +outcome = "applied" +''' + return text + + +LEFT_OUT = '''# Left out. Entries are sorted by name. + +[[trail]] +id = "alpha-trail" +name = "Alpha Trail" +country = "US" +regions = ["PA"] +length_mi = 42.0 +length_km = 68 +reason = "below-floor" +note = "The holder gives it as 42 miles. See https://example.org/alpha." +source_url = "https://example.org/alpha" +decided = "2026-11-14" +was_listed = false + +[[trail]] +id = "gamma-trail" +name = "Gamma Trail" +country = "US" +regions = ["PA"] +reason = "waiting" +note = "Not yet one trail." +source_url = "https://example.org/gamma" +decided = "2026-11-14" +was_listed = false +waiting_for = "It is designated." +''' + + +def make_repo(tmp, trails=None): + root = os.path.join(tmp, "repo") + os.makedirs(root) + for tid, name, kw in trails or [("aaa", "Aaa Trail", {}), ("bbb", "Bbb Trail", {"checked": "2026-10-01"}), + ("ccc", "Ccc Route", {"hike": False})]: + os.makedirs(os.path.join(root, tid)) + with open(os.path.join(root, tid, "trail.toml"), "w", encoding="utf-8") as f: + f.write(record(tid, name, **kw)) + with open(os.path.join(root, "left-out.toml"), "w", encoding="utf-8") as f: + f.write(LEFT_OUT) + return root + + +def main(root, *argv): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = R.main(["--root", root, "--today", TODAY, *argv]) + return code, out.getvalue() + err.getvalue() + + +def read(root, rel): + with open(os.path.join(root, rel), encoding="utf-8") as f: + return f.read() + + +def write(path, text): + with open(path, "w", encoding="utf-8") as f: + f.write(text) + + +class Tmp(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.tmp, True) + self.root = make_repo(self.tmp) + self.d = os.path.join(self.tmp, "stage") + os.makedirs(self.d) + + +class SliceTest(Tmp): + def slice_files(self): + sdir = os.path.join(self.d, "slices") + return {n: [x.strip() for x in read(sdir, n).splitlines() if x.strip()] + for n in sorted(os.listdir(sdir)) if n.endswith(".txt")} + + def test_every_id_once_and_left_out_apart(self): + code, out = main(self.root, "--dir", self.d, "slices", "--n", "2") + self.assertEqual(code, 0, out) + files = self.slice_files() + trails = sorted(i for n, ids in files.items() if n.startswith("trails") for i in ids) + self.assertEqual(trails, ["aaa", "bbb", "ccc"]) + left = sorted(i for n, ids in files.items() if n.startswith("left-out") for i in ids) + self.assertEqual(left, ["alpha-trail", "gamma-trail"]) + self.assertIn("trails-01.txt", files) + self.assertIn("trails-02.txt", files) + + def test_more_slices_than_ids(self): + main(self.root, "--dir", self.d, "slices", "--n", "9") + self.assertEqual(len([n for n in self.slice_files() if n.startswith("trails")]), 3) + + def test_since_uses_hike_checked_then_source_checked(self): + # today 2026-12-01: aaa checked 11-13 (18 days), bbb 10-01 (61 days), + # ccc has no [hike] and falls back to source_checked 11-10 (21 days) + code, out = main(self.root, "--dir", self.d, "slices", "--n", "2", "--since", "20") + self.assertEqual(code, 0) + ids = sorted(i for n, v in self.slice_files().items() if n.startswith("trails") for i in v) + self.assertEqual(ids, ["bbb", "ccc"]) + self.assertIn("hike.checked", out) + main(self.root, "--dir", self.d, "slices", "--n", "2", "--since", "90") + ids = [i for n, v in self.slice_files().items() if n.startswith("trails") for i in v] + self.assertEqual(ids, []) + + def test_rerun_replaces_old_slices(self): + main(self.root, "--dir", self.d, "slices", "--n", "3") + main(self.root, "--dir", self.d, "slices", "--n", "1") + self.assertEqual([n for n in self.slice_files() if n.startswith("trails")], ["trails-01.txt"]) + + def test_effective_check(self): + self.assertEqual(R.effective_check({"hike": {"checked": "2026-01-02"}, "source": {"source_checked": "2026-05-05"}}), + ("2026-01-02", "hike.checked")) + self.assertEqual(R.effective_check({"source": {"source_checked": "2026-05-05"}}), + ("2026-05-05", "source.source_checked")) + self.assertEqual(R.effective_check({}), (None, None)) + + def test_real_tree_is_covered(self): + code, out = main(R.ROOT, "--dir", self.d, "slices", "--n", "6") + self.assertEqual(code, 0, out) + files = self.slice_files() + ids = [i for n, v in files.items() if n.startswith("trails") for i in v] + self.assertEqual(len(ids), len(set(ids))) + self.assertEqual(set(ids), set(R.trail_ids(R.ROOT))) + sizes = [len(v) for n, v in files.items() if n.startswith("trails")] + self.assertEqual(len(sizes), 6) + self.assertLessEqual(max(sizes) - min(sizes), 12) + + +class StagingDirTest(Tmp): + def test_default_is_newest_and_preflight_starts_today(self): + base = os.path.join(self.root, "refresh") + os.makedirs(os.path.join(base, "2026-10-01")) + os.makedirs(os.path.join(base, "2026-10-20")) + self.assertTrue(R.staging_dir(self.root).endswith("2026-10-20")) + self.assertTrue(R.staging_dir(self.root, today=TODAY, fresh=True, create=True).endswith(TODAY)) + self.assertTrue(os.path.isdir(os.path.join(base, TODAY))) + self.assertTrue(R.staging_dir(self.root).endswith(TODAY)) + + def test_preflight_reports_a_dirty_tree_and_an_unignored_staging_directory(self): + import subprocess + git = lambda *a: subprocess.run(["git", *a], cwd=self.root, capture_output=True, check=True) + git("init", "-q") + git("config", "user.email", "t@example.org") + git("config", "user.name", "t") + git("add", ".") + git("commit", "-q", "-m", "x") + code, out = main(self.root, "preflight", "--no-tests", "--no-validate") + self.assertEqual(code, 1) + self.assertIn("is not ignored by git", out) + write(os.path.join(self.root, ".gitignore"), "/refresh/\n") + git("add", ".") + git("commit", "-q", "-m", "ignore") + code, out = main(self.root, "preflight", "--no-tests", "--no-validate") + self.assertEqual(code, 0, out) + self.assertIn("preflight OK", out) + write(os.path.join(self.root, "aaa", "trail.toml"), "id = 'aaa'\n") + code, out = main(self.root, "preflight", "--no-tests", "--no-validate") + self.assertEqual(code, 1) + self.assertIn("not clean", out) + + +class AddressTest(unittest.TestCase): + def test_urls_in_strips_punctuation(self): + rec = {"a": "See https://example.org/x. And (https://example.org/y) and https://e.org/z_(w).", + "b": ["http://e.org/q,"], "n": 5} + urls = sorted(u for u, _ in R.urls_in(rec)) + self.assertEqual(urls, ["http://e.org/q", "https://e.org/z_(w)", "https://example.org/x", + "https://example.org/y"]) + + def test_collect_addresses_reads_records_and_left_out(self): + with tempfile.TemporaryDirectory() as tmp: + root = make_repo(tmp) + found = R.collect_addresses(root) + self.assertIn("https://example.org/aaa/about", found) # inside the summary text + self.assertIn("https://example.org/alpha", found) + owners = {o for o, _ in found["https://example.org/alpha"]} + self.assertEqual(owners, {"left-out:alpha-trail"}) + + +class Handler(http.server.BaseHTTPRequestHandler): + hits = [] + lock = threading.Lock() + + def log_message(self, *a): + pass + + def _answer(self, head): + with Handler.lock: + Handler.hits.append((self.command, self.path, self.headers.get("User-Agent"))) + path = self.path + if path == "/robots.txt": + body = b"User-agent: *\nDisallow: /private\n" + return self._send(200, body, head) + if path == "/ok": + return self._send(200, b"fine", head) + if path == "/redir": + self.send_response(301) + self.send_header("Location", "/ok") + self.end_headers() + return + if path == "/slash": + self.send_response(301) + self.send_header("Location", "/slash/") + self.end_headers() + return + if path == "/slash/": + return self._send(200, b"x", head) + if path == "/gone": + return self._send(404, b"no", head) + if path == "/forbidden": + return self._send(403, b"no", head) + if path == "/limited": + return self._send(429, b"slow down", head) + if path == "/headbad": + return self._send(405 if head else 200, b"ok", head) + if path == "/challenge": + return self._send(200, b"Just a moment...", head) + if path == "/private": + return self._send(200, b"secret", head) + return self._send(200, b"other", head) + + def _send(self, code, body, head): + self.send_response(code) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + if not head: + self.wfile.write(body) + + def do_HEAD(self): + self._answer(True) + + def do_GET(self): + self._answer(False) + + +class LinkTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + cls.port = cls.server.server_address[1] + threading.Thread(target=cls.server.serve_forever, daemon=True).start() + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.server.server_close() + + def setUp(self): + Handler.hits.clear() + self.base = f"http://127.0.0.1:{self.port}" + self.p = R.Prober(delay=0, timeout=5) + + def hits_for(self, path): + return [h for h in Handler.hits if h[1] == path] + + def test_ok_uses_head_only(self): + row = self.p.probe(self.base + "/ok") + self.assertEqual(row["status"], 200) + self.assertEqual(row["method"], "HEAD") + self.assertEqual([h[0] for h in self.hits_for("/ok")], ["HEAD"]) + + def test_generic_user_agent_and_no_extra_headers(self): + self.p.probe(self.base + "/ok") + uas = {h[2] for h in Handler.hits} + self.assertEqual(uas, {R.USER_AGENT}) + self.assertNotIn("swaits", R.USER_AGENT.lower()) + self.assertNotIn("longhikes", R.USER_AGENT.lower()) + + def test_redirect_target_recorded(self): + row = self.p.probe(self.base + "/redir") + self.assertEqual(row["status"], 200) + self.assertEqual(row["final_url"], self.base + "/ok") + self.assertEqual(R.redirect_kind(self.base + "/slash", self.base + "/slash/"), "slash") + self.assertEqual(R.redirect_kind(self.base + "/redir", self.base + "/ok"), "path") + self.assertEqual(R.redirect_kind("http://a.org/x", "https://a.org/x"), "scheme") + self.assertEqual(R.redirect_kind("http://a.org/x", "http://a.org/x"), "") + + def test_head_refused_falls_back_to_get(self): + row = self.p.probe(self.base + "/headbad") + self.assertEqual(row["status"], 200) + self.assertEqual([h[0] for h in self.hits_for("/headbad")], ["HEAD", "GET"]) + + def test_not_found_is_an_error_not_a_refusal(self): + row = self.p.probe(self.base + "/gone") + self.assertEqual(row["status"], 404) + self.assertEqual(row["refused"], "") + + def test_refusal_is_recorded_and_never_retried(self): + row = self.p.probe(self.base + "/forbidden") + self.assertEqual(row["status"], 403) + self.assertEqual(row["refused"], "yes") + self.assertEqual(len(self.hits_for("/forbidden")), 1) + + def test_429_stops_the_whole_host(self): + row = self.p.probe(self.base + "/limited") + self.assertEqual(row["refused"], "yes") + after = self.p.probe(self.base + "/ok") + self.assertEqual(after["refused"], "host") + self.assertEqual(after["status"], "") + self.assertEqual(self.hits_for("/ok"), []) + self.assertEqual(len(self.hits_for("/limited")), 1) + + def test_challenge_page_counts_as_refusal(self): + # HEAD sees 200 with no body; the GET fallback is not tried, so make HEAD uninformative + # by calling the body check directly, as the GET path does + self.assertTrue(R.Prober.is_challenge({}, b"Just a moment...")) + self.assertTrue(R.Prober.is_challenge({"CF-Mitigated": "challenge"}, b"")) + self.assertFalse(R.Prober.is_challenge({}, b"Trail")) + + def test_robots_disallow_is_honoured(self): + row = self.p.probe(self.base + "/private") + self.assertEqual(row["refused"], "robots") + self.assertEqual(self.hits_for("/private"), []) + + def test_robots_txt_fetched_once_per_host(self): + self.p.probe(self.base + "/ok") + self.p.probe(self.base + "/gone") + self.assertEqual(len(self.hits_for("/robots.txt")), 1) + + def test_no_answer_is_an_error_row(self): + row = R.Prober(delay=0, timeout=2).probe("http://127.0.0.1:9/nothing") + self.assertEqual(row["status"], "") + self.assertTrue(row["error"]) + + def test_delay_between_requests_to_one_host(self): + slow = R.Prober(delay=0.15, timeout=5) + import time + t0 = time.monotonic() + slow.probe(self.base + "/ok") + slow.probe(self.base + "/gone") + self.assertGreaterEqual(time.monotonic() - t0, 0.3) # robots + two probes, spaced + + def test_links_command_writes_csv_once_per_address(self): + with tempfile.TemporaryDirectory() as tmp: + root = make_repo(tmp, trails=[("aaa", "Aaa Trail", {})]) + path = os.path.join(root, "aaa", "trail.toml") + text = read(root, "aaa/trail.toml").replace("https://example.org/aaa/permits", self.base + "/ok") + text = text.replace('official_url = "https://example.org/aaa/"', f'official_url = "{self.base}/ok"') + write(path, text) + d = os.path.join(tmp, "stage") + os.makedirs(d) + code, out = main(root, "--dir", d, "links", "--delay", "0", "--timeout", "2", + "--only-prefix", self.base) + self.assertEqual(code, 0, out) + with open(os.path.join(d, "links.csv"), newline="") as f: + rows = list(csv.DictReader(f)) + self.assertEqual([r["url"] for r in rows], [self.base + "/ok"]) + self.assertEqual(rows[0]["status"], "200") + self.assertIn("aaa", rows[0]["used_by"]) + self.assertEqual(len(self.hits_for("/ok")), 1) # used twice in the record, fetched once + + +# ----------------------------------------------------------------------------- collect and apply + +def propose(stage, worker, tid, body, files=None): + pdir = os.path.join(stage, "staged", worker, tid) + os.makedirs(pdir, exist_ok=True) + with open(os.path.join(pdir, "proposal.toml"), "w", encoding="utf-8") as f: + f.write(body) + for name, data in (files or {}).items(): + os.makedirs(os.path.dirname(os.path.join(pdir, name)), exist_ok=True) + with open(os.path.join(pdir, name), "w", encoding="utf-8") as f: + f.write(data) + return pdir + + +PERMIT_CHANGE = ''' +[[proposal]] +kind = "change" +id = "aaa" +date = "2026-11-30" +summary = "The permit sentence changed." + +[[proposal.edit]] +field = "hike.permit" +old = "No permit is needed." +new = "A free permit is needed from the ranger district." +page = "https://example.org/aaa/permits" +quote = "Hikers need a free permit from the ranger district." + +[proposal.history] +change = "The permit sentence now says a free permit is needed." +basis = "The club's permit page says a free permit is needed." +basis_url = "https://example.org/aaa/permits" +asked_by = "the dataset's own check" +''' + + +class CollectTest(Tmp): + def collect(self): + code, out = main(self.root, "--dir", self.d, "collect") + return code, out + + def collected(self): + return tomllib.loads(read(self.d, "collected.toml")) + + def test_empty_staging_directory(self): + code, out = self.collect() + self.assertEqual(code, 0, out) + self.assertIn("0 proposals", out) + self.assertIn("No proposals are staged", read(self.d, "summary.md")) + + def test_missing_staging_directory_is_an_error_message(self): + code, out = main(self.root, "--dir", os.path.join(self.tmp, "nope"), "collect") + self.assertEqual(code, 2) + self.assertIn("preflight", out) + + def test_valid_change_is_collected_with_digest(self): + propose(self.d, "trails-01", "aaa", PERMIT_CHANGE) + code, out = self.collect() + self.assertEqual(code, 0, out) + p = self.collected()["proposal"][0] + self.assertEqual(p["pid"], "trails-01:aaa:1") + self.assertEqual(p["status"], "proposed") + self.assertEqual(len(p["digest"]), 10) + s = read(self.d, "summary.md") + self.assertIn("hike.permit", s) + self.assertIn("Hikers need a free permit", s) + self.assertIn("https://example.org/aaa/permits", s) + + def test_fact_change_needs_history(self): + body = PERMIT_CHANGE.split("[proposal.history]")[0] + propose(self.d, "trails-01", "aaa", body) + code, out = self.collect() + self.assertEqual(code, 1) + self.assertIn("needs [proposal.history]", out) + + def test_non_fact_change_needs_no_history(self): + body = ''' +[[proposal]] +kind = "change" +id = "aaa" +date = "2026-11-30" +summary = "Reword." + +[[proposal.edit]] +field = "hike.summary" +old = "Runs north to south. See https://example.org/aaa/about." +new = "Runs north to south." +page = "https://example.org/aaa/" +quote = "The trail runs north to south." +''' + propose(self.d, "trails-01", "aaa", body) + self.assertEqual(self.collect()[0], 0) + + def test_edit_needs_page_and_quote_and_known_field(self): + body = PERMIT_CHANGE.replace('quote = "Hikers need a free permit from the ranger district."\n', "") + body = body.replace('field = "hike.permit"', 'field = "hike.permitt"') + propose(self.d, "trails-01", "aaa", body) + code, out = self.collect() + self.assertEqual(code, 1) + self.assertIn("quote is required", out + read(self.d, "summary.md")) + self.assertIn("not a field of the record", read(self.d, "summary.md")) + + def test_unknown_kind_and_bad_toml(self): + propose(self.d, "trails-01", "aaa", '[[proposal]]\nkind = "fix"\nid = "aaa"\n') + propose(self.d, "trails-01", "bbb", "this is not toml") + code, out = self.collect() + self.assertEqual(code, 1) + text = read(self.d, "summary.md") + self.assertIn("kind must be one of", text) + self.assertIn("does not parse", text) + + def test_report_rules(self): + os.makedirs(os.path.join(self.d, "staged", "trails-01")) + with open(os.path.join(self.d, "staged", "trails-01", "report.csv"), "w", newline="") as f: + w = csv.writer(f) + w.writerow(R.REPORT_COLUMNS) + w.writerow(["aaa", "verified", "https://example.org/aaa/", ""]) + w.writerow(["bbb", "could-not-check", "", ""]) + w.writerow(["ccc", "bogus", "x", "y"]) + os.makedirs(os.path.join(self.d, "slices")) + write(os.path.join(self.d, "slices", "trails-01.txt"), "aaa\nbbb\nccc\nddd\n") + code, out = self.collect() + self.assertEqual(code, 1) + text = out + read(self.d, "summary.md") + self.assertIn("needs pages", text) + self.assertIn("needs a remark", text) + self.assertIn("outcome 'bogus'", text) + self.assertIn("ddd", read(self.d, "summary.md")) # not reported + self.assertIn("reported verified but has no `verified` proposal", read(self.d, "summary.md")) + self.assertIn("## Could not check", read(self.d, "summary.md")) + + def test_verified_with_cited_pages_missing_is_a_warning(self): + os.makedirs(os.path.join(self.d, "staged", "trails-01")) + with open(os.path.join(self.d, "staged", "trails-01", "report.csv"), "w", newline="") as f: + w = csv.writer(f) + w.writerow(R.REPORT_COLUMNS) + w.writerow(["aaa", "verified", "http://www.example.org/aaa", ""]) + body = (''' +[[proposal]] +kind = "verified" +id = "aaa" +date = "2026-11-30" +summary = "Nothing changed." +pages = ["https://example.org/aaa/"] +''') + propose(self.d, "trails-01", "aaa", body) + self.collect() + text = read(self.d, "summary.md") + self.assertIn("aaa: 1 of 2 cited pages are not listed as opened", text) + self.assertIn("example.org/aaa/permits", text) + + def test_not_found_must_say_where_it_looked(self): + os.makedirs(os.path.join(self.d, "staged", "region-x")) + with open(os.path.join(self.d, "staged", "region-x", "report.csv"), "w", newline="") as f: + w = csv.writer(f) + w.writerow(R.REPORT_COLUMNS) + w.writerow(["Idaho", "not-found", "", "nothing"]) + code, out = self.collect() + self.assertEqual(code, 1) + self.assertIn("needs pages", out + read(self.d, "summary.md")) + + def test_decisions_and_digest(self): + propose(self.d, "trails-01", "aaa", PERMIT_CHANGE) + self.collect() + digest = self.collected()["proposal"][0]["digest"] + os.makedirs(os.path.join(self.d, "review")) + path = os.path.join(self.d, "review", "r1.csv") + + def write(rows): + with open(path, "w", newline="") as f: + w = csv.writer(f) + w.writerow(("pid", "digest", "decision", "note")) + w.writerows(rows) + + write([("trails-01:aaa:1", digest, "accept", "page says so")]) + self.collect() + self.assertEqual(self.collected()["proposal"][0]["status"], "accepted") + write([("trails-01:aaa:1", "deadbeef00", "accept", "")]) + self.collect() + self.assertEqual(self.collected()["proposal"][0]["status"], "proposed") + self.assertIn("proposal changed after review", read(self.d, "summary.md")) + write([("trails-01:aaa:1", digest, "accept", "")]) + with open(os.path.join(self.d, "review", "r2.csv"), "w", newline="") as f: + f.write(f"pid,digest,decision,note\ntrails-01:aaa:1,{digest},reject,quote not on page\n") + self.collect() + self.assertEqual(self.collected()["proposal"][0]["status"], "rejected") + with open(os.path.join(self.d, "owner.csv"), "w", newline="") as f: + f.write(f"pid,digest,decision,note\ntrails-01:aaa:1,{digest},accept,owner agreed\n") + self.collect() + self.assertEqual(self.collected()["proposal"][0]["status"], "accepted") + + def test_new_record_checks(self): + body = ''' +[[proposal]] +kind = "new-record" +id = "ddd" +date = "2026-11-30" +summary = "A new trail." +basis_url = "https://example.org/ddd/" +''' + propose(self.d, "region-1", "ddd", body, {"trail.toml": record("ddd", "Ddd Trail")}) + self.assertEqual(self.collect()[0], 0) + propose(self.d, "region-2", "aaa", body.replace('"ddd"', '"aaa"'), {"trail.toml": record("aaa", "Aaa")}) + code, out = self.collect() + self.assertEqual(code, 1) + self.assertIn("already exists in the repository", read(self.d, "summary.md")) + + def test_new_record_still_in_left_out_needs_removal(self): + body = ''' +[[proposal]] +kind = "new-record" +id = "gamma-trail" +date = "2026-11-30" +summary = "Gamma is now a trail." +basis_url = "https://example.org/gamma" +''' + propose(self.d, "region-1", "gamma-trail", body, {"trail.toml": record("gamma-trail", "Gamma Trail")}) + self.collect() + self.assertIn("needs a left-out-remove proposal", read(self.d, "summary.md")) + + def test_candidates_and_duplicates_are_listed(self): + body = ''' +[[proposal]] +kind = "candidate" +id = "delta-trail" +date = "2026-11-30" +name = "Delta Trail" +country = "US" +regions = ["OR"] +length_mi = 55 +source_url = "https://example.org/delta" +recommendation = "owner" +borderline = true +summary = "Delta might be a network." +''' + propose(self.d, "region-1", "delta-trail", body) + self.assertEqual(self.collect()[0], 0) + self.assertIn("| Delta Trail |", read(self.d, "summary.md")) + + +class ApplyTest(Tmp): + def stage_and_accept(self, worker, tid, body, files=None, accept=True): + propose(self.d, worker, tid, body, files) + + def collect_accept_all(self): + code, out = main(self.root, "--dir", self.d, "collect") + self.assertEqual(code, 0, out) + coll = tomllib.loads(read(self.d, "collected.toml")) + os.makedirs(os.path.join(self.d, "review"), exist_ok=True) + with open(os.path.join(self.d, "review", "r.csv"), "w", newline="") as f: + w = csv.writer(f) + w.writerow(("pid", "digest", "decision", "note")) + for p in coll["proposal"]: + if p["kind"] in R.APPLIED_KINDS: + w.writerow((p["pid"], p["digest"], "accept", "")) + code, out = main(self.root, "--dir", self.d, "collect") + self.assertEqual(code, 0, out) + + def apply(self, *extra): + return main(self.root, "--dir", self.d, "apply", *extra) + + def rec(self, tid): + return tomllib.loads(read(self.root, f"{tid}/trail.toml")) + + def test_edit_changes_one_line_and_adds_history(self): + before = read(self.root, "aaa/trail.toml") + propose(self.d, "trails-01", "aaa", PERMIT_CHANGE) + self.collect_accept_all() + code, out = self.apply() + self.assertEqual(code, 0, out) + after = read(self.root, "aaa/trail.toml") + old_lines, new_lines = before.split("\n"), after.split("\n") + removed = [l for l in old_lines if l not in new_lines] + self.assertEqual(removed, ['permit = "No permit is needed."']) + added = [l for l in new_lines if l not in old_lines] + self.assertIn('permit = "A free permit is needed from the ranger district."', added) + self.assertEqual(new_lines.count("[[history]]"), 2) + # hand formatting survives: comment after start, header comments + self.assertIn('start = "North Gap" # as the club writes it', after) + self.assertIn("# History of this record, oldest first.", after) + rec = self.rec("aaa") + self.assertEqual(rec["hike"]["permit"], "A free permit is needed from the ranger district.") + entry = rec["history"][-1] + self.assertEqual(entry["date"], TODAY) + self.assertEqual(entry["fields"], ["hike.permit"]) + self.assertEqual(entry["outcome"], "applied") + self.assertEqual(entry["asked_by"], "the dataset's own check") + errors = [] + H.check_entries("aaa", rec, errors) + self.assertEqual(errors, []) + + def test_only_accepted_proposals_apply(self): + propose(self.d, "trails-01", "aaa", PERMIT_CHANGE) + main(self.root, "--dir", self.d, "collect") + before = read(self.root, "aaa/trail.toml") + code, out = self.apply() + self.assertEqual(code, 0) + self.assertEqual(read(self.root, "aaa/trail.toml"), before) + + def test_refuses_when_old_value_no_longer_matches(self): + propose(self.d, "trails-01", "aaa", PERMIT_CHANGE) + self.collect_accept_all() + path = os.path.join(self.root, "aaa", "trail.toml") + text = read(self.root, "aaa/trail.toml").replace("No permit is needed.", "Permits are free.") + write(path, text) + code, out = self.apply() + self.assertEqual(code, 1) + self.assertIn("not the proposal's old value", out) + self.assertEqual(read(self.root, "aaa/trail.toml"), text) + self.assertIn("refused", read(self.d, "apply-log.csv")) + + def test_second_run_says_already_applied(self): + propose(self.d, "trails-01", "aaa", PERMIT_CHANGE) + self.collect_accept_all() + self.apply() + once = read(self.root, "aaa/trail.toml") + code, out = self.apply() + self.assertEqual(code, 0, out) + self.assertIn("already applied", out) + self.assertEqual(read(self.root, "aaa/trail.toml"), once) + + def test_refuses_when_proposal_changed_after_collect(self): + propose(self.d, "trails-01", "aaa", PERMIT_CHANGE) + self.collect_accept_all() + propose(self.d, "trails-01", "aaa", PERMIT_CHANGE.replace("A free permit", "A paid permit")) + before = read(self.root, "aaa/trail.toml") + code, out = self.apply() + self.assertEqual(code, 1) + self.assertIn("changed after it was collected", out) + self.assertEqual(read(self.root, "aaa/trail.toml"), before) + + def test_dry_run_writes_nothing(self): + propose(self.d, "trails-01", "aaa", PERMIT_CHANGE) + self.collect_accept_all() + before = read(self.root, "aaa/trail.toml") + code, out = self.apply("--dry-run") + self.assertEqual(code, 0) + self.assertIn("would apply", out) + self.assertEqual(read(self.root, "aaa/trail.toml"), before) + + def test_add_remove_and_array_edits(self): + body = ''' +[[proposal]] +kind = "change" +id = "aaa" +date = "2026-11-30" +summary = "Add a caution, drop the permit, change a source, add a source and a link." + +[[proposal.edit]] +field = "hike.caution" +new = "Most of the trail has no water." +page = "https://example.org/aaa/" +quote = "There is no water on most of the trail." + +[[proposal.edit]] +field = "hike.permit" +old = "No permit is needed." +page = "https://example.org/aaa/permits" +quote = "The page no longer mentions a permit." + +[[proposal.edit]] +field = "hike.source[1].facts" +old = ["permit"] +new = ["permit", "caution"] +page = "https://example.org/aaa/permits" +quote = "x" + +[[proposal.edit]] +field = "length_km" +old = 100 +new = 105 +page = "https://example.org/aaa/" +quote = "65 miles" + +[[proposal.append]] +table = "hike.source" +page = "https://example.org/aaa/water" +quote = "There is no water on most of the trail." +[proposal.append.entry] +url = "https://example.org/aaa/water" +publisher = "Example Club" +facts = ["caution"] + +[[proposal.append]] +table = "link" +page = "https://example.org/aaa/more" +quote = "More about the trail" +[proposal.append.entry] +title = "More" +publisher = "Another Club" +url = "https://example.org/aaa/more" + +[proposal.history] +change = "The caution was added, the permit sentence removed and the length changed." +basis = "The club's pages say so." +basis_url = "https://example.org/aaa/" +asked_by = "a hiker" +''' + propose(self.d, "trails-01", "aaa", body) + self.collect_accept_all() + code, out = self.apply() + self.assertEqual(code, 0, out) + rec = self.rec("aaa") + self.assertEqual(rec["hike"]["caution"], "Most of the trail has no water.") + self.assertNotIn("permit", rec["hike"]) + self.assertEqual(rec["hike"]["source"][1]["facts"], ["permit", "caution"]) + self.assertEqual(rec["length_km"], 105) + self.assertEqual([s["url"] for s in rec["hike"]["source"]][-1], "https://example.org/aaa/water") + self.assertEqual([x["url"] for x in rec["link"]][-1], "https://example.org/aaa/more") + self.assertEqual(len(rec["history"]), 2) + self.assertEqual(rec["history"][-1]["fields"], + ["hike.caution", "hike.permit", "hike.source.facts", "length_km", + "hike.source", "link"]) + text = read(self.root, "aaa/trail.toml") + # the new link block sits after the old one and before the history comment + self.assertLess(text.index("https://en.wikipedia.org/wiki/aaa"), text.index("https://example.org/aaa/more")) + self.assertLess(text.index("https://example.org/aaa/more"), text.index("# History of this record")) + self.assertLess(text.index("https://example.org/aaa/permits"), text.index("https://example.org/aaa/water")) + + def test_edit_in_a_record_without_the_table_is_refused(self): + body = PERMIT_CHANGE.replace('id = "aaa"', 'id = "ccc"') + propose(self.d, "trails-01", "ccc", body) + self.collect_accept_all() + code, out = self.apply() + self.assertEqual(code, 1) + self.assertIn("ccc", out) + + def test_verified_sets_checked_date(self): + body = ''' +[[proposal]] +kind = "verified" +id = "aaa" +date = "2026-11-30" +summary = "Nothing changed." +pages = ["https://example.org/aaa/", "https://example.org/aaa/permits"] + +[[proposal]] +kind = "verified" +id = "ccc" +date = "2026-11-30" +summary = "Nothing changed." +pages = ["https://example.org/ccc/data"] +''' + propose(self.d, "trails-01", "aaa", body.split("[[proposal]]")[1].join(["[[proposal]]", ""])) + propose(self.d, "trails-01", "ccc", "[[proposal]]" + body.split("[[proposal]]")[2]) + self.collect_accept_all() + code, out = self.apply() + self.assertEqual(code, 0, out) + self.assertEqual(self.rec("aaa")["hike"]["checked"], "2026-11-30") + self.assertEqual(len(self.rec("aaa")["history"]), 1) # not a fact: no history entry + self.assertEqual(self.rec("ccc")["source"]["source_checked"], "2026-11-30") + + def test_declined_adds_only_a_history_entry(self): + body = ''' +[[proposal]] +kind = "declined" +id = "aaa" +date = "2026-11-30" +summary = "A request to change the length lost to the holder's page." + +[proposal.history] +change = "A request for 70 miles was not applied." +basis = "The club's own page gives 62 miles." +basis_url = "https://example.org/aaa/" +asked_by = "a hiker" +fields = ["length_km", "length_note"] +''' + propose(self.d, "trails-01", "aaa", body) + self.collect_accept_all() + before = read(self.root, "aaa/trail.toml") + code, out = self.apply() + self.assertEqual(code, 0, out) + after = read(self.root, "aaa/trail.toml") + self.assertTrue(after.startswith(before.rstrip("\n"))) + self.assertEqual(self.rec("aaa")["history"][-1]["outcome"], "declined") + + def test_left_out_add_keeps_order_remove_and_change(self): + add = ''' +[[proposal]] +kind = "left-out-add" +id = "beta-trail" +date = "2026-11-30" +summary = "Beta is below the floor." +basis_url = "https://example.org/beta" + +[proposal.entry] +id = "beta-trail" +name = "Beta Trail" +country = "US" +regions = ["NY"] +reason = "below-floor" +note = "It is 30 miles." +decided = "2026-11-30" +was_listed = false +''' + change = ''' +[[proposal]] +kind = "change" +target = "left-out" +id = "gamma-trail" +date = "2026-11-30" +summary = "Gamma still waits." + +[[proposal.edit]] +field = "note" +old = "Not yet one trail." +new = "Still not one trail." +page = "https://example.org/gamma" +quote = "x" +''' + remove = ''' +[[proposal]] +kind = "left-out-remove" +id = "alpha-trail" +date = "2026-11-30" +summary = "Alpha is now a record." +why = "It is listed." +basis_url = "https://example.org/alpha" +''' + propose(self.d, "left-out-01", "beta-trail", add) + propose(self.d, "left-out-01", "gamma-trail", change) + propose(self.d, "left-out-01", "alpha-trail", remove) + self.collect_accept_all() + code, out = self.apply() + self.assertEqual(code, 0, out) + doc = tomllib.loads(read(self.root, "left-out.toml")) + self.assertEqual([e["id"] for e in doc["trail"]], ["beta-trail", "gamma-trail"]) + self.assertEqual(doc["trail"][1]["note"], "Still not one trail.") + text = read(self.root, "left-out.toml") + self.assertTrue(text.startswith("# Left out. Entries are sorted by name.")) + self.assertNotIn("\n\n\n", text) + + def test_left_out_add_in_the_middle_and_at_the_end(self): + def add(tid, name): + return f''' +[[proposal]] +kind = "left-out-add" +id = "{tid}" +date = "2026-11-30" +summary = "x" +basis_url = "https://example.org/x" + +[proposal.entry] +id = "{tid}" +name = "{name}" +country = "US" +regions = ["NY"] +reason = "below-floor" +note = "It is 30 miles." +decided = "2026-11-30" +was_listed = false +''' + propose(self.d, "left-out-01", "beta-trail", add("beta-trail", "Beta Trail")) + propose(self.d, "left-out-01", "zeta-trail", add("zeta-trail", "Zeta Trail")) + propose(self.d, "left-out-01", "a-first", add("a-first", "A First Trail")) + self.collect_accept_all() + code, out = self.apply() + self.assertEqual(code, 0, out) + ids = [e["id"] for e in tomllib.loads(read(self.root, "left-out.toml"))["trail"]] + self.assertEqual(ids, ["a-first", "alpha-trail", "beta-trail", "gamma-trail", "zeta-trail"]) + + def test_new_record_is_copied_without_the_proposal_file(self): + body = ''' +[[proposal]] +kind = "new-record" +id = "ddd" +date = "2026-11-30" +summary = "A new trail." +basis_url = "https://example.org/ddd/" +''' + propose(self.d, "region-1", "ddd", body, {"trail.toml": record("ddd", "Ddd Trail"), "shield.png": "png"}) + self.collect_accept_all() + code, out = self.apply() + self.assertEqual(code, 0, out) + self.assertEqual(sorted(os.listdir(os.path.join(self.root, "ddd"))), ["shield.png", "trail.toml"]) + code, out = self.apply() # the directory now exists + self.assertEqual(code, 1) + self.assertIn("already exists", out) + + def test_file_operations_need_matching_hash(self): + import hashlib + os.makedirs(os.path.join(self.root, "aaa"), exist_ok=True) + with open(os.path.join(self.root, "aaa", "shield.png"), "w") as f: + f.write("old logo") + good = hashlib.sha256(b"old logo").hexdigest() + body = f''' +[[proposal]] +kind = "change" +id = "aaa" +date = "2026-11-30" +summary = "A better logo." + +[[proposal.file]] +to = "shield.png" +from = "files/shield.png" +old_sha256 = "{good}" +source_url = "https://example.org/aaa/logo" + +[proposal.history] +change = "The logo was replaced." +basis = "The club's page shows this emblem." +basis_url = "https://example.org/aaa/logo" +asked_by = "the dataset's own check" +''' + propose(self.d, "emblems-1", "aaa", body, {"files/shield.png": "new logo"}) + self.collect_accept_all() + code, out = self.apply() + self.assertEqual(code, 0, out) + self.assertEqual(read(self.root, "aaa/shield.png"), "new logo") + self.assertEqual(self.rec("aaa")["history"][-1]["fields"], ["shield.logo_file"]) + # a second proposal against the same old hash is now stale + stale = body.replace("A better logo.", "Another logo.") + propose(self.d, "emblems-2", "aaa", stale, {"files/shield.png": "third"}) + self.collect_accept_all() + code, out = self.apply("--only", "emblems-2:aaa:1") + self.assertEqual(code, 1) + self.assertIn("sha256 differs", out) + self.assertEqual(read(self.root, "aaa/shield.png"), "new logo") + + def test_target_file_name_is_limited(self): + body = ''' +[[proposal]] +kind = "change" +id = "aaa" +date = "2026-11-30" +summary = "Bad." + +[[proposal.file]] +to = "../escape.txt" +from = "x.png" +source_url = "https://example.org/" + +[proposal.history] +change = "x" +basis = "x" +basis_url = "https://example.org/" +asked_by = "a hiker" +''' + propose(self.d, "emblems-1", "aaa", body, {"x.png": "x"}) + code, out = main(self.root, "--dir", self.d, "collect") + self.assertEqual(code, 1) + self.assertIn("to must be", read(self.d, "summary.md")) + + +class DocTest(unittest.TestCase): + def test_comment_after_value_is_kept(self): + d = R.Doc('[hike]\nstart = "A # B" # note\nend = "C"\n') + span = d.span("hike") + d.set_value(span, "start", "D", "A # B", True) + self.assertEqual(d.text(), '[hike]\nstart = "D" # note\nend = "C"\n') + + def test_new_key_goes_after_last_key_of_its_table(self): + d = R.Doc('[hike]\nstart = "A"\n\n# a comment\n[other]\nx = 1\n') + d.set_value(d.span("hike"), "end", "B", None, False) + self.assertEqual(d.text(), '[hike]\nstart = "A"\nend = "B"\n\n# a comment\n[other]\nx = 1\n') + + def test_multiline_value_is_refused(self): + d = R.Doc('[hike]\nterrain = [\n "a",\n]\n') + with self.assertRaises(R.RefreshError): + d.set_value(d.span("hike"), "terrain", ["b"], ["a"], True) + + def test_dump_toml_round_trip(self): + doc = {"a": 1, "s": 'q"uote\nnew', "l": ["x", "y"], "t": {"k": True}, + "arr": [{"n": 1, "sub": {"z": 2.5}}, {"n": 2}]} + self.assertEqual(tomllib.loads(R.dump_toml(doc)), doc) + + def test_scalar_non_ascii_is_kept(self): + self.assertEqual(R._scalar("Dän"), '"Dän"') + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_refresh_skill.py b/tools/tests/test_refresh_skill.py new file mode 100644 index 0000000..4fbaf8a --- /dev/null +++ b/tools/tests/test_refresh_skill.py @@ -0,0 +1,140 @@ +"""Tests that the refresh runbook is whole: the skill's frontmatter parses, every file it +points to exists, the briefs point at the shared rules, the examples in the proposal format +are valid proposals, the commands it names exist, and the text keeps the house wording. + +Run from the repository root: + python3 -m unittest discover tools/tests +""" +import os +import re +import sys +import tomllib +import unittest + +sys.dont_write_bytecode = True +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import refresh as R # noqa: E402 + +SKILL_DIR = os.path.join(R.ROOT, ".claude", "skills", "refresh-trails") +BRIEFS = ("verify-records", "recheck-left-out", "find-missing-trails", "find-routes", "tracks", + "emblems", "review", "apply") + + +def text_of(*parts): + with open(os.path.join(SKILL_DIR, *parts), encoding="utf-8") as f: + return f.read() + + +def frontmatter(text): + m = re.match(r"^---\n(.*?)\n---\n", text, re.S) + assert m, "no frontmatter" + out = {} + for line in m.group(1).split("\n"): + k, _, v = line.partition(":") + out[k.strip()] = v.strip().strip('"') + return out + + +def all_docs(): + names = ["SKILL.md", "rules.md", "records.md", "proposal-format.md"] + [f"briefs/{b}.md" for b in BRIEFS] + return {n: text_of(*n.split("/")) for n in names} + + +class SkillTest(unittest.TestCase): + def test_frontmatter(self): + fm = frontmatter(text_of("SKILL.md")) + self.assertEqual(fm["name"], "refresh-trails") + self.assertEqual(os.path.basename(SKILL_DIR), fm["name"]) + self.assertGreater(len(fm["description"]), 60) + self.assertIn("Use when", fm["description"]) + + def test_every_file_it_points_to_exists(self): + skill = text_of("SKILL.md") + for rel in sorted(set(re.findall(r"`((?:briefs/)?[a-z\-]+\.md)`", skill))): + self.assertTrue(os.path.isfile(os.path.join(SKILL_DIR, rel)), rel) + for b in BRIEFS: + self.assertIn(f"briefs/{b}.md", skill) + self.assertTrue(os.path.isfile(os.path.join(SKILL_DIR, "briefs", b + ".md"))) + for n, t in all_docs().items(): + base = os.path.dirname(os.path.join(SKILL_DIR, n)) + for rel in set(re.findall(r"`(\.\./[a-z\-]+\.md)`", t)): + self.assertTrue(os.path.isfile(os.path.normpath(os.path.join(base, rel))), f"{n}: {rel}") + + def test_repository_files_it_names_exist(self): + for n, t in all_docs().items(): + for rel in set(re.findall(r"`((?:tools|docs|web)/[A-Za-z0-9_./\-]+\.(?:py|md))`", t)): + self.assertTrue(os.path.isfile(os.path.join(R.ROOT, rel)), f"{n}: {rel}") + for rel in ("README.md", "CONTRIBUTING.md", "left-out.toml", "CHANGELOG.md", "SOURCES.md"): + self.assertTrue(os.path.isfile(os.path.join(R.ROOT, rel))) + + def test_briefs_point_at_the_shared_files(self): + for b in BRIEFS: + t = text_of("briefs", b + ".md") + self.assertTrue("../rules.md" in t, b) + self.assertTrue("../proposal-format.md" in t, b) + self.assertTrue(t.startswith("# "), b) + self.assertTrue("## What this is for" in t, b) + self.assertTrue("## Report" in t, b) + + def test_phases_are_in_order(self): + skill = text_of("SKILL.md") + found = re.findall(r"^\*\*(\d)\. ", skill, re.M) + self.assertEqual(found, [str(i) for i in range(10)]) + self.assertIn("light", skill.lower()) + + def test_commands_named_exist(self): + parser = R.build_parser() + names = set(parser._subparsers._group_actions[0].choices) + skill = text_of("SKILL.md") + for cmd in re.findall(r"tools/refresh\.py (\w+)", skill + text_of("briefs", "apply.md")): + self.assertIn(cmd, names) + self.assertEqual(names, {"preflight", "slices", "links", "collect", "apply"}) + + def test_staging_is_ignored_by_git(self): + with open(os.path.join(R.ROOT, ".gitignore"), encoding="utf-8") as f: + lines = [l.strip() for l in f] + self.assertIn("/refresh/", lines) + + def test_examples_in_the_proposal_format_are_valid(self): + doc = text_of("proposal-format.md") + blocks = re.findall(r"```toml\n(.*?)```", doc, re.S) + self.assertGreaterEqual(len(blocks), 2) + kinds = set() + for block in blocks: + data = tomllib.loads(block) + for p in data["proposal"]: + kinds.add(p["kind"]) + self.assertEqual(R.validate_proposal(p, {}), [], p) + self.assertTrue({"verified", "change"} <= kinds) + + def test_every_kind_and_outcome_is_documented(self): + doc = text_of("proposal-format.md") + for kind in R.KINDS: + self.assertIn(f"`{kind}`", doc) + for outcome in R.OUTCOMES: + if outcome != "not-found-emblem": + self.assertIn(f"`{outcome}`", doc) + + def test_house_wording(self): + for n, t in all_docs().items(): + body = re.sub(r"```.*?```", "", t, flags=re.S) + self.assertNotIn("—", body, f"{n}: em dash") + self.assertNotIn("–", body, f"{n}: en dash") + self.assertIsNone(re.search(r"\S - \S", body), f"{n}: dash used as punctuation") + for word in ("MUST", "NEVER", "ALWAYS", "CRITICAL", "IMPORTANT"): + self.assertIsNone(re.search(rf"\b{word}\b", body), f"{n}: {word}") + self.assertNotRegex(body, r"(?i)you are an? (expert|senior|world)") + self.assertNotRegex(body, r"/tmp/|/home/") + self.assertNotRegex(body, r"(?i)\bpurple\b|\bphrp\b") + + def test_briefs_that_may_start_a_process_forbid_killing_by_name(self): + rules = text_of("rules.md") + self.assertIn("pkill", rules) + self.assertIn("killall", rules) + for b in BRIEFS: + self.assertIn("../rules.md", text_of("briefs", b + ".md")) + + +if __name__ == "__main__": + unittest.main()