diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc index 29f28899..0dec532e 100644 --- a/CHANGELOG.adoc +++ b/CHANGELOG.adoc @@ -10,6 +10,13 @@ https://semver.org/spec/v2.0.0.html[Semantic Versioning]. ==== Fixed +* **A repository named `../..` is no longer accepted.** The census, the claims + registry, engineering receipts and the ultraplan each checked `OWNER/REPO` + with a pattern like `[-\w.]+/[-\w.]+`, which accepts dot segments. A + github.com link made from such a name resolves, in a browser, to some other + page. All of them now use one rule, GitHub's own, in `scripts/repo/github.mjs`: + a login (single hyphens only, none at either end), then a repository name + that is not dots alone. Every name in the current data passes it. * **A `CI/gate` publisher may not filter `workflow_run` by branch.** GitHub applies `branches` and `branches-ignore` to the triggering run's branch, so a filtered publisher never posts the status on a PR head and the @@ -72,6 +79,65 @@ https://semver.org/spec/v2.0.0.html[Semantic Versioning]. ==== Added +* **The ultraplan: a tech tree of Mathesis, data first.** `docs/ultraplan/` + holds three JCS JSON Lines files: + ** `tree.jsonl`, the nodes, whose needs are the edges; + ** `advisors.jsonl`, the council; + ** `expeditions.jsonl`, the return tickets. ++ + `scripts/ultraplan/ultraplan.mjs` generates `generated/ultraplan.adoc` and a + picture, `generated/tree.svg`. They show the eras, the frontier, the forks, + the confluences and each advisor's pick (the private me advisor names none), all + derived and none typed. ++ + The generator refuses: + ** a done node without evidence that holds: a file that git tracks, a claim + grade the registry derives, or an accepted ADR. Every file the checks read + (evidence, refs, ADRs, the registry view and the plan's own sources) is + one git tracks, at its own path: no link along it, nothing untracked, + nothing in `.git`, and valid UTF-8 (a malformed byte is an error, never + a silent U+FFFD). `scripts/repo/files.mjs` reads them, so a clone and + a linked worktree read the same; An ADR is accepted only when its + header states `:status: ACCEPTED` and its Status section agrees (owner + ruling 2026-11-25), each read by `scripts/decisions/adr-status.mjs` so + that it never finds a status Asciidoctor would not. A record holding an + inline reference that changes an attribute (`{set:...}`, `{counter:...}` + or `{counter2:...}`; a counter turns ACCEPTED into ACCEPTEE) has no + readable header. `just adr-check` reads the records git tracks, each at + its own path, and fails when `docs/decisions` is a link. A record whose + status the readers refuse fails the check; only a record that states no + status at all is listed as unset; + ** a done node whose needs are not done, and a node still in play that needs + a dropped node (it could never start); + ** a cycle; + ** more than three active nodes; + ** a ref that does not point at one place: each names a passage that occurs + exactly once in a file here, a path here, a file of another repository at + a full commit, or an issue, and never a line number; + ** a text the page could not show as written: one holding a control + character, a line or paragraph separator (U+2028, U+2029), a + bidirectional formatting control, a run of + spaces, or a space at its start or end. Every text is plain text (owner + ruling 2026-11-25): the page writes each ASCII punctuation mark in it as a + character reference, so it shows exactly as written and forms no markup; + ** any note from the private me advisor. ++ + `just ultraplan` and `just ultraplan-check` run it, and `check-views` includes + the check. A line not in JCS form is named with the command that writes its + form; no error message echoes a record. The site copies a view's pictures, + so the tree's image works there. +* **The site reads nothing from outside the repository.** `scripts/site/site.mjs` + reads each view, the front page's sources and each asset it copies only as a + file git tracks, at its own path, and fails the build otherwise. Asciidoctor + now runs in secure mode, so an `include::` in a view becomes a link, which + the link check refuses, instead of the included file's text: in safe mode, + with the base directory at `/`, a view could include any file on the + system. The output is otherwise byte-identical. A link to a repository file + becomes a GitHub link only when git tracks the file. The build writes only + into a fresh output directory (absent, or empty and not a link), so a link + left in an old output tree cannot make it overwrite a file elsewhere. + `site-check` now runs the site tests, so CI runs them; it did not before. + * The 27 `hyperpolymath/resource-algebra` claims move their pin to `a17ffb6` (2026-11-17), whose receipt describes `47de4a8`, the merge of hyperpolymath/resource-algebra#36. F-5 now names `maps-disagree-at-positive`, diff --git a/Justfile b/Justfile index b9034c19..7419326c 100644 --- a/Justfile +++ b/Justfile @@ -712,7 +712,7 @@ check: check-views site-check check-proofs receipt-check # Needs bun, network for the receipts, and MATHESIS_STANDARDS (see `registry`). # Views current: catalogue, census tests, atlas, claims registry, bridges and # the worked cohort examples -check-views: catalogue-check census-test atlas-check registry-check applied-check +check-views: catalogue-check census-test atlas-check registry-check applied-check ultraplan-check adr-check repo-files-test # Needs agda, coqc and lean, e.g. in the pinned Guix: # guix time-machine -C build/channels.scm -- shell -m build/manifest.scm -- just check-proofs @@ -797,6 +797,32 @@ applied-check: bun scripts/applied/cohort.mjs check bun test tests/applied/ +# Regenerate the ultraplan (the tech tree of Mathesis) from docs/ultraplan/*.jsonl: +# the page docs/ultraplan/generated/ultraplan.adoc and its picture tree.svg +ultraplan: + bun scripts/ultraplan/ultraplan.mjs build + +# Fail if the ultraplan views are stale, or the tree's data is not sound: an unknown +# or cyclic need, a done node without evidence that holds, too many active nodes. +# Claim evidence is read from the registry view, so registry-check runs first: a +# stale view would let a done node rest on a grade the receipts no longer give. +ultraplan-check: registry-check + bun scripts/ultraplan/ultraplan.mjs check + bun test tests/ultraplan/ + +# Test what the generators may read from the repository: a file that git tracks, +# at its own path, with no link along it (scripts/repo/files.mjs). The ultraplan's +# evidence and the site's views and assets are read only so. +repo-files-test: + bun test tests/repo/ + +# Fail if a decision record's header status (`:status:`) and its Status section +# disagree, or only one of them states a status (owner ruling 2026-11-25). A +# record that states neither is listed, for the owner to set. +adr-check: + bun scripts/decisions/adr-status.mjs check + bun test tests/decisions/ + # ── mathesis: static site of the generated views (re-anchoring plan WO 4.3) ── # Build the site into OUT (default: a fresh temp dir; never a tracked path). @@ -805,15 +831,16 @@ applied-check: site out="": bun scripts/site/site.mjs build {{out}} -# Build the site into a temp dir, then discard it. `check` runs this, so CI -# builds the site on every pull request and push to main. -site-check: +# Test the site, then build it into a temp dir and discard it. `check` runs +# this, so CI tests and builds the site on every pull request and push to main. +site-check: site-test #!/usr/bin/env bash set -euo pipefail out="$(mktemp -d)" trap 'rm -rf "$out"' EXIT bun scripts/site/site.mjs build "$out" -# Test the front-page generator and the link check (no asciidoctor needed) +# Test the front page, the link check, and that the build reads nothing from +# outside the repository. Needs asciidoctor, as `site` does. site-test: bun test tests/site/ diff --git a/docs/decisions/0000-template.adoc b/docs/decisions/0000-template.adoc index 0345028b..b5ecdfc9 100644 --- a/docs/decisions/0000-template.adoc +++ b/docs/decisions/0000-template.adoc @@ -1,6 +1,7 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell = Architecture Decision Record: 0000-template +:status: PROPOSED // SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) <6759885+hyperpolymath@users.noreply.github.com> diff --git a/docs/decisions/0001-adopt-rsr-standard.adoc b/docs/decisions/0001-adopt-rsr-standard.adoc index 80ce7d60..bec4f972 100644 --- a/docs/decisions/0001-adopt-rsr-standard.adoc +++ b/docs/decisions/0001-adopt-rsr-standard.adoc @@ -1,6 +1,7 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell = Architecture Decision Record: 0001-adopt-rsr-standard +:status: ACCEPTED // SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) <6759885+hyperpolymath@users.noreply.github.com> diff --git a/docs/decisions/0002-variant-contract.adoc b/docs/decisions/0002-variant-contract.adoc index 80e16742..2a1bacfb 100644 --- a/docs/decisions/0002-variant-contract.adoc +++ b/docs/decisions/0002-variant-contract.adoc @@ -1,6 +1,7 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell = Architecture Decision Record: 0002-variant-contract +:status: ACCEPTED NOTE: Superseded in part (2026-10-06, rsr-template-repo#209): the `.a2ml` files named below no longer exist; their facts are clauses of the repo deed (`*_chora.deed`). The variant contract is the `(variant)` clause that `just repo-init` writes into a minted child's deed. diff --git a/docs/decisions/0003-forge-and-sustain-lifecycle.adoc b/docs/decisions/0003-forge-and-sustain-lifecycle.adoc index 540fffce..7a00174e 100644 --- a/docs/decisions/0003-forge-and-sustain-lifecycle.adoc +++ b/docs/decisions/0003-forge-and-sustain-lifecycle.adoc @@ -1,6 +1,7 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell = Architecture Decision Record: 0003-forge-and-sustain-lifecycle +:status: ACCEPTED NOTE: Superseded in part (2026-10-06, rsr-template-repo#209): the `.a2ml` files named below no longer exist; their facts are clauses of the repo deed (`*_chora.deed`). `just repo-init` writes the `(rsr-profile)`, `(variant)` and `(provenance)` clauses into a minted child's deed, and an archetype is `archetypes//_praxis.deed`. diff --git a/docs/decisions/0004-claims-registry.adoc b/docs/decisions/0004-claims-registry.adoc index eed4286f..0e10f04e 100644 --- a/docs/decisions/0004-claims-registry.adoc +++ b/docs/decisions/0004-claims-registry.adoc @@ -1,6 +1,7 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell = Architecture Decision Record: 0004-claims-registry +:status: ACCEPTED == 4. A theorem-level claims registry that derives grades and never assigns them diff --git a/docs/decisions/0005-jcs-json-receipt.adoc b/docs/decisions/0005-jcs-json-receipt.adoc index 17fdb208..5c3f76ac 100644 --- a/docs/decisions/0005-jcs-json-receipt.adoc +++ b/docs/decisions/0005-jcs-json-receipt.adoc @@ -1,6 +1,7 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell = Architecture Decision Record: 0005-jcs-json-receipt +:status: PROPOSED == 5. The claims registry also reads a proof receipt written as canonical JCS I-JSON diff --git a/docs/decisions/README.adoc b/docs/decisions/README.adoc index cb9c6d84..5a7118c6 100644 --- a/docs/decisions/README.adoc +++ b/docs/decisions/README.adoc @@ -1,3 +1,62 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell = decisions Unit + +== The status of a decision record + +Each decision record (`NNNN-title.adoc`) states its status twice, and the two +must agree (owner ruling 2026-11-25): + +* once in its document header, as the attribute `:status:`, on a line of the +header (the title line and the lines after it, up to the first blank line); +* once in its prose, as the first word of its Status section. + +The header uses the words of the ADR template (`0001-template.adoc`, with +REJECTED from `0000-template.adoc`), written exactly so: `PROPOSED`, `ACCEPTED`, +`DEPRECATED`, `SUPERSEDED by NNNN` or `REJECTED`. The Status section may write +the word in any case and add what it likes after it, such as "*Accepted +(ratified by owner 2026-11-10).*". + +[source,asciidoc] +---- += Architecture Decision Record: 0004-claims-registry +:status: ACCEPTED + +== 4. A theorem-level claims registry ... + +=== Status + +*Accepted (ratified by owner 2026-11-10).* ... +---- + +`just adr-check` (part of `just check-views`) runs +`scripts/decisions/adr-status.mjs check`. It fails when a record's header and +Status section disagree, when only one of them states a status, or when a +record states a status the readers refuse to read (for example, beside a +preprocessor directive or under a heading such as "Status quo"). It reads the +records that git tracks here, each at its own path: when this directory, or a +record, is a link, the check fails and reads nothing through it. A record that +states no status at all (no `status` entry, no heading that could read Status, +whether `== Status` or `Status` over an underline, no directive that could bring +one in) is listed, for the owner to set; it does +not count as accepted. + +Both are read conservatively, so the reader never finds a status Asciidoctor +would not: + +* The header is the title line, after any blank lines and line comments, and +the lines up to the first blank line. Each of those lines is a line comment or +an attribute entry, and none ends in a continuation. Exactly one line in the +whole record sets or unsets `status`, in any letter case (Asciidoctor reads +`:Status:` as `:status:`), and it is in the header. A preprocessor +directive, or an inline reference that changes an attribute (`{set:...}`, +`{counter:...}` or `{counter2:...}`), anywhere leaves the header unread: a +counter turns ACCEPTED into ACCEPTEE. +* In the Status section, every line that could be a heading titled Status counts, +inside a block or not. The section is read only when exactly one does, and that +one is a plain section heading (`==` to `======`, then `Status`) whose first +paragraph opens with the word, ending where no letter, number or combining mark +of any script follows (so "Acceptedé" is not "Accepted"). + +Only a record whose header says ACCEPTED, with a Status section that agrees, can +stand as evidence in the ultraplan. diff --git a/docs/status/ROADMAP.adoc b/docs/status/ROADMAP.adoc index 8e9aef0c..f2ff26d4 100644 --- a/docs/status/ROADMAP.adoc +++ b/docs/status/ROADMAP.adoc @@ -10,6 +10,13 @@ Phase `incubating`, maturity `experimental` (the deed's `(status)` and truth". The stages are under <>; the rulings that steer them are under <>. +What comes next is drawn as a tech tree, the ultraplan +(link:../ultraplan/generated/ultraplan.adoc[`docs/ultraplan/generated/ultraplan.adoc`], +from the data in `docs/ultraplan/`). Its frontier is the work that is ready, to +start when an active slot is free, and each advisor of the council, except the +private me advisor, names a pick from it. This roadmap keeps the record of what happened; the tree says what each +piece enables. + === Proven lifecycle registration (2026-11-25) The Proven owner has retained production Idris lifecycle proof checks, negative @@ -439,3 +446,56 @@ scheduled census, a view of what each repository owes the source of generated Agda; proofs in Agda, Rocq and Lean; three pull requests; the laws of the integer instance proved in the second pull request. +* Ultraplan (2026-11-24), through the selector: +** The plan is a data-first tech tree. Views are generated from the data, and + `just check` checks them. +** The advisors are the owner's six (mathematician, scientist, engineer, + economist, publisher, me) and four more (soundness auditor, estate + cartographer, teacher, contrarian). +** The me advisor is private. Its notes stay outside this repository and every + feed, in a private panel the owner owns, and a node carries at most the + tag `owner_value`. It names no public pick: the page lists the tagged + frontier nodes unranked, and the owner chooses in that panel. +** Off-tree trips are return tickets: each is grafted onto the tree or + archived with what it taught. +** The maths panel waits on a feed and panel contract. The estate coordinator + has answered: a read-only feed, one panel type, and open decisions sent to + the owner's decision desk. +** The feed's reader pins by commit (owner ruling 2026-11-24). Mathesis + commits the feed as a generated view, which `just check` refuses when + stale. The reader asks the GitHub API for the head commit of main, then + reads the feed at that commit, so each read names its commit. The fetch + logic and its rate limits belong to the reader. Mathesis needs no new + permission and holds no inbound secret. +** These rulings were recorded while the panel was taken to be in GELS, a name + now retired. See the clarification of 2026-11-25 below. +* Owner clarification (2026-11-25): two systems had been mixed up. The owner + named them the same day (relayed to this work by the estate hub session). + Both are in metadatastician: +** MPSCI is the Master Production and Scheduling Command Interface. +** GELO is the Git Estate Logistics Office. It was called GELS, the Git + Estate Logistics System; "GELS" is retired. +** Earlier text here and in the ultraplan called that system GELS, and "the + estate display". Which system, MPSCI or GELO, shows the maths panel and the + owner's private panel, and reads the feed, is open for the owner. The + panel node is now `maths-panel`. +** The feed-panel contract thread, the estate coordinator and the decision + desk were told of the clarification the same day. +* Owner rulings (2026-11-25), through the selector: +** Plan texts are plain text everywhere: in the data, on the page and in the + feed. The page writes each ASCII punctuation mark in a text as a character + reference, so the text shows as written and forms no markup. +** An ADR's status becomes a header attribute, `:status:`, kept in step with + its Status section. +** Guix proof CI gets one estate-wide fix at source, queued as its own task + (CI upkeep, on a cheaper model). +* Owner rulings (2026-11-25), through the decision desk: +** Mathesis hosts its own visual proof space: the maths panel and the + owner's private me panel live in Mathesis. MPSCI only links to it, with a + summary card or a link. GELO is not involved yet. The me panel's notes + still stay outside this public repository and every feed (ruling + 2026-11-24). The `maths-panel` node is now open. +** Agent pull requests are committed through the GitHub API, so each commit + carries GitHub's verified (web-flow) signature; the owner re-signs + nothing. The signature attests GitHub and the owner's account, not the + estate signing key (a doctrine 9 note). diff --git a/docs/ultraplan/README.adoc b/docs/ultraplan/README.adoc new file mode 100644 index 00000000..87e8be45 --- /dev/null +++ b/docs/ultraplan/README.adoc @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) += The ultraplan: how to read and grow the tech tree +:toc: preamble + +The ultraplan is the plan of Mathesis drawn as a tech tree, like a civilisation +game. Each node is a capability: a theorem, a tool, a view, a paper or a decision. +A node's *needs* are the nodes it builds on. Read the other way, each node +*enables* the nodes that need it. The generated page, +link:generated/ultraplan.adoc[`generated/ultraplan.adoc`], and its picture, +`generated/tree.svg`, show the whole tree. They are rebuilt from the data here by +`just ultraplan`, and `just check` refuses them when they are stale. + +The plan is data first (owner ruling 2026-11-24). The three files in this +directory are its whole source. Each holds I-JSON, one record a line in JCS form, +so a diff shows only real change. + +[cols="1,3",options="header"] +|=== +|File |What it holds + +|`tree.jsonl` +|The nodes. Each names its needs, so the edges live in the data. + +|`advisors.jsonl` +|The council: who reads the tree, the one question each asks, and which value +mark each reads. + +|`expeditions.jsonl` +|Return tickets: trips off the tree, each grafted on as a node or archived with +what it taught. +|=== + +== What is typed and what is derived + +Typed by hand: + +* each node's name, track, kind, size, summary and needs; +* its status; +* its value marks; +* the counsel advisors give on it. + +Derived by `scripts/ultraplan/ultraplan.mjs`, and never typed: + +* *Era*: the length of the longest chain of needs below a node. +* *Frontier*: the open nodes whose needs are all done. They are ready, and one can +start today whenever an active slot is free. +* *Unlocks*: how many live nodes depend on a node, directly or through others. +* *Forks*: nodes that enable two or more tracks, where work spreads. +* *Confluences*: nodes that need two or more tracks, where work joins. +* *Each advisor's pick*: one node from the frontier. The private me advisor names +none; the page lists the frontier nodes the owner tagged, unranked. + +A typed status is held to account: + +* *Done* needs evidence that the generator checks against the repository. It +accepts a file that git tracks, a claim whose grade the registry view derives at +or above a stated grade, or a decision record whose status is Accepted. ++ +Every file the checks read is one that git tracks, at its own path: no link +along the path, nothing untracked, nothing in `.git`. That holds for evidence, +refs, decision records, the registry view and the three sources here. So the +evidence is what a reviewer reads in the commit, and a clone and a linked +worktree read the same. `scripts/repo/files.mjs` reads them. A done +node's needs must be done too. ++ +A decision record counts only when it states its status twice, in agreement +(owner ruling 2026-11-25). Its header must hold `:status: ACCEPTED`, and its +Status section must open with the same word. `scripts/decisions/adr-status.mjs` +reads both conservatively, so it never finds a status that Asciidoctor would +not; `docs/decisions/README.adoc` sets out the rules. +* *Active* is limited: at most three nodes may be active at once. To start a +fourth, finish or park one first. This is the guard against starting everything. +When every slot is taken, the page and the picture still show the frontier, and +say that it is ready but cannot start. +* *Blocked* must say what blocks it. +* *Dropped* takes the nodes that need it along: a node still in play may not +need a dropped node, since it could never start. So nothing below a dropped node +is counted as unlocked. + +Each text (a name, a summary, a piece of counsel, a reason, a quote) is plain +text on one line (owner ruling 2026-11-25). It carries no markup, and the page +shows it exactly as written: + +* AsciiDoc builds all its markup from ASCII punctuation. The generator writes +each such mark in a text as a numeric character reference, which Asciidoctor +shows as the mark itself and never reads as markup. +* So no text can open a block, start a list or a description list, end a table +cell or a link, form a span, or name an attribute, wherever it stands on the +page. +* A feed can carry the same strings unchanged, as plain text. +* The generator refuses a text the page could not show as written: one that +holds a control character (a line break among them), a line or paragraph +separator (U+2028 or U+2029, where a browser breaks the line), a bidirectional +formatting control (such as U+202E, which reorders what is shown), a run of two or +more spaces (HTML shows a run as one), or a space at its start or end. A +no-break space is shown as written, and is allowed. + +A text does not type a count that the data derives, such as a number of claims, +repositories or theorems: the views carry those counts, and a typed one goes stale. + +The value marks (0 to 3 on maths, science, engineering, economics, publications, +teaching, soundness and ecosystem) are judgements, not measurements. They are +written down so they can be argued with. The page labels them as judgements. + +== The council + +The council is the data in `advisors.jsonl`, and the generated page lists it. On +2026-11-24 the owner set it to: + +* the six the owner named (mathematician, scientist, engineer, economist, +publisher, and "me"); +* four more (soundness auditor, estate cartographer, teacher and contrarian). + +The generator requires only the me advisor, because the page's privacy claim +rests on it. Who else sits on the council is the owner's to change in the data. + +Each asks one question of every node. Each names one pick from the frontier, +except the me advisor: + +* An advisor that reads a value mark ranks the frontier nodes it marks above +zero: by the mark, then by how much the node unlocks, then by value for effort +(its marks summed, over its size). A node it marks zero is +not one it would pick, so when no node is marked above zero the advisor names +nothing. +* The contrarian asks which node everyone is overlooking. It names the frontier +node the council rates lowest (its value marks summed), and among nodes rated +equally low, the one that unlocks the most. Leverage only breaks the tie: ranked +by leverage first, the contrarian would name what the council already ranks +first. That keeps the road not taken in view. +* The *me* advisor looks out for what could help the owner's own life. Its notes +are kept privately, outside this public repository and out of every feed: in +a private panel that the owner owns (owner ruling 2026-11-24). Mathesis hosts +that panel in its own visual proof space (owner ruling 2026-11-25, see +<>), and its notes still never enter this repository or a feed. A node carries at most the +neutral tag `"owner_value":"high"`, and the generator refuses any counsel under +the key `me`. The me advisor names no public pick (owner ruling 2026-11-24): the +owner chooses in that private panel, and the page lists, in id order and +unranked, the frontier nodes the owner tagged. + +== Wandering: return tickets + +Going off the tree is allowed, and expected. Before a trip, add a card to +`expeditions.jsonl`: + +[source,json] +---- +{"date":"2026-11-24","id":"X-001","size":"S","status":"out","what":"Try a tropical semiring model of proof cost","why":"It might give the economist a real cost measure"} +---- + +On return, change the card: + +* *grafted*: the trip found something the tree should hold. Add the node, and set +`"graft":""`. +* *archived*: it did not belong. Set `"lesson"` to what it taught, so the trip +still counts. + +== Adding or changing a node + +. Add or edit the line in `tree.jsonl`, keeping its JCS form. Keys are sorted +and there are no spaces between tokens. When a line is not in that form, the +generator names it and the command that writes its form, such as +`sed -n 23p docs/ultraplan/tree.jsonl | bun scripts/ijson-jcs-cli.js canon`. Its id is a lowercase slug that begins with a +letter, because the id is also the node's anchor on the page. +. Give it needs, so it sits in the right era. A node with no needs starts a new +root. +. If it is another route to a node that already exists, name each in the other's +`rivals`. +. If the work lands in another repository, set `"where":"estate:OWNER/REPO"` or +`"upstream:OWNER/REPO"`. The page lists those nodes so they can be carried +there. +. Point at its sources in `refs`, by what they say and never by line number: a +line number goes stale with the next edit, and nothing notices. A ref is one of +these: +** `+{"at":"a passage","path":"docs/x.adoc"}+`: a passage of a file in this +repository. The passage must occur in the file exactly once. `just check` +refuses the ref when the passage is reworded, moved away or repeated, so a ref +never points nowhere unseen. A passage is one line of up to 160 characters. +** `+{"path":"docs/x"}+`: a file of this repository, or a directory that holds +one, which git must track. +** `+{"at":"…","commit":"","path":"…","repo":"OWNER/REPO"}+`: a +file of another repository at a commit. The commit fixes its content, so it +cannot drift. It is not checked here. +** `+{"issue":"OWNER/REPO#N"}+`: a GitHub issue or pull request. +. Run `just ultraplan`, then `just check`. + +[[estate-panel]] +== The estate panel + +The owner asked for a maths panel, as a sub-panel of one of the estate's +systems. On 2026-11-25 the owner made clear that two systems had been mixed up +in that request, and named them. Both live in metadatastician: + +* *MPSCI* is the Master Production and Scheduling Command Interface. +* *GELO* is the Git Estate Logistics Office. It was called GELS, the Git Estate +Logistics System, a name now retired. + +Earlier text here called that system GELS, and "the estate display"; that was +the mix-up. + +The host is settled (owner ruling 2026-11-25, through the decision desk): + +* *Mathesis hosts its own visual proof space.* The maths panel and the owner's +private me panel live in Mathesis. The me panel's notes still stay outside this +public repository and out of every feed (ruling 2026-11-24): where they are +kept is settled when the panel is built. +* *MPSCI only links to it*, with a summary card or a link. +* *GELO is not involved yet.* + +What was settled on 2026-11-24 still holds where a reader outside Mathesis needs +the data, such as MPSCI's summary card: + +* Mathesis publishes a read-only I-JSON/JCS feed. It carries the tree's nodes, +the advisors' picks (never the me advisor's), the grade census with its +denominator, and the claim pins. +* Open decisions go to the owner's decision desk, not the panel. +* The reader pins by commit (owner ruling). Mathesis commits the feed as a +generated view, which `just check` refuses when stale. The reader asks the +GitHub API for the head commit of main and reads the feed at that commit, so +each read names its commit. No secret comes into this repository, and nothing +here needs a new permission. + +A draft of the feed and panel contract was begun in MPSCI's repository +(`docs/proposals/feed-panel-contract.adoc`). With the host settled, that +contract shrinks to what MPSCI's card reads. Nothing here writes a feed until +the card has an agreed reader: a feed with no reader would be unwired. The proof +space is a node in the tree (`maths-panel`), now open. diff --git a/docs/ultraplan/advisors.jsonl b/docs/ultraplan/advisors.jsonl new file mode 100644 index 00000000..2f34eafd --- /dev/null +++ b/docs/ultraplan/advisors.jsonl @@ -0,0 +1,10 @@ +{"asks":"Is it true, is it new, and does it join two things that were apart?","glyph":"∑","id":"maths","name":"Mathematician","reads":"maths"} +{"asks":"What would we measure, and what result would change our mind?","glyph":"🔬","id":"science","name":"Scientist","reads":"science"} +{"asks":"Does it run in the gate, fail loudly, and stay cheap to keep?","glyph":"⚙️","id":"engineering","name":"Engineer","reads":"engineering"} +{"asks":"What does it cost, what does it return, and who would fund or use it?","glyph":"🪙","id":"economics","name":"Economist","reads":"economics"} +{"asks":"Is there a paper, a talk or a citable artefact here?","glyph":"📜","id":"publications","name":"Publisher","reads":"publications"} +{"asks":"Is every done backed by a receipt, and where is the hole?","glyph":"🔍","id":"soundness","name":"Soundness auditor","reads":"soundness"} +{"asks":"Does another repository already have this, or need it? Converge rather than rebuild.","glyph":"🗺️","id":"cartographer","name":"Estate cartographer","reads":"ecosystem"} +{"asks":"Could a newcomer learn something true and useful from it?","glyph":"🍎","id":"teacher","name":"Teacher","reads":"teaching"} +{"asks":"What if we took the other road? Which cheap node is everyone overlooking?","glyph":"🃏","id":"contrarian","name":"Contrarian"} +{"asks":"Does it help the owner’s own life and work? Its notes are kept privately, outside this repository.","glyph":"🫶","id":"me","name":"Me","private":true} diff --git a/docs/ultraplan/expeditions.jsonl b/docs/ultraplan/expeditions.jsonl new file mode 100644 index 00000000..e69de29b diff --git a/docs/ultraplan/generated/tree.svg b/docs/ultraplan/generated/tree.svg new file mode 100644 index 00000000..98c14b8a --- /dev/null +++ b/docs/ultraplan/generated/tree.svg @@ -0,0 +1,530 @@ + + + +The Mathesis tech tree +Generated by scripts/ultraplan/ultraplan.mjs from docs/ultraplan/tree.jsonl. 52 nodes in 8 eras; each arrow runs from a node to a node it enables. + + + + + +🦉 Mathesis tech tree +each arrow: this enables that · gold border: start it now · ✅ done 🔨 active 🌱 open ⛔ blocked 🍂 dropped + +🪨 Tally sticks + +🧮 Abacus + +📐 Euclid + +🌌 Kepler + +♾️ Cantor + +🧩 Gödel + +🌀 Grothendieck + +🚀 Frontier beyond + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +APP-1 to APP-4: missing stays missing: Missing inputs propagate and never read as zero; the cash identity; the least funding gap; status never upgrades. Each proved in Agda, Rocq and Lean. + +💧 +APP-1 to APP-4: missi… +∑ maths · M +✅ + + +Atlas views: The catalogue and the A to Z and organisation views, generated from the census rows and checked for staleness by just check-views. + +🗺️ +Atlas views +⚙ engineering · M +✅ + + +Bridges by construction: Generate the Agda, Rocq and Lean forms of a statement from one source (Q-2.3, E-2.3), so a re-proof starts from a statement known to match. + +🏗 +Bridges by constructi… +⚙ engineering · L +🌱 + + +Bridge candidates: Three unassessed candidate links between theorems in different repositories and provers (tropical MaxPlus, resource-algebra M-2, squeakwell). Candidates, not evidence. + +🌉 +Bridge candidates +🗺 ecosystem · S +✅ + + +Bridge lock pilot: The full bridge record for two pilots, a squeakwell ladder row and resource-algebra to tropical-types (WO 5.2, ruling D-7 a): what is claimed equal, by which map, checked how. + +🔗 +Bridge lock pilot +🗺 ecosystem · M +🌱 + + +Census of the estate: The proof census of the public repositories: a row for each proof file, with its holes and axioms, at a pinned commit and time. + +🧾 +Census of the estate +⚙ engineering · L +✅ + + +Census on a schedule: A scheduled census workflow as the one writer of the census rows (WO 5.3), so refreshes stop arriving by hand and unrecorded. + +⏰ +Census on a schedule +⚙ engineering · M +🌱 + + +Centre computations: Over locked bridges: classes under a criterion, their order, contradictions, and the five different absences (RA 786-801). + +🎯 +Centre computations +∑ maths · L +🌱 + + +Is a chain enough? (X-PF1): Experiment X-PF1, pre-registered: list each rule, gate and report in the estate that reads a status token (at least the proof-route ABI, the registry and ledger rule 3) and ask whether its result changes between the two members of a fibre. Outcome A, B or C (or D: two tokens the wrong way round) decides the order. + +🧩 +Is a chain enough? (X… +∑ maths · M +🔨 + + +CI records its own runs: A trusted publisher that writes each green run's ledger rows to the repository, so no human copies rows. The piece standards PR 1675 leaves open. + +🤖 +CI records its own ru… +⚙ engineering · M · 🌍 +🌱 + + +Claims registry: Pins each claim in its home repository and derives each grade from the home receipt with the pinned canon reader. No grade is typed. + +📒 +Claims registry +⚙ engineering · L +✅ + + +Cohort model in Agda: The cohort-economics model of the applied shelf, with three number modes and synthetic examples generated into Agda from JSON Lines. + +👥 +Cohort model in Agda +∑ maths · M +✅ + + +Concept commons: The horizon of the atlas (M4): a commons of the estate's concepts, navigable by A to Z, subject (MSC2020), project and provenance. + +🏛️ +Concept commons +∑ maths · XL +🌱 + + +Propose and dispose corpus: A corpus as a view over bridges and receipts (E-H.1), and 20 ungraded Agda theorems given model-proposed Rocq and Lean legs, kept BRIDGE-PENDING until checked (E-H.2). + +🧪 +Propose and dispose c… +🔬 science · XL +🌱 + + +Transport through Dedukti: Check an Agda proof in Rocq and Lean by translating it through Dedukti and Lambdapi instead of re-proving it, the route PROOF-POLICY section 2 puts first. + +🚂 +Transport through Ded… +⚙ engineering · L · 🌍 +⛔ + + +Mend the status documents: ROADMAP, PROOF-NEEDS, README and the intend contract contradict the receipts (PWG-1 vs PWG-2ii, receipts called planned that exist, stage states). Make each agree with the derived facts. + +🧹 +Mend the status docum… +⚙ engineering · S +🌱 + + +Theorem dossier: The eight-item dossier for each theorem (Line 0), scored first on THY-1, five januskey theorems and two each of secret-types and lintel (E-0). Its home (here or standards, R-5) is still open. + +🗂️ +Theorem dossier +∑ maths · S +🌱 + + +Echo mirror records: Bridge records for the six languages that mirror echo-types (E-2.5), with the graded-comonad disagreement kept as an open question. + +🪞 +Echo mirror records +🗺 ecosystem · M · 🌍 +🌱 + + +Closed list of encoding differences: A closed, tested list of the ways the same statement differs between Agda, Rocq and Lean (Q-2.1), built from the existing comparisons as bridge records (E-2.1). + +🔤 +Closed list of encodi… +🔬 science · M +🌱 + + +PWG-2ii across the estate: The long horizon (Q-H.3): the 900 and more ungraded theorems of the estate each carry two checked recheck legs. The question is whether that takes months or years. + +🏔️ +PWG-2ii across the es… +🗺 ecosystem · XL +🌱 + + +File the transport reproducers: File the THY-1 reproducers upstream (E-2.4): the Agda2Dedukti crash and option gaps, and Lambdapi dropping rules. Filing is the owner's act. + +🐛 +File the transport re… +🗺 ecosystem · S · 🌍 +🌱 + + +Thirteen-week forecast: A synthetic thirteen-week cash forecast on the proved cohort model (E-4.1), the first worked decision of the applied shelf. + +📅 +Thirteen-week forecast +🪙 economics · M +🌱 + + +Visual proof space: Mathesis hosts its own visual proof space (owner ruling 2026-11-25): the tech tree, its frontier, the grade census with its denominator, and the claim pins. The owner’s private me panel lives here too, its notes kept outside this repository and every feed. MPSCI links to it with a summary card. Open decisions go to the owner’s decision desk. + +🪟 +Visual proof space +🗺 ecosystem · M +🌱 + + +Generated Idris2 token laws: Generate the Idris2 token laws of the proof-route Token module from S-1 (E-3.2), so the engineering side cites the theorem instead of restating it. + +🧬 +Generated Idris2 toke… +⚙ engineering · M · 🌍 +🌱 + + +Theorem to code: januskey: Follow one theorem into running code (E-3.1): the januskey slice T-1, with T-10 open and G-2 assumed, and a composite status for the whole (Q-3.1). + +🗝️ +Theorem to code: janu… +⚙ engineering · L · 🌍 +🌱 + + +Liquidity shelf: The liquidity part of the applied shelf: a forecast whose every verdict carries its proof status, from synthetic data only. + +💶 +Liquidity shelf +🪙 economics · M +🌱 + + +Paper: receipts, not claims: A methods paper: proof status derived from machine receipts, graded by witness count, never typed, with the registry as a working instance across an estate. + +📰 +Paper: receipts, not … +📜 publications · L +🌱 + + +Paper: an algebra of proof status: S-1 to S-3 written up: proof status as a dioid, its monotone evaluation, and the grade as a checked function of the receipt. + +📘 +Paper: an algebra of … +📜 publications · L +🌱 + + +Note: feature reachability: A short note on THY-1: why requesting every feature is a sound check for absence, with the three-prover receipt as artefact. Its dependant is a real standards rule. + +📄 +Note: feature reachab… +📜 publications · M +🌱 + + +Proof lanes in a pinned image: Run the three proof lanes in a container image pinned by digest, the condition PROOF-POLICY now sets for PWG-1 (standards#1625). The Guix shell alone does not qualify. + +📦 +Proof lanes in a pinn… +⚙ engineering · M +🌱 + + +Proof gate in pinned Guix: Agda 2.7.0.1, Rocq 8.18.0 and Lean 4.29.0 check every gated module on every commit, with an axiom audit over theorems and definitions and planted controls that must fail. + +🛡️ +Proof gate in pinned … +⚙ engineering · L +✅ + + +Publish the atlas: Deploy the built site (WO 4.3), once the owner says go. Publication is outward-facing, so it is gated on the owner, not on any node. + +🌐 +Publish the atlas +📜 publications · S +⛔ + + +Back to PWG-1: THY-1 and APP-1 to APP-4 derive PWG-1 again, from receipts whose rows name the pinned image. + +🥇 +Back to PWG-1 +⚙ engineering · S +🌱 + + +Shared receipt generator: Adopt the standards generator: the receipt is generated from a run ledger, and the gate lists each green run's ledger rows. Pull request 122. + +🏭 +Shared receipt genera… +⚙ engineering · M +🔨 + + +Proof receipts: The PROOF-POLICY 8.5.1 receipt of Mathesis: per-leg run, commit, checker, inputs manifest and axioms, checked by the shared git checker and read by the canon reader. + +🔏 +Proof receipts +⚙ engineering · M +✅ + + +Receipts campaign: Home repositories re-record their receipts (WO 5.1): secret-types and lintel for the reader they fail, resource-algebra for its Lean leg. Takes the ungraded theorems towards a grade. + +📣 +Receipts campaign +🗺 ecosystem · L · 🌍 +🌱 + + +S-1 by reuse of resource-algebra: Prove only the morphism here, and take the dioid laws from resource-algebra's E-1 to E-3 (already PWG-2i) through a locked bridge, instead of proving them again. + +♻️ +S-1 by reuse of resou… +🗺 ecosystem · M · 🌍 +🌱 + + +S-1: tokens form a dioid: The status tokens form a ResourceAlgebra and dioid with an annihilating zero, with an injective strict morphism into MinMax. Agda against resource-algebra at a pin, re-proved in Rocq and Lean (E-1.1). + +🔢 +S-1: tokens form a di… +∑ maths · L +🌱 + + +S-2: evaluation is monotone: Positive evaluation of status is monotone. It holds for each ordered resource algebra, so it can be proved once against the kernel now, whatever X-PF1 decides (R-3). + +📈 +S-2: evaluation is mo… +∑ maths · S +🌱 + + +S-3: the grade is a function: The Proof Witness Grade is a total monotone function of the receipt, and the canon reader agrees with it on every case, shown by exhaustion as in residual-evidence-types (E-1.3). + +🎚️ +S-3: the grade is a f… +∑ maths · M +🌱 + + +S-4 and S-5: honest cash verdicts: A sound three-valued cash verdict over intervals, where missing means unbounded (S-4), and more uncertainty never strengthens a verdict (S-5). Reuses residual-evidence-types at a pin; pass is PWG-3 (E-4.2). + +🌦️ +S-4 and S-5: honest c… +∑ maths · M +🌱 + + +Atlas site (build): Renders every generated view with Asciidoctor and fails on any warning or broken link. It builds; it does not deploy. + +🏗️ +Atlas site (build) +⚙ engineering · S +✅ + + +From oracle to theorem: S-MN and S-DM (the multinomial logit closed form and the DM contrast limit) are tested only, against MetaManifold-WebUI as oracle. Prove them in Agda, Rocq and Lean for admission (Q-2.6). + +🎲 +From oracle to theorem +🔬 science · L +🌱 + + +Keep superseded manifests (option): A generator option that keeps the inputs digest, manifest and axioms on superseded receipts (owner ruling 2026-11-24). It landed in standards as #1705, and hyperpolymath/mathesis#122 turns it on; it is done when that pull request merges. + +🗄️ +Keep superseded manif… +⚙ engineering · S +🌱 + + +Talk: an atlas of an estate: A talk on mapping the mathematics of hundreds of repositories, with every status traced to a receipt. + +🎤 +Talk: an atlas of an … +📜 publications · S +🌱 + + +Cohort economics, taught: A worked tutorial: a small business model where missing data stays missing, with the proofs alongside and synthetic data only. + +📓 +Cohort economics, tau… +📜 publications · M +🌱 + + +Theory shelf and ledger: The admission rule for theory no single system owns, with an append-only ledger of every grade and receipt change. One theorem admitted so far. + +📚 +Theory shelf and ledg… +∑ maths · S +✅ + + +THY-1: reachability is monotone: In a dependency graph with feature-guarded edges, a node unreachable with every feature requested is unreachable under any request. Proved in Agda, re-proved in Rocq and Lean. + +🧭 +THY-1: reachability i… +∑ maths · M +✅ + + +Settle the order of status tokens: Record the order X-PF1 decides, in Mathesis (R-1, provisional) and in the canon. Evidence it must answer: R-1 reads PROOF-POLICY section 5 as open < argued < tested-only, resource-algebra E-1 (PWG-2i) proves open < tested-only < argued, and section 5 itself lists the tokens without stating an order. + +⚖️ +Settle the order of s… +∑ maths · S +🌱 + + +The ultraplan: This tech tree: data first, with derived eras, frontier, forks, confluences and advisor picks, and a done that must show evidence. + +🌳 +The ultraplan +⚙ engineering · S +✅ + + +Value of information: Decision science on the shelf: what a missing input is worth to know, computed from the three-valued verdicts. No optimiser (decision-science README). + +🔭 +Value of information +🪙 economics · L +🌱 + + +What is owed: A view of the standards requirements master list beside the census and the registry (WO 5.4): what each repository owes, and what it has. + +📋 +What is owed +🗺 ecosystem · M +🌱 + + +∑ maths + +⚙ engineering + +🔬 science + +🪙 economics + +📜 publications + +🗺 ecosystem +🌍 lands in another repository + diff --git a/docs/ultraplan/generated/ultraplan.adoc b/docs/ultraplan/generated/ultraplan.adoc new file mode 100644 index 00000000..b55ee27a --- /dev/null +++ b/docs/ultraplan/generated/ultraplan.adoc @@ -0,0 +1,841 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 +// GENERATED by scripts/ultraplan/ultraplan.mjs from docs/ultraplan/tree.jsonl, +// docs/ultraplan/advisors.jsonl and docs/ultraplan/expeditions.jsonl; do not hand-edit. += Mathesis ultraplan: the tech tree +:toc: macro +:toclevels: 1 + +Each node is a capability. Its needs are the nodes it is built on, so the tree reads +like a civilisation game: one discovery enables the next. The data in +`docs/ultraplan/` is the source; this page and its picture are generated from it. +The era, the frontier, the forks, the confluences and each advisor's pick are derived, +never typed. A node marked done carries evidence the generator checks: a file, a +claim grade that the registry derives, or an accepted decision record. The value marks +are judgements, written down so they can be argued with. + +Census of the tree: 12 done, 2 active (at most 3), 36 open, 2 blocked, 0 dropped, of 52 nodes. 13 can be started now. + +toc::[] + +image::tree.svg[The tech tree of Mathesis, from the first era on the left to the frontier on the right] + +Key: ✅ done · 🔨 active · 🌱 open · ⛔ blocked · 🍂 dropped. A gold border marks a node +that can be started now. Colours are tracks: ∑ maths · ⚙ engineering · 🔬 science · 🪙 economics · 📜 publications · 🗺 ecosystem. + +== Research now: the frontier + +These open nodes have every need done, so any of them can start today. "Unlocks" +counts the live nodes that depend on it, directly or through others. + +[cols="3,1,1,1,5",options="header"] +|=== +|Node |Track |Size |Unlocks |Summary +|xref:bridge-lock-pilot[🔗 Bridge lock pilot] |ecosystem |M |8 |The full bridge record for two pilots, a squeakwell ladder row and resource-algebra to tropical-types (WO 5.2, ruling D-7 a): what is claimed equal, by which map, checked how. +|xref:census-workflow[⏰ Census on a schedule] |engineering |M |2 |A scheduled census workflow as the one writer of the census rows (WO 5.3), so refreshes stop arriving by hand and unrecorded. +|xref:forecast-13wk[📅 Thirteen-week forecast] |economics |M |2 |A synthetic thirteen-week cash forecast on the proved cohort model (E-4.1), the first worked decision of the applied shelf. +|xref:s4-s5-verdict[🌦️ S-4 and S-5: honest cash verdicts] |maths |M |2 |A sound three-valued cash verdict over intervals, where missing means unbounded (S-4), and more uncertainty never strengthens a verdict (S-5). Reuses residual-evidence-types at a pin; pass is PWG-3 (E-4.2). +|xref:dossier[🗂️ Theorem dossier] |maths |S |1 |The eight-item dossier for each theorem (Line 0), scored first on THY-1, five januskey theorems and two each of secret-types and lintel (E-0). Its home (here or standards, R-5) is still open. +|xref:file-transport-bugs[🐛 File the transport reproducers] |ecosystem |S |1 |File the THY-1 reproducers upstream (E-2.4): the Agda2Dedukti crash and option gaps, and Lambdapi dropping rules. Filing is the owner's act. _(upstream:Deducteam/agda2dedukti)_ +|xref:pinned-image[📦 Proof lanes in a pinned image] |engineering |M |1 |Run the three proof lanes in a container image pinned by digest, the condition PROOF-POLICY now sets for PWG-1 (standards#1625). The Guix shell alone does not qualify. +|xref:s2-monotone[📈 S-2: evaluation is monotone] |maths |S |1 |Positive evaluation of status is monotone. It holds for each ordered resource algebra, so it can be proved once against the kernel now, whatever X-PF1 decides (R-3). +|xref:doc-drift-fix[🧹 Mend the status documents] |engineering |S |0 |ROADMAP, PROOF-NEEDS, README and the intend contract contradict the receipts (PWG-1 vs PWG-2ii, receipts called planned that exist, stage states). Make each agree with the derived facts. +|xref:maths-panel[🪟 Visual proof space] |ecosystem |M |0 |Mathesis hosts its own visual proof space (owner ruling 2026-11-25): the tech tree, its frontier, the grade census with its denominator, and the claim pins. The owner’s private me panel lives here too, its notes kept outside this repository and every feed. MPSCI links to it with a summary card. Open decisions go to the owner’s decision desk. +|xref:paper-thy1[📄 Note: feature reachability] |publications |M |0 |A short note on THY-1: why requesting every feature is a sound check for absence, with the three-prover receipt as artefact. Its dependant is a real standards rule. +|xref:statistical-bridge[🎲 From oracle to theorem] |science |L |0 |S-MN and S-DM (the multinomial logit closed form and the DM contrast limit) are tested only, against MetaManifold-WebUI as oracle. Prove them in Agda, Rocq and Lean for admission (Q-2.6). +|xref:teaching-cohort[📓 Cohort economics, taught] |publications |M |0 |A worked tutorial: a small business model where missing data stays missing, with the proofs alongside and synthetic data only. +|=== + +== The council + +Each advisor asks one question of every node and names one pick from the frontier, +except the me advisor. It is private: its notes and its choice stay outside this +repository, and the page lists, unranked, the frontier nodes the owner has tagged. + +=== ∑ Mathematician + +_Asks:_ Is it true, is it new, and does it join two things that were apart? + +_Pick:_ xref:bridge-lock-pilot[🔗 Bridge lock pilot]. Equivalence as identity, made checkable. + +=== 🔬 Scientist + +_Asks:_ What would we measure, and what result would change our mind? + +_Pick:_ xref:statistical-bridge[🎲 From oracle to theorem]. Takes a statistical result that is only tested and makes it a theorem. + +=== ⚙️ Engineer + +_Asks:_ Does it run in the gate, fail loudly, and stay cheap to keep? + +_Pick:_ xref:census-workflow[⏰ Census on a schedule]. + +=== 🪙 Economist + +_Asks:_ What does it cost, what does it return, and who would fund or use it? + +_Pick:_ xref:s4-s5-verdict[🌦️ S-4 and S-5: honest cash verdicts]. A forecast that can say undecided is worth more than one that guesses. + +=== 📜 Publisher + +_Asks:_ Is there a paper, a talk or a citable artefact here? + +_Pick:_ xref:paper-thy1[📄 Note: feature reachability]. A complete, small, checked result: the easiest first paper. + +=== 🔍 Soundness auditor + +_Asks:_ Is every done backed by a receipt, and where is the hole? + +_Pick:_ xref:pinned-image[📦 Proof lanes in a pinned image]. The only road back to PWG-1 for THY-1 and APP-1 to APP-4. + +=== 🗺️ Estate cartographer + +_Asks:_ Does another repository already have this, or need it? Converge rather than rebuild. + +_Pick:_ xref:bridge-lock-pilot[🔗 Bridge lock pilot]. The first real convergence between repositories; everything cross-repo waits on it. + +=== 🍎 Teacher + +_Asks:_ Could a newcomer learn something true and useful from it? + +_Pick:_ xref:teaching-cohort[📓 Cohort economics, taught]. Shows why a proof matters to someone who reads spreadsheets, not theorems. + +=== 🃏 Contrarian + +_Asks:_ What if we took the other road? Which cheap node is everyone overlooking? + +_Pick:_ xref:file-transport-bugs[🐛 File the transport reproducers]. + +=== 🫶 Me + +_Asks:_ Does it help the owner’s own life and work? Its notes are kept privately, outside this repository. + +_No public pick:_ the owner chooses in a private panel of their own. Tagged on the frontier, in id order: xref:forecast-13wk[📅 Thirteen-week forecast], xref:paper-thy1[📄 Note: feature reachability], xref:teaching-cohort[📓 Cohort economics, taught]. + +== Forks and confluences + +A fork enables nodes on two or more tracks: work there spreads. A confluence needs +nodes from two or more tracks: work there joins. Rivals are different routes to the +same place; the contrarian keeps the road not taken in view. + +.Forks +* xref:app-proofs[💧 APP-1 to APP-4: missing stays missing] -> xref:forecast-13wk[📅 Thirteen-week forecast], xref:s4-s5-verdict[🌦️ S-4 and S-5: honest cash verdicts], xref:teaching-cohort[📓 Cohort economics, taught] +* xref:bridge-lock-pilot[🔗 Bridge lock pilot] -> xref:centre-computations[🎯 Centre computations], xref:echo-mirrors[🪞 Echo mirror records], xref:encoding-differences[🔤 Closed list of encoding differences], xref:s1-reuse[♻️ S-1 by reuse of resource-algebra] +* xref:centre-computations[🎯 Centre computations] -> xref:concept-commons[🏛️ Concept commons], xref:corpus[🧪 Propose and dispose corpus] +* xref:claims-registry[📒 Claims registry] -> xref:bridge-candidates[🌉 Bridge candidates], xref:chain-question[🧩 Is a chain enough? (X-PF1)], xref:doc-drift-fix[🧹 Mend the status documents], xref:maths-panel[🪟 Visual proof space], xref:paper-receipts[📰 Paper: receipts, not claims], xref:receipts[🔏 Proof receipts], xref:theory-shelf[📚 Theory shelf and ledger], xref:whats-owed[📋 What is owed] +* xref:proof-gate[🛡️ Proof gate in pinned Guix] -> xref:cohort-model[👥 Cohort model in Agda], xref:pinned-image[📦 Proof lanes in a pinned image], xref:receipts[🔏 Proof receipts], xref:thy1[🧭 THY-1: reachability is monotone] +* xref:receipt-generator[🏭 Shared receipt generator] -> xref:ci-recorder[🤖 CI records its own runs], xref:paper-receipts[📰 Paper: receipts, not claims], xref:pwg1-regained[🥇 Back to PWG-1], xref:receipts-campaign[📣 Receipts campaign], xref:superseded-manifests-option[🗄️ Keep superseded manifests (option)] +* xref:receipts[🔏 Proof receipts] -> xref:paper-thy1[📄 Note: feature reachability], xref:receipt-generator[🏭 Shared receipt generator], xref:s3-grade-function[🎚️ S-3: the grade is a function] +* xref:s1-token-algebra[🔢 S-1: tokens form a dioid] -> xref:bridge-by-construction[🏗 Bridges by construction], xref:idris-token-laws[🧬 Generated Idris2 token laws], xref:paper-status-algebra[📘 Paper: an algebra of proof status] +* xref:s3-grade-function[🎚️ S-3: the grade is a function] -> xref:corpus[🧪 Propose and dispose corpus], xref:paper-receipts[📰 Paper: receipts, not claims], xref:paper-status-algebra[📘 Paper: an algebra of proof status] +* xref:theory-shelf[📚 Theory shelf and ledger] -> xref:dossier[🗂️ Theorem dossier], xref:s1-token-algebra[🔢 S-1: tokens form a dioid], xref:s2-monotone[📈 S-2: evaluation is monotone], xref:statistical-bridge[🎲 From oracle to theorem] +* xref:thy1[🧭 THY-1: reachability is monotone] -> xref:dedukti-transport[🚂 Transport through Dedukti], xref:file-transport-bugs[🐛 File the transport reproducers], xref:paper-thy1[📄 Note: feature reachability], xref:theory-shelf[📚 Theory shelf and ledger] +* xref:token-order[⚖️ Settle the order of status tokens] -> xref:centre-computations[🎯 Centre computations], xref:s1-reuse[♻️ S-1 by reuse of resource-algebra], xref:s1-token-algebra[🔢 S-1: tokens form a dioid], xref:s3-grade-function[🎚️ S-3: the grade is a function] + +.Confluences +* xref:encoding-differences[🔤 Closed list of encoding differences] + xref:s1-token-algebra[🔢 S-1: tokens form a dioid] -> xref:bridge-by-construction[🏗 Bridges by construction] +* xref:bridge-lock-pilot[🔗 Bridge lock pilot] + xref:token-order[⚖️ Settle the order of status tokens] -> xref:centre-computations[🎯 Centre computations] +* xref:centre-computations[🎯 Centre computations] + xref:whats-owed[📋 What is owed] -> xref:concept-commons[🏛️ Concept commons] +* xref:bridge-by-construction[🏗 Bridges by construction] + xref:centre-computations[🎯 Centre computations] + xref:s3-grade-function[🎚️ S-3: the grade is a function] -> xref:corpus[🧪 Propose and dispose corpus] +* xref:thy1[🧭 THY-1: reachability is monotone] + xref:file-transport-bugs[🐛 File the transport reproducers] -> xref:dedukti-transport[🚂 Transport through Dedukti] +* xref:corpus[🧪 Propose and dispose corpus] + xref:receipts-campaign[📣 Receipts campaign] + xref:ci-recorder[🤖 CI records its own runs] -> xref:estate-pwg2ii[🏔️ PWG-2ii across the estate] +* xref:s4-s5-verdict[🌦️ S-4 and S-5: honest cash verdicts] + xref:forecast-13wk[📅 Thirteen-week forecast] -> xref:liquidity-shelf[💶 Liquidity shelf] +* xref:receipt-generator[🏭 Shared receipt generator] + xref:claims-registry[📒 Claims registry] + xref:s3-grade-function[🎚️ S-3: the grade is a function] -> xref:paper-receipts[📰 Paper: receipts, not claims] +* xref:thy1[🧭 THY-1: reachability is monotone] + xref:receipts[🔏 Proof receipts] -> xref:paper-thy1[📄 Note: feature reachability] +* xref:bridge-lock-pilot[🔗 Bridge lock pilot] + xref:token-order[⚖️ Settle the order of status tokens] -> xref:s1-reuse[♻️ S-1 by reuse of resource-algebra] +* xref:receipts[🔏 Proof receipts] + xref:token-order[⚖️ Settle the order of status tokens] -> xref:s3-grade-function[🎚️ S-3: the grade is a function] +* xref:claims-registry[📒 Claims registry] + xref:thy1[🧭 THY-1: reachability is monotone] -> xref:theory-shelf[📚 Theory shelf and ledger] + +.Rivals +* xref:bridge-by-construction[🏗 Bridges by construction] or xref:dedukti-transport[🚂 Transport through Dedukti] +* xref:s1-reuse[♻️ S-1 by reuse of resource-algebra] or xref:s1-token-algebra[🔢 S-1: tokens form a dioid] + +== The eras + +=== 🪨 Era 0: Tally sticks + +[[census]] +==== ✅ 🧾 Census of the estate + +The proof census of the public repositories: a row for each proof file, with its holes and axioms, at a pinned commit and time. + +*Track:* ⚙ engineering · *Kind:* data · *Size:* L · *Status:* done + +*Enables:* xref:atlas-views[🗺️ Atlas views], xref:census-workflow[⏰ Census on a schedule], xref:claims-registry[📒 Claims registry] + +*Evidence:* `docs/atlas/census/rows.jsonl`; `scripts/census/run-census.sh` + +*Value (judgement):* engineering ●●, science ●●, ecosystem ●●● + +[[proof-gate]] +==== ✅ 🛡️ Proof gate in pinned Guix + +Agda 2.7.0.1, Rocq 8.18.0 and Lean 4.29.0 check every gated module on every commit, with an axiom audit over theorems and definitions and planted controls that must fail. + +*Track:* ⚙ engineering · *Kind:* infrastructure · *Size:* L · *Status:* done + +*Enables:* xref:cohort-model[👥 Cohort model in Agda], xref:pinned-image[📦 Proof lanes in a pinned image], xref:receipts[🔏 Proof receipts], xref:thy1[🧭 THY-1: reachability is monotone] + +*Evidence:* `scripts/check-proofs.sh`; `tests/proofs/gate_controls_test.sh` + +*Value (judgement):* engineering ●●●, soundness ●●● + +=== 🧮 Era 1: Abacus + +[[cohort-model]] +==== ✅ 👥 Cohort model in Agda + +The cohort-economics model of the applied shelf, with three number modes and synthetic examples generated into Agda from JSON Lines. + +*Track:* ∑ maths · *Kind:* method · *Size:* M · *Status:* done + +*Needs:* xref:proof-gate[🛡️ Proof gate in pinned Guix] + +*Enables:* xref:app-proofs[💧 APP-1 to APP-4: missing stays missing] + +*Evidence:* `verification/proofs/agda/Applied/Cohort.agda`; `applied-systems/methods/input-schema.adoc` + +*Value (judgement):* maths ●●, economics ●●, teaching ●● + +[[thy1]] +==== ✅ 🧭 THY-1: reachability is monotone + +In a dependency graph with feature-guarded edges, a node unreachable with every feature requested is unreachable under any request. Proved in Agda, re-proved in Rocq and Lean. + +*Track:* ∑ maths · *Kind:* theorem · *Size:* M · *Status:* done + +*Needs:* xref:proof-gate[🛡️ Proof gate in pinned Guix] + +*Enables:* xref:dedukti-transport[🚂 Transport through Dedukti], xref:file-transport-bugs[🐛 File the transport reproducers], xref:paper-thy1[📄 Note: feature reachability], xref:theory-shelf[📚 Theory shelf and ledger] + +*Evidence:* hyperpolymath/mathesis#THY-1 at PWG-2ii or above + +*Value (judgement):* maths ●●, engineering ●●, publications ●● + +[[atlas-views]] +==== ✅ 🗺️ Atlas views + +The catalogue and the A to Z and organisation views, generated from the census rows and checked for staleness by just check-views. + +*Track:* ⚙ engineering · *Kind:* view · *Size:* M · *Status:* done + +*Needs:* xref:census[🧾 Census of the estate] + +*Enables:* xref:site-build[🏗️ Atlas site (build)], xref:ultraplan[🌳 The ultraplan] + +*Evidence:* `docs/atlas/generated/catalogue.adoc`; `docs/atlas/generated/az.adoc` + +*Value (judgement):* engineering ●●, teaching ●●, ecosystem ●● + +[[census-workflow]] +==== 🌱 ⏰ Census on a schedule + +A scheduled census workflow as the one writer of the census rows (WO 5.3), so refreshes stop arriving by hand and unrecorded. + +*Track:* ⚙ engineering · *Kind:* infrastructure · *Size:* M · *Status:* open + +*Needs:* xref:census[🧾 Census of the estate] + +*Enables:* xref:whats-owed[📋 What is owed] + +*Value (judgement):* engineering ●●, ecosystem ●● + +*See:* `docs/proposals/mathesis-re-anchoring.adoc`, at `WO 5.3 Schedule the census` + +[[claims-registry]] +==== ✅ 📒 Claims registry + +Pins each claim in its home repository and derives each grade from the home receipt with the pinned canon reader. No grade is typed. + +*Track:* ⚙ engineering · *Kind:* tool · *Size:* L · *Status:* done + +*Needs:* xref:census[🧾 Census of the estate] + +*Enables:* xref:bridge-candidates[🌉 Bridge candidates], xref:chain-question[🧩 Is a chain enough? (X-PF1)], xref:doc-drift-fix[🧹 Mend the status documents], xref:maths-panel[🪟 Visual proof space], xref:paper-receipts[📰 Paper: receipts, not claims], xref:receipts[🔏 Proof receipts], xref:theory-shelf[📚 Theory shelf and ledger], xref:whats-owed[📋 What is owed] + +*Evidence:* ADR 0004 accepted; `docs/atlas/generated/registry.adoc` + +*Value (judgement):* engineering ●●●, soundness ●●●, ecosystem ●●● + +[[pinned-image]] +==== 🌱 📦 Proof lanes in a pinned image + +Run the three proof lanes in a container image pinned by digest, the condition PROOF-POLICY now sets for PWG-1 (standards#1625). The Guix shell alone does not qualify. + +*Track:* ⚙ engineering · *Kind:* infrastructure · *Size:* M · *Status:* open + +*Needs:* xref:proof-gate[🛡️ Proof gate in pinned Guix] + +*Enables:* xref:pwg1-regained[🥇 Back to PWG-1] + +*Value (judgement):* engineering ●●, soundness ●●● + +*See:* `docs/status/PROOF-STATUS.adoc`, at `standards#1625 (2026-11-17)` + +* 🔍 _Soundness auditor:_ The only road back to PWG-1 for THY-1 and APP-1 to APP-4. + +=== 📐 Era 2: Euclid + +[[app-proofs]] +==== ✅ 💧 APP-1 to APP-4: missing stays missing + +Missing inputs propagate and never read as zero; the cash identity; the least funding gap; status never upgrades. Each proved in Agda, Rocq and Lean. + +*Track:* ∑ maths · *Kind:* theorem · *Size:* M · *Status:* done + +*Needs:* xref:cohort-model[👥 Cohort model in Agda] + +*Enables:* xref:forecast-13wk[📅 Thirteen-week forecast], xref:s4-s5-verdict[🌦️ S-4 and S-5: honest cash verdicts], xref:teaching-cohort[📓 Cohort economics, taught] + +*Evidence:* hyperpolymath/mathesis#APP-1 at PWG-2ii or above; hyperpolymath/mathesis#APP-2 at PWG-2ii or above; hyperpolymath/mathesis#APP-3 at PWG-2ii or above; hyperpolymath/mathesis#APP-4 at PWG-2ii or above + +*Value (judgement):* maths ●●, economics ●●●, teaching ●● + +[[chain-question]] +==== 🔨 🧩 Is a chain enough? (X-PF1) + +Experiment X-PF1, pre-registered: list each rule, gate and report in the estate that reads a status token (at least the proof-route ABI, the registry and ledger rule 3) and ask whether its result changes between the two members of a fibre. Outcome A, B or C (or D: two tokens the wrong way round) decides the order. + +*Track:* ∑ maths · *Kind:* theorem · *Size:* M · *Status:* active + +*Needs:* xref:claims-registry[📒 Claims registry] + +*Enables:* xref:token-order[⚖️ Settle the order of status tokens] + +*Value (judgement):* maths ●●●, science ●●, soundness ●● + +*See:* `docs/proposals/mathesis-research-programme.adoc`, at `=== What experiment X-PF1 can change`; `docs/proposals/mathesis-research-programme.adoc`, at `the list covers the proof-route ABI, the registry and` + +* ∑ _Mathematician:_ The deepest open question on the board; it decides what S-1 even says. +* 🔬 _Scientist:_ Pre-register what result means A, B or C before computing. + +[[theory-shelf]] +==== ✅ 📚 Theory shelf and ledger + +The admission rule for theory no single system owns, with an append-only ledger of every grade and receipt change. One theorem admitted so far. + +*Track:* ∑ maths · *Kind:* data · *Size:* S · *Status:* done + +*Needs:* xref:claims-registry[📒 Claims registry], xref:thy1[🧭 THY-1: reachability is monotone] + +*Enables:* xref:dossier[🗂️ Theorem dossier], xref:s1-token-algebra[🔢 S-1: tokens form a dioid], xref:s2-monotone[📈 S-2: evaluation is monotone], xref:statistical-bridge[🎲 From oracle to theorem] + +*Evidence:* `docs/theory/admissions.jsonl`; `docs/theory/ledger.jsonl` + +*Value (judgement):* maths ●●, soundness ●● + +[[doc-drift-fix]] +==== 🌱 🧹 Mend the status documents + +ROADMAP, PROOF-NEEDS, README and the intend contract contradict the receipts (PWG-1 vs PWG-2ii, receipts called planned that exist, stage states). Make each agree with the derived facts. + +*Track:* ⚙ engineering · *Kind:* decision · *Size:* S · *Status:* open + +*Needs:* xref:claims-registry[📒 Claims registry] + +*Value (judgement):* teaching ●, soundness ●●● + +*See:* `docs/status/ROADMAP.adoc`, at `=== First theory theorem (2026-11-09)`; `docs/status/PROOF-NEEDS.adoc`, at `Discharged: the receipt derives`; `README.adoc`, at `The token-lattice theorems of the theory shelf, receipts for the cohort model`; `.machine_readable/contractiles/intend` + +* 🃏 _Contrarian:_ Cheapest node on the board, and the auditor's favourite. +* 🔍 _Soundness auditor:_ Every one of these is a claim with no receipt behind it; mend before adding. + +[[receipts]] +==== ✅ 🔏 Proof receipts + +The PROOF-POLICY 8.5.1 receipt of Mathesis: per-leg run, commit, checker, inputs manifest and axioms, checked by the shared git checker and read by the canon reader. + +*Track:* ⚙ engineering · *Kind:* data · *Size:* M · *Status:* done + +*Needs:* xref:proof-gate[🛡️ Proof gate in pinned Guix], xref:claims-registry[📒 Claims registry] + +*Enables:* xref:paper-thy1[📄 Note: feature reachability], xref:receipt-generator[🏭 Shared receipt generator], xref:s3-grade-function[🎚️ S-3: the grade is a function] + +*Evidence:* `verification/receipts/theory_praxis.deed` + +*Value (judgement):* engineering ●●, soundness ●●● + +[[site-build]] +==== ✅ 🏗️ Atlas site (build) + +Renders every generated view with Asciidoctor and fails on any warning or broken link. It builds; it does not deploy. + +*Track:* ⚙ engineering · *Kind:* view · *Size:* S · *Status:* done + +*Needs:* xref:atlas-views[🗺️ Atlas views] + +*Enables:* xref:publish-atlas[🌐 Publish the atlas] + +*Evidence:* `scripts/site/site.mjs` + +*Value (judgement):* engineering ●, teaching ●● + +[[ultraplan]] +==== ✅ 🌳 The ultraplan + +This tech tree: data first, with derived eras, frontier, forks, confluences and advisor picks, and a done that must show evidence. + +*Track:* ⚙ engineering · *Kind:* view · *Size:* S · *Status:* done + +*Needs:* xref:atlas-views[🗺️ Atlas views] + +*Enables:* xref:maths-panel[🪟 Visual proof space] + +*Evidence:* `docs/ultraplan/tree.jsonl`; `scripts/ultraplan/ultraplan.mjs` + +*Value (judgement):* engineering ●, teaching ● + +[[bridge-candidates]] +==== ✅ 🌉 Bridge candidates + +Three unassessed candidate links between theorems in different repositories and provers (tropical MaxPlus, resource-algebra M-2, squeakwell). Candidates, not evidence. + +*Track:* 🗺 ecosystem · *Kind:* data · *Size:* S · *Status:* done + +*Needs:* xref:claims-registry[📒 Claims registry] + +*Enables:* xref:bridge-lock-pilot[🔗 Bridge lock pilot] + +*Evidence:* `docs/atlas/claims/bridges.jsonl` + +*Value (judgement):* maths ●●, ecosystem ●●● + +[[file-transport-bugs]] +==== 🌱 🐛 File the transport reproducers + +File the THY-1 reproducers upstream (E-2.4): the Agda2Dedukti crash and option gaps, and Lambdapi dropping rules. Filing is the owner's act. + +*Track:* 🗺 ecosystem · *Kind:* decision · *Size:* S · *Status:* open · *Beyond this repository:* upstream:Deducteam/agda2dedukti + +*Needs:* xref:thy1[🧭 THY-1: reachability is monotone] + +*Enables:* xref:dedukti-transport[🚂 Transport through Dedukti] + +*Value (judgement):* engineering ●, ecosystem ●● + +*See:* `docs/status/ROADMAP.adoc`, at `Next action: the owner files both reports`; `docs/proposals/mathesis-research-programme.adoc`, at `File the THY-1 reproducer with the translator's authors` + +* 🪙 _Economist:_ A few hours of filing could unblock a whole route for everyone. + +[[whats-owed]] +==== 🌱 📋 What is owed + +A view of the standards requirements master list beside the census and the registry (WO 5.4): what each repository owes, and what it has. + +*Track:* 🗺 ecosystem · *Kind:* view · *Size:* M · *Status:* open + +*Needs:* xref:census-workflow[⏰ Census on a schedule], xref:claims-registry[📒 Claims registry] + +*Enables:* xref:concept-commons[🏛️ Concept commons] + +*Value (judgement):* engineering ●, soundness ●●, ecosystem ●●● + +*See:* `docs/proposals/mathesis-re-anchoring.adoc`, at `WO 5.4 Report what is owed` + +=== 🌌 Era 3: Kepler + +[[dossier]] +==== 🌱 🗂️ Theorem dossier + +The eight-item dossier for each theorem (Line 0), scored first on THY-1, five januskey theorems and two each of secret-types and lintel (E-0). Its home (here or standards, R-5) is still open. + +*Track:* ∑ maths · *Kind:* method · *Size:* S · *Status:* open + +*Needs:* xref:theory-shelf[📚 Theory shelf and ledger] + +*Enables:* xref:januskey-slice[🗝️ Theorem to code: januskey] + +*Value (judgement):* maths ●, teaching ●●, soundness ●● + +*See:* `docs/proposals/mathesis-research-programme.adoc`, at `Describe the method of the previous section as one checklist`; `docs/proposals/mathesis-research-programme.adoc`, at `R-5 The dossier.` + +[[s2-monotone]] +==== 🌱 📈 S-2: evaluation is monotone + +Positive evaluation of status is monotone. It holds for each ordered resource algebra, so it can be proved once against the kernel now, whatever X-PF1 decides (R-3). + +*Track:* ∑ maths · *Kind:* theorem · *Size:* S · *Status:* open + +*Needs:* xref:theory-shelf[📚 Theory shelf and ledger] + +*Enables:* xref:paper-status-algebra[📘 Paper: an algebra of proof status] + +*Value (judgement):* maths ●●, soundness ● + +*See:* `docs/proposals/mathesis-research-programme.adoc`, at `S-2 (positive evaluation is monotone)` + +* 🃏 _Contrarian:_ The one theorem of the line that does not wait for the order: start it early. + +[[s4-s5-verdict]] +==== 🌱 🌦️ S-4 and S-5: honest cash verdicts + +A sound three-valued cash verdict over intervals, where missing means unbounded (S-4), and more uncertainty never strengthens a verdict (S-5). Reuses residual-evidence-types at a pin; pass is PWG-3 (E-4.2). + +*Track:* ∑ maths · *Kind:* theorem · *Size:* M · *Status:* open + +*Needs:* xref:app-proofs[💧 APP-1 to APP-4: missing stays missing] + +*Enables:* xref:liquidity-shelf[💶 Liquidity shelf] + +*Value (judgement):* maths ●●, economics ●●●, teaching ●● + +*See:* `docs/proposals/mathesis-research-programme.adoc`, at `S-4 (a sound cash verdict)`; `docs/proposals/mathesis-research-programme.adoc`, at `Write one synthetic 13-week forecast as records` + +* 🪙 _Economist:_ A forecast that can say undecided is worth more than one that guesses. +* 🍎 _Teacher:_ Three-valued logic with money attached: an easy story to teach. + +[[token-order]] +==== 🌱 ⚖️ Settle the order of status tokens + +Record the order X-PF1 decides, in Mathesis (R-1, provisional) and in the canon. Evidence it must answer: R-1 reads PROOF-POLICY section 5 as open < argued < tested-only, resource-algebra E-1 (PWG-2i) proves open < tested-only < argued, and section 5 itself lists the tokens without stating an order. + +*Track:* ∑ maths · *Kind:* decision · *Size:* S · *Status:* open + +*Needs:* xref:chain-question[🧩 Is a chain enough? (X-PF1)] + +*Enables:* xref:centre-computations[🎯 Centre computations], xref:s1-reuse[♻️ S-1 by reuse of resource-algebra], xref:s1-token-algebra[🔢 S-1: tokens form a dioid], xref:s3-grade-function[🎚️ S-3: the grade is a function] + +*Value (judgement):* maths ●●, soundness ●●●, ecosystem ●● + +*See:* `docs/proposals/mathesis-research-programme.adoc`, at `R-1 The order of the tokens.`; `docs/atlas/generated/registry.adoc`, at `[hyperpolymath/resource-algebra#E-1]`; https://github.com/metadatastician/standards/blob/745fc744158047a675eeb92464167c9961d66c4b/3-practice/PROOF-POLICY.adoc[metadatastician/standards: 3-practice/PROOF-POLICY.adoc] at `745fc7441580`, at `== 5. Status vocabulary` + +* 🗺️ _Estate cartographer:_ The canon order is the owner’s ruling in standards, and resource-algebra E-1 may need re-proving; carry both. +* ∑ _Mathematician:_ Two careful readings disagree; that is a sign the two tokens are incomparable, which is outcome C. + +[[dedukti-transport]] +==== ⛔ 🚂 Transport through Dedukti + +Check an Agda proof in Rocq and Lean by translating it through Dedukti and Lambdapi instead of re-proving it, the route PROOF-POLICY section 2 puts first. + +*Track:* ⚙ engineering · *Kind:* tool · *Size:* L · *Status:* blocked · *Beyond this repository:* upstream:Deducteam/lambdapi + +*Needs:* xref:thy1[🧭 THY-1: reachability is monotone], xref:file-transport-bugs[🐛 File the transport reproducers] + +*Rivals:* xref:bridge-by-construction[🏗 Bridges by construction] + +*Blocked by:* Agda2Dedukti fails on a parameterised record in Set1 and rejects --cubical-compatible; Lambdapi raw_lean and raw_coq drop rewrite rules. A transport row stays a re-proof until a fixed release passes the round trip. + +*Value (judgement):* maths ●, engineering ●●, soundness ●● + +*See:* `docs/status/ROADMAP.adoc`, at `PROOF-POLICY §2 puts Dedukti transport first and a re-proof by hand second.` + +* 🃏 _Contrarian:_ Policy puts this route first, yet every re-proof so far went the other way. + +[[receipt-generator]] +==== 🔨 🏭 Shared receipt generator + +Adopt the standards generator: the receipt is generated from a run ledger, and the gate lists each green run's ledger rows. Pull request 122. + +*Track:* ⚙ engineering · *Kind:* tool · *Size:* M · *Status:* active + +*Needs:* xref:receipts[🔏 Proof receipts] + +*Enables:* xref:ci-recorder[🤖 CI records its own runs], xref:paper-receipts[📰 Paper: receipts, not claims], xref:pwg1-regained[🥇 Back to PWG-1], xref:receipts-campaign[📣 Receipts campaign], xref:superseded-manifests-option[🗄️ Keep superseded manifests (option)] + +*Value (judgement):* engineering ●●●, soundness ●●● + +* ⚙️ _Engineer:_ One generator for the estate instead of one per repository. + +[[statistical-bridge]] +==== 🌱 🎲 From oracle to theorem + +S-MN and S-DM (the multinomial logit closed form and the DM contrast limit) are tested only, against MetaManifold-WebUI as oracle. Prove them in Agda, Rocq and Lean for admission (Q-2.6). + +*Track:* 🔬 science · *Kind:* theorem · *Size:* L · *Status:* open + +*Needs:* xref:theory-shelf[📚 Theory shelf and ledger] + +*Value (judgement):* maths ●●, science ●●●, publications ●● + +*See:* `docs/proposals/mathesis-research-programme.adoc`, at `Q-2.6 Can a statistical oracle become theory?` + +* 🔬 _Scientist:_ Takes a statistical result that is only tested and makes it a theorem. + +[[forecast-13wk]] +==== 🌱 📅 Thirteen-week forecast + +A synthetic thirteen-week cash forecast on the proved cohort model (E-4.1), the first worked decision of the applied shelf. + +*Track:* 🪙 economics · *Kind:* method · *Size:* M · *Status:* open + +*Needs:* xref:app-proofs[💧 APP-1 to APP-4: missing stays missing] + +*Enables:* xref:liquidity-shelf[💶 Liquidity shelf] + +*Value (judgement):* engineering ●, economics ●●●, teaching ●● + +*See:* `docs/proposals/mathesis-research-programme.adoc`, at `Write one synthetic 13-week forecast as records`; `applied-systems/finance/liquidity/README.adoc` + +* 🪙 _Economist:_ The first output a business reader would recognise. + +[[paper-thy1]] +==== 🌱 📄 Note: feature reachability + +A short note on THY-1: why requesting every feature is a sound check for absence, with the three-prover receipt as artefact. Its dependant is a real standards rule. + +*Track:* 📜 publications · *Kind:* paper · *Size:* M · *Status:* open + +*Needs:* xref:thy1[🧭 THY-1: reachability is monotone], xref:receipts[🔏 Proof receipts] + +*Value (judgement):* maths ●, publications ●●●, teaching ● + +* 📜 _Publisher:_ A complete, small, checked result: the easiest first paper. + +[[publish-atlas]] +==== ⛔ 🌐 Publish the atlas + +Deploy the built site (WO 4.3), once the owner says go. Publication is outward-facing, so it is gated on the owner, not on any node. + +*Track:* 📜 publications · *Kind:* view · *Size:* S · *Status:* blocked + +*Needs:* xref:site-build[🏗️ Atlas site (build)] + +*Enables:* xref:talk-atlas[🎤 Talk: an atlas of an estate] + +*Blocked by:* the owner’s go-ahead to deploy (WO 4.3): deploying is outward-facing, so the hold that ended on 2026-11-24 is followed by a fresh owner question, through the decision desk + +*Value (judgement):* publications ●●●, teaching ●●, ecosystem ●● + +*See:* `docs/status/ROADMAP.adoc`, at `WO 4.3, publish the atlas`; `docs/proposals/mathesis-re-anchoring.adoc`, at `WO 4.3 Publish the atlas` + +* 📜 _Publisher:_ Everything else here is invisible until this happens. +* 🔍 _Soundness auditor:_ Publish only views whose checks are green, or the site states what the receipts do not. + +[[teaching-cohort]] +==== 🌱 📓 Cohort economics, taught + +A worked tutorial: a small business model where missing data stays missing, with the proofs alongside and synthetic data only. + +*Track:* 📜 publications · *Kind:* paper · *Size:* M · *Status:* open + +*Needs:* xref:app-proofs[💧 APP-1 to APP-4: missing stays missing] + +*Value (judgement):* economics ●, publications ●●, teaching ●●● + +* 🍎 _Teacher:_ Shows why a proof matters to someone who reads spreadsheets, not theorems. + +[[bridge-lock-pilot]] +==== 🌱 🔗 Bridge lock pilot + +The full bridge record for two pilots, a squeakwell ladder row and resource-algebra to tropical-types (WO 5.2, ruling D-7 a): what is claimed equal, by which map, checked how. + +*Track:* 🗺 ecosystem · *Kind:* method · *Size:* M · *Status:* open + +*Needs:* xref:bridge-candidates[🌉 Bridge candidates] + +*Enables:* xref:centre-computations[🎯 Centre computations], xref:echo-mirrors[🪞 Echo mirror records], xref:encoding-differences[🔤 Closed list of encoding differences], xref:s1-reuse[♻️ S-1 by reuse of resource-algebra] + +*Value (judgement):* maths ●●, science ●, ecosystem ●●● + +*See:* `docs/proposals/mathesis-re-anchoring.adoc`, at `=== The lock`; `docs/proposals/mathesis-re-anchoring.adoc`, at `WO 5.2 Pilot the bridge lock` + +* 🗺️ _Estate cartographer:_ The first real convergence between repositories; everything cross-repo waits on it. +* ∑ _Mathematician:_ Equivalence as identity, made checkable. + +[[maths-panel]] +==== 🌱 🪟 Visual proof space + +Mathesis hosts its own visual proof space (owner ruling 2026-11-25): the tech tree, its frontier, the grade census with its denominator, and the claim pins. The owner’s private me panel lives here too, its notes kept outside this repository and every feed. MPSCI links to it with a summary card. Open decisions go to the owner’s decision desk. + +*Track:* 🗺 ecosystem · *Kind:* view · *Size:* M · *Status:* open + +*Needs:* xref:claims-registry[📒 Claims registry], xref:ultraplan[🌳 The ultraplan] + +*Value (judgement):* engineering ●●, teaching ●, ecosystem ●● + +=== ♾️ Era 4: Cantor + +[[centre-computations]] +==== 🌱 🎯 Centre computations + +Over locked bridges: classes under a criterion, their order, contradictions, and the five different absences (RA 786-801). + +*Track:* ∑ maths · *Kind:* method · *Size:* L · *Status:* open + +*Needs:* xref:bridge-lock-pilot[🔗 Bridge lock pilot], xref:token-order[⚖️ Settle the order of status tokens] + +*Enables:* xref:concept-commons[🏛️ Concept commons], xref:corpus[🧪 Propose and dispose corpus] + +*Value (judgement):* maths ●●●, science ●● + +*See:* `docs/proposals/mathesis-re-anchoring.adoc`, at `=== What the centre computes` + +[[s1-token-algebra]] +==== 🌱 🔢 S-1: tokens form a dioid + +The status tokens form a ResourceAlgebra and dioid with an annihilating zero, with an injective strict morphism into MinMax. Agda against resource-algebra at a pin, re-proved in Rocq and Lean (E-1.1). + +*Track:* ∑ maths · *Kind:* theorem · *Size:* L · *Status:* open + +*Needs:* xref:theory-shelf[📚 Theory shelf and ledger], xref:token-order[⚖️ Settle the order of status tokens] + +*Enables:* xref:bridge-by-construction[🏗 Bridges by construction], xref:idris-token-laws[🧬 Generated Idris2 token laws], xref:paper-status-algebra[📘 Paper: an algebra of proof status] + +*Rivals:* xref:s1-reuse[♻️ S-1 by reuse of resource-algebra] + +*Value (judgement):* maths ●●●, publications ●●, soundness ●● + +*See:* `docs/proposals/mathesis-research-programme.adoc`, at `S-1 (the tokens are a bottleneck grade)`; `docs/proposals/mathesis-research-programme.adoc`, at `Prove S-1 in Agda against` + +* 🃏 _Contrarian:_ resource-algebra already pins E-1 to E-3; proving it again here may be duplication. +* ∑ _Mathematician:_ A real algebra of evidence; the centre of the research programme. + +[[s3-grade-function]] +==== 🌱 🎚️ S-3: the grade is a function + +The Proof Witness Grade is a total monotone function of the receipt, and the canon reader agrees with it on every case, shown by exhaustion as in residual-evidence-types (E-1.3). + +*Track:* ∑ maths · *Kind:* theorem · *Size:* M · *Status:* open + +*Needs:* xref:receipts[🔏 Proof receipts], xref:token-order[⚖️ Settle the order of status tokens] + +*Enables:* xref:corpus[🧪 Propose and dispose corpus], xref:paper-receipts[📰 Paper: receipts, not claims], xref:paper-status-algebra[📘 Paper: an algebra of proof status] + +*Value (judgement):* maths ●●, engineering ●●, soundness ●●● + +*See:* `docs/proposals/mathesis-research-programme.adoc`, at `S-3 (the grade is a function of the receipt)`; `docs/proposals/mathesis-research-programme.adoc`, at `Run the table of S-3 against the canon reader` + +* 🔍 _Soundness auditor:_ Turns the reader from trusted code into a checked one. + +[[ci-recorder]] +==== 🌱 🤖 CI records its own runs + +A trusted publisher that writes each green run's ledger rows to the repository, so no human copies rows. The piece standards PR 1675 leaves open. + +*Track:* ⚙ engineering · *Kind:* infrastructure · *Size:* M · *Status:* open · *Beyond this repository:* estate:metadatastician/standards + +*Needs:* xref:receipt-generator[🏭 Shared receipt generator] + +*Enables:* xref:estate-pwg2ii[🏔️ PWG-2ii across the estate] + +*Value (judgement):* engineering ●●●, soundness ●●, ecosystem ●● + +[[januskey-slice]] +==== 🌱 🗝️ Theorem to code: januskey + +Follow one theorem into running code (E-3.1): the januskey slice T-1, with T-10 open and G-2 assumed, and a composite status for the whole (Q-3.1). + +*Track:* ⚙ engineering · *Kind:* method · *Size:* L · *Status:* open · *Beyond this repository:* estate:hyperpolymath/januskey + +*Needs:* xref:dossier[🗂️ Theorem dossier] + +*Value (judgement):* maths ●, engineering ●●●, soundness ●● + +*See:* `docs/proposals/mathesis-research-programme.adoc`, at `Q-3.1 Can the composite status be computed?`; `docs/proposals/mathesis-research-programme.adoc`, at `as the first vertical slice (ruling R-4)` + +[[pwg1-regained]] +==== 🌱 🥇 Back to PWG-1 + +THY-1 and APP-1 to APP-4 derive PWG-1 again, from receipts whose rows name the pinned image. + +*Track:* ⚙ engineering · *Kind:* data · *Size:* S · *Status:* open + +*Needs:* xref:pinned-image[📦 Proof lanes in a pinned image], xref:receipt-generator[🏭 Shared receipt generator] + +*Value (judgement):* publications ●, soundness ●● + +[[superseded-manifests-option]] +==== 🌱 🗄️ Keep superseded manifests (option) + +A generator option that keeps the inputs digest, manifest and axioms on superseded receipts (owner ruling 2026-11-24). It landed in standards as #1705, and hyperpolymath/mathesis#122 turns it on; it is done when that pull request merges. + +*Track:* ⚙ engineering · *Kind:* tool · *Size:* S · *Status:* open + +*Needs:* xref:receipt-generator[🏭 Shared receipt generator] + +*Value (judgement):* engineering ●, soundness ●●, ecosystem ● + +*See:* https://github.com/metadatastician/standards/issues/1705[metadatastician/standards#1705]; https://github.com/hyperpolymath/mathesis/issues/122[hyperpolymath/mathesis#122] + +* 🃏 _Contrarian:_ The ledger already holds every digest; check the option earns its keep. +* 🔍 _Soundness auditor:_ Lineage you can re-check without git archaeology. + +[[encoding-differences]] +==== 🌱 🔤 Closed list of encoding differences + +A closed, tested list of the ways the same statement differs between Agda, Rocq and Lean (Q-2.1), built from the existing comparisons as bridge records (E-2.1). + +*Track:* 🔬 science · *Kind:* data · *Size:* M · *Status:* open + +*Needs:* xref:bridge-lock-pilot[🔗 Bridge lock pilot] + +*Enables:* xref:bridge-by-construction[🏗 Bridges by construction] + +*Value (judgement):* maths ●, science ●●●, publications ●● + +*See:* `docs/proposals/mathesis-research-programme.adoc`, at `Q-2.1 What must a statement comparison record?`; `docs/proposals/mathesis-research-programme.adoc`, at `Write the five existing comparisons as bridge records` + +* 📜 _Publisher:_ Nobody has this list; it is citable on its own. +* 🔬 _Scientist:_ Each entry should come with a counterexample that shows it. + +[[liquidity-shelf]] +==== 🌱 💶 Liquidity shelf + +The liquidity part of the applied shelf: a forecast whose every verdict carries its proof status, from synthetic data only. + +*Track:* 🪙 economics · *Kind:* view · *Size:* M · *Status:* open + +*Needs:* xref:s4-s5-verdict[🌦️ S-4 and S-5: honest cash verdicts], xref:forecast-13wk[📅 Thirteen-week forecast] + +*Enables:* xref:value-of-information[🔭 Value of information] + +*Value (judgement):* economics ●●●, publications ●, teaching ●● + +[[talk-atlas]] +==== 🌱 🎤 Talk: an atlas of an estate + +A talk on mapping the mathematics of hundreds of repositories, with every status traced to a receipt. + +*Track:* 📜 publications · *Kind:* paper · *Size:* S · *Status:* open + +*Needs:* xref:publish-atlas[🌐 Publish the atlas] + +*Value (judgement):* publications ●●, teaching ●●, ecosystem ● + +[[echo-mirrors]] +==== 🌱 🪞 Echo mirror records + +Bridge records for the six languages that mirror echo-types (E-2.5), with the graded-comonad disagreement kept as an open question. + +*Track:* 🗺 ecosystem · *Kind:* data · *Size:* M · *Status:* open · *Beyond this repository:* estate:hyperpolymath/echo-types + +*Needs:* xref:bridge-lock-pilot[🔗 Bridge lock pilot] + +*Value (judgement):* maths ●●, ecosystem ●● + +*See:* `docs/proposals/mathesis-research-programme.adoc`, at `Write one bridge record for each of the six Echo mirrors` + +[[receipts-campaign]] +==== 🌱 📣 Receipts campaign + +Home repositories re-record their receipts (WO 5.1): secret-types and lintel for the reader they fail, resource-algebra for its Lean leg. Takes the ungraded theorems towards a grade. + +*Track:* 🗺 ecosystem · *Kind:* method · *Size:* L · *Status:* open · *Beyond this repository:* estate:hyperpolymath/secret-types + +*Needs:* xref:receipt-generator[🏭 Shared receipt generator] + +*Enables:* xref:estate-pwg2ii[🏔️ PWG-2ii across the estate] + +*Value (judgement):* soundness ●●, ecosystem ●●● + +*See:* `docs/status/ROADMAP.adoc`, at `(re-anchoring plan WO 5.1)`; `docs/proposals/mathesis-re-anchoring.adoc`, at `WO 5.1 Bring receipts to the home repositories` + +* 🗺️ _Estate cartographer:_ The registry is only as current as the home receipts. + +[[s1-reuse]] +==== 🌱 ♻️ S-1 by reuse of resource-algebra + +Prove only the morphism here, and take the dioid laws from resource-algebra's E-1 to E-3 (already PWG-2i) through a locked bridge, instead of proving them again. + +*Track:* 🗺 ecosystem · *Kind:* theorem · *Size:* M · *Status:* open · *Beyond this repository:* estate:hyperpolymath/resource-algebra + +*Needs:* xref:bridge-lock-pilot[🔗 Bridge lock pilot], xref:token-order[⚖️ Settle the order of status tokens] + +*Rivals:* xref:s1-token-algebra[🔢 S-1: tokens form a dioid] + +*Value (judgement):* maths ●●, engineering ●, ecosystem ●●● + +* 🗺️ _Estate cartographer:_ Converge: the laws exist, at a grade, in their home repository. + +=== 🧩 Era 5: Gödel + +[[concept-commons]] +==== 🌱 🏛️ Concept commons + +The horizon of the atlas (M4): a commons of the estate's concepts, navigable by A to Z, subject (MSC2020), project and provenance. + +*Track:* ∑ maths · *Kind:* view · *Size:* XL · *Status:* open + +*Needs:* xref:centre-computations[🎯 Centre computations], xref:whats-owed[📋 What is owed] + +*Value (judgement):* maths ●●, teaching ●●●, ecosystem ●● + +*See:* `docs/proposals/mathesis-re-anchoring.adoc`, at `M4. Concept commons`; `docs/proposals/estate-mathematical-architecture.adoc`, at `4. Navigation Views` + +[[bridge-by-construction]] +==== 🌱 🏗 Bridges by construction + +Generate the Agda, Rocq and Lean forms of a statement from one source (Q-2.3, E-2.3), so a re-proof starts from a statement known to match. + +*Track:* ⚙ engineering · *Kind:* tool · *Size:* L · *Status:* open + +*Needs:* xref:encoding-differences[🔤 Closed list of encoding differences], xref:s1-token-algebra[🔢 S-1: tokens form a dioid] + +*Enables:* xref:corpus[🧪 Propose and dispose corpus] + +*Rivals:* xref:dedukti-transport[🚂 Transport through Dedukti] + +*Value (judgement):* maths ●●, engineering ●●●, publications ● + +*See:* `docs/proposals/mathesis-research-programme.adoc`, at `Q-2.3 Can a bridge hold by construction?`; `docs/proposals/mathesis-research-programme.adoc`, at `Generate the three forms of S-1 from one source` + +* ⚙️ _Engineer:_ Removes the hand-copying of statements that every re-proof does today. + +[[idris-token-laws]] +==== 🌱 🧬 Generated Idris2 token laws + +Generate the Idris2 token laws of the proof-route Token module from S-1 (E-3.2), so the engineering side cites the theorem instead of restating it. + +*Track:* ⚙ engineering · *Kind:* tool · *Size:* M · *Status:* open · *Beyond this repository:* estate:metadatastician/standards + +*Needs:* xref:s1-token-algebra[🔢 S-1: tokens form a dioid] + +*Value (judgement):* maths ●, engineering ●●, ecosystem ●● + +*See:* `docs/proposals/mathesis-research-programme.adoc`, at `Generate the Idris2 statement of the token laws from the source of` + +[[value-of-information]] +==== 🌱 🔭 Value of information + +Decision science on the shelf: what a missing input is worth to know, computed from the three-valued verdicts. No optimiser (decision-science README). + +*Track:* 🪙 economics · *Kind:* method · *Size:* L · *Status:* open + +*Needs:* xref:liquidity-shelf[💶 Liquidity shelf] + +*Value (judgement):* maths ●●, science ●●, economics ●●● + +*See:* `applied-systems/decision-science/README.adoc` + +[[paper-receipts]] +==== 🌱 📰 Paper: receipts, not claims + +A methods paper: proof status derived from machine receipts, graded by witness count, never typed, with the registry as a working instance across an estate. + +*Track:* 📜 publications · *Kind:* paper · *Size:* L · *Status:* open + +*Needs:* xref:receipt-generator[🏭 Shared receipt generator], xref:claims-registry[📒 Claims registry], xref:s3-grade-function[🎚️ S-3: the grade is a function] + +*Value (judgement):* engineering ●, publications ●●●, soundness ●● + +[[paper-status-algebra]] +==== 🌱 📘 Paper: an algebra of proof status + +S-1 to S-3 written up: proof status as a dioid, its monotone evaluation, and the grade as a checked function of the receipt. + +*Track:* 📜 publications · *Kind:* paper · *Size:* L · *Status:* open + +*Needs:* xref:s1-token-algebra[🔢 S-1: tokens form a dioid], xref:s2-monotone[📈 S-2: evaluation is monotone], xref:s3-grade-function[🎚️ S-3: the grade is a function] + +*Value (judgement):* maths ●●●, publications ●●● + +=== 🌀 Era 6: Grothendieck + +[[corpus]] +==== 🌱 🧪 Propose and dispose corpus + +A corpus as a view over bridges and receipts (E-H.1), and 20 ungraded Agda theorems given model-proposed Rocq and Lean legs, kept BRIDGE-PENDING until checked (E-H.2). + +*Track:* 🔬 science · *Kind:* method · *Size:* XL · *Status:* open + +*Needs:* xref:bridge-by-construction[🏗 Bridges by construction], xref:centre-computations[🎯 Centre computations], xref:s3-grade-function[🎚️ S-3: the grade is a function] + +*Enables:* xref:estate-pwg2ii[🏔️ PWG-2ii across the estate] + +*Value (judgement):* maths ●●, engineering ●●, science ●●● + +*See:* `docs/proposals/mathesis-research-programme.adoc`, at `Define the corpus as a view over bridge records and receipts` + +=== 🚀 Era 7: Frontier beyond + +[[estate-pwg2ii]] +==== 🌱 🏔️ PWG-2ii across the estate + +The long horizon (Q-H.3): the 900 and more ungraded theorems of the estate each carry two checked recheck legs. The question is whether that takes months or years. + +*Track:* 🗺 ecosystem · *Kind:* data · *Size:* XL · *Status:* open + +*Needs:* xref:corpus[🧪 Propose and dispose corpus], xref:receipts-campaign[📣 Receipts campaign], xref:ci-recorder[🤖 CI records its own runs] + +*Value (judgement):* maths ●●, science ●, soundness ●●●, ecosystem ●●● + +*See:* `docs/proposals/mathesis-research-programme.adoc`, at `Q-H.3 What does a recheck leg cost?`; `docs/proposals/mathesis-research-programme.adoc`, at `A measured cost for a recheck leg, and with it a` + +== Return tickets + +Wandering off the tree is allowed. Each trip gets a card: what, why, and how big. +On return it is grafted onto the tree as a node, or archived with what it taught. + +No trip is out. + +== Beyond this repository + +Nodes whose work lands in another repository. They are listed here so they can be +carried to that repository, not done here. + +* estate:hyperpolymath/echo-types: xref:echo-mirrors[🪞 Echo mirror records] (open) +* estate:hyperpolymath/januskey: xref:januskey-slice[🗝️ Theorem to code: januskey] (open) +* estate:hyperpolymath/resource-algebra: xref:s1-reuse[♻️ S-1 by reuse of resource-algebra] (open) +* estate:hyperpolymath/secret-types: xref:receipts-campaign[📣 Receipts campaign] (open) +* estate:metadatastician/standards: xref:ci-recorder[🤖 CI records its own runs] (open) +* estate:metadatastician/standards: xref:idris-token-laws[🧬 Generated Idris2 token laws] (open) +* upstream:Deducteam/agda2dedukti: xref:file-transport-bugs[🐛 File the transport reproducers] (open) +* upstream:Deducteam/lambdapi: xref:dedukti-transport[🚂 Transport through Dedukti] (blocked) diff --git a/docs/ultraplan/tree.jsonl b/docs/ultraplan/tree.jsonl new file mode 100644 index 00000000..b9eed8a9 --- /dev/null +++ b/docs/ultraplan/tree.jsonl @@ -0,0 +1,52 @@ +{"evidence":[{"claim":"hyperpolymath/mathesis#APP-1","min_pwg":"PWG-2ii"},{"claim":"hyperpolymath/mathesis#APP-2","min_pwg":"PWG-2ii"},{"claim":"hyperpolymath/mathesis#APP-3","min_pwg":"PWG-2ii"},{"claim":"hyperpolymath/mathesis#APP-4","min_pwg":"PWG-2ii"}],"glyph":"💧","id":"app-proofs","kind":"theorem","name":"APP-1 to APP-4: missing stays missing","needs":["cohort-model"],"size":"M","status":"done","summary":"Missing inputs propagate and never read as zero; the cash identity; the least funding gap; status never upgrades. Each proved in Agda, Rocq and Lean.","track":"maths","value":{"economics":3,"maths":2,"teaching":2}} +{"evidence":[{"path":"docs/atlas/generated/catalogue.adoc"},{"path":"docs/atlas/generated/az.adoc"}],"glyph":"🗺️","id":"atlas-views","kind":"view","name":"Atlas views","needs":["census"],"size":"M","status":"done","summary":"The catalogue and the A to Z and organisation views, generated from the census rows and checked for staleness by just check-views.","track":"engineering","value":{"ecosystem":2,"engineering":2,"teaching":2}} +{"counsel":{"engineering":"Removes the hand-copying of statements that every re-proof does today."},"glyph":"🏗","id":"bridge-by-construction","kind":"tool","name":"Bridges by construction","needs":["encoding-differences","s1-token-algebra"],"refs":[{"at":"Q-2.3 Can a bridge hold by construction?","path":"docs/proposals/mathesis-research-programme.adoc"},{"at":"Generate the three forms of S-1 from one source","path":"docs/proposals/mathesis-research-programme.adoc"}],"rivals":["dedukti-transport"],"size":"L","status":"open","summary":"Generate the Agda, Rocq and Lean forms of a statement from one source (Q-2.3, E-2.3), so a re-proof starts from a statement known to match.","track":"engineering","value":{"engineering":3,"maths":2,"publications":1}} +{"evidence":[{"path":"docs/atlas/claims/bridges.jsonl"}],"glyph":"🌉","id":"bridge-candidates","kind":"data","name":"Bridge candidates","needs":["claims-registry"],"size":"S","status":"done","summary":"Three unassessed candidate links between theorems in different repositories and provers (tropical MaxPlus, resource-algebra M-2, squeakwell). Candidates, not evidence.","track":"ecosystem","value":{"ecosystem":3,"maths":2}} +{"counsel":{"cartographer":"The first real convergence between repositories; everything cross-repo waits on it.","maths":"Equivalence as identity, made checkable."},"glyph":"🔗","id":"bridge-lock-pilot","kind":"method","name":"Bridge lock pilot","needs":["bridge-candidates"],"refs":[{"at":"=== The lock","path":"docs/proposals/mathesis-re-anchoring.adoc"},{"at":"WO 5.2 Pilot the bridge lock","path":"docs/proposals/mathesis-re-anchoring.adoc"}],"size":"M","status":"open","summary":"The full bridge record for two pilots, a squeakwell ladder row and resource-algebra to tropical-types (WO 5.2, ruling D-7 a): what is claimed equal, by which map, checked how.","track":"ecosystem","value":{"ecosystem":3,"maths":2,"science":1}} +{"evidence":[{"path":"docs/atlas/census/rows.jsonl"},{"path":"scripts/census/run-census.sh"}],"glyph":"🧾","id":"census","kind":"data","name":"Census of the estate","size":"L","status":"done","summary":"The proof census of the public repositories: a row for each proof file, with its holes and axioms, at a pinned commit and time.","track":"engineering","value":{"ecosystem":3,"engineering":2,"science":2}} +{"glyph":"⏰","id":"census-workflow","kind":"infrastructure","name":"Census on a schedule","needs":["census"],"refs":[{"at":"WO 5.3 Schedule the census","path":"docs/proposals/mathesis-re-anchoring.adoc"}],"size":"M","status":"open","summary":"A scheduled census workflow as the one writer of the census rows (WO 5.3), so refreshes stop arriving by hand and unrecorded.","track":"engineering","value":{"ecosystem":2,"engineering":2}} +{"glyph":"🎯","id":"centre-computations","kind":"method","name":"Centre computations","needs":["bridge-lock-pilot","token-order"],"refs":[{"at":"=== What the centre computes","path":"docs/proposals/mathesis-re-anchoring.adoc"}],"size":"L","status":"open","summary":"Over locked bridges: classes under a criterion, their order, contradictions, and the five different absences (RA 786-801).","track":"maths","value":{"maths":3,"science":2}} +{"counsel":{"maths":"The deepest open question on the board; it decides what S-1 even says.","science":"Pre-register what result means A, B or C before computing."},"glyph":"🧩","id":"chain-question","kind":"theorem","name":"Is a chain enough? (X-PF1)","needs":["claims-registry"],"refs":[{"at":"=== What experiment X-PF1 can change","path":"docs/proposals/mathesis-research-programme.adoc"},{"at":"the list covers the proof-route ABI, the registry and","path":"docs/proposals/mathesis-research-programme.adoc"}],"size":"M","status":"active","summary":"Experiment X-PF1, pre-registered: list each rule, gate and report in the estate that reads a status token (at least the proof-route ABI, the registry and ledger rule 3) and ask whether its result changes between the two members of a fibre. Outcome A, B or C (or D: two tokens the wrong way round) decides the order.","track":"maths","value":{"maths":3,"science":2,"soundness":2}} +{"glyph":"🤖","id":"ci-recorder","kind":"infrastructure","name":"CI records its own runs","needs":["receipt-generator"],"size":"M","status":"open","summary":"A trusted publisher that writes each green run's ledger rows to the repository, so no human copies rows. The piece standards PR 1675 leaves open.","track":"engineering","value":{"ecosystem":2,"engineering":3,"soundness":2},"where":"estate:metadatastician/standards"} +{"evidence":[{"adr":"0004"},{"path":"docs/atlas/generated/registry.adoc"}],"glyph":"📒","id":"claims-registry","kind":"tool","name":"Claims registry","needs":["census"],"size":"L","status":"done","summary":"Pins each claim in its home repository and derives each grade from the home receipt with the pinned canon reader. No grade is typed.","track":"engineering","value":{"ecosystem":3,"engineering":3,"soundness":3}} +{"evidence":[{"path":"verification/proofs/agda/Applied/Cohort.agda"},{"path":"applied-systems/methods/input-schema.adoc"}],"glyph":"👥","id":"cohort-model","kind":"method","name":"Cohort model in Agda","needs":["proof-gate"],"size":"M","status":"done","summary":"The cohort-economics model of the applied shelf, with three number modes and synthetic examples generated into Agda from JSON Lines.","track":"maths","value":{"economics":2,"maths":2,"teaching":2}} +{"glyph":"🏛️","id":"concept-commons","kind":"view","name":"Concept commons","needs":["centre-computations","whats-owed"],"refs":[{"at":"M4. Concept commons","path":"docs/proposals/mathesis-re-anchoring.adoc"},{"at":"4. Navigation Views","path":"docs/proposals/estate-mathematical-architecture.adoc"}],"size":"XL","status":"open","summary":"The horizon of the atlas (M4): a commons of the estate's concepts, navigable by A to Z, subject (MSC2020), project and provenance.","track":"maths","value":{"ecosystem":2,"maths":2,"teaching":3}} +{"glyph":"🧪","id":"corpus","kind":"method","name":"Propose and dispose corpus","needs":["bridge-by-construction","centre-computations","s3-grade-function"],"refs":[{"at":"Define the corpus as a view over bridge records and receipts","path":"docs/proposals/mathesis-research-programme.adoc"}],"size":"XL","status":"open","summary":"A corpus as a view over bridges and receipts (E-H.1), and 20 ungraded Agda theorems given model-proposed Rocq and Lean legs, kept BRIDGE-PENDING until checked (E-H.2).","track":"science","value":{"engineering":2,"maths":2,"science":3}} +{"blocked_by":"Agda2Dedukti fails on a parameterised record in Set1 and rejects --cubical-compatible; Lambdapi raw_lean and raw_coq drop rewrite rules. A transport row stays a re-proof until a fixed release passes the round trip.","counsel":{"contrarian":"Policy puts this route first, yet every re-proof so far went the other way."},"glyph":"🚂","id":"dedukti-transport","kind":"tool","name":"Transport through Dedukti","needs":["thy1","file-transport-bugs"],"refs":[{"at":"PROOF-POLICY §2 puts Dedukti transport first and a re-proof by hand second.","path":"docs/status/ROADMAP.adoc"}],"rivals":["bridge-by-construction"],"size":"L","status":"blocked","summary":"Check an Agda proof in Rocq and Lean by translating it through Dedukti and Lambdapi instead of re-proving it, the route PROOF-POLICY section 2 puts first.","track":"engineering","value":{"engineering":2,"maths":1,"soundness":2},"where":"upstream:Deducteam/lambdapi"} +{"counsel":{"contrarian":"Cheapest node on the board, and the auditor's favourite.","soundness":"Every one of these is a claim with no receipt behind it; mend before adding."},"glyph":"🧹","id":"doc-drift-fix","kind":"decision","name":"Mend the status documents","needs":["claims-registry"],"refs":[{"at":"=== First theory theorem (2026-11-09)","path":"docs/status/ROADMAP.adoc"},{"at":"Discharged: the receipt derives","path":"docs/status/PROOF-NEEDS.adoc"},{"at":"The token-lattice theorems of the theory shelf, receipts for the cohort model","path":"README.adoc"},{"path":".machine_readable/contractiles/intend"}],"size":"S","status":"open","summary":"ROADMAP, PROOF-NEEDS, README and the intend contract contradict the receipts (PWG-1 vs PWG-2ii, receipts called planned that exist, stage states). Make each agree with the derived facts.","track":"engineering","value":{"soundness":3,"teaching":1}} +{"glyph":"🗂️","id":"dossier","kind":"method","name":"Theorem dossier","needs":["theory-shelf"],"refs":[{"at":"Describe the method of the previous section as one checklist","path":"docs/proposals/mathesis-research-programme.adoc"},{"at":"R-5 The dossier.","path":"docs/proposals/mathesis-research-programme.adoc"}],"size":"S","status":"open","summary":"The eight-item dossier for each theorem (Line 0), scored first on THY-1, five januskey theorems and two each of secret-types and lintel (E-0). Its home (here or standards, R-5) is still open.","track":"maths","value":{"maths":1,"soundness":2,"teaching":2}} +{"glyph":"🪞","id":"echo-mirrors","kind":"data","name":"Echo mirror records","needs":["bridge-lock-pilot"],"refs":[{"at":"Write one bridge record for each of the six Echo mirrors","path":"docs/proposals/mathesis-research-programme.adoc"}],"size":"M","status":"open","summary":"Bridge records for the six languages that mirror echo-types (E-2.5), with the graded-comonad disagreement kept as an open question.","track":"ecosystem","value":{"ecosystem":2,"maths":2},"where":"estate:hyperpolymath/echo-types"} +{"counsel":{"publications":"Nobody has this list; it is citable on its own.","science":"Each entry should come with a counterexample that shows it."},"glyph":"🔤","id":"encoding-differences","kind":"data","name":"Closed list of encoding differences","needs":["bridge-lock-pilot"],"refs":[{"at":"Q-2.1 What must a statement comparison record?","path":"docs/proposals/mathesis-research-programme.adoc"},{"at":"Write the five existing comparisons as bridge records","path":"docs/proposals/mathesis-research-programme.adoc"}],"size":"M","status":"open","summary":"A closed, tested list of the ways the same statement differs between Agda, Rocq and Lean (Q-2.1), built from the existing comparisons as bridge records (E-2.1).","track":"science","value":{"maths":1,"publications":2,"science":3}} +{"glyph":"🏔️","id":"estate-pwg2ii","kind":"data","name":"PWG-2ii across the estate","needs":["corpus","receipts-campaign","ci-recorder"],"refs":[{"at":"Q-H.3 What does a recheck leg cost?","path":"docs/proposals/mathesis-research-programme.adoc"},{"at":"A measured cost for a recheck leg, and with it a","path":"docs/proposals/mathesis-research-programme.adoc"}],"size":"XL","status":"open","summary":"The long horizon (Q-H.3): the 900 and more ungraded theorems of the estate each carry two checked recheck legs. The question is whether that takes months or years.","track":"ecosystem","value":{"ecosystem":3,"maths":2,"science":1,"soundness":3}} +{"counsel":{"economics":"A few hours of filing could unblock a whole route for everyone."},"glyph":"🐛","id":"file-transport-bugs","kind":"decision","name":"File the transport reproducers","needs":["thy1"],"refs":[{"at":"Next action: the owner files both reports","path":"docs/status/ROADMAP.adoc"},{"at":"File the THY-1 reproducer with the translator's authors","path":"docs/proposals/mathesis-research-programme.adoc"}],"size":"S","status":"open","summary":"File the THY-1 reproducers upstream (E-2.4): the Agda2Dedukti crash and option gaps, and Lambdapi dropping rules. Filing is the owner's act.","track":"ecosystem","value":{"ecosystem":2,"engineering":1},"where":"upstream:Deducteam/agda2dedukti"} +{"counsel":{"economics":"The first output a business reader would recognise."},"glyph":"📅","id":"forecast-13wk","kind":"method","name":"Thirteen-week forecast","needs":["app-proofs"],"owner_value":"high","refs":[{"at":"Write one synthetic 13-week forecast as records","path":"docs/proposals/mathesis-research-programme.adoc"},{"path":"applied-systems/finance/liquidity/README.adoc"}],"size":"M","status":"open","summary":"A synthetic thirteen-week cash forecast on the proved cohort model (E-4.1), the first worked decision of the applied shelf.","track":"economics","value":{"economics":3,"engineering":1,"teaching":2}} +{"glyph":"🪟","id":"maths-panel","kind":"view","name":"Visual proof space","needs":["claims-registry","ultraplan"],"size":"M","status":"open","summary":"Mathesis hosts its own visual proof space (owner ruling 2026-11-25): the tech tree, its frontier, the grade census with its denominator, and the claim pins. The owner’s private me panel lives here too, its notes kept outside this repository and every feed. MPSCI links to it with a summary card. Open decisions go to the owner’s decision desk.","track":"ecosystem","value":{"ecosystem":2,"engineering":2,"teaching":1}} +{"glyph":"🧬","id":"idris-token-laws","kind":"tool","name":"Generated Idris2 token laws","needs":["s1-token-algebra"],"refs":[{"at":"Generate the Idris2 statement of the token laws from the source of","path":"docs/proposals/mathesis-research-programme.adoc"}],"size":"M","status":"open","summary":"Generate the Idris2 token laws of the proof-route Token module from S-1 (E-3.2), so the engineering side cites the theorem instead of restating it.","track":"engineering","value":{"ecosystem":2,"engineering":2,"maths":1},"where":"estate:metadatastician/standards"} +{"glyph":"🗝️","id":"januskey-slice","kind":"method","name":"Theorem to code: januskey","needs":["dossier"],"refs":[{"at":"Q-3.1 Can the composite status be computed?","path":"docs/proposals/mathesis-research-programme.adoc"},{"at":"as the first vertical slice (ruling R-4)","path":"docs/proposals/mathesis-research-programme.adoc"}],"size":"L","status":"open","summary":"Follow one theorem into running code (E-3.1): the januskey slice T-1, with T-10 open and G-2 assumed, and a composite status for the whole (Q-3.1).","track":"engineering","value":{"engineering":3,"maths":1,"soundness":2},"where":"estate:hyperpolymath/januskey"} +{"glyph":"💶","id":"liquidity-shelf","kind":"view","name":"Liquidity shelf","needs":["s4-s5-verdict","forecast-13wk"],"size":"M","status":"open","summary":"The liquidity part of the applied shelf: a forecast whose every verdict carries its proof status, from synthetic data only.","track":"economics","value":{"economics":3,"publications":1,"teaching":2}} +{"glyph":"📰","id":"paper-receipts","kind":"paper","name":"Paper: receipts, not claims","needs":["receipt-generator","claims-registry","s3-grade-function"],"size":"L","status":"open","summary":"A methods paper: proof status derived from machine receipts, graded by witness count, never typed, with the registry as a working instance across an estate.","track":"publications","value":{"engineering":1,"publications":3,"soundness":2}} +{"glyph":"📘","id":"paper-status-algebra","kind":"paper","name":"Paper: an algebra of proof status","needs":["s1-token-algebra","s2-monotone","s3-grade-function"],"size":"L","status":"open","summary":"S-1 to S-3 written up: proof status as a dioid, its monotone evaluation, and the grade as a checked function of the receipt.","track":"publications","value":{"maths":3,"publications":3}} +{"counsel":{"publications":"A complete, small, checked result: the easiest first paper."},"glyph":"📄","id":"paper-thy1","kind":"paper","name":"Note: feature reachability","needs":["thy1","receipts"],"owner_value":"high","size":"M","status":"open","summary":"A short note on THY-1: why requesting every feature is a sound check for absence, with the three-prover receipt as artefact. Its dependant is a real standards rule.","track":"publications","value":{"maths":1,"publications":3,"teaching":1}} +{"counsel":{"soundness":"The only road back to PWG-1 for THY-1 and APP-1 to APP-4."},"glyph":"📦","id":"pinned-image","kind":"infrastructure","name":"Proof lanes in a pinned image","needs":["proof-gate"],"refs":[{"at":"standards#1625 (2026-11-17)","path":"docs/status/PROOF-STATUS.adoc"}],"size":"M","status":"open","summary":"Run the three proof lanes in a container image pinned by digest, the condition PROOF-POLICY now sets for PWG-1 (standards#1625). The Guix shell alone does not qualify.","track":"engineering","value":{"engineering":2,"soundness":3}} +{"evidence":[{"path":"scripts/check-proofs.sh"},{"path":"tests/proofs/gate_controls_test.sh"}],"glyph":"🛡️","id":"proof-gate","kind":"infrastructure","name":"Proof gate in pinned Guix","size":"L","status":"done","summary":"Agda 2.7.0.1, Rocq 8.18.0 and Lean 4.29.0 check every gated module on every commit, with an axiom audit over theorems and definitions and planted controls that must fail.","track":"engineering","value":{"engineering":3,"soundness":3}} +{"blocked_by":"the owner’s go-ahead to deploy (WO 4.3): deploying is outward-facing, so the hold that ended on 2026-11-24 is followed by a fresh owner question, through the decision desk","counsel":{"publications":"Everything else here is invisible until this happens.","soundness":"Publish only views whose checks are green, or the site states what the receipts do not."},"glyph":"🌐","id":"publish-atlas","kind":"view","name":"Publish the atlas","needs":["site-build"],"refs":[{"at":"WO 4.3, publish the atlas","path":"docs/status/ROADMAP.adoc"},{"at":"WO 4.3 Publish the atlas","path":"docs/proposals/mathesis-re-anchoring.adoc"}],"size":"S","status":"blocked","summary":"Deploy the built site (WO 4.3), once the owner says go. Publication is outward-facing, so it is gated on the owner, not on any node.","track":"publications","value":{"ecosystem":2,"publications":3,"teaching":2}} +{"glyph":"🥇","id":"pwg1-regained","kind":"data","name":"Back to PWG-1","needs":["pinned-image","receipt-generator"],"size":"S","status":"open","summary":"THY-1 and APP-1 to APP-4 derive PWG-1 again, from receipts whose rows name the pinned image.","track":"engineering","value":{"publications":1,"soundness":2}} +{"counsel":{"engineering":"One generator for the estate instead of one per repository."},"glyph":"🏭","id":"receipt-generator","kind":"tool","name":"Shared receipt generator","needs":["receipts"],"size":"M","status":"active","summary":"Adopt the standards generator: the receipt is generated from a run ledger, and the gate lists each green run's ledger rows. Pull request 122.","track":"engineering","value":{"engineering":3,"soundness":3}} +{"evidence":[{"path":"verification/receipts/theory_praxis.deed"}],"glyph":"🔏","id":"receipts","kind":"data","name":"Proof receipts","needs":["proof-gate","claims-registry"],"size":"M","status":"done","summary":"The PROOF-POLICY 8.5.1 receipt of Mathesis: per-leg run, commit, checker, inputs manifest and axioms, checked by the shared git checker and read by the canon reader.","track":"engineering","value":{"engineering":2,"soundness":3}} +{"counsel":{"cartographer":"The registry is only as current as the home receipts."},"glyph":"📣","id":"receipts-campaign","kind":"method","name":"Receipts campaign","needs":["receipt-generator"],"refs":[{"at":"(re-anchoring plan WO 5.1)","path":"docs/status/ROADMAP.adoc"},{"at":"WO 5.1 Bring receipts to the home repositories","path":"docs/proposals/mathesis-re-anchoring.adoc"}],"size":"L","status":"open","summary":"Home repositories re-record their receipts (WO 5.1): secret-types and lintel for the reader they fail, resource-algebra for its Lean leg. Takes the ungraded theorems towards a grade.","track":"ecosystem","value":{"ecosystem":3,"soundness":2},"where":"estate:hyperpolymath/secret-types"} +{"counsel":{"cartographer":"Converge: the laws exist, at a grade, in their home repository."},"glyph":"♻️","id":"s1-reuse","kind":"theorem","name":"S-1 by reuse of resource-algebra","needs":["bridge-lock-pilot","token-order"],"rivals":["s1-token-algebra"],"size":"M","status":"open","summary":"Prove only the morphism here, and take the dioid laws from resource-algebra's E-1 to E-3 (already PWG-2i) through a locked bridge, instead of proving them again.","track":"ecosystem","value":{"ecosystem":3,"engineering":1,"maths":2},"where":"estate:hyperpolymath/resource-algebra"} +{"counsel":{"contrarian":"resource-algebra already pins E-1 to E-3; proving it again here may be duplication.","maths":"A real algebra of evidence; the centre of the research programme."},"glyph":"🔢","id":"s1-token-algebra","kind":"theorem","name":"S-1: tokens form a dioid","needs":["theory-shelf","token-order"],"refs":[{"at":"S-1 (the tokens are a bottleneck grade)","path":"docs/proposals/mathesis-research-programme.adoc"},{"at":"Prove S-1 in Agda against","path":"docs/proposals/mathesis-research-programme.adoc"}],"rivals":["s1-reuse"],"size":"L","status":"open","summary":"The status tokens form a ResourceAlgebra and dioid with an annihilating zero, with an injective strict morphism into MinMax. Agda against resource-algebra at a pin, re-proved in Rocq and Lean (E-1.1).","track":"maths","value":{"maths":3,"publications":2,"soundness":2}} +{"counsel":{"contrarian":"The one theorem of the line that does not wait for the order: start it early."},"glyph":"📈","id":"s2-monotone","kind":"theorem","name":"S-2: evaluation is monotone","needs":["theory-shelf"],"refs":[{"at":"S-2 (positive evaluation is monotone)","path":"docs/proposals/mathesis-research-programme.adoc"}],"size":"S","status":"open","summary":"Positive evaluation of status is monotone. It holds for each ordered resource algebra, so it can be proved once against the kernel now, whatever X-PF1 decides (R-3).","track":"maths","value":{"maths":2,"soundness":1}} +{"counsel":{"soundness":"Turns the reader from trusted code into a checked one."},"glyph":"🎚️","id":"s3-grade-function","kind":"theorem","name":"S-3: the grade is a function","needs":["receipts","token-order"],"refs":[{"at":"S-3 (the grade is a function of the receipt)","path":"docs/proposals/mathesis-research-programme.adoc"},{"at":"Run the table of S-3 against the canon reader","path":"docs/proposals/mathesis-research-programme.adoc"}],"size":"M","status":"open","summary":"The Proof Witness Grade is a total monotone function of the receipt, and the canon reader agrees with it on every case, shown by exhaustion as in residual-evidence-types (E-1.3).","track":"maths","value":{"engineering":2,"maths":2,"soundness":3}} +{"counsel":{"economics":"A forecast that can say undecided is worth more than one that guesses.","teacher":"Three-valued logic with money attached: an easy story to teach."},"glyph":"🌦️","id":"s4-s5-verdict","kind":"theorem","name":"S-4 and S-5: honest cash verdicts","needs":["app-proofs"],"refs":[{"at":"S-4 (a sound cash verdict)","path":"docs/proposals/mathesis-research-programme.adoc"},{"at":"Write one synthetic 13-week forecast as records","path":"docs/proposals/mathesis-research-programme.adoc"}],"size":"M","status":"open","summary":"A sound three-valued cash verdict over intervals, where missing means unbounded (S-4), and more uncertainty never strengthens a verdict (S-5). Reuses residual-evidence-types at a pin; pass is PWG-3 (E-4.2).","track":"maths","value":{"economics":3,"maths":2,"teaching":2}} +{"evidence":[{"path":"scripts/site/site.mjs"}],"glyph":"🏗️","id":"site-build","kind":"view","name":"Atlas site (build)","needs":["atlas-views"],"size":"S","status":"done","summary":"Renders every generated view with Asciidoctor and fails on any warning or broken link. It builds; it does not deploy.","track":"engineering","value":{"engineering":1,"teaching":2}} +{"counsel":{"science":"Takes a statistical result that is only tested and makes it a theorem."},"glyph":"🎲","id":"statistical-bridge","kind":"theorem","name":"From oracle to theorem","needs":["theory-shelf"],"refs":[{"at":"Q-2.6 Can a statistical oracle become theory?","path":"docs/proposals/mathesis-research-programme.adoc"}],"size":"L","status":"open","summary":"S-MN and S-DM (the multinomial logit closed form and the DM contrast limit) are tested only, against MetaManifold-WebUI as oracle. Prove them in Agda, Rocq and Lean for admission (Q-2.6).","track":"science","value":{"maths":2,"publications":2,"science":3}} +{"counsel":{"contrarian":"The ledger already holds every digest; check the option earns its keep.","soundness":"Lineage you can re-check without git archaeology."},"glyph":"🗄️","id":"superseded-manifests-option","kind":"tool","name":"Keep superseded manifests (option)","needs":["receipt-generator"],"refs":[{"issue":"metadatastician/standards#1705"},{"issue":"hyperpolymath/mathesis#122"}],"size":"S","status":"open","summary":"A generator option that keeps the inputs digest, manifest and axioms on superseded receipts (owner ruling 2026-11-24). It landed in standards as #1705, and hyperpolymath/mathesis#122 turns it on; it is done when that pull request merges.","track":"engineering","value":{"ecosystem":1,"engineering":1,"soundness":2}} +{"glyph":"🎤","id":"talk-atlas","kind":"paper","name":"Talk: an atlas of an estate","needs":["publish-atlas"],"owner_value":"high","size":"S","status":"open","summary":"A talk on mapping the mathematics of hundreds of repositories, with every status traced to a receipt.","track":"publications","value":{"ecosystem":1,"publications":2,"teaching":2}} +{"counsel":{"teacher":"Shows why a proof matters to someone who reads spreadsheets, not theorems."},"glyph":"📓","id":"teaching-cohort","kind":"paper","name":"Cohort economics, taught","needs":["app-proofs"],"owner_value":"high","size":"M","status":"open","summary":"A worked tutorial: a small business model where missing data stays missing, with the proofs alongside and synthetic data only.","track":"publications","value":{"economics":1,"publications":2,"teaching":3}} +{"evidence":[{"path":"docs/theory/admissions.jsonl"},{"path":"docs/theory/ledger.jsonl"}],"glyph":"📚","id":"theory-shelf","kind":"data","name":"Theory shelf and ledger","needs":["claims-registry","thy1"],"size":"S","status":"done","summary":"The admission rule for theory no single system owns, with an append-only ledger of every grade and receipt change. One theorem admitted so far.","track":"maths","value":{"maths":2,"soundness":2}} +{"evidence":[{"claim":"hyperpolymath/mathesis#THY-1","min_pwg":"PWG-2ii"}],"glyph":"🧭","id":"thy1","kind":"theorem","name":"THY-1: reachability is monotone","needs":["proof-gate"],"size":"M","status":"done","summary":"In a dependency graph with feature-guarded edges, a node unreachable with every feature requested is unreachable under any request. Proved in Agda, re-proved in Rocq and Lean.","track":"maths","value":{"engineering":2,"maths":2,"publications":2}} +{"counsel":{"cartographer":"The canon order is the owner’s ruling in standards, and resource-algebra E-1 may need re-proving; carry both.","maths":"Two careful readings disagree; that is a sign the two tokens are incomparable, which is outcome C."},"glyph":"⚖️","id":"token-order","kind":"decision","name":"Settle the order of status tokens","needs":["chain-question"],"refs":[{"at":"R-1 The order of the tokens.","path":"docs/proposals/mathesis-research-programme.adoc"},{"at":"[hyperpolymath/resource-algebra#E-1]","path":"docs/atlas/generated/registry.adoc"},{"at":"== 5. Status vocabulary","commit":"745fc744158047a675eeb92464167c9961d66c4b","path":"3-practice/PROOF-POLICY.adoc","repo":"metadatastician/standards"}],"size":"S","status":"open","summary":"Record the order X-PF1 decides, in Mathesis (R-1, provisional) and in the canon. Evidence it must answer: R-1 reads PROOF-POLICY section 5 as open < argued < tested-only, resource-algebra E-1 (PWG-2i) proves open < tested-only < argued, and section 5 itself lists the tokens without stating an order.","track":"maths","value":{"ecosystem":2,"maths":2,"soundness":3}} +{"evidence":[{"path":"docs/ultraplan/tree.jsonl"},{"path":"scripts/ultraplan/ultraplan.mjs"}],"glyph":"🌳","id":"ultraplan","kind":"view","name":"The ultraplan","needs":["atlas-views"],"size":"S","status":"done","summary":"This tech tree: data first, with derived eras, frontier, forks, confluences and advisor picks, and a done that must show evidence.","track":"engineering","value":{"engineering":1,"teaching":1}} +{"glyph":"🔭","id":"value-of-information","kind":"method","name":"Value of information","needs":["liquidity-shelf"],"refs":[{"path":"applied-systems/decision-science/README.adoc"}],"size":"L","status":"open","summary":"Decision science on the shelf: what a missing input is worth to know, computed from the three-valued verdicts. No optimiser (decision-science README).","track":"economics","value":{"economics":3,"maths":2,"science":2}} +{"glyph":"📋","id":"whats-owed","kind":"view","name":"What is owed","needs":["census-workflow","claims-registry"],"refs":[{"at":"WO 5.4 Report what is owed","path":"docs/proposals/mathesis-re-anchoring.adoc"}],"size":"M","status":"open","summary":"A view of the standards requirements master list beside the census and the registry (WO 5.4): what each repository owes, and what it has.","track":"ecosystem","value":{"ecosystem":3,"engineering":1,"soundness":2}} diff --git a/scripts/atlas/census-atlas.mjs b/scripts/atlas/census-atlas.mjs index 469c66a8..b0642e94 100644 --- a/scripts/atlas/census-atlas.mjs +++ b/scripts/atlas/census-atlas.mjs @@ -3,6 +3,7 @@ import {readFile, writeFile, mkdir} from 'node:fs/promises'; import {fileURLToPath} from 'node:url'; import path from 'node:path'; +import {isGitHubRepo} from '../repo/github.mjs'; const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); const censusDir=path.join(root,'docs/atlas/census'); const rowsFile=path.join(censusDir,'rows.jsonl'); @@ -38,7 +39,7 @@ export function validate(rows){ if(!Array.isArray(rows))throw new Error('Census rows must be an array'); const seen=new Set(); for(const r of rows){ - if(typeof r.repo!=='string'||!/^[-\w.]+\/[-\w.]+$/.test(r.repo)||seen.has(r.repo))throw new Error('Invalid or duplicate repo'); + if(!isGitHubRepo(r.repo)||seen.has(r.repo))throw new Error('Invalid or duplicate repo'); if(!validClass.has(r.class))throw new Error('Unknown census class '+r.repo); for(const name of ['own_files','declarations','holes','axioms','fixture_files','unsafe','policy']) if(!Number.isSafeInteger(r[name])||r[name]<0)throw new Error('Invalid census counts '+r.repo+': '+name); diff --git a/scripts/decisions/adr-status.mjs b/scripts/decisions/adr-status.mjs new file mode 100644 index 00000000..77731e89 --- /dev/null +++ b/scripts/decisions/adr-status.mjs @@ -0,0 +1,223 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) +// +// The status of a decision record (ADR), read soundly. +// +// bun scripts/decisions/adr-status.mjs check every ADR's header and Status section agree +// +// An ADR states its status twice (owner ruling 2026-11-25): once as an +// attribute of its document header, `:status: ACCEPTED`, in the words of the +// estate's ADR template (docs/decisions/0001-template.adoc: PROPOSED, +// ACCEPTED, DEPRECATED, SUPERSEDED, and REJECTED from 0000-template.adoc), +// and once in its prose, as the opening word of its Status section. The header +// is what a machine reads; the section is what a person reads; `check` keeps +// the two in step. An ADR counts as ACCEPTED only when both say so. +import path from 'node:path'; +import {repoFiles} from '../repo/files.mjs'; + +export const ROOT = path.resolve(import.meta.dir, '../..'); +export const DECISIONS = 'docs/decisions'; + +// A description-list marker ("::", ":::", "::::" or ";;", then a blank or the +// end) makes Asciidoctor read the line that holds it as a list term, wherever +// in the line it sits. +const LIST_MARKER = /(?::{2,4}|;;)(?:[ \t]|$)/; + +// ── The Status section ─────────────────────────────────────────────────────── +// The word an ADR's Status section opens with, as AsciiDoc reads it, or null. +// It must never name a word where Asciidoctor finds no such section. So it does +// not try to mirror every way Asciidoctor reads a heading: it over-counts, and +// it reads one plain shape only (it fails closed). +// - Every line that could be a heading titled Status counts, inside a block or +// not: "=" or "#" markers and a blank, then a title that holds the letters +// "status" in any case, or a reference that could spell them. An ADR with a +// count other than one is not read. +// - That one line is "==" to "======", one space and "Status"; it is outside any +// delimited block; and it follows a blank line, with nothing above it, across +// blank lines and comments, that attaches it to what came before: a block +// attribute line, a block title, a list continuation or a description-list term. +// - The first line after it, past blank lines and comments, is text that begins +// with a word, after any "*": not indented, and holding no description-list marker. +// - No text line stands over an underline ("-", "=", "~", "^" or "+" repeated) +// of about its length: Asciidoctor reads such a pair as a section title. +// - A preprocessor directive could change which lines count, so an ADR that +// holds one is not read. +// A delimiter is one of these characters four or more times, "--", or a table's "|===". +// It closes on the same line again. +const DELIMITER = /^(?:([/\-.+*=_])\1{3,}|--|[|,:!]={3,})$/; +// A Markdown fence, which Asciidoctor reads too: three backticks open it, with +// any language after them but never a fourth backtick, and only a line of +// exactly three backticks closes it. "````" and "~~~" delimit nothing. +const FENCE = /^```(?!`)/; +const opener = l => { + if (DELIMITER.test(l)) return l; + return FENCE.test(l) ? '```' : null; +}; +const PREPROCESSOR = /^(?:ifdef|ifndef|ifeval|endif|include)::/; +// "//" begins a line comment, but "///" begins text. +const COMMENT = /^\/\/(?!\/)/; +// What each line is: inside a delimited block or one of its delimiters +// ('block'), part of a comment, which AsciiDoc drops ('comment'), or text. +const kindOf = (l, block) => { + if (block) return block.startsWith('//') ? 'comment' : 'block'; + return COMMENT.test(l) ? 'comment' : 'text'; +}; +function lineKinds(lines) { + let open = null; + return lines.map(l => { + const block = open ?? opener(l); + const closes = open !== null && l === open; + open = closes ? null : block; + return kindOf(l, block); + }); +} +// A heading in any form AsciiDoc or Markdown gives one: its markers and a blank, +// then a title that could read "Status". The title is the rest of the line, taken +// whole, so the pattern cannot backtrack and no character of the title escapes it. +const HEADING = /^[=#]+[ \t]/; +const titleMayBeStatus = title => /\{|&#?\w+;/.test(title) || /status/i.test(title.replace(/[^\p{L}]/gu, '')); +const mayBeStatus = l => { + const m = HEADING.exec(l); + return m !== null && titleMayBeStatus(l.slice(m[0].length)); +}; +// Asciidoctor reads a line over an underline within one character of its +// length as a two-line section title; two characters are allowed here. +const UNDERLINE = /^([-=~^+])\1+$/; +const width = s => [...s].length; +const overUnderline = (lines, kinds, i) => kinds[i] === 'text' && lines[i] !== '' && UNDERLINE.test(lines[i + 1] ?? '') + && Math.abs(width(lines[i + 1]) - width(lines[i])) <= 2; +// What, standing above a heading across blank lines and comments, attaches the +// heading to it: a block attribute line, a block title, a list continuation or +// a description-list term. +const ATTACHES = /^(?:\[.*\]|\.[^.\s].*|\+)$|(?::{2,4}|;;)(?:[ \t]|$)/; +function startsSection(lines, kinds, i) { + if (i > 0 && lines[i - 1] !== '') return false; + let j = i - 1; + while (j >= 0 && (lines[j] === '' || kinds[j] === 'comment')) j--; + return j < 0 || !ATTACHES.test(lines[j]); +} +const linesOf = text => text.split('\n').map(l => l.trimEnd()); +// The opening word of the Status section: ASCII letters after any "*", ending +// where no letter, number, combining mark or "_" of any script follows, so +// "Acceptedé" or "Accepted" with a combining accent is not the word "Accepted". +// (\b alone knows only ASCII word characters.) +const OPENING_WORD = /^\**([A-Za-z]+)(?![\p{L}\p{N}\p{M}_])/u; +export function sectionStatus(text) { + const lines = linesOf(text); + if (lines.some(l => PREPROCESSOR.test(l))) return null; + const kinds = lineKinds(lines); + if (lines.some((_, i) => overUnderline(lines, kinds, i))) return null; + const heads = lines.flatMap((l, i) => (mayBeStatus(l) ? [i] : [])); + if (heads.length !== 1) return null; + const [h] = heads; + if (kinds[h] !== 'text' || !/^={2,6} Status$/.test(lines[h]) || !startsSection(lines, kinds, h)) return null; + // The heading is text, so the line after it is text too, unless it opens a + // block, and no delimiter that opens one begins with a letter. + const n = lines.findIndex((l, i) => i > h && l !== '' && kinds[i] !== 'comment'); + const word = n > h && !LIST_MARKER.test(lines[n]) ? OPENING_WORD.exec(lines[n]) : null; + return word ? word[1].toUpperCase() : null; +} + +// ── The header attribute ───────────────────────────────────────────────────── +// The status an ADR's document header states, or null. The header is the title +// line ("= Title"), after any blank lines and line comments, and the lines that +// follow it up to the first blank line. Read strictly, so it never names a +// status Asciidoctor would not set: +// - Each header line after the title is a line comment or an attribute entry, +// and none ends in a continuation ("\" or "+"). An author or revision line, +// or a comment block, could change what the header holds, so it is refused. +// - Exactly one line in the whole file sets or unsets "status", and it is in +// the header. Nothing later can change it: no ":status:", ":status!:" or +// ":!status:", in any letter case (Asciidoctor lowercases an entry's name, +// so ":Status: PROPOSED" sets "status"), and no inline reference that changes an attribute +// ("{set:...}", "{counter:...}" or "{counter2:...}"; a counter turns +// ACCEPTED into ACCEPTEE). Any such reference, to any attribute, leaves the +// header unread. +// - Its value is one of the template's words: PROPOSED, ACCEPTED, DEPRECATED, +// SUPERSEDED (optionally "by NNNN") or REJECTED, written exactly so. +const ENTRY = /^:!?[\w-]+!?:(?: |$)/; +// An inline reference that changes an attribute where it stands. +const MUTATES = /\{(?:set|counter2?):/i; +const STATUS_ENTRY = /^:!?status!?:/i; +const STATUS_VALUE = /^:status: (PROPOSED|ACCEPTED|DEPRECATED|SUPERSEDED(?: by \d{4})?|REJECTED)$/; +function headerRange(lines) { + let t = 0; + while (t < lines.length && (lines[t] === '' || COMMENT.test(lines[t]))) t++; + if (!/^= \S/.test(lines[t] ?? '')) return null; + let end = t + 1; + while (end < lines.length && lines[end] !== '') end++; + const body = lines.slice(t + 1, end); + const plain = body.every(l => (COMMENT.test(l) || ENTRY.test(l)) && !/[\\+]$/.test(l)); + return plain ? [t, end] : null; +} +export function headerStatus(text) { + const lines = linesOf(text); + if (lines.some(l => PREPROCESSOR.test(l) || MUTATES.test(l))) return null; + const range = headerRange(lines); + if (range === null) return null; + const entries = lines.flatMap((l, i) => (STATUS_ENTRY.test(l) ? [i] : [])); + if (entries.length !== 1 || entries[0] <= range[0] || entries[0] >= range[1]) return null; + const m = STATUS_VALUE.exec(lines[entries[0]]); + return m ? m[1] : null; +} + +// ── Both, in step ──────────────────────────────────────────────────────────── +// The header's status, the section's opening word, and whether they agree (the +// section names the header's first word: "SUPERSEDED by 0007" agrees with a +// section opening "Superseded"). +export function adrStatus(text) { + const header = headerStatus(text), section = sectionStatus(text); + return {header, section, inStep: header !== null && header.split(' ')[0] === section}; +} +// Whether a record states no status at all, as far as can be shown: no line could +// set "status" (an entry in any letter case, a {set:...} or {counter:...} that +// names it, or a preprocessor directive that could bring either in), and no line +// could be a heading titled Status, in either form: "== Status", or "Status" over +// an underline. A record the readers refuse is not one of +// these: its status is there but cannot be read soundly, and that fails the check. +// ({set:Status:X} sets "status"; a counter on another attribute does not.) +const SETS_STATUS = /\{(?:set|counter2?):status(?=[:!}])/i; +export function statesNoStatus(text) { + const lines = linesOf(text); + const kinds = lineKinds(lines); + const underlined = i => overUnderline(lines, kinds, i) && titleMayBeStatus(lines[i]); + return !lines.some((l, i) => STATUS_ENTRY.test(l) || SETS_STATUS.test(l) || PREPROCESSOR.test(l) || mayBeStatus(l) || underlined(i)); +} +export const adrAccepted = text => { + const s = adrStatus(text); + return s.inStep && s.header === 'ACCEPTED'; +}; + +// ── The check ──────────────────────────────────────────────────────────────── +// Every decision record, NNNN-title.adoc with the boilerplate NNNN-template.adoc +// set aside, states its status in both places and they agree; or it states none +// at all (a status the owner has yet to set), which is reported, not refused. A +// record whose status the readers refuse to read is refused: it is not unset. +// The records are the files git tracks in docs/decisions, read at their own path +// (scripts/repo/files.mjs): a directory or a record that is a link leads out of +// the repository, so it is refused, and never read. +export function checkDecisions(root = ROOT) { + const files = repoFiles(root); + if (!files.isDir(DECISIONS)) return [{file: DECISIONS, problem: 'is not a directory in the repository that holds a file git tracks'}]; + const records = files.under(DECISIONS).map(p => p.slice(DECISIONS.length + 1)) + .filter(f => /^\d{4}-[^/]+\.adoc$/.test(f) && !/^\d{4}-template\.adoc$/.test(f)); + return records.map(f => { + const p = `${DECISIONS}/${f}`; + if (!files.isFile(p)) return {file: f, problem: 'is not a file that git tracks in the repository, at its own path'}; + const text = files.read(p); + const s = adrStatus(text); + if (s.inStep) return {file: f, status: s.header}; + if (statesNoStatus(text)) return {file: f, status: null}; + if (s.header === null && s.section === null) return {file: f, problem: 'it states a status that cannot be read soundly (see docs/decisions/README.adoc)'}; + return {file: f, problem: `its header says ${s.header ?? 'nothing readable'} but its Status section says ${s.section ?? 'nothing readable'}`}; + }); +} + +if (import.meta.main) { + if (process.argv[2] !== 'check') { console.error('usage: adr-status.mjs check'); process.exit(2); } + const results = checkDecisions(); + for (const r of results) console.log(`${r.problem ? 'FAIL' : 'ok '} ${r.file}: ${r.problem ?? r.status ?? 'no status stated (the owner sets it)'}`); + const failed = results.filter(r => r.problem); + if (failed.length) { console.error(`adr-status: FAIL: ${failed.length} decision record(s) out of step`); process.exit(1); } + console.log(`PASS: ${results.length} decision records; each states its status in step, or states none`); +} diff --git a/scripts/registry/claims-registry.mjs b/scripts/registry/claims-registry.mjs index 24ae0af3..1347a13c 100644 --- a/scripts/registry/claims-registry.mjs +++ b/scripts/registry/claims-registry.mjs @@ -30,6 +30,7 @@ import {createHash} from 'node:crypto'; import {fileURLToPath, pathToFileURL} from 'node:url'; import path from 'node:path'; import {readJsonl} from '../atlas/census-atlas.mjs'; +import {GITHUB_REPO} from '../repo/github.mjs'; import {validateBridges, renderBridges} from './bridges.mjs'; import {validateAdmissions, renderTheoryIndex, HOME} from './theory.mjs'; import {validateLedger, snapshot, pending, checkAppendOnly, jcs} from './theory-ledger.mjs'; @@ -94,6 +95,23 @@ export const CHECKER = { // ── Validation of the registry rows ────────────────────────────────────────── +// A claim id is OWNER/REPO#CLAIM. The claim uses the characters of a repository +// name, so every id survives the registry view, where it is a link's text inside +// a table row: "]", "|", "#" and white space cannot occur in it. The registry's +// rows obey this rule, and readers that cite a claim (the ultraplan) use it too. +// A claim's repository is named by GitHub's own rule (scripts/repo/github.mjs). +export const CLAIM_REPO = GITHUB_REPO; +export const CLAIM_NAME = /^[-\w.]+$/; +// A status document is named by a relative path in its repository. The view puts +// it in a link's target, so it uses the same characters, with "/" between its +// parts, and no part is "." or "..": "[", "]", "|", "#" and white space cannot occur. +export const isDocPath = p => p.split('/').every(s => CLAIM_NAME.test(s) && s !== '.' && s !== '..'); +export function isClaimId(id) { + if (typeof id !== 'string') return false; + const i = id.indexOf('#'); + return i > 0 && CLAIM_REPO.test(id.slice(0, i)) && CLAIM_NAME.test(id.slice(i + 1)); +} + // Throw unless every row is well formed and its repository is public in the // census inventory (the registry never names a private repository). export function validate(rows, inventory) { @@ -104,14 +122,14 @@ export function validate(rows, inventory) { const where = r && r.id ? r.id : JSON.stringify(r); if (r === null || typeof r !== 'object' || Array.isArray(r)) throw new Error(`A claim record is an object: ${where}`); closed(r, FIELDS, 'Unknown field (a record holds no grade, token, leg or flag):', where); - if (typeof r.repo !== 'string' || !/^[-\w.]+\/[-\w.]+$/.test(r.repo)) throw new Error(`Invalid repo: ${where}`); - if (typeof r.claim !== 'string' || r.claim === '') throw new Error(`Missing claim id: ${where}`); + if (typeof r.repo !== 'string' || !CLAIM_REPO.test(r.repo)) throw new Error(`Invalid repo: ${where}`); + if (typeof r.claim !== 'string' || !CLAIM_NAME.test(r.claim)) throw new Error(`Missing or invalid claim id (letters, digits, "-", "_" and "." only): ${where}`); if (r.id !== `${r.repo}#${r.claim}`) throw new Error(`id must be repo#claim: ${where}`); if (seen.has(r.id)) throw new Error(`Duplicate id: ${r.id}`); seen.add(r.id); if (!KINDS.has(r.kind)) throw new Error(`Unknown kind ${r.kind}: ${r.id}`); if (typeof r.statement !== 'string' || r.statement.length < 10) throw new Error(`Missing statement: ${r.id}`); - if (typeof r.status_doc !== 'string' || r.status_doc === '') throw new Error(`Missing status_doc: ${r.id}`); + if (typeof r.status_doc !== 'string' || !isDocPath(r.status_doc)) throw new Error(`Missing or invalid status_doc (a relative path of letters, digits, "-", "_", "." and "/"): ${r.id}`); if (typeof r.source_commit !== 'string' || !/^[0-9a-f]{40}$/.test(r.source_commit)) throw new Error(`source_commit must be 40 lowercase hex: ${r.id}`); if (r.kind === 'theorem') { if (!r.agda || typeof r.agda.module !== 'string' || !Array.isArray(r.agda.names) || r.agda.names.length === 0) diff --git a/scripts/registry/engineering-receipt.mjs b/scripts/registry/engineering-receipt.mjs index 546c91bf..7f80da0c 100644 --- a/scripts/registry/engineering-receipt.mjs +++ b/scripts/registry/engineering-receipt.mjs @@ -4,6 +4,7 @@ // validates their identity, declared source binding and retained evidence, not // the truth of an execution log or compiler correctness. See ADR 0006. import {jcs} from './theory-ledger.mjs'; +import {isGitHubRepo} from '../repo/github.mjs'; const need = (ok, message) => { if (!ok) throw new Error(`engineering receipt: ${message}`); }; const object = (v, fields) => { @@ -38,7 +39,7 @@ export function parseEngineeringReceipt(text) { need(r.profile === 'engineering-receipt' && r.schema_version === '1.0.0', 'unsupported profile/version'); need(r.kind === 'demonstration', 'engineering evidence is only a demonstration'); for (const k of ['repository', 'source_commit', 'claim', 'statement', 'status_doc']) string(r[k]); - need(/^[-\w.]+\/[-\w.]+$/.test(r.repository), 'invalid repository'); + need(isGitHubRepo(r.repository), 'invalid repository'); need(/^[a-f0-9]{40}$/.test(r.source_commit) && !/^0+$/.test(r.source_commit), 'invalid implementation source commit'); file(r.source_inputs); file(r.evidence_manifest); diff --git a/scripts/repo/files.mjs b/scripts/repo/files.mjs new file mode 100644 index 00000000..c63edeae --- /dev/null +++ b/scripts/repo/files.mjs @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) +// +// The files of the repository, as the generators may read them. +// +// A generator that checks evidence, or copies a file into the site, reads only +// what a reviewer can read in the commit: a file that git tracks, at its own +// path. So a path counts only when +// - git tracks it (it is in the index): nothing untracked, nothing in .git; +// - no part of it is a link: the file system holds, at that very path, what +// the path names, so nothing is read from outside the repository; +// - it is a regular file, or, where a directory may be named, a directory that +// holds a tracked file. +// The answer is the same in a clone and in a linked worktree, where .git is a file. +// +// The generated views are the one exception: a generator writes them before git +// tracks them, so `local` reads and checks a path with the same link rule but +// without asking git. +import {readFileSync, realpathSync, statSync, lstatSync, accessSync, constants} from 'node:fs'; +import {spawnSync} from 'node:child_process'; +import path from 'node:path'; + +// Find a program in the absolute directories of PATH, and run it by that absolute +// path, so no relative PATH entry (such as ".") can pick the program. As a shell +// does, it passes over anything there by that name that is not a regular file +// it may run (a directory, a plain file without the execute bit). +const runnable = f => { + try { + accessSync(f, constants.X_OK); + return statSync(f).isFile(); + } catch { return false; } +}; +export function findProgram(name, env = process.env) { + for (const d of (env.PATH || '').split(path.delimiter)) { + if (path.isAbsolute(d) && runnable(path.join(d, name))) return path.join(d, name); + } + throw new Error(`${name} not found in an absolute directory of PATH`); +} + +// The paths git tracks in the checkout at `base`, which must be the top of its +// work tree, relative to it. Only git's closing newline is cut from the path it +// prints: a directory name may itself end in white space. +function trackedPaths(base) { + const git = args => spawnSync(findProgram('git'), ['-C', base, ...args], {encoding: 'utf8', maxBuffer: 1 << 28}); + const top = git(['rev-parse', '--show-toplevel']); + if (top.error || top.status !== 0 || realpathSync(top.stdout.replace(/\n$/, '')) !== base) { + throw new Error(`${base} is not the top of a git checkout; the files read here are the files git tracks`); + } + const ls = git(['ls-files', '-z', '--full-name']); + if (ls.error || ls.status !== 0) throw new Error(`git ls-files failed in ${base}`); + return new Set(ls.stdout.split('\0').filter(Boolean)); +} + +// Repository text is UTF-8, decoded strictly: a malformed byte is an error, never +// a silent U+FFFD, so what a generator reads is exactly what is committed. A byte +// order mark is kept as a character, so a check sees it. +const UTF8 = new TextDecoder('utf-8', {fatal: true, ignoreBOM: true}); +const decode = (buf, p) => { + try { return UTF8.decode(buf); } catch { throw new Error(`${p} is not valid UTF-8`); } +}; + +export function repoFiles(root) { + const base = realpathSync(root); + // git is asked once, when a check first needs the answer. + let tracked = null; + const trackedSet = () => { + if (tracked === null) tracked = trackedPaths(base); + return tracked; + }; + const isTracked = p => trackedSet().has(p); + const holdsTracked = p => [...trackedSet()].some(t => t.startsWith(`${p}/`)); + // The full path of p when p is a relative path to something inside the + // checkout, below its top: "", ".", "..", an absolute path, or a path that + // climbs out is null. + const within = p => { + if (typeof p !== 'string' || p === '' || path.isAbsolute(p)) return null; + const full = path.join(base, p); + const rel = path.relative(base, full); + return rel !== '' && rel !== '..' && !rel.startsWith(`..${path.sep}`) ? full : null; + }; + // What stands at the path itself, inside the checkout, when no part of it is a + // link; else null. + const at = p => { + const full = within(p); + if (full === null) return null; + try { return realpathSync(full) === full ? statSync(full) : null; } catch { return null; } + }; + const isFile = p => isTracked(p) && at(p)?.isFile() === true; + const isDir = p => at(p)?.isDirectory() === true && holdsTracked(p); + const bytes = p => { + if (!isFile(p)) throw new Error(`${p} is not a file that git tracks in the repository`); + return readFileSync(path.join(base, p)); + }; + const localFile = p => at(p)?.isFile() === true; + return { + root: base, + isFile, + isDir, + // A file or a directory: a ref may name either. + exists: p => isFile(p) || isDir(p), + bytes, + read: p => decode(bytes(p), p), + // The tracked paths under a directory, in the order git lists them (sorted). + under: dir => [...trackedSet()].filter(t => t.startsWith(`${dir}/`)), + local: { + isFile: localFile, + isDir: p => at(p)?.isDirectory() === true, + // Nothing at all stands at the path, not even a link that leads nowhere. A + // path outside the checkout is never absent: nothing may be made there. + isAbsent: p => { + const full = within(p); + if (full === null) return false; + try { lstatSync(full); return false; } catch { return true; } + }, + read: p => { + if (!localFile(p)) throw new Error(`${p} is not a plain file inside the repository`); + return decode(readFileSync(path.join(base, p)), p); + }, + }, + }; +} diff --git a/scripts/repo/github.mjs b/scripts/repo/github.mjs new file mode 100644 index 00000000..f731636b --- /dev/null +++ b/scripts/repo/github.mjs @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) +// +// A GitHub repository named OWNER/REPO, by GitHub's own naming rules. +// +// Every generator that writes a github.com link from a repository name, or +// clones one, checks the name here first. A looser rule let "../.." through, +// and a link such as https://github.com/../../blob/c/x resolves, in a browser, +// to a page of some other repository. +// - OWNER, a user or organisation login: 1 to 39 letters, digits and single +// hyphens, with no hyphen at either end and never two in a row. +// - REPO: letters, digits, ".", "-" and "_", 1 to 100, and not dots alone: +// GitHub has no repository named "." or "..". +export const GITHUB_REPO = /^(?=[A-Za-z0-9-]{1,39}\/)[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*\/(?!\.+$)[A-Za-z0-9._-]{1,100}$/; +export const isGitHubRepo = s => typeof s === 'string' && GITHUB_REPO.test(s); diff --git a/scripts/site/site.mjs b/scripts/site/site.mjs index da4bc81c..f5941037 100644 --- a/scripts/site/site.mjs +++ b/scripts/site/site.mjs @@ -8,15 +8,22 @@ // // It writes one generated front page, then renders that page and each view // with Asciidoctor into OUT, at the same paths as the views. It fails closed: -// - Asciidoctor runs with --failure-level=WARN, so any warning fails. +// - Asciidoctor runs with --failure-level=WARN, so any warning fails, and +// in secure mode, so it reads no file but the page it renders. // - A view header that no longer names its source fails the build. // - A relative link to a file that is neither in the site nor in the // repository fails. A relative link to a repository file that is not in // the site becomes an absolute GitHub link at `main`. -import {readFileSync, writeFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, statSync} from 'node:fs'; +// - It writes only into a fresh output directory: OUT is absent, or empty. +// - It reads from the repository only files that git tracks, at their own +// path (scripts/repo/files.mjs): each view, the front page's sources and +// each asset it copies. A view or an asset that is a link, or untracked, +// fails the build, so nothing from outside the repository enters the site. +import {readFileSync, writeFileSync, mkdirSync, mkdtempSync, readdirSync, statSync, lstatSync} from 'node:fs'; import {spawnSync} from 'node:child_process'; import {tmpdir} from 'node:os'; import path from 'node:path'; +import {repoFiles, findProgram} from '../repo/files.mjs'; export const GITHUB = 'https://github.com/hyperpolymath/mathesis'; @@ -37,6 +44,9 @@ export const VIEWS = [ how: 'Built by `scripts/registry/claims-registry.mjs` from `docs/theory/admissions.jsonl`, the claims and the receipt they pin.'}, {file: 'applied-systems/finance/cohort-economics/generated/examples.adoc', needs: 'scripts/applied/cohort.mjs', how: 'Built by `scripts/applied/cohort.mjs` from the files in `applied-systems/finance/cohort-economics/examples/`.'}, + {file: 'docs/ultraplan/generated/ultraplan.adoc', needs: 'scripts/ultraplan/ultraplan.mjs', + how: 'Built by `scripts/ultraplan/ultraplan.mjs` from `docs/ultraplan/tree.jsonl`, its advisors and its return tickets. Eras, frontier and picks are derived.', + assets: ['docs/ultraplan/generated/tree.svg']}, ]; export const htmlPath = adoc => adoc.replace(/\.adoc$/, '.html'); @@ -122,38 +132,59 @@ const walk = (root, dir = '') => readdirSync(path.join(root, dir)).flatMap(n => // run it by its absolute path, so no relative PATH entry can pick the program. export function findAsciidoctor(env = process.env) { if (env.ASCIIDOCTOR) return env.ASCIIDOCTOR; - for (const d of (env.PATH || '').split(path.delimiter)) { - if (path.isAbsolute(d) && existsSync(path.join(d, 'asciidoctor'))) return path.join(d, 'asciidoctor'); - } - throw new Error('asciidoctor not found in an absolute directory of PATH (set ASCIIDOCTOR to its path)'); + try { return findProgram('asciidoctor', env); } catch (e) { throw new Error(`${e.message} (set ASCIIDOCTOR to its path)`); } } +// Asciidoctor runs in secure mode, so it reads no file but the page it renders: +// an include:: in a view becomes a link to its target (which the link check then +// fails), never the target's text, wherever the target is. Safe mode would read it, +// and with the base directory at "/" its jail is the whole file system. linkcss! +// keeps the stylesheet embedded, as it was in safe mode; it is part of Asciidoctor, +// not a file of the repository. function asciidoctor(args) { - const r = spawnSync(findAsciidoctor(), ['-S', 'safe', '-B', '/', '--failure-level=WARN', '-a', 'nofooter', '-a', 'webfonts!', ...args], {encoding: 'utf8'}); + const r = spawnSync(findAsciidoctor(), ['-S', 'secure', '-a', 'linkcss!', '-B', '/', '--failure-level=WARN', '-a', 'nofooter', '-a', 'webfonts!', ...args], {encoding: 'utf8'}); if (r.error) throw new Error(`asciidoctor not runnable: ${r.error.message}`); process.stderr.write(r.stderr || ''); if (r.status !== 0) throw new Error(`asciidoctor failed (status ${r.status})`); } +// The site is built into a fresh tree: OUT is absent, or an empty directory that +// is not itself a link. A stale or planted tree could hold a link where the build +// writes, and the build (or Asciidoctor) would write through it, out of OUT. +function freshOut(out) { + let st = null; + try { st = lstatSync(out); } catch { return; } + if (!st.isDirectory() || readdirSync(out).length) throw new Error(`${out} is not a fresh output directory: give a path that does not exist, or an empty directory`); +} export function build(root, out) { - const read = f => readFileSync(path.join(root, f), 'utf8'); + freshOut(out); + const files = repoFiles(root); + const unread = [...VIEWS.map(v => v.file), ...VIEWS.flatMap(v => v.assets ?? [])].filter(f => !files.isFile(f)); + if (unread.length) throw new Error(unread.map(f => `${f} is not a file that git tracks in the repository`).join('\n')); + const read = files.read; mkdirSync(out, {recursive: true}); const stage = mkdtempSync(path.join(tmpdir(), 'mathesis-site-')); writeFileSync(path.join(stage, 'index.adoc'), frontPage(read)); asciidoctor(['-D', out, path.join(stage, 'index.adoc')]); asciidoctor(['-R', root, '-D', out, ...VIEWS.map(v => path.join(root, v.file))]); + // A view's assets (its pictures) are copied to the same path in the site, so + // a relative image stays relative there and is checked like any link. + for (const a of VIEWS.flatMap(v => v.assets ?? [])) { + mkdirSync(path.dirname(path.join(out, a)), {recursive: true}); + writeFileSync(path.join(out, a), files.bytes(a)); + } const pages = walk(out).filter(f => f.endsWith('.html')); - const files = new Set(walk(out)); + const built = new Set(walk(out)); const ids = new Map(); const idsOf = p => ids.get(p) ?? ids.set(p, new Set([...readFileSync(path.join(out, p), 'utf8').matchAll(/\bid="([^"]+)"/g)].map(m => m[1]))).get(p); const errors = []; for (const p of pages) { - const r = checkLinks(p, readFileSync(path.join(out, p), 'utf8'), x => files.has(x), x => existsSync(path.join(root, x)), idsOf); + const r = checkLinks(p, readFileSync(path.join(out, p), 'utf8'), x => built.has(x), x => files.exists(x.replace(/\/$/, '')), idsOf); writeFileSync(path.join(out, p), r.html); errors.push(...r.errors); } - for (const v of VIEWS) if (!files.has(htmlPath(v.file))) errors.push(`missing page ${htmlPath(v.file)}`); + for (const v of VIEWS) if (!built.has(htmlPath(v.file))) errors.push(`missing page ${htmlPath(v.file)}`); if (errors.length) throw new Error(errors.join('\n')); return pages; } diff --git a/scripts/ultraplan/ultraplan.mjs b/scripts/ultraplan/ultraplan.mjs new file mode 100644 index 00000000..6d685877 --- /dev/null +++ b/scripts/ultraplan/ultraplan.mjs @@ -0,0 +1,931 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) +// +// The ultraplan of Mathesis: a tech tree whose source of truth is data. +// +// bun scripts/ultraplan/ultraplan.mjs build write the generated views +// bun scripts/ultraplan/ultraplan.mjs check refuse stale views or bad data +// +// Sources (I-JSON, one JCS record a line): +// docs/ultraplan/advisors.jsonl the council: who reads the tree, and how +// docs/ultraplan/tree.jsonl the nodes; `needs` are the edges +// docs/ultraplan/expeditions.jsonl return tickets: off-tree trips, each one +// grafted onto the tree or archived +// Views: +// docs/ultraplan/generated/ultraplan.adoc +// docs/ultraplan/generated/tree.svg +// +// What is typed and what is derived. A node's era, what it enables, the +// frontier (what can be started now), the forks and confluences and each +// advisor's pick are derived from the data and never typed. A node's status +// is typed, but `done` must carry evidence that this script checks against the +// repository: a file that exists, a claim whose grade the registry view +// derives, or an ADR whose status is Accepted. A done node's needs must be +// done too, and no more than ACTIVE_LIMIT nodes may be active at once. The +// value marks are judgements, and the view says so. +// +// The "me" advisor is private (owner ruling 2026-11-24): its notes are kept +// outside this public repository, and a node carries at most the neutral tag +// `owner_value: "high"`. Counsel under the key `me` is refused. +import {writeFileSync, mkdirSync} from 'node:fs'; +import path from 'node:path'; +import {parseJsonl} from '../atlas/census-atlas.mjs'; +import {jcs} from '../registry/theory-ledger.mjs'; +import {isClaimId, isDocPath} from '../registry/claims-registry.mjs'; +import {adrStatus} from '../decisions/adr-status.mjs'; +import {repoFiles} from '../repo/files.mjs'; +import {isGitHubRepo} from '../repo/github.mjs'; + +export const ROOT = path.resolve(import.meta.dir, '../..'); +export const DIR = 'docs/ultraplan'; +export const VIEW = `${DIR}/generated/ultraplan.adoc`; +export const SVG = `${DIR}/generated/tree.svg`; + +export const TRACKS = ['maths', 'engineering', 'science', 'economics', 'publications', 'ecosystem']; +export const STATUSES = ['done', 'active', 'open', 'blocked', 'dropped']; +export const SIZES = {S: 1, M: 2, L: 4, XL: 8}; +export const VALUE_KEYS = ['maths', 'engineering', 'science', 'economics', 'publications', 'teaching', 'soundness', 'ecosystem']; +export const KINDS = ['theorem', 'tool', 'data', 'view', 'paper', 'decision', 'infrastructure', 'method']; +export const ACTIVE_LIMIT = 3; +export const SPECIAL_ADVISORS = ['contrarian', 'me']; +export const PWG_ORDER = ['ungraded', 'PWG-3', 'PWG-2i', 'PWG-2ii', 'PWG-1']; + +// The eras of the tree, by depth (the longest chain of needs below a node). +export const ERAS = [ + ['🪨', 'Tally sticks'], ['🧮', 'Abacus'], ['📐', 'Euclid'], ['🌌', 'Kepler'], + ['♾️', 'Cantor'], ['🧩', 'Gödel'], ['🌀', 'Grothendieck'], ['🚀', 'Frontier beyond'], +]; +export const era = d => d < ERAS.length ? ERAS[d] : ['🚀', `Frontier beyond +${d - ERAS.length + 1}`]; + +export const STATUS_GLYPH = {done: '✅', active: '🔨', open: '🌱', blocked: '⛔', dropped: '🍂'}; +export const TRACK_GLYPH = {maths: '∑', engineering: '⚙', science: '🔬', economics: '🪙', publications: '📜', ecosystem: '🗺'}; +export const TRACK_FILL = { + maths: '#fff1b8', engineering: '#d6e8ff', science: '#d9f7df', + economics: '#ffe0d6', publications: '#eee0ff', ecosystem: '#ffe9c7', +}; + +// A lowercase slug that begins with a letter: a node's id is also its AsciiDoc +// anchor, and an anchor cannot begin with a digit. +const SLUG = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/; +// A size is one of the four own keys of SIZES, never an inherited name such as "toString". +const isSize = s => typeof s === 'string' && Object.hasOwn(SIZES, s); +// A YYYY-MM-DD that names a real day (no 2026-02-30). +export const isDate = s => { + if (typeof s !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(s)) return false; + const d = new Date(`${s}T00:00:00Z`); + return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === s; +}; +const isStr = (v, max = 400) => typeof v === 'string' && v.length > 0 && v.length <= max && v === v.trim() && !/[\u0000-\u001f]/.test(v); + +// ── Reading ────────────────────────────────────────────────────────────────── +// Each source line must already be its own JCS form, so the data has one +// spelling and a diff shows only real change. +// I-JSON (RFC 7493 §2.1) refuses a string or a member name that holds a lone +// surrogate or a Unicode noncharacter (U+FDD0 to U+FDEF, and the last two code +// points of every plane). JSON.parse accepts both and JSON.stringify writes them +// back unchanged, so they are refused here, as the I-JSON gate refuses them. +const isNonchar = cp => (cp >= 0xFDD0 && cp <= 0xFDEF) || (cp & 0xFFFE) === 0xFFFE; +const isIJsonString = s => s.isWellFormed() && ![...s].some(c => isNonchar(c.codePointAt(0))); +export function wellFormed(v) { + if (typeof v === 'string') return isIJsonString(v); + if (Array.isArray(v)) return v.every(wellFormed); + if (v !== null && typeof v === 'object') return Object.entries(v).every(([k, x]) => isIJsonString(k) && wellFormed(x)); + return true; +} + +// Each text in the plan is one line of plain text, and the page shows it exactly +// as written. So no string in a record, its keys included, holds any of these. +// This is the plan's own rule, stricter than I-JSON. +// - A control character: a line break among them would let a text start a line +// of the page, where AsciiDoc reads block syntax. +// - A line or paragraph separator (U+2028, U+2029): a browser breaks the line there. +// - A bidirectional formatting control (U+061C, U+200E, U+200F, U+202A to U+202E, +// U+2066 to U+2069): it reorders what is shown, so text could look other than +// it is. +// - A run of two or more spaces, or a space at the start or end: HTML shows a run +// of spaces as one, and drops a space at the edge of a cell. +const TEXT_FAULTS = [ + [/[\u0000-\u001f\u007f-\u009f]/, 'a control character'], + [/[\u2028\u2029]/, 'a line or paragraph separator (U+2028 or U+2029)'], + // A bidirectional control reorders the text around it as it is shown. + [/[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/, 'a bidirectional formatting control'], + [/ {2}/, 'a run of spaces'], + [/^ | $/, 'a space at the start or end of a text'], +]; +// The values a record holds directly: a list's items, or an object's keys and values. +const partsOf = v => { + if (Array.isArray(v)) return v; + return v !== null && typeof v === 'object' ? Object.entries(v).flat() : []; +}; +// The first fault of any string in a record, or null. +function textFault(v) { + if (typeof v === 'string') return TEXT_FAULTS.find(([re]) => re.test(v))?.[1] ?? null; + for (const x of partsOf(v)) { + const fault = textFault(x); + if (fault) return fault; + } + return null; +} + +export function readSource(text, name) { + const rows = parseJsonl(text, name); + const lines = text === '' ? [] : text.slice(0, -1).split('\n'); + rows.forEach((r, i) => { + if (!wellFormed(r)) throw new Error(`${name}: line ${i + 1} holds a lone surrogate or a Unicode noncharacter, which I-JSON refuses`); + const fault = textFault(r); + if (fault) throw new Error(`${name}: line ${i + 1} holds ${fault}; each text in the plan is one line of plain text, shown as written`); + if (jcs(r) !== lines[i]) throw new Error(`${name}: line ${i + 1} is not in JCS form (RFC 8785); run: sed -n ${i + 1}p ${name} | bun scripts/ijson-jcs-cli.js canon`); + }); + return rows; +} + +// ── Rules ──────────────────────────────────────────────────────────────────── +// The checks are data. A rule is [holds, message]: holds(record, env) is true +// when the record keeps the rule, and the message says what it must be. +const list = v => (Array.isArray(v) ? v : []); +// Byte order, the same in every locale, so the views are deterministic. +const cmp = (a, b) => (a < b ? -1 : Number(a > b)); +const oneOf = (name, allowed) => `${name} must be one of ${allowed.join(', ')}`; + +function closed(obj, allowed, where) { + if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) throw new Error(`${where}: must be an object`); + for (const k of Object.keys(obj)) if (!allowed.includes(k)) throw new Error(`${where}: unknown field "${k}"`); +} +// Whether a record is an object with only the allowed fields; a failure is recorded. +function isClosed(obj, allowed, where, fail) { + try { closed(obj, allowed, where); return true; } catch (e) { fail(e.message); return false; } +} +function applyRules(rules, rec, env, where, fail) { + for (const [holds, message] of rules) if (!holds(rec, env)) fail(`${where}: ${message}`); +} + +// ── Evidence ───────────────────────────────────────────────────────────────── +// The grade the registry view derives for a claim id, or null when the view +// does not list it. The view is generated and checked by registry-check. +// A registry row opens with its claim cell (a link whose label is the claim id), +// then its kind and its grade. Only the claim cell names the row's claim: an id +// mentioned in another row's statement is not that claim's row. The link runs +// to the first "[", so the pattern matches in linear time. +const ROW = /^\|https:\/\/[^\s[]*\[([^\]]+)\][^|]* \|(?:theorem|demonstration|assumption) \|`(PWG-1|PWG-2ii|PWG-2i|PWG-3|ungraded)` \|/; +export function registryGrade(registryText, id) { + for (const line of registryText.split('\n')) { + const m = ROW.exec(line); + if (m && m[1] === id) return m[2]; + } + return null; +} + +// A path in this repository, by the registry's own rule: letters, digits, "-", "_" +// and "." in each part, "/" between parts, and no part "." or "..". Nothing in it +// can end a code span on the page, and it cannot climb out of the repository. +const isRepoPath = p => isStr(p, 300) && isDocPath(p); + +// One check for each kind of evidence; each returns an error or null. +const EVIDENCE = { + path(ev, ctx) { + const p = ev.path; + if (!isRepoPath(p)) return `evidence path ${JSON.stringify(p)} is not a repository path`; + return ctx.isFile(p) ? null : `evidence path ${p} is not a file that git tracks in the repository`; + }, + claim(ev, ctx) { + // The registry's own rule, so any claim it can list can be cited here. + if (!isStr(ev.claim) || !isClaimId(ev.claim)) return `evidence claim ${JSON.stringify(ev.claim)} is not OWNER/REPO#ID`; + const min = ev.min_pwg ?? 'PWG-3'; + if (!PWG_ORDER.includes(min) || min === 'ungraded') return `evidence min_pwg ${JSON.stringify(min)} is not a grade`; + const got = registryGrade(ctx.registry, ev.claim); + if (got === null) return `the registry view does not list ${ev.claim}`; + return PWG_ORDER.indexOf(got) >= PWG_ORDER.indexOf(min) ? null : `${ev.claim} derives ${got}, below ${min}`; + }, + adr(ev, ctx) { + if (!isStr(ev.adr) || !/^\d{4}$/.test(ev.adr)) return `evidence adr ${JSON.stringify(ev.adr)} is not a four-digit ADR number`; + const files = ctx.adrFiles(ev.adr); + if (!files.length) return `no ADR ${ev.adr} in docs/decisions`; + if (files.length > 1) return `ADR ${ev.adr} is ambiguous: ${files.join(', ')} share the number`; + const [file] = files; + if (!ctx.isFile(file)) return `ADR ${ev.adr} (${file}) is not a file that git tracks in the repository`; + // Its header states the status and its Status section agrees (owner ruling 2026-11-25). + const st = adrStatus(ctx.read(file)); + if (st.header === null) return `ADR ${ev.adr} states no readable status in its header (:status: ACCEPTED, as the ADR template has it)`; + if (!st.inStep) return `ADR ${ev.adr}'s header says ${st.header} but its Status section says ${st.section ?? 'nothing readable'}`; + return st.header === 'ACCEPTED' ? null : `ADR ${ev.adr} is ${st.header}, not ACCEPTED`; + }, +}; + +// Check one evidence item against the repository; return an error or null. +export function checkEvidence(ev, ctx) { + closed(ev, ['path', 'claim', 'min_pwg', 'adr'], 'evidence'); + const kinds = Object.keys(EVIDENCE).filter(k => k in ev); + if (kinds.length !== 1) return 'an evidence item names exactly one of path, claim or adr'; + if (ev.min_pwg !== undefined && ev.claim === undefined) return 'min_pwg belongs to claim evidence only'; + return EVIDENCE[kinds[0]](ev, ctx); +} +const evidenceError = (ev, ctx) => { try { return checkEvidence(ev, ctx); } catch (e) { return e.message; } }; + +// ── References ─────────────────────────────────────────────────────────────── +// A ref points at one place, and no ref types a line number, which goes stale +// with the next edit. A ref into this repository is checked: its path exists, +// and its quote ("at") occurs in the file exactly once, so a ref whose passage +// was reworded, moved away or repeated is refused, never left pointing nowhere. +// A ref into another repository names a full commit, so its content cannot +// drift; it is not checked here. An issue ref names a GitHub issue or pull request. +const REF_FIELDS = ['path', 'at', 'repo', 'commit', 'issue']; +// A quote is plain text like any other, escaped on the page, so any one line of +// up to 160 characters can be quoted. +const isQuote = s => isStr(s, 160); +// How often s occurs in text, overlaps counted: "aaaa" occurs twice in "aaaaa". +const occurrences = (text, s) => { + let k = 0; + for (let i = text.indexOf(s); i !== -1; i = text.indexOf(s, i + 1)) k++; + return k; +}; +const REF = { + issue: r => (Object.keys(r).length === 1 && typeof r.issue === 'string' && /^[^#]+#[1-9]\d*$/.test(r.issue) && isGitHubRepo(r.issue.split('#')[0]) + ? null : `ref issue ${JSON.stringify(r.issue)} is not OWNER/REPO#N, alone`), + pinned(r) { + if (!isGitHubRepo(r.repo)) return `ref repo ${JSON.stringify(r.repo)} is not OWNER/REPO`; + return typeof r.commit === 'string' && /^[0-9a-f]{40}$/.test(r.commit) ? null : `ref commit ${JSON.stringify(r.commit)} is not a full commit id`; + }, + here(r, ctx) { + if (r.at === undefined) return ctx.exists(r.path) ? null : `ref path ${r.path} is not a file or directory that git tracks in the repository`; + if (!ctx.isFile(r.path)) return `ref path ${r.path} is not a file that git tracks in the repository`; + const k = occurrences(ctx.read(r.path), r.at); + return k === 1 ? null : `ref ${r.path} holds ${JSON.stringify(r.at)} ${k} times; a ref quotes a passage that occurs exactly once`; + }, +}; +const refKind = r => { + if (r.issue !== undefined) return 'issue'; + return r.repo !== undefined || r.commit !== undefined ? 'pinned' : 'here'; +}; + +// Check one ref; return an error or null. +export function checkRef(r, ctx) { + closed(r, REF_FIELDS, 'ref'); + const kind = refKind(r); + if (kind === 'issue') return REF.issue(r); + if (!isRepoPath(r.path)) return `ref path ${JSON.stringify(r.path)} is not a repository path`; + if (r.at !== undefined && !isQuote(r.at)) return `ref at ${JSON.stringify(r.at)} is not a short quote (one line of up to 160 characters, no blank at either end)`; + return REF[kind](r, ctx); +} +const refError = (r, ctx) => { try { return checkRef(r, ctx); } catch (e) { return e.message; } }; + +// ── Validation: the council ────────────────────────────────────────────────── +const ADVISOR_FIELDS = ['id', 'name', 'glyph', 'asks', 'reads', 'private']; +const ADVISOR_RULES = [ + ...['name', 'glyph', 'asks'].map(k => [a => isStr(a[k]), `${k} is required`]), + [a => a.reads === undefined || VALUE_KEYS.includes(a.reads), oneOf('reads', VALUE_KEYS)], + [a => a.private === undefined || a.private === true, 'private is true or absent'], + // Exactly the me advisor is private: its ranking and the page's privacy claim depend on it. + [a => a.id !== 'me' || a.private === true, 'must be private ("private":true)'], + [a => a.id === 'me' || a.private === undefined, 'only the me advisor is private'], + // The contrarian and the me advisor have their own ranking; every other advisor ranks by one mark. + [a => !SPECIAL_ADVISORS.includes(a.id) || a.reads === undefined, 'reads no value mark (it has its own ranking)'], + [a => SPECIAL_ADVISORS.includes(a.id) || a.reads !== undefined, 'reads is required (the value mark it ranks by)'], +]; + +function checkAdvisors(advisors, fail) { + const ids = new Set(); + for (const a of advisors) { + if (!isClosed(a, ADVISOR_FIELDS, `advisor ${a?.id}`, fail)) continue; + if (!isStr(a.id, 40) || !SLUG.test(a.id) || ids.has(a.id)) fail(`advisor id ${JSON.stringify(a.id)} is missing, not a slug, or repeated`); + ids.add(a.id); + applyRules(ADVISOR_RULES, a, null, `advisor ${a.id}`, fail); + } + if (!ids.has('me')) fail('advisors: the me advisor is required ("id":"me","private":true)'); + return ids; +} + +// ── Validation: the nodes ──────────────────────────────────────────────────── +const NODE_FIELDS = ['id', 'name', 'glyph', 'track', 'kind', 'status', 'size', 'summary', 'needs', 'rivals', 'value', + 'counsel', 'evidence', 'blocked_by', 'where', 'owner_value', 'refs']; +const NODE_RULES = [ + [n => isStr(n.name, 80), 'name is required (at most 80 characters)'], + [n => isStr(n.glyph, 16), 'glyph is required'], + [n => TRACKS.includes(n.track), oneOf('track', TRACKS)], + [n => KINDS.includes(n.kind), oneOf('kind', KINDS)], + [n => STATUSES.includes(n.status), oneOf('status', STATUSES)], + [n => isSize(n.size), oneOf('size', Object.keys(SIZES))], + [n => isStr(n.summary, 600), 'summary is required (at most 600 characters)'], + ...['needs', 'rivals', 'evidence', 'refs'].map(k => [n => n[k] === undefined || Array.isArray(n[k]), `${k} must be a list`]), + [n => n.where === undefined || (typeof n.where === 'string' && /^(estate|upstream):/.test(n.where) && isGitHubRepo(n.where.replace(/^\w+:/, ''))), + 'where is estate:OWNER/REPO or upstream:OWNER/REPO, or absent for this repository'], + [n => n.owner_value === undefined || n.owner_value === 'high', 'owner_value is "high" or absent'], + [n => n.status !== 'blocked' || isStr(n.blocked_by), 'a blocked node says what blocks it (blocked_by)'], + [n => n.status === 'blocked' || n.blocked_by === undefined, 'blocked_by belongs to a blocked node only'], +]; + +function checkValue(n, where, fail) { + if (n.value === undefined) return; + isClosed(n.value, VALUE_KEYS, `${where} value`, fail); + for (const [k, v] of Object.entries(n.value ?? {})) if (!Number.isInteger(v) || v < 0 || v > 3) fail(`${where}: value.${k} must be 0, 1, 2 or 3`); +} + +function checkCounsel(n, advisorIds, where, fail) { + if (n.counsel === undefined) return; + if (n.counsel === null || typeof n.counsel !== 'object' || Array.isArray(n.counsel)) { fail(`${where}: counsel must be an object`); return; } + for (const [k, v] of Object.entries(n.counsel)) { + if (k === 'me') fail(`${where}: counsel.me is refused; the me advisor's notes stay outside the public repository`); + else if (!advisorIds.has(k)) fail(`${where}: counsel from unknown advisor ${k}`); + if (!isStr(v, 300)) fail(`${where}: counsel.${k} must be a short text`); + } +} + +function checkNodes(nodes, advisorIds, fail) { + const byId = new Map(); + for (const n of nodes) { + const where = `node ${n?.id}`; + if (!isClosed(n, NODE_FIELDS, where, fail)) continue; + if (!isStr(n.id, 60) || !SLUG.test(n.id)) { fail(`${where}: id must be a lowercase slug that begins with a letter`); continue; } + if (byId.has(n.id)) { fail(`${where}: repeated id`); continue; } + byId.set(n.id, n); + applyRules(NODE_RULES, n, null, where, fail); + checkValue(n, where, fail); + checkCounsel(n, advisorIds, where, fail); + } + return byId; +} + +// ── Validation: the edges ──────────────────────────────────────────────────── +// needs and rivals name known nodes, never the node itself, and each at most once. +function checkNames(n, k, byId, fail) { + const seen = new Set(); + for (const t of list(n[k])) { + if (!byId.has(t)) fail(`node ${n.id}: ${k} names unknown node ${t}`); + if (t === n.id) fail(`node ${n.id}: ${k} names itself`); + if (seen.has(t)) fail(`node ${n.id}: ${k} names ${t} twice`); + seen.add(t); + } +} + +function checkLinks(n, byId, fail) { + checkNames(n, 'needs', byId, fail); + checkNames(n, 'rivals', byId, fail); + // A node still in play needs no dropped node: it could never start, and every + // node below it would be counted as unlocked when it never can be. + if (n.status !== 'dropped') { + for (const t of list(n.needs)) if (byId.get(t)?.status === 'dropped') fail(`node ${n.id}: needs ${t}, which is dropped; drop this node too, or name another need`); + } + for (const r of list(n.rivals)) if (byId.has(r) && !list(byId.get(r).rivals).includes(n.id)) fail(`node ${n.id}: rival ${r} does not name ${n.id} back`); +} + +// What a node's status asks of it: a done node shows evidence, a started +// node's evidence holds, and only a started node carries evidence. +function checkStarted(n, byId, ctx, fail) { + const where = `node ${n.id}`; + if (n.status === 'done' && !list(n.evidence).length) fail(`${where}: done needs evidence (a path, a claim grade or an accepted ADR)`); + if (n.status !== 'done' && n.status !== 'active') { + if (n.evidence !== undefined) fail(`${where}: evidence belongs to a done or active node`); + return; + } + // Evidence an active node shows must hold as much as a done node's. + for (const ev of list(n.evidence)) { + const e = evidenceError(ev, ctx); + if (e) fail(`${where}: ${e}`); + } + // A node is started only from the frontier, so an active node's needs are done too. + for (const t of list(n.needs)) if (byId.get(t)?.status !== 'done') fail(`${where}: ${n.status}, but its need ${t} is not done`); +} + +// Every ref of every node holds, whatever the node's status. +function checkRefs(n, ctx, fail) { + for (const r of list(n.refs)) { + const e = refError(r, ctx); + if (e) fail(`node ${n.id}: ${e}`); + } +} + +// The needs form a DAG. +function checkAcyclic(byId, fail) { + const state = new Map(); + const visit = (id, trail) => { + if (state.get(id) === 2) return; + if (state.get(id) === 1) { fail(`the needs form a cycle: ${[...trail, id].join(' -> ')}`); return; } + state.set(id, 1); + for (const t of list(byId.get(id)?.needs)) if (byId.has(t)) visit(t, [...trail, id]); + state.set(id, 2); + }; + for (const id of byId.keys()) visit(id, []); +} + +function checkActiveLimit(byId, fail) { + const active = [...byId.values()].filter(n => n.status === 'active'); + if (active.length > ACTIVE_LIMIT) fail(`${active.length} nodes are active (${active.map(n => n.id).join(', ')}); at most ${ACTIVE_LIMIT} may be, so finish or park one first`); +} + +// ── Validation: the return tickets ─────────────────────────────────────────── +const EXPEDITION_FIELDS = ['id', 'what', 'why', 'size', 'date', 'status', 'graft', 'lesson']; +const EXPEDITION_RULES = [ + ...['what', 'why'].map(k => [x => isStr(x[k]), `${k} is required`]), + [x => isSize(x.size), oneOf('size', Object.keys(SIZES))], + [x => isDate(x.date), 'date is a real calendar date, YYYY-MM-DD'], + [x => ['out', 'grafted', 'archived'].includes(x.status), 'status is out, grafted or archived'], + [(x, byId) => x.status !== 'grafted' || byId.has(x.graft), 'a grafted expedition names the node it became (graft)'], + [x => x.status === 'grafted' || x.graft === undefined, 'graft belongs to a grafted expedition'], + [x => x.status !== 'archived' || isStr(x.lesson), 'an archived expedition records what it taught (lesson)'], + [x => x.status === 'archived' || x.lesson === undefined, 'lesson belongs to an archived expedition'], +]; + +// The rule tables, exported so the tests can show that every rule has a witness. +export const RULES = {advisor: ADVISOR_RULES, node: NODE_RULES, expedition: EXPEDITION_RULES}; + +function checkExpeditions(expeditions, byId, fail) { + const ids = new Set(); + for (const x of expeditions) { + const where = `expedition ${x?.id}`; + if (!isClosed(x, EXPEDITION_FIELDS, where, fail)) continue; + if (!isStr(x.id, 20) || !/^X-\d{3}$/.test(x.id) || ids.has(x.id)) fail(`${where}: id is X-NNN and unique`); + ids.add(x.id); + applyRules(EXPEDITION_RULES, x, byId, where, fail); + } +} + +// ── Validation ─────────────────────────────────────────────────────────────── +// Every failure is collected, so one run reports them all. +export function validate({advisors, nodes, expeditions}, ctx) { + const errors = []; + const fail = m => errors.push(m); + const advisorIds = checkAdvisors(advisors, fail); + const byId = checkNodes(nodes, advisorIds, fail); + for (const n of byId.values()) { checkLinks(n, byId, fail); checkStarted(n, byId, ctx, fail); checkRefs(n, ctx, fail); } + checkAcyclic(byId, fail); + checkActiveLimit(byId, fail); + checkExpeditions(expeditions, byId, fail); + if (errors.length) throw new Error(errors.join('\n')); + return byId; +} + +// ── Derivation ─────────────────────────────────────────────────────────────── +// Each advisor's pick from the frontier. An advisor that reads a value key +// ranks the nodes it marks above zero by that mark, then as the council +// ranks: by leverage, then by value for effort. The contrarian asks which node +// everyone is overlooking: it takes the frontier node the council rates lowest +// (its marks summed), and among nodes rated equally low, the one that unlocks +// the most. Leverage only breaks the tie: ranked by leverage first, it would +// name what the council already ranks first. The me +// advisor reads no mark, since another advisor's mark is not the owner's +// preference: it ranks the nodes the owner tagged owner_value as the council +// ranks, and has no notes. +function pickFor(a, frontier, total, leverage) { + const first = (pool, order) => [...pool].sort(order)[0] ?? null; + const council = (x, y) => leverage(y.id) - leverage(x.id) || total(y) / SIZES[y.size] - total(x) / SIZES[x.size] || cmp(x.id, y.id); + const byKey = k => (x, y) => (y.value?.[k] ?? 0) - (x.value?.[k] ?? 0) || council(x, y); + if (a.id === 'contrarian') return first(frontier, (x, y) => total(x) - total(y) || leverage(y.id) - leverage(x.id) || cmp(x.id, y.id)); + // The me advisor names no public pick (owner ruling 2026-11-24): the owner chooses in a + // private panel the owner owns, and the page lists the tagged frontier unranked (ownerTagged). + if (a.private) return null; + if (a.reads) return first(frontier.filter(n => (n.value?.[a.reads] ?? 0) > 0), byKey(a.reads)); + return null; +} + +export function derive(byId, advisors) { + const children = new Map([...byId.keys()].map(id => [id, []])); + for (const n of byId.values()) for (const t of list(n.needs)) children.get(t).push(n.id); + for (const c of children.values()) c.sort(cmp); + + const depth = new Map(); + const depthOf = id => { + if (depth.has(id)) return depth.get(id); + const ns = list(byId.get(id).needs); + const d = ns.length ? 1 + Math.max(...ns.map(depthOf)) : 0; + depth.set(id, d); + return d; + }; + const below = new Map(); + const belowOf = id => { + if (below.has(id)) return below.get(id); + const s = new Set(); + for (const c of children.get(id)) { s.add(c); for (const x of belowOf(c)) s.add(x); } + below.set(id, s); + return s; + }; + for (const id of byId.keys()) { depthOf(id); belowOf(id); } + + const live = n => n.status !== 'dropped'; + const nodes = [...byId.values()]; + // Active slots still free: when none is, the frontier is ready but cannot start. + const slots = ACTIVE_LIMIT - nodes.filter(n => n.status === 'active').length; + const frontier = nodes.filter(n => n.status === 'open' && list(n.needs).every(t => byId.get(t).status === 'done')); + const total = n => Object.values(n.value ?? {}).reduce((a, b) => a + b, 0); + const leverage = id => [...below.get(id)].filter(x => live(byId.get(x))).length; + const tracksOf = ids => new Set(ids.map(t => byId.get(t)).filter(live).map(t => t.track)); + const byNodeId = (a, b) => cmp(a.id, b.id); + + const forks = nodes.filter(n => live(n) && tracksOf(children.get(n.id)).size >= 2).sort(byNodeId); + const confluences = nodes.filter(n => live(n) && new Set(list(n.needs).map(t => byId.get(t).track)).size >= 2).sort(byNodeId); + const rivalries = []; + for (const n of nodes) for (const r of list(n.rivals)) if (n.id < r) rivalries.push([n.id, r]); + + const picks = new Map(advisors.map(a => [a.id, pickFor(a, frontier, total, leverage)])); + // The frontier nodes the owner tagged, in id order: a list, never a ranking. + const ownerTagged = frontier.filter(n => n.owner_value === 'high').sort(byNodeId); + return {children, depth, below, frontier, forks, confluences, rivalries, picks, ownerTagged, leverage, total, slots}; +} + +// ── Rendering: AsciiDoc ────────────────────────────────────────────────────── +// The page is a list of sections; each section is a list of lines. +// +// Every text in the plan is plain text (owner ruling 2026-11-25), and the page +// shows it exactly as written. AsciiDoc builds all its markup from ASCII +// punctuation, so text() writes each such character as a numeric character +// reference, which Asciidoctor shows as that character and never reads as +// markup. A text can then open no block, start no list or description list, +// end no table cell or link, form no span and name no attribute, wherever it +// stands: at the start of a line, in a table, in a heading or in a link's text. +// Letters, digits, blanks and every character beyond ASCII pass unchanged. +const text = s => String(s).replace(/[\x21-\x2f\x3a-\x40\x5b-\x60\x7b-\x7e]/g, c => `&#${c.codePointAt(0)};`); +const nameOf = (byId, id) => `${byId.get(id).glyph} ${byId.get(id).name}`; +// A link to a node, as the xref macro, with its text escaped like any other. +const xref = (byId, id) => `xref:${id}[${text(nameOf(byId, id))}]`; +const xrefs = (byId, ids, sep = ', ') => ids.map(t => xref(byId, t)).join(sep); +const orNone = (items, none) => (items.length ? items : [none]); +const trackKey = t => `${TRACK_GLYPH[t]} ${t}`; + +function introLines(byId, d) { + const nodes = [...byId.values()]; + const count = s => nodes.filter(n => n.status === s).length; + return [ + '// SPDX-License-Identifier: CC-BY-SA-4.0', + '// GENERATED by scripts/ultraplan/ultraplan.mjs from docs/ultraplan/tree.jsonl,', + '// docs/ultraplan/advisors.jsonl and docs/ultraplan/expeditions.jsonl; do not hand-edit.', + '= Mathesis ultraplan: the tech tree', + ':toc: macro', + ':toclevels: 1', + '', + 'Each node is a capability. Its needs are the nodes it is built on, so the tree reads', + 'like a civilisation game: one discovery enables the next. The data in', + '`docs/ultraplan/` is the source; this page and its picture are generated from it.', + 'The era, the frontier, the forks, the confluences and each advisor\'s pick are derived,', + 'never typed. A node marked done carries evidence the generator checks: a file, a', + 'claim grade that the registry derives, or an accepted decision record. The value marks', + 'are judgements, written down so they can be argued with.', + '', + `Census of the tree: ${count('done')} done, ${count('active')} active (at most ${ACTIVE_LIMIT}), ${count('open')} open, ${count('blocked')} blocked, ${count('dropped')} dropped, of ${nodes.length} nodes. ${startable(d)}`, + '', + 'toc::[]', + '', + 'image::tree.svg[The tech tree of Mathesis, from the first era on the left to the frontier on the right]', + '', + 'Key: ✅ done · 🔨 active · 🌱 open · ⛔ blocked · 🍂 dropped. A gold border marks a node', + `that ${d.slots > 0 ? 'can be started now' : 'is ready, once an active slot is free'}. Colours are tracks: ${TRACKS.map(trackKey).join(' · ')}.`, + '', + ]; +} + +const beyondNote = n => (n.where ? ` _(${text(n.where)})_` : ''); +const startable = d => (d.slots > 0 ? `${d.frontier.length} can be started now.` : `${d.frontier.length} are ready, but all ${ACTIVE_LIMIT} active slots are full.`); +const slotsFull = `*All ${ACTIVE_LIMIT} active slots are full.* These nodes are ready, but none can start until an active node is finished or parked.`; +function frontierLines(byId, d) { + const head = [ + '== Research now: the frontier', + '', + d.slots > 0 ? 'These open nodes have every need done, so any of them can start today. "Unlocks"' + : 'These open nodes have every need done, so each can start once an active slot is free. "Unlocks"', + 'counts the live nodes that depend on it, directly or through others.', + '', + ]; + if (!d.frontier.length) return [...head, 'Nothing is on the frontier.', '']; + if (d.slots <= 0) head.push(slotsFull, ''); + const rows = [...d.frontier].sort((a, b) => d.leverage(b.id) - d.leverage(a.id) || cmp(a.id, b.id)); + return [ + ...head, + '[cols="3,1,1,1,5",options="header"]', + '|===', + '|Node |Track |Size |Unlocks |Summary', + ...rows.map(n => `|${xref(byId, n.id)} |${n.track} |${n.size} |${d.leverage(n.id)} |${text(n.summary)}${beyondNote(n)}`), + '|===', + '', + ]; +} + +function pickLine(byId, a, p) { + if (!p) return '_Pick:_ nothing on the frontier answers this advisor yet.'; + const note = p.counsel?.[a.id]; + return `_Pick:_ ${xref(byId, p.id)}${note ? '. ' + text(note) : '.'}`; +} +// The me advisor's line: its choice is made privately, so the page shows only what the +// owner tagged, unranked. +function privateLine(byId, d) { + const tagged = d.ownerTagged.length ? `Tagged on the frontier, in id order: ${xrefs(byId, d.ownerTagged.map(n => n.id))}.` : 'Nothing tagged is on the frontier.'; + return `_No public pick:_ the owner chooses in a private panel of their own. ${tagged}`; +} +function councilLines(byId, advisors, d) { + return [ + '== The council', + '', + 'Each advisor asks one question of every node and names one pick from the frontier,', + 'except the me advisor. It is private: its notes and its choice stay outside this', + 'repository, and the page lists, unranked, the frontier nodes the owner has tagged.', + '', + ...advisors.flatMap(a => [`=== ${text(a.glyph)} ${text(a.name)}`, '', `_Asks:_ ${text(a.asks)}`, '', a.private ? privateLine(byId, d) : pickLine(byId, a, d.picks.get(a.id)), '']), + ]; +} + +function forkLines(byId, d) { + return [ + '== Forks and confluences', + '', + 'A fork enables nodes on two or more tracks: work there spreads. A confluence needs', + 'nodes from two or more tracks: work there joins. Rivals are different routes to the', + 'same place; the contrarian keeps the road not taken in view.', + '', + '.Forks', + ...orNone(d.forks.map(n => `* ${xref(byId, n.id)} -> ${xrefs(byId, d.children.get(n.id))}`), '* None yet.'), + '', + '.Confluences', + ...orNone(d.confluences.map(n => `* ${xrefs(byId, list(n.needs), ' + ')} -> ${xref(byId, n.id)}`), '* None yet.'), + '', + '.Rivals', + ...orNone(d.rivalries.map(([a, b]) => `* ${xref(byId, a)} or ${xref(byId, b)}`), '* None yet.'), + '', + ]; +} + +function evidenceText(ev) { + if (ev.path) return `\`${text(ev.path)}\``; + if (ev.claim) return `${text(ev.claim)} at ${ev.min_pwg ?? 'PWG-3'} or above`; + return `ADR ${ev.adr} accepted`; +} +// A quote is shown verbatim, as a literal code span. +function refText(r) { + if (r.issue) { + const [repo, number] = r.issue.split('#'); + return `https://github.com/${repo}/issues/${number}[${text(r.issue)}]`; + } + const at = r.at === undefined ? '' : `, at \`${text(r.at)}\``; + if (r.repo) return `https://github.com/${r.repo}/blob/${r.commit}/${r.path}[${text(r.repo + ': ' + r.path)}] at \`${r.commit.slice(0, 12)}\`${at}`; + return `\`${text(r.path)}\`${at}`; +} +// Every mark the data holds is shown, a 0 as an open circle: a 0 is a judgement too. +const marks = value => VALUE_KEYS.filter(k => Object.hasOwn(value, k)).map(k => `${k} ${'●'.repeat(value[k]) || '○'}`).join(', '); + +function nodeLines(byId, advisors, d, n) { + const facts = [`*Track:* ${trackKey(n.track)}`, `*Kind:* ${n.kind}`, `*Size:* ${n.size}`, `*Status:* ${n.status}`]; + if (n.where) facts.push(`*Beyond this repository:* ${text(n.where)}`); + const enables = d.children.get(n.id); + // Each fact the node has, one a line, joined by hard line breaks. + const details = [ + [list(n.needs).length, () => `*Needs:* ${xrefs(byId, n.needs)}`], + [enables.length, () => `*Enables:* ${xrefs(byId, enables)}`], + [list(n.rivals).length, () => `*Rivals:* ${xrefs(byId, n.rivals)}`], + [n.status === 'blocked', () => `*Blocked by:* ${text(n.blocked_by)}`], + [list(n.evidence).length, () => `*Evidence:* ${n.evidence.map(evidenceText).join('; ')}`], + [n.value && Object.keys(n.value).length, () => `*Value (judgement):* ${marks(n.value)}`], + [list(n.refs).length, () => `*See:* ${n.refs.map(refText).join('; ')}`], + ].filter(([has]) => has).map(([, text]) => text()); + const counsel = Object.entries(n.counsel ?? {}).map(([id, words]) => { + const adv = advisors.find(x => x.id === id); + return `* ${text(adv.glyph)} _${text(adv.name)}:_ ${text(words)}`; + }); + return [ + `[[${n.id}]]`, + `==== ${STATUS_GLYPH[n.status]} ${text(n.glyph)} ${text(n.name)}`, + '', + text(n.summary), + '', + facts.join(' · '), + '', + ...details.map((line, i) => (i < details.length - 1 ? `${line} +` : line)), + '', + ...(counsel.length ? [...counsel, ''] : []), + ]; +} + +function eraLines(byId, advisors, d) { + const nodes = [...byId.values()]; + const maxDepth = Math.max(0, ...d.depth.values()); + const L = ['== The eras', '']; + for (let k = 0; k <= maxDepth; k++) { + const inEra = nodes.filter(n => d.depth.get(n.id) === k).sort((a, b) => TRACKS.indexOf(a.track) - TRACKS.indexOf(b.track) || cmp(a.id, b.id)); + if (!inEra.length) continue; + const [g, name] = era(k); + L.push(`=== ${g} Era ${k}: ${name}`, '', ...inEra.flatMap(n => nodeLines(byId, advisors, d, n))); + } + return L; +} + +function outcomeText(byId, x) { + if (x.status === 'out') return '🎒 out'; + if (x.status === 'grafted') return `🌿 grafted as ${xref(byId, x.graft)}`; + return `📦 archived: ${text(x.lesson)}`; +} +function ticketLines(byId, expeditions) { + const head = [ + '== Return tickets', + '', + 'Wandering off the tree is allowed. Each trip gets a card: what, why, and how big.', + 'On return it is grafted onto the tree as a node, or archived with what it taught.', + '', + ]; + if (!expeditions.length) return [...head, 'No trip is out.', '']; + return [ + ...head, + '[cols="1,1,1,3,3,3",options="header"]', + '|===', + '|Card |Date |Size |What |Why |Outcome', + ...expeditions.map(x => `|${text(x.id)} |${text(x.date)} |${x.size} |${text(x.what)} |${text(x.why)} |${outcomeText(byId, x)}`), + '|===', + '', + ]; +} + +function beyondLines(byId) { + const beyond = [...byId.values()].filter(n => n.where).sort((a, b) => cmp(a.where, b.where) || cmp(a.id, b.id)); + return [ + '== Beyond this repository', + '', + 'Nodes whose work lands in another repository. They are listed here so they can be', + 'carried to that repository, not done here.', + '', + ...orNone(beyond.map(n => `* ${text(n.where)}: ${xref(byId, n.id)} (${n.status})`), 'None.'), + '', + ]; +} + +export function renderAdoc(byId, advisors, expeditions, d) { + return [ + ...introLines(byId, d), + ...frontierLines(byId, d), + ...councilLines(byId, advisors, d), + ...forkLines(byId, d), + ...eraLines(byId, advisors, d), + ...ticketLines(byId, expeditions), + ...beyondLines(byId), + ].join('\n'); +} + +// ── Rendering: SVG ─────────────────────────────────────────────────────────── +const esc = s => String(s).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"'); +const clip = (s, n) => [...s].length <= n ? s : [...s].slice(0, n - 1).join('') + '…'; +const COL = 250, BOX_W = 214, BOX_H = 50, GAP = 14, TOP = 96, LEFT = 24, LEGEND_STEP = 128; +const GOLD = '#d4a017', EDGE = '#b9ab8c'; +// An arrowhead of fixed size whose tip sits on the end of its edge. +const arrowHead = (id, fill) => ``; + +// Where each node sits: its era is its column, and each column is ordered by +// track, then by where its needs sit, so edges cross less. +function layout(byId, d) { + const maxDepth = Math.max(0, ...d.depth.values()); + const cols = Array.from({length: maxDepth + 1}, () => []); + for (const n of byId.values()) cols[d.depth.get(n.id)].push(n); + const yOf = new Map(); + const bary = n => { + const ys = list(n.needs).map(t => yOf.get(t)).filter(v => v !== undefined); + return ys.length ? ys.reduce((a, b) => a + b, 0) / ys.length : -1; + }; + for (const col of cols) { + col.sort((a, b) => TRACKS.indexOf(a.track) - TRACKS.indexOf(b.track) || bary(a) - bary(b) || cmp(a.id, b.id)); + col.forEach((n, i) => yOf.set(n.id, TOP + i * (BOX_H + GAP))); + } + const tallest = Math.max(1, ...cols.map(c => c.length)); + // At least as wide as the fixed legend (six tracks and the beyond-repository key). + const legendW = LEFT + TRACKS.length * LEGEND_STEP + 260; + const W = Math.max(LEFT * 2 + (maxDepth + 1) * COL - (COL - BOX_W), legendW); + const H = TOP + tallest * (BOX_H + GAP) + 70; + return {maxDepth, yOf, xOf: id => LEFT + d.depth.get(id) * COL, W, H}; +} + +function svgHead(byId, {maxDepth, W, H}, d) { + const desc = `Generated by scripts/ultraplan/ultraplan.mjs from docs/ultraplan/tree.jsonl. ${byId.size} nodes in ${maxDepth + 1} eras; each arrow runs from a node to a node it enables.`; + return [ + // The SVG namespace is an identifier, never fetched, and XML Namespaces 1.0 fixes it as http. + ``, // hypatia: allow code_safety/js_http_url_in_code -- the SVG namespace URI is an identifier, not a fetched URL + '', + '', + 'The Mathesis tech tree', + `${desc}`, + '', + arrowHead('arrow', EDGE), + arrowHead('arrow-hot', GOLD), + '', + ``, + `🦉 Mathesis tech tree`, + `each arrow: this enables that · gold border: ${d.slots > 0 ? 'start it now' : 'ready, once an active slot is free'} · ✅ done 🔨 active 🌱 open ⛔ blocked 🍂 dropped`, + ]; +} + +function svgEras({maxDepth, H}) { + return Array.from({length: maxDepth + 1}, (_, k) => { + const [g, name] = era(k); + const x = LEFT + k * COL; + return [ + ``, + `${esc(g + ' ' + name)}`, + ]; + }).flat(); +} + +function svgEdge(n, t, hot, {xOf, yOf}) { + const x1 = xOf(t) + BOX_W, y1 = yOf.get(t) + BOX_H / 2, x2 = xOf(n.id), y2 = yOf.get(n.id) + BOX_H / 2; + const dx = Math.max(30, (x2 - x1) / 2); + const stroke = hot ? `stroke="${GOLD}" stroke-width="2" marker-end="url(#arrow-hot)"` : `stroke="${EDGE}" stroke-width="1.3" marker-end="url(#arrow)"`; + return ``; +} + +function svgBox(n, hot, {xOf, yOf}) { + const x = xOf(n.id), y = yOf.get(n.id); + const faded = n.status === 'dropped' ? ' opacity="0.45"' : ''; + const border = hot ? `stroke="${GOLD}" stroke-width="3"` : 'stroke="#a8977a" stroke-width="1"'; + const dashed = n.status === 'blocked' ? ' stroke-dasharray="5 3"' : ''; + const tag = `${trackKey(n.track)} · ${n.size}${n.where ? ' · 🌍' : ''}`; + return [ + ``, + `${esc(n.name + ': ' + n.summary)}`, + ``, + `${esc(n.glyph)}`, + `${esc(clip(n.name, 22))}`, + `${esc(tag)}`, + `${STATUS_GLYPH[n.status]}`, + '', + ]; +} + +function svgLegend({H}) { + const ly = H - 22; + const keys = TRACKS.flatMap((t, i) => { + const lx = LEFT + i * LEGEND_STEP; + return [ + ``, + `${esc(trackKey(t))}`, + ]; + }); + return [...keys, `🌍 lands in another repository`]; +} + +export function renderSvg(byId, d) { + const g = layout(byId, d); + const frontier = new Set(d.frontier.map(n => n.id)); + const nodes = [...byId.values()]; + return [ + ...svgHead(byId, g, d), + ...svgEras(g), + ...nodes.flatMap(n => list(n.needs).map(t => svgEdge(n, t, frontier.has(n.id), g))), + ...nodes.flatMap(n => svgBox(n, frontier.has(n.id), g)), + ...svgLegend(g), + '', + ].join('\n') + '\n'; +} + + +// ── Driver ─────────────────────────────────────────────────────────────────── +// Every path a check reads goes through the repository's files (scripts/repo/files.mjs): +// a file that git tracks, at its own path, with no link along it. The views are +// read and written as plain files inside the repository, tracked yet or not. +export function context(root = ROOT) { + const files = repoFiles(root); + const registry = 'docs/atlas/generated/registry.adoc'; + return { + isFile: files.isFile, + exists: files.exists, + read: files.read, + local: files.local, + // No registry view means no claim is listed; anything else at its path must be + // a tracked file, or it is refused. + registry: files.local.isAbsent(registry) ? '' : files.read(registry), + // Every tracked decision record with this number, in a fixed order. Only the + // boilerplate NNNN-template.adoc is set aside; a record such as + // 0006-template-inheritance.adoc counts. + adrFiles: n => files.under('docs/decisions') + .filter(x => /^docs\/decisions\/[^/]+\.adoc$/.test(x) && x.startsWith(`docs/decisions/${n}-`) && x !== `docs/decisions/${n}-template.adoc`) + .sort(cmp), + }; +} + +export function generate(root = ROOT) { + const ctx = context(root); + // The sources are read as evidence is: regular files inside the repository. + const read = f => readSource(ctx.read(`${DIR}/${f}`), `${DIR}/${f}`); + const data = {advisors: read('advisors.jsonl'), nodes: read('tree.jsonl'), expeditions: read('expeditions.jsonl')}; + const byId = validate(data, ctx); + const d = derive(byId, data.advisors); + return {[VIEW]: renderAdoc(byId, data.advisors, data.expeditions, d), [SVG]: renderSvg(byId, d), derived: d, byId}; +} + +// The views are plain files inside the repository, never links: a check would +// read through a link, and a build would write through one, out of the repository. +const VIEWS = [VIEW, SVG]; +export function staleViews(out, root = ROOT) { + const ctx = context(root); + return VIEWS.filter(f => !ctx.local.isFile(f) || ctx.local.read(f) !== out[f]); +} +export function writeViews(out, root = ROOT) { + const ctx = context(root); + if (!ctx.local.isDir(DIR)) throw new Error(`${DIR} is not a directory in the repository`); + mkdirSync(path.join(root, DIR, 'generated'), {recursive: true}); + const unsafe = VIEWS.filter(f => !ctx.local.isDir(path.dirname(f)) || !(ctx.local.isAbsent(f) || ctx.local.isFile(f))); + if (unsafe.length) throw new Error(`not written: ${unsafe.join(', ')}; a view is a plain file inside the repository, not a link`); + for (const f of VIEWS) writeFileSync(path.join(root, f), out[f]); +} + +if (import.meta.main) { + const cmd = process.argv[2]; + if (!['build', 'check'].includes(cmd)) { console.error('usage: ultraplan.mjs build|check'); process.exit(2); } + let out; + try { out = generate(); } catch (e) { console.error(`ultraplan: FAIL\n${e.message}`); process.exit(1); } + if (cmd === 'build') { + try { writeViews(out); } catch (e) { console.error(`ultraplan: FAIL\n${e.message}`); process.exit(1); } + console.log(`WROTE ${VIEWS.join(' and ')} (${out.byId.size} nodes, ${out.derived.frontier.length} on the frontier)`); + } else { + const stale = staleViews(out); + if (stale.length) { console.error(`ultraplan: FAIL\nstale: ${stale.join(', ')}; run: bun scripts/ultraplan/ultraplan.mjs build`); process.exit(1); } + console.log(`PASS: the ultraplan views match the data (${out.byId.size} nodes, ${out.derived.frontier.length} on the frontier)`); + } +} diff --git a/tests/atlas/census-atlas.test.mjs b/tests/atlas/census-atlas.test.mjs index 0a5c5e22..92f4d1e0 100644 --- a/tests/atlas/census-atlas.test.mjs +++ b/tests/atlas/census-atlas.test.mjs @@ -18,3 +18,4 @@ test('full context budget cannot omit mandatory caveat',()=>{expect(()=>pack(row test('JSON Lines input: one record per line, LF at the end, no blank line',()=>{expect(parseJsonl('')).toEqual([]);expect(parseJsonl('{"a":1}\n{"a":2}\n')).toEqual([{a:1},{a:2}]);expect(()=>parseJsonl('{"a":1}')).toThrow(/no LF/);expect(()=>parseJsonl('{"a":1}\n\n{"a":2}\n')).toThrow(/blank/);expect(()=>parseJsonl('[{"a":1},\n')).toThrow();}); test('each row names its source commit and census time',()=>{for(const r of rows){expect(r.commit).toMatch(/^[0-9a-f]{40}$/);expect(r.censused_at).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);}const {commit,censused_at,...bare}=rows[0];expect(()=>validate([bare])).toThrow(/source commit/);expect(()=>validate([{...rows[0],commit:'HEAD'}])).toThrow(/source commit/);expect(()=>validate([{...rows[0],censused_at:'2026-11-10'}])).toThrow(/census time/);}); test('the frame names public repositories only, and counts the private ones',()=>{const read=f=>readFileSync(new URL('../../docs/atlas/census/'+f,import.meta.url),'utf8');const repos=parseJsonl(read('repos.jsonl')),unreachable=parseJsonl(read('unreachable.jsonl')),count=JSON.parse(read('private-count.json'));expect(validateFrame(repos,unreachable,count)).toHaveLength(repos.length);expect(()=>validateFrame([...repos,{...repos[0],full_name:'o/hidden',visibility:'private'}],unreachable,count)).toThrow(/Nonpublic frame record/);expect(()=>validateFrame(repos,[...unreachable,{repo:'o/unlisted'}],count)).toThrow(/outside the public frame/);expect(()=>validateFrame(repos,unreachable,{...count,private_repositories:'40'})).toThrow(/private-count/);expect(()=>validateFrame(repos,unreachable,{...count,names:[]})).toThrow(/private-count/);}); +test('a census row names a GitHub repository by GitHub\'s own rule',()=>{for(const repo of ['../..','o/..','./x','o_x/r','o']){expect(()=>validate([{...rows[0],repo}])).toThrow(/Invalid or duplicate repo/);}}); diff --git a/tests/decisions/adr-status.test.mjs b/tests/decisions/adr-status.test.mjs new file mode 100644 index 00000000..b42d3ecc --- /dev/null +++ b/tests/decisions/adr-status.test.mjs @@ -0,0 +1,286 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) +// +// The status of a decision record: the Status section (read so that it never +// names a word where Asciidoctor finds no such section), the header attribute +// (read so that it never names a status Asciidoctor would not set), and the +// check that keeps the two in step (owner ruling 2026-11-25). +import {test, expect, afterAll} from 'bun:test'; +import {mkdtempSync, mkdirSync, writeFileSync, rmSync, symlinkSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import path from 'node:path'; +import {sectionStatus, headerStatus, adrStatus, adrAccepted, checkDecisions} from '../../scripts/decisions/adr-status.mjs'; + +const roots = []; +afterAll(() => { for (const r of roots) rmSync(r, {recursive: true, force: true}); }); +const sectionAccepted = t => sectionStatus(t) === 'ACCEPTED'; + + +// The status is the ADR's own text, as AsciiDoc reads it. Each of these was +// accepted when the first "Status" heading anywhere in the file was taken. +test('an ADR is accepted only by its own one Status section', () => { + const adr = body => `= ADR\n\n${body}\n`; + expect(sectionAccepted(adr('=== Status\n\n*Accepted (ratified).*'))).toBe(true); + // A heading that could read Status counts even inside a block, so this ADR is + // not read. Asciidoctor finds one Status section here; the reader fails closed. + expect(sectionAccepted(adr('=== Status\n\nAccepted\n\n----\n=== Status\nProposed\n----'))).toBe(false); + expect(sectionAccepted(adr('----\nan example\n----\n\n=== Status\n\nAccepted'))).toBe(true); + expect(sectionAccepted(adr('=== Status'))).toBe(false); + expect(sectionAccepted(adr('=== Status\n\nProposed.'))).toBe(false); + expect(sectionAccepted(adr('////\n=== Status\nAccepted\n////\n\n=== Status\n\nProposed.'))).toBe(false); + expect(sectionAccepted(adr('----\n=== Status\nAccepted\n----\n\n=== Status\n\nProposed.'))).toBe(false); + expect(sectionAccepted(adr('....\n=== Status\nAccepted\n....\n\n=== Status\n\nProposed.'))).toBe(false); + expect(sectionAccepted(adr('ifdef::never[]\n=== Status\nAccepted\nendif::[]\n\n=== Status\n\nProposed.'))).toBe(false); + expect(sectionAccepted(adr('=== Status\n\nAccepted\n\n=== Status\n\nProposed.'))).toBe(false); + expect(sectionAccepted(adr('=== Status\n// Accepted\nProposed.'))).toBe(false); + expect(sectionAccepted(adr('=== Status\n----\nAccepted\n----'))).toBe(false); + expect(sectionAccepted(adr('include::status.adoc[]\n\n=== Status\n\nAccepted'))).toBe(false); + expect(sectionAccepted(adr('// === Status\n// Accepted'))).toBe(false); + // Each of these agrees with Asciidoctor 2.0.26: a "[discrete]" waiting above the + // heading, across blank lines and comments, makes it a floating title, not a + // section; a heading straight after a paragraph line belongs to the paragraph. + for (const above of ['[discrete]\n', '[float]\n', '[discrete]\n\n', '[discrete]\n////\nx\n////\n\n', '[discrete]\n// note\n\n', 'Some text.\n']) + expect(sectionAccepted(adr(`${above}=== Status\n\nAccepted`))).toBe(false); + expect(sectionAccepted(adr('=== Status\n// a comment\nAccepted'))).toBe(true); + // "= Status" is the document's title, not a section (Asciidoctor agrees), also + // after leading comments, which may come before a document header. + expect(sectionAccepted('= Status\n\nAccepted\n')).toBe(false); + expect(sectionAccepted('// note\n////\nx\n////\n\n= Status\n\nAccepted\n')).toBe(false); + expect(sectionAccepted('== Status\n\nAccepted\n')).toBe(true); + // A heading inside a block is not a section even with a blank line above it. + for (const block of ['----\nexample\n\n=== Status\n\nAccepted\n----', '////\nold\n\n=== Status\n\nAccepted\n////', '====\n\n=== Status\n\nAccepted\n====']) + expect(sectionAccepted(adr(block))).toBe(false); + expect(sectionAccepted(adr('=== Status\n\n////\nAccepted\n////\n\nProposed.'))).toBe(false); + // Asciidoctor reads a section here, but the reader says no: it fails closed on + // any attribute line or block title above a Status heading. + for (const above of ['[[status]]\n', '.A title\n']) expect(sectionAccepted(adr(`${above}=== Status\n\nAccepted`))).toBe(false); +}); + +// Each case below was checked against Asciidoctor 2.0.26. Where the comment says +// the reader fails closed, Asciidoctor would accept and the reader refuses. +test('a Markdown fence hides what it holds, as Asciidoctor reads it', () => { + const adr = body => `= ADR\n\n${body}\n`; + // A heading inside a fence is not a section, blank lines around it or not. + expect(sectionAccepted(adr('```\n\n=== Status\n\nAccepted\n```'))).toBe(false); + expect(sectionAccepted(adr('```\n=== Status\nAccepted\n```'))).toBe(false); + // A fence opens with a language after it, and only three bare backticks close it. + expect(sectionAccepted(adr('```ruby\ncode\n```\n\n=== Status\n\nAccepted'))).toBe(true); + expect(sectionAccepted(adr('```ruby\ncode\n```ruby\n\n=== Status\n\nAccepted'))).toBe(false); + expect(sectionAccepted(adr('``` ruby\ncode\n``` ruby\n\n=== Status\n\nAccepted'))).toBe(false); + // "````" and "~~~" delimit nothing, so a later "```" opens a fence that hides the rest. + expect(sectionAccepted(adr('````\ncode\n````\n\n=== Status\n\nAccepted'))).toBe(true); + for (const lead of ['````', '~~~', '`` `']) expect(sectionAccepted(adr(`${lead}\ncode\n\`\`\`\n\n=== Status\n\nAccepted`))).toBe(false); +}); + +test('a second heading that could read Status leaves the ADR unread', () => { + const adr = body => `= ADR\n\n=== Status\n\nAccepted\n\n${body}\n\nProposed.\n`; + expect(sectionAccepted(adr('=== Context'))).toBe(true); + // Each is a second section titled Status to Asciidoctor: a later level-0 title, + // Markdown and symmetric markers, extra blanks, an underlined title, a title that + // a substitution spells, an attribute line above, and a heading straight after a block. + for (const second of ['= Status', '## Status', '### Status', '== Status ==', '== Status', '==\tStatus', + 'Status\n------', 'Status\n~~~~~~', ':s: Status\n\n== {s}', '== +Status+', '== pass:[Status]', + '== Stat{empty}us', '== ((Status))', '[#sid]\n== Status', '[appendix]\n== Status', '----\ncode\n----\n== Status']) + expect(sectionAccepted(adr(second))).toBe(false); + // A title is read whole, past a line separator (which the earlier pattern's "." + // stopped at), and a long run of blanks before one costs no backtracking. + for (const title of ['Status
', 'x
Status']) expect(sectionAccepted(adr(`== ${title}`))).toBe(false); + const started = performance.now(); + expect(sectionAccepted(adr(`=${' '.repeat(50000)}
`))).toBe(true); + expect(performance.now() - started).toBeLessThan(200); + // Seven markers make no heading, so the line cannot be the Status section. + expect(sectionAccepted('= ADR\n\n======= Status\n\nAccepted\n')).toBe(false); + for (const level of ['==', '===', '======']) expect(sectionAccepted(`= ADR\n\n${level} Status\n\nAccepted\n`)).toBe(true); +}); + +test('the Status section opens with a paragraph that says Accepted', () => { + const adr = body => `= ADR\n\n${body}\n`; + // To Asciidoctor none of these opens with such a paragraph: a literal (indented) + // line, a description-list term, an underlined title, and "///", which is text. + for (const opening of [' Accepted', 'Accepted:: yes', 'Accepted::', 'Accepted;; yes', 'Accepted\n--------', '/// x\nAccepted', '///\nAccepted']) + expect(sectionAccepted(adr(`=== Status\n\n${opening}`))).toBe(false); + expect(sectionAccepted(adr('=== Status\n\n// a comment\nAccepted'))).toBe(true); + // A heading inside a comment block is no section, though text follows the block. + expect(sectionAccepted(adr('////\n\n=== Status\n////\nAccepted'))).toBe(false); + // A heading below a list continuation, or below a term with nothing after it, + // belongs to the list. Below a term with a description the reader fails closed. + for (const above of ['* item\n+\n\n', 'term::\n\n', 'term:: words\n\n']) + expect(sectionAccepted(adr(`${above}=== Status\n\nAccepted`))).toBe(false); + expect(sectionAccepted(adr('* item\n\n=== Status\n\nAccepted'))).toBe(true); + // A short line over a delimiter of about its length is a two-line title, so no + // block opens there; the reader does not read such an ADR. + expect(sectionAccepted(adr('foo\n----\n=== Status\nProposed\n----\n\n=== Status\n\nAccepted'))).toBe(false); + // A line far from the delimiter's length leaves it a delimiter, and inside a + // block no title is read at all, whatever the lengths. + expect(sectionAccepted(adr('A much longer paragraph line\n----\ncode\n----\n\n=== Status\n\nAccepted'))).toBe(true); + expect(sectionAccepted(adr('----\nfoo\n----\n\n=== Status\n\nAccepted'))).toBe(true); +}); + +// The opening word ends where no letter, number, mark or "_" of any script +// follows: "Acceptedé" is not "Accepted", though \b would say it is. +test('the opening word of the Status section ends at a Unicode word boundary', () => { + const doc = w => `= A\n:status: ACCEPTED\n\n=== Status\n\n${w} by the owner.\n`; + for (const w of ['Accepted\u00e9', 'Accepted\u03b2', 'Accepted\u0301', 'Accepted\u0663', 'Accepted_x', 'Accepted2']) { + expect(sectionStatus(doc(w))).toBe(null); + expect(adrAccepted(doc(w))).toBe(false); + } + for (const w of ['Accepted', '*Accepted*', 'Accepted.', 'Accepted\u2014', 'Accepted (ratified)']) expect(sectionStatus(doc(w))).toBe('ACCEPTED'); +}); + +test('the Status section names its opening word, whatever the status', () => { + const adr = body => `= ADR\n\n=== Status\n\n${body}\n`; + for (const [opening, word] of [['Accepted', 'ACCEPTED'], ['*Proposed. Not yet.*', 'PROPOSED'], ['Superseded by 0007.', 'SUPERSEDED'], ['Deprecated', 'DEPRECATED']]) + expect(sectionStatus(adr(opening))).toBe(word); + // A word is a whole word: "Acceptedly" is not "Accepted". + expect(sectionStatus(adr('Acceptedly'))).toBe('ACCEPTEDLY'); + expect(sectionStatus(adr('Accepted2'))).toBe(null); + expect(sectionStatus(adr('`Accepted`'))).toBe(null); +}); + +// Each case below was checked against Asciidoctor 2.0.26's own status attribute. +test('the header states the status once, as the ADR template words it', () => { + const doc = (head, body = '') => `= ADR\n${head}\n\n${body}`; + for (const v of ['PROPOSED', 'ACCEPTED', 'DEPRECATED', 'SUPERSEDED', 'SUPERSEDED by 0007', 'REJECTED']) + expect(headerStatus(doc(`:status: ${v}`))).toBe(v); + // Leading comments and blank lines before the title, and comments and other + // attribute entries in the header, are allowed. + expect(headerStatus(`// SPDX\n// x\n\n= ADR\n// note\n:revdate: 2026-11-25\n:status: ACCEPTED\n\nBody.\n`)).toBe('ACCEPTED'); + // Other spellings and values are refused: the template's words, written exactly. + // A blank after the value is no difference: Asciidoctor, like the reader, drops it. + expect(headerStatus(doc(':status: ACCEPTED '))).toBe('ACCEPTED'); + for (const v of ['Accepted', 'accepted', ' ACCEPTED', 'ACCEPTED, really', 'SUPERSEDED by 7', 'DONE']) + expect(headerStatus(doc(`:status: ${v}`))).toBe(null); + // Not a document title, or no header at all. + expect(headerStatus('== ADR\n:status: ACCEPTED\n')).toBe(null); + expect(headerStatus('Text first.\n\n= ADR\n:status: ACCEPTED\n')).toBe(null); + // Below a blank line the entry is in the body, not the header. + expect(headerStatus('= ADR\n\n:status: ACCEPTED\n')).toBe(null); +}); + +test('nothing but the one header entry can set or unset the status', () => { + const doc = (head, body = '') => `= ADR\n${head}\n\n${body}`; + // A second entry, an unset, an inline set or a conditional anywhere. + for (const body of [':status: PROPOSED\n', ':status!:\n', ':!status:\n', 'Text {set:status:PROPOSED} here.\n', 'ifdef::x[]\n:status: PROPOSED\nendif::[]\n']) + expect(headerStatus(doc(':status: ACCEPTED', body))).toBe(null); + // Asciidoctor lowercases an entry's name: ":Status: PROPOSED" sets "status" + // (probed with 2.0.26), so an entry in any letter case counts. + for (const body of [':Status: PROPOSED\n', ':STATUS: PROPOSED\n', ':Status!:\n', ':!Status:\n', ':sTaTuS: REJECTED\n']) + expect(headerStatus(doc(':status: ACCEPTED', body))).toBe(null); + // The one header entry is written exactly as the template writes it. + expect(headerStatus(doc(':Status: ACCEPTED'))).toBe(null); + // A counter changes the attribute it names (Asciidoctor 2.0.26 turns ACCEPTED + // into ACCEPTEE), so any inline reference that changes an attribute, whichever + // it names and in whatever case, leaves the header unread. + for (const ref of ['{counter:status}', '{counter2:status}', '{counter:status:A}', '{counter:other}', '{COUNTER:status}', '{Set:status:x}']) + expect(headerStatus(doc(':status: ACCEPTED', `Accepted ${ref}\n`))).toBe(null); + // A brace that changes nothing is plain text. + expect(headerStatus(doc(':status: ACCEPTED', 'A {status} and a {counterpart}.\n'))).toBe('ACCEPTED'); + expect(headerStatus(doc(':status: ACCEPTED\n:status: ACCEPTED'))).toBe(null); + // An included file could set the status where no line here does. + expect(headerStatus(doc(':status: ACCEPTED', 'include::more.adoc[]\n'))).toBe(null); + // A header line that is neither a comment nor an entry could change what the + // header holds (an author line, a comment block), and a continuation joins + // the next line to an entry's value; each is refused. + for (const head of ['Ann Author\n:status: ACCEPTED', '////\n:status: ACCEPTED\n////', ':foo: bar \\\n:status: ACCEPTED', ':foo: bar +\n:status: ACCEPTED', ':status: ACCEPTED \\']) + expect(headerStatus(doc(head))).toBe(null); +}); + +test('an ADR is accepted only when its header and its Status section both say so', () => { + const adr = (head, opening) => `= ADR\n${head}\n\n=== Status\n\n${opening}\n`; + expect(adrAccepted(adr(':status: ACCEPTED', '*Accepted (ratified).*'))).toBe(true); + expect(adrStatus(adr(':status: ACCEPTED', 'Accepted'))).toEqual({header: 'ACCEPTED', section: 'ACCEPTED', inStep: true}); + // Out of step either way, or half stated: not accepted. + expect(adrStatus(adr(':status: ACCEPTED', 'Proposed.'))).toEqual({header: 'ACCEPTED', section: 'PROPOSED', inStep: false}); + expect(adrAccepted(adr(':status: ACCEPTED', 'Proposed.'))).toBe(false); + expect(adrAccepted(adr(':status: PROPOSED', 'Accepted'))).toBe(false); + expect(adrAccepted(adr(':revdate: x', 'Accepted'))).toBe(false); + expect(adrAccepted(`= ADR\n:status: ACCEPTED\n\nNo Status section.\n`)).toBe(false); + // In step, but not accepted. + expect(adrStatus(adr(':status: SUPERSEDED by 0007', 'Superseded by ADR 0007.'))).toEqual({header: 'SUPERSEDED by 0007', section: 'SUPERSEDED', inStep: true}); + expect(adrAccepted(adr(':status: PROPOSED', 'Proposed.'))).toBe(false); +}); + +// git, run in a fixture: the check reads only the records git tracks there. +const git = (root, ...args) => { + const r = Bun.spawnSync(['git', '-C', root, '-c', 'init.defaultBranch=main', ...args]); + if (r.exitCode !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`); +}; + +test('the check keeps every decision record in step, and reports one that states none', () => { + const root = mkdtempSync(path.join(tmpdir(), 'adr-')); + roots.push(root); + const dir = path.join(root, 'docs/decisions'); + mkdirSync(dir, {recursive: true}); + git(root, 'init', '-q'); + // Each record is written and tracked, as a commit would track it. + const put = (f, s) => { writeFileSync(path.join(dir, f), s); git(root, 'add', '-A'); }; + put('0001-a.adoc', '= A\n:status: ACCEPTED\n\n=== Status\n\nAccepted\n'); + put('0002-b.adoc', '= B\n\n== Scope\n\nNo status yet.\n'); + put('0003-template.adoc', '= Template\n:status: PROPOSED\n'); + put('README.adoc', '= Decisions\n'); + expect(checkDecisions(root)).toEqual([{file: '0001-a.adoc', status: 'ACCEPTED'}, {file: '0002-b.adoc', status: null}]); + put('0004-c.adoc', '= C\n:status: ACCEPTED\n\n=== Status\n\nProposed.\n'); + put('0005-d.adoc', '= D\n\n=== Status\n\nAccepted\n'); + put('0006-e.adoc', '= E\n:status: PROPOSED\n\nNo section.\n'); + const problems = checkDecisions(root).filter(r => r.problem).map(r => `${r.file}: ${r.problem}`); + expect(problems).toEqual([ + '0004-c.adoc: its header says ACCEPTED but its Status section says PROPOSED', + '0005-d.adoc: its header says nothing readable but its Status section says ACCEPTED', + '0006-e.adoc: its header says PROPOSED but its Status section says nothing readable', + ]); + // A record that is a link is not read. + const other = mkdtempSync(path.join(tmpdir(), 'adr-out-')); + roots.push(other); + writeFileSync(path.join(other, 'x.adoc'), '= X\n:status: ACCEPTED\n\n=== Status\n\nAccepted\n'); + symlinkSync(path.join(other, 'x.adoc'), path.join(dir, '0007-link.adoc')); + git(root, 'add', '-A'); + expect(checkDecisions(root).find(r => r.file === '0007-link.adoc')).toEqual({file: '0007-link.adoc', problem: 'is not a file that git tracks in the repository, at its own path'}); + // A record git does not track is not one, nor is a file in a directory named like one. + writeFileSync(path.join(dir, '0008-draft.adoc'), '= D\n:status: ACCEPTED\n\n=== Status\n\nProposed.\n'); + mkdirSync(path.join(dir, '0009-notes')); + writeFileSync(path.join(dir, '0009-notes/x.adoc'), '= N\n:status: ACCEPTED\n\n=== Status\n\nProposed.\n'); + git(root, 'add', 'docs/decisions/0009-notes'); + expect(checkDecisions(root).map(r => r.file)).toEqual(['0001-a.adoc', '0002-b.adoc', '0004-c.adoc', '0005-d.adoc', '0006-e.adoc', '0007-link.adoc']); + // A record whose status the readers refuse is refused, not reported as unset: + // a directive, a mutating reference or a heading that could read Status beside + // an otherwise sound status makes it unreadable, never silently empty. + const unreadable = 'it states a status that cannot be read soundly (see docs/decisions/README.adoc)'; + for (const [f, body] of [ + ['0010-include.adoc', '= J\n:status: ACCEPTED\n\n=== Status\n\nAccepted\n\ninclude::more.adoc[]\n'], + ['0011-ifdef.adoc', '= K\n:status: ACCEPTED\n\nifdef::x[]\n\n=== Status\n\nAccepted\nendif::[]\n'], + ['0012-quo.adoc', '= L\n\n== Status quo\n\nNothing is decided.\n'], + ['0013-counter.adoc', '= M\n\nA {counter:status} count.\n'], + ['0014-entry.adoc', '= N\n\nBody.\n\n:Status: ACCEPTED\n'], + ['0016-set.adoc', '= P\n\nText {set:Status:ACCEPTED} here.\n'], + // Nothing here names a status, but the included file could set one. + ['0017-include-only.adoc', '= Q\n\ninclude::decision.adoc[]\n'], + // A two-line title, "Status" over an underline, is a Status heading too. + ['0018-underlined.adoc', '= R\n\nStatus\n------\n\nAccepted\n'], + // An underlined title that cannot read Status leaves the record unset. + ['0019-context.adoc', '= S\n\nContext\n-------\n\nNothing is decided.\n'], + ['0015-plain-counter.adoc', '= O\n\nA {counter:n} count and the word status in prose.\n'], + ]) put(f, body); + const byFile = new Map(checkDecisions(root).map(r => [r.file, r])); + for (const f of ['0010-include.adoc', '0011-ifdef.adoc', '0012-quo.adoc', '0013-counter.adoc', '0014-entry.adoc', '0016-set.adoc', '0017-include-only.adoc', '0018-underlined.adoc']) + expect(byFile.get(f)).toEqual({file: f, problem: unreadable}); + // A record that states nothing about status, in any form, is still listed as + // unset, though it counts something else or says "status" in its prose. + expect(byFile.get('0002-b.adoc')).toEqual({file: '0002-b.adoc', status: null}); + expect(byFile.get('0015-plain-counter.adoc')).toEqual({file: '0015-plain-counter.adoc', status: null}); + expect(byFile.get('0019-context.adoc')).toEqual({file: '0019-context.adoc', status: null}); + // A decisions directory that is a link out of the repository is refused, and + // nothing through it is read, though git tracks the link. + const linked = mkdtempSync(path.join(tmpdir(), 'adr-linked-')); + roots.push(linked); + mkdirSync(path.join(linked, 'docs')); + symlinkSync(dir, path.join(linked, 'docs/decisions')); + git(linked, 'init', '-q'); + git(linked, 'add', '-A'); + expect(checkDecisions(linked)).toEqual([{file: 'docs/decisions', problem: 'is not a directory in the repository that holds a file git tracks'}]); +}); + +test('the decision records here are in step', () => { + const results = checkDecisions(); + expect(results.filter(r => r.problem)).toEqual([]); + expect(results.find(r => r.file === '0004-claims-registry.adoc')?.status).toBe('ACCEPTED'); +}); diff --git a/tests/registry/claims-registry.test.mjs b/tests/registry/claims-registry.test.mjs index 96fe952f..1fb54a8e 100644 --- a/tests/registry/claims-registry.test.mjs +++ b/tests/registry/claims-registry.test.mjs @@ -9,7 +9,7 @@ import {readFileSync, mkdtempSync, mkdirSync, writeFileSync, copyFileSync} from import {createHash} from 'node:crypto'; import {tmpdir} from 'node:os'; import path from 'node:path'; -import {validate, loadReader, derive, deriveAll, withGitCheck, findTool, gitChecker, checkerScript, render, READER, CHECKER} from '../../scripts/registry/claims-registry.mjs'; +import {isClaimId, validate, loadReader, derive, deriveAll, withGitCheck, findTool, gitChecker, checkerScript, render, READER, CHECKER} from '../../scripts/registry/claims-registry.mjs'; import {parseJsonl} from '../../scripts/atlas/census-atlas.mjs'; const rows = parseJsonl(readFileSync(new URL('../../docs/atlas/claims/claims.jsonl', import.meta.url), 'utf8')); @@ -63,6 +63,11 @@ test('validation fails closed', () => { expect(() => validate([{...theorem, kind: 'machine-verified'}], inv)).toThrow(/Unknown kind/); expect(() => validate([{...theorem, agda: null}], inv)).toThrow(/Agda module/); expect(() => validate([{...theorem, id: 'o/r#X'}], inv)).toThrow(/repo#claim/); + // A claim must survive the view, where its id is a link's text in a table row. + for (const claim of ['A]B', 'A|B', 'A#B', 'A B', '']) + expect(() => validate([{...theorem, id: `o/r#${claim}`, claim}], inv)).toThrow(/invalid claim id/); + for (const claim of ['N-7.1', 'THY-1-A', 'C-4a']) + expect(validate([{...theorem, id: `o/r#${claim}`, claim}], inv)).toHaveLength(1); expect(() => validate([theorem], [{full_name: 'o/r', visibility: 'private'}])).toThrow(/Nonpublic/); expect(() => validate([{...theorem, receipt: {path: 'x', sha256: 'nope'}}], inv)).toThrow(/sha256/); const home = {...theorem, id: 'hyperpolymath/mathesis#T-1', repo: 'hyperpolymath/mathesis', shelf: 'theory'}; @@ -86,7 +91,12 @@ test('validation is closed over the ADR 0004 field set', () => { expect(validate([{...theorem, receipt}], inv)).toHaveLength(1); expect(() => validate([{...theorem, receipt: {...receipt, pwg: 'PWG-1'}}], inv)).toThrow(/Unknown receipt field/); const {status_doc: _, ...missing} = theorem; - expect(() => validate([missing], inv)).toThrow(/Missing status_doc/); + expect(() => validate([missing], inv)).toThrow(/Missing or invalid status_doc/); + // The view puts the path in a link's target, so it holds only what survives there. + for (const status_doc of ['', 'docs/P[old].adoc', 'docs/a b.adoc', 'docs/x|y.adoc', 'a#b.adoc', '../x.adoc', '/abs.adoc', 'a//b.adoc', './x.adoc']) + expect(() => validate([{...theorem, status_doc}], inv)).toThrow(/Missing or invalid status_doc/); + for (const status_doc of ['PROOF-STATUS.adoc', 'docs/status/PROOF-STATUS.adoc', 'v1.2/notes_x.adoc']) + expect(validate([{...theorem, status_doc}], inv)).toHaveLength(1); }); test('only the pinned reader is loaded', async () => { @@ -217,3 +227,10 @@ test('the checker runs only beside the pinned canon reader', async () => { writeFileSync(path.join(std, READER.path), '// changed\n', {flag: 'a'}); await expect(checkerScript(std)).rejects.toThrow(/is not the pinned file/); }); + +// A claim's repository is named by GitHub's own rule: the registry makes a +// github.com link and a clone URL from it. +test('a claim id names a GitHub repository by GitHub\'s own rule', () => { + expect(isClaimId('hyperpolymath/resource-algebra#C-1')).toBe(true); + for (const id of ['../..#C-1', 'o/..#C-1', 'o_x/r#C-1', 'o#C-1', '#C-1', 'o/r#']) expect(isClaimId(id)).toBe(false); +}); diff --git a/tests/registry/engineering-receipt.test.mjs b/tests/registry/engineering-receipt.test.mjs index db6b7b2e..2713e5cf 100644 --- a/tests/registry/engineering-receipt.test.mjs +++ b/tests/registry/engineering-receipt.test.mjs @@ -58,6 +58,7 @@ test('arbitrary JSON fails registration; legacy deed refusal remains visible and for (const [name, mutate, message] of [ ['wrong repository', r => {r.repository = 'o/other';}, /repo does not match/], + ['dot-segment repository', r => {r.repository = '../..';}, /invalid repository/], ['wrong claim', r => {r.claim = 'D-2';}, /claim does not match/], ['changed statement', r => {r.statement = 'A different assertion.';}, /statement does not match/], ['changed status document', r => {r.status_doc = 'OTHER.adoc';}, /status_doc does not match/], diff --git a/tests/repo/files.test.mjs b/tests/repo/files.test.mjs new file mode 100644 index 00000000..bd385313 --- /dev/null +++ b/tests/repo/files.test.mjs @@ -0,0 +1,183 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) +// +// What the generators may read from the repository: a file that git tracks, at +// its own path, with no link along it (scripts/repo/files.mjs). +import {test, expect, afterAll} from 'bun:test'; +import {mkdtempSync, mkdirSync, writeFileSync, rmSync, symlinkSync, chmodSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import path from 'node:path'; +import {repoFiles, findProgram} from '../../scripts/repo/files.mjs'; + +const dirs = []; +afterAll(() => { for (const d of dirs) rmSync(d, {recursive: true, force: true}); }); +const temp = prefix => { const d = mkdtempSync(path.join(tmpdir(), prefix)); dirs.push(d); return d; }; +const git = (root, ...args) => { + const r = Bun.spawnSync(['git', '-C', root, '-c', 'init.defaultBranch=main', ...args]); + if (r.exitCode !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`); +}; +// A checkout: README.adoc, docs/a.adoc and docs/sub/b.adoc tracked, docs/loose.adoc and the +// directory doc/ (a prefix of docs) holding only an untracked file. +function checkout() { + const root = temp('repo-files-'); + mkdirSync(path.join(root, 'docs/sub'), {recursive: true}); + mkdirSync(path.join(root, 'doc')); + mkdirSync(path.join(root, 'empty')); + writeFileSync(path.join(root, 'README.adoc'), 'r\n'); + writeFileSync(path.join(root, 'docs/a.adoc'), 'a\n'); + writeFileSync(path.join(root, 'docs/sub/b.adoc'), 'b\n'); + git(root, 'init', '-q'); + git(root, 'add', '-A'); + writeFileSync(path.join(root, 'docs/loose.adoc'), 'loose\n'); + writeFileSync(path.join(root, 'doc/x.adoc'), 'x\n'); + return root; +} + +test('a file counts when git tracks it and it stands at its own path', () => { + const root = checkout(); + const files = repoFiles(root); + expect(files.isFile('docs/a.adoc')).toBe(true); + expect(files.read('docs/sub/b.adoc')).toBe('b\n'); + expect(files.bytes('docs/a.adoc')).toEqual(Buffer.from('a\n')); + // Untracked, in .git, absent, or not a path at all: not a file of the repository. + for (const p of ['docs/loose.adoc', '.git/HEAD', '.git/config', 'docs/none.adoc', '', 42, undefined]) { + expect(files.isFile(p)).toBe(false); + expect(files.exists(p)).toBe(false); + } + expect(() => files.read('docs/loose.adoc')).toThrow(/^docs\/loose\.adoc is not a file that git tracks in the repository$/); + // A tracked path that is now a directory is not a file. + rmSync(path.join(root, 'docs/a.adoc')); + mkdirSync(path.join(root, 'docs/a.adoc')); + writeFileSync(path.join(root, 'docs/a.adoc/inner'), 'x\n'); + expect(files.isFile('docs/a.adoc')).toBe(false); +}); + +test('a directory counts when it stands at its own path and holds a tracked file', () => { + const root = checkout(); + const files = repoFiles(root); + expect(files.isDir('docs')).toBe(true); + expect(files.isDir('docs/sub')).toBe(true); + expect(files.exists('docs/sub')).toBe(true); + // An empty directory, one holding only untracked files, and one whose name is a + // prefix of a tracked directory's (doc, beside docs) hold no tracked file. + for (const p of ['empty', 'doc', 'docs/sub/b.adoc']) { + expect(files.isDir(p)).toBe(false); + if (p !== 'docs/sub/b.adoc') expect(files.exists(p)).toBe(false); + } + // A tracked directory gone from the checkout is not one. + rmSync(path.join(root, 'docs/sub'), {recursive: true}); + expect(files.isDir('docs/sub')).toBe(false); + expect(files.exists('docs/sub')).toBe(false); + expect(files.under('docs')).toEqual(['docs/a.adoc', 'docs/sub/b.adoc']); +}); + +test('no link along a path counts, even one git tracks that stays inside', () => { + const root = checkout(); + const outside = temp('repo-files-out-'); + writeFileSync(path.join(outside, 'secret.adoc'), 'secret\n'); + symlinkSync(path.join(outside, 'secret.adoc'), path.join(root, 'docs/out.adoc')); + symlinkSync('a.adoc', path.join(root, 'docs/in.adoc')); + symlinkSync('docs', path.join(root, 'linked')); + git(root, 'add', '-A'); + const files = repoFiles(root); + for (const p of ['docs/out.adoc', 'docs/in.adoc', 'linked/a.adoc']) { + expect(files.isFile(p)).toBe(false); + expect(files.local.isFile(p)).toBe(false); + expect(() => files.read(p)).toThrow(/is not a file that git tracks/); + expect(() => files.local.read(p)).toThrow(/is not a plain file inside the repository/); + } + expect(files.isDir('linked')).toBe(false); + expect(files.local.isDir('linked')).toBe(false); +}); + +// Nothing outside the checkout is a local path: not "..", not an absolute path, +// not a path that climbs out, though a plain file stands there. +test('a local path never leads out of the checkout', () => { + const root = checkout(); + const outside = temp('repo-files-out-'); + writeFileSync(path.join(outside, 'secret.txt'), 'secret\n'); + const files = repoFiles(root); + const climb = path.relative(root, path.join(outside, 'secret.txt')); + expect(climb.startsWith('..')).toBe(true); + for (const p of [climb, path.join(outside, 'secret.txt'), '../../etc/passwd', 'docs/../../x', '..', '.']) { + expect(files.local.isFile(p)).toBe(false); + expect(files.local.isDir(p)).toBe(false); + expect(files.local.isAbsent(p)).toBe(false); + expect(() => files.local.read(p)).toThrow(/is not a plain file inside the repository/); + expect(files.isFile(p)).toBe(false); + } + // A name that only begins with two dots is inside. + writeFileSync(path.join(root, '..notes'), 'n\n'); + expect(files.local.read('..notes')).toBe('n\n'); +}); + +test('local paths: plain files and directories inside, tracked or not', () => { + const root = checkout(); + const files = repoFiles(root); + expect(files.local.isFile('docs/loose.adoc')).toBe(true); + expect(files.local.read('docs/loose.adoc')).toBe('loose\n'); + expect(files.local.isDir('empty')).toBe(true); + expect(files.local.isDir('')).toBe(false); + expect(files.local.isFile('empty')).toBe(false); + expect(files.local.isAbsent('docs/none.adoc')).toBe(true); + expect(files.local.isAbsent('docs/a.adoc')).toBe(false); + // A link that leads nowhere is not absent: something stands at the path. + symlinkSync(path.join(root, 'nowhere'), path.join(root, 'dangling')); + expect(files.local.isAbsent('dangling')).toBe(false); + expect(files.local.isFile('dangling')).toBe(false); +}); + +// git prints the top of the checkout with a closing newline, which is cut; white +// space that ends the directory's own name is part of the path and is kept. +test('a checkout whose name ends in white space is read like any other', () => { + const root = path.join(temp('repo-files-ws-'), 'repo \t '); + mkdirSync(path.join(root, 'docs'), {recursive: true}); + writeFileSync(path.join(root, 'docs/a.adoc'), 'a\n'); + git(root, 'init', '-q'); + git(root, 'add', '-A'); + expect(repoFiles(root).read('docs/a.adoc')).toBe('a\n'); +}); + +test('only the top of a git checkout is read, and a failing git fails loudly', () => { + const bare = temp('repo-files-nogit-'); + expect(() => repoFiles(bare).isFile('x')).toThrow(/is not the top of a git checkout/); + const root = checkout(); + expect(() => repoFiles(path.join(root, 'docs')).isFile('a.adoc')).toThrow(/is not the top of a git checkout/); + // An index git cannot read: git rev-parse still answers, git ls-files does not. + writeFileSync(path.join(root, '.git/index'), 'not an index'); + expect(() => repoFiles(root).isFile('docs/a.adoc')).toThrow(/^git ls-files failed in /); +}); + +test('a program is found only in an absolute directory of PATH', () => { + const bin = temp('repo-files-bin-'); + writeFileSync(path.join(bin, 'prog'), '#!/bin/sh\n'); + chmodSync(path.join(bin, 'prog'), 0o755); + expect(findProgram('prog', {PATH: `/nonexistent${path.delimiter}${bin}`})).toBe(path.join(bin, 'prog')); + // The same directory named relatively is passed over. + expect(() => findProgram('prog', {PATH: path.relative(process.cwd(), bin)})).toThrow(/^prog not found in an absolute directory of PATH$/); + expect(() => findProgram('prog', {})).toThrow(/not found/); + // As a shell does, it passes over a plain file without the execute bit and a + // directory by that name, and runs the next one that is a program. + const plain = temp('repo-files-plain-'), dir = temp('repo-files-dir-'); + writeFileSync(path.join(plain, 'prog'), 'not a program\n'); + chmodSync(path.join(plain, 'prog'), 0o644); + mkdirSync(path.join(dir, 'prog')); + expect(findProgram('prog', {PATH: [plain, dir, bin].join(path.delimiter)})).toBe(path.join(bin, 'prog')); + expect(() => findProgram('prog', {PATH: [plain, dir].join(path.delimiter)})).toThrow(/not found/); +}); + +// Repository text is decoded strictly: a malformed byte is an error, never a +// silent U+FFFD, and a byte order mark is kept as a character. +test('repository text is valid UTF-8, read exactly', () => { + const root = checkout(); + writeFileSync(path.join(root, 'bad.txt'), Buffer.from([0x61, 0xff, 0x62, 0x0a])); + writeFileSync(path.join(root, 'bom.txt'), Buffer.from([0xef, 0xbb, 0xbf, 0x61, 0x0a])); + writeFileSync(path.join(root, 'ok.txt'), 'caf\u00e9 \u2203\n'); + git(root, 'add', '-A'); + const files = repoFiles(root); + expect(() => files.read('bad.txt')).toThrow(/^bad\.txt is not valid UTF-8$/); + expect(() => files.local.read('bad.txt')).toThrow(/^bad\.txt is not valid UTF-8$/); + expect(files.read('bom.txt')).toBe('\uFEFFa\n'); + expect(files.read('ok.txt')).toBe('caf\u00e9 \u2203\n'); + expect(files.bytes('bad.txt')).toEqual(Buffer.from([0x61, 0xff, 0x62, 0x0a])); +}); diff --git a/tests/repo/github.test.mjs b/tests/repo/github.test.mjs new file mode 100644 index 00000000..8685f29b --- /dev/null +++ b/tests/repo/github.test.mjs @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) +// +// A GitHub repository named OWNER/REPO, by GitHub's own naming rules +// (scripts/repo/github.mjs). Every generator that makes a github.com link from +// a name checks it here. +import {test, expect} from 'bun:test'; +import {isGitHubRepo, GITHUB_REPO} from '../../scripts/repo/github.mjs'; + +test('real repository names pass', () => { + for (const r of ['hyperpolymath/mathesis', 'metadatastician/ZenodoDeposits.jl', 'a/b', 'o/.github', 'o/a.b-c_d', + 'o/..x', 'o/x..', `${'x'.repeat(39)}/r`, `o/${'r'.repeat(100)}`, 'a-b/c', 'a-b-c/d', 'A1/B2', + `${'ab-'.repeat(12)}abc/r`]) expect(isGitHubRepo(r)).toBe(true); +}); + +test('a name that is not a GitHub repository is refused', () => { + // Dot segments would make a link that a browser resolves to another page. + for (const r of ['../..', './x', 'x/.', 'x/..', 'x/...', '../x', './.']) expect(isGitHubRepo(r)).toBe(false); + // An owner is a login: no dot, no underscore, no hyphen at either end or two in a + // row, at most 39 characters (hyphens counted). + for (const r of ['-o/r', 'o-/r', 'o.x/r', 'o_x/r', `${'x'.repeat(40)}/r`, '/r', 'foo--bar/r', 'a---b/r', '-/r', + `${'ab-'.repeat(12)}abcd/r`]) expect(isGitHubRepo(r)).toBe(false); + // A repository name: at most 100 of letters, digits, ".", "-" and "_". + for (const r of [`o/${'r'.repeat(101)}`, 'o/', 'o/r x', 'o/r/x', 'o/r#1', 'o/r?x', 'o/r%2e', 'o', 'o/r\n']) expect(isGitHubRepo(r)).toBe(false); + for (const r of [undefined, null, 42, ['o/r'], {}]) expect(isGitHubRepo(r)).toBe(false); + expect(GITHUB_REPO.test('o/r')).toBe(true); +}); diff --git a/tests/site/site.test.mjs b/tests/site/site.test.mjs index 2570e728..c669b838 100644 --- a/tests/site/site.test.mjs +++ b/tests/site/site.test.mjs @@ -1,8 +1,10 @@ // SPDX-License-Identifier: MPL-2.0 // SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell import {test, expect} from 'bun:test'; -import {readFileSync} from 'node:fs'; -import {VIEWS, frontPage, checkLinks, htmlPath, findAsciidoctor, GITHUB} from '../../scripts/site/site.mjs'; +import {readFileSync, writeFileSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, existsSync, readdirSync, statSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import path from 'node:path'; +import {VIEWS, frontPage, checkLinks, htmlPath, findAsciidoctor, build, GITHUB} from '../../scripts/site/site.mjs'; const root = new URL('../../', import.meta.url).pathname; const read = f => readFileSync(root + f, 'utf8'); @@ -55,3 +57,107 @@ test('asciidoctor is found only in an absolute directory of PATH', () => { expect(findAsciidoctor({ASCIIDOCTOR: '/x/asciidoctor'})).toBe('/x/asciidoctor'); expect(() => findAsciidoctor({PATH: 'relative/dir'})).toThrow(/not found/); }); + +// A throwaway checkout holding every view, each a plain tracked file whose header +// names its source, and a directory outside it. Removed when `body` returns. +function withSite(body) { + const tmp = prefix => mkdtempSync(path.join(tmpdir(), prefix)); + const fix = tmp('site-fix-'), outside = tmp('site-outside-'), outs = tmp('site-out-'); + const git = (...args) => { + const r = Bun.spawnSync(['git', '-C', fix, '-c', 'init.defaultBranch=main', ...args]); + if (r.exitCode !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`); + }; + try { + git('init', '-q'); + for (const f of [...VIEWS.map(v => v.file), ...VIEWS.flatMap(v => v.assets ?? [])]) { + mkdirSync(path.dirname(path.join(fix, f)), {recursive: true}); + const v = VIEWS.find(x => x.file === f); + writeFileSync(path.join(fix, f), v ? `// ${v.needs}\n= View\n` : '\n'); + } + git('add', '-A'); + body({fix, outside, out: path.join(outs, 'site'), git}); + } finally { + for (const d of [fix, outside, outs]) rmSync(d, {recursive: true, force: true}); + } +} +const pathRe = p => p.replaceAll('.', '\\.'); +// Every file the build wrote, and whether any holds `s`. +const holds = (dir, s) => existsSync(dir) && readdirSync(dir, {recursive: true}) + .some(f => statSync(path.join(dir, f)).isFile() && readFileSync(path.join(dir, f), 'utf8').includes(s)); + +// The site takes from the repository only files that git tracks, at their own +// path. An asset or a view that is a link, even one git tracks, or one git does +// not track, fails the build before anything is written or copied. +test('the site copies nothing from outside the repository', () => withSite(({fix, outside, out, git}) => { + writeFileSync(path.join(outside, 'secret.svg'), 'secret\n'); + const [asset] = VIEWS.flatMap(v => v.assets ?? []); + rmSync(path.join(fix, asset)); + symlinkSync(path.join(outside, 'secret.svg'), path.join(fix, asset)); + git('add', '-A'); + expect(() => build(fix, out)).toThrow(new RegExp(`^${pathRe(asset)} is not a file that git tracks in the repository$`)); + expect(existsSync(out)).toBe(false); + // A plain asset that git does not track is refused the same way. + rmSync(path.join(fix, asset)); + writeFileSync(path.join(fix, asset), '\n'); + git('rm', '-q', '--cached', '-f', asset); + expect(() => build(fix, out)).toThrow(new RegExp(`^${pathRe(asset)} is not a file that git tracks in the repository$`)); + // So is a view that is a link into the repository. + git('add', '-A'); + const [view] = VIEWS; + rmSync(path.join(fix, view.file)); + symlinkSync(path.join(fix, VIEWS[1].file), path.join(fix, view.file)); + git('add', '-A'); + expect(() => build(fix, out)).toThrow(new RegExp(`^${pathRe(view.file)} is not a file that git tracks`)); + expect(existsSync(out)).toBe(false); +})); + +// A link in a view to a file of the repository that the site does not hold +// becomes a GitHub link, but only when git tracks the file: an untracked one +// would be a link to nothing on GitHub, so it fails the build. +test('a view links on GitHub only to files git tracks', () => withSite(({fix, out, git}) => { + const [view] = VIEWS; + const up = path.posix.relative(path.posix.dirname(view.file), 'notes.adoc'); + writeFileSync(path.join(fix, view.file), `// ${view.needs}\n= View\n\nlink:${up}[notes]\n`); + writeFileSync(path.join(fix, 'notes.adoc'), '= Notes\n'); + git('add', view.file); + expect(() => build(fix, out)).toThrow(/broken relative link .*notes\.adoc \(not in the site, not in the repository\)/); + git('add', 'notes.adoc'); + build(fix, `${out}-tracked`); + expect(readFileSync(path.join(`${out}-tracked`, htmlPath(view.file)), 'utf8')).toContain(`${GITHUB}/blob/main/notes.adoc`); +})); + +// The site is built into a fresh tree. An output directory that holds anything, +// a link where the build writes above all, or that is itself a link, is refused +// before a byte is written, so nothing outside it can be overwritten. +test('the site is built only into a fresh output directory', () => withSite(({fix, outside, out}) => { + const [asset] = VIEWS.flatMap(v => v.assets ?? []); + writeFileSync(path.join(outside, 'victim.txt'), 'ORIGINAL\n'); + mkdirSync(path.dirname(path.join(out, asset)), {recursive: true}); + symlinkSync(path.join(outside, 'victim.txt'), path.join(out, asset)); + expect(() => build(fix, out)).toThrow(/is not a fresh output directory/); + expect(readFileSync(path.join(outside, 'victim.txt'), 'utf8')).toBe('ORIGINAL\n'); + // A directory that is itself a link is refused, though empty. + const empty = path.join(outside, 'empty'); + mkdirSync(empty); + symlinkSync(empty, `${out}-link`); + expect(() => build(fix, `${out}-link`)).toThrow(/is not a fresh output directory/); + // An empty directory, or a path that does not exist yet, is fresh. + mkdirSync(`${out}-empty`); + expect(build(fix, `${out}-empty`).length).toBe(VIEWS.length + 1); + expect(build(fix, `${out}-new`).length).toBe(VIEWS.length + 1); +})); + +// Asciidoctor reads no file but the page it renders: an include in a view, of a +// file outside the repository, is not read into the site; it fails the build. +test('an include in a view reads nothing into the site', () => withSite(({fix, outside, out, git}) => { + expect(build(fix, out).length).toBe(VIEWS.length + 1); + writeFileSync(path.join(outside, 'secret.txt'), 'SECRET-LINE\n'); + const [view] = VIEWS; + writeFileSync(path.join(fix, view.file), `// ${view.needs}\n= View\n\ninclude::${path.join(outside, 'secret.txt')}[]\n`); + git('add', '-A'); + const again = `${out}-again`; + expect(() => build(fix, again)).toThrow(/broken relative link .*secret\.txt/); + expect(holds(again, 'SECRET-LINE')).toBe(false); + expect(holds(again, 'secret.txt')).toBe(true); // a link to it, never its text + rmSync(again, {recursive: true, force: true}); +})); diff --git a/tests/ultraplan/ultraplan.test.mjs b/tests/ultraplan/ultraplan.test.mjs new file mode 100644 index 00000000..36f2d3e4 --- /dev/null +++ b/tests/ultraplan/ultraplan.test.mjs @@ -0,0 +1,656 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) +// +// The ultraplan generator: what it derives, and each thing it refuses. +import {test, expect, afterAll} from 'bun:test'; +import {mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync, symlinkSync, existsSync, readdirSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import path from 'node:path'; +import {generate, validate, derive, readSource, registryGrade, context, staleViews, writeViews, ACTIVE_LIMIT, ROOT, VIEW, SVG, RULES} + from '../../scripts/ultraplan/ultraplan.mjs'; +import {jcs} from '../../scripts/registry/theory-ledger.mjs'; +import {adrAccepted} from '../../scripts/decisions/adr-status.mjs'; + +const roots = []; +// git, run in a fixture: the generator reads only what git tracks there. +const git = (root, ...args) => { + const r = Bun.spawnSync(['git', '-C', root, '-c', 'user.name=t', '-c', 'user.email=t@example.invalid', '-c', 'init.defaultBranch=main', ...args]); + if (r.exitCode !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`); + return r.stdout.toString(); +}; +// Track everything now in the fixture, as a commit would. +const track = root => { git(root, 'add', '-A'); return root; }; +afterAll(() => { for (const r of roots) rmSync(r, {recursive: true, force: true}); }); + +const ADVISORS = [ + {id: 'maths', name: 'Mathematician', glyph: '∑', asks: 'Is it true, and is it deep?', reads: 'maths'}, + {id: 'engineering', name: 'Engineer', glyph: '⚙', asks: 'Does it run, and can it be kept?', reads: 'engineering'}, + {id: 'contrarian', name: 'Contrarian', glyph: '🦉', asks: 'What if the opposite?'}, + {id: 'me', name: 'Me', glyph: '🫶', asks: 'Does it help the owner?', private: true}, +]; +const node = (id, extra = {}) => ({id, name: id, glyph: '🔷', track: 'maths', kind: 'theorem', status: 'open', size: 'M', summary: `The ${id} node.`, ...extra}); +const BASE = [ + node('root', {status: 'done', evidence: [{path: 'README.adoc'}]}), + node('tool', {track: 'engineering', kind: 'tool', status: 'done', needs: ['root'], evidence: [{adr: '0004'}]}), + node('theorem', {needs: ['root'], value: {maths: 3}, counsel: {maths: 'The deep one.'}, owner_value: 'high'}), + node('panel', {track: 'engineering', kind: 'view', needs: ['tool', 'theorem'], value: {engineering: 2}}), + node('paper', {track: 'publications', kind: 'paper', needs: ['theorem'], value: {publications: 3}}), + node('cheap', {needs: ['tool'], value: {engineering: 1}, size: 'S'}), +]; + +// A throwaway repository root with the files the evidence checks read. +function fixture({advisors = ADVISORS, nodes = BASE, expeditions = [], registry = '', raw = {}} = {}) { + const root = mkdtempSync(path.join(tmpdir(), 'ultraplan-')); + roots.push(root); + mkdirSync(path.join(root, 'docs/ultraplan'), {recursive: true}); + mkdirSync(path.join(root, 'docs/decisions'), {recursive: true}); + mkdirSync(path.join(root, 'docs/atlas/generated'), {recursive: true}); + writeFileSync(path.join(root, 'README.adoc'), '= Fixture\n'); + writeFileSync(path.join(root, 'docs/decisions/0004-claims-registry.adoc'), '= ADR\n:status: ACCEPTED\n\n=== Status\n\n*Accepted (ratified).*\n'); + writeFileSync(path.join(root, 'docs/decisions/0005-jcs.adoc'), '= ADR\n:status: PROPOSED\n\n=== Status\n\n*Proposed. Not accepted.*\n'); + writeFileSync(path.join(root, 'docs/atlas/generated/registry.adoc'), registry); + const jl = rows => rows.map(r => jcs(r) + '\n').join(''); + writeFileSync(path.join(root, 'docs/ultraplan/advisors.jsonl'), raw.advisors ?? jl(advisors)); + writeFileSync(path.join(root, 'docs/ultraplan/tree.jsonl'), raw.nodes ?? jl(nodes)); + writeFileSync(path.join(root, 'docs/ultraplan/expeditions.jsonl'), raw.expeditions ?? jl(expeditions)); + git(root, 'init', '-q'); + return track(root); +} +// The page shows each text as written: every ASCII punctuation mark in it is a +// numeric character reference (the rule, stated here apart from the generator). +const PUNCTUATION = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'; +const plainOnPage = t => [...t].map(c => (PUNCTUATION.includes(c) ? `&#${c.codePointAt(0)};` : c)).join(''); +const refuses = (opts, re) => expect(() => generate(fixture(opts))).toThrow(re); +// Replace fields of one node; a field set to undefined is removed. +const strip = o => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)); +const swap = (id, extra, nodes = BASE) => nodes.map(n => n.id === id ? strip({...n, ...extra}) : n); + +// The contrarian names the node the council rates lowest; leverage only breaks a +// tie between nodes rated equally low, and the id breaks a tie after that. +test('the contrarian takes the lowest-rated node, and unlocks break the tie', () => { + const nodes = [...BASE, node('alpha', {needs: ['root']}), node('zeta', {needs: ['root']}), node('zeta-next', {needs: ['zeta']})]; + const d = generate(fixture({nodes})).derived; + // alpha and zeta are both rated 0, below cheap (1); zeta unlocks one live node, alpha none. + expect(d.picks.get('contrarian').id).toBe('zeta'); + // A node that unlocks more but is rated higher is not the contrarian's. + const rated = nodes.map(n => (n.id === 'zeta' ? {...n, value: {maths: 1}} : n)); + expect(generate(fixture({nodes: rated})).derived.picks.get('contrarian').id).toBe('alpha'); +}); + +test('derives eras, the frontier, forks, confluences and each advisor\'s pick', () => { + const out = generate(fixture()); + const d = out.derived; + expect([...d.depth.entries()].sort()).toEqual([['cheap', 2], ['panel', 2], ['paper', 2], ['root', 0], ['theorem', 1], ['tool', 1]]); + expect(d.frontier.map(n => n.id).sort()).toEqual(['cheap', 'theorem']); + expect(d.forks.map(n => n.id).sort()).toEqual(['root', 'theorem', 'tool']); // each enables nodes on two tracks + expect(d.confluences.map(n => n.id)).toEqual(['panel']); // engineering + maths + expect(d.leverage('root')).toBe(5); + expect(d.picks.get('maths').id).toBe('theorem'); + expect(d.picks.get('engineering').id).toBe('cheap'); + expect(d.picks.get('contrarian').id).toBe('cheap'); // rated lowest by the council + expect(d.picks.get('me')).toBe(null); // no public pick (owner ruling 2026-11-24) + expect(d.ownerTagged.map(n => n.id)).toEqual(['theorem']); // tagged owner_value, no notes + expect(out[VIEW]).toContain('== Research now: the frontier'); + expect(out[VIEW]).toContain(`_Pick:_ xref:theorem[🔷 theorem]. ${plainOnPage('The deep one.')}`); + expect(out[VIEW]).toContain('_No public pick:_ the owner chooses in a private panel of their own. Tagged on the frontier, in id order: xref:theorem[🔷 theorem].'); + expect(out[SVG].startsWith(''); + // Three eras are narrower than the legend; the canvas still holds the legend. + expect(Number(/width="(\d+)"/.exec(out[SVG])[1])).toBeGreaterThanOrEqual(24 + 6 * 128 + 260); + // Every edge (six in the fixture) ends in an arrowhead, gold where it leads to the frontier. + const edges = out[SVG].match(/]*\/>/g); + expect(edges.length).toBe(6); + expect(edges.every(e => /marker-end="url\(#arrow(-hot)?\)"/.test(e))).toBe(true); + expect(out[SVG]).toContain(' { + // `<>` ends at ">>"; the xref macro's text ends at "]", turns into attributes at "=", + // and a table cell ends at "|". Every one is a character reference, so the link text is the name. + const page = generate(fixture({nodes: swap('theorem', {name: 'a >> b = c ] d | e'})}))[VIEW]; + expect(page).toContain('xref:theorem[🔷 a >> b = c ] d | e]'); + expect(page).not.toContain('< { + const page = generate(fixture({nodes: swap('paper', {value: {maths: 0, publications: 3}})}))[VIEW]; + expect(page).toContain('*Value (judgement):* maths ○, publications ●●●'); + const zero = generate(fixture({nodes: swap('paper', {value: {maths: 0}})}))[VIEW]; + expect(zero).toContain('*Value (judgement):* maths ○'); +}); + +test('the views are deterministic', () => { + const a = generate(fixture()), b = generate(fixture()); + expect(a[VIEW]).toBe(b[VIEW]); + expect(a[SVG]).toBe(b[SVG]); +}); + +test('done needs evidence that holds', () => { + refuses({nodes: swap('root', {evidence: []})}, /node root: done needs evidence/); + refuses({nodes: swap('root', {evidence: [{path: 'NOPE.adoc'}]})}, /evidence path NOPE.adoc is not a file that git tracks in the repository/); + refuses({nodes: swap('root', {evidence: [{path: '../etc/passwd'}]})}, /is not a repository path/); + refuses({nodes: swap('root', {evidence: [{path: '.'}]})}, /evidence path "." is not a repository path/); + refuses({nodes: swap('root', {evidence: [{path: 'docs'}]})}, /evidence path docs is not a file that git tracks in the repository/); + refuses({nodes: swap('root', {evidence: [{path: 'docs/decisions'}]})}, /evidence path docs\/decisions is not a file/); + // A committed symlink to a file outside the repository is not evidence in it. + const outside = mkdtempSync(path.join(tmpdir(), 'ultraplan-outside-')); + roots.push(outside); + writeFileSync(path.join(outside, 'secret.txt'), 'x\n'); + const root = fixture({nodes: swap('root', {evidence: [{path: 'link.txt'}]})}); + symlinkSync(path.join(outside, 'secret.txt'), path.join(track(root), 'link.txt')); + track(root); + expect(() => generate(root)).toThrow(/evidence path link.txt is not a file that git tracks in the repository/); + const inside = fixture({nodes: swap('root', {evidence: [{path: 'inner.adoc'}]})}); + // A link that stays inside is refused too: a path names the file itself, and + // git tracks a link, not the file it leads to. + symlinkSync('README.adoc', path.join(inside, 'inner.adoc')); + track(inside); + expect(() => generate(inside)).toThrow(/evidence path inner\.adoc is not a file that git tracks in the repository/); + // So is a path through a linked directory, though the file it reaches is tracked. + const viaDir = fixture({nodes: swap('root', {evidence: [{path: 'notes/README.adoc'}]})}); + symlinkSync('.', path.join(viaDir, 'notes')); + track(viaDir); + expect(() => generate(viaDir)).toThrow(/evidence path notes\/README\.adoc is not a file that git tracks/); + // A file git does not track is no evidence, though it stands in the checkout: + // nothing a reviewer could read in the commit. Nor is anything in .git. + const loose = fixture({nodes: swap('root', {evidence: [{path: 'draft.adoc'}]})}); + writeFileSync(path.join(loose, 'draft.adoc'), 'x\n'); + expect(() => generate(loose)).toThrow(/evidence path draft\.adoc is not a file that git tracks in the repository/); + track(loose); + expect(() => generate(loose)).not.toThrow(); + for (const p of ['.git/config', '.git/HEAD']) refuses({nodes: swap('root', {evidence: [{path: p}]})}, /is not a file that git tracks in the repository/); + // A tracked file that is gone from the checkout is no evidence either. + const gone = fixture(); + rmSync(path.join(gone, 'README.adoc')); + expect(() => generate(gone)).toThrow(/evidence path README\.adoc is not a file that git tracks/); + // An ADR that is a symlink to an accepted record outside the repository is not one in it. + writeFileSync(path.join(outside, 'accepted.adoc'), '= ADR\n\n=== Status\n\n*Accepted.*\n'); + const adr = fixture({nodes: swap('tool', {evidence: [{adr: '0007'}]})}); + symlinkSync(path.join(outside, 'accepted.adoc'), path.join(adr, 'docs/decisions/0007-outside.adoc')); + track(adr); + expect(() => generate(adr)).toThrow(/ADR 0007 \(docs\/decisions\/0007-outside\.adoc\) is not a file that git tracks in the repository/); + // The context reads no file outside the repository, whoever asks. + expect(() => context(adr).read('docs/decisions/0007-outside.adoc')).toThrow(/is not a file that git tracks in the repository/); + expect(context(adr).read('README.adoc')).toBe('= Fixture\n'); + // The registry view is evidence too: one that leads outside the repository is refused. + writeFileSync(path.join(outside, 'registry.adoc'), '|https://x/blob/c/P.adoc[o/r#T-1] at `c` |theorem |`PWG-1` |s |w\n'); + const reg = fixture({nodes: swap('root', {evidence: [{claim: 'o/r#T-1'}]})}); + rmSync(path.join(reg, 'docs/atlas/generated/registry.adoc')); + symlinkSync(path.join(outside, 'registry.adoc'), path.join(reg, 'docs/atlas/generated/registry.adoc')); + track(reg); + expect(() => generate(reg)).toThrow(/docs\/atlas\/generated\/registry\.adoc is not a file that git tracks in the repository/); + refuses({nodes: swap('tool', {evidence: [{adr: '0005'}]})}, /ADR 0005 is PROPOSED, not ACCEPTED/); + refuses({nodes: swap('tool', {evidence: [{adr: '0009'}]})}, /no ADR 0009/); + // Two records with one number are refused, not picked between by directory order. + const twin = fixture(); + writeFileSync(path.join(twin, 'docs/decisions/0004-second.adoc'), '= ADR\n\n=== Status\n\n*Proposed.*\n'); + expect(() => generate(twin)).not.toThrow(); // untracked, so not yet a record + track(twin); + // A file in a directory named like a record is not a record. + const nested = fixture(); + mkdirSync(path.join(nested, 'docs/decisions/0004-notes')); + writeFileSync(path.join(nested, 'docs/decisions/0004-notes/draft.adoc'), '= Draft\n:status: PROPOSED\n\n=== Status\n\nProposed.\n'); + expect(() => generate(track(nested))).not.toThrow(); + expect(() => generate(twin)).toThrow(/ADR 0004 is ambiguous: docs\/decisions\/0004-claims-registry\.adoc, docs\/decisions\/0004-second\.adoc share the number/); + // Only the boilerplate NNNN-template.adoc is set aside: a record whose title says template counts, + // and a template that shares a number with a record does not make it ambiguous. + const titled = fixture({nodes: swap('tool', {evidence: [{adr: '0006'}]})}); + writeFileSync(path.join(titled, 'docs/decisions/0006-template-inheritance.adoc'), '= ADR\n:status: ACCEPTED\n\n=== Status\n\n*Accepted.*\n'); + track(titled); + expect(() => generate(titled)).not.toThrow(); + const boiler = fixture(); + writeFileSync(path.join(boiler, 'docs/decisions/0004-template.adoc'), '= Template\n\n=== Status\n\nProposed\n'); + track(boiler); + expect(() => generate(boiler)).not.toThrow(); + refuses({nodes: swap('root', {evidence: [{path: 'README.adoc', adr: '0004'}]})}, /exactly one of path, claim or adr/); + refuses({nodes: swap('root', {evidence: [{path: 'README.adoc', min_pwg: 'PWG-1'}]})}, /min_pwg belongs to claim evidence only/); + refuses({nodes: swap('tool', {evidence: [{adr: '0004', min_pwg: 'PWG-1'}]})}, /min_pwg belongs to claim evidence only/); +}); + +test('a claim is evidence only at the grade the registry derives', () => { + const registry = '|https://x/blob/c/P.adoc[o/r#T-1] at `c` |theorem |`PWG-2i` |text |why\n'; + const ok = swap('root', {evidence: [{claim: 'o/r#T-1', min_pwg: 'PWG-2i'}]}); + expect(() => generate(fixture({nodes: ok, registry}))).not.toThrow(); + refuses({nodes: swap('root', {evidence: [{claim: 'o/r#T-1', min_pwg: 'PWG-2ii'}]}), registry}, /o\/r#T-1 derives PWG-2i, below PWG-2ii/); + refuses({nodes: swap('root', {evidence: [{claim: 'o/r#T-9'}]}), registry}, /does not list o\/r#T-9/); + // An id mentioned inside another row's statement does not list that claim. + const mention = '|https://x/blob/c/P.adoc[o/r#T-1] at `c` |theorem |`PWG-2ii` |Builds on [o/r#GHOST-1] |why\n'; + refuses({nodes: swap('root', {evidence: [{claim: 'o/r#GHOST-1'}]}), registry: mention}, /does not list o\/r#GHOST-1/); + // Any id the registry accepts can be cited, and only those: its rule is shared. + const odd = '|https://x/blob/c/P.adoc[o/r#N-7.1] at `c` |theorem |`PWG-2i` |s |w\n|https://x/blob/c/P.adoc[o/r#THY-1-A] at `c` |theorem |`PWG-3` |s |w\n'; + expect(() => generate(fixture({nodes: swap('root', {evidence: [{claim: 'o/r#N-7.1'}, {claim: 'o/r#THY-1-A'}]}), registry: odd}))).not.toThrow(); + refuses({nodes: swap('root', {evidence: [{claim: 'o/r#'}]}), registry: odd}, /evidence claim "o\/r#" is not OWNER\/REPO#ID/); + refuses({nodes: swap('root', {evidence: [{claim: 'or#N-1'}]}), registry: odd}, /evidence claim "or#N-1" is not OWNER\/REPO#ID/); + refuses({nodes: swap('root', {evidence: [{claim: 'o/r#A]B'}]}), registry: odd}, /evidence claim "o\/r#A\]B" is not OWNER\/REPO#ID/); +}); + +test('a done or active node cannot rest on an unfinished need', () => { + refuses({nodes: swap('cheap', {status: 'done', evidence: [{path: 'README.adoc'}], needs: ['theorem']})}, /node cheap: done, but its need theorem is not done/); + refuses({nodes: swap('panel', {status: 'active'})}, /node panel: active, but its need theorem is not done/); + expect(() => generate(fixture({nodes: swap('cheap', {status: 'active'})}))).not.toThrow(); +}); + +test('the needs form a DAG over known nodes', () => { + refuses({nodes: swap('tool', {status: 'open', evidence: undefined}, swap('root', {status: 'open', evidence: undefined, needs: ['paper']}))}, /cycle/); + refuses({nodes: swap('theorem', {needs: ['root', 'ghost']})}, /needs names unknown node ghost/); + refuses({nodes: swap('theorem', {needs: ['root', 'root']})}, /needs names root twice/); +}); + +// A node still in play needs no dropped node: it could never start. Dropping a +// node means dropping what needs it too, so nothing below a dropped node is ever +// counted as unlocked. +test('a node still in play needs no dropped node', () => { + refuses({nodes: swap('theorem', {status: 'dropped', owner_value: undefined})}, /node paper: needs theorem, which is dropped; drop this node too, or name another need/); + refuses({nodes: swap('theorem', {status: 'dropped', owner_value: undefined})}, /node panel: needs theorem, which is dropped/); + const dropped = BASE.map(n => (['theorem', 'paper', 'panel'].includes(n.id) ? strip({...n, status: 'dropped', owner_value: undefined}) : n)); + const d = generate(fixture({nodes: dropped})).derived; + // root now unlocks only tool and cheap, the nodes still in play below it. + expect(d.leverage('root')).toBe(2); +}); + +test('rivals name each other back', () => { + refuses({nodes: swap('paper', {rivals: ['cheap']})}, /rival cheap does not name paper back/); + const both = BASE.map(n => n.id === 'paper' ? {...n, rivals: ['cheap']} : n.id === 'cheap' ? {...n, rivals: ['paper']} : n); + expect(generate(fixture({nodes: both})).derived.rivalries).toEqual([['cheap', 'paper']]); +}); + +test('the council is well formed', () => { + refuses({advisors: ADVISORS.filter(a => a.id !== 'me')}, /the me advisor is required/); + refuses({advisors: ADVISORS.map(a => a.id === 'maths' ? {id: a.id, name: a.name, glyph: a.glyph, asks: a.asks} : a)}, /advisor maths: reads is required/); + refuses({advisors: ADVISORS.map(a => a.id === 'contrarian' ? {...a, reads: 'maths'} : a)}, /advisor contrarian: reads no value mark/); +}); + +test('exactly the me advisor is private', () => { + refuses({advisors: ADVISORS.map(a => a.id === 'me' ? {...a, private: undefined} : a).map(a => JSON.parse(JSON.stringify(a)))}, /advisor me: must be private/); + refuses({advisors: ADVISORS.map(a => a.id === 'maths' ? {...a, private: true} : a)}, /advisor maths: only the me advisor is private/); +}); + +test('the me advisor writes nothing into the public tree', () => { + refuses({nodes: swap('theorem', {counsel: {me: 'personal note'}})}, /counsel\.me is refused/); + refuses({nodes: swap('theorem', {owner_value: 'medium'})}, /owner_value is "high" or absent/); +}); + +test('evidence on an active node must hold too', () => { + refuses({nodes: swap('theorem', {status: 'active', evidence: [{}]})}, /exactly one of path, claim or adr/); + refuses({nodes: swap('theorem', {status: 'active', evidence: [{path: 'NOPE.adoc'}]})}, /is not a file that git tracks in the repository/); + expect(() => generate(fixture({nodes: swap('theorem', {status: 'active', evidence: [{path: 'README.adoc'}]})}))).not.toThrow(); + refuses({nodes: swap('paper', {evidence: [{path: 'README.adoc'}]})}, /evidence belongs to a done or active node/); +}); + +test(`at most ${ACTIVE_LIMIT} nodes are active`, () => { + const busy = BASE.map(n => ['theorem', 'paper', 'cheap', 'panel'].includes(n.id) ? {...n, status: 'active'} : n); + refuses({nodes: busy}, new RegExp(`4 nodes are active .* at most ${ACTIVE_LIMIT}`)); +}); + +test('closed schema, blocked reasons and canonical lines', () => { + refuses({nodes: swap('paper', {colour: 'red'})}, /node paper: unknown field "colour"/); + refuses({nodes: swap('paper', {status: 'blocked'})}, /says what blocks it/); + refuses({nodes: swap('paper', {track: 'poetry'})}, /track must be one of/); + refuses({nodes: swap('paper', {value: {maths: 4}})}, /value\.maths must be 0, 1, 2 or 3/); + refuses({nodes: swap('paper', {where: 'elsewhere'})}, /where is estate:OWNER\/REPO/); + // A list holding a valid place is not a place (a regular expression would read it as one). + refuses({nodes: swap('paper', {where: ['estate:o/r']})}, /where is estate:OWNER\/REPO/); + // A place is a GitHub repository by GitHub's own rule: no dot segments. + for (const where of ['estate:../..', 'upstream:o/..', 'estate:o', 'elsewhere:o/r']) + refuses({nodes: swap('paper', {where})}, /where is estate:OWNER\/REPO/); + expect(() => generate(fixture({nodes: swap('paper', {where: 'upstream:o/.github'})}))).not.toThrow(); + // A list field that is not a list is refused by name, not by a crash. + refuses({nodes: swap('paper', {needs: {}})}, /node paper: needs must be a list/); + refuses({nodes: swap('paper', {rivals: 'cheap'})}, /node paper: rivals must be a list/); + refuses({nodes: swap('paper', {size: 'toString'})}, /size must be one of S, M, L, XL/); + refuses({nodes: swap('paper', {size: 'constructor'})}, /size must be one of/); + refuses({raw: {nodes: BASE.map(n => JSON.stringify(n, null, 0)).join('\n') + '\n'}}, /not in JCS form/); + // The message names the line and a command that writes its JCS form. It never + // echoes the record: a log is no place for a file's content. + const loose = BASE.map((n, i) => (i === 1 ? JSON.stringify(n, null, 1).replaceAll('\n', '') : jcs(n))); + let msg = ''; + try { generate(fixture({raw: {nodes: loose.join('\n') + '\n'}})); } catch (e) { msg = e.message; } + expect(msg).toBe('docs/ultraplan/tree.jsonl: line 2 is not in JCS form (RFC 8785); run: sed -n 2p docs/ultraplan/tree.jsonl | bun scripts/ijson-jcs-cli.js canon'); + // The command does what the message says: it writes the line's JCS form. + const canon = Bun.spawnSync(['bun', path.join(ROOT, 'scripts/ijson-jcs-cli.js'), 'canon'], {stdin: Buffer.from(loose[1] + '\n')}); + expect(canon.exitCode).toBe(0); + expect(canon.stdout.toString()).toBe(jcs(BASE[1])); + // A lone surrogate survives JSON.parse and JSON.stringify alike; I-JSON refuses it. + const lone = jcs({...BASE[0], name: 'x'}).replace('"name":"x"', '"name":"\\ud800"'); + refuses({raw: {nodes: [lone, ...BASE.slice(1).map(n => jcs(n))].join('\n') + '\n'}}, /line 1 holds a lone surrogate/); + const pair = jcs({...BASE[0], name: 'x \u{1F600}'}); + expect(() => generate(fixture({raw: {nodes: [pair, ...BASE.slice(1).map(n => jcs(n))].join('\n') + '\n'}}))).not.toThrow(); + // I-JSON refuses Unicode noncharacters too: U+FDD0 to U+FDEF and the last two code points of each plane. + for (const nc of ['\uFFFE', '\uFDD0', '\u{1FFFF}', '\u{10FFFE}']) { + const line = jcs({...BASE[0], name: `x${nc}y`}); + refuses({raw: {nodes: [line, ...BASE.slice(1).map(n => jcs(n))].join('\n') + '\n'}}, /line 1 holds a lone surrogate or a Unicode noncharacter/); + } + const key = jcs({...BASE[0], value: {maths: 1}}).replace('"maths":', '"m\uFFFEaths":'); + refuses({raw: {nodes: [key, ...BASE.slice(1).map(n => jcs(n))].join('\n') + '\n'}}, /line 1 holds a lone surrogate or a Unicode noncharacter/); + // Each text is one line: a line break would let a text start a line of the page. + for (const cc of ['\n', '\r', '\t', '\u0000', '\u007f', '\u0085']) { + const line = jcs({...BASE[0], summary: `x${cc}|===`}); + refuses({raw: {nodes: [line, ...BASE.slice(1).map(n => jcs(n))].join('\n') + '\n'}}, /line 1 holds a control character; each text in the plan is one line/); + } + const ckey = jcs({...BASE[0], value: {maths: 1}}).replace('"maths":', '"m\\naths":'); + refuses({raw: {nodes: [ckey, ...BASE.slice(1).map(n => jcs(n))].join('\n') + '\n'}}, /line 1 holds a control character/); + // And the page shows each text as written: a browser breaks a line at U+2028 or + // U+2029, and HTML shows a run of spaces as one and drops a space at a cell's edge. + const faulty = (extra, re) => refuses({raw: {nodes: [jcs({...BASE[0], ...extra}), ...BASE.slice(1).map(n => jcs(n))].join('\n') + '\n'}}, re); + for (const sep of ['\u2028', '\u2029']) faulty({summary: `one${sep}two`}, /line 1 holds a line or paragraph separator \(U\+2028 or U\+2029\)/); + // A bidirectional control reorders what is shown, so text could look other than it is. + for (const c of ['\u061C', '\u200E', '\u200F', '\u202A', '\u202E', '\u2066', '\u2069']) + faulty({summary: `abc${c}def`}, /line 1 holds a bidirectional formatting control/); + // A malformed byte is refused, never read as U+FFFD. + refuses({raw: {nodes: Buffer.concat([Buffer.from(BASE.map(n => jcs(n)).join('\n').slice(0, 20)), Buffer.from([0xff]), Buffer.from(BASE.map(n => jcs(n)).join('\n').slice(20) + '\n')])}}, /docs\/ultraplan\/tree\.jsonl is not valid UTF-8/); + faulty({summary: 'two spaces'}, /line 1 holds a run of spaces; each text in the plan is one line of plain text, shown as written/); + faulty({counsel: {maths: 'a wide gap'}}, /line 1 holds a run of spaces/); + faulty({refs: [{at: 'a b', path: 'README.adoc'}]}, /line 1 holds a run of spaces/); + faulty({summary: ' leading'}, /line 1 holds a space at the start or end of a text/); + faulty({counsel: {maths: 'trailing '}}, /line 1 holds a space at the start or end of a text/); + // One space, a no-break space and a tab-free text are as written, and pass. + const fine = generate(fixture({nodes: swap('root', {summary: 'one space and a\u00a0no-break space'})}))[VIEW]; + expect(fine).toContain(plainOnPage('one space and a\u00a0no-break space')); +}); + +// Every text is plain (owner ruling 2026-11-25). A description-list marker, which +// Asciidoctor 2.0.26 reads as a list term wherever it stands in a line, is +// accepted like any other characters and shown as written. +test('a text holding list or block syntax is shown as written', () => { + for (const s of ['The lock:: and more', 'The lock;; and more', 'The lock::', ':: at the start', 'a ::: b', 'NOTE: x', '{nbsp} and {empty}']) { + const page = generate(fixture({nodes: swap('cheap', {summary: s, counsel: {maths: s}, name: s.slice(0, 80)})}))[VIEW]; + expect(page).toContain(plainOnPage(s)); + for (const line of page.split('\n')) expect(line.includes(s)).toBe(false); + } +}); + +test('a ref points at one place, and each ref in this repository is checked', () => { + const page = refs => generate(fixture({nodes: swap('paper', {refs})}))[VIEW]; + const refused = (refs, re) => refuses({nodes: swap('paper', {refs})}, re); + // A file or a directory, and a quote that occurs in its file exactly once. + const shown = page([{path: 'README.adoc'}, {path: 'docs/decisions'}, {at: '= Fixture', path: 'README.adoc'}, + {issue: 'metadatastician/standards#1705'}, + {at: '== 5. Status vocabulary', commit: 'a'.repeat(40), path: '3-practice/PROOF-POLICY.adoc', repo: 'metadatastician/standards'}]); + const P = plainOnPage; + expect(shown).toContain(`*See:* \`${P('README.adoc')}\`; \`${P('docs/decisions')}\`; \`${P('README.adoc')}\`, at \`${P('= Fixture')}\`; ` + + `https://github.com/metadatastician/standards/issues/1705[${P('metadatastician/standards#1705')}]; ` + + `https://github.com/metadatastician/standards/blob/${'a'.repeat(40)}/3-practice/PROOF-POLICY.adoc[${P('metadatastician/standards: 3-practice/PROOF-POLICY.adoc')}] at \`aaaaaaaaaaaa\`, at \`${P('== 5. Status vocabulary')}\``); + // A quote may hold any characters of one line, a backtick, plus or backslash among them. + const odd = 'a `tick` + back\\slash'; + const oddRoot = fixture({nodes: swap('paper', {refs: [{at: odd, path: 'notes.adoc'}]})}); + writeFileSync(path.join(oddRoot, 'notes.adoc'), `${odd}\n`); + track(oddRoot); + expect(generate(oddRoot)[VIEW]).toContain(`at \`${P(odd)}\``); + // A quote that is gone, or that occurs more than once, names no one place. + refused([{at: 'Gone', path: 'README.adoc'}], /node paper: ref README\.adoc holds "Gone" 0 times; a ref quotes a passage that occurs exactly once/); + refused([{at: 'at', path: 'docs/decisions/0004-claims-registry.adoc'}], /holds "at" [2-9] times/); + // Each part is checked: the path, what it names, the quote, the commit and the issue. + refused([{path: 'missing.adoc'}], /node paper: ref path missing\.adoc is not a file or directory that git tracks in the repository/); + refused([{at: 'x', path: 'docs/decisions'}], /ref path docs\/decisions is not a file that git tracks in the repository/); + for (const p of ['../outside', '/etc/passwd', 'a/./b', 'a b', '']) refused([{path: p}], /is not a repository path/); + for (const q of ['\u00a0padded', 'x'.repeat(161), '']) refused([{at: q, path: 'README.adoc'}], /is not a short quote/); + refused([{at: 'x', commit: '745fc74', path: 'a.adoc', repo: 'o/r'}], /ref commit "745fc74" is not a full commit id/); + refused([{commit: 'a'.repeat(40), path: 'a.adoc', repo: 'nobody'}], /ref repo "nobody" is not OWNER\/REPO/); + refused([{commit: 'a'.repeat(40), path: 'a.adoc'}], /ref repo undefined is not OWNER\/REPO/); + refused([{issue: 'standards#1705'}], /ref issue "standards#1705" is not OWNER\/REPO#N, alone/); + // A link made from "../.." would resolve to some other page of GitHub. + refused([{commit: 'a'.repeat(40), path: 'a.adoc', repo: '../..'}], /ref repo "\.\.\/\.\." is not OWNER\/REPO/); + refused([{issue: '../..#1'}], /ref issue "\.\.\/\.\.#1" is not OWNER\/REPO#N, alone/); + refused([{issue: 'o/r#1#2'}], /is not OWNER\/REPO#N, alone/); + refused([{issue: 'o/r#1', path: 'README.adoc'}], /is not OWNER\/REPO#N, alone/); + refused([{line: 92, path: 'README.adoc'}], /node paper: ref: unknown field "line"/); + refused(['README.adoc:46'], /node paper: ref: must be an object/); +}); + +test('a quote counts every place it occurs, overlaps included', () => { + const root = fixture({nodes: swap('paper', {refs: [{at: 'aaaa', path: 'notes.adoc'}]})}); + writeFileSync(path.join(root, 'notes.adoc'), 'aaaaa\n'); + track(root); + expect(() => generate(root)).toThrow(/ref notes\.adoc holds "aaaa" 2 times/); + writeFileSync(path.join(root, 'notes.adoc'), 'aaaa b\n'); + expect(() => generate(root)).not.toThrow(); +}); + +test('an evidence path follows the repository path rule, so it renders as written', () => { + for (const p of ['a`b.adoc', 'a b.adoc', 'docs/../README.adoc', './README.adoc', '/etc/passwd']) { + const root = fixture({nodes: swap('root', {evidence: [{path: p}]})}); + if (!p.startsWith('/') && !p.includes('..')) writeFileSync(path.join(root, p), 'x\n'); + expect(() => generate(root)).toThrow(/node root: evidence path .* is not a repository path/); + } +}); + +test('the sources are read only as regular files inside the repository', () => { + const outside = mkdtempSync(path.join(tmpdir(), 'ultraplan-out-')); + roots.push(outside); + writeFileSync(path.join(outside, 'tree.jsonl'), BASE.map(n => jcs(n) + '\n').join('')); + for (const [file, target] of [['expeditions.jsonl', '/dev/null'], ['tree.jsonl', path.join(outside, 'tree.jsonl')]]) { + const root = fixture(); + rmSync(path.join(root, 'docs/ultraplan', file)); + symlinkSync(target, path.join(root, 'docs/ultraplan', file)); + track(root); + expect(() => generate(root)).toThrow(new RegExp(`docs/ultraplan/${file.replace('.', '\\.')} is not a file that git tracks in the repository`)); + } +}); + +test('the views are plain files: a check never reads, nor a build writes, through a link', () => { + const root = fixture(); + const out = generate(root); + expect(staleViews(out, root)).toEqual([VIEW, SVG]); + writeViews(out, root); + expect(staleViews(out, root)).toEqual([]); + // A view linked to a file outside, even one holding the right text, is stale, + // and a build refuses to write through the link. + const outside = mkdtempSync(path.join(tmpdir(), 'ultraplan-out-')); + roots.push(outside); + writeFileSync(path.join(outside, 'page.adoc'), out[VIEW]); + rmSync(path.join(root, VIEW)); + symlinkSync(path.join(outside, 'page.adoc'), path.join(root, VIEW)); + expect(staleViews(out, root)).toEqual([VIEW]); + writeFileSync(path.join(outside, 'page.adoc'), 'untouched\n'); + expect(() => writeViews(out, root)).toThrow(/not written: docs\/ultraplan\/generated\/ultraplan\.adoc; a view is a plain file/); + expect(readFileSync(path.join(outside, 'page.adoc'), 'utf8')).toBe('untouched\n'); + // A link that leads nowhere yet is refused too: writing would create its target. + rmSync(path.join(root, VIEW)); + symlinkSync(path.join(outside, 'new.adoc'), path.join(root, VIEW)); + expect(() => writeViews(out, root)).toThrow(/not written/); + expect(existsSync(path.join(outside, 'new.adoc'))).toBe(false); + // A link to a file inside the repository is refused too, and that file is + // neither read as the view nor written over. + rmSync(path.join(root, VIEW)); + writeFileSync(path.join(root, 'copy.adoc'), out[VIEW]); + symlinkSync(path.join(root, 'copy.adoc'), path.join(root, VIEW)); + expect(staleViews(out, root)).toEqual([VIEW]); + expect(() => writeViews(out, root)).toThrow(/not written/); + expect(readFileSync(path.join(root, 'copy.adoc'), 'utf8')).toBe(out[VIEW]); + // So is a generated directory that is a link out of the repository. + const dirRoot = fixture(); + const away = mkdtempSync(path.join(tmpdir(), 'ultraplan-out-')); + roots.push(away); + symlinkSync(away, path.join(dirRoot, 'docs/ultraplan/generated')); + expect(() => writeViews(generate(dirRoot), dirRoot)).toThrow(/not written: docs\/ultraplan\/generated\/ultraplan\.adoc, docs\/ultraplan\/generated\/tree\.svg/); + expect(readdirSync(away)).toEqual([]); + // Views placed there, though plain files with the right text, are outside the + // repository, so the check counts them stale. + const dirOut = generate(dirRoot); + writeFileSync(path.join(away, 'ultraplan.adoc'), dirOut[VIEW]); + writeFileSync(path.join(away, 'tree.svg'), dirOut[SVG]); + expect(staleViews(dirOut, dirRoot)).toEqual([VIEW, SVG]); + // And a plan directory that leads out of the repository gets nothing made in it. + const planRoot = fixture(); + const planOut = generate(planRoot); + const elsewhere = mkdtempSync(path.join(tmpdir(), 'ultraplan-out-')); + roots.push(elsewhere); + rmSync(path.join(planRoot, 'docs/ultraplan'), {recursive: true}); + symlinkSync(elsewhere, path.join(planRoot, 'docs/ultraplan')); + expect(() => writeViews(planOut, planRoot)).toThrow(/docs\/ultraplan is not a directory in the repository/); + expect(readdirSync(elsewhere)).toEqual([]); +}); + +test('a ref cannot lead out of the repository', () => { + const outside = mkdtempSync(path.join(tmpdir(), 'ultraplan-out-')); + roots.push(outside); + writeFileSync(path.join(outside, 'secret.adoc'), 'only once\n'); + const root = fixture({nodes: swap('paper', {refs: [{at: 'only once', path: 'link.adoc'}]})}); + symlinkSync(path.join(outside, 'secret.adoc'), path.join(root, 'link.adoc')); + track(root); + expect(() => generate(root)).toThrow(/ref path link\.adoc is not a file that git tracks in the repository/); + const dirRoot = fixture({nodes: swap('paper', {refs: [{path: 'away'}]})}); + symlinkSync(outside, path.join(dirRoot, 'away')); + track(dirRoot); + expect(() => generate(dirRoot)).toThrow(/ref path away is not a file or directory that git tracks in the repository/); +}); + +// The answer does not hang on how the checkout is laid out: a linked worktree, +// where .git is a file, reads what a clone reads. And the generator runs only at +// the top of a checkout, where git can say what it tracks. +test('a linked worktree reads what a clone reads, and only a checkout is read', () => { + const main = fixture(); + git(main, 'commit', '-q', '-m', 'fixture'); + const linked = path.join(mkdtempSync(path.join(tmpdir(), 'ultraplan-wt-')), 'linked'); + roots.push(path.dirname(linked)); + git(main, 'worktree', 'add', '-q', linked); + expect(generate(linked)[VIEW]).toBe(generate(main)[VIEW]); + for (const root of [main, linked]) { + rmSync(path.join(root, 'docs/ultraplan/tree.jsonl')); + writeFileSync(path.join(root, 'docs/ultraplan/tree.jsonl'), swap('root', {evidence: [{path: '.git'}]}).map(n => jcs(n) + '\n').join('')); + expect(() => generate(root)).toThrow(/evidence path \.git is not a file that git tracks in the repository/); + } + // A directory that is not a checkout, or that is not the top of one, is refused. + const bare = mkdtempSync(path.join(tmpdir(), 'ultraplan-nogit-')); + roots.push(bare); + expect(() => context(bare).isFile('x')).toThrow(/is not the top of a git checkout/); + expect(() => generate(path.join(main, 'docs'))).toThrow(/is not the top of a git checkout/); +}); + +test('a summary that looks like block syntax is text on the page', () => { + const base = generate(fixture())[VIEW].split('\n'); + const bare = (lines, s) => lines.filter(l => l === s).length; + for (const s of ['|===', 'image::missing.svg[]', '// a comment', 'include::x.adoc[]', '== heading', '* item']) { + const page = generate(fixture({nodes: swap('cheap', {summary: s})}))[VIEW].split('\n'); + expect(page).toContain(plainOnPage(s)); + expect(bare(page, s)).toBe(bare(base, s)); // the summary adds no line of its own syntax + } + for (const n of BASE) expect(base).toContain(plainOnPage(n.summary)); +}); + +// Every rule in the generator's rule tables has a witness: a change to the sound +// fixture that breaks the rule and is refused with its message. A rule with no +// witness fails this test, so no rule can be vacuous, and none can be added +// without a test. +test('every rule has a witness', () => { + const ctx = context(fixture()); + const on = (rows, id, extra) => rows.map(r => r.id === id ? strip({...r, ...extra}) : r); + const A = (id, extra) => ({advisors: on(ADVISORS, id, extra)}); + const N = (id, extra) => ({nodes: on(BASE, id, extra)}); + const T = extra => ({expeditions: [strip({id: 'X-001', what: 'A trip', why: 'Because', size: 'S', date: '2026-11-24', status: 'out', ...extra})]}); + const witnesses = [ + A('maths', {name: ''}), A('maths', {glyph: undefined}), A('maths', {asks: ' padded'}), + A('maths', {reads: 'poetry'}), A('me', {private: false}), A('maths', {private: true}), + A('contrarian', {reads: 'maths'}), A('engineering', {reads: undefined}), + N('paper', {name: 'x'.repeat(81)}), N('paper', {glyph: ''}), N('paper', {track: 'poetry'}), + N('paper', {kind: 'novel'}), N('paper', {status: 'finished'}), N('paper', {size: 'XXL'}), + N('paper', {summary: undefined}), N('paper', {needs: 'theorem'}), N('paper', {rivals: {}}), + N('root', {evidence: 'README.adoc'}), N('paper', {refs: 'see'}), N('paper', {where: ['estate:o/r']}), + N('paper', {owner_value: 'low'}), N('paper', {status: 'blocked'}), N('paper', {blocked_by: 'the owner'}), + T({what: ''}), T({why: undefined}), T({size: 'toString'}), T({date: '2026-02-30'}), T({status: 'lost'}), + T({status: 'grafted', graft: 'ghost'}), T({graft: 'paper'}), T({status: 'archived'}), T({lesson: 'It taught.'}), + ]; + // Within a table each message names one rule, so (table, message) is the rule's identity. + for (const rules of Object.values(RULES)) expect(new Set(rules.map(([, m]) => m)).size).toBe(rules.length); + const seen = new Set(); + for (const w of witnesses) { + let refusal = ''; + try { validate({advisors: ADVISORS, nodes: BASE, expeditions: [], ...w}, ctx); } catch (e) { refusal = e.message; } + expect(refusal).not.toBe(''); + for (const line of refusal.split('\n')) { + const m = /^(advisor|node|expedition) [^\s:]+: (.*)$/.exec(line); + if (m) seen.add(`${m[1]}: ${m[2]}`); + } + } + const unwitnessed = Object.entries(RULES).flatMap(([kind, rules]) => rules.map(([, m]) => `${kind}: ${m}`).filter(id => !seen.has(id))); + expect(unwitnessed).toEqual([]); +}); + +test('the me advisor names no public pick, and lists the owner\'s tags unranked', () => { + // theorem unlocks more and cheap carries the higher maths mark: neither orders the list. + const nodes = swap('cheap', {owner_value: 'high', value: {maths: 3}}, swap('theorem', {value: {maths: 1}})); + const out = generate(fixture({nodes})); + expect(out.derived.picks.get('me')).toBe(null); + expect(out.derived.ownerTagged.map(n => n.id)).toEqual(['cheap', 'theorem']); + expect(out[VIEW]).toContain('Tagged on the frontier, in id order: xref:cheap[🔷 cheap], xref:theorem[🔷 theorem].'); + const none = generate(fixture({nodes: swap('theorem', {owner_value: undefined})}))[VIEW]; + expect(none).toContain('_No public pick:_ the owner chooses in a private panel of their own. Nothing tagged is on the frontier.'); +}); + +test('when every active slot is taken, the frontier is ready but cannot start', () => { + const open = generate(fixture()); + expect(open.derived.slots).toBe(ACTIVE_LIMIT); + expect(open[VIEW]).toContain('can be started now.'); + expect(open[VIEW]).toContain('so any of them can start today.'); + expect(open[VIEW]).not.toContain('active slots are full'); + expect(open[SVG]).toContain('gold border: start it now'); + // theorem and cheap are ready; with a third started node, every slot is taken and spare waits. + const nodes = [...swap('cheap', {status: 'active'}, swap('theorem', {status: 'active'})), + node('extra', {needs: ['root'], status: 'active'}), node('spare', {needs: ['root']})]; + const full = generate(fixture({nodes})); + expect(full.derived.slots).toBe(0); + expect(full.derived.frontier.map(n => n.id)).toEqual(['spare']); + expect(full[VIEW]).toContain(`1 are ready, but all ${ACTIVE_LIMIT} active slots are full.`); + expect(full[VIEW]).toContain(`*All ${ACTIVE_LIMIT} active slots are full.* These nodes are ready`); + expect(full[VIEW]).toContain('so each can start once an active slot is free.'); + expect(full[VIEW]).not.toContain('can start today'); + expect(full[VIEW]).not.toContain('can be started now'); + expect(full[VIEW]).toContain('A gold border marks a node\nthat is ready, once an active slot is free.'); + expect(full[SVG]).toContain('gold border: ready, once an active slot is free'); +}); + +test('ids are slugs and unique, and counsel comes from the council', () => { + refuses({nodes: swap('paper', {id: 'Paper X'})}, /id must be a lowercase slug/); + refuses({nodes: swap('paper', {id: '13-week'})}, /node 13-week: id must be a lowercase slug that begins with a letter/); + refuses({advisors: [...ADVISORS, {id: '2nd', name: 'Second', glyph: '2', asks: 'Again?', reads: 'maths'}]}, /advisor id "2nd" is missing, not a slug, or repeated/); + refuses({nodes: [...BASE, BASE[4]]}, /node paper: repeated id/); + refuses({advisors: [...ADVISORS, ADVISORS[0]]}, /advisor id "maths" is missing, not a slug, or repeated/); + refuses({nodes: swap('paper', {rivals: ['paper']})}, /node paper: rivals names itself/); + refuses({nodes: swap('theorem', {counsel: {ghost: 'Hm.'}})}, /counsel from unknown advisor ghost/); + refuses({nodes: swap('theorem', {counsel: {maths: ''}})}, /counsel\.maths must be a short text/); +}); + +test('return tickets are grafted or archived honestly', () => { + const x = {id: 'X-001', what: 'A trip', why: 'Because', size: 'S', date: '2026-11-24', status: 'out'}; + expect(generate(fixture({expeditions: [x]}))[VIEW]).toContain(`|${plainOnPage('X-001')} |${plainOnPage('2026-11-24')} |S |A trip |Because |🎒 out`); + // A ticket's texts sit in table cells, so a "|" in one would end its cell: each is escaped. + const odd = {...x, what: 'Try | this: *now*', why: 'Since [a] = b', status: 'archived', lesson: 'It taught | much'}; + expect(generate(fixture({expeditions: [odd]}))[VIEW]).toContain( + `|${plainOnPage(odd.what)} |${plainOnPage(odd.why)} |📦 archived: ${plainOnPage(odd.lesson)}`); + refuses({expeditions: [{...x, status: 'grafted', graft: 'ghost'}]}, /names the node it became/); + refuses({expeditions: [{...x, status: 'archived'}]}, /records what it taught/); + refuses({expeditions: [x, {...x}]}, /id is X-NNN and unique/); + refuses({expeditions: [{...x, date: '2026-02-30'}]}, /date is a real calendar date/); + refuses({expeditions: [{...x, date: '2026-99-99'}]}, /date is a real calendar date/); + expect(() => generate(fixture({expeditions: [{...x, date: '2028-02-29'}]}))).not.toThrow(); +}); + +test('the evidence parsers read the real registry view and ADRs', () => { + const ctx = context(ROOT); + expect(registryGrade(ctx.registry, 'hyperpolymath/mathesis#THY-1')).toMatch(/^PWG-/); + expect(adrAccepted(ctx.read(ctx.adrFiles('0004')[0]))).toBe(true); + expect(adrAccepted(ctx.read(ctx.adrFiles('0005')[0]))).toBe(false); + for (const n of ['0001', '0002', '0003']) expect(adrAccepted(ctx.read(ctx.adrFiles(n)[0]))).toBe(true); +}); + +// ADR evidence counts only when the header states ACCEPTED and the Status +// section agrees (owner ruling 2026-11-25); each failure says which part fails. +test('ADR evidence needs its header and its Status section to agree', () => { + const root = fixture({nodes: swap('tool', {evidence: [{adr: '0007'}]})}); + const put = s => { writeFileSync(path.join(root, 'docs/decisions/0007-x.adoc'), s); track(root); }; + put('= ADR\n\n=== Status\n\nAccepted\n'); + expect(() => generate(root)).toThrow(/node tool: ADR 0007 states no readable status in its header/); + put('= ADR\n:status: ACCEPTED\n\n=== Status\n\nProposed.\n'); + expect(() => generate(root)).toThrow(/node tool: ADR 0007's header says ACCEPTED but its Status section says PROPOSED/); + put('= ADR\n:status: ACCEPTED\n\nNo section.\n'); + expect(() => generate(root)).toThrow(/its Status section says nothing readable/); + put('= ADR\n:status: ACCEPTED\n\n=== Status\n\nAccepted\n'); + expect(() => generate(root)).not.toThrow(); +}); + +test('the committed views match the committed data', () => { + const out = generate(ROOT); + expect(readFileSync(path.join(ROOT, VIEW), 'utf8')).toBe(out[VIEW]); + expect(readFileSync(path.join(ROOT, SVG), 'utf8')).toBe(out[SVG]); +});