diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index f206f482..4f94b8ce 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -100,8 +100,10 @@ These were needed to make the pieces fit. Each is open to change by the lanes it
6. **The web bundle** is `index.json`, `findings.json`, `decisions.json` and `map.json`.
Only the finding record is fixed by the spec; the rest is a first draft for the report
and web lanes to settle. Code slices for the code pane are not in it yet.
-7. **Web navigation** lists the six screens of spec.md §10.2. The prototype has five tabs;
- the web lane decides which screens are tabs and which open from a finding.
+7. **Web navigation** has seven tabs per repository: Overview, Decisions, Findings, Map,
+ Change, Trust and Size. A finding opens on its own page from the Findings tab, and the
+ Map shows a finding or its simulated fix from a link on that page. The routes are in
+ `web/src/App.tsx` and the screens in `web/src/routes/`.
8. **Python 3.12**, pinned in `.python-version`, because every dependency has ready-built
packages for it.
diff --git a/README.md b/README.md
index fab9850f..cfd01e65 100644
--- a/README.md
+++ b/README.md
@@ -20,12 +20,12 @@ writes prose on top of those facts, and the app marks every AI sentence as AI.
| Stage 3, `model`: the map of modules per snapshot | Works on all three repositories |
| Stage 5, `analyze`: decisions, finding types, before and after | Works on all three repositories |
| Stage 7, `report`: ranking, `findings.json`, the web bundle | Works on all three repositories |
-| Web app: Decisions, Structure grid, Close-up, Code, Before and after, Size, Report | Works on the three bundles in `web/public/bundles/` |
+| Web app: the tabs Report, Findings (with finding detail), Map, Before and after, Approach, and the Decisions and Size screens | Works on the three bundles and the two synthetic fixtures in `web/public/bundles/`; see [Web app](#web-app) |
| Stage 6, `judge`: AI text for the shown findings | Works with `LLM_API_KEY` set; answers are cached in the run folder, so a re-run makes no call |
| `decisions propose`: rules proposed from written decision documents | Works with `LLM_API_KEY` set; writes `proposals.yaml` for review, and the reviewed rules are in `rules/` |
| `check ..
`: decisions a change breaks | Works; lists each broken decision with file and line, and exits 1 when there is one |
| Stability table (spec.md §11.3) | Measured on all three repositories: `make robustness REPO=` after `report` measures it and rebuilds the report |
-| Emerging-hotspots list (spec.md §12.2) | Filled on all three repositories; the Report screen lists up to 25 files, highest z first (25 on Artemis, 18 on Shopware, 1 on Graylog) |
+| Emerging-hotspots list (spec.md §12.2) | Filled on all three repositories; the Change screen lists up to 25 files, highest z first (25 on Artemis, 18 on Shopware, 1 on Graylog) |
The results in this repository include AI text. On each repository `judge` judged the 25
highest-ranked findings of four types (broken rule, cheap loop, foundation depending on
@@ -127,7 +127,7 @@ does not depend on test code". A decision that is written but not checkable by m
## Token usage per analysis
The ledger of every AI call the gateway answered for these three runs, summed from
-`results//usage.json`. The Report screen shows the same rows. Job B writes the claim
+`results//usage.json`. The Trust screen shows the same rows. Job B writes the claim
and fix for the 25 judged findings (three votes per finding, and one more call for a vote
whose answer fails a check that allows a retry); job C writes a two-sentence description
of each module.
@@ -155,14 +155,14 @@ of each module.
- A re-run of `judge` answers from the cache in the run folder (`judgements/cache/`) and
makes no call; the ledger counts only calls the gateway answered, so it does not grow.
The stability step makes no AI call.
-- With AI text switched off (the "AI text" switch in the app, kept in the address as
- `ai=off`), every finding shows the fixed sentence built from the facts. Without `judge`
- the report is complete with those sentences (spec.md §8.7).
+- A finding without an AI answer that passed every check shows the fixed sentence built
+ from the facts, marked as computed. Without `judge` the report is complete with those
+ sentences (spec.md §8.7).
## Stability of the ranking
`make robustness REPO=` runs the five tests of spec.md §11.3 and writes
-`robustness.json`; the Report screen shows the same rows. Each cell says how many of the
+`robustness.json`; the Trust screen shows the same rows. Each cell says how many of the
top 5 and of the top 10 are still in the top 5 and top 10 under the test.
| Test | Artemis top 5 | Artemis top 10 | Shopware top 5 | Shopware top 10 | Graylog top 5 | Graylog top 10 |
@@ -185,6 +185,50 @@ top 5 and of the top 10 are still in the top 5 and top 10 under the test.
- The step took 12.2 minutes on Artemis, 14.1 on Shopware and 10.4 on Graylog on a
10-core machine while other runs shared it.
+## Web app
+
+The web app shows one report per repository from the files in `web/public/bundles/`. It
+loads static files only: it needs no server of its own and never calls an AI model. Every
+AI sentence it shows was written by `judge` and stored in the bundle, and carries an "AI"
+badge; everything else is marked as computed.
+
+```sh
+make web # development server at http://localhost:5173
+cd web && npm run build && npm run preview # build the static app into web/dist and serve it
+```
+
+`web/dist` works offline and from any static host, opened at its `index.html`: every view
+lives after the `#` of the address. `make bundle REPO=` copies a run's bundle into
+`web/public/bundles//` and lists it in `web/public/bundles/index.json`; build again
+to include it in `web/dist`.
+
+| Address (after `#`) | Screen |
+|---|---|
+| `/` | every repository, with the finding to fix first and its decisions by status; how the pipeline works |
+| `/r/` | Report: verdict, yardsticks, decisions, the simulated fix batch, the top findings |
+| `/r//decisions` | Decisions, reached from Report: each checked decision with its conformance over time, and the written ones that cannot be checked |
+| `/r//findings` | Findings: the ranked list and how the ranking is worked out |
+| `/r//findings/` | one finding: the reading of the code, the cited lines, the simulation, the priority |
+| `/r//map` | Map: the module grid. `?view=before\|now\|after`, `?cell=,`, `?finding=`, `?fix=` |
+| `/r//change` | Before and after: before and after the compared date, structural events, hotspots |
+| `/r//trust` | Approach: coverage, limits, stability of the ranking, AI calls and their cost |
+| `/r//size` | Size, reached from Map: lines by module and file, and where the new lines landed |
+
+Some values show "not measured in this run" because the bundle does not carry them yet:
+
+- the rules hash;
+- the evidence behind the AI adoption date;
+- the authority of a decision that no finding cites;
+- the share of commits with an AI marker;
+- the expected and found labels of module links;
+- AI-marked changes against changes with no AI signal, by size band;
+- agreement of the links, and of the file to module assignment, with the comparison
+ linkers;
+- the share of silent misses;
+- the after-fixes grid recoloured for the real repositories: the simulation counts links
+ between modules on a different basis from the grid, so its changes are listed but not
+ drawn on it.
+
## Limits
- Shopware and Graylog have no measured habit: no folder role met the settings for one
@@ -194,7 +238,7 @@ top 5 and of the top 10 are still in the top 5 and top 10 under the test.
answers. It does not make a new call, so it does not show how the AI text would change
on a run with the cache off.
- A simulated fix that leaves its target link on the map is shown as "Simulated: the link
- remains" (on the grid, "Fix simulated: the link remains"), not as checked: 29 of the 50
+ remains" (on the finding page, "Fix simulated: the link remains."), not as checked: 29 of the 50
simulated fixes on Artemis, 1 of 19 on Shopware and 22 of 50 on Graylog.
- The simulation works on link counts between modules, and a move moves the whole
declaring file. Of the 119 simulated fixes, 14 are fixes that remove a link (Artemis 8,
@@ -215,7 +259,7 @@ top 5 and of the top 10 are still in the top 5 and top 10 under the test.
Links made while the program runs (computed paths, settings files, reflection) are not
seen.
- Thresholds and ranking weights are judgements, kept in `src/codexray/settings/`.
-- Every run writes its own limits into `manifest.json` and the Report screen.
+- Every run writes its own limits into `manifest.json`; the Trust screen lists them.
## Layout
@@ -236,7 +280,14 @@ schemas/ JSON Schema generated from contracts.py
rules/ reviewed decisions per analysed repository
repos.yaml the three repositories and their pinned commits
results/ findings, manifest, decisions, AI usage and stability of each repository's run
-web/ the static web app (React, Vite, TypeScript)
+web/ the static web app (React, Vite, TypeScript, Tailwind)
+ src/App.tsx the routes
+ src/routes/ one file per screen: Landing, Overview, Decisions, Findings,
+ FindingDetail, MapPage, Change, Trust, Size
+ src/components/cx/ shared parts: header, map grid, close-up, code pane, badges
+ src/cx/ the shapes the screens read, addresses, labels
+ src/data/ the bundle loader and the adapter from bundle to screens
+ scripts/ contract types and the stored map layouts, run at bundle-build time
public/bundles/ the bundles it loads: the three repositories and two synthetic fixtures
probes/ measurement scripts behind the spec's numbers; kept as measured
docs/research/ the team's research documents and starter kits
diff --git a/web/index.html b/web/index.html
index 9b49293d..03aa3226 100644
--- a/web/index.html
+++ b/web/index.html
@@ -3,6 +3,11 @@
+
+
CodeXray
diff --git a/web/package-lock.json b/web/package-lock.json
index afe18404..c12fe143 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -8,23 +8,21 @@
"name": "codexray-web",
"version": "0.1.0",
"dependencies": {
- "@fontsource-variable/hanken-grotesk": "^5.3.0",
+ "@fontsource-variable/instrument-sans": "^5.3.0",
"@fontsource-variable/jetbrains-mono": "^5.3.0",
- "cytoscape": "^3.35.0",
"d3-hierarchy": "^3.1.3",
- "d3-scale": "^4.0.3",
"d3-scale-chromatic": "^3.1.1",
"elkjs": "^0.12.2",
+ "lucide-react": "^1.83.0",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-router": "^8.5.3",
"shiki": "^4.6.0"
},
"devDependencies": {
+ "@tailwindcss/vite": "^4.3.5",
"@testing-library/react": "^16.3.3",
- "@types/cytoscape": "^3.21.9",
"@types/d3-hierarchy": "^3.1.7",
- "@types/d3-scale": "^4.0.9",
"@types/d3-scale-chromatic": "^3.1.0",
"@types/node": "^26.6.11",
"@types/react": "^19.3.3",
@@ -33,6 +31,7 @@
"jsdom": "^29.1.1",
"json-schema-to-typescript": "^16.0.0",
"prettier": "^3.10.1",
+ "tailwindcss": "^4.3.5",
"typescript": "^7.0.2",
"vite": "^8.4.0",
"vitest": "^4.1.12"
@@ -345,10 +344,10 @@
}
}
},
- "node_modules/@fontsource-variable/hanken-grotesk": {
+ "node_modules/@fontsource-variable/instrument-sans": {
"version": "5.3.0",
- "resolved": "https://registry.npmjs.org/@fontsource-variable/hanken-grotesk/-/hanken-grotesk-5.3.0.tgz",
- "integrity": "sha512-DOd0FqL+3cH2dfNy0JtSq9tUfxBz5mLmHMjTU0DOr3E9Zo6wxuatCl53DIPNrSPgCsnuKyM739BTIG5glCLirw==",
+ "resolved": "https://registry.npmjs.org/@fontsource-variable/instrument-sans/-/instrument-sans-5.3.0.tgz",
+ "integrity": "sha512-u4gKbDBTNFGkg997tfQn3eHOhHuquWUFTRT/rwzuKtrxX5P2ekfs2x+LgBPP4P32+cC+vUwF1Cr+IdRoPQbrGw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
@@ -363,6 +362,38 @@
"url": "https://github.com/sponsors/ayuhito"
}
},
+ "node_modules/@jridgewell/gen-mapping": {
+ "version": "0.3.13",
+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.0",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/remapping": {
+ "version": "2.3.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
+ "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/gen-mapping": "^0.3.5",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz",
+ "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
@@ -370,6 +401,17 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.31",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
"node_modules/@jsdevtools/ono": {
"version": "7.1.3",
"resolved": "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz",
@@ -779,6 +821,354 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@tailwindcss/node": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.5.tgz",
+ "integrity": "sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/remapping": "^2.3.5",
+ "enhanced-resolve": "^5.24.5",
+ "jiti": "^2.7.0",
+ "lightningcss": "1.33.0",
+ "magic-string": "^1.1.0",
+ "source-map-js": "^1.2.1",
+ "tailwindcss": "4.3.5"
+ }
+ },
+ "node_modules/@tailwindcss/node/node_modules/magic-string": {
+ "version": "1.4.5",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz",
+ "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.6.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.5.tgz",
+ "integrity": "sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 20"
+ },
+ "optionalDependencies": {
+ "@tailwindcss/oxide-android-arm64": "4.3.5",
+ "@tailwindcss/oxide-darwin-arm64": "4.3.5",
+ "@tailwindcss/oxide-darwin-x64": "4.3.5",
+ "@tailwindcss/oxide-freebsd-x64": "4.3.5",
+ "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5",
+ "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5",
+ "@tailwindcss/oxide-linux-arm64-musl": "4.3.5",
+ "@tailwindcss/oxide-linux-x64-gnu": "4.3.5",
+ "@tailwindcss/oxide-linux-x64-musl": "4.3.5",
+ "@tailwindcss/oxide-wasm32-wasi": "4.3.5",
+ "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5",
+ "@tailwindcss/oxide-win32-x64-msvc": "4.3.5"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-android-arm64": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.5.tgz",
+ "integrity": "sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-darwin-arm64": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.5.tgz",
+ "integrity": "sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-darwin-x64": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.5.tgz",
+ "integrity": "sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-freebsd-x64": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.5.tgz",
+ "integrity": "sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.5.tgz",
+ "integrity": "sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-linux-arm64-gnu": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.5.tgz",
+ "integrity": "sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-linux-arm64-musl": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.5.tgz",
+ "integrity": "sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-linux-x64-gnu": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.5.tgz",
+ "integrity": "sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-linux-x64-musl": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.5.tgz",
+ "integrity": "sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.5.tgz",
+ "integrity": "sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw==",
+ "bundleDependencies": [
+ "@napi-rs/wasm-runtime",
+ "@emnapi/core",
+ "@emnapi/runtime",
+ "@tybys/wasm-util",
+ "@emnapi/wasi-threads",
+ "tslib"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/core": "^1.11.3",
+ "@emnapi/runtime": "^1.11.3",
+ "@emnapi/wasi-threads": "^1.2.3",
+ "@napi-rs/wasm-runtime": "^1.2.2",
+ "@tybys/wasm-util": "^0.10.3",
+ "tslib": "^2.8.1"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=23.5.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": {
+ "version": "1.11.3",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/wasi-threads": "1.2.3",
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": {
+ "version": "1.11.3",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
+ "version": "1.2.3",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": {
+ "version": "1.2.2",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@tybys/wasm-util": "^0.10.3"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=23.5.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ },
+ "peerDependencies": {
+ "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3",
+ "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": {
+ "version": "0.10.3",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": {
+ "version": "2.8.1",
+ "dev": true,
+ "inBundle": true,
+ "license": "0BSD",
+ "optional": true
+ },
+ "node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.5.tgz",
+ "integrity": "sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-win32-x64-msvc": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.5.tgz",
+ "integrity": "sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@tailwindcss/vite": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.3.5.tgz",
+ "integrity": "sha512-BCNiY0a1ZjdOHVqw7kyb7U72BwfMF3dfUuN+tQsLWky/J5JOI/r7abibglXfygrZhVO/3u3V+E25kkKTeMkXaQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@tailwindcss/node": "4.3.5",
+ "@tailwindcss/oxide": "4.3.5",
+ "tailwindcss": "4.3.5"
+ },
+ "peerDependencies": {
+ "vite": "^5.2.0 || ^6 || ^7 || ^8"
+ }
+ },
"node_modules/@testing-library/dom": {
"version": "10.4.2",
"resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz",
@@ -847,13 +1237,6 @@
"assertion-error": "^2.0.1"
}
},
- "node_modules/@types/cytoscape": {
- "version": "3.21.9",
- "resolved": "https://registry.npmjs.org/@types/cytoscape/-/cytoscape-3.21.9.tgz",
- "integrity": "sha512-JyrG4tllI6jvuISPjHK9j2Xv/LTbnLekLke5otGStjFluIyA9JjgnvgZrSBsp8cEDpiTjwgZUZwpPv8TSBcoLw==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/@types/d3-hierarchy": {
"version": "3.1.7",
"resolved": "https://registry.npmjs.org/@types/d3-hierarchy/-/d3-hierarchy-3.1.7.tgz",
@@ -861,16 +1244,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/@types/d3-scale": {
- "version": "4.0.9",
- "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
- "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/d3-time": "*"
- }
- },
"node_modules/@types/d3-scale-chromatic": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@types/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",
@@ -878,13 +1251,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/@types/d3-time": {
- "version": "3.0.4",
- "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",
- "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/@types/deep-eql": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
@@ -1613,15 +1979,6 @@
"devOptional": true,
"license": "MIT"
},
- "node_modules/cytoscape": {
- "version": "3.35.0",
- "resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.35.0.tgz",
- "integrity": "sha512-sMvBIXiGMnhkCaWz2R06FwF/27MNlS+Tqvi17foO9UhnUg3XGZccKjxsvEqQFAQYMSSZmN5SxYzUYlQ0DOJJ3g==",
- "license": "MIT",
- "engines": {
- "node": ">=0.10"
- }
- },
"node_modules/d3-array": {
"version": "3.2.5",
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.5.tgz",
@@ -1794,6 +2151,20 @@
"integrity": "sha512-YC42gyUwsOeKWB/EVTr1abEnNhDEoz+qeLshCBufNW0qrJPcxk+/s1lih4Sbke4BOgjficJGvJ2D9jL/QTC/ew==",
"license": "EPL-2.0 OR GPL-3.0-or-later"
},
+ "node_modules/enhanced-resolve": {
+ "version": "5.27.0",
+ "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.27.0.tgz",
+ "integrity": "sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "graceful-fs": "^4.2.4",
+ "tapable": "^2.3.3"
+ },
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
"node_modules/entities": {
"version": "9.0.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz",
@@ -1867,6 +2238,13 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
+ "node_modules/graceful-fs": {
+ "version": "4.2.12",
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz",
+ "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==",
+ "dev": true,
+ "license": "BlueOak-1.0.0"
+ },
"node_modules/hast-util-to-html": {
"version": "9.0.7",
"resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.7.tgz",
@@ -1942,6 +2320,16 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/jiti": {
+ "version": "2.7.0",
+ "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
+ "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "jiti": "lib/jiti-cli.mjs"
+ }
+ },
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@@ -2315,6 +2703,21 @@
"node": "20 || >=22"
}
},
+ "node_modules/lucide-react": {
+ "version": "1.83.0",
+ "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.83.0.tgz",
+ "integrity": "sha512-bYosQeQphbbNtdWT4DvY1/wlen2CcsZEQI/pMykcQ8twiu+T7m7cY7s8hOTJiMEAs3nUxCkeCxTe4ohczS5jhA==",
+ "license": "ISC",
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
"node_modules/lz-string": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz",
@@ -2880,6 +3283,27 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/tailwindcss": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.5.tgz",
+ "integrity": "sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tapable": {
+ "version": "2.3.4",
+ "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.4.tgz",
+ "integrity": "sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/webpack"
+ }
+ },
"node_modules/tinybench": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
diff --git a/web/package.json b/web/package.json
index 2fa8dfd5..a13aac8a 100644
--- a/web/package.json
+++ b/web/package.json
@@ -14,23 +14,21 @@
"contracts:check": "node scripts/gen-contracts.mjs --check"
},
"dependencies": {
- "@fontsource-variable/hanken-grotesk": "^5.3.0",
+ "@fontsource-variable/instrument-sans": "^5.3.0",
"@fontsource-variable/jetbrains-mono": "^5.3.0",
- "cytoscape": "^3.35.0",
"d3-hierarchy": "^3.1.3",
- "d3-scale": "^4.0.3",
"d3-scale-chromatic": "^3.1.1",
"elkjs": "^0.12.2",
+ "lucide-react": "^1.83.0",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-router": "^8.5.3",
"shiki": "^4.6.0"
},
"devDependencies": {
+ "@tailwindcss/vite": "^4.3.5",
"@testing-library/react": "^16.3.3",
- "@types/cytoscape": "^3.21.9",
"@types/d3-hierarchy": "^3.1.7",
- "@types/d3-scale": "^4.0.9",
"@types/d3-scale-chromatic": "^3.1.0",
"@types/node": "^26.6.11",
"@types/react": "^19.3.3",
@@ -39,6 +37,7 @@
"jsdom": "^29.1.1",
"json-schema-to-typescript": "^16.0.0",
"prettier": "^3.10.1",
+ "tailwindcss": "^4.3.5",
"typescript": "^7.0.2",
"vite": "^8.4.0",
"vitest": "^4.1.12"
diff --git a/web/public/bundles/artemis/journeys.json b/web/public/bundles/artemis/journeys.json
new file mode 100644
index 00000000..757e076f
--- /dev/null
+++ b/web/public/bundles/artemis/journeys.json
@@ -0,0 +1,769 @@
+{
+ "lanes": [
+ "Browser",
+ "Web entry",
+ "Feature services",
+ "Course core",
+ "Queues & workers"
+ ],
+ "journeys": [
+ {
+ "id": "push",
+ "name": "A student pushes code for a programming exercise",
+ "summary": "8 stops · 4 modules · 1 queue · ends with a live score in the browser",
+ "stops": [
+ {
+ "lane": 0,
+ "module": "client",
+ "label": "git push",
+ "caption": "The student pushes their solution with git. Artemis hosts the repository itself, so the push goes straight to the server.",
+ "file": "git client → /git/ARTEMIS101/artemis101-alice.git",
+ "method": "HTTP POST · git-receive-pack",
+ "via": null,
+ "findingRank": null,
+ "payload": {
+ "type": "GitPush",
+ "definedIn": "git smart HTTP",
+ "fields": [
+ {
+ "key": "ref",
+ "value": "\"refs/heads/main\""
+ },
+ {
+ "key": "commit",
+ "value": "\"8f2c1e4\""
+ },
+ {
+ "key": "changedFiles",
+ "value": "3"
+ }
+ ]
+ }
+ },
+ {
+ "lane": 1,
+ "module": "programming",
+ "label": "accept push",
+ "caption": "The git servlet checks that the student is allowed to push and finds which participation the repository belongs to.",
+ "file": "programming/service/localvc/LocalVCServletService.java:412",
+ "method": "processNewPush(commitHash, repository)",
+ "via": {
+ "kind": "call",
+ "label": "HTTP request"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "PushContext",
+ "definedIn": "LocalVCServletService.java",
+ "fields": [
+ {
+ "key": "commit",
+ "value": "\"8f2c1e4\""
+ },
+ {
+ "key": "participationId",
+ "value": "48213"
+ },
+ {
+ "key": "exerciseId",
+ "value": "3071"
+ },
+ {
+ "key": "branch",
+ "value": "\"main\""
+ }
+ ]
+ }
+ },
+ {
+ "lane": 2,
+ "module": "programming",
+ "label": "save submission",
+ "caption": "A submission record is saved for this commit, so the build result can be attached to it later.",
+ "file": "programming/service/ProgrammingSubmissionService.java:118",
+ "method": "processNewProgrammingSubmission(participation, commit)",
+ "via": {
+ "kind": "call",
+ "label": "method call"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "ProgrammingSubmission",
+ "definedIn": "programming/domain/ProgrammingSubmission.java",
+ "fields": [
+ {
+ "key": "id",
+ "value": "902114"
+ },
+ {
+ "key": "commitHash",
+ "value": "\"8f2c1e4\""
+ },
+ {
+ "key": "participationId",
+ "value": "48213"
+ },
+ {
+ "key": "type",
+ "value": "\"MANUAL\""
+ },
+ {
+ "key": "submissionDate",
+ "value": "\"2026-11-27T14:02:11Z\""
+ }
+ ]
+ }
+ },
+ {
+ "lane": 4,
+ "module": "programming",
+ "label": "queue build",
+ "caption": "Instead of building right away, the job goes onto a shared queue so that any free build agent can pick it up.",
+ "file": "programming/service/localci/LocalCITriggerService.java:96",
+ "method": "triggerBuild(participation, commitHash)",
+ "via": {
+ "kind": "queue",
+ "label": "Hazelcast queue buildJobQueue"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "BuildJobQueueItem",
+ "definedIn": "buildagent/dto/BuildJobQueueItem.java",
+ "fields": [
+ {
+ "key": "id",
+ "value": "\"bj-77a1\""
+ },
+ {
+ "key": "participationId",
+ "value": "48213"
+ },
+ {
+ "key": "repositoryUri",
+ "value": "\"…/artemis101-alice.git\""
+ },
+ {
+ "key": "commitHash",
+ "value": "\"8f2c1e4\""
+ },
+ {
+ "key": "priority",
+ "value": "2"
+ },
+ {
+ "key": "buildConfig",
+ "value": "{ dockerImage: \"ls1tum/artemis-maven\", timeoutSec: 120 }"
+ }
+ ]
+ }
+ },
+ {
+ "lane": 4,
+ "module": "buildagent",
+ "label": "run tests",
+ "caption": "A build agent takes the job, runs the instructor's tests in a container, and reports which tests passed.",
+ "file": "buildagent/service/BuildJobExecutionService.java:201",
+ "method": "runBuildJob(buildJob, containerName)",
+ "via": {
+ "kind": "queue",
+ "label": "polled from buildJobQueue"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "BuildResult",
+ "definedIn": "buildagent/dto/BuildResult.java",
+ "fields": [
+ {
+ "key": "jobId",
+ "value": "\"bj-77a1\""
+ },
+ {
+ "key": "successful",
+ "value": "false"
+ },
+ {
+ "key": "testResults",
+ "value": "[ 17 passed, 3 failed ]"
+ },
+ {
+ "key": "buildLogs",
+ "value": "\"214 lines\""
+ },
+ {
+ "key": "durationMs",
+ "value": "38412"
+ }
+ ]
+ }
+ },
+ {
+ "lane": 3,
+ "module": "assessment",
+ "label": "score result",
+ "caption": "The test results become a score with one piece of feedback per test, and it is stored against the submission.",
+ "file": "assessment/service/ResultService.java:233",
+ "method": "processNewProgrammingExerciseResult(participation, buildResult)",
+ "via": {
+ "kind": "queue",
+ "label": "Hazelcast result queue"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "Result",
+ "definedIn": "assessment/domain/Result.java",
+ "fields": [
+ {
+ "key": "id",
+ "value": "1500872"
+ },
+ {
+ "key": "submissionId",
+ "value": "902114"
+ },
+ {
+ "key": "score",
+ "value": "85.0"
+ },
+ {
+ "key": "successful",
+ "value": "false"
+ },
+ {
+ "key": "feedbacks",
+ "value": "[ 20 items ]"
+ },
+ {
+ "key": "completionDate",
+ "value": "\"2026-11-27T14:02:52Z\""
+ }
+ ]
+ }
+ },
+ {
+ "lane": 1,
+ "module": "communication",
+ "label": "push to browser",
+ "caption": "The new result is sent over a websocket to the topic the student's browser is already listening on.",
+ "file": "communication/service/WebsocketMessagingService.java:58",
+ "method": "sendMessage(\"/topic/participation/48213/newResults\", result)",
+ "via": {
+ "kind": "call",
+ "label": "method call"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "ResultDTO",
+ "definedIn": "assessment/dto/ResultDTO.java",
+ "fields": [
+ {
+ "key": "topic",
+ "value": "\"/topic/participation/48213/newResults\""
+ },
+ {
+ "key": "score",
+ "value": "85.0"
+ },
+ {
+ "key": "successful",
+ "value": "false"
+ },
+ {
+ "key": "testCaseCount",
+ "value": "20"
+ },
+ {
+ "key": "passedTestCaseCount",
+ "value": "17"
+ }
+ ]
+ }
+ },
+ {
+ "lane": 0,
+ "module": "client",
+ "label": "show score",
+ "caption": "The exercise page updates without a reload and shows 85% with the three failing tests listed.",
+ "file": "webapp/app/programming/…/result.component.ts",
+ "method": "subscribe → onNewResult(result)",
+ "via": {
+ "kind": "ws",
+ "label": "websocket"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "UI state",
+ "definedIn": "Angular component",
+ "fields": [
+ {
+ "key": "badge",
+ "value": "\"85 %\""
+ },
+ {
+ "key": "passed",
+ "value": "\"17 of 20 tests\""
+ },
+ {
+ "key": "failing",
+ "value": "[\"testSortEmpty\", \"testSortNull\", \"testStable\"]"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "id": "exam",
+ "name": "An instructor starts an exam for 412 students",
+ "summary": "7 stops · 3 modules · 1 step is a finding",
+ "stops": [
+ {
+ "lane": 0,
+ "module": "client",
+ "label": "click Start",
+ "caption": "The instructor clicks Start exercises on the exam page.",
+ "file": "webapp/app/exam/manage/exam-checklist.component.ts",
+ "method": "POST /api/exam/courses/12/exams/77/student-exams/start-exercises",
+ "via": null,
+ "findingRank": null,
+ "payload": {
+ "type": "HTTP request",
+ "definedIn": "REST",
+ "fields": [
+ {
+ "key": "courseId",
+ "value": "12"
+ },
+ {
+ "key": "examId",
+ "value": "77"
+ }
+ ]
+ }
+ },
+ {
+ "lane": 1,
+ "module": "exam",
+ "label": "exam endpoint",
+ "caption": "The exam endpoint checks the instructor's role and hands the work to the exam service.",
+ "file": "exam/web/StudentExamResource.java:340",
+ "method": "startExercises(courseId, examId)",
+ "via": {
+ "kind": "call",
+ "label": "HTTP request"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "StartRequest",
+ "definedIn": "exam/web/StudentExamResource.java",
+ "fields": [
+ {
+ "key": "courseId",
+ "value": "12"
+ },
+ {
+ "key": "examId",
+ "value": "77"
+ },
+ {
+ "key": "requestedBy",
+ "value": "\"instructor42\""
+ }
+ ]
+ }
+ },
+ {
+ "lane": 2,
+ "module": "exam",
+ "label": "plan participations",
+ "caption": "The service loads every student exam and works out which exercises each student gets.",
+ "file": "exam/service/StudentExamService.java:512",
+ "method": "startExercises(examId)",
+ "via": {
+ "kind": "call",
+ "label": "method call"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "List",
+ "definedIn": "exam/domain/StudentExam.java",
+ "fields": [
+ {
+ "key": "examId",
+ "value": "77"
+ },
+ {
+ "key": "studentExams",
+ "value": "412"
+ },
+ {
+ "key": "exercisesPerStudent",
+ "value": "5"
+ }
+ ]
+ }
+ },
+ {
+ "lane": 4,
+ "module": "programming",
+ "label": "read repo table",
+ "caption": "Exam reads programming's repository class directly to load the exercise templates. That repository is used by 107 files and changed 30 times in 12 months, which is finding #22.",
+ "file": "exam/service/StudentExamService.java:548 → programming/repository/ProgrammingExerciseRepository.java",
+ "method": "findByIdWithTemplateAndSolutionParticipationElseThrow(id)",
+ "via": {
+ "kind": "find",
+ "label": "direct repository access"
+ },
+ "findingRank": 22,
+ "payload": {
+ "type": "ProgrammingExercise",
+ "definedIn": "programming/domain/ProgrammingExercise.java",
+ "fields": [
+ {
+ "key": "id",
+ "value": "3071"
+ },
+ {
+ "key": "templateParticipation",
+ "value": "{ id: 901 }"
+ },
+ {
+ "key": "solutionParticipation",
+ "value": "{ id: 902 }"
+ },
+ {
+ "key": "buildConfig",
+ "value": "{ … }"
+ }
+ ]
+ }
+ },
+ {
+ "lane": 2,
+ "module": "programming",
+ "label": "create participations",
+ "caption": "For each student, a personal repository is copied from the template and a participation is created.",
+ "file": "programming/service/ParticipationService.java:190",
+ "method": "startExercise(exercise, student)",
+ "via": {
+ "kind": "call",
+ "label": "method call"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "StudentParticipation",
+ "definedIn": "exercise/domain/participation/StudentParticipation.java",
+ "fields": [
+ {
+ "key": "created",
+ "value": "412"
+ },
+ {
+ "key": "failed",
+ "value": "0"
+ },
+ {
+ "key": "repositoriesCopied",
+ "value": "412"
+ }
+ ]
+ }
+ },
+ {
+ "lane": 1,
+ "module": "communication",
+ "label": "report progress",
+ "caption": "Progress is pushed to the instructor's page while students are processed.",
+ "file": "exam/service/StudentExamService.java:603",
+ "method": "convertAndSend(\"/topic/exams/77/exercise-start-status\")",
+ "via": {
+ "kind": "call",
+ "label": "method call"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "ExerciseStartStatus",
+ "definedIn": "exam/dto/ExamExerciseStartPreparationStatus.java",
+ "fields": [
+ {
+ "key": "finished",
+ "value": "412"
+ },
+ {
+ "key": "failed",
+ "value": "0"
+ },
+ {
+ "key": "participationCount",
+ "value": "2060"
+ }
+ ]
+ }
+ },
+ {
+ "lane": 0,
+ "module": "client",
+ "label": "show 100%",
+ "caption": "The progress bar reaches 412 of 412 and the exam can open.",
+ "file": "webapp/app/exam/manage/exam-checklist.component.ts",
+ "method": "subscribe → updateProgress(status)",
+ "via": {
+ "kind": "ws",
+ "label": "websocket"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "UI state",
+ "definedIn": "Angular component",
+ "fields": [
+ {
+ "key": "progress",
+ "value": "\"412 / 412\""
+ },
+ {
+ "key": "readyToOpen",
+ "value": "true"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "id": "grade",
+ "name": "A tutor grades a text answer",
+ "summary": "7 stops · 4 modules · ends with a notification to the student",
+ "stops": [
+ {
+ "lane": 0,
+ "module": "client",
+ "label": "submit grade",
+ "caption": "The tutor highlights parts of the answer, adds comments, and clicks Submit.",
+ "file": "webapp/app/text/manage/assess/text-submission-assessment.component.ts",
+ "method": "PUT /api/text/participations/5521/results/889/submit-text-assessment",
+ "via": null,
+ "findingRank": null,
+ "payload": {
+ "type": "HTTP body",
+ "definedIn": "REST",
+ "fields": [
+ {
+ "key": "feedbacks",
+ "value": "[ 4 items ]"
+ },
+ {
+ "key": "textBlocks",
+ "value": "[ 6 items ]"
+ }
+ ]
+ }
+ },
+ {
+ "lane": 1,
+ "module": "text",
+ "label": "grading endpoint",
+ "caption": "The text endpoint checks that this tutor holds the lock on the submission.",
+ "file": "text/web/TextAssessmentResource.java:171",
+ "method": "submitTextAssessment(participationId, resultId, dto)",
+ "via": {
+ "kind": "call",
+ "label": "HTTP request"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "TextAssessmentDTO",
+ "definedIn": "text/dto/TextAssessmentDTO.java",
+ "fields": [
+ {
+ "key": "participationId",
+ "value": "5521"
+ },
+ {
+ "key": "resultId",
+ "value": "889"
+ },
+ {
+ "key": "feedbacks",
+ "value": "[ 4 items ]"
+ },
+ {
+ "key": "textBlocks",
+ "value": "[ 6 items ]"
+ }
+ ]
+ }
+ },
+ {
+ "lane": 2,
+ "module": "text",
+ "label": "store feedback",
+ "caption": "Each comment is tied to the highlighted text block so it can be shown in place later.",
+ "file": "text/service/TextAssessmentService.java:84",
+ "method": "saveFeedback(textBlocks, feedbacks)",
+ "via": {
+ "kind": "call",
+ "label": "method call"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "List",
+ "definedIn": "assessment/domain/Feedback.java",
+ "fields": [
+ {
+ "key": "resultId",
+ "value": "889"
+ },
+ {
+ "key": "feedbacks",
+ "value": "[ 4 items ]"
+ },
+ {
+ "key": "linkedBlocks",
+ "value": "4"
+ },
+ {
+ "key": "totalCredits",
+ "value": "7.5"
+ }
+ ]
+ }
+ },
+ {
+ "lane": 3,
+ "module": "assessment",
+ "label": "finalise result",
+ "caption": "The result is scored, marked as rated, and locked against further edits.",
+ "file": "assessment/service/ResultService.java:301",
+ "method": "submitManualAssessment(resultId)",
+ "via": {
+ "kind": "call",
+ "label": "method call"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "Result",
+ "definedIn": "assessment/domain/Result.java",
+ "fields": [
+ {
+ "key": "id",
+ "value": "889"
+ },
+ {
+ "key": "score",
+ "value": "75.0"
+ },
+ {
+ "key": "rated",
+ "value": "true"
+ },
+ {
+ "key": "assessor",
+ "value": "\"tutor17\""
+ },
+ {
+ "key": "completionDate",
+ "value": "\"2026-11-27T16:40:03Z\""
+ }
+ ]
+ }
+ },
+ {
+ "lane": 2,
+ "module": "athena",
+ "label": "share for learning",
+ "caption": "If the course allows it, the graded feedback is sent to Athena so it can suggest feedback for similar answers.",
+ "file": "athena/service/AthenaFeedbackSendingService.java:72",
+ "method": "sendFeedback(exercise, submission, feedbacks)",
+ "via": {
+ "kind": "call",
+ "label": "method call (async)"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "AthenaFeedbackDTO",
+ "definedIn": "athena/dto/TextFeedbackDTO.java",
+ "fields": [
+ {
+ "key": "exerciseId",
+ "value": "2210"
+ },
+ {
+ "key": "submissionId",
+ "value": "5521"
+ },
+ {
+ "key": "feedbacks",
+ "value": "[ 4 items ]"
+ },
+ {
+ "key": "module",
+ "value": "\"module_text_cofee\""
+ }
+ ]
+ }
+ },
+ {
+ "lane": 1,
+ "module": "communication",
+ "label": "notify student",
+ "caption": "The student gets a notification that their answer was graded.",
+ "file": "communication/service/notifications/SingleUserNotificationService.java:140",
+ "method": "notifyUserAboutAssessedExerciseSubmission(exercise, user)",
+ "via": {
+ "kind": "call",
+ "label": "method call"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "SingleUserNotification",
+ "definedIn": "communication/domain/notification/SingleUserNotification.java",
+ "fields": [
+ {
+ "key": "recipient",
+ "value": "\"alice\""
+ },
+ {
+ "key": "title",
+ "value": "\"Exercise assessed\""
+ },
+ {
+ "key": "exerciseId",
+ "value": "2210"
+ },
+ {
+ "key": "score",
+ "value": "75.0"
+ }
+ ]
+ }
+ },
+ {
+ "lane": 0,
+ "module": "client",
+ "label": "see feedback",
+ "caption": "The student opens the notification and sees each comment next to the sentence it is about.",
+ "file": "webapp/app/text/overview/text-result.component.ts",
+ "method": "subscribe → onNotification(n)",
+ "via": {
+ "kind": "ws",
+ "label": "websocket"
+ },
+ "findingRank": null,
+ "payload": {
+ "type": "UI state",
+ "definedIn": "Angular component",
+ "fields": [
+ {
+ "key": "score",
+ "value": "\"75 %\""
+ },
+ {
+ "key": "inlineComments",
+ "value": "4"
+ }
+ ]
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 51759dd3..655c2fb2 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -1,71 +1,44 @@
-import { useEffect, useState } from "react";
-import { Navigate, Route, Routes, useParams } from "react-router";
-import { Shell } from "./components/Shell";
-import type { BundleList } from "./contracts/generated";
-import { type Bundle, loadBundle, loadBundleList } from "./data/bundle";
-import { BundlesProvider } from "./data/context";
-import { SCREENS } from "./screens";
+import { Route, Routes } from "react-router";
+import { SitePage } from "./components/cx/site-header";
+import { Change } from "./routes/Change";
+import { Decisions } from "./routes/Decisions";
+import { FindingDetail } from "./routes/FindingDetail";
+import { Findings } from "./routes/Findings";
+import { Journeys } from "./routes/Journeys";
+import { Landing } from "./routes/Landing";
+import { MapPage } from "./routes/MapPage";
+import { NotFound } from "./routes/NotFound";
+import { Overview } from "./routes/Overview";
+import { RepoLayout } from "./routes/RepoLayout";
+import { Size } from "./routes/Size";
+import { Trust } from "./routes/Trust";
-type Loaded =
- { state: "loading" } | { state: "ready"; value: T } | { state: "failed"; why: string };
-
-function useLoaded(load: () => Promise, key: string): Loaded {
- const [result, setResult] = useState>({ state: "loading" });
- useEffect(() => {
- let current = true;
- setResult({ state: "loading" });
- load().then(
- (value) => current && setResult({ state: "ready", value }),
- (error: unknown) => current && setResult({ state: "failed", why: String(error) }),
- );
- return () => {
- current = false;
- };
- // `load` is rebuilt on every render; `key` says when the request really changes.
- }, [key]);
- return result;
-}
-
-// Routes are //, kept in the address bar after the "#", so every view has
-// a permanent link and the app works from any static host (spec.md §10.3).
+// Every view has its own address after the "#", so each one can be linked to and the app
+// works from any static host (spec.md §10.3).
export function App() {
- const list = useLoaded(() => loadBundleList(), "list");
- if (list.state === "loading") return Loading… ;
- if (list.state === "failed") return {list.why} ;
- const first = list.value.bundles[0];
- if (!first) return No repository bundles found in bundles/index.json. ;
-
- return (
-
-
- } />
- }
- />
-
-
- );
-}
-
-function RepoScreen({ list }: { list: BundleList }) {
- const { repoId, screen: screenPath } = useParams();
- const entry = list.bundles.find((bundle) => bundle.repo_id === repoId);
- const screen = SCREENS.find((candidate) => candidate.path === screenPath);
- const bundle = useLoaded(
- () => (entry ? loadBundle(entry.path) : Promise.resolve(null)),
- entry?.path ?? "",
- );
-
- if (!entry || !screen) return ;
- if (bundle.state === "loading") return Loading… ;
- if (bundle.state === "failed") return {bundle.why} ;
- if (!bundle.value) return ;
-
- const Screen = screen.component;
return (
-
-
-
+
+ } />
+ }>
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+
+
+
+
+ }
+ />
+
);
}
diff --git a/web/src/app.test.tsx b/web/src/app.test.tsx
index 45604b20..1c839cf1 100644
--- a/web/src/app.test.tsx
+++ b/web/src/app.test.tsx
@@ -1,11 +1,13 @@
import { readFile } from "node:fs/promises";
import { join } from "node:path";
-import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { afterEach, describe, expect, it } from "vitest";
-import { Shell } from "./components/Shell";
+import { App } from "./App";
+import { statusCounts } from "./cx/meta";
import { expectSchema, loadBundle, loadBundleList } from "./data/bundle";
-import { Decisions, verdictSentence } from "./screens/Decisions";
+import { serveBundlesFromDisk } from "./data/testing";
+import { VerdictSentence } from "./routes/Overview";
afterEach(cleanup);
@@ -34,34 +36,41 @@ describe("bundle loader", () => {
});
});
-describe("decisions screen", () => {
+describe("report screens", () => {
it("states the verdict from the checks at the end snapshot", async () => {
const { decisions, index } = await fixture();
const atEnd = decisions.checks.filter((check) => check.snapshot_sha === index.end_sha);
- expect(verdictSentence(decisions.decisions, atEnd)).toBe(
- "1 of 2 checkable decisions is holding.",
- );
+ render( );
+ expect(document.body.textContent).toBe("1 broken\u00a0— 1 of 2 still holding.");
});
it("opens a finding's evidence and labels template text as computed", async () => {
- const bundle = await fixture();
- render(
-
-
-
-
- ,
- );
- expect(screen.getByRole("note").textContent).toContain("Synthetic fixture data");
- expect(screen.queryByLabelText("Selected finding")).toBeNull();
+ const restore = serveBundlesFromDisk();
+ try {
+ render(
+
+
+ ,
+ );
+ const first = await screen.findByRole("link", {
+ name: /shared uses billing through 1 link/,
+ });
+ expect(screen.getByRole("note").textContent).toContain("Synthetic fixture data");
- fireEvent.click(screen.getByText(/shared uses billing through 1 link/));
+ fireEvent.click(first);
- const detail = screen.getByLabelText("Selected finding");
- expect(detail.textContent).toContain("shared/money/Rounding.src:3");
- expect(detail.textContent).toContain("Computed");
- expect(detail.textContent).toContain("loops 1 to 0");
- expect(detail.textContent).toContain("no AI signal");
- expect(detail.querySelector(".badge--ai")).toBeNull();
+ const summary = await screen.findByRole("region", { name: "Computed summary" });
+ const page = screen.getByRole("article");
+ const evidence = screen.getByRole("region", { name: "Evidence" });
+ expect(evidence.textContent).toContain("shared/money/Rounding.src:3");
+ // The cited lines themselves, read from the bundle's code file.
+ expect(await within(evidence).findByText(/import billing\.tax\.TaxTable/)).toBeTruthy();
+ expect(summary.querySelector('[data-source="computed"]')).not.toBeNull();
+ expect(summary.textContent).toContain("1 → 0");
+ expect(page.textContent).toContain("no AI signal");
+ expect(summary.querySelector('[data-source="ai"]')).toBeNull();
+ } finally {
+ restore();
+ }
});
});
diff --git a/web/src/components/AiSwitch.tsx b/web/src/components/AiSwitch.tsx
deleted file mode 100644
index 7077132f..00000000
--- a/web/src/components/AiSwitch.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-// Turns AI-written text off for the whole app. The report stays complete with it off: every
-// finding falls back to its computed summary (spec.md §8.7), and the ranking never moves.
-import { useSetView, useView } from "../data/view";
-
-export function AiSwitch() {
- const view = useView();
- const setView = useSetView();
- const on = view.ai !== "off";
- return (
-
-
- AI text
-
- setView({ ai: on ? "off" : undefined })}
- >
-
-
-
- );
-}
diff --git a/web/src/components/Badge.tsx b/web/src/components/Badge.tsx
deleted file mode 100644
index 50c28128..00000000
--- a/web/src/components/Badge.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-// Every sentence on screen says where it came from (spec.md §10.3): "AI" for text a model
-// wrote and the checks accepted, "Computed" for everything ordinary code worked out.
-export type Origin = "ai" | "computed";
-
-export function Badge({ origin }: { origin: Origin }) {
- return origin === "ai" ? (
-
- AI
-
- ) : (
-
- Computed
-
- );
-}
diff --git a/web/src/components/RepoSwitcher.tsx b/web/src/components/RepoSwitcher.tsx
deleted file mode 100644
index 5406d6d5..00000000
--- a/web/src/components/RepoSwitcher.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-// Moves between the repositories in bundles/index.json, keeping the screen. The rest of
-// the address names things inside one repository, so only the AI choice is carried over.
-import { useEffect, useRef, useState } from "react";
-import { Link, useLocation } from "react-router";
-import type { BundleIndex } from "../contracts/generated";
-import { useBundles } from "../data/context";
-import { useView, viewLink } from "../data/view";
-
-export function RepoSwitcher({ index }: { index: BundleIndex }) {
- const bundles = useBundles();
- const view = useView();
- const { pathname } = useLocation();
- const screen = pathname.split("/")[2] || "decisions";
- const [open, setOpen] = useState(false);
- const ref = useRef(null);
-
- useEffect(() => {
- if (!open) return;
- const close = (event: MouseEvent | KeyboardEvent) => {
- if (
- event instanceof KeyboardEvent
- ? event.key === "Escape"
- : !ref.current?.contains(event.target as Node)
- ) {
- setOpen(false);
- }
- };
- document.addEventListener("mousedown", close);
- document.addEventListener("keydown", close);
- return () => {
- document.removeEventListener("mousedown", close);
- document.removeEventListener("keydown", close);
- };
- }, [open]);
-
- const pill = (
- <>
- {index.repo}
- {index.end_sha.slice(0, 7)}
- >
- );
-
- if (bundles.length < 2) {
- return (
-
- {pill}
-
- );
- }
-
- return (
-
-
setOpen(!open)}
- >
- {pill}
-
-
-
-
- {open && (
-
- {bundles.map((bundle) => {
- const current = bundle.repo_id === index.repo_id;
- return (
-
- setOpen(false)}
- >
-
- {current && }
-
-
- {bundle.label}
- {bundle.repo_id}
-
-
-
- );
- })}
-
- )}
-
- );
-}
diff --git a/web/src/components/Shell.tsx b/web/src/components/Shell.tsx
deleted file mode 100644
index 1165a0ba..00000000
--- a/web/src/components/Shell.tsx
+++ /dev/null
@@ -1,112 +0,0 @@
-import type { ReactNode } from "react";
-import { NavLink } from "react-router";
-import type { BundleIndex } from "../contracts/generated";
-import { useView, viewLink } from "../data/view";
-import { SCREENS } from "../screens";
-import { AiSwitch } from "./AiSwitch";
-import { Badge } from "./Badge";
-import { RepoSwitcher } from "./RepoSwitcher";
-import { STATUSES, StatusGlyph } from "./Status";
-
-// The tabs, in order. Close-up and Code open from a finding and are not tabs. A path that
-// is not in SCREENS yet is simply not shown.
-export const TAB_PATHS = ["decisions", "grid", "before-after", "size", "report"];
-
-const TAB_LABELS: Record = {
- decisions: "Decisions",
- grid: "Map",
- "before-after": "Before and after",
- size: "Size",
- report: "Report",
-};
-
-export const tabs = () =>
- TAB_PATHS.flatMap((path) => {
- const screen = SCREENS.find((candidate) => candidate.path === path);
- return screen ? [{ path, label: TAB_LABELS[path] ?? screen.label }] : [];
- });
-
-const snapshotDate = (index: BundleIndex) =>
- index.snapshots.find((snapshot) => snapshot.sha === index.end_sha)?.date ??
- index.snapshots[index.snapshots.length - 1]?.date;
-
-export function Shell({ index, children }: { index: BundleIndex; children: ReactNode }) {
- const date = snapshotDate(index);
- const aiOff = useView().ai === "off";
- return (
-
-
- CodeXray
-
- {date && Snapshot {formatDate(date)} }
-
- {tabs().map((tab) => (
-
- {tab.label}
-
- ))}
-
-
-
-
-
-
- {STATUSES.map((status) => (
-
-
- {status.label}
-
- ))}
-
-
-
-
- every number, the ranking and template text
-
- {aiOff ? (
-
- AI text is off: every sentence is a computed summary
-
- ) : (
-
-
-
- sentence written by a model, checked against the facts
-
-
- )}
-
-
-
- {index.synthetic && (
-
- Synthetic fixture data. {" "}
-
- Made by hand for building the app. Nothing here was measured on a real repository.
-
-
- )}
-
-
-
{children}
-
- );
-}
-
-const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
-
-/** "2026-11-27" to "27 Nov 2026". Parsed by hand so the time zone never shifts the day. */
-export function formatDate(iso: string): string {
- const [year, month, day] = iso.split("-").map(Number);
- if (!year || !month || !day) return iso;
- return `${day} ${MONTHS[month - 1]} ${year}`;
-}
-
-/** The sponsor date as shown in running text; a bundle without one gets the plain name. */
-export function formatSponsorDate(iso: string | null): string {
- return iso ? formatDate(iso) : "the sponsor date";
-}
diff --git a/web/src/components/Sparkline.tsx b/web/src/components/Sparkline.tsx
deleted file mode 100644
index c79d36ab..00000000
--- a/web/src/components/Sparkline.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-export interface SparkPoint {
- date: string;
- value: number;
-}
-
-interface Props {
- points: SparkPoint[];
- /** Dates to mark with a dashed vertical line, such as the sponsor date. */
- marks?: string[];
- width?: number;
- height?: number;
- label: string;
-}
-
-/**
- * A small line of values over snapshot dates. Points are spaced by date, so an uneven
- * series (quarters plus 1 March 2025) keeps its true shape.
- */
-export function Sparkline({ points, marks = [], width = 120, height = 28, label }: Props) {
- if (points.length === 0) return null;
- const pad = 3;
- const times = points.map((point) => Date.parse(point.date));
- const t0 = Math.min(...times);
- const t1 = Math.max(...times);
- const values = points.map((point) => point.value);
- let lo = Math.min(...values);
- let hi = Math.max(...values);
- // A flat series is drawn in the middle, not pinned to an edge.
- if (hi - lo < 1e-9) {
- lo -= 1;
- hi += 1;
- }
- const x = (t: number) =>
- t1 === t0 ? width / 2 : pad + ((t - t0) / (t1 - t0)) * (width - 2 * pad);
- const y = (v: number) => pad + (1 - (v - lo) / (hi - lo)) * (height - 2 * pad);
- const coords = points.map((point, i) => [x(times[i]!), y(point.value)] as const);
- const last = coords[coords.length - 1]!;
-
- return (
-
- {marks
- .map((date) => Date.parse(date))
- .filter((t) => t > t0 && t < t1)
- .map((t) => (
-
- ))}
- {coords.length > 1 && (
- `${px.toFixed(1)},${py.toFixed(1)}`).join(" ")}
- />
- )}
-
-
- );
-}
diff --git a/web/src/components/Status.tsx b/web/src/components/Status.tsx
deleted file mode 100644
index 7056e67f..00000000
--- a/web/src/components/Status.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import type { DecisionCheck } from "../contracts/generated";
-
-export type StatusKey = DecisionCheck["status"];
-
-export interface StatusInfo {
- key: StatusKey;
- label: string;
- /** SVG path in a 12 by 12 box. Every status has its own shape as well as its own colour. */
- glyph: string;
- colour: string;
-}
-
-// Ordered from best to worst, the order the legend and the status list use (spec.md §9.2).
-export const STATUSES: StatusInfo[] = [
- {
- key: "holding",
- label: "Holding",
- glyph: "M6 1a5 5 0 1 0 0 10A5 5 0 0 0 6 1z",
- colour: "var(--status-holding)",
- },
- {
- key: "mostly_holding",
- label: "Mostly holding",
- glyph: "M6 1a5 5 0 1 0 0 10A5 5 0 0 0 6 1zm0 1.5a3.5 3.5 0 0 1 0 7z",
- colour: "var(--status-mostly-holding)",
- },
- {
- key: "spreading",
- label: "Spreading",
- glyph:
- "M6 1a5 5 0 1 0 0 10A5 5 0 0 0 6 1zm0 1.5a3.5 3.5 0 1 1 0 7a3.5 3.5 0 0 1 0-7zm0 2a1.5 1.5 0 1 0 0 3a1.5 1.5 0 0 0 0-3z",
- colour: "var(--status-spreading)",
- },
- {
- key: "slipping",
- label: "Slipping",
- glyph: "M1 2.5h10L6 11z",
- colour: "var(--status-slipping)",
- },
- {
- key: "broken",
- label: "Broken",
- glyph: "M6 .5L11.5 6L6 11.5L.5 6z",
- colour: "var(--status-broken)",
- },
-];
-
-const BY_KEY = new Map(STATUSES.map((status) => [status.key, status]));
-
-export function statusInfo(status: StatusKey): StatusInfo {
- return BY_KEY.get(status)!;
-}
-
-export function StatusGlyph({ status }: { status: StatusKey }) {
- const info = statusInfo(status);
- return (
-
-
-
- );
-}
-
-export function Status({ status }: { status: StatusKey }) {
- return (
-
-
- {statusInfo(status).label}
-
- );
-}
diff --git a/web/src/components/cx/badges.tsx b/web/src/components/cx/badges.tsx
new file mode 100644
index 00000000..55865eff
--- /dev/null
+++ b/web/src/components/cx/badges.tsx
@@ -0,0 +1,48 @@
+// Where a sentence or a value comes from (spec.md §10.3): every sentence an AI model wrote carries
+// a small "AI" badge, everything else is marked computed, and a value the bundle does not
+// hold says so instead of showing a zero.
+import { cn } from "./cn";
+
+/** Marks text written by the AI and kept because it passed every check (spec.md §8.4). */
+export function AiBadge({ className }: { className?: string }) {
+ return (
+
+ AI
+
+ );
+}
+
+/** Marks text or numbers built by arithmetic and fixed templates from stored facts. */
+export function ComputedMark({ className }: { className?: string }) {
+ return (
+
+ computed
+
+ );
+}
+
+/** Stands in for a value this run did not measure. */
+export function NotMeasured({ className }: { className?: string }) {
+ return (
+
+ not measured in this run
+
+ );
+}
diff --git a/web/src/components/cx/closeup.tsx b/web/src/components/cx/closeup.tsx
new file mode 100644
index 00000000..95d7615c
--- /dev/null
+++ b/web/src/components/cx/closeup.tsx
@@ -0,0 +1,266 @@
+// Boxes and arrows for only the modules of one finding (spec.md §10.2 screen 3). Positions
+// are the ones stored in the bundle's layouts.json when it was built (§10.4); nothing is
+// laid out here. The stored layout runs left to right; it is drawn turned a quarter, top to
+// bottom, and stretched to the panel, so the picture is the same on every visit.
+import { cellKey } from "../../cx/grid";
+import type { Finding, RepoBundle } from "../../cx/types";
+
+const W = 360;
+const BOX_H = 26;
+const PAD_Y = 22;
+/** Height per stored layer, within limits, so close layers never overlap. */
+const ROW = 72;
+
+interface Box {
+ id: string;
+ label: string;
+ path: string;
+ x: number;
+ y: number;
+ w: number;
+ core: boolean;
+}
+
+interface Arrow {
+ src: string;
+ dst: string;
+ count: number;
+ against: boolean;
+ /** A link between two of the finding's own modules. */
+ hot: boolean;
+}
+
+/** The boxes and arrows for a finding, or null when the bundle holds no layout for it. */
+export function closeupPicture(repo: RepoBundle, finding: Finding) {
+ const layout = finding.layout;
+ if (!layout || layout.length === 0) return null;
+ const byId = new Map(repo.modules.map((m) => [m.id, m]));
+ const core = new Set(finding.modules);
+
+ // Turned a quarter: the stored x runs down the panel, the stored y across it.
+ const xs = layout.map((p) => p.x);
+ const ys = layout.map((p) => p.y);
+ const minX = Math.min(...xs);
+ const maxX = Math.max(...xs);
+ const minY = Math.min(...ys);
+ const maxY = Math.max(...ys);
+ const layers = new Set(xs).size;
+ const H = Math.min(600, Math.max(150, layers * ROW));
+
+ const boxes: Box[] = layout.map((p) => {
+ const m = byId.get(p.nodeId);
+ const label = m?.name ?? p.nodeId.replace(/^M:/, "");
+ const w = Math.min(124, Math.max(64, label.length * 6.4 + 16));
+ return {
+ id: p.nodeId,
+ label: label.length > 18 ? `…${label.slice(-17)}` : label,
+ path: m?.path ?? p.nodeId,
+ w,
+ x: maxY === minY ? W / 2 : 66 + ((p.y - minY) / (maxY - minY)) * (W - 132),
+ y:
+ maxX === minX
+ ? H / 2
+ : PAD_Y + BOX_H / 2 + ((p.x - minX) / (maxX - minX)) * (H - 2 * PAD_Y - BOX_H),
+ core: core.has(p.nodeId),
+ };
+ });
+
+ const ids = new Set(boxes.map((b) => b.id));
+ const hotCells = new Set(finding.cells.map(([s, d]) => cellKey(s, d)));
+ const arrows: Arrow[] = Object.values(repo.cellLinks)
+ // Links between two neighbours are left out: they say nothing about this finding and
+ // crowd a picture this narrow.
+ .filter(
+ (c) =>
+ ids.has(c.src) && ids.has(c.dst) && c.count > 0 && (core.has(c.src) || core.has(c.dst)),
+ )
+ .map((c) => ({
+ src: c.src,
+ dst: c.dst,
+ count: c.count,
+ against: (byId.get(c.src)?.index ?? -1) > (byId.get(c.dst)?.index ?? -1),
+ // With no link between the finding's own modules, its links to neighbours lead.
+ hot:
+ hotCells.size > 0
+ ? hotCells.has(cellKey(c.src, c.dst))
+ : core.has(c.src) || core.has(c.dst),
+ }))
+ // Faded links first, so the finding's own links are drawn on top.
+ .sort(
+ (a, b) =>
+ Number(a.hot) - Number(b.hot) || cellKey(a.src, a.dst).localeCompare(cellKey(b.src, b.dst)),
+ );
+ return { boxes, arrows, H };
+}
+
+/** Where the segment from the centre of `a` towards `b` leaves the box of `a`. */
+function edgePoint(a: Box, dx: number, dy: number, gap: number) {
+ const hw = a.w / 2 + gap;
+ const hh = BOX_H / 2 + gap;
+ const t = Math.min(
+ dx === 0 ? Infinity : hw / Math.abs(dx),
+ dy === 0 ? Infinity : hh / Math.abs(dy),
+ );
+ return { x: a.x + dx * t, y: a.y + dy * t };
+}
+
+export function Closeup({ repo, finding }: { repo: RepoBundle; finding: Finding }) {
+ const picture = closeupPicture(repo, finding);
+ if (!picture) {
+ return (
+
+ The bundle holds no stored layout for this finding, so no close-up is drawn.
+
+ );
+ }
+ const { boxes, arrows, H } = picture;
+ const at = new Map(boxes.map((b) => [b.id, b]));
+ const pairs = new Set(arrows.map((a) => cellKey(a.src, a.dst)));
+ const max = Math.max(1, ...arrows.map((a) => a.count));
+ const partners =
+ finding.type === "hidden_partners" ? boxes.filter((b) => b.core).slice(0, 2) : [];
+
+ return (
+ b.label).join(", ")}: ${arrows.length} links between them`}
+ >
+
+
+
+
+
+ {arrows.map((e) => {
+ const p = at.get(e.src)!;
+ const q = at.get(e.dst)!;
+ const dx = q.x - p.x;
+ const dy = q.y - p.y;
+ const len = Math.hypot(dx, dy) || 1;
+ // Two links between the same pair run side by side.
+ const off = pairs.has(cellKey(e.dst, e.src)) ? 5 : 0;
+ const nx = (-dy / len) * off;
+ const ny = (dx / len) * off;
+ const s = edgePoint(p, dx, dy, 1);
+ const t = edgePoint(q, -dx, -dy, 3);
+ const sx = s.x + nx;
+ const sy = s.y + ny;
+ const ex = t.x + nx;
+ const ey = t.y + ny;
+ const width = 0.8 + 3.2 * (Math.log1p(e.count) / Math.log1p(max));
+ const stroke = e.against ? "var(--against)" : "var(--grain)";
+ const lx = (sx + ex) / 2 + (off ? nx * 1.8 : (-dy / len) * 8);
+ const ly = (sy + ey) / 2 + (off ? ny * 1.8 : (dx / len) * 8) + 3;
+ return (
+
+ {`${at.get(e.src)!.label} uses ${at.get(e.dst)!.label}: ${e.count} ${e.count === 1 ? "link" : "links"}, ${e.against ? "backward" : "forward"}`}
+
+
+ {e.count}
+
+
+ );
+ })}
+ {partners.length === 2 && (
+
+ )}
+ {boxes.map((b) => (
+
+ {b.path}
+
+
+ {b.label}
+
+
+ ))}
+
+ );
+}
+
+/** The key to the close-up's colours and shapes. */
+export function CloseupLegend({ partners }: { partners: boolean }) {
+ return (
+
+
+
+ this finding
+
+
+
+ neighbour
+
+
+
+ forward link
+
+
+
+ backward link
+
+ {partners && (
+
+
+ changed together, no link
+
+ )}
+
+ );
+}
diff --git a/web/src/components/cx/cn.ts b/web/src/components/cx/cn.ts
new file mode 100644
index 00000000..eb567491
--- /dev/null
+++ b/web/src/components/cx/cn.ts
@@ -0,0 +1,8 @@
+// Joins class names, skipping empty values.
+export function cn(...parts: (string | false | null | undefined)[]): string {
+ return parts.filter(Boolean).join(" ");
+}
+
+/** A visible focus ring for links and buttons, drawn only for keyboard focus. */
+export const FOCUS =
+ "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring";
diff --git a/web/src/components/cx/code-block.tsx b/web/src/components/cx/code-block.tsx
new file mode 100644
index 00000000..23efd07b
--- /dev/null
+++ b/web/src/components/cx/code-block.tsx
@@ -0,0 +1,600 @@
+// The cited code of one finding (spec.md §4.4, §10.2 screen 4). Evidence is grouped by
+// file. Each open file shows an excerpt around every cited range with a few lines of
+// context, the cited lines highlighted; the text loads only when a file is opened, and its
+// colours after that. Every block links to the host, pinned to the snapshot commit, and to
+// the reader's own editor once the reader has given the clone folder.
+import {
+ ChevronRight,
+ ExternalLink,
+ FolderOpen,
+ GitCommitHorizontal,
+ SquareCode,
+} from "lucide-react";
+import { type FormEvent, useEffect, useId, useState } from "react";
+import type { ThemedToken } from "shiki/core";
+import { readCloneRoot, writeCloneRoot } from "../../cx/clone";
+import { editorLink, hostLink } from "../../cx/meta";
+import type { Evidence, RepoBundle } from "../../cx/types";
+import { loadEvidenceCode } from "../../data/repo";
+import { FOCUS, cn } from "./cn";
+import { splitLines, tokenStyle, tokenizeRange } from "./code-highlight";
+import { useLoaded } from "./use-page";
+
+/** Files open when the page loads; the rest are listed and open on click. */
+const OPEN_FILES = 3;
+/** Lines of context above and below each cited range. */
+const CONTEXT = 3;
+/** Lines of a long cited range shown before "Show more lines". */
+const RANGE_CAP = 30;
+/** Lines added on each side by one "Show more lines". */
+const MORE = 40;
+/** Commits listed before "Show all". */
+const COMMITS_SHOWN = 12;
+
+interface FileGroup {
+ key: string;
+ path: string;
+ blobSha: string | null;
+ records: Evidence[];
+}
+
+/** File evidence grouped by path in the order it was cited; commit evidence on its own. */
+function groupEvidence(evidence: Evidence[]): { files: FileGroup[]; commits: Evidence[] } {
+ const files: FileGroup[] = [];
+ const commits: Evidence[] = [];
+ const byKey = new Map();
+ for (const ev of evidence) {
+ if (ev.kind === "commits" || !ev.path) {
+ commits.push(ev);
+ continue;
+ }
+ const key = `${ev.path}@${ev.blobSha ?? ""}`;
+ let group = byKey.get(key);
+ if (!group) {
+ group = { key, path: ev.path, blobSha: ev.blobSha, records: [] };
+ byKey.set(key, group);
+ files.push(group);
+ }
+ group.records.push(ev);
+ }
+ return { files, commits };
+}
+
+/** "4", "4–9", "4, 5, 6", "4, 5 and 12 more". */
+function rangesText(records: Evidence[], max = 4): string {
+ const parts = records
+ .filter((r) => r.startLine !== null)
+ .map((r) =>
+ r.endLine !== null && r.endLine !== r.startLine
+ ? `${r.startLine}–${r.endLine}`
+ : `${r.startLine}`,
+ );
+ const unique = [...new Set(parts)];
+ if (unique.length <= max) return unique.join(", ");
+ return `${unique.slice(0, max).join(", ")} and ${unique.length - max} more`;
+}
+
+const rolesText = (records: Evidence[]) => [...new Set(records.map((r) => r.role))].join(", ");
+
+const hostName = (host: string) => {
+ try {
+ return new URL(host).host;
+ } catch {
+ return host;
+ }
+};
+
+const linkCls = cn(
+ "inline-flex items-center gap-1 rounded-sm text-muted-foreground hover:text-foreground",
+ FOCUS,
+);
+
+export function EvidencePane({ repo, evidence }: { repo: RepoBundle; evidence: Evidence[] }) {
+ const { files, commits } = groupEvidence(evidence);
+ const [root, setRoot] = useState(() => readCloneRoot(repo.id));
+ const [editing, setEditing] = useState(false);
+ const [opened, setOpened] = useState>(() => new Set());
+ const [moreFiles, setMoreFiles] = useState(false);
+ const [showCommits, setShowCommits] = useState(false);
+ const shown = files.slice(0, OPEN_FILES);
+ const listed = files.slice(OPEN_FILES);
+ const commitCount = commits.reduce((n, ev) => n + ev.commits.length, 0);
+ const listId = useId();
+ const commitsId = useId();
+
+ return (
+
+
+
+ Evidence
+
+
+ {evidence.length} {evidence.length === 1 ? "record" : "records"}
+ {files.length > 0 &&
+ ` in ${files.length} ${files.length === 1 ? "file" : "files"}`} @{" "}
+ {repo.endSha.slice(0, 7)}
+
+
+ {
+ writeCloneRoot(repo.id, value);
+ setRoot(value.trim() || null);
+ setEditing(false);
+ }}
+ />
+ {evidence.length === 0 && (
+ This finding holds no evidence record.
+ )}
+ {shown.map((g) => (
+
+ ))}
+ {listed.length > 0 && (
+ setMoreFiles((on) => !on)}
+ controls={listId}
+ label={
+ moreFiles
+ ? `Hide the ${fmtCount(listed.length, "other file", "other files")}`
+ : `Show ${fmtCount(listed.length, "more file", "more files")}`
+ }
+ />
+ )}
+ {listed.length > 0 && moreFiles && (
+
+
+ Open a file to read its lines.
+
+
+ {listed.map((g) => {
+ const open = opened.has(g.key);
+ return (
+
+
+ setOpened((prev) => {
+ const next = new Set(prev);
+ if (open) next.delete(g.key);
+ else next.add(g.key);
+ return next;
+ })
+ }
+ className={cn(
+ "flex w-full min-w-0 items-baseline gap-2 px-3 py-2 text-left font-mono text-xs hover:bg-muted/40",
+ FOCUS,
+ )}
+ >
+
+
+ {g.path}
+ :{rangesText(g.records)}
+
+ {" "}
+ · {rolesText(g.records)}
+
+
+
+ {open && (
+
+
+
+ )}
+
+ );
+ })}
+
+
+ )}
+ {commitCount > 0 && (
+ setShowCommits((on) => !on)}
+ controls={commitsId}
+ label={
+ showCommits
+ ? "Hide the commits"
+ : `Show the ${fmtCount(commitCount, "commit", "commits")}`
+ }
+ />
+ )}
+ {commitCount > 0 && showCommits && (
+
+ {commits.map((ev) => (
+
+ ))}
+
+ )}
+
+ );
+}
+
+const fmtCount = (n: number, one: string, many: string) =>
+ `${n.toLocaleString("en-US")} ${n === 1 ? one : many}`;
+
+/** One closed control that opens the rest of the evidence. */
+function Disclosure({
+ open,
+ onToggle,
+ controls,
+ label,
+}: {
+ open: boolean;
+ onToggle: () => void;
+ controls: string;
+ label: string;
+}) {
+ return (
+
+
+ {label}
+
+ );
+}
+
+function CloneFolder({
+ repoId,
+ root,
+ editing,
+ onEdit,
+ onSave,
+}: {
+ repoId: string;
+ root: string | null;
+ editing: boolean;
+ onEdit: (on: boolean) => void;
+ onSave: (value: string) => void;
+}) {
+ const id = useId();
+ const [draft, setDraft] = useState(root ?? "");
+ useEffect(() => {
+ if (editing) setDraft(root ?? "");
+ }, [editing, root]);
+ if (!editing) {
+ return (
+
+
+ {root ? (
+ <>
+ Editor links open files in {root}
+ >
+ ) : (
+ <>Editor links need the folder of your own clone of {repoId}.>
+ )}
+ onEdit(true)}
+ className={cn(
+ "rounded-sm font-medium text-foreground underline-offset-2 hover:underline",
+ FOCUS,
+ )}
+ >
+ {root ? "Change" : "Set clone folder"}
+
+
+ );
+ }
+ const submit = (e: FormEvent) => {
+ e.preventDefault();
+ onSave(draft);
+ };
+ return (
+
+ );
+}
+
+function FileBlock({
+ repo,
+ group,
+ root,
+}: {
+ repo: RepoBundle;
+ group: FileGroup;
+ root: string | null;
+}) {
+ const first = group.records.find((r) => r.startLine !== null) ?? group.records[0]!;
+ const file = group.path.split("/").pop() ?? group.path;
+ const dir = group.path.slice(0, group.path.length - file.length);
+ const host = hostLink(repo, group.path, first.startLine, first.endLine);
+ const editor = editorLink(root, group.path, first.startLine);
+ return (
+
+
+
+
+ {dir.length > 48 ? `…${dir.slice(-46)}` : dir}
+
+ {file}
+ :{rangesText(group.records)}
+ · {rolesText(group.records)}
+
+
+
+ {group.blobSha ? (
+
+ ) : (
+
+ The bundle holds no copy of this file. Use the links above to read it.
+
+ )}
+
+ );
+}
+
+type Row = { kind: "line"; n: number; hl: boolean } | { kind: "gap"; from: number; to: number };
+
+/** The excerpt windows around each cited range, merged where they touch. */
+function windowsOf(records: Evidence[], total: number, step: number): [number, number][] {
+ const ctx = CONTEXT + step * MORE;
+ const cap = RANGE_CAP + step * MORE * 2;
+ const raw = records
+ .filter((r) => r.startLine !== null)
+ .map((r): [number, number] => {
+ const s = r.startLine!;
+ const e = Math.min(r.endLine ?? s, s + cap - 1);
+ return [Math.max(1, s - ctx), Math.min(total, e + ctx)];
+ })
+ .sort((a, b) => a[0] - b[0] || a[1] - b[1]);
+ const out: [number, number][] = [];
+ for (const w of raw) {
+ const last = out[out.length - 1];
+ if (last && w[0] <= last[1] + 2) last[1] = Math.max(last[1], w[1]);
+ else out.push([...w]);
+ }
+ return out;
+}
+
+function FileCode({
+ repo,
+ blobSha,
+ records,
+}: {
+ repo: RepoBundle;
+ blobSha: string;
+ records: Evidence[];
+}) {
+ const loaded = useLoaded(() => loadEvidenceCode(repo, blobSha), `${repo.id}/${blobSha}`);
+ const [step, setStep] = useState(0);
+ const [whole, setWhole] = useState(false);
+ const code = loaded.state === "ready" ? loaded.value : null;
+ const lines = code ? splitLines(code.text) : [];
+ const total = lines.length;
+ const windows: [number, number][] =
+ whole || total === 0 ? [[1, total]] : windowsOf(records, total, step);
+ const windowKey = windows.map((w) => w.join("-")).join(",");
+ const [tokens, setTokens] = useState>(() => new Map());
+
+ useEffect(() => {
+ if (!code) return;
+ let current = true;
+ Promise.all(
+ windows.map(([from, to]) =>
+ tokenizeRange(blobSha, code.text, code.language, from, to).then(
+ (t) => [from, t] as const,
+ () => [from, null] as const,
+ ),
+ ),
+ ).then((parts) => {
+ if (!current) return;
+ const map = new Map();
+ for (const [from, t] of parts) t?.forEach((line, i) => map.set(from + i, line));
+ setTokens(map);
+ });
+ return () => {
+ current = false;
+ };
+ // `windowKey` stands for `windows`, which is rebuilt on every render.
+ }, [code, blobSha, windowKey]);
+
+ if (loaded.state === "loading") {
+ return (
+ Loading the cited lines…
+ );
+ }
+ if (loaded.state === "failed") {
+ return (
+
+ The cited file could not be read from the bundle: {loaded.why}
+
+ );
+ }
+
+ const cited = (n: number) =>
+ records.some(
+ (r) => r.startLine !== null && n >= r.startLine && n <= (r.endLine ?? r.startLine),
+ );
+ const rows: Row[] = [];
+ windows.forEach(([from, to], i) => {
+ const prevEnd = i === 0 ? 0 : windows[i - 1]![1];
+ if (from > prevEnd + 1) rows.push({ kind: "gap", from: prevEnd + 1, to: from - 1 });
+ for (let n = from; n <= to; n++) rows.push({ kind: "line", n, hl: cited(n) });
+ });
+ const lastEnd = windows.length ? windows[windows.length - 1]![1] : 0;
+ if (lastEnd < total) rows.push({ kind: "gap", from: lastEnd + 1, to: total });
+ const partial = rows.some((r) => r.kind === "gap");
+
+ return (
+ <>
+
+
+
+ {rows.map((r) =>
+ r.kind === "gap" ? (
+
+ {r.from === r.to ? `line ${r.from}` : `lines ${r.from}–${r.to}`} not shown
+ {cited(r.from) && " · the cited range continues"}
+
+ ) : (
+
+ {tokens.get(r.n)
+ ? tokens.get(r.n)!.map((t, j) => (
+
+ {t.content}
+
+ ))
+ : lines[r.n - 1] || " "}
+
+ ),
+ )}
+
+
+
+ {partial && (
+
+ setStep((s) => s + 1)}
+ className={cn(
+ "rounded-sm font-medium text-foreground underline-offset-2 hover:underline",
+ FOCUS,
+ )}
+ >
+ Show more lines
+
+ setWhole(true)}
+ className={cn(
+ "rounded-sm text-muted-foreground underline-offset-2 hover:text-foreground hover:underline",
+ FOCUS,
+ )}
+ >
+ Show the whole file ({total.toLocaleString("en-US")} lines)
+
+
+ )}
+ >
+ );
+}
+
+function CommitsBlock({ repo, ev }: { repo: RepoBundle; ev: Evidence }) {
+ const base = repo.host ? repo.host.replace(/\/+$/, "") : null;
+ const [all, setAll] = useState(false);
+ const commits = all ? ev.commits : ev.commits.slice(0, COMMITS_SHOWN);
+ return (
+
+
+
+
+ {ev.commits.length} {ev.commits.length === 1 ? "commit" : "commits"}
+ · {ev.role}
+
+ {!base && (
+
+ No public host: open the commits in your clone.
+
+ )}
+
+
+ {ev.commits.length > COMMITS_SHOWN && (
+
+ setAll((on) => !on)}
+ className={cn(
+ "rounded-sm font-medium text-foreground underline-offset-2 hover:underline",
+ FOCUS,
+ )}
+ >
+ {all ? `Show the first ${COMMITS_SHOWN}` : `Show all ${ev.commits.length} commits`}
+
+
+ )}
+
+ );
+}
diff --git a/web/src/components/cx/code-highlight.ts b/web/src/components/cx/code-highlight.ts
new file mode 100644
index 00000000..ed837912
--- /dev/null
+++ b/web/src/components/cx/code-highlight.ts
@@ -0,0 +1,87 @@
+// Syntax colours for cited code (spec.md §10.5: Shiki, read-only). Shiki, the one light
+// theme and the one grammar a file needs load on demand, so the main bundle carries none of
+// them. A grammar that is unknown or fails to load leaves the text plain.
+import type { HighlighterCore, ThemedToken } from "shiki/core";
+
+const THEME = "github-light";
+
+let highlighter: Promise | null = null;
+
+function getHighlighter(): Promise {
+ highlighter ??= (async () => {
+ const [{ createHighlighterCore }, { createJavaScriptRegexEngine }, theme] = await Promise.all([
+ import("shiki/core"),
+ import("shiki/engine/javascript"),
+ import("shiki/themes/github-light.mjs"),
+ ]);
+ return createHighlighterCore({
+ themes: [theme.default],
+ langs: [],
+ engine: createJavaScriptRegexEngine(),
+ });
+ })();
+ highlighter.catch(() => {
+ highlighter = null;
+ });
+ return highlighter;
+}
+
+const cache = new Map>();
+
+/**
+ * Token lines for `lines` (1-based, inclusive) of `text`, or null to show plain text. A few
+ * lines before the range are read too, so a comment or string that starts above it is
+ * coloured correctly; only the range's own lines are returned.
+ */
+export function tokenizeRange(
+ key: string,
+ text: string,
+ language: string | null,
+ from: number,
+ to: number,
+): Promise {
+ const id = `${key}:${from}-${to}`;
+ const hit = cache.get(id);
+ if (hit) return hit;
+ const run = (async () => {
+ if (!language) return null;
+ const { bundledLanguages, bundledLanguagesAlias } = await import("shiki/langs");
+ const lang = language.toLowerCase();
+ const loader =
+ bundledLanguages[lang as keyof typeof bundledLanguages] ??
+ bundledLanguagesAlias[lang as keyof typeof bundledLanguagesAlias];
+ if (!loader) return null;
+ const core = await getHighlighter();
+ if (!core.getLoadedLanguages().includes(lang)) await core.loadLanguage(loader);
+ const all = splitLines(text);
+ const lead = Math.max(1, from - LEAD);
+ const slice = all.slice(lead - 1, to).join("\n");
+ const tokens = core.codeToTokens(slice, { lang, theme: THEME }).tokens;
+ return tokens.slice(from - lead, from - lead + (to - from + 1));
+ })();
+ cache.set(id, run);
+ run.catch(() => cache.delete(id));
+ return run;
+}
+
+/** Lines read before a range only to set up the grammar's state. */
+const LEAD = 60;
+
+export function splitLines(text: string): string[] {
+ const lines = text.split("\n");
+ if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();
+ return lines;
+}
+
+/** Inline style of one token. Shiki packs font styles into bits: 1 italic, 2 bold. */
+export function tokenStyle(token: ThemedToken): {
+ color?: string;
+ fontStyle?: string;
+ fontWeight?: number;
+} {
+ const style: { color?: string; fontStyle?: string; fontWeight?: number } = { color: token.color };
+ const font = token.fontStyle ?? 0;
+ if (font & 1) style.fontStyle = "italic";
+ if (font & 2) style.fontWeight = 600;
+ return style;
+}
diff --git a/web/src/components/cx/finding-fix.ts b/web/src/components/cx/finding-fix.ts
new file mode 100644
index 00000000..0c09e470
--- /dev/null
+++ b/web/src/components/cx/finding-fix.ts
@@ -0,0 +1,56 @@
+// What a finding proposes and what its stored simulation can be said to show (spec.md §8.5,
+// §8.7). Shared by the findings list and the finding page so both word it the same way.
+import { NO_FIX_TEXT, SIMULATION } from "../../cx/meta";
+import type { Finding, FixAction, RepoBundle, TextSource } from "../../cx/types";
+
+export interface ProposedFix {
+ text: string;
+ action: FixAction;
+ /** "ai" for job B's fix, "computed" for the template's. */
+ source: TextSource;
+}
+
+/** The fix the finding proposes, or null when it proposes none. */
+export function fixOf(f: Finding): ProposedFix | null {
+ if (f.judgement) {
+ if (f.judgement.action === "none") return null;
+ return { text: f.judgement.fixText, action: f.judgement.action, source: "ai" };
+ }
+ const c = f.computedFix;
+ if (!c || c.action === "none" || !c.text.trim()) return null;
+ return { text: c.text, action: c.action, source: "computed" };
+}
+
+/** True when the stored simulation changed the map, so the fix can be tried on it. */
+export function hasSimulatedFix(f: Finding): boolean {
+ const kind = f.simulation?.kind;
+ return (
+ fixOf(f) !== null &&
+ kind !== undefined &&
+ kind !== "not-simulated" &&
+ kind !== "nothing-changed"
+ );
+}
+
+/** One short phrase for a list row: the simulation result, or that no fix is proposed. */
+export function simulationShort(f: Finding): string {
+ if (!fixOf(f)) return NO_FIX_TEXT;
+ return SIMULATION[f.simulation?.kind ?? "not-simulated"].short;
+}
+
+/** A module id as its short grid name, or the id itself when it is not a module of the grid. */
+export function moduleLabel(repo: RepoBundle, id: string | null): string | null {
+ if (!id) return null;
+ return repo.modules.find((m) => m.id === id)?.name ?? id.replace(/^M:/, "");
+}
+
+/** The weight of one ranking input, as stored in the report, or null when not stored. */
+export function weightOf(repo: RepoBundle, key: "S" | "R" | "P"): number | null {
+ const w = repo.weights[key];
+ return typeof w === "number" ? w : null;
+}
+
+/** Every finding of the repository: the top 10, then the rest, both in stored rank order. */
+export function allFindings(repo: RepoBundle): Finding[] {
+ return [...repo.findings, ...repo.supporting];
+}
diff --git a/web/src/components/cx/finding-list-row.tsx b/web/src/components/cx/finding-list-row.tsx
new file mode 100644
index 00000000..b7712489
--- /dev/null
+++ b/web/src/components/cx/finding-list-row.tsx
@@ -0,0 +1,193 @@
+// Rows of the findings list. The top 10 use the full row: what the finding is, a short
+// excerpt of its text with where that text comes from, the simulation result, the trend and
+// the stored score. The rest use a compact row. Both are links to the finding's page.
+import { ArrowUpRight, Check } from "lucide-react";
+import { Link } from "react-router";
+import { findingPath } from "../../cx/address";
+import { ACTION, TYPE, VERDICT } from "../../cx/meta";
+import type { Finding } from "../../cx/types";
+import { AiBadge, ComputedMark } from "./badges";
+import { FOCUS, cn } from "./cn";
+import { fixOf, simulationShort } from "./finding-fix";
+import { TREND } from "./finding-row";
+import { Sparkline, markIndex } from "./sparkline";
+
+/** Backticks mark code names in stored text; an excerpt shows them as plain mono text. */
+function Excerpt({ text, className }: { text: string; className?: string }) {
+ const parts = text.split(/(`[^`]+`)/g);
+ return (
+
+ {parts.map((p, i) =>
+ p.startsWith("`") ? (
+
+ {p.slice(1, -1)}
+
+ ) : (
+ {p}
+ ),
+ )}
+
+ );
+}
+
+/** "Legitimate wiring" is shown as its own outlined badge; it never moves the finding. */
+export function LegitimateBadge({ className }: { className?: string }) {
+ return (
+
+
+ {VERDICT.legitimate_wiring}
+
+ );
+}
+
+/** The verdict chip with its AI badge, or the computed mark when there is no AI reading. */
+export function VerdictMark({ f }: { f: Finding }) {
+ if (!f.judgement) return ;
+ return (
+
+ {f.judgement.verdict === "legitimate_wiring" ? (
+
+ ) : (
+
+ {VERDICT[f.judgement.verdict]}
+
+ )}
+
+
+ );
+}
+
+export function FindingListRow({
+ repoId,
+ f,
+ sponsorDate,
+}: {
+ repoId: string;
+ f: Finding;
+ /** The date marked on the trend sparkline. */
+ sponsorDate: string | null;
+}) {
+ const t = TREND[f.trend.status];
+ const series = f.trend.series;
+ const fix = fixOf(f);
+ return (
+
+
+
+ {f.rank}
+
+
+
+
+ {TYPE[f.type].label}
+
+
+
+ {t.label}
+
+
+
{f.title}
+
+ {f.judgement ? (
+ <>
+
+
+ >
+ ) : (
+ <>
+
+
+ >
+ )}
+
+
+ {fix ? <>{ACTION[fix.action]} · > : null}
+ {simulationShort(f)}
+
+
+
+ p.value)}
+ mark={markIndex(
+ series.map((p) => p.date),
+ sponsorDate,
+ )}
+ width={96}
+ height={24}
+ color="var(--accent)"
+ label={`Trend for finding ${f.rank}`}
+ />
+
+
+
+
+ {f.priority.score.toFixed(2)}
+
+
+
+
+
+ );
+}
+
+/** One line per finding below the top 10: rank, type, title, verdict and score. */
+export function FindingCompactRow({ repoId, f }: { repoId: string; f: Finding }) {
+ return (
+
+
+
+ {f.rank}
+
+
+ {TYPE[f.type].label}
+
+
+
+ {f.title}
+
+ {f.judgement?.verdict === "legitimate_wiring" && (
+
+
+
+
+ )}
+
+
+ {f.priority.score.toFixed(2)}
+
+
+
+ );
+}
diff --git a/web/src/components/cx/finding-row.tsx b/web/src/components/cx/finding-row.tsx
new file mode 100644
index 00000000..695e397d
--- /dev/null
+++ b/web/src/components/cx/finding-row.tsx
@@ -0,0 +1,103 @@
+import { ArrowUpRight } from "lucide-react";
+import { Link } from "react-router";
+import { findingPath } from "../../cx/address";
+import { STATUS, TYPE, VERDICT } from "../../cx/meta";
+import type { Finding } from "../../cx/types";
+import { AiBadge, ComputedMark } from "./badges";
+import { FOCUS, cn } from "./cn";
+import { Sparkline, markIndex } from "./sparkline";
+
+export const TREND: Record<
+ Finding["trend"]["status"],
+ { label: string; cls: string; color?: string }
+> = {
+ new_since_2025_03: { label: "new since Mar 2025", cls: "text-accent" },
+ worse: { label: "getting worse", cls: "text-accent" },
+ better: { label: "improving", cls: "", color: STATUS.holding.color },
+ unchanged: { label: "unchanged", cls: "text-muted-foreground" },
+};
+
+/**
+ * One ranked finding as a link to its detail page. The verdict chip appears only for an AI
+ * judgement and carries the AI badge; without one the row is marked computed.
+ */
+export function FindingRow({
+ repoId,
+ f,
+ sponsorDate,
+}: {
+ repoId: string;
+ f: Finding;
+ /** The date marked on the trend sparkline. */
+ sponsorDate: string | null;
+}) {
+ const t = TREND[f.trend.status];
+ const series = f.trend.series;
+ return (
+
+
+
+ {f.rank}
+
+
+
+
+ {TYPE[f.type].label}
+
+ {f.judgement ? (
+
+
+ {VERDICT[f.judgement.verdict]}
+
+
+
+ ) : (
+
+ )}
+
+ {t.label}
+
+
+
{f.title}
+
+
+ p.value)}
+ mark={markIndex(
+ series.map((p) => p.date),
+ sponsorDate,
+ )}
+ width={96}
+ height={24}
+ color="var(--accent)"
+ label={`Trend for finding ${f.rank}`}
+ />
+
+
+
+
+ {f.priority.score.toFixed(2)}
+
+
+
+
+
+ );
+}
diff --git a/web/src/components/cx/journeys.tsx b/web/src/components/cx/journeys.tsx
new file mode 100644
index 00000000..ec07f89f
--- /dev/null
+++ b/web/src/components/cx/journeys.tsx
@@ -0,0 +1,584 @@
+// The journey player: one user action drawn as a line across the layers of the codebase. A dip
+// means the request goes down into core code, a rise means the result comes back up. Plain SVG
+// and CSS; the only animation is a small packet travelling along the edge being played.
+import { ChevronLeft, ChevronRight, Pause, Play } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { Link } from "react-router";
+import { findingPath } from "../../cx/address";
+import { TYPE } from "../../cx/meta";
+import type { RepoBundle } from "../../cx/types";
+import type { Journey, JourneyBundle, JourneyStop } from "../../data/journeys";
+import { FOCUS, cn } from "./cn";
+import { allFindings } from "./finding-fix";
+
+const W = 1000;
+const X0 = 190;
+const X1 = 950;
+const LANE_H = 72;
+
+/** How long the packet takes along one edge, and how long a stop stays open while playing. */
+const TRAVEL_MS = 1000;
+const DWELL_MS = 1900;
+
+const VIA_TEXT: Record = {
+ call: "method call",
+ queue: "queue, handled later",
+ ws: "pushed to the browser",
+ find: "step that is a ranked finding",
+};
+
+function reducedMotion(): boolean {
+ return (
+ typeof window !== "undefined" &&
+ !!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches
+ );
+}
+
+/** "A student pushes code for a programming exercise" → "Student pushes code". */
+function shortName(name: string): string {
+ const s = name.replace(/^(An?|The) /, "").replace(/ for .*$/, "");
+ return s.charAt(0).toUpperCase() + s.slice(1);
+}
+
+type Pt = { x: number; y: number };
+
+function edgePath(a: Pt, b: Pt): string {
+ const mx = (a.x + b.x) / 2;
+ return `M${a.x},${a.y} C${mx},${a.y} ${mx},${b.y} ${b.x},${b.y}`;
+}
+
+function edgeKind(s: JourneyStop): "call" | "queue" | "ws" | "find" {
+ if (s.findingRank) return "find";
+ return s.via?.kind ?? "call";
+}
+
+const EDGE_STYLE: Record =
+ {
+ call: { stroke: "var(--grain)", width: 2.5 },
+ queue: { stroke: "var(--foreground)", dash: "7 5", width: 2.5 },
+ ws: { stroke: "var(--grain)", dash: "2 5", width: 2.5, cap: "round" },
+ // A finding step is drawn heavier; vermilion only when the finding is code against a decision.
+ find: { stroke: "var(--foreground)", width: 4 },
+ against: { stroke: "var(--against)", width: 4 },
+ };
+
+// ---- the wave ---------------------------------------------------------------------------
+
+function Wave({
+ lanes,
+ journey,
+ idx,
+ travelling,
+ onPick,
+ against = new Set(),
+ compact = false,
+}: {
+ lanes: string[];
+ journey: Journey;
+ idx: number;
+ /** The edge the packet is on, or null. */
+ travelling: number | null;
+ onPick?: (i: number) => void;
+ /** Ranks of findings that are code against a decision. */
+ against?: Set;
+ compact?: boolean;
+}) {
+ const stops = journey.stops;
+ const n = stops.length;
+ // The still preview packs the lanes closer so the drawing stays short on the report page.
+ const laneH = compact ? 50 : LANE_H;
+ const laneY = (i: number) => (compact ? 54 : 46) + i * laneH;
+ const pts = stops.map((s, i) => ({
+ x: X0 + (i * (X1 - X0)) / Math.max(1, n - 1),
+ y: laneY(s.lane),
+ }));
+ const H = laneY(lanes.length - 1) + (compact ? 46 : 54);
+ const pathRefs = useRef<(SVGPathElement | null)[]>([]);
+ const packet = useRef(null);
+
+ // Moves the packet along the edge being played.
+ useEffect(() => {
+ const g = packet.current;
+ if (!g) return;
+ if (travelling === null || reducedMotion()) {
+ g.style.opacity = "0";
+ return;
+ }
+ const path = pathRefs.current[travelling];
+ if (!path) return;
+ const len = path.getTotalLength();
+ const start = performance.now();
+ let raf = 0;
+ g.style.opacity = "1";
+ const step = (now: number) => {
+ const k = Math.min(1, (now - start) / TRAVEL_MS);
+ const e = k < 0.5 ? 2 * k * k : 1 - Math.pow(-2 * k + 2, 2) / 2;
+ const p = path.getPointAtLength(len * e);
+ g.setAttribute("transform", `translate(${p.x},${p.y})`);
+ if (k < 1) raf = requestAnimationFrame(step);
+ else g.style.opacity = "0";
+ };
+ raf = requestAnimationFrame(step);
+ return () => cancelAnimationFrame(raf);
+ }, [travelling]);
+
+ const label = travelling !== null ? (stops[travelling + 1]?.payload.type ?? "") : "";
+
+ return (
+
+ {lanes.map((l, i) => (
+
+ {i % 2 === 0 && (
+
+ )}
+
+
+ {l}
+
+
+ ))}
+ {pts.slice(1).map((b, i) => {
+ const next = stops[i + 1];
+ const kind = next.findingRank && against.has(next.findingRank) ? "against" : edgeKind(next);
+ const st = EDGE_STYLE[kind];
+ const future = i >= idx && travelling !== i;
+ return (
+ {
+ pathRefs.current[i] = el;
+ }}
+ d={edgePath(pts[i], b)}
+ fill="none"
+ stroke={st.stroke}
+ strokeWidth={st.width}
+ strokeDasharray={st.dash}
+ strokeLinecap={st.cap}
+ className="transition-opacity duration-300"
+ opacity={future ? 0.2 : 1}
+ />
+ );
+ })}
+ {stops.map((s, i) => {
+ const p = pts[i];
+ const up = i % 2 === 0;
+ const on = i === idx && travelling === null;
+ const future = i > idx;
+ const flag = !!s.findingRank;
+ const flagColor =
+ s.findingRank && against.has(s.findingRank) ? "var(--against)" : "var(--foreground)";
+ return (
+ onPick(i) : undefined}
+ onKeyDown={
+ onPick
+ ? (e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ onPick(i);
+ }
+ }
+ : undefined
+ }
+ className={cn("group outline-none", onPick && "cursor-pointer")}
+ opacity={future ? 0.45 : 1}
+ >
+
+
+
+ {s.module}
+
+
+ {s.label}
+
+
+ );
+ })}
+
+
+
+ {label}
+
+
+
+
+ );
+}
+
+function Legend() {
+ return (
+
+ {Object.entries(VIA_TEXT).map(([k, text]) => {
+ const st = EDGE_STYLE[k];
+ return (
+
+
+
+
+ {text}
+
+ );
+ })}
+
+ );
+}
+
+// ---- the stop detail --------------------------------------------------------------------
+
+function Payload({ stop, prev }: { stop: JourneyStop; prev: JourneyStop | null }) {
+ const before = new Set((prev?.payload.fields ?? []).map((f) => f.key));
+ return (
+
+
+ {stop.payload.type}
+
+ {stop.payload.definedIn}
+
+
+
+ {"{"}
+ {stop.payload.fields.map((f) => {
+ const added = prev !== null && !before.has(f.key);
+ return (
+
+ {" "}
+ {f.key}
+ :
+ {f.value}
+
+ );
+ })}
+ {"}"}
+
+
+ {prev ? "Highlighted fields are new at this stop. " : ""}Values are an example request.
+
+
+ );
+}
+
+function StopDetail({
+ repo,
+ lanes,
+ journey,
+ idx,
+}: {
+ repo: RepoBundle;
+ lanes: string[];
+ journey: Journey;
+ idx: number;
+}) {
+ const s = journey.stops[idx];
+ const prev = idx > 0 ? journey.stops[idx - 1] : null;
+ const finding = s.findingRank
+ ? allFindings(repo).find((f) => f.rank === s.findingRank)
+ : undefined;
+ return (
+
+
+
+ Stop {idx + 1} of {journey.stops.length}
+ /
+ {lanes[s.lane]}
+
+
{s.caption}
+
+ {s.file}
+
+ {s.method}
+
+
+
+ {s.via ? (
+ <>
+ Arrived by {s.via.label}
+ {prev && (
+ <>
+ {" "}
+ from {prev.module}
+ >
+ )}
+ >
+ ) : (
+ "Start of the journey"
+ )}
+
+ {finding && (
+
+
#{finding.rank}
+
+ {finding.title}
+
+ Open the finding, its graph and its code
+
+
+
+ )}
+
+
+
+ );
+}
+
+// ---- the player -------------------------------------------------------------------------
+
+const ctlBase =
+ "inline-flex h-8 min-w-8 items-center justify-center gap-1.5 rounded-md border px-2.5 font-mono text-xs transition-colors disabled:opacity-40";
+const ctl = cn(ctlBase, "bg-card hover:bg-muted", FOCUS);
+const ctlPrimary = cn(
+ ctlBase,
+ "border-foreground bg-foreground px-3 text-background hover:bg-foreground/85",
+ FOCUS,
+);
+
+export function JourneyPlayer({
+ repo,
+ bundle,
+ start,
+}: {
+ repo: RepoBundle;
+ bundle: JourneyBundle;
+ /** The journey id and 0-based stop to open first, from the address. */
+ start?: { journey: string | null; stop: number };
+}) {
+ const startJ = Math.max(
+ 0,
+ bundle.journeys.findIndex((j) => j.id === start?.journey),
+ );
+ const [jIdx, setJIdx] = useState(startJ);
+ const [idx, setIdx] = useState(() =>
+ Math.max(0, Math.min(bundle.journeys[startJ].stops.length - 1, start?.stop ?? 0)),
+ );
+ const [playing, setPlaying] = useState(false);
+ const [travelling, setTravelling] = useState(null);
+ const journey = bundle.journeys[jIdx];
+ const last = journey.stops.length - 1;
+
+ const stop = useCallback(() => {
+ setPlaying(false);
+ setTravelling(null);
+ }, []);
+ const go = useCallback(
+ (i: number) => {
+ stop();
+ setIdx(Math.max(0, Math.min(last, i)));
+ },
+ [last, stop],
+ );
+
+ // While playing: travel one edge, open the stop it reaches, stay there a moment, repeat.
+ useEffect(() => {
+ if (!playing) return;
+ if (travelling === null) {
+ if (idx >= last) {
+ setPlaying(false);
+ return;
+ }
+ const t = window.setTimeout(() => setTravelling(idx), DWELL_MS);
+ return () => window.clearTimeout(t);
+ }
+ const t = window.setTimeout(
+ () => {
+ setTravelling(null);
+ setIdx(travelling + 1);
+ },
+ reducedMotion() ? 0 : TRAVEL_MS,
+ );
+ return () => window.clearTimeout(t);
+ }, [playing, travelling, idx, last]);
+
+ const togglePlay = () => {
+ if (playing) return stop();
+ const from = idx >= last ? 0 : idx;
+ setIdx(from);
+ setPlaying(true);
+ setTravelling(from);
+ };
+
+ const onKey = (e: React.KeyboardEvent) => {
+ if ((e.target as HTMLElement).tagName === "BUTTON" && e.key === " ") return;
+ if (e.key === "ArrowRight") go(idx + 1);
+ else if (e.key === "ArrowLeft") go(idx - 1);
+ };
+
+ const modules = useMemo(() => new Set(journey.stops.map((s) => s.module)).size, [journey]);
+ const findingSteps = journey.stops.filter((s) =>
+ allFindings(repo).some((f) => f.rank === s.findingRank),
+ ).length;
+ const against = useMemo(
+ () =>
+ new Set(
+ allFindings(repo)
+ .filter((f) => TYPE[f.type].group === "Decision exception")
+ .map((f) => f.rank),
+ ),
+ [repo],
+ );
+
+ return (
+
+
+
+ {bundle.journeys.map((j, i) => (
+ {
+ stop();
+ setJIdx(i);
+ setIdx(0);
+ }}
+ className={cn(
+ "rounded-[5px] px-2.5 py-1 text-[13px] transition-colors",
+ i === jIdx
+ ? "bg-foreground text-background"
+ : "text-muted-foreground hover:text-foreground",
+ FOCUS,
+ )}
+ >
+ {shortName(j.name)}
+
+ ))}
+
+
+
go(idx - 1)}
+ disabled={idx === 0}
+ aria-label="Previous stop"
+ >
+
+
+
+ {playing ? (
+
+ ) : (
+
+ )}
+ {playing ? "Pause" : "Play"}
+
+
go(idx + 1)}
+ disabled={idx === last}
+ aria-label="Next stop"
+ >
+
+
+
+
+
+
{journey.name}
+
+ {journey.stops.length} stops through {modules} modules
+ {findingSteps > 0 &&
+ `, ${findingSteps} ${findingSteps === 1 ? "step is a ranked finding" : "steps are ranked findings"}`}
+ .
+
+
+
+
+
+
+
+
+
+
+ );
+}
+
+/** A still drawing of one journey for the report page. */
+export function JourneyPreview({ bundle, journey }: { bundle: JourneyBundle; journey: Journey }) {
+ return (
+
+ );
+}
diff --git a/web/src/components/cx/map-controls.tsx b/web/src/components/cx/map-controls.tsx
new file mode 100644
index 00000000..474be24b
--- /dev/null
+++ b/web/src/components/cx/map-controls.tsx
@@ -0,0 +1,247 @@
+// The parts the Map and the Overview's small grid share: the date switch, the stored
+// numbers beside it, and the legend. The numbers are stored yardsticks or the stored batch
+// result, never a count of the cells on screen.
+import { type KeyboardEvent, useRef } from "react";
+import type { MapView } from "../../cx/address";
+import { fmt, pct } from "../../cx/meta";
+import type { Finding, RepoBundle, Yardstick } from "../../cx/types";
+import { FOCUS, cn } from "./cn";
+
+export const GRID_ORDER_NOTE =
+ "Every view keeps the same module order so squares line up between dates. The totals above use each date's own order, so they can differ slightly from the squares.";
+
+export function viewLabel(repo: RepoBundle, view: MapView): string {
+ if (view === "before") return `Before · ${repo.beforeDate.slice(0, 7)}`;
+ if (view === "now") return "Now";
+ if (!repo.batch) return "After fixes";
+ const n = repo.batch.fixesApplied;
+ return `After ${fmt(n)} ${n === 1 ? "fix" : "fixes"}`;
+}
+
+/** The date switch. `view` null means none is shown, for example while a fix is tried. */
+export function ViewToggle({
+ repo,
+ view,
+ onView,
+ small = false,
+}: {
+ repo: RepoBundle;
+ view: MapView | null;
+ onView: (view: MapView) => void;
+ small?: boolean;
+}) {
+ const refs = useRef<(HTMLButtonElement | null)[]>([]);
+ const views: MapView[] = ["before", "now", "after"];
+ const enabled = (v: MapView) => v !== "after" || repo.batch !== null;
+ const onKey = (event: KeyboardEvent) => {
+ const step =
+ event.key === "ArrowRight" || event.key === "ArrowDown"
+ ? 1
+ : event.key === "ArrowLeft" || event.key === "ArrowUp"
+ ? -1
+ : 0;
+ if (!step) return;
+ event.preventDefault();
+ const usable = views.filter(enabled);
+ const at = usable.indexOf(view ?? "now");
+ const next = usable[(at + step + usable.length) % usable.length]!;
+ onView(next);
+ refs.current[views.indexOf(next)]?.focus();
+ };
+ return (
+
+
+ {views.map((v, k) => {
+ const on = view === v;
+ const usable = enabled(v);
+ return (
+ {
+ refs.current[k] = el;
+ }}
+ type="button"
+ role="radio"
+ aria-checked={on}
+ aria-disabled={!usable || undefined}
+ disabled={!usable}
+ tabIndex={on || (view === null && v === "now") ? 0 : -1}
+ title={usable ? undefined : "Not simulated in this run"}
+ onClick={() => usable && onView(v)}
+ className={cn(
+ "rounded-[4px] px-2.5 py-1 whitespace-nowrap transition-colors",
+ on
+ ? "bg-foreground text-background"
+ : usable
+ ? "text-muted-foreground hover:text-foreground"
+ : "cursor-not-allowed text-muted-foreground/50",
+ FOCUS,
+ )}
+ >
+ {viewLabel(repo, v)}
+
+ );
+ })}
+
+ {!repo.batch && (
+
+ after fixes: not simulated in this run
+
+ )}
+
+ );
+}
+
+const at = (y: Yardstick, view: "before" | "now") => (view === "before" ? y.before : y.now);
+
+/**
+ * The stored numbers for the view: the yardsticks at the end snapshot or at the before
+ * date; for the fix batch and a tried fix, the simulation's own loop counts. A value the
+ * bundle does not hold is left out.
+ */
+export function GridNumbers({
+ repo,
+ view,
+ fix,
+ small = false,
+}: {
+ repo: RepoBundle;
+ view: MapView;
+ fix?: Finding | null;
+ small?: boolean;
+}) {
+ const y = repo.yardsticks;
+ const cls = cn("flex flex-wrap gap-x-5 gap-y-1 font-mono", small ? "text-[11px]" : "text-xs");
+ if (fix?.simulation) {
+ const s = fix.simulation;
+ if (s.loopsBefore === null || s.loopsAfter === null) return null;
+ return (
+
+
+
module loops in this simulation
+
+ {fmt(s.loopsBefore)} → {fmt(s.loopsAfter)}
+
+
+
+ );
+ }
+ if (view === "after") {
+ const b = repo.batch;
+ if (!b) return null;
+ return (
+
+
+
module loops, before and after the fixes
+
+ {fmt(b.loopsBefore)} → {fmt(b.loopsAfter)}
+
+
+
+ );
+ }
+ const share = at(y.againstGrainShare, view);
+ const links = at(y.againstGrain, view);
+ const pairs = at(y.twoWayPairs, view);
+ if (share === null && pairs === null) return null;
+ return (
+
+ {share !== null && (
+
+
backward links
+
+ {pct(share)}
+ {!small && links !== null && (
+ · {fmt(links)} links
+ )}
+
+
+ )}
+ {pairs !== null && (
+
+
two-way dependencies
+ {fmt(pairs)}
+
+ )}
+
+ );
+}
+
+/** The legend; always shown with the grid (spec.md §10.3). */
+export function MapLegend({
+ changed = false,
+ emphasis = false,
+ beforeOnly = false,
+ small = false,
+}: {
+ changed?: boolean;
+ emphasis?: boolean;
+ beforeOnly?: boolean;
+ small?: boolean;
+}) {
+ return (
+
+
+ forward link
+
+
+ backward link
+
+
+
+
+
+
+ deeper = more links
+
+
+ in
+ a top-10 finding
+
+ {emphasis && (
+
+ {" "}
+ in this finding
+
+ )}
+ {changed && (
+
+ {" "}
+ changed by the simulation
+
+ )}
+ {beforeOnly && (
+
+
+ name
+ {" "}
+ only at the before date
+
+ )}
+
+ );
+}
diff --git a/web/src/components/cx/map-model.ts b/web/src/components/cx/map-model.ts
new file mode 100644
index 00000000..46f3f800
--- /dev/null
+++ b/web/src/components/cx/map-model.ts
@@ -0,0 +1,155 @@
+// What the module grid draws for each view, built from stored values only. Nothing here
+// counts links or recomputes a yardstick; it only places stored counts in the grid order.
+import { applyCellChanges } from "../../cx/grid";
+import type { CellChange, Finding, RepoBundle } from "../../cx/types";
+
+/** A cell's place in a grid of `n` modules, as one number: row × n + column. */
+export const cellIndex = (n: number, i: number, j: number): number => i * n + j;
+
+/** One stored cell change, placed on the grid where both modules are on it. */
+export interface PlacedChange extends CellChange {
+ /** Row and column in the grid order; null when the module is not on the grid. */
+ i: number | null;
+ j: number | null;
+ /** The grid's own count for the cell now; null when the cell is not on the grid. */
+ gridCount: number | null;
+}
+
+export interface GridPicture {
+ /** The counts the cells are coloured by. */
+ values: number[][];
+ /** True when `values` holds stored after-counts instead of the Now counts. */
+ redrawn: boolean;
+ /** On-grid cells a change touches, by `cellIndex`. */
+ changed: Map;
+ /** Every stored change, in stored order, for listing. */
+ changes: PlacedChange[];
+}
+
+export function placeChanges(repo: RepoBundle, changes: readonly CellChange[]): PlacedChange[] {
+ const index = moduleIndex(repo);
+ return changes.map((c) => {
+ const i = index.get(c.src) ?? null;
+ const j = index.get(c.dst) ?? null;
+ return { ...c, i, j, gridCount: i !== null && j !== null ? repo.matrix[i]![j]! : null };
+ });
+}
+
+const indexCache = new WeakMap>();
+
+/** Module id to its place in the grid order. */
+export function moduleIndex(repo: RepoBundle): Map {
+ let index = indexCache.get(repo);
+ if (!index) {
+ index = new Map(repo.modules.map((m, i) => [m.id, i]));
+ indexCache.set(repo, index);
+ }
+ return index;
+}
+
+function changedMap(n: number, placed: readonly PlacedChange[]) {
+ const out = new Map();
+ for (const c of placed) {
+ if (c.i === null || c.j === null) continue;
+ out.set(cellIndex(n, c.i, c.j), { before: c.before, after: c.after });
+ }
+ return out;
+}
+
+export type PictureMode =
+ { kind: "before" } | { kind: "now" } | { kind: "after" } | { kind: "fix"; finding: Finding };
+
+/**
+ * The grid for one view. The after-fixes view and a tried fix recolour the grid only when
+ * the stored change counts start from the grid's own counts (`onGrid`); otherwise the Now
+ * colours stay and the changes are only outlined and listed.
+ */
+export function pictureFor(repo: RepoBundle, mode: PictureMode): GridPicture {
+ const n = repo.modules.length;
+ if (mode.kind === "before") {
+ return { values: repo.matrixBefore, redrawn: false, changed: new Map(), changes: [] };
+ }
+ if (mode.kind === "after" && repo.batch) {
+ const changes = placeChanges(repo, repo.batch.cellChanges);
+ const redrawn = repo.matrixFixed !== null;
+ return {
+ values: repo.matrixFixed ?? repo.matrix,
+ redrawn,
+ changed: changedMap(n, changes),
+ changes,
+ };
+ }
+ if (mode.kind === "fix" && mode.finding.simulation?.simulated) {
+ const sim = mode.finding.simulation;
+ const changes = placeChanges(repo, sim.cellChanges);
+ const ids = repo.modules.map((m) => m.id);
+ return {
+ values: sim.onGrid ? applyCellChanges(repo.matrix, ids, sim.cellChanges) : repo.matrix,
+ redrawn: sim.onGrid,
+ changed: changedMap(n, changes),
+ changes,
+ };
+ }
+ return { values: repo.matrix, redrawn: false, changed: new Map(), changes: [] };
+}
+
+const maxCache = new WeakMap();
+
+/**
+ * The largest count over every grid the Map can show, so one colour means the same number
+ * of links in every view.
+ */
+export function gridMax(repo: RepoBundle): number {
+ let max = maxCache.get(repo);
+ if (max === undefined) {
+ max = 1;
+ for (const m of [repo.matrix, repo.matrixBefore, repo.matrixFixed]) {
+ if (!m) continue;
+ for (const row of m) for (const v of row) if (v > max) max = v;
+ }
+ maxCache.set(repo, max);
+ }
+ return max;
+}
+
+/**
+ * Cells of the ten top-ranked findings, by `cellIndex`, each with the best-ranked finding
+ * it belongs to.
+ */
+export function topFindingCells(repo: RepoBundle): Map {
+ const n = repo.modules.length;
+ const index = moduleIndex(repo);
+ const out = new Map();
+ for (const f of repo.findings) {
+ for (const [src, dst] of f.cells) {
+ const i = index.get(src);
+ const j = index.get(dst);
+ if (i === undefined || j === undefined) continue;
+ const key = cellIndex(n, i, j);
+ const held = out.get(key);
+ if (!held || f.rank < held.rank) out.set(key, f);
+ }
+ }
+ return out;
+}
+
+/** The finding with this slug, among the top ten and the supporting ones. */
+export function findingBySlug(repo: RepoBundle, slug: string | null): Finding | null {
+ if (!slug) return null;
+ return (
+ repo.findings.find((f) => f.slug === slug) ??
+ repo.supporting.find((f) => f.slug === slug) ??
+ null
+ );
+}
+
+/** How many changed cells cannot be drawn on the grid, and why, from stored counts. */
+export function offGridCounts(changes: readonly PlacedChange[]) {
+ let notOnGrid = 0;
+ let otherCount = 0;
+ for (const c of changes) {
+ if (c.gridCount === null) notOnGrid++;
+ else if (c.gridCount !== c.before) otherCount++;
+ }
+ return { total: changes.length, notOnGrid, otherCount };
+}
diff --git a/web/src/components/cx/matrix.tsx b/web/src/components/cx/matrix.tsx
new file mode 100644
index 00000000..57effd3c
--- /dev/null
+++ b/web/src/components/cx/matrix.tsx
@@ -0,0 +1,901 @@
+// The module grid (spec.md §10.2 screen 2, §10.5): rows use columns, foundations last, so
+// links with the grain sit above the diagonal and links against it below. Up to 22,000
+// cells, so the cells are drawn on a canvas; labels, focus, selection and the tooltip are
+// small DOM layers on top, and the keyboard moves one active cell that screen readers read
+// through `aria-activedescendant`.
+import {
+ type KeyboardEvent,
+ type MouseEvent,
+ type ReactNode,
+ memo,
+ useCallback,
+ useEffect,
+ useId,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
+import { fmt } from "../../cx/meta";
+import type { ModuleInfo } from "../../cx/types";
+import { FOCUS, cn } from "./cn";
+import { cellIndex } from "./map-model";
+
+export type Cell = [number, number];
+type Density = "fit" | "names";
+
+export interface MatrixProps {
+ modules: ModuleInfo[];
+ /** Counts to colour by, rows use columns, in `modules` order. */
+ values: number[][];
+ /** The count that gets the strongest colour; shared by every view. */
+ max: number;
+ /** Cells of the top findings, by `cellIndex`: outlined. */
+ flagged: ReadonlySet;
+ /** Cells of one finding to bring forward; everything else is dimmed. */
+ emphasis?: ReadonlySet | null;
+ /** Cells a stored change touches, by `cellIndex`: dashed outline. */
+ changed?: ReadonlyMap | null;
+ /** How a change's two counts are named in the tooltip, for example "in the simulation". */
+ changeSource?: string;
+ selected: Cell | null;
+ onSelect: (cell: Cell | null) => void;
+ /** A module whose row and column are highlighted. */
+ picked?: number | null;
+ compact?: boolean;
+ /** The grid's accessible name, for example "Module grid at 2025-03-01". */
+ label: string;
+ /** Shown to the right of the hint line under the grid (the legend). */
+ footer?: ReactNode;
+}
+
+// Sizes in CSS pixels.
+const NAMES_LABEL_W = 176;
+const NUMBER_LABEL_W = 34;
+const HEAD_H = 22;
+const COMPACT_HEAD_H = 14;
+const NAMES_MIN_CELL = 12;
+const FIT_MIN_CELL = 4;
+const COMPACT_MIN_CELL = 3;
+const MAX_CELL = 36;
+const COMPACT_MAX_CELL = 26;
+
+function token(name: string, fallback: string): string {
+ const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
+ return value || fallback;
+}
+
+const pad2 = (i: number, n: number) => String(i + 1).padStart(n >= 100 ? 3 : 2, "0");
+
+/** Every k-th axis number, so numbers of `digits` characters do not overlap. */
+const numberStep = (cell: number, digits: number, font: number) =>
+ Math.max(1, Math.ceil((digits * font * 0.62 + 3) / cell));
+
+function times(v: number): string {
+ return v === 1 ? "1 time" : `${fmt(v)} times`;
+}
+
+/** The accessible name of one cell, with full module paths. */
+export function cellName(
+ modules: ModuleInfo[],
+ values: number[][],
+ [i, j]: Cell,
+ change?: { before: number; after: number },
+ changeSource = "",
+): string {
+ const src = modules[i]!;
+ const dst = modules[j]!;
+ const only = (m: ModuleInfo) => (m.presentAtEnd ? "" : " (exists only at the before date)");
+ if (i === j) return `${src.path}${only(src)}, the module itself`;
+ const v = values[i]![j]!;
+ const head = `${src.path}${only(src)} uses ${dst.path}${only(dst)}`;
+ const body =
+ v === 0 ? `${head}, no links` : `${head} ${times(v)}, ${i > j ? "backward" : "forward"}`;
+ return change
+ ? `${body}; ${fmt(change.before)} to ${fmt(change.after)} links ${changeSource}`.trim()
+ : body;
+}
+
+export function Matrix({
+ modules,
+ values,
+ max,
+ flagged,
+ emphasis,
+ changed,
+ changeSource = "",
+ selected,
+ onSelect,
+ picked = null,
+ compact = false,
+ label,
+ footer,
+}: MatrixProps) {
+ const n = modules.length;
+ const baseId = useId();
+ const boxRef = useRef(null);
+ const scrollRef = useRef(null);
+ const canvasRef = useRef(null);
+ const [width, setWidth] = useState(0);
+ const [hover, setHover] = useState(null);
+ const [active, setActive] = useState(selected);
+ const [focused, setFocused] = useState(false);
+ const [choice, setChoice] = useState(null);
+
+ useLayoutEffect(() => {
+ const element = boxRef.current;
+ if (!element) return;
+ setWidth(Math.floor(element.clientWidth));
+ if (typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(([entry]) => {
+ if (entry) setWidth(Math.floor(entry.contentRect.width));
+ });
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, []);
+
+ // Names on the axis need 12 px rows; when they do not fit, the grid fits its panel and
+ // the axis shows numbers, unless the reader asks for names.
+ const namesFit = n * NAMES_MIN_CELL + NAMES_LABEL_W <= width;
+ const density: Density = compact ? "fit" : (choice ?? (namesFit ? "names" : "fit"));
+ const labelW = compact ? 0 : density === "names" ? NAMES_LABEL_W : NUMBER_LABEL_W;
+ const headH = compact ? COMPACT_HEAD_H : HEAD_H;
+ const room = Math.max(0, width - labelW);
+ const fitted = n > 0 ? Math.floor(room / n) : MAX_CELL;
+ const cell = compact
+ ? Math.max(COMPACT_MIN_CELL, Math.min(COMPACT_MAX_CELL, fitted))
+ : Math.max(density === "names" ? NAMES_MIN_CELL : FIT_MIN_CELL, Math.min(MAX_CELL, fitted));
+ const side = n * cell;
+
+ // Follow a selection made outside, such as from the address bar.
+ useEffect(() => {
+ if (selected) setActive(selected);
+ }, [selected?.[0], selected?.[1]]);
+
+ // Draw only when what is drawn changes; hover and focus never redraw the canvas.
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ const ctx = canvas?.getContext?.("2d");
+ if (!canvas || !ctx || width === 0) return;
+ const ratio = window.devicePixelRatio || 1;
+ canvas.width = Math.round(side * ratio);
+ canvas.height = Math.round(side * ratio);
+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
+ drawGrid(ctx, { values, n, cell, max, flagged, emphasis, changed });
+ }, [values, n, cell, side, max, flagged, emphasis, changed, width]);
+
+ const reveal = useCallback(
+ ([i, j]: Cell) => {
+ const box = scrollRef.current;
+ if (!box) return;
+ const x = labelW + j * cell;
+ const y = headH + i * cell;
+ if (x < box.scrollLeft + labelW) box.scrollLeft = x - labelW - cell;
+ else if (x + cell > box.scrollLeft + box.clientWidth)
+ box.scrollLeft = x + 2 * cell - box.clientWidth;
+ if (y < box.scrollTop + headH) box.scrollTop = y - headH - cell;
+ else if (y + cell > box.scrollTop + box.clientHeight)
+ box.scrollTop = y + 2 * cell - box.clientHeight;
+ },
+ [labelW, headH, cell],
+ );
+
+ // Bring a selection from the address bar into the panel's view once the size is known.
+ useEffect(() => {
+ if (selected && width > 0) reveal(selected);
+ }, [width > 0, density]);
+
+ const cellAt = (event: MouseEvent): Cell | null => {
+ const rect = event.currentTarget.getBoundingClientRect();
+ const j = Math.floor((event.clientX - rect.left) / cell);
+ const i = Math.floor((event.clientY - rect.top) / cell);
+ return i >= 0 && j >= 0 && i < n && j < n ? [i, j] : null;
+ };
+
+ const onMove = (event: MouseEvent) => {
+ const at = cellAt(event);
+ if (at?.[0] !== hover?.[0] || at?.[1] !== hover?.[1]) setHover(at);
+ };
+
+ const onKey = (event: KeyboardEvent) => {
+ if (n === 0) return;
+ const [i, j] = active ?? [0, 0];
+ let next: Cell | null = null;
+ switch (event.key) {
+ case "ArrowUp":
+ next = [Math.max(0, i - 1), j];
+ break;
+ case "ArrowDown":
+ next = [Math.min(n - 1, i + 1), j];
+ break;
+ case "ArrowLeft":
+ next = [i, Math.max(0, j - 1)];
+ break;
+ case "ArrowRight":
+ next = [i, Math.min(n - 1, j + 1)];
+ break;
+ case "Home":
+ next = [i, 0];
+ break;
+ case "End":
+ next = [i, n - 1];
+ break;
+ case "PageUp":
+ next = [Math.max(0, i - 10), j];
+ break;
+ case "PageDown":
+ next = [Math.min(n - 1, i + 10), j];
+ break;
+ case "Enter":
+ case " ":
+ event.preventDefault();
+ onSelect([i, j]);
+ return;
+ case "Escape":
+ if (selected) {
+ event.preventDefault();
+ onSelect(null);
+ }
+ return;
+ default:
+ return;
+ }
+ event.preventDefault();
+ setHover(null);
+ setActive(next);
+ reveal(next);
+ };
+
+ const shown = hover ?? (focused ? active : null);
+ const band = shown ?? selected;
+ const change = (c: Cell | null) => (c ? changed?.get(cellIndex(n, c[0], c[1])) : undefined);
+ const activeId = active ? `${baseId}-c${active[0]}-${active[1]}` : undefined;
+
+ return (
+
+ {!compact && (
+
+ Axis
+
+ {(
+ [
+ ["fit", "Numbers, fit"],
+ ["names", "Names"],
+ ] as const
+ ).map(([d, text]) => (
+ setChoice(d)}
+ className={cn(
+ "rounded-[4px] px-2 py-0.5 transition-colors",
+ density === d
+ ? "bg-foreground text-background"
+ : "text-muted-foreground hover:text-foreground",
+ FOCUS,
+ )}
+ >
+ {text}
+
+ ))}
+
+
+ )}
+
+
+
+
+
+
+ {band && }
+
+
+ {!compact && (
+
+ )}
+ {!compact && band && (
+
+ )}
+
+
+ {
+ setFocused(true);
+ if (!active && n > 0) setActive(selected ?? [0, Math.min(1, n - 1)]);
+ }}
+ onBlur={() => setFocused(false)}
+ onKeyDown={onKey}
+ onMouseMove={onMove}
+ onMouseLeave={() => setHover(null)}
+ onClick={(event) => {
+ const at = cellAt(event);
+ if (!at) return;
+ setActive(at);
+ onSelect(at);
+ }}
+ >
+
+ {picked !== null && picked >= 0 && picked < n && (
+ <>
+
+
+ >
+ )}
+ {band && (
+ <>
+
+
+ >
+ )}
+ {selected && (
+
+ )}
+ {active && (
+
+ )}
+ {shown && (
+
+ )}
+
+
+
+
+ {!compact && (
+
+
+ {shown ? (
+
+ ) : (
+ "Hover or focus a cell. Rows use columns. Click or press Enter to list the links."
+ )}
+
+ {footer}
+
+ )}
+
+ );
+}
+
+// ---- canvas -----------------------------------------------------------------------------
+
+interface DrawInput {
+ values: number[][];
+ n: number;
+ cell: number;
+ max: number;
+ flagged: ReadonlySet;
+ emphasis?: ReadonlySet | null;
+ changed?: ReadonlyMap | null;
+}
+
+function drawGrid(ctx: CanvasRenderingContext2D, d: DrawInput) {
+ const { values, n, cell, max, flagged, emphasis, changed } = d;
+ const side = n * cell;
+ const grain = token("--grain", "#1f4e8c");
+ const against = token("--against", "#d55e00");
+ const fg = token("--foreground", "#14181f");
+ const card = token("--card", "#fafaf7");
+ const gap = cell >= 6 ? 1 : 0;
+ const inner = cell - gap;
+ const off = gap / 2;
+ const logMax = Math.log1p(Math.max(1, max));
+ const alphaOf = (v: number) => 0.14 + 0.86 * (Math.log1p(v) / logMax);
+
+ ctx.clearRect(0, 0, side, side);
+ ctx.setLineDash([]);
+
+ // A faint wash over the lower triangle, where links go against the grain.
+ ctx.globalAlpha = 0.035;
+ ctx.fillStyle = against;
+ ctx.beginPath();
+ ctx.moveTo(0, 0);
+ ctx.lineTo(0, side);
+ ctx.lineTo(side, side);
+ ctx.closePath();
+ ctx.fill();
+
+ // Empty cells: a hairline square, where there is room for one.
+ if (cell >= 7) {
+ ctx.globalAlpha = 0.06;
+ ctx.strokeStyle = fg;
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ for (let i = 0; i < n; i++) {
+ const row = values[i]!;
+ for (let j = 0; j < n; j++) {
+ if (i === j || row[j]! > 0) continue;
+ ctx.rect(j * cell + off + 0.5, i * cell + off + 0.5, inner - 1, inner - 1);
+ }
+ }
+ ctx.stroke();
+ }
+
+ // The diagonal: a module and itself.
+ ctx.globalAlpha = 0.09;
+ ctx.fillStyle = fg;
+ for (let i = 0; i < n; i++) ctx.fillRect(i * cell + off, i * cell + off, inner, inner);
+
+ // Links: blue with the grain, vermilion against it; deeper for more links.
+ const fill = (i: number, j: number, v: number) => {
+ ctx.globalAlpha = alphaOf(v);
+ ctx.fillRect(j * cell + off, i * cell + off, inner, inner);
+ };
+ ctx.fillStyle = grain;
+ for (let i = 0; i < n; i++) {
+ const row = values[i]!;
+ for (let j = i + 1; j < n; j++) if (row[j]! > 0) fill(i, j, row[j]!);
+ }
+ ctx.fillStyle = against;
+ for (let i = 1; i < n; i++) {
+ const row = values[i]!;
+ for (let j = 0; j < i; j++) if (row[j]! > 0) fill(i, j, row[j]!);
+ }
+
+ // The diagonal hatch line.
+ ctx.globalAlpha = 0.25;
+ ctx.strokeStyle = fg;
+ ctx.lineWidth = 1;
+ ctx.setLineDash([3, 3]);
+ ctx.beginPath();
+ ctx.moveTo(0, 0);
+ ctx.lineTo(side, side);
+ ctx.stroke();
+ ctx.setLineDash([]);
+
+ // One finding brought forward: dim the rest, then draw its cells again on top.
+ if (emphasis && emphasis.size > 0) {
+ ctx.globalAlpha = 0.62;
+ ctx.fillStyle = card;
+ ctx.fillRect(0, 0, side, side);
+ for (const key of emphasis) {
+ const i = Math.floor(key / n);
+ const j = key % n;
+ const v = values[i]?.[j] ?? 0;
+ ctx.globalAlpha = 1;
+ ctx.fillStyle = card;
+ ctx.fillRect(j * cell + off, i * cell + off, inner, inner);
+ if (v > 0 && i !== j) {
+ ctx.fillStyle = i > j ? against : grain;
+ fill(i, j, v);
+ }
+ }
+ }
+
+ // Cells of the top findings: a solid outline.
+ ctx.globalAlpha = 1;
+ ctx.strokeStyle = fg;
+ for (const key of flagged) {
+ const i = Math.floor(key / n);
+ const j = key % n;
+ const strong = emphasis?.has(key) ?? false;
+ const lw = strong ? Math.min(2.4, Math.max(1.2, cell / 6)) : cell >= 10 ? 1.6 : 1;
+ ctx.lineWidth = lw;
+ ctx.strokeRect(j * cell + off + lw / 2, i * cell + off + lw / 2, inner - lw, inner - lw);
+ }
+ if (emphasis) {
+ for (const key of emphasis) {
+ if (flagged.has(key)) continue;
+ const i = Math.floor(key / n);
+ const j = key % n;
+ const lw = Math.min(2.4, Math.max(1.2, cell / 6));
+ ctx.lineWidth = lw;
+ ctx.strokeRect(j * cell + off + lw / 2, i * cell + off + lw / 2, inner - lw, inner - lw);
+ }
+ }
+
+ // Cells a stored change touches: a dashed inner outline.
+ if (changed && changed.size > 0) {
+ ctx.strokeStyle = fg;
+ ctx.lineWidth = cell >= 10 ? 1.25 : 1;
+ ctx.setLineDash(cell >= 10 ? [2, 1.5] : cell >= 6 ? [1.5, 1] : []);
+ const inset = cell >= 10 ? 2.5 : cell >= 6 ? 1.5 : 0.5;
+ for (const key of changed.keys()) {
+ const i = Math.floor(key / n);
+ const j = key % n;
+ ctx.strokeRect(
+ j * cell + off + inset,
+ i * cell + off + inset,
+ Math.max(1, inner - 2 * inset),
+ Math.max(1, inner - 2 * inset),
+ );
+ }
+ ctx.setLineDash([]);
+ }
+ ctx.globalAlpha = 1;
+}
+
+// ---- axes -------------------------------------------------------------------------------
+
+const ColumnNumbers = memo(function ColumnNumbers({
+ n,
+ cell,
+ headH,
+ compact,
+}: {
+ n: number;
+ cell: number;
+ headH: number;
+ compact: boolean;
+}) {
+ const font = compact ? 8 : Math.min(10, Math.max(8, cell * 0.6));
+ const step = numberStep(cell, String(n).length, font);
+ const items = [];
+ for (let j = 0; j < n; j += step) {
+ items.push(
+
+ {j + 1}
+ ,
+ );
+ }
+ return (
+
+ {items}
+
+ );
+});
+
+function ColumnMark({ j, n, cell, headH }: { j: number; n: number; cell: number; headH: number }) {
+ const wide = String(n).length * 7 + 6;
+ return (
+
+ {j + 1}
+
+ );
+}
+
+const RowLabels = memo(function RowLabels({
+ modules,
+ cell,
+ labelW,
+ density,
+}: {
+ modules: ModuleInfo[];
+ cell: number;
+ labelW: number;
+ density: Density;
+}) {
+ const n = modules.length;
+ if (density === "names") {
+ return (
+
+ {modules.map((m, i) => (
+
+ {pad2(i, n)}
+ {m.name}
+
+ ))}
+
+ );
+ }
+ const font = 10;
+ const step = Math.max(1, Math.ceil(12 / cell));
+ const items = [];
+ for (let i = 0; i < n; i += step) {
+ items.push(
+
+ {i + 1}
+ ,
+ );
+ }
+ return (
+
+ {items}
+
+ );
+});
+
+function RowMark({
+ m,
+ i,
+ n,
+ cell,
+ labelW,
+ density,
+}: {
+ m: ModuleInfo;
+ i: number;
+ n: number;
+ cell: number;
+ labelW: number;
+ density: Density;
+}) {
+ const h = Math.max(cell, 14);
+ return (
+
+ {density === "names" ? (
+ <>
+ {pad2(i, n)}
+ {m.name}
+ >
+ ) : (
+ {i + 1}
+ )}
+
+ );
+}
+
+// ---- hover and focus text ---------------------------------------------------------------
+
+/** The visible part of the cell area inside a scrolled panel; the whole area without one. */
+function visibleArea(box: HTMLDivElement | null, labelW: number, headH: number, side: number) {
+ if (!box || box.clientWidth === 0) return { left: 0, top: 0, right: side, bottom: side };
+ return {
+ left: Math.max(0, box.scrollLeft),
+ top: Math.max(0, box.scrollTop),
+ right: Math.min(side, box.scrollLeft + box.clientWidth - labelW),
+ bottom: Math.min(side, box.scrollTop + box.clientHeight - headH),
+ };
+}
+
+function countText(v: number) {
+ return v === 0 ? "no links" : `${fmt(v)} ${v === 1 ? "link" : "links"}`;
+}
+
+function StatusText({
+ modules,
+ values,
+ at: [i, j],
+ change,
+ changeSource,
+}: {
+ modules: ModuleInfo[];
+ values: number[][];
+ at: Cell;
+ change?: { before: number; after: number };
+ changeSource: string;
+}) {
+ const v = values[i]![j]!;
+ if (i === j) {
+ return (
+ <>
+ {modules[i]!.name} · the module itself
+ >
+ );
+ }
+ return (
+ <>
+
+ {modules[i]!.name} → {modules[j]!.name}
+ {" "}
+ · {countText(v)}
+ {v > 0 && (
+ <>
+ {" · "}
+ j ? "text-accent" : "text-primary"}>
+ {i > j ? "backward link" : "forward link"}
+
+ >
+ )}
+ {change && (
+ <>
+ {" · "}
+ {fmt(change.before)} → {fmt(change.after)} {changeSource}
+ >
+ )}
+ >
+ );
+}
+
+function Tip({
+ modules,
+ values,
+ at,
+ cell,
+ visible,
+ change,
+ changeSource,
+ compact,
+}: {
+ modules: ModuleInfo[];
+ values: number[][];
+ at: Cell;
+ cell: number;
+ /** The part of the cell area the reader can see, in cell-area pixels. */
+ visible: { left: number; top: number; right: number; bottom: number };
+ change?: { before: number; after: number };
+ changeSource: string;
+ compact: boolean;
+}) {
+ const [i, j] = at;
+ const src = modules[i]!;
+ const dst = modules[j]!;
+ const v = values[i]![j]!;
+ const width = compact ? 220 : 280;
+ // Beside the cell, on whichever side has room in the visible part of the grid.
+ const right = (j + 1) * cell + 10;
+ const leftSide = j * cell - 10 - width;
+ const fitsRight = right + width <= visible.right;
+ const left = fitsRight || leftSide < visible.left ? right : leftSide;
+ const below = i * cell + cell + 8;
+ const above = i * cell - 86;
+ const top = below + 80 > visible.bottom && above >= visible.top ? above : below;
+ return (
+
+
+ {i === j ? src.name : `${src.name} → ${dst.name}`}
+
+
+ {i === j ? (
+ "the module itself"
+ ) : (
+ <>
+ {countText(v)}
+ {v > 0 && (
+ j ? "text-accent" : "text-primary"}>
+ {" · "}
+ {i > j ? "backward link" : "forward link"}
+
+ )}
+ >
+ )}
+
+ {change && (
+
+ {fmt(change.before)} → {fmt(change.after)} {changeSource}
+
+ )}
+ {!compact && (
+
+ {i === j ? src.path : `${src.path} → ${dst.path}`}
+
+ )}
+ {(!src.presentAtEnd || !dst.presentAtEnd) && (
+
+ {[src, dst]
+ .filter((m, k) => !m.presentAtEnd && (k === 0 || i !== j))
+ .map((m) => m.name)
+ .join(" and ")}{" "}
+ {!src.presentAtEnd && !dst.presentAtEnd && i !== j ? "exist" : "exists"} only at the
+ before date
+
+ )}
+
+ );
+}
diff --git a/web/src/components/cx/overview-map.tsx b/web/src/components/cx/overview-map.tsx
new file mode 100644
index 00000000..68de887d
--- /dev/null
+++ b/web/src/components/cx/overview-map.tsx
@@ -0,0 +1,72 @@
+import { ArrowRight } from "lucide-react";
+import { useMemo, useState } from "react";
+import { Link, useNavigate } from "react-router";
+import { type MapView, mapPath } from "../../cx/address";
+import type { RepoBundle } from "../../cx/types";
+import { FOCUS, cn } from "./cn";
+import { GridNumbers, MapLegend, ViewToggle, viewLabel } from "./map-controls";
+import { gridMax, pictureFor, topFindingCells } from "./map-model";
+import { Matrix } from "./matrix";
+
+/** The small grid on the Overview; a cell opens the Map with that cell selected. */
+export function OverviewMap({ repo }: { repo: RepoBundle }) {
+ const [view, setView] = useState("now");
+ const navigate = useNavigate();
+ const ids = useMemo(() => repo.modules.map((m) => m.id), [repo]);
+ const picture = useMemo(() => pictureFor(repo, { kind: view }), [repo, view]);
+ const flagged = useMemo(() => new Set(topFindingCells(repo).keys()), [repo]);
+ return (
+
+
+ Which module uses which
+
+ Open map
+
+
+
+
+
+
+
+ {
+ if (!cell) return;
+ navigate(
+ mapPath(repo.id, {
+ view,
+ cell: cell[0] === cell[1] ? null : [ids[cell[0]]!, ids[cell[1]]!],
+ }),
+ );
+ }}
+ label={`Small module grid, ${viewLabel(repo, view)}. Enter opens the Map at the cell`}
+ />
+
+ {view === "after" && repo.batch && !repo.matrixFixed && (
+
+ Not recoloured: the simulation counted links on a different basis from the grid. Its
+ changed cells are outlined; the Map lists them.
+
+ )}
+
+
+ Rows use columns. Click a cell to open it on the Map.
+
+ 0} />
+
+
+ );
+}
diff --git a/web/src/components/cx/primitives.tsx b/web/src/components/cx/primitives.tsx
new file mode 100644
index 00000000..f61b39ac
--- /dev/null
+++ b/web/src/components/cx/primitives.tsx
@@ -0,0 +1,163 @@
+import type { ReactNode } from "react";
+import { STATUS } from "../../cx/meta";
+import type { Status } from "../../cx/types";
+import { cn } from "./cn";
+
+export function Logo({ className }: { className?: string }) {
+ // 3×3 dependency grid: upper cells with the grain, one lower cell against it.
+ const cells = [0, 1, 1, 0, 0, 1, 2, 0, 0];
+ return (
+
+ {cells.map((c, i) => (
+
+ ))}
+
+ );
+}
+
+export function StatusDot({ status, className }: { status: Status; className?: string }) {
+ return (
+
+ );
+}
+
+export function StatusPill({ status }: { status: Status }) {
+ const s = STATUS[status];
+ return (
+
+
+ {s.label}
+
+ );
+}
+
+export function Eyebrow({ children, className }: { children: ReactNode; className?: string }) {
+ return (
+
+ {children}
+
+ );
+}
+
+export function SectionHead({
+ eyebrow,
+ title,
+ aside,
+ id,
+}: {
+ eyebrow?: ReactNode;
+ title: ReactNode;
+ aside?: ReactNode;
+ id?: string;
+}) {
+ return (
+
+
+ {eyebrow && {eyebrow} }
+
+ {title}
+
+
+ {aside && {aside} }
+
+ );
+}
+
+export function Mono({ children, className }: { children: ReactNode; className?: string }) {
+ return {children} ;
+}
+
+export function Chip({
+ children,
+ className,
+ tone = "default",
+}: {
+ children: ReactNode;
+ className?: string;
+ tone?: "default" | "ink" | "accent" | "grain";
+}) {
+ return (
+
+ {children}
+
+ );
+}
+
+export function Panel({
+ children,
+ className,
+ labelledBy,
+}: {
+ children: ReactNode;
+ className?: string;
+ /** Id of the panel's own title; the panel is then a named region. */
+ labelledBy?: string;
+}) {
+ return (
+
+ {children}
+
+ );
+}
+
+/** Renders `backticked` spans in computed or AI prose as code identifiers. */
+export function Prose({ text, className }: { text: string; className?: string }) {
+ const parts = text.split(/(`[^`]+`)/g);
+ return (
+
+ {parts.map((p, i) =>
+ p.startsWith("`") ? (
+
+ {p.slice(1, -1)}
+
+ ) : (
+ {p}
+ ),
+ )}
+
+ );
+}
diff --git a/web/src/components/cx/series-chart.tsx b/web/src/components/cx/series-chart.tsx
new file mode 100644
index 00000000..7f4f232b
--- /dev/null
+++ b/web/src/components/cx/series-chart.tsx
@@ -0,0 +1,277 @@
+// A small line chart over dated snapshots with two labelled vertical marks: the comparison date
+// and the detected adoption date (spec.md §12.1 asks for both on every chart). The x axis is
+// in calendar time, so a mark between two snapshots sits where its date falls.
+import { useLayoutEffect, useRef, useState } from "react";
+import type { SeriesPoint } from "../../cx/types";
+import { cn } from "./cn";
+
+const DAY = 86_400_000;
+
+/** Days since 1970 for an ISO date; NaN when it is not one. */
+function dayOf(date: string): number {
+ const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(date);
+ return m ? Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])) / DAY : Number.NaN;
+}
+
+/** Follows the width of its box, so the chart fills it at any screen width. */
+function useWidth(initial: number) {
+ const ref = useRef(null);
+ const [width, setWidth] = useState(initial);
+ useLayoutEffect(() => {
+ const el = ref.current;
+ if (!el || typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(([entry]) => {
+ if (entry) setWidth(Math.max(80, Math.floor(entry.contentRect.width)));
+ });
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, []);
+ return { ref, width };
+}
+
+interface Mark {
+ key: "sponsor" | "adoption";
+ /** What the mark is called in text a reader sees. */
+ name: string;
+ day: number;
+ label: string;
+ dash: string;
+}
+
+export function SeriesChart({
+ series,
+ sponsorDate,
+ adoptionDate,
+ height = 72,
+ compact = false,
+ color = "var(--primary)",
+ domain,
+ label,
+ className,
+}: {
+ series: SeriesPoint[];
+ sponsorDate: string | null;
+ adoptionDate: string | null;
+ /** Height of the plot itself; the mark labels and the dated axis are added around it. */
+ height?: number;
+ /** Short mark labels ("comparison", "adoption") and month-only axis ends, for small charts. */
+ compact?: boolean;
+ color?: string;
+ domain?: [number, number];
+ label: string;
+ className?: string;
+}) {
+ const { ref, width } = useWidth(compact ? 200 : 320);
+ const points = series.filter((p) => Number.isFinite(dayOf(p.date)));
+
+ if (points.length < 2) {
+ return (
+
+
+ {points.length === 1 ? `one value only, at ${points[0]!.date}` : "no stored series"}
+
+
+ );
+ }
+
+ const rowH = compact ? 11 : 13;
+ const baseTop = compact ? 12 : 16;
+ const bottom = compact ? 13 : 16;
+ const fontSize = compact ? 9 : 10;
+ const charW = fontSize * 0.62;
+ const pad = 3;
+
+ const d0 = dayOf(points[0]!.date);
+ const d1 = dayOf(points.at(-1)!.date);
+ const span = d1 - d0 || 1;
+ const x = (day: number) => pad + ((day - d0) / span) * (width - pad * 2);
+
+ const values = points.map((p) => p.value);
+ const lo = domain?.[0] ?? Math.min(...values);
+ const hi = domain?.[1] ?? Math.max(...values);
+ const range = hi - lo || 1;
+
+ const marks: Mark[] = [];
+ if (sponsorDate) {
+ marks.push({
+ key: "sponsor",
+ name: "comparison",
+ day: dayOf(sponsorDate),
+ label: compact ? "comparison" : `comparison date ${sponsorDate}`,
+ dash: "3 3",
+ });
+ }
+ if (adoptionDate) {
+ marks.push({
+ key: "adoption",
+ name: "adoption",
+ day: dayOf(adoptionDate),
+ label: compact ? "adoption" : `adoption ${adoptionDate}`,
+ dash: "1 2",
+ });
+ }
+ const inRange = marks
+ .filter((m) => Number.isFinite(m.day) && m.day >= d0 && m.day <= d1)
+ .sort((a, b) => a.day - b.day || (a.key < b.key ? -1 : 1));
+
+ // The earlier mark's label sits left of its line, the later one's right of it, so two close
+ // dates do not print over each other; both stay inside the box. If they still overlap, the
+ // earlier label moves up one row.
+ const placed = inRange.map((m, i) => {
+ const mx = x(m.day);
+ const w = m.label.length * charW;
+ let anchor: "start" | "end" = inRange.length > 1 && i === 0 ? "end" : "start";
+ if (anchor === "end" && mx - 3 - w < 0) anchor = "start";
+ if (anchor === "start" && mx + 3 + w > width) anchor = "end";
+ const x0 = anchor === "end" ? mx - 3 - w : mx + 3;
+ return { m, mx, anchor, x0, x1: x0 + w, row: 0 };
+ });
+ if (
+ placed.length === 2 &&
+ placed[0]!.x1 + 4 > placed[1]!.x0 &&
+ placed[1]!.x1 + 4 > placed[0]!.x0
+ ) {
+ placed[0]!.row = 1;
+ }
+ const rows = Math.max(1, ...placed.map((p) => p.row + 1));
+ const top = baseTop + (rows - 1) * rowH;
+ const total = top + height + bottom;
+
+ const y = (v: number) => top + pad + (1 - (v - lo) / range) * (height - pad * 2);
+
+ const path = points
+ .map((p, i) => `${i ? "L" : "M"}${x(dayOf(p.date)).toFixed(1)},${y(p.value).toFixed(1)}`)
+ .join("");
+ const lastX = x(d1);
+ const lastY = y(points.at(-1)!.value);
+
+ const axisStart = compact ? points[0]!.date.slice(0, 7) : points[0]!.date;
+ const axisEnd = compact ? points.at(-1)!.date.slice(0, 7) : points.at(-1)!.date;
+ const outside = marks.filter((m) => !inRange.includes(m));
+
+ const aria = [
+ label,
+ `from ${points[0]!.date} to ${points.at(-1)!.date}`,
+ ...inRange.map((m) => `${m.name} date marked`),
+ ...outside.map((m) => `${m.name} date outside the series`),
+ ].join(", ");
+
+ return (
+
+
+
+ {placed.map(({ m, mx, anchor, row }) => (
+
+
+
+ {m.label}
+
+
+ ))}
+
+
+
+
+ {axisStart}
+
+
+ {axisEnd}
+
+
+
+ );
+}
+
+/** Explains the two dashed marks; the adoption date may be missing in a run. */
+export function SeriesLegend({
+ sponsorDate,
+ adoptionDate,
+ className,
+}: {
+ sponsorDate: string | null;
+ adoptionDate: string | null;
+ className?: string;
+}) {
+ const sample = (dash: string) => (
+
+
+
+ );
+ return (
+
+
+ {sample("3 3")}
+ comparison date{" "}
+ {sponsorDate ?? "not in the bundle"}
+
+
+ {sample("1 2")}
+ detected adoption date{" "}
+ {adoptionDate ? (
+ {adoptionDate}
+ ) : (
+ not detected in this run
+ )}
+
+
+ );
+}
diff --git a/web/src/components/cx/site-header.tsx b/web/src/components/cx/site-header.tsx
new file mode 100644
index 00000000..fc8e08fd
--- /dev/null
+++ b/web/src/components/cx/site-header.tsx
@@ -0,0 +1,83 @@
+import type { ReactNode } from "react";
+import { Link } from "react-router";
+import { repoPath } from "../../cx/address";
+import type { RepoSummary } from "../../cx/types";
+import { loadRepoSummaries } from "../../data/repo";
+import { FOCUS, cn } from "./cn";
+import { Logo } from "./primitives";
+import { useLoaded } from "./use-page";
+
+const shortName = (name: string) => name.slice(name.lastIndexOf("/") + 1);
+
+/**
+ * The top bar: logo and one button per real repository in the order of
+ * `bundles/index.json`. Synthetic bundles are reached by their address only.
+ */
+export function SiteHeader({ current }: { current?: string }) {
+ const summaries = useLoaded(() => loadRepoSummaries(), "summaries");
+ const all = summaries.state === "ready" ? summaries.value : [];
+ const real = all.filter((r) => !r.synthetic);
+ return (
+
+ );
+}
+
+/** The bottom line of every page: what the numbers rest on, if given, and the project credit. */
+export function SiteFooter({ children }: { children?: ReactNode }) {
+ return (
+
+ );
+}
+
+/** A page outside any repository: header, content, footer. */
+export function SitePage({ children, current }: { children: ReactNode; current?: string }) {
+ return (
+
+
+
+ {children}
+
+
+
+ );
+}
diff --git a/web/src/components/cx/sparkline.tsx b/web/src/components/cx/sparkline.tsx
new file mode 100644
index 00000000..e9f7e1e0
--- /dev/null
+++ b/web/src/components/cx/sparkline.tsx
@@ -0,0 +1,78 @@
+import { cn } from "./cn";
+
+/**
+ * Index of the first date on or after `date`, for the dashed date mark on a sparkline;
+ * undefined when there is no such date or no date to mark.
+ */
+export function markIndex(dates: readonly string[], date: string | null): number | undefined {
+ if (!date) return undefined;
+ const i = dates.findIndex((d) => d >= date);
+ return i >= 0 ? i : undefined;
+}
+
+export function Sparkline({
+ values,
+ mark,
+ width = 120,
+ height = 28,
+ color = "var(--primary)",
+ domain,
+ className,
+ label,
+ area = false,
+}: {
+ values: number[];
+ /** Index of the point to mark with a dashed line, usually the sponsor date. */
+ mark?: number;
+ width?: number;
+ height?: number;
+ color?: string;
+ domain?: [number, number];
+ className?: string;
+ label: string;
+ area?: boolean;
+}) {
+ if (values.length < 2) return null;
+ const lo = domain?.[0] ?? Math.min(...values);
+ const hi = domain?.[1] ?? Math.max(...values);
+ const span = hi - lo || 1;
+ const pad = 2;
+ const x = (i: number) => pad + (i * (width - pad * 2)) / (values.length - 1);
+ const y = (v: number) => pad + (1 - (v - lo) / span) * (height - pad * 2);
+ const d = values.map((v, i) => `${i ? "L" : "M"}${x(i).toFixed(1)},${y(v).toFixed(1)}`).join("");
+ const last = values.length - 1;
+ return (
+
+ {mark !== undefined && mark >= 0 && (
+
+ )}
+ {area && (
+
+ )}
+
+
+
+ );
+}
diff --git a/web/src/components/cx/use-page.ts b/web/src/components/cx/use-page.ts
new file mode 100644
index 00000000..0ab3f426
--- /dev/null
+++ b/web/src/components/cx/use-page.ts
@@ -0,0 +1,43 @@
+import { useEffect, useState } from "react";
+
+/**
+ * Sets the browser tab title to " · CodeXray"; null sets "CodeXray". Undefined
+ * leaves the title alone, for a layout whose screen sets its own.
+ */
+export function useTitle(title: string | null | undefined): void {
+ useEffect(() => {
+ if (title === undefined) return;
+ document.title = title ? `${title} · CodeXray` : "CodeXray";
+ }, [title]);
+}
+
+export type Loaded =
+ { state: "loading" } | { state: "ready"; value: T } | { state: "failed"; why: string };
+
+/**
+ * Runs `load` when `key` changes and keeps its result. A result that arrives after the key
+ * has changed again is dropped.
+ */
+export function useLoaded(load: () => Promise, key: string): Loaded {
+ const [result, setResult] = useState<{ key: string; loaded: Loaded }>({
+ key,
+ loaded: { state: "loading" },
+ });
+ useEffect(() => {
+ let current = true;
+ load().then(
+ (value) => current && setResult({ key, loaded: { state: "ready", value } }),
+ (error: unknown) =>
+ current &&
+ setResult({
+ key,
+ loaded: { state: "failed", why: error instanceof Error ? error.message : String(error) },
+ }),
+ );
+ return () => {
+ current = false;
+ };
+ // `load` is rebuilt on every render; `key` says when the request really changes.
+ }, [key]);
+ return result.key === key ? result.loaded : { state: "loading" };
+}
diff --git a/web/src/cx/address.ts b/web/src/cx/address.ts
new file mode 100644
index 00000000..abb0510a
--- /dev/null
+++ b/web/src/cx/address.ts
@@ -0,0 +1,114 @@
+// Every view has an address (spec.md §10.3). These build the paths after the "#" and read
+// and write the Map's search parameters, so reloading or sharing a link restores the view.
+
+export type RepoTab = "journeys" | "decisions" | "findings" | "map" | "change" | "trust" | "size";
+
+const seg = (s: string) => encodeURIComponent(s);
+
+/** "/r/" for the overview, "/r//" for any other tab. */
+export function repoPath(repoId: string, tab?: RepoTab): string {
+ return tab ? `/r/${seg(repoId)}/${tab}` : `/r/${seg(repoId)}`;
+}
+
+/** "/r//findings/". */
+export function findingPath(repoId: string, slug: string): string {
+ return `/r/${seg(repoId)}/findings/${seg(slug)}`;
+}
+
+/** Which grid the Map shows: the before date, the end snapshot, or after the fix batch. */
+export type MapView = "before" | "now" | "after";
+export const MAP_VIEWS: readonly MapView[] = ["before", "now", "after"];
+export const DEFAULT_MAP_VIEW: MapView = "now";
+
+export interface MapState {
+ view: MapView;
+ /** The selected cell as [source module id, target module id], or null. */
+ cell: [string, string] | null;
+ /** Slug of the finding whose cells are emphasised (`finding=`), or null. */
+ finding: string | null;
+ /** Slug of the finding whose simulated fix is shown on the grid (`fix=`), or null. */
+ fix: string | null;
+}
+
+const paramsOf = (search: string | URLSearchParams): URLSearchParams =>
+ typeof search === "string" ? new URLSearchParams(search) : search;
+
+/** `view=before|now|after`; anything else reads as the default, "now". */
+export function readMapView(search: string | URLSearchParams): MapView {
+ const v = paramsOf(search).get("view");
+ return (MAP_VIEWS as readonly string[]).includes(v ?? "") ? (v as MapView) : DEFAULT_MAP_VIEW;
+}
+
+/**
+ * `cell=,`. Module ids may themselves hold a comma, so the value
+ * is split only where both halves are known module ids. Returns null when no split matches.
+ */
+export function readMapCell(
+ search: string | URLSearchParams,
+ moduleIds: readonly string[],
+): [string, string] | null {
+ const raw = paramsOf(search).get("cell");
+ if (!raw) return null;
+ const known = new Set(moduleIds);
+ // Try every comma, left to right, so the result is the same on every run.
+ for (let i = raw.indexOf(","); i >= 0; i = raw.indexOf(",", i + 1)) {
+ const src = raw.slice(0, i);
+ const dst = raw.slice(i + 1);
+ if (known.has(src) && known.has(dst)) return [src, dst];
+ }
+ return null;
+}
+
+/** `finding=`: the finding whose cells the Map emphasises; empty reads as null. */
+export function readMapFinding(search: string | URLSearchParams): string | null {
+ return paramsOf(search).get("finding") || null;
+}
+
+/** `fix=`: the finding whose simulated fix the Map draws; empty reads as null. */
+export function readMapFix(search: string | URLSearchParams): string | null {
+ return paramsOf(search).get("fix") || null;
+}
+
+export function readMapState(
+ search: string | URLSearchParams,
+ moduleIds: readonly string[],
+): MapState {
+ return {
+ view: readMapView(search),
+ cell: readMapCell(search, moduleIds),
+ finding: readMapFinding(search),
+ fix: readMapFix(search),
+ };
+}
+
+// Encodes a query value but keeps ",", ":" and "/" readable; all three are allowed there.
+const queryValue = (v: string) =>
+ encodeURIComponent(v).replace(/%2C/gi, ",").replace(/%3A/gi, ":").replace(/%2F/gi, "/");
+
+/**
+ * The search string for a Map state, for example "?view=before&cell=M:a,M:b". The default
+ * view, an empty cell and an empty finding or fix are left out; with nothing to say it
+ * returns "". The parameters always come in the order view, cell, finding, fix.
+ */
+export function mapSearch(state: Partial): string {
+ const parts: string[] = [];
+ if (state.view && state.view !== DEFAULT_MAP_VIEW) parts.push(`view=${queryValue(state.view)}`);
+ if (state.cell) parts.push(`cell=${queryValue(`${state.cell[0]},${state.cell[1]}`)}`);
+ if (state.finding) parts.push(`finding=${queryValue(state.finding)}`);
+ if (state.fix) parts.push(`fix=${queryValue(state.fix)}`);
+ return parts.length ? `?${parts.join("&")}` : "";
+}
+
+/** The current search string with some of the Map state replaced. */
+export function withMapState(
+ search: string | URLSearchParams,
+ moduleIds: readonly string[],
+ patch: Partial,
+): string {
+ return mapSearch({ ...readMapState(search, moduleIds), ...patch });
+}
+
+/** "/r//map" with the given view and cell. */
+export function mapPath(repoId: string, state: Partial = {}): string {
+ return `${repoPath(repoId, "map")}${mapSearch(state)}`;
+}
diff --git a/web/src/cx/clone.ts b/web/src/cx/clone.ts
new file mode 100644
index 00000000..f0bd54f1
--- /dev/null
+++ b/web/src/cx/clone.ts
@@ -0,0 +1,27 @@
+// The folder of the reader's own clone, for the "open in editor" link (spec.md §4.4). The
+// bundle holds no absolute path, so the reader gives it once and it stays in this browser.
+// The storage key is the one the code pane has always used, so a saved folder carries over.
+
+const rootKey = (repoId: string) => `codexray.root.${repoId}`;
+
+/** The saved clone folder for a repository, or null when none is saved or storage is blocked. */
+export function readCloneRoot(repoId: string): string | null {
+ try {
+ const value = localStorage.getItem(rootKey(repoId));
+ return value && value.trim() ? value : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Saves the clone folder; an empty value forgets it. Returns false when storage is blocked. */
+export function writeCloneRoot(repoId: string, value: string): boolean {
+ try {
+ const trimmed = value.trim();
+ if (trimmed) localStorage.setItem(rootKey(repoId), trimmed);
+ else localStorage.removeItem(rootKey(repoId));
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/web/src/cx/grid.ts b/web/src/cx/grid.ts
new file mode 100644
index 00000000..6433bd6f
--- /dev/null
+++ b/web/src/cx/grid.ts
@@ -0,0 +1,103 @@
+// Pure helpers for the structure grid. A cell is one module using another: row = source,
+// column = target, both in the users-to-foundations order of spec.md §9.5.
+
+export const cellKey = (src: string, dst: string): string => `${src}~${dst}`;
+
+export function splitCellKey(key: string): [string, string] | null {
+ const at = key.indexOf("~");
+ return at > 0 ? [key.slice(0, at), key.slice(at + 1)] : null;
+}
+
+/**
+ * True when the link points from a foundation back up to one of its users: the source
+ * sits below the target in the order. A module missing from the order never counts.
+ */
+export function againstGrain(order: string[], src: string, dst: string): boolean {
+ const from = order.indexOf(src);
+ const to = order.indexOf(dst);
+ return from >= 0 && to >= 0 && from > to;
+}
+
+interface TreeNode {
+ id: string;
+ level: string;
+ parent_id: string | null;
+}
+
+/**
+ * Finds the module of any node by walking `parent_id` up. A class or function id that has
+ * no node of its own ("F:path#Name") falls back to its file. Build it once per map.
+ */
+export function moduleFinder(nodes: readonly TreeNode[]): (nodeId: string) => string | null {
+ const byId = new Map(nodes.map((node) => [node.id, node]));
+ return (nodeId) => {
+ let node = byId.get(nodeId);
+ if (!node && nodeId.includes("#")) node = byId.get(nodeId.slice(0, nodeId.indexOf("#")));
+ const seen = new Set();
+ while (node && !seen.has(node.id)) {
+ if (node.level === "module") return node.id;
+ seen.add(node.id);
+ node = node.parent_id ? byId.get(node.parent_id) : undefined;
+ }
+ return null;
+ };
+}
+
+/**
+ * A readable name per node: the last part of its path, longer where two would match. A
+ * module shows its folder and the one above it. The same rule the pipeline uses for the
+ * names in finding titles, so the grid and the titles agree.
+ */
+export function shortNames(nodeIds: readonly string[]): Map {
+ const parts = (nodeId: string): string[] => {
+ if (nodeId.includes("#")) return [nodeId.slice(nodeId.lastIndexOf("#") + 1)];
+ const at = nodeId.indexOf(":");
+ const split = (at >= 0 ? nodeId.slice(at + 1) : nodeId).split("/");
+ return split.length ? split : [nodeId];
+ };
+ const unique = [...new Set(nodeIds)];
+ const depth = new Map(
+ unique.map((n) => [n, n.startsWith("M:") ? Math.min(2, parts(n).length) : 1] as const),
+ );
+ for (;;) {
+ const names = new Map(unique.map((n) => [n, parts(n).slice(-depth.get(n)!).join("/")]));
+ const count = new Map();
+ for (const name of names.values()) count.set(name, (count.get(name) ?? 0) + 1);
+ const grow = unique.filter(
+ (n) => count.get(names.get(n)!)! > 1 && depth.get(n)! < parts(n).length,
+ );
+ if (!grow.length) return names;
+ for (const n of grow) depth.set(n, depth.get(n)! + 1);
+ }
+}
+
+/** A square matrix in `order`, filled from cell counts; pairs outside the order are skipped. */
+export function matrixOf(
+ order: readonly string[],
+ cells: readonly { src: string; dst: string; count: number }[],
+): number[][] {
+ const index = new Map(order.map((id, i) => [id, i]));
+ const out = order.map(() => order.map(() => 0));
+ for (const cell of cells) {
+ const i = index.get(cell.src);
+ const j = index.get(cell.dst);
+ if (i !== undefined && j !== undefined) out[i]![j] = cell.count;
+ }
+ return out;
+}
+
+/** A copy of `matrix` with each change's `after` count put in its cell. */
+export function applyCellChanges(
+ matrix: readonly number[][],
+ order: readonly string[],
+ changes: readonly { src: string; dst: string; after: number }[],
+): number[][] {
+ const index = new Map(order.map((id, i) => [id, i]));
+ const out = matrix.map((row) => [...row]);
+ for (const change of changes) {
+ const i = index.get(change.src);
+ const j = index.get(change.dst);
+ if (i !== undefined && j !== undefined) out[i]![j] = change.after;
+ }
+ return out;
+}
diff --git a/web/src/cx/meta.ts b/web/src/cx/meta.ts
new file mode 100644
index 00000000..bbe4c3a4
--- /dev/null
+++ b/web/src/cx/meta.ts
@@ -0,0 +1,245 @@
+// Labels, colours and small formatters shared by every screen.
+import type {
+ FindingType,
+ RepoBundle,
+ Shape,
+ SimulationKind,
+ SourceKind,
+ Status,
+ Verdict,
+} from "./types";
+
+// Okabe-Ito categorical palette (colour-blind safe), spec §10.5
+export const STATUS: Record =
+ {
+ broken: {
+ label: "Broken",
+ color: "#D55E00",
+ order: 0,
+ hint: "Kept in less than 90% of the code it covers",
+ },
+ slipping: {
+ label: "Getting worse",
+ color: "#E69F00",
+ order: 1,
+ hint: "Kept less often than before: down more than 1 point over the last two snapshots",
+ },
+ spreading: {
+ label: "Reaching more modules",
+ color: "#CC79A7",
+ order: 2,
+ hint: "The rule now covers more modules than before, so there is more code that has to keep it",
+ },
+ mostly_holding: {
+ label: "Mostly holding",
+ color: "#56B4E9",
+ order: 3,
+ hint: "Kept in 90% to 98% of the code it covers, and stable",
+ },
+ holding: {
+ label: "Holding",
+ color: "#009E73",
+ order: 4,
+ hint: "Kept in at least 98% of the code it covers",
+ },
+ };
+
+export const STATUS_ORDER: Status[] = [
+ "broken",
+ "slipping",
+ "spreading",
+ "mostly_holding",
+ "holding",
+];
+
+/** Label, group and a fixed "why it matters" sentence per finding type (not AI text). */
+export const TYPE: Record = {
+ broken_rule: {
+ label: "Broken rule",
+ group: "Decision exception",
+ why: "The code goes against a recorded decision about which code may use which. Each exception makes the decision harder to rely on.",
+ },
+ cheap_loop: {
+ label: "Cheap loop to cut",
+ group: "Decision exception",
+ why: "Two modules use each other, so neither is easy to change or test on its own. One direction rests on only a few links, so the loop is cheap to cut.",
+ },
+ foundation_on_features: {
+ label: "Foundation on features",
+ group: "Decision exception",
+ why: "A module that most others in its area build on itself uses a feature module, so a change to that feature can reach everything built on the foundation.",
+ },
+ shaky_foundation: {
+ label: "Shaky foundation",
+ group: "Pressure point",
+ why: "Many files use this one directly and it changes often, so each change to it can reach any of the files that use it.",
+ },
+ hidden_partners: {
+ label: "Hidden partners",
+ group: "Pressure point",
+ why: "These files keep changing in the same commits, but no link in the code connects them. Nothing in the code tells someone who changes one that the other may need to change too.",
+ },
+ overloaded_class: {
+ label: "Overloaded class",
+ group: "Inside a file",
+ why: "This class is among the largest in the project, uses many other project files and is used by many. A class like this is harder to understand and test, and a change to it can reach every file that uses it.",
+ },
+ large_complex_changed: {
+ label: "Large, complex, often changed",
+ group: "Supporting detail",
+ why: "Code with many branches that changes often takes longer to review and is harder to change safely.",
+ },
+};
+
+export const SHAPE: Record = {
+ forbid: "forbid(A, B)",
+ only_via: "only_via(B, C)",
+ direction: "direction(X, Y)",
+ acyclic: "acyclic(scope)",
+};
+
+export const SOURCE: Record = {
+ enforced: "Enforced by the project",
+ written: "Written decision",
+ measured: "Measured habit",
+ universal: "Universal",
+};
+
+export const VERDICT: Record = {
+ misplaced_type: "Misplaced type",
+ missing_api: "Missing API",
+ legitimate_wiring: "Legitimate wiring",
+ mixed_concerns: "Mixed concerns",
+ single_concern: "Single concern",
+ insufficient_evidence: "Insufficient evidence",
+};
+
+export const ACTION: Record = {
+ move_symbol: "Move symbol",
+ route_through_api: "Route through API",
+ invert_dependency: "Invert dependency",
+ extract_interface: "Extract interface",
+ split_by_responsibility: "Split by responsibility",
+ none: "No change",
+};
+
+/** How each simulation kind is worded (spec.md §8.5). */
+export const SIMULATION: Record = {
+ "not-simulated": {
+ short: "Not simulated",
+ long: "Not simulated. Only moves and single-link removals are tried on the map.",
+ },
+ "nothing-changed": {
+ short: "Not simulated",
+ long: "Not simulated. Nothing on the map changed for this fix.",
+ },
+ "effect-if-removed": {
+ short: "Effect if the link is removed",
+ long: "Not tested: the map is shown with the link taken away.",
+ },
+ "link-remains": {
+ short: "Simulated: the link remains",
+ long: "Fix simulated: the link remains.",
+ },
+ "adds-exceptions": {
+ short: "Simulated, adds exceptions",
+ long: "Fix simulated: it creates new exceptions.",
+ },
+ checked: { short: "Checked by simulation", long: "Fix checked by simulation." },
+};
+
+/** The sentence shown where a finding has no fix (spec.md §8.7). */
+export const NO_FIX_TEXT = "No improvement proposed.";
+
+/** Said next to the simulated batch's loop counts, which are not the yardstick's pairs. */
+export const BATCH_LOOPS_NOTE =
+ "Loop counts here are the simulation's own, on its set of module links, so they differ from the two-way dependencies count.";
+
+/**
+ * A readable label for each stored fact key. The value is shown after it with the fact's
+ * stored unit. A key missing here is shown with its underscores as spaces.
+ */
+export const FACT_LABEL: Record = {
+ violating_links: "Links against the decision",
+ reverse_links: "Links in the opposite direction",
+ files: "Files holding those links",
+ weak_links: "Links in the weak direction",
+ strong_links: "Links in the strong direction",
+ symbol: "Declaration it imports",
+ feature_links: "Links into the feature module",
+ instability: "Instability (outgoing links ÷ all links)",
+ user_modules: "Modules that use it",
+ user_modules_in_area: "Modules in its area that use it",
+ other_modules_in_area: "Other modules in its area",
+ modules_total: "Modules with production code",
+ direct_users: "Used directly by",
+ dependencies: "Depends on",
+ changes_12m: "Changed in the last 12 months",
+ changes_a: "Changes to the first file",
+ changes_b: "Changes to the second file",
+ shared_commits: "Commits that change both",
+ shared_share: "Share of changes made together",
+ lines: "Length",
+ branches: "Branches",
+ score: "Score (changes × branches)",
+ top_functions: "Functions with the most branches",
+ longest_functions: "Longest functions",
+ reach: "Reach (files using it directly or at one remove)",
+ pressure: "Changes to the affected code in 12 months",
+};
+
+/** Fact keys whose value is a share between 0 and 1, shown as a percentage. */
+export const FACT_SHARE: ReadonlySet = new Set(["shared_share"]);
+
+export const fmt = (n: number) => n.toLocaleString("en-US");
+export const pct = (n: number, d = 1) => `${(n * 100).toFixed(d)}%`;
+
+/**
+ * "/blob//#L-L", pinned to the end commit, or null for a private
+ * repository (spec.md §4.4).
+ */
+export function hostLink(
+ repo: Pick,
+ path: string,
+ s?: number | null,
+ e?: number | null,
+): string | null {
+ if (!repo.host) return null;
+ const base = repo.host.replace(/\/+$/, "");
+ const file = path.split("/").map(encodeURIComponent).join("/");
+ const anchor = s ? `#L${s}${e && e !== s ? `-L${e}` : ""}` : "";
+ return `${base}/blob/${repo.endSha}/${file}${anchor}`;
+}
+
+/** "/commit/", or null for a private repository. */
+export function commitLink(repo: Pick, sha: string): string | null {
+ if (!repo.host) return null;
+ return `${repo.host.replace(/\/+$/, "")}/commit/${encodeURIComponent(sha)}`;
+}
+
+/**
+ * "vscode://file//:" for the reader's own clone, or null until the
+ * reader has given the clone folder (see `cx/clone.ts`). The bundle holds no absolute path.
+ */
+export function editorLink(
+ localRoot: string | null,
+ path: string,
+ line: number | null = 1,
+): string | null {
+ const root = (localRoot ?? "").trim().replace(/\\/g, "/").replace(/\/+$/, "");
+ if (!root) return null;
+ const rooted = root.startsWith("/") ? root : `/${root}`;
+ return `vscode://file${rooted}/${path.replace(/^\/+/, "")}:${line ?? 1}`;
+}
+
+export function statusCounts(decisions: { status: Status }[]) {
+ const out: Record = {
+ broken: 0,
+ slipping: 0,
+ spreading: 0,
+ mostly_holding: 0,
+ holding: 0,
+ };
+ for (const d of decisions) out[d.status]++;
+ return out;
+}
diff --git a/web/src/cx/types.ts b/web/src/cx/types.ts
new file mode 100644
index 00000000..9cddc96d
--- /dev/null
+++ b/web/src/cx/types.ts
@@ -0,0 +1,455 @@
+// The shape the screens read. Built from a real bundle by `data/adapt.ts`; nothing here is
+// measured or computed by the app beyond arithmetic on stored values. A value the bundle
+// does not hold is `null`, never 0, so a screen can say it is not measured.
+
+export type Status = "holding" | "mostly_holding" | "spreading" | "slipping" | "broken";
+export type Shape = "forbid" | "only_via" | "direction" | "acyclic";
+/** `measured` is the bundle's `habit` source kind (spec.md §9.1, "measured habit"). */
+export type SourceKind = "enforced" | "written" | "measured" | "universal";
+export type FindingType =
+ | "broken_rule"
+ | "cheap_loop"
+ | "foundation_on_features"
+ | "shaky_foundation"
+ | "hidden_partners"
+ | "overloaded_class"
+ | "large_complex_changed";
+
+export type Verdict =
+ | "misplaced_type"
+ | "missing_api"
+ | "legitimate_wiring"
+ | "mixed_concerns"
+ | "single_concern"
+ | "insufficient_evidence";
+
+export type FixAction =
+ | "move_symbol"
+ | "route_through_api"
+ | "invert_dependency"
+ | "extract_interface"
+ | "split_by_responsibility"
+ | "none";
+
+export type Confidence = "low" | "medium" | "high";
+export type TextSource = "ai" | "computed";
+
+/** What a finding's stored simulation can be said to show (spec.md §8.5). */
+export type SimulationKind =
+ | "not-simulated"
+ | "nothing-changed"
+ | "effect-if-removed"
+ | "link-remains"
+ | "adds-exceptions"
+ | "checked";
+
+export interface SeriesPoint {
+ date: string;
+ value: number;
+}
+
+export interface ModuleInfo {
+ /** Position in the one grid order (`before_after.module_order`). */
+ index: number;
+ id: string;
+ /** Full path of the module folder. */
+ path: string;
+ /** Short display name: the last part of the path, longer where two would match. */
+ name: string;
+ /** False for a module that exists only at the before date: its numbers are then null. */
+ presentAtEnd: boolean;
+ kind: "production" | "test" | "generated" | null;
+ /** Lines in the module at the end snapshot, all file kinds. */
+ loc: number | null;
+ files: number | null;
+ linksIn: number | null;
+ linksOut: number | null;
+ /** linksOut ÷ (linksIn + linksOut) (spec.md §9.3); null with no links or no stats. */
+ instability: number | null;
+ changes12m: number | null;
+ /** Share of the module's lines that arrived after the sponsor date, 0 to 1. */
+ postMarchShare: number | null;
+ /** Not in the bundle. */
+ aiMarkedShare: number | null;
+ description: { text: string; source: TextSource } | null;
+}
+
+export interface DecisionPoint {
+ date: string;
+ sha: string;
+ status: Status;
+ conformance: number;
+ perKloc: number;
+ exceptions: number;
+ opportunities: number;
+ modulesCovered: number;
+}
+
+export interface Decision {
+ id: string;
+ statement: string;
+ shape: Shape;
+ /** The shape's arguments as one readable string, for example `from=M:a, to=[M:b, M:c]`. */
+ args: string;
+ /** The same arguments, one entry per key in stored order. */
+ argList: { key: string; values: string[] }[];
+ source: { kind: SourceKind; path: string | null; lines: [number, number] | null };
+ /** The rule's authority as stored on its findings (priority.A); null when no finding cites it. */
+ authority: number | null;
+ // Values at the end snapshot.
+ status: Status;
+ conformance: number;
+ opportunities: number;
+ exceptions: number;
+ perKloc: number;
+ modulesCovered: number;
+ proposedBy: "ai" | "computed" | "hand";
+ reviewed: boolean;
+ /** One point per checked snapshot date, oldest first. */
+ series: DecisionPoint[];
+ /** Number of the project's own allowed exceptions. */
+ allowed: number;
+}
+
+export interface WrittenDecision {
+ id: string;
+ statement: string;
+ /** The source path, or the source kind's label when there is no path. */
+ source: string;
+ sourceKind: SourceKind;
+ sourcePath: string | null;
+ lines: [number, number] | null;
+ /** Why it is not in the checked list, as a computed sentence. */
+ reason: string;
+ /** Who wrote the statement: job A ("ai"), the pipeline ("computed") or a person ("hand"). */
+ proposedBy: "ai" | "computed" | "hand";
+}
+
+/** One file on the map at the end snapshot, for the size map. */
+export interface FileSize {
+ path: string;
+ /** Module id the file belongs to. */
+ module: string;
+ kind: "production" | "test" | "generated";
+ loc: number;
+ /** Share of the file's lines that arrived after the sponsor date, 0 to 1; null without stats. */
+ postMarchShare: number | null;
+ changes12m: number | null;
+}
+
+/** Proof for one fact (spec.md §4.4). Code is loaded on demand by `blobSha`. */
+export interface Evidence {
+ id: string;
+ kind: "lines" | "commits";
+ blobSha: string | null;
+ path: string | null;
+ startLine: number | null;
+ endLine: number | null;
+ role: string;
+ commits: string[];
+ snapshotSha: string;
+}
+
+export interface Fact {
+ key: string;
+ value: number | string | boolean;
+ unit: string | null;
+ source: string;
+}
+
+/** Job B's text. Present only when it passed every check of spec.md §8.4. */
+export interface Judgement {
+ verdict: Verdict;
+ confidence: Confidence;
+ claim: string;
+ fixText: string;
+ action: FixAction;
+ symbol: string | null;
+ from: string | null;
+ to: string | null;
+ /** For example "3 of 3": votes that agree with the verdict, of all votes. Empty with no votes. */
+ votes: string;
+ voteList: Verdict[];
+ /** Number of citations; all of them passed the checks, so `citationsChecked` equals it. */
+ citations: number;
+ citationsChecked: number;
+ model: string | null;
+}
+
+export interface CellChange {
+ src: string;
+ dst: string;
+ before: number;
+ after: number;
+}
+
+export interface Simulation {
+ simulated: boolean;
+ targetLinkRemoved: boolean;
+ loopsBefore: number | null;
+ loopsAfter: number | null;
+ linksRemoved: number;
+ linksAdded: number;
+ newExceptions: string[];
+ cellChanges: CellChange[];
+ /**
+ * True when every change's `before` equals the grid's count for that cell, so `after`
+ * can be drawn on the grid. False when the simulation counted links on another basis.
+ */
+ onGrid: boolean;
+ /** What this simulation can be said to show, decided once for every screen. */
+ kind: SimulationKind;
+}
+
+export interface Finding {
+ /** The pipeline's id: repo, type and sorted targets (spec.md §11.2). */
+ id: string;
+ /** URL-safe short hash of `id`, stable across runs. */
+ slug: string;
+ rank: number;
+ type: FindingType;
+ decisionId: string | null;
+ title: string;
+ /** The fixed sentence built from facts (spec.md §8.7). Always present. */
+ summary: string;
+ targets: { nodeId: string; role: string }[];
+ /** Module ids the targets belong to, in grid order. */
+ modules: string[];
+ facts: Fact[];
+ evidence: Evidence[];
+ priority: { S: number; R: number; P: number; A: number; ease: number; score: number };
+ trend: {
+ firstSeen: string;
+ status: "new_since_2025_03" | "worse" | "better" | "unchanged";
+ series: SeriesPoint[];
+ };
+ origin: { linesAfter: number; linesAiMarked: number; note: string };
+ linkQuality: { how: string; agreement: number | null } | null;
+ /** Null when there is no AI text that passed the checks: show `summary` instead. */
+ judgement: Judgement | null;
+ /** The template's fix (spec.md §8.7), when the pipeline stored one. */
+ computedFix: { text: string; action: FixAction } | null;
+ simulation: Simulation | null;
+ caveats: string[];
+ /** Grid cells `[src, dst]` (module ids) that exist between the finding's modules. */
+ cells: [string, string][];
+ /** Ids of other findings that share a target node, by rank. */
+ related: string[];
+ /**
+ * Close-up positions stored when the bundle was built (`layouts.json`, spec.md §10.4),
+ * one per module node, in stored order. Null when the bundle holds none for this finding.
+ */
+ layout: { nodeId: string; x: number; y: number }[] | null;
+}
+
+/** Links behind one grid cell at the end snapshot: the true count and a capped sample. */
+export interface CellLinks {
+ src: string;
+ dst: string;
+ count: number;
+ how: string;
+ kind: string;
+ /** File and line records, at most the number the pipeline keeps per link. */
+ refs: Evidence[];
+}
+
+export interface StructuralEvent {
+ id: string;
+ kind: "restructuring" | "link_added" | "link_removed" | "module_added" | "module_removed";
+ title: string;
+ label: "planned" | "no_stated_intent";
+ basis: "same_code_old_layout" | "restructuring_commit" | "decision_document" | "pr_goal" | null;
+ source: TextSource;
+ evidence: Evidence[];
+ /** Interval start and end, only where the id format defines them; otherwise null. */
+ fromDate: string | null;
+ date: string | null;
+}
+
+export interface Hotspot {
+ path: string;
+ nodeId: string;
+ /** Module id, through the file's parent. */
+ module: string | null;
+ moduleName: string | null;
+ z: number;
+ /** Changes in the recent window (the last 3 months, spec.md §12.2). */
+ recent: number;
+ /** Expected changes in a window of the same length, from the prior months. */
+ prior: number;
+}
+
+export interface LinkChange {
+ src: string;
+ dst: string;
+ label: "expected_found" | "found_not_expected" | "expected_missing";
+ count: number;
+ note: string;
+}
+
+export interface CoverageRow {
+ language: string;
+ files: number;
+ unread: number;
+ /** Shares of imports, 0 to 1. */
+ linked: number;
+ outside: number;
+ unexplained: number;
+ linkAgreement: number | null;
+ /** Not in the bundle. */
+ fileAgreement: number | null;
+ moduleAgreement: number | null;
+}
+
+export interface StabilityRow {
+ test: string;
+ top5: number;
+ top10: number;
+ rbo: number;
+ note: string | null;
+}
+
+export interface UsageRow {
+ job: "A" | "B" | "C";
+ model: string;
+ calls: number;
+ tokensIn: number;
+ tokensOut: number;
+ /** Calls served from the cache. */
+ cached: number;
+ cachedInputTokens: number;
+ cost: number;
+}
+
+export interface Yardstick {
+ name: string;
+ unit: string | null;
+ /** Value at the end snapshot, from `report.yardsticks`. */
+ now: number | null;
+ /** Value at the before date of the comparison, from the stored series. */
+ before: number | null;
+ series: SeriesPoint[];
+}
+
+export interface Batch {
+ fixesApplied: number;
+ fixesSkipped: number;
+ loopsBefore: number;
+ loopsAfter: number;
+ linksRemoved: number;
+ linksAdded: number;
+ newExceptions: string[];
+ cellChanges: CellChange[];
+ /** As `Simulation.onGrid`: whether the changes' `before` counts equal the grid's. */
+ onGrid: boolean;
+}
+
+export interface RepoBundle {
+ id: string;
+ /** For example "owner/project". */
+ name: string;
+ /** The last part of `name`. */
+ short: string;
+ synthetic: boolean;
+ /** Public host URL, or null for a private repository. */
+ host: string | null;
+ /** Bundle folder URL, for loading cited code. */
+ folder: string;
+ languages: string[];
+ endSha: string;
+ snapshotDate: string;
+ paramsHash: string;
+ /** Not in the bundle. */
+ rulesHash: string | null;
+ sponsorDate: string | null;
+ /** The detected adoption date, null when none was detected. */
+ adoptionDate: string | null;
+ /** Not in the bundle. */
+ adoptionEvidence: string | null;
+ /** The two dates the before-and-after views compare. */
+ beforeDate: string;
+ afterDate: string;
+ /** Lines and number of production files at the end snapshot. */
+ prodLoc: number;
+ prodFiles: number;
+ /** Ranking weights (spec.md §11.1), for showing the formula. */
+ weights: Record;
+ modules: ModuleInfo[];
+ /** Links per cell, rows use columns, in `modules` order, at the end and before dates. */
+ matrix: number[][];
+ matrixBefore: number[][];
+ /**
+ * `matrix` with the batch's `after` counts put in. Null with no batch, and null when
+ * `batch.onGrid` is false: the batch then counted links on another basis, and its
+ * numbers cannot be drawn on this grid without inventing counts.
+ */
+ matrixFixed: number[][] | null;
+ /** Keyed by `cellKey(src, dst)`. */
+ cellLinks: Record;
+ decisions: Decision[];
+ written: WrittenDecision[];
+ /** Ranks 1 to 10, in the pipeline's order. */
+ findings: Finding[];
+ /** Every other finding, in rank order. */
+ supporting: Finding[];
+ yardsticks: {
+ againstGrain: Yardstick;
+ againstGrainShare: Yardstick;
+ twoWayPairs: Yardstick;
+ perKloc: Yardstick;
+ crossModule: Yardstick;
+ };
+ /** Every stored yardstick series, by stored name. */
+ yardstickSeries: Record;
+ /** Against-the-grain share at every snapshot date. */
+ grainSeries: SeriesPoint[];
+ batch: Batch | null;
+ events: StructuralEvent[];
+ hotspots: Hotspot[];
+ /** Not in the bundle. */
+ linkChanges: LinkChange[] | null;
+ aiRisk:
+ | { band: string; aiMarked: number; noSignal: number; aiCount: number; noSignalCount: number }[]
+ | null;
+ aiShareSeries: SeriesPoint[] | null;
+ coverage: CoverageRow[];
+ silentMiss: number | null;
+ blindSpots: string[];
+ stability: StabilityRow[];
+ usage: UsageRow[];
+ healthy: { decisionId: string; evidence: string }[];
+ /** Snapshot dates, oldest first. */
+ snapshots: string[];
+ /** Every file on the map at the end snapshot, by path; null when the map lists no file. */
+ fileSizes: FileSize[] | null;
+}
+
+/** What the landing page and the repository switcher need, from two small files. */
+export interface RepoSummary {
+ id: string;
+ /** The bundle list's label. */
+ label: string;
+ name: string;
+ synthetic: boolean;
+ snapshotDate: string | null;
+ statusCounts: Record;
+}
+
+/**
+ * A repository card on the landing page: the summary plus what `report.json` and
+ * `before_after.json` hold. Lines and module counts need the map and are not part of it.
+ */
+export interface RepoCard extends RepoSummary {
+ languages: string[];
+ sponsorDate: string | null;
+ /** The before date of the comparison. */
+ beforeDate: string;
+ againstGrainShare: Yardstick;
+}
+
+/** The rank-1 finding of a repository, read from `findings.json` alone. */
+export interface FixFirst {
+ rank: number;
+ title: string;
+ slug: string;
+}
diff --git a/web/src/data/adapt.ts b/web/src/data/adapt.ts
new file mode 100644
index 00000000..a2e0c8c0
--- /dev/null
+++ b/web/src/data/adapt.ts
@@ -0,0 +1,659 @@
+// Turns one loaded bundle into the shape the screens read (`cx/types.ts`). Pure and
+// deterministic: the same bundle always gives the same result. It only renames, groups and
+// looks up stored values; it never detects, counts or ranks anything of its own, and a
+// value the bundle does not hold comes out as null.
+import type * as C from "../contracts/generated";
+import { applyCellChanges, cellKey, matrixOf, moduleFinder, shortNames } from "../cx/grid";
+import { fmt, statusCounts } from "../cx/meta";
+import type {
+ Batch,
+ CellLinks,
+ Decision,
+ DecisionPoint,
+ Evidence,
+ FileSize,
+ Finding,
+ Judgement,
+ ModuleInfo,
+ RepoBundle,
+ SeriesPoint,
+ Simulation,
+ SimulationKind,
+ SourceKind,
+ Status,
+ StructuralEvent,
+ WrittenDecision,
+ Yardstick,
+} from "../cx/types";
+import { type Bundle, sponsorDate } from "./bundle";
+
+/** Findings shown as "fix first"; the pipeline's post-processing already shaped this list. */
+const TOP = 10;
+
+// Stored yardstick names (spec.md §9.5), as written by the pipeline.
+const YARDSTICK = {
+ againstGrain: "against_grain_links",
+ againstGrainShare: "against_grain_share",
+ twoWayPairs: "two_way_module_pairs",
+ perKloc: "exceptions_per_kloc",
+ crossModule: "cross_module_links",
+} as const;
+
+/** Fix actions whose simulation takes the link away by assumption (spec.md §8.5). */
+const LINK_REMOVING: ReadonlySet = new Set([
+ "route_through_api",
+ "invert_dependency",
+ "extract_interface",
+]);
+
+const byText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
+
+const plural = (n: number, one: string, many: string): string =>
+ `${fmt(n)} ${n === 1 ? one : many}`;
+
+// Only changes the grammar of template text: "1 link(s)" -> "1 link", "3 link(s)" -> "3 links".
+const settlePlurals = (text: string): string =>
+ text.replace(/\b(\d[\d,]*)(\s+)([A-Za-z]+)\(s\)/g, (_, n: string, gap: string, word: string) =>
+ n === "1" ? `${n}${gap}${word}` : `${n}${gap}${word}s`,
+ );
+
+function evidenceOf(e: C.Evidence): Evidence {
+ return {
+ id: e.id,
+ kind: e.kind,
+ blobSha: e.blob_sha,
+ path: e.path,
+ startLine: e.start_line,
+ endLine: e.end_line,
+ role: e.role,
+ commits: [...e.commits],
+ snapshotSha: e.snapshot_sha,
+ };
+}
+
+function sourceKindOf(kind: C.DecisionSource["kind"]): SourceKind {
+ return kind === "habit" ? "measured" : kind;
+}
+
+function linesOf(lines: number[] | null): [number, number] | null {
+ if (!lines || lines.length === 0) return null;
+ const start = lines[0]!;
+ return [start, lines.length > 1 ? lines[1]! : start];
+}
+
+function seriesOf(points: readonly C.TrendPoint[]): SeriesPoint[] {
+ return points
+ .map((p) => ({ date: p.snapshot_date, value: p.value }))
+ .sort((a, b) => byText(a.date, b.date));
+}
+
+function endDateOf(index: C.BundleIndex): string | null {
+ return index.snapshots.find((s) => s.role === "end")?.date ?? null;
+}
+
+/**
+ * Each checkable decision with its check at the end snapshot. A decision without a shape,
+ * or without a check at the end commit, is not counted.
+ */
+function endChecks(
+ index: C.BundleIndex,
+ file: C.DecisionsFile,
+): { decision: C.Decision; check: C.DecisionCheck | null }[] {
+ const atEnd = new Map();
+ for (const check of file.checks) {
+ if (check.snapshot_sha === index.end_sha) atEnd.set(check.decision_id, check);
+ }
+ return file.decisions
+ .filter((decision) => decision.shape !== null)
+ .map((decision) => ({ decision, check: atEnd.get(decision.id) ?? null }));
+}
+
+/** Decisions by status at the end snapshot, from `index.json` and `decisions.json` alone. */
+export function decisionStatusCounts(
+ index: C.BundleIndex,
+ file: C.DecisionsFile,
+): Record {
+ const checked = endChecks(index, file).flatMap(({ check }) => (check ? [check] : []));
+ return statusCounts(checked);
+}
+
+// A short, URL-safe hash of a finding id: two 32-bit FNV-1a passes with different seeds.
+function fnv1a(text: string, seed: number): number {
+ let h = seed >>> 0;
+ for (let i = 0; i < text.length; i++) {
+ h ^= text.charCodeAt(i);
+ h = Math.imul(h, 0x01000193) >>> 0;
+ }
+ return h >>> 0;
+}
+
+function slugBase(id: string): string {
+ const a = fnv1a(id, 0x811c9dc5).toString(16).padStart(8, "0");
+ const b = fnv1a(id, 0x2b0d1a3f).toString(16).padStart(8, "0");
+ return `${a}${b.slice(0, 2)}`;
+}
+
+/**
+ * One slug per finding id. Ids are taken in sorted order, so when two ids share a hash the
+ * later one gets "-2" (then "-3"), the same on every run.
+ */
+export function findingSlugs(ids: readonly string[]): Map {
+ const out = new Map();
+ const taken = new Set();
+ for (const id of [...new Set(ids)].sort(byText)) {
+ const base = slugBase(id);
+ let slug = base;
+ for (let n = 2; taken.has(slug); n++) slug = `${base}-${n}`;
+ taken.add(slug);
+ out.set(id, slug);
+ }
+ return out;
+}
+
+function simulationKind(
+ simulation: C.Simulation | null,
+ action: string | undefined,
+): SimulationKind {
+ if (!simulation?.simulated) return "not-simulated";
+ if (simulation.links_removed === 0 && simulation.links_added === 0) return "nothing-changed";
+ if (action && LINK_REMOVING.has(action)) return "effect-if-removed";
+ if (!simulation.target_link_removed) return "link-remains";
+ if (simulation.new_exceptions.length > 0) return "adds-exceptions";
+ return "checked";
+}
+
+function judgementOf(j: C.Judgement | null): Judgement | null {
+ if (!j || j.status !== "ai") return null;
+ const agree = j.votes.filter((v) => v === j.verdict).length;
+ return {
+ verdict: j.verdict,
+ confidence: j.confidence,
+ claim: j.claim,
+ fixText: j.fix.text,
+ action: j.fix.action,
+ symbol: j.fix.symbol,
+ from: j.fix.from,
+ to: j.fix.to,
+ votes: j.votes.length ? `${agree} of ${j.votes.length}` : "",
+ voteList: [...j.votes],
+ // An "ai" judgement is stored only after every citation passed spec.md §8.4.
+ citations: j.citations.length,
+ citationsChecked: j.citations.length,
+ model: j.model,
+ };
+}
+
+/**
+ * True when every change names two modules of the grid and its `before` count is the
+ * grid's count for that cell, so its `after` count can be drawn on the same grid.
+ */
+function onGrid(
+ changes: readonly C.CellChange[],
+ matrix: readonly number[][],
+ orderIndex: ReadonlyMap,
+): boolean {
+ return changes.every((c) => {
+ const i = orderIndex.get(c.src);
+ const j = orderIndex.get(c.dst);
+ return i !== undefined && j !== undefined && matrix[i]![j] === c.before;
+ });
+}
+
+function simulationOf(
+ s: C.Simulation | null,
+ action: string | undefined,
+ drawable: (changes: readonly C.CellChange[]) => boolean,
+): Simulation | null {
+ if (!s) return null;
+ return {
+ simulated: s.simulated,
+ targetLinkRemoved: s.target_link_removed,
+ loopsBefore: s.loops_before,
+ loopsAfter: s.loops_after,
+ linksRemoved: s.links_removed,
+ linksAdded: s.links_added,
+ newExceptions: [...s.new_exceptions],
+ cellChanges: s.cell_changes.map((c) => ({ ...c })),
+ onGrid: drawable(s.cell_changes),
+ kind: simulationKind(s, action),
+ };
+}
+
+function formatArgs(args: Record): { key: string; values: string[] }[] {
+ return Object.entries(args).map(([key, value]) => ({
+ key,
+ values: (Array.isArray(value) ? value : [value]).map((v) =>
+ typeof v === "string" ? v : JSON.stringify(v),
+ ),
+ }));
+}
+
+function healthySentence(d: Decision, date: string): string {
+ const head =
+ `${plural(d.exceptions, "exception", "exceptions")} in ` +
+ `${plural(d.opportunities, "link", "links")} the rule applies to, at ${date}.`;
+ if (!d.source.path) return head;
+ const lines = d.source.lines
+ ? d.source.lines[0] === d.source.lines[1]
+ ? `, line ${d.source.lines[0]}`
+ : `, lines ${d.source.lines[0]} to ${d.source.lines[1]}`
+ : "";
+ return `${head} Source: ${d.source.path}${lines}.`;
+}
+
+/** The languages the run read, as stored in the coverage rows, once each, sorted. */
+export function languagesOf(report: C.ReportFile): string[] {
+ return [...new Set(report.coverage.map((c) => c.language))].sort(byText);
+}
+
+/** Every stored yardstick series, by stored name, oldest point first. */
+function yardstickSeriesOf(ba: C.BeforeAfterFile): Record {
+ const out: Record = {};
+ for (const y of [...ba.yardsticks].sort((a, b) => byText(a.name, b.name))) {
+ out[y.name] = seriesOf(y.series);
+ }
+ return out;
+}
+
+/** One yardstick: the stored value now, and the stored series value at the before date. */
+function yardstickFrom(
+ report: C.ReportFile,
+ ba: C.BeforeAfterFile,
+ allSeries: Record,
+ name: string,
+): Yardstick {
+ const stored = report.yardsticks.find((y) => y.name === name);
+ const series = allSeries[name] ?? [];
+ return {
+ name,
+ unit: stored?.unit ?? null,
+ now: stored?.value ?? null,
+ before: series.find((p) => p.date === ba.before.date)?.value ?? null,
+ series,
+ };
+}
+
+/** The against-the-grain share yardstick, from `report.json` and `before_after.json` alone. */
+export function againstGrainShareOf(report: C.ReportFile, ba: C.BeforeAfterFile): Yardstick {
+ return yardstickFrom(report, ba, yardstickSeriesOf(ba), YARDSTICK.againstGrainShare);
+}
+
+/** The rank-1 finding, with the same slug the full adapter gives it; null with no findings. */
+export function fixFirstOf(
+ file: C.FindingsFile,
+): { rank: number; title: string; slug: string } | null {
+ const top = file.findings.find((f) => f.priority.rank === 1);
+ if (!top) return null;
+ const slug = findingSlugs(file.findings.map((f) => f.id)).get(top.id)!;
+ return { rank: top.priority.rank, title: settlePlurals(top.title), slug };
+}
+
+export function adaptBundle(bundle: Bundle): RepoBundle {
+ const { index, map, beforeAfter: ba, report, decisions: decisionsFile } = bundle;
+ const order = ba.module_order;
+ const orderIndex = new Map(order.map((id, i) => [id, i]));
+ const moduleOf = moduleFinder(map.nodes);
+ const names = shortNames(order);
+ const nodeById = new Map(map.nodes.map((n) => [n.id, n]));
+ const stats = new Map(map.stats.map((s) => [s.node_id, s]));
+ const descriptions = new Map(map.descriptions.map((d) => [d.node_id, d]));
+ const snapshotDate = endDateOf(index) ?? ba.after.date;
+
+ // Modules, in the one grid order shared by every date (spec.md §10.4).
+ const modules: ModuleInfo[] = order.map((id, i) => {
+ const node = nodeById.get(id);
+ const stat = stats.get(id);
+ const description = descriptions.get(id);
+ const linksIn = stat?.links_in ?? null;
+ const linksOut = stat?.links_out ?? null;
+ const links = (linksIn ?? 0) + (linksOut ?? 0);
+ return {
+ index: i,
+ id,
+ path: node?.path ?? id.slice(id.indexOf(":") + 1),
+ name: names.get(id) ?? id,
+ presentAtEnd: node !== undefined,
+ kind: node?.kind ?? null,
+ loc: stat?.loc ?? null,
+ files: stat?.files ?? null,
+ linksIn,
+ linksOut,
+ instability: linksIn !== null && linksOut !== null && links > 0 ? linksOut / links : null,
+ changes12m: stat?.changes_12m ?? null,
+ postMarchShare: stat?.share_after_2025_03 ?? null,
+ aiMarkedShare: null,
+ description: description ? { text: description.text, source: description.source } : null,
+ };
+ });
+
+ // The grid. Counts come from before_after cells, which equal the end map's module edges.
+ const matrix = matrixOf(
+ order,
+ ba.cells.map((c) => ({ src: c.src, dst: c.dst, count: c.after })),
+ );
+ const matrixBefore = matrixOf(
+ order,
+ ba.cells.map((c) => ({ src: c.src, dst: c.dst, count: c.before })),
+ );
+ const drawable = (changes: readonly C.CellChange[]) => onGrid(changes, matrix, orderIndex);
+ const batchFile = report.batch_simulation;
+ const batchOnGrid = batchFile ? drawable(batchFile.cell_changes) : false;
+ const matrixFixed =
+ batchFile && batchOnGrid ? applyCellChanges(matrix, order, batchFile.cell_changes) : null;
+
+ const cellLinks: Record = {};
+ const moduleEdges = map.edges
+ .filter((e) => e.src !== e.dst && orderIndex.has(e.src) && orderIndex.has(e.dst))
+ .sort((a, b) => byText(cellKey(a.src, a.dst), cellKey(b.src, b.dst)));
+ for (const e of moduleEdges) {
+ cellLinks[cellKey(e.src, e.dst)] = {
+ src: e.src,
+ dst: e.dst,
+ count: e.count,
+ how: e.how,
+ kind: e.kind,
+ refs: e.refs.map(evidenceOf),
+ };
+ }
+
+ // Findings, in the pipeline's rank order; never re-sorted here.
+ const allFindings = bundle.findings.findings;
+ const slugs = findingSlugs(allFindings.map((f) => f.id));
+ const position = new Map(allFindings.map((f, i) => [f.id, i]));
+ const layouts = new Map(bundle.layouts.layouts.map((l) => [l.finding_id, l.positions]));
+ const byTarget = new Map();
+ for (const f of allFindings) {
+ for (const t of f.targets) {
+ const list = byTarget.get(t.node_id) ?? [];
+ if (!list.includes(f.id)) list.push(f.id);
+ byTarget.set(t.node_id, list);
+ }
+ }
+ const gridPlace = (id: string): number => orderIndex.get(id) ?? Number.MAX_SAFE_INTEGER;
+ const byGrid = (a: string, b: string): number => gridPlace(a) - gridPlace(b) || byText(a, b);
+
+ const findingOf = (f: C.Finding): Finding => {
+ const targetModules = new Set();
+ for (const t of f.targets) {
+ const m = moduleOf(t.node_id);
+ if (m) targetModules.add(m);
+ }
+ const cells: [string, string][] = map.edges
+ .filter((e) => e.src !== e.dst && targetModules.has(e.src) && targetModules.has(e.dst))
+ .map((e): [string, string] => [e.src, e.dst])
+ .sort((a, b) => byGrid(a[0], b[0]) || byGrid(a[1], b[1]));
+ const related = new Set();
+ for (const t of f.targets) {
+ for (const id of byTarget.get(t.node_id) ?? []) if (id !== f.id) related.add(id);
+ }
+ const j = f.judgement;
+ return {
+ id: f.id,
+ slug: slugs.get(f.id)!,
+ rank: f.priority.rank,
+ type: f.type,
+ decisionId: f.decision_id,
+ title: settlePlurals(f.title),
+ summary: settlePlurals(f.summary),
+ targets: f.targets.map((t) => ({ nodeId: t.node_id, role: t.role })),
+ modules: [...targetModules].sort(byGrid),
+ facts: f.facts.map((x) => ({ key: x.key, value: x.value, unit: x.unit, source: x.source })),
+ evidence: f.evidence.map(evidenceOf),
+ priority: {
+ S: f.priority.S,
+ R: f.priority.R,
+ P: f.priority.P,
+ A: f.priority.A,
+ ease: f.priority.ease,
+ score: f.priority.score,
+ },
+ trend: {
+ firstSeen: f.trend.first_seen,
+ status: f.trend.status,
+ series: seriesOf(f.trend.series),
+ },
+ origin: {
+ linesAfter: f.origin.lines_after_2025_03,
+ linesAiMarked: f.origin.lines_ai_marked,
+ note: f.origin.note,
+ },
+ linkQuality: f.link_quality
+ ? { how: f.link_quality.how, agreement: f.link_quality.measured_agreement }
+ : null,
+ judgement: judgementOf(j),
+ computedFix: j && j.status === "template" ? { text: j.fix.text, action: j.fix.action } : null,
+ // The stored fix action decides the label whatever the AI switch says: the
+ // simulation was made for it.
+ simulation: simulationOf(f.simulation, j?.fix.action, drawable),
+ caveats: [...f.caveats],
+ cells,
+ related: [...related].sort((a, b) => position.get(a)! - position.get(b)!),
+ layout: layouts.get(f.id)?.map((p) => ({ nodeId: p.node_id, x: p.x, y: p.y })) ?? null,
+ };
+ };
+ const adapted = allFindings.map(findingOf);
+ const findings = adapted.filter((f) => f.rank >= 1 && f.rank <= TOP);
+ const supporting = adapted.filter((f) => !(f.rank >= 1 && f.rank <= TOP));
+
+ // Decisions. Authority is read from the findings that cite the rule (priority.A).
+ const authority = new Map();
+ for (const f of allFindings) {
+ if (f.decision_id && !authority.has(f.decision_id)) authority.set(f.decision_id, f.priority.A);
+ }
+ const checksOf = new Map();
+ for (const check of decisionsFile.checks) {
+ const list = checksOf.get(check.decision_id) ?? [];
+ list.push(check);
+ checksOf.set(check.decision_id, list);
+ }
+ const atEnd = new Map(
+ endChecks(index, decisionsFile).map(({ decision, check }) => [decision.id, check]),
+ );
+ const decisions: Decision[] = [];
+ const written: WrittenDecision[] = [];
+ for (const d of decisionsFile.decisions) {
+ const sourceKind = sourceKindOf(d.source.kind);
+ const lines = linesOf(d.source.lines);
+ const end = atEnd.get(d.id) ?? null;
+ if (d.shape === null || end === null) {
+ written.push({
+ id: d.id,
+ statement: d.statement,
+ source: d.source.path ?? sourceKind,
+ sourceKind,
+ sourcePath: d.source.path,
+ lines,
+ reason:
+ d.shape === null
+ ? "Not one of the four checkable shapes, so it is not checked and produces no finding."
+ : "In a checkable shape, but there is no check of it at the end snapshot.",
+ proposedBy: d.proposed_by,
+ });
+ continue;
+ }
+ const argList = formatArgs(d.args);
+ const series: DecisionPoint[] = (checksOf.get(d.id) ?? [])
+ .map((c) => ({
+ date: c.snapshot_date,
+ sha: c.snapshot_sha,
+ status: c.status,
+ conformance: c.conformance,
+ perKloc: c.exceptions_per_kloc,
+ exceptions: c.exceptions,
+ opportunities: c.opportunities,
+ modulesCovered: c.modules_covered,
+ }))
+ .sort((a, b) => byText(a.date, b.date) || byText(a.sha, b.sha));
+ decisions.push({
+ id: d.id,
+ statement: d.statement,
+ shape: d.shape,
+ args: argList
+ .map(({ key, values }) =>
+ values.length === 1 ? `${key}=${values[0]}` : `${key}=[${values.join(", ")}]`,
+ )
+ .join(", "),
+ argList,
+ source: { kind: sourceKind, path: d.source.path, lines },
+ authority: authority.get(d.id) ?? null,
+ status: end.status,
+ conformance: end.conformance,
+ opportunities: end.opportunities,
+ exceptions: end.exceptions,
+ perKloc: end.exceptions_per_kloc,
+ modulesCovered: end.modules_covered,
+ proposedBy: d.proposed_by,
+ reviewed: d.reviewed,
+ series,
+ allowed: d.exceptions_allowed.length,
+ });
+ }
+ const healthy = decisions
+ .filter((d) => d.status === "holding")
+ .map((d) => ({ decisionId: d.id, evidence: healthySentence(d, snapshotDate) }));
+
+ // Yardsticks: the stored values, never recounted from the grid.
+ const yardstickSeries = yardstickSeriesOf(ba);
+ const yardstick = (name: string): Yardstick => yardstickFrom(report, ba, yardstickSeries, name);
+
+ const batch: Batch | null = batchFile
+ ? {
+ fixesApplied: batchFile.fixes_applied,
+ fixesSkipped: batchFile.fixes_skipped,
+ loopsBefore: batchFile.loops_before,
+ loopsAfter: batchFile.loops_after,
+ linksRemoved: batchFile.links_removed,
+ linksAdded: batchFile.links_added,
+ newExceptions: [...batchFile.new_exceptions],
+ cellChanges: batchFile.cell_changes.map((c) => ({ ...c })),
+ onGrid: batchOnGrid,
+ }
+ : null;
+
+ // Only the layout ids carry their interval, as "layout/..".
+ const events: StructuralEvent[] = ba.changes.map((c) => {
+ const dates = /^layout\/(\d{4}-\d{2}-\d{2})\.\.(\d{4}-\d{2}-\d{2})$/.exec(c.id);
+ return {
+ id: c.id,
+ kind: c.kind,
+ title: c.title,
+ label: c.label,
+ basis: c.basis,
+ source: c.source,
+ evidence: c.evidence.map(evidenceOf),
+ fromDate: dates ? dates[1]! : null,
+ date: dates ? dates[2]! : null,
+ };
+ });
+
+ const hotspots = report.hotspots.map((h) => {
+ const module = moduleOf(h.node_id);
+ return {
+ path: h.path,
+ nodeId: h.node_id,
+ module,
+ moduleName: module ? (names.get(module) ?? null) : null,
+ z: h.z,
+ recent: h.recent,
+ prior: h.prior,
+ };
+ });
+
+ const productionFiles = map.nodes.filter((n) => n.level === "file" && n.kind === "production");
+
+ // File sizes for the size map: the stored node and its stats, sorted by path.
+ const fileSizes: FileSize[] = map.nodes
+ .filter((n) => n.level === "file")
+ .map((n) => {
+ const stat = stats.get(n.id);
+ return {
+ path: n.path,
+ module: moduleOf(n.id) ?? n.parent_id ?? "",
+ kind: n.kind,
+ loc: n.loc,
+ postMarchShare: stat?.share_after_2025_03 ?? null,
+ changes12m: stat?.changes_12m ?? null,
+ };
+ })
+ .sort((a, b) => byText(a.path, b.path));
+ const short = index.repo.slice(index.repo.lastIndexOf("/") + 1);
+
+ return {
+ id: index.repo_id,
+ name: index.repo,
+ short,
+ synthetic: index.synthetic,
+ host: index.host_url,
+ folder: bundle.folder,
+ languages: languagesOf(report),
+ endSha: index.end_sha,
+ snapshotDate,
+ paramsHash: index.params_hash,
+ rulesHash: null,
+ sponsorDate: sponsorDate(index),
+ adoptionDate: ba.adoption_date,
+ adoptionEvidence: null,
+ beforeDate: ba.before.date,
+ afterDate: ba.after.date,
+ prodLoc: productionFiles.reduce((sum, n) => sum + n.loc, 0),
+ prodFiles: productionFiles.length,
+ weights: Object.fromEntries(Object.entries(report.weights).sort(([a], [b]) => byText(a, b))),
+ modules,
+ matrix,
+ matrixBefore,
+ matrixFixed,
+ cellLinks,
+ decisions,
+ written,
+ findings,
+ supporting,
+ yardsticks: {
+ againstGrain: yardstick(YARDSTICK.againstGrain),
+ againstGrainShare: yardstick(YARDSTICK.againstGrainShare),
+ twoWayPairs: yardstick(YARDSTICK.twoWayPairs),
+ perKloc: yardstick(YARDSTICK.perKloc),
+ crossModule: yardstick(YARDSTICK.crossModule),
+ },
+ yardstickSeries,
+ grainSeries: yardstickSeries[YARDSTICK.againstGrainShare] ?? [],
+ batch,
+ events,
+ hotspots,
+ linkChanges: null,
+ aiRisk: null,
+ aiShareSeries: null,
+ coverage: report.coverage.map((c) => ({
+ language: c.language,
+ files: c.files_read,
+ unread: c.files_with_unread,
+ linked: c.imports_linked_share,
+ outside: c.imports_outside_share,
+ unexplained: c.imports_unexplained,
+ linkAgreement: c.link_agreement,
+ fileAgreement: null,
+ moduleAgreement: null,
+ })),
+ silentMiss: null,
+ blindSpots: [...report.limits],
+ stability: report.stability.map((s) => ({
+ test: s.test,
+ top5: s.top5_overlap,
+ top10: s.top10_overlap,
+ rbo: s.rbo,
+ note: null,
+ })),
+ usage: report.usage.map((u) => ({
+ job: u.job,
+ model: u.model,
+ calls: u.calls,
+ tokensIn: u.input_tokens,
+ tokensOut: u.output_tokens,
+ cached: u.cached_calls,
+ cachedInputTokens: u.cached_input_tokens,
+ cost: u.cost_usd,
+ })),
+ healthy,
+ snapshots: index.snapshots.map((s) => s.date).sort(byText),
+ fileSizes: fileSizes.length > 0 ? fileSizes : null,
+ };
+}
diff --git a/web/src/data/bundle.ts b/web/src/data/bundle.ts
index 897899ce..668391af 100644
--- a/web/src/data/bundle.ts
+++ b/web/src/data/bundle.ts
@@ -32,7 +32,7 @@ export function sponsorDate(index: BundleIndex): string | null {
return index.snapshots.find((snapshot) => snapshot.role === "sponsor_date")?.date ?? null;
}
-type FetchJson = (url: string) => Promise;
+export type FetchJson = (url: string) => Promise;
const fetchJson: FetchJson = async (url) => {
const response = await fetch(url);
@@ -98,6 +98,65 @@ export async function loadBundle(
return { index, findings, decisions, map, layouts, beforeAfter, report, folder };
}
+/**
+ * Only `index.json` and `decisions.json` of one bundle: enough for a list of repositories
+ * without loading every map.
+ */
+export async function loadBundleSummary(
+ indexPath: string,
+ root = bundlesRoot(),
+ get: FetchJson = fetchJson,
+): Promise> {
+ const indexUrl = `${root}${indexPath}`;
+ const folder = indexUrl.slice(0, indexUrl.lastIndexOf("/") + 1);
+ const index = expectSchema(await get(indexUrl), "codexray.bundle/1", indexUrl);
+ const file = index.files["decisions"];
+ if (!file) throw new Error(`${indexUrl} lists no "decisions" file`);
+ const decisions = expectSchema(
+ await get(folder + file),
+ "codexray.decisions/1",
+ folder + file,
+ );
+ return { index, decisions, folder };
+}
+
+/**
+ * What a repository card on the landing page needs: `index.json`, `decisions.json`,
+ * `report.json` and `before_after.json`. The map and the findings are left out, so the
+ * card never waits for the largest files.
+ */
+export async function loadBundleCard(
+ indexPath: string,
+ root = bundlesRoot(),
+ get: FetchJson = fetchJson,
+): Promise> {
+ const { index, decisions, folder } = await loadBundleSummary(indexPath, root, get);
+ const part = async (key: string, schema: T["schema"]) => {
+ const file = index.files[key];
+ if (!file) throw new Error(`${folder}index.json lists no "${key}" file`);
+ return expectSchema(await get(folder + file), schema, folder + file);
+ };
+ const [report, beforeAfter] = await Promise.all([
+ part("report", "codexray.report/1"),
+ part("before_after", "codexray.before_after/1"),
+ ]);
+ return { index, decisions, report, beforeAfter, folder };
+}
+
+/** Only `findings.json` of one bundle, for the "fix first" line of a repository card. */
+export async function loadBundleFindings(
+ indexPath: string,
+ root = bundlesRoot(),
+ get: FetchJson = fetchJson,
+): Promise {
+ const indexUrl = `${root}${indexPath}`;
+ const folder = indexUrl.slice(0, indexUrl.lastIndexOf("/") + 1);
+ const index = expectSchema(await get(indexUrl), "codexray.bundle/1", indexUrl);
+ const file = index.files["findings"];
+ if (!file) throw new Error(`${indexUrl} lists no "findings" file`);
+ return expectSchema(await get(folder + file), "codexray.findings/1", folder + file);
+}
+
// Keyed by file URL. A blob's content never changes, so a cached file stays correct.
const codeCache = new Map>();
@@ -106,14 +165,19 @@ const codeCache = new Map>();
* is fetched once; later calls for the same bundle and blob reuse the first result.
*/
export function loadCode(bundle: Bundle, blobSha: string): Promise {
+ return loadCodeAt(bundle.folder, blobSha);
+}
+
+/** The same as `loadCode`, for a caller that holds only the bundle folder URL. */
+export function loadCodeAt(folder: string, blobSha: string): Promise {
if (!/^[0-9a-f]+$/.test(blobSha)) {
return Promise.reject(new Error(`${JSON.stringify(blobSha)} is not a blob id`));
}
- const url = `${bundle.folder}code/${blobSha}.json`;
+ const url = `${folder}code/${blobSha}.json`;
const cached = codeCache.get(url);
if (cached) return cached;
- const get = readers.get(bundle.folder) ?? fetchJson;
+ const get = readers.get(folder) ?? fetchJson;
const loading = get(url).then((data) => {
const code = expectSchema(data, "codexray.code/1", url);
if (code.blob_sha !== blobSha) {
diff --git a/web/src/data/context.tsx b/web/src/data/context.tsx
deleted file mode 100644
index 7c44ba8c..00000000
--- a/web/src/data/context.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-// The list of repositories the app can open, from bundles/index.json. App.tsx provides
-// it, so any component can offer a repository switch without new props.
-import { createContext, type ReactNode, useContext } from "react";
-import type { BundleListEntry } from "../contracts/generated";
-
-// Outside a provider (for example a screen rendered alone in a test) the list is empty.
-const BundlesContext = createContext([]);
-
-export function BundlesProvider({
- bundles,
- children,
-}: {
- bundles: BundleListEntry[];
- children: ReactNode;
-}) {
- return {children} ;
-}
-
-/** Every repository the app can open, in the order of bundles/index.json. */
-export function useBundles(): BundleListEntry[] {
- return useContext(BundlesContext);
-}
diff --git a/web/src/data/journeys.ts b/web/src/data/journeys.ts
new file mode 100644
index 00000000..9ed80a78
--- /dev/null
+++ b/web/src/data/journeys.ts
@@ -0,0 +1,62 @@
+// Journeys: one user action traced through the main modules, step by step. They sit next to a
+// repository's bundle as `journeys.json`; a repository without that file has no journeys and
+// the screens leave the Journeys tab out.
+import { bundlesRoot } from "./bundle";
+import { loadRepoList } from "./repo";
+
+export type JourneyVia = { kind: "call" | "queue" | "ws" | "find"; label: string } | null;
+
+export interface JourneyStop {
+ /** Index into the bundle's lanes. */
+ lane: number;
+ module: string;
+ /** A short verb phrase shown on the node. */
+ label: string;
+ /** One sentence for a newcomer. */
+ caption: string;
+ /** "path:line" of the code that runs at this stop. */
+ file: string;
+ method: string;
+ /** How the request reached this stop; null on the first stop. */
+ via: JourneyVia;
+ /** Set when this step is a ranked finding. */
+ findingRank: number | null;
+ payload: { type: string; definedIn: string; fields: { key: string; value: string }[] };
+}
+
+export interface Journey {
+ id: string;
+ name: string;
+ summary: string;
+ stops: JourneyStop[];
+}
+
+export interface JourneyBundle {
+ lanes: string[];
+ journeys: Journey[];
+}
+
+const loaded = new Map>();
+
+/** The repository's journeys, or null when its bundle folder holds none. */
+export function loadJourneys(repoId: string): Promise {
+ const hit = loaded.get(repoId);
+ if (hit) return hit;
+ const loading = (async () => {
+ const entry = (await loadRepoList()).find((b) => b.repo_id === repoId);
+ if (!entry) return null;
+ const folder = entry.path.includes("/")
+ ? entry.path.slice(0, entry.path.lastIndexOf("/") + 1)
+ : "";
+ try {
+ const res = await fetch(`${bundlesRoot()}${folder}journeys.json`);
+ if (!res.ok) return null;
+ const data = (await res.json()) as JourneyBundle;
+ return Array.isArray(data.journeys) && data.journeys.length > 0 ? data : null;
+ } catch {
+ return null;
+ }
+ })();
+ loaded.set(repoId, loading);
+ return loading;
+}
diff --git a/web/src/data/repo.ts b/web/src/data/repo.ts
new file mode 100644
index 00000000..cb50b1f0
--- /dev/null
+++ b/web/src/data/repo.ts
@@ -0,0 +1,174 @@
+// Loads repositories for the screens. The list of repositories always comes from
+// `bundles/index.json`. Each result is kept in memory per repository id, so switching tabs
+// or screens never fetches the same bundle twice.
+import type { BundleListEntry, CodeFile } from "../contracts/generated";
+import { statusCounts } from "../cx/meta";
+import type { FixFirst, RepoBundle, RepoCard, RepoSummary } from "../cx/types";
+import {
+ adaptBundle,
+ againstGrainShareOf,
+ decisionStatusCounts,
+ fixFirstOf,
+ languagesOf,
+} from "./adapt";
+import {
+ type FetchJson,
+ loadBundle,
+ loadBundleCard,
+ loadBundleFindings,
+ loadBundleList,
+ loadBundleSummary,
+ loadCodeAt,
+ sponsorDate,
+} from "./bundle";
+
+export interface RepoSource {
+ /** The bundle list, in its stored order. */
+ list(): Promise;
+ /** Light summaries of every listed repository: two small files each. */
+ summaries(): Promise;
+ /** The light summary of one repository. */
+ summary(id: string): Promise;
+ /** The full repository, adapted for the screens. */
+ repo(id: string): Promise;
+ /** A landing-page card: four small files, never the map or the findings. */
+ card(id: string): Promise;
+ /** The rank-1 finding, from the findings file alone; null when there is none. */
+ fixFirst(id: string): Promise;
+}
+
+/** Keeps a promise per key; a failed load is dropped so the screen can try again. */
+function cached(store: Map>, key: string, load: () => Promise) {
+ const hit = store.get(key);
+ if (hit) return hit;
+ const loading = load();
+ store.set(key, loading);
+ loading.catch(() => store.delete(key));
+ return loading;
+}
+
+/**
+ * A source of repositories read from `root` (the bundles folder) through `get`. Both
+ * default to the app's own: the `bundles/` folder next to the page, fetched over HTTP.
+ */
+export function createRepoSource(root?: string, get?: FetchJson): RepoSource {
+ let listing: Promise | null = null;
+ const fulls = new Map>();
+ const summaries = new Map>();
+ const cards = new Map>();
+ const tops = new Map>();
+
+ const list = (): Promise => {
+ if (!listing) {
+ const loading = loadBundleList(root, get).then((l) => l.bundles);
+ listing = loading;
+ loading.catch(() => {
+ if (listing === loading) listing = null;
+ });
+ }
+ return listing;
+ };
+
+ const entry = async (id: string): Promise => {
+ const found = (await list()).find((b) => b.repo_id === id);
+ if (!found) throw new Error(`bundles/index.json lists no "${id}" bundle`);
+ return found;
+ };
+
+ const repo = (id: string): Promise =>
+ cached(fulls, id, async () => adaptBundle(await loadBundle((await entry(id)).path, root, get)));
+
+ const summary = (id: string): Promise =>
+ cached(summaries, id, async () => {
+ const e = await entry(id);
+ // A repository already loaded in full needs no further request.
+ const full = fulls.get(id);
+ if (full) {
+ const r = await full;
+ return {
+ id: r.id,
+ label: e.label,
+ name: r.name,
+ synthetic: r.synthetic,
+ snapshotDate: r.snapshotDate,
+ statusCounts: statusCounts(r.decisions),
+ };
+ }
+ const { index, decisions } = await loadBundleSummary(e.path, root, get);
+ return {
+ id: index.repo_id,
+ label: e.label,
+ name: index.repo,
+ synthetic: index.synthetic,
+ snapshotDate: index.snapshots.find((s) => s.role === "end")?.date ?? null,
+ statusCounts: decisionStatusCounts(index, decisions),
+ };
+ });
+
+ const all = async (): Promise =>
+ Promise.all((await list()).map((b) => summary(b.repo_id)));
+
+ const card = (id: string): Promise =>
+ cached(cards, id, async () => {
+ const e = await entry(id);
+ const full = fulls.get(id);
+ if (full) {
+ const r = await full;
+ return {
+ ...(await summary(id)),
+ languages: r.languages,
+ sponsorDate: r.sponsorDate,
+ beforeDate: r.beforeDate,
+ againstGrainShare: r.yardsticks.againstGrainShare,
+ };
+ }
+ const { index, decisions, report, beforeAfter } = await loadBundleCard(e.path, root, get);
+ return {
+ id: index.repo_id,
+ label: e.label,
+ name: index.repo,
+ synthetic: index.synthetic,
+ snapshotDate: index.snapshots.find((s) => s.role === "end")?.date ?? null,
+ statusCounts: decisionStatusCounts(index, decisions),
+ languages: languagesOf(report),
+ sponsorDate: sponsorDate(index),
+ beforeDate: beforeAfter.before.date,
+ againstGrainShare: againstGrainShareOf(report, beforeAfter),
+ };
+ });
+
+ const fixFirst = (id: string): Promise =>
+ cached(tops, id, async () => {
+ const full = fulls.get(id);
+ if (full) {
+ const top = (await full).findings.find((f) => f.rank === 1);
+ return top ? { rank: top.rank, title: top.title, slug: top.slug } : null;
+ }
+ return fixFirstOf(await loadBundleFindings((await entry(id)).path, root, get));
+ });
+
+ return { list, summaries: all, summary, repo, card, fixFirst };
+}
+
+let appSource: RepoSource | null = null;
+const source = (): RepoSource => (appSource ??= createRepoSource());
+
+/** The bundle list of the app. */
+export const loadRepoList = (): Promise => source().list();
+/** Summaries for the landing page and the repository switcher. */
+export const loadRepoSummaries = (): Promise => source().summaries();
+export const loadRepoSummary = (id: string): Promise => source().summary(id);
+/** One landing-page card per id, without the map or the findings. */
+export const loadRepoCard = (id: string): Promise => source().card(id);
+/** The rank-1 finding of one repository, loaded after its card. */
+export const loadRepoFixFirst = (id: string): Promise => source().fixFirst(id);
+/** One full repository, fetched once per id. */
+export const loadRepo = (id: string): Promise => source().repo(id);
+
+/** The text of one cited file of a loaded repository (`code/.json`), fetched once. */
+export function loadEvidenceCode(
+ repo: Pick,
+ blobSha: string,
+): Promise {
+ return loadCodeAt(repo.folder, blobSha);
+}
diff --git a/web/src/data/testing.ts b/web/src/data/testing.ts
index ca9169aa..e20ba024 100644
--- a/web/src/data/testing.ts
+++ b/web/src/data/testing.ts
@@ -1,13 +1,15 @@
// For screen tests only: reads the committed synthetic bundles from disk through the
// same loader the app uses. App code must not import this file; it uses Node modules.
import { readFile } from "node:fs/promises";
-import { fileURLToPath } from "node:url";
+import { join } from "node:path";
import { type Bundle, loadBundle, loadBundleList } from "./bundle";
-const publicFolder = new URL("../../public/", import.meta.url);
+// Vitest runs from the web/ folder. In the test environment `import.meta.url` is an http
+// address, not a file path, so the folder is found from the working directory.
+const fromPublic = (url: string): string => join(process.cwd(), "public", url);
const fromDisk = async (url: string): Promise =>
- JSON.parse(await readFile(fileURLToPath(new URL(url, publicFolder)), "utf8"));
+ JSON.parse(await readFile(fromPublic(url), "utf8"));
export async function loadFixture(repoId: "fixture" | "fixture-wide"): Promise {
const list = await loadBundleList("bundles/", fromDisk);
@@ -15,3 +17,26 @@ export async function loadFixture(repoId: "fixture" | "fixture-wide"): Promise void {
+ const previous = globalThis.fetch;
+ globalThis.fetch = (async (input: RequestInfo | URL) => {
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
+ const at = url.indexOf("bundles/");
+ if (at < 0) return new Response(null, { status: 404 });
+ try {
+ const text = await readFile(fromPublic(url.slice(at)), "utf8");
+ return new Response(text, { headers: { "content-type": "application/json" } });
+ } catch {
+ return new Response(null, { status: 404 });
+ }
+ }) as typeof fetch;
+ return () => {
+ globalThis.fetch = previous;
+ };
+}
diff --git a/web/src/data/view.ts b/web/src/data/view.ts
deleted file mode 100644
index fa394eef..00000000
--- a/web/src/data/view.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-// The address bar is the only state shared between screens (spec.md §10.3): every view
-// has a permanent link, and the same view always gives the same link.
-import { useMemo } from "react";
-import { useSearchParams } from "react-router";
-
-export interface View {
- finding?: string;
- /** "~", two module node ids. */
- cell?: string;
- /** ":-", a line range in one file. */
- at?: string;
- /** Snapshot date. */
- snapshot?: string;
- fix?: "one" | "all";
- ai?: "off";
-}
-
-// The order parameters are written in. Changing it changes every link.
-const KEYS = ["finding", "cell", "at", "snapshot", "fix", "ai"] as const;
-type Key = (typeof KEYS)[number];
-const IS_KEY = new Set(KEYS);
-
-function readView(params: URLSearchParams): View {
- const view: View = {};
- for (const key of KEYS) {
- const value = params.get(key);
- if (!value) continue;
- if (key === "fix") {
- if (value === "one" || value === "all") view.fix = value;
- } else if (key === "ai") {
- if (value === "off") view.ai = value;
- } else {
- view[key] = value;
- }
- }
- return view;
-}
-
-/** The view's parameters in fixed order, then any other parameters as they were. */
-function writeView(view: View, others?: URLSearchParams): URLSearchParams {
- const params = new URLSearchParams();
- for (const key of KEYS) {
- const value = view[key as Key];
- if (value) params.append(key, value);
- }
- others?.forEach((value, key) => {
- if (!IS_KEY.has(key)) params.append(key, value);
- });
- return params;
-}
-
-export function useView(): View {
- const [params] = useSearchParams();
- const search = params.toString();
- // A new object only when the address really changes.
- return useMemo(() => readView(new URLSearchParams(search)), [search]);
-}
-
-/** Merges a patch into the current address. A key set to `undefined` is removed. */
-export function useSetView(): (patch: Partial) => void {
- const [, setParams] = useSearchParams();
- return (patch) =>
- setParams((current) => {
- const next: View = { ...readView(current) };
- for (const [key, value] of Object.entries(patch) as [Key, string | undefined][]) {
- if (value === undefined) delete next[key];
- else Object.assign(next, { [key]: value });
- }
- return writeView(next, current);
- });
-}
-
-/** A link to one screen of one repository, for example "/fixture/grid?finding=F1". */
-export function viewLink(repoId: string, screenPath: string, view: View = {}): string {
- const search = writeView(view).toString();
- const path = `/${encodeURIComponent(repoId)}/${encodeURIComponent(screenPath)}`;
- return search ? `${path}?${search}` : path;
-}
diff --git a/web/src/main.tsx b/web/src/main.tsx
index 790b7b75..9323010a 100644
--- a/web/src/main.tsx
+++ b/web/src/main.tsx
@@ -1,7 +1,6 @@
-import "@fontsource-variable/hanken-grotesk";
+import "@fontsource-variable/instrument-sans";
import "@fontsource-variable/jetbrains-mono";
-import "./styles/tokens.css";
-import "./styles/base.css";
+import "./styles/globals.css";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
diff --git a/web/src/routes/Change.tsx b/web/src/routes/Change.tsx
new file mode 100644
index 00000000..09a19b7e
--- /dev/null
+++ b/web/src/routes/Change.tsx
@@ -0,0 +1,389 @@
+import { ArrowRight } from "lucide-react";
+import { Link } from "react-router";
+import { AiBadge, ComputedMark } from "../components/cx/badges";
+import { FOCUS, cn } from "../components/cx/cn";
+import { Panel, SectionHead } from "../components/cx/primitives";
+import { SeriesChart } from "../components/cx/series-chart";
+import { useTitle } from "../components/cx/use-page";
+import { findingPath } from "../cx/address";
+import { fmt, hostLink, pct } from "../cx/meta";
+import type { RepoBundle, StructuralEvent } from "../cx/types";
+import { Drift } from "./change/drift";
+import { Impact } from "./change/impact";
+import { LabelChip, StructuralEvents, labelCounts } from "./change/events";
+import { ShowMoreButton, useShowMore } from "./decisions/show-more";
+import { useRepo } from "./RepoLayout";
+
+/** Hotspots and new links shown before "Show all". */
+const FIRST = 5;
+
+const pathLinkCls = cn("rounded-sm hover:underline decoration-border underline-offset-2", FOCUS);
+
+/** "March 2025" for "2025-03-01", read as a calendar date with no time zone. */
+function monthYear(date: string): string {
+ return new Date(`${date}T00:00:00Z`).toLocaleString("en-US", {
+ month: "long",
+ year: "numeric",
+ timeZone: "UTC",
+ });
+}
+
+/** The Before and after screen: what changed around the comparison date, descriptive only. */
+export function Change() {
+ const repo = useRepo();
+ useTitle(`Before and after · ${repo.name}`);
+ return (
+
+ );
+}
+
+function Header({ repo }: { repo: RepoBundle }) {
+ const series = repo.aiShareSeries;
+ const compared = repo.sponsorDate ?? repo.beforeDate;
+ return (
+
+
+
+ Before and after {monthYear(compared)}
+
+
+ Did the structure get better or worse once the team started using AI coding tools?
+
+
+ This page shows what changed between the two dates. It does not blame any change on AI:
+ only commits with an explicit AI marker are counted as AI, so that share is a lower bound,
+ and everything else is no AI signal.
+
+
+
+ Comparison date:
+ {compared}
+
+ {repo.adoptionDate && (
+
+ Detected adoption date:
+ {repo.adoptionDate}
+
+ )}
+ {repo.adoptionEvidence && (
+
+ Adoption evidence:
+ {repo.adoptionEvidence}
+
+ )}
+
+
+ {series && (
+
+
+ Share of commits with an explicit AI marker
+ {series.length > 0 && (
+
+ {pct(series.at(-1)!.value, 0)}
+
+ )}
+
+ p.value), 0.1)]}
+ label="Share of commits with an explicit AI marker"
+ />
+
+ )}
+
+ );
+}
+
+/** One sentence naming the AI-marker comparisons this bundle does not hold; null when it holds both. */
+function missingAiData(repo: RepoBundle): string | null {
+ const gaps: string[] = [];
+ if (repo.aiShareSeries === null) gaps.push("no series of AI-marked commits over time");
+ if (repo.aiRisk === null) gaps.push("no comparison of AI-marked and no-signal changes by size");
+ if (gaps.length === 0) return null;
+ return `This report holds ${gaps.join(" and ")}.`;
+}
+
+function Hotspots({ repo }: { repo: RepoBundle }) {
+ const { shown, all, toggle } = useShowMore(repo.hotspots, FIRST);
+ const maxZ = Math.max(...repo.hotspots.map((h) => h.z), 1);
+ return (
+
+
+
+ Files that changed far more often in the last 3 months than their own history predicts. New
+ files and restructuring commits are left out.
+
+ {repo.hotspots.length === 0 ? (
+ No file met the rule in this run.
+ ) : (
+ <>
+
+
+ >
+ )}
+
+ );
+}
+
+/** Source and target module of a link event, read from its id ("...M:->"), by short name. */
+function linkEnds(repo: RepoBundle, e: StructuralEvent): [string, string] | null {
+ const m = /(M:.*?)-?>(M:.*)$/.exec(e.id);
+ if (!m) return null;
+ const name = (id: string) =>
+ repo.modules.find((x) => x.id === id)?.name ?? id.slice(id.indexOf(":") + 1);
+ return [name(m[1]!), name(m[2]!)];
+}
+
+function NewLinks({ repo }: { repo: RepoBundle }) {
+ const added = repo.events.filter((e) => e.kind === "link_added");
+ const { shown, all, toggle } = useShowMore(added, FIRST);
+ const c = labelCounts(added);
+ const plan = repo.linkChanges && {
+ expected_found: repo.linkChanges.filter((l) => l.label === "expected_found").length,
+ found_not_expected: repo.linkChanges.filter((l) => l.label === "found_not_expected").length,
+ expected_missing: repo.linkChanges.filter((l) => l.label === "expected_missing").length,
+ };
+ return (
+
+
+
+
+ {fmt(added.length)} new {added.length === 1 ? "link" : "links"} between modules:{" "}
+ {fmt(c.planned)} planned, {fmt(c.none)} unexplained. Each one's evidence is listed under
+ "Show every change" above.
+
+ {plan && (
+
+ Against the written plan, by module pair: {fmt(plan.expected_found)} expected and found,{" "}
+ {fmt(plan.found_not_expected)} found but not expected, {fmt(plan.expected_missing)}{" "}
+ expected but missing.
+
+ )}
+
+ {added.length === 0 ? (
+ No new link between modules in this run.
+ ) : (
+ <>
+
+ {shown.map((e) => {
+ const ends = linkEnds(repo, e);
+ return (
+
+
+ {ends ? (
+ <>
+ {ends[0]}
+
+ {ends[1]}
+ >
+ ) : (
+ {e.id}
+ )}
+
+
+
+ {e.source === "ai" ? : null}
+
+
+ );
+ })}
+
+
+ >
+ )}
+
+ );
+}
+
+function AiRisk({ repo }: { repo: RepoBundle }) {
+ const sponsor = repo.sponsorDate ?? repo.beforeDate;
+ const missing = missingAiData(repo);
+ return (
+
+ {repo.aiRisk && (
+
+
+
+
+
+
+ change size
+ AI-marked
+ no signal
+
+
+
+ {repo.aiRisk.map((r) => (
+
+ {r.band}
+
+ {r.aiMarked.toFixed(3)}{" "}
+ n={fmt(r.aiCount)}
+
+
+ {r.noSignal.toFixed(3)}{" "}
+ n={fmt(r.noSignalCount)}
+
+
+ ))}
+
+
+
+
+ )}
+
+
+ } />
+
+ For each top finding: how much of the code behind it changed after {sponsor}, and how much
+ of that carries an explicit AI marker. Each line counts toward the last change that
+ touched it. Only explicit markers count as AI, so the AI share is a lower bound.
+ {missing && ` ${missing}`}
+
+ {repo.findings.length === 0 ? (
+ No finding was ranked in this run.
+ ) : (
+
+
+
+
+
+ rank
+
+
+ finding
+
+
+ lines last changed after {sponsor}
+
+
+ lines with an AI marker (lower bound)
+
+
+
+
+ {repo.findings.map((f) => (
+
+
+ {f.rank}
+
+
+
+ {f.title}
+
+
+
+ {pct(f.origin.linesAfter, 0)}
+
+
+ {pct(f.origin.linesAiMarked, 0)}
+
+
+ ))}
+
+
+
+ )}
+
+
+ );
+}
diff --git a/web/src/routes/Decisions.tsx b/web/src/routes/Decisions.tsx
new file mode 100644
index 00000000..c45f03e5
--- /dev/null
+++ b/web/src/routes/Decisions.tsx
@@ -0,0 +1,320 @@
+import { ArrowLeft, ChevronRight } from "lucide-react";
+import type { ReactNode } from "react";
+import { Link } from "react-router";
+import { AiBadge, ComputedMark } from "../components/cx/badges";
+import { FOCUS, cn } from "../components/cx/cn";
+import { Eyebrow, StatusDot, StatusPill } from "../components/cx/primitives";
+import { Sparkline, markIndex } from "../components/cx/sparkline";
+import { useTitle } from "../components/cx/use-page";
+import { findingPath, repoPath } from "../cx/address";
+import { SHAPE, SOURCE, STATUS, STATUS_ORDER, fmt, hostLink, pct, statusCounts } from "../cx/meta";
+import type { Decision, RepoBundle, SourceKind, WrittenDecision } from "../cx/types";
+import { ShowMoreButton, useShowMore } from "./decisions/show-more";
+import { useRepo } from "./RepoLayout";
+
+/** Written, not checkable statements shown before "Show all". */
+const WRITTEN_SHOWN = 10;
+/** Width of a decision's trend line, in CSS pixels. */
+const TREND_W = 160;
+
+const byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
+
+const sourceLinkCls = cn(
+ "rounded-sm text-foreground underline decoration-border underline-offset-2 hover:decoration-foreground",
+ FOCUS,
+);
+const summaryBase = cn(
+ "inline-flex cursor-pointer list-none items-center gap-1 rounded-sm text-muted-foreground hover:text-foreground [&::-webkit-details-marker]:hidden",
+ FOCUS,
+);
+
+/** The decisions page (spec.md §10.2 screen 1): every checked decision as one compact row. */
+export function Decisions() {
+ const repo = useRepo();
+ useTitle(`Decisions checked · ${repo.name}`);
+ const compareDate = repo.sponsorDate ?? repo.beforeDate;
+ const list = [...repo.decisions].sort(
+ (a, b) => STATUS[a.status].order - STATUS[b.status].order || byText(a.id, b.id),
+ );
+
+ return (
+
+
+
+ Back to the report
+
+ Decisions · {fmt(list.length)} checked
+ Decisions checked
+
+ Decisions come from what the project enforces in its build and tests, what its documents
+ say, and habits the code measurably keeps; conformance is the share of links where a
+ decision could apply and is kept.
+
+
+
+ {list.length === 0 ? (
+ No decision could be checked in this run.
+ ) : (
+
+
+
+ {list.map((d) => (
+
+ ))}
+
+
+ )}
+
+
+
+ );
+}
+
+/** The statuses with their counts on one line; each status's test is in its tooltip. */
+function StatusLegend({ decisions, compareDate }: { decisions: Decision[]; compareDate: string }) {
+ const counts = statusCounts(decisions);
+ return (
+
+ {STATUS_ORDER.map((s) => (
+
+
+ {STATUS[s].label}
+ {counts[s]}
+
+ ))}
+ dashed line on a trend: {compareDate}
+
+ );
+}
+
+/** Who wrote the decision's statement: the AI badge, the computed mark, or "by hand". */
+function Origin({ d }: { d: Pick }) {
+ if (d.proposedBy === "ai") return ;
+ if (d.proposedBy === "computed") return ;
+ return (
+
+ by hand
+
+ );
+}
+
+/** The source as "path#Ls-e", linked to the host at the end commit when there is one. */
+function SourceRef({
+ repo,
+ kind,
+ path,
+ lines,
+}: {
+ repo: RepoBundle;
+ kind: SourceKind;
+ path: string | null;
+ lines: [number, number] | null;
+}) {
+ if (!path) return {kind === "universal" ? "built-in" : SOURCE[kind]} ;
+ const text = `${path}${lines ? (lines[0] === lines[1] ? `#L${lines[0]}` : `#L${lines[0]}-${lines[1]}`) : ""}`;
+ const href = hostLink(repo, path, lines?.[0], lines?.[1]);
+ return href ? (
+
+ {text}
+
+ ) : (
+ {text}
+ );
+}
+
+function Trend({ d, compareDate }: { d: Decision; compareDate: string }) {
+ const values = d.series.map((s) => s.conformance);
+ const dates = d.series.map((s) => s.date);
+ if (values.length === 0) return null;
+ if (values.length === 1) {
+ return (
+ one check, at {dates[0]}
+ );
+ }
+ return (
+
+
+
+ {dates[0]!.slice(0, 7)}
+ {dates.at(-1)!.slice(0, 7)}
+
+
+ );
+}
+
+function RuleRow({
+ repo,
+ d,
+ compareDate,
+}: {
+ repo: RepoBundle;
+ d: Decision;
+ compareDate: string;
+}) {
+ const findings = repo.findings.filter((f) => f.decisionId === d.id);
+ return (
+
+
+
+
+
+
+ {d.statement}
+
+
+ {findings.length > 0 && (
+
+ {findings.map((f) => (
+
+
+ #{f.rank}
+ {f.title}
+
+
+ ))}
+
+ )}
+
+
+
+
+
+ {pct(d.conformance)}
+
+
+ {fmt(d.exceptions)} of {fmt(d.opportunities)} links break it
+
+
+
+
+
+
+
+ );
+}
+
+/** The technical detail of one decision, closed until asked for. */
+function RuleDetails({ repo, d }: { repo: RepoBundle; d: Decision }) {
+ const rows: [string, ReactNode][] = [
+ ["shape", SHAPE[d.shape]],
+ ...d.argList.map(({ key, values }): [string, ReactNode] => [key, values.join(", ")]),
+ ["id", d.id],
+ [
+ "source",
+ <>
+ {SOURCE[d.source.kind]}
+ {d.source.path && (
+ <>
+ {" · "}
+
+ >
+ )}
+ >,
+ ],
+ ];
+ if (d.proposedBy === "ai") {
+ rows.push(["proposed", d.reviewed ? "by an AI model, reviewed" : "by an AI model, not reviewed"]);
+ }
+ if (d.authority !== null) rows.push(["authority", d.authority.toFixed(2)]);
+ rows.push(
+ ["opportunities", fmt(d.opportunities)],
+ ["exceptions", fmt(d.exceptions)],
+ ["per 1,000 lines", d.perKloc.toFixed(2)],
+ ["modules covered", fmt(d.modulesCovered)],
+ ["allowed exceptions", fmt(d.allowed)],
+ );
+ return (
+
+
+
+ Details
+
+
+ {rows.map(([k, v]) => (
+
+ {k}
+ {v}
+
+ ))}
+
+
+ );
+}
+
+function Written({ repo }: { repo: RepoBundle }) {
+ const { shown, all, toggle } = useShowMore(repo.written, WRITTEN_SHOWN);
+ const n = repo.written.length;
+ if (n === 0) return null;
+ return (
+
+
+
+ {fmt(n)} written {n === 1 ? "decision cannot" : "decisions cannot"} be checked by machine
+
+
+
+ {shown.map((w) => (
+
+ ))}
+
+
+
+
+ );
+}
+
+function WrittenRow({ repo, w }: { repo: RepoBundle; w: WrittenDecision }) {
+ return (
+
+
+ “{w.statement}”
+ {w.proposedBy === "ai" && }
+
+
+
+
+
+ {w.reason}
+
+
+ );
+}
diff --git a/web/src/routes/FindingDetail.tsx b/web/src/routes/FindingDetail.tsx
new file mode 100644
index 00000000..a04830b4
--- /dev/null
+++ b/web/src/routes/FindingDetail.tsx
@@ -0,0 +1,203 @@
+import { ArrowLeft } from "lucide-react";
+import { Link, useParams } from "react-router";
+import { EvidencePane } from "../components/cx/code-block";
+import { allFindings } from "../components/cx/finding-fix";
+import { ComputedMark } from "../components/cx/badges";
+import { FOCUS, cn } from "../components/cx/cn";
+import { Chip, Prose } from "../components/cx/primitives";
+import { useTitle } from "../components/cx/use-page";
+import { findingPath, repoPath } from "../cx/address";
+import { TYPE, fmt } from "../cx/meta";
+import type { Finding, RepoBundle } from "../cx/types";
+import { ShowMoreButton, useShowMore } from "./decisions/show-more";
+import { Reading } from "./finding/Reading";
+import { CloseupPanel, DecisionCard, FactsPanel, PriorityPanel, TrendPanel } from "./finding/Rail";
+import { NotFound } from "./NotFound";
+import { useJourneys, useRepo } from "./RepoLayout";
+
+/** One finding of one repository, found by its slug among the top 10 and the rest. */
+export function FindingDetail() {
+ const repo = useRepo();
+ const slug = useParams().slug ?? "";
+ const finding =
+ repo.findings.find((f) => f.slug === slug) ?? repo.supporting.find((f) => f.slug === slug);
+ if (!finding) return ;
+ return ;
+}
+
+const navCls = cn("rounded-md border px-2 py-1 hover:bg-muted", FOCUS);
+
+function FindingPage({ repo, f }: { repo: RepoBundle; f: Finding }) {
+ useTitle(`Finding ${f.rank} · ${repo.name}`);
+ const all = allFindings(repo);
+ const pos = all.indexOf(f);
+ const prev = pos > 0 ? all[pos - 1] : null;
+ const next = pos >= 0 && pos < all.length - 1 ? all[pos + 1] : null;
+ const decision = f.decisionId ? repo.decisions.find((d) => d.id === f.decisionId) : undefined;
+ const byId = new Map(all.map((x) => [x.id, x]));
+ const related = f.related.map((id) => byId.get(id)).filter((x): x is Finding => Boolean(x));
+ const inTop = repo.findings.includes(f);
+ const journeys = useJourneys();
+ const seenIn = (journeys?.journeys ?? []).flatMap((journey) => {
+ const stop = journey.stops.findIndex((s) => s.findingRank === f.rank);
+ return stop >= 0 ? [{ journey, stop }] : [];
+ });
+
+ return (
+
+
+
+ All findings
+
+
+ {prev && (
+
+ ← #{prev.rank}
+
+ )}
+ {next && (
+
+ #{next.rank} →
+
+ )}
+
+
+
+
+
+ #{f.rank}
+ of {fmt(all.length)}
+ /
+ {TYPE[f.type].label}
+ {!inTop && below the top {repo.findings.length} }
+
+
+ {f.title}
+
+ {f.judgement && (
+
+ )}
+ {seenIn.length > 0 && (
+
+ Seen in{" "}
+ {seenIn.map((x, i) => (
+
+ {i > 0 && ", "}
+
+ the journey "{x.journey.name}", stop {x.stop + 1}
+
+
+ ))}
+
+ )}
+
+
+
+
+
+
+
+
+ {f.caveats.length > 0 && (
+
+
+ Caveats
+
+
+ {f.caveats.map((c) => (
+
+
+
+
+ ))}
+
+
+ )}
+
+ {related.length > 0 && }
+
+
+
+
+
+ );
+}
+
+/** Related findings shown before "Show all". */
+const RELATED_SHOWN = 6;
+
+function Related({ repo, related }: { repo: RepoBundle; related: Finding[] }) {
+ const { shown, all, toggle } = useShowMore(related, RELATED_SHOWN);
+ return (
+
+
+
+ {related.length === 1
+ ? "One finding shares a target with this one."
+ : `${fmt(related.length)} findings share a target with this one.`}
+
+
+
+
+ );
+}
diff --git a/web/src/routes/Findings.tsx b/web/src/routes/Findings.tsx
new file mode 100644
index 00000000..98033b29
--- /dev/null
+++ b/web/src/routes/Findings.tsx
@@ -0,0 +1,232 @@
+import { ArrowRight, ChevronRight, EyeOff } from "lucide-react";
+import { Link, useSearchParams } from "react-router";
+import { FOCUS, cn } from "../components/cx/cn";
+import { FindingCompactRow, FindingListRow } from "../components/cx/finding-list-row";
+import { Eyebrow, SectionHead } from "../components/cx/primitives";
+import { useTitle } from "../components/cx/use-page";
+import { repoPath } from "../cx/address";
+import { BATCH_LOOPS_NOTE, fmt } from "../cx/meta";
+import type { Batch, Finding } from "../cx/types";
+import { useRepo } from "./RepoLayout";
+
+/** Findings below the top 10 shown before "Show all". */
+const SUPPORTING_SHOWN = 25;
+/** Address-bar parameters of this screen. */
+const HIDE_PARAM = "hide";
+const HIDE_VALUE = "legitimate-wiring";
+const ALL_PARAM = "all";
+const BELOW_PARAM = "below";
+
+const isLegitimate = (f: Finding) => f.judgement?.verdict === "legitimate_wiring";
+
+const buttonCls = cn(
+ "inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs font-medium transition-colors hover:bg-card",
+ FOCUS,
+);
+
+/** The findings of one repository: the top 10 in stored rank order, then every other one. */
+export function Findings() {
+ const repo = useRepo();
+ useTitle(`Findings · ${repo.name}`);
+ const [params, setParams] = useSearchParams();
+ const hideLegit = params.get(HIDE_PARAM) === HIDE_VALUE;
+ const showAll = params.get(ALL_PARAM) === "1";
+ const showBelow = showAll || params.get(BELOW_PARAM) === "1";
+ const compareDate = repo.sponsorDate ?? repo.beforeDate;
+
+ const setParam = (key: string, value: string | null) => {
+ const next = new URLSearchParams(params);
+ if (value === null) next.delete(key);
+ else next.set(key, value);
+ setParams(next, { replace: true });
+ };
+
+ // Hiding only removes rows from view: ranks and order stay as stored.
+ const top = hideLegit ? repo.findings.filter((f) => !isLegitimate(f)) : repo.findings;
+ const restAll = hideLegit ? repo.supporting.filter((f) => !isLegitimate(f)) : repo.supporting;
+ const rest = showAll ? restAll : restAll.slice(0, SUPPORTING_SHOWN);
+ const legitCount = [...repo.findings, ...repo.supporting].filter(isLegitimate).length;
+ const rankedCount = repo.findings.length + repo.supporting.length;
+
+ return (
+
+
+ Findings
+
+ {rankedCount === 1 ? "1 finding is ranked" : `${fmt(rankedCount)} findings are ranked`},
+ in an order computed from stored numbers with no AI model.
+
+
+
+
+
+
+
+
+ Top {repo.findings.length} · in stored rank order
+
+ What to fix first
+
+
+
+ setParam(HIDE_PARAM, hideLegit ? null : HIDE_VALUE)}
+ className={cn(
+ buttonCls,
+ hideLegit && "border-foreground bg-ink text-ink-foreground hover:bg-ink",
+ )}
+ >
+
+ Hide legitimate wiring
+
+
+ {legitCount === 0
+ ? "no finding read as legitimate wiring"
+ : hideLegit
+ ? `${legitCount} hidden; ranks unchanged`
+ : `${legitCount} read as legitimate wiring`}
+
+
+
+ {repo.findings.length === 0 ? (
+ No finding was ranked in this run.
+ ) : top.length === 0 ? (
+
+ Every finding in the top {repo.findings.length} is hidden by the filter.
+
+ ) : (
+
+ {top.map((f) => (
+
+ ))}
+
+ )}
+
+
+
+
+ How the rank is computed, under Approach
+
+
+
+
+ {repo.supporting.length > 0 && (
+
+
+ {fmt(rest.length)} of {fmt(restAll.length)} shown
+
+ ) : undefined
+ }
+ />
+ {showBelow ? (
+ <>
+
+ The top 10 holds at most a few findings per type and per module, so some of these
+ score higher than a finding above them.
+
+
+ {rest.map((f) => (
+
+ ))}
+
+
+ {restAll.length > SUPPORTING_SHOWN && (
+ setParam(ALL_PARAM, showAll ? null : "1")}
+ className={buttonCls}
+ >
+ {showAll
+ ? `Show the first ${SUPPORTING_SHOWN}`
+ : `Show all ${fmt(restAll.length)}`}
+
+ )}
+ {
+ const next = new URLSearchParams(params);
+ next.delete(BELOW_PARAM);
+ next.delete(ALL_PARAM);
+ setParams(next, { replace: true });
+ }}
+ className={buttonCls}
+ >
+ Hide the lower-ranked findings
+
+
+ >
+ ) : (
+
+ setParam(BELOW_PARAM, "1")}
+ className={cn(buttonCls, "px-3 py-1.5 text-sm")}
+ >
+
+ {restAll.length === 1
+ ? "Show 1 lower-ranked finding"
+ : `Show ${fmt(restAll.length)} lower-ranked findings`}
+
+
+ )}
+
+ )}
+
+ );
+}
+
+function BatchStrip({ batch }: { batch: Batch | null }) {
+ return (
+
+
+ Simulated fix batch
+
+ {batch ? (
+ <>
+
+ {(
+ [
+ ["loops", `${fmt(batch.loopsBefore)} → ${fmt(batch.loopsAfter)}`, BATCH_LOOPS_NOTE],
+ ["links cut", fmt(batch.linksRemoved), undefined],
+ ["links added", fmt(batch.linksAdded), undefined],
+ ["applied", fmt(batch.fixesApplied), undefined],
+ ["skipped", fmt(batch.fixesSkipped), undefined],
+ ...(batch.newExceptions.length > 0
+ ? ([["new exceptions", fmt(batch.newExceptions.length), undefined]] as const)
+ : []),
+ ] as const
+ ).map(([k, v, hint]) => (
+
+ {k}
+ {v}
+
+ ))}
+
+
+ Every cheap-loop fix that simulated cleanly, applied together on a copy of the map, not
+ to the code.
+
+ >
+ ) : (
+ Not simulated in this run.
+ )}
+
+ );
+}
diff --git a/web/src/routes/Journeys.tsx b/web/src/routes/Journeys.tsx
new file mode 100644
index 00000000..a222a67a
--- /dev/null
+++ b/web/src/routes/Journeys.tsx
@@ -0,0 +1,37 @@
+import { useSearchParams } from "react-router";
+import { JourneyPlayer } from "../components/cx/journeys";
+import { useTitle } from "../components/cx/use-page";
+import { NotFound } from "./NotFound";
+import { useJourneys, useRepo } from "./RepoLayout";
+
+/** Journeys: follow one user action through the code, the quickest way into a new codebase. */
+export function Journeys() {
+ const repo = useRepo();
+ const journeys = useJourneys();
+ const [params] = useSearchParams();
+ const start = {
+ journey: params.get("j"),
+ stop: Math.max(0, Number(params.get("s") ?? 1) - 1 || 0),
+ };
+ useTitle(`Journeys · ${repo.name}`);
+ if (!journeys) return ;
+ return (
+
+
+
+ Follow one request through the code
+
+
+ Each journey starts with something a person does in the browser and follows it through the
+ modules that handle it. The height of the line is the layer: a dip goes down into core
+ code, a rise brings the result back up. Press Play or pick any stop.
+
+
+
+
+ These journeys are a hand-traced sample for {repo.name}, not yet produced by the pipeline.
+ File paths are shortened to the module folder.
+
+
+ );
+}
diff --git a/web/src/routes/Landing.tsx b/web/src/routes/Landing.tsx
new file mode 100644
index 00000000..d328909d
--- /dev/null
+++ b/web/src/routes/Landing.tsx
@@ -0,0 +1,260 @@
+import { ArrowUpRight } from "lucide-react";
+import { Link } from "react-router";
+import { FOCUS, cn } from "../components/cx/cn";
+import { SiteFooter, SiteHeader } from "../components/cx/site-header";
+import { Sparkline, markIndex } from "../components/cx/sparkline";
+import { useLoaded, useTitle } from "../components/cx/use-page";
+import { repoPath } from "../cx/address";
+import { STATUS, STATUS_ORDER, pct } from "../cx/meta";
+import type { FixFirst, RepoCard, RepoSummary } from "../cx/types";
+import { loadRepoCard, loadRepoFixFirst, loadRepoSummaries } from "../data/repo";
+
+/** The pipeline's seven stages, split into the computed ones and those that carry AI text. */
+const COMPUTED = [
+ ["Repository", "Reads the full history and records which commit last wrote each line."],
+ ["Parse", "Reads every file and resolves imports and calls into links between files."],
+ ["Model", "Groups the files into modules and stores the module map for each snapshot."],
+ ["Visualize", "Draws the module grid, ordered so that normal dependencies fall on one side."],
+ [
+ "Analyze",
+ "Checks each decision against the links, snapshot by snapshot, and lists the exceptions.",
+ ],
+] as const;
+
+const WITH_AI = [
+ [
+ "LLM Judge",
+ "An AI model reads decision documents, judges the shown findings and describes modules. Its text is checked against the stored facts.",
+ ],
+ [
+ "Explain",
+ "Ranks the findings by arithmetic alone and shows the model's text beside them, marked AI.",
+ ],
+] as const;
+
+export function Landing() {
+ useTitle(null);
+ const summaries = useLoaded(() => loadRepoSummaries(), "summaries");
+ const all = summaries.state === "ready" ? summaries.value : [];
+ const real = all.filter((r) => !r.synthetic);
+ const dates = [...new Set(real.map((r) => r.snapshotDate).filter((d): d is string => !!d))];
+
+ return (
+
+
+
+
+
+
+
+
+
+ Reports
+
+ {dates.length === 1 && (
+ snapshot {dates[0]}
+ )}
+
+ {summaries.state === "loading" && (
+
+ Loading the list of reports…
+
+ )}
+ {summaries.state === "failed" && (
+
+ The list of reports could not be loaded.{" "}
+ {summaries.why}
+
+ )}
+ {summaries.state === "ready" && real.length === 0 && (
+
+ No report of a real repository is in bundles/index.json.
+
+ )}
+ {real.length > 0 && (
+
+ {real.map((r) => (
+
+
+
+ ))}
+
+ )}
+
+
+
+
+ How it works
+
+
+
+
+
+
+
+
+
+
+ );
+}
+
+function StageGroup({
+ title,
+ stages,
+ from,
+}: {
+ title: string;
+ stages: readonly (readonly [string, string])[];
+ from: number;
+}) {
+ return (
+
+ {title}
+ 2 ? "lg:grid-cols-5" : "lg:grid-cols-2",
+ )}
+ >
+ {stages.map(([name, text], i) => (
+
+ {from + i}
+ {name}
+
+ {text}
+
+
+ ))}
+
+
+ );
+}
+
+function RepoCardView({ id, summary }: { id: string; summary: RepoSummary }) {
+ const card = useLoaded(() => loadRepoCard(id), id);
+ // Loaded after the card's own files, so the card appears without waiting for it.
+ const top = useLoaded(
+ () => loadRepoCard(id).then(() => loadRepoFixFirst(id)),
+ id,
+ );
+ const c = card.state === "ready" ? card.value : null;
+ const counts = summary.statusCounts;
+ const present = STATUS_ORDER.filter((s) => counts[s] > 0);
+ const checked = present.reduce((n, s) => n + counts[s], 0);
+ const grain = c?.againstGrainShare ?? null;
+ const now = grain?.now ?? null;
+ const before = grain?.before ?? null;
+ const compareDate = c ? (c.sponsorDate ?? c.beforeDate) : null;
+ const langs = c
+ ? c.languages.length > 3
+ ? `${c.languages.slice(0, 3).join(" + ")} +${c.languages.length - 3}`
+ : c.languages.join(" + ")
+ : "";
+
+ return (
+
+
+
+ {summary.name}
+
+ {[langs, summary.snapshotDate && `snapshot ${summary.snapshotDate}`]
+ .filter(Boolean)
+ .map((part, i) => (
+
+ {i > 0 && "· "}
+ {part}
+
+ ))}
+
+
+
+
+
+
+ Fix first
+
+ {top.state === "ready" ? (
+ (top.value?.title ?? "No finding was ranked in this run.")
+ ) : top.state === "failed" ? (
+ could not be loaded
+ ) : (
+ Loading…
+ )}
+
+
+
+
+ {checked === 0
+ ? "No decision checked."
+ : `${checked} ${checked === 1 ? "decision" : "decisions"} checked: ${present
+ .map((s) => `${counts[s]} ${STATUS[s].label.toLowerCase()}`)
+ .join(", ")}`}
+
+
+ {card.state === "failed" && (
+
+ The rest of this card could not be loaded.
+
+ )}
+ {grain && now !== null && (
+
+
+
+ links against the main dependency direction
+
+
+ {pct(now)}
+ {before !== null && (
+
+ {now === before ? "unchanged from" : "from"} {pct(before)}
+ {compareDate && ` at ${compareDate.slice(0, 7)}`}
+
+ )}
+
+
+ {grain.series.length > 1 && (
+ p.value)}
+ mark={markIndex(
+ grain.series.map((p) => p.date),
+ compareDate,
+ )}
+ width={96}
+ height={28}
+ color="var(--muted-foreground)"
+ label={`${summary.name}: share of links against the main dependency direction at each snapshot`}
+ />
+ )}
+
+ )}
+
+ );
+}
diff --git a/web/src/routes/MapPage.tsx b/web/src/routes/MapPage.tsx
new file mode 100644
index 00000000..62646cf7
--- /dev/null
+++ b/web/src/routes/MapPage.tsx
@@ -0,0 +1,232 @@
+import { ArrowRight } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import { Link, useLocation, useNavigate } from "react-router";
+import { FOCUS, cn } from "../components/cx/cn";
+import {
+ GRID_ORDER_NOTE,
+ GridNumbers,
+ MapLegend,
+ ViewToggle,
+ viewLabel,
+} from "../components/cx/map-controls";
+import {
+ cellIndex,
+ findingBySlug,
+ gridMax,
+ moduleIndex,
+ pictureFor,
+ topFindingCells,
+} from "../components/cx/map-model";
+import { type Cell, Matrix } from "../components/cx/matrix";
+import { useTitle } from "../components/cx/use-page";
+import { type MapState, type MapView, readMapState, repoPath, withMapState } from "../cx/address";
+import { fmt } from "../cx/meta";
+import { useRepo } from "./RepoLayout";
+import { CellPanel } from "./map/CellPanel";
+import { BatchPanel, ChangeList, FindingBanner, FixPanel } from "./map/ChangePanels";
+import { ModulePanel } from "./map/ModulePanel";
+
+/** The Map screen of one repository: the module grid (spec.md §10.2 screen 2). */
+export function MapPage() {
+ const repo = useRepo();
+ useTitle(`Map · ${repo.name}`);
+ const { search, pathname } = useLocation();
+ const navigate = useNavigate();
+ const ids = useMemo(() => repo.modules.map((m) => m.id), [repo]);
+ const state = readMapState(search, ids);
+ // The address keeps module ids readable ("?cell=M:a,M:b"), so it is written as a string.
+ const update = (patch: Partial) =>
+ navigate({ pathname, search: withMapState(search, ids, patch) }, { replace: true });
+ const [picked, setPicked] = useState(null);
+
+ const n = repo.modules.length;
+ const index = moduleIndex(repo);
+ // An "after" address for a run with no batch reads as Now.
+ const view: MapView = state.view === "after" && !repo.batch ? "now" : state.view;
+ const fixFinding = findingBySlug(repo, state.fix);
+ const trying = fixFinding?.simulation?.simulated ? fixFinding : null;
+ const highlighted = findingBySlug(repo, state.finding);
+
+ const picture = useMemo(
+ () => pictureFor(repo, trying ? { kind: "fix", finding: trying } : { kind: view }),
+ [repo, view, trying],
+ );
+ const topCells = useMemo(() => topFindingCells(repo), [repo]);
+ const flagged = useMemo(() => new Set(topCells.keys()), [topCells]);
+ const emphasis = useMemo(() => {
+ if (!highlighted) return null;
+ const out = new Set();
+ for (const [src, dst] of highlighted.cells) {
+ const i = index.get(src);
+ const j = index.get(dst);
+ if (i !== undefined && j !== undefined) out.add(cellIndex(n, i, j));
+ }
+ return out;
+ }, [highlighted, index, n]);
+
+ // Modules that exist only at the before date are listed only in the Before view.
+ const listsBeforeOnly = !trying && view === "before";
+ const pickedShown =
+ picked !== null && (listsBeforeOnly || repo.modules[picked]?.presentAtEnd) ? picked : null;
+
+ const selected: Cell | null = state.cell
+ ? [index.get(state.cell[0])!, index.get(state.cell[1])!]
+ : null;
+ const select = (cell: Cell | null) => {
+ if (cell && cell[0] === cell[1]) {
+ setPicked(pickedShown === cell[0] ? null : cell[0]);
+ update({ cell: null });
+ return;
+ }
+ update({ cell: cell ? [ids[cell[0]]!, ids[cell[1]]!] : null });
+ };
+
+ // Escape clears the selected cell from anywhere on the page, except while typing.
+ const hasCell = selected !== null;
+ useEffect(() => {
+ if (!hasCell) return;
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key !== "Escape" || event.defaultPrevented) return;
+ const target = event.target as HTMLElement | null;
+ if (target?.closest("input, textarea, select")) return;
+ navigate({ pathname, search: withMapState(search, ids, { cell: null }) }, { replace: true });
+ };
+ document.addEventListener("keydown", onKey);
+ return () => document.removeEventListener("keydown", onKey);
+ }, [hasCell, ids, search, pathname, navigate]);
+
+ const changeSource = trying ? "in the fix's simulation" : "in the batch simulation";
+ const beforeOnly = repo.modules.filter((m) => !m.presentAtEnd).length;
+ const present = n - beforeOnly;
+ const gridLabel = trying
+ ? `Module grid with the simulated fix for finding ${trying.rank}`
+ : `Module grid, ${viewLabel(repo, view)}${view === "before" ? ` (${repo.beforeDate})` : view === "now" ? ` (${repo.snapshotDate})` : ""}`;
+
+ return (
+
+
+
+ Which module uses which
+
+
+ Every square is one of the {fmt(present)} modules using another. Above the diagonal, blue
+ squares point the normal way, from features down to the shared code they build on. Below
+ it, orange squares point backwards. Click a square to see the code behind it.
+ {listsBeforeOnly &&
+ beforeOnly > 0 &&
+ ` ${fmt(beforeOnly)} more ${beforeOnly === 1 ? "module" : "modules"} existed only at the before date.`}
+
+
+ Lines of code by module and file
+
+
+
+ {highlighted && (
+
+ update({ fix: trying?.slug === highlighted.slug ? null : highlighted.slug })
+ }
+ onClose={() => update({ finding: null })}
+ />
+ )}
+ {state.fix && !fixFinding && (
+
+ No finding matches the fix in this address; the grid shows {viewLabel(repo, view)}.
+
+ )}
+ {fixFinding && (
+ update({ fix: null })}
+ />
+ )}
+
+
+
+
+ update({ view: v, fix: null })}
+ />
+
+
+ {!trying && view === "after" && repo.batch && (
+
+ )}
+ 0}
+ emphasis={!!emphasis && emphasis.size > 0}
+ beforeOnly={beforeOnly > 0}
+ />
+ }
+ />
+
+ {GRID_ORDER_NOTE}
+
+ {picture.changes.length > 0 && (
+ select(cell)}
+ title={
+ trying
+ ? "Cells the fix changes, with the simulation's own counts"
+ : "Cells the batch changes, with the simulation's own counts"
+ }
+ />
+ )}
+
+
+
+ {selected ? (
+ select(null)}
+ />
+ ) : (
+
+ )}
+
+
+
+ );
+}
diff --git a/web/src/routes/NotFound.tsx b/web/src/routes/NotFound.tsx
new file mode 100644
index 00000000..4549afb0
--- /dev/null
+++ b/web/src/routes/NotFound.tsx
@@ -0,0 +1,35 @@
+import { ArrowRight } from "lucide-react";
+import { Link } from "react-router";
+import { FOCUS, cn } from "../components/cx/cn";
+import { Eyebrow } from "../components/cx/primitives";
+import { useTitle } from "../components/cx/use-page";
+
+/**
+ * Shown for an address the app has no page for: an unknown path, repository or finding.
+ * Inside a repository the repository's name is already the page's `h1`, so the heading
+ * here is an `h2`.
+ */
+export function NotFound({ what, inRepo = false }: { what?: string; inRepo?: boolean }) {
+ useTitle("Not found");
+ const Heading = inRepo ? "h2" : "h1";
+ return (
+
+ Not found
+
+ There is no page at this address.
+
+
+ {what ?? "The link may be from another version of the report, or mistyped."}
+
+
+ All reports
+
+
+ );
+}
diff --git a/web/src/routes/Overview.tsx b/web/src/routes/Overview.tsx
new file mode 100644
index 00000000..4b394927
--- /dev/null
+++ b/web/src/routes/Overview.tsx
@@ -0,0 +1,196 @@
+import { ArrowRight } from "lucide-react";
+import { Fragment, type ReactNode } from "react";
+import { Link } from "react-router";
+import { JourneyPreview } from "../components/cx/journeys";
+import { FOCUS, cn } from "../components/cx/cn";
+import { SectionHead, StatusDot } from "../components/cx/primitives";
+import { useTitle } from "../components/cx/use-page";
+import { repoPath } from "../cx/address";
+import { STATUS, STATUS_ORDER, statusCounts } from "../cx/meta";
+import type { JourneyBundle } from "../data/journeys";
+import type { RepoBundle, Status } from "../cx/types";
+import { BeforeAfter } from "./overview/BeforeAfter";
+import { FixFirst } from "./overview/FixFirst";
+import { MainModules } from "./overview/Structure";
+import { TrustStrip } from "./overview/TrustStrip";
+import { useJourneys, useRepo } from "./RepoLayout";
+
+/** The statuses that count as not holding in the verdict sentence, worst first. */
+const NOT_HOLDING: Status[] = ["broken", "slipping", "spreading"];
+
+const linkCls = cn(
+ "inline-flex items-center gap-1 rounded-sm text-foreground hover:underline",
+ FOCUS,
+);
+
+export function Overview() {
+ const repo = useRepo();
+ const journeys = useJourneys();
+ useTitle(`Overview · ${repo.name}`);
+ const compareDate = repo.sponsorDate ?? repo.beforeDate;
+
+ return (
+
+
+
+
+
+
+
+ );
+}
+
+// ---- verdict ----------------------------------------------------------------------------
+
+/** "a", "a and b", "a, b and c". */
+function joined(items: ReactNode[]): ReactNode {
+ return items.map((item, i) => (
+
+ {item}
+ {i < items.length - 2 ? ", " : i === items.length - 2 ? " and " : ""}
+
+ ));
+}
+
+/** The verdict of the overview, from the decisions' statuses at the end snapshot. */
+export function VerdictSentence({
+ counts,
+ total,
+}: {
+ counts: Record;
+ total: number;
+}) {
+ if (total === 0) return <>No decision could be checked in this run.>;
+ const failing = NOT_HOLDING.filter((s) => counts[s] > 0);
+ const holding = counts.holding + counts.mostly_holding;
+ if (failing.length === 0) {
+ return counts.mostly_holding > 0 ? (
+ <>
+ All {total} checked {total === 1 ? "decision is" : "decisions are"} holding or mostly
+ holding.
+ >
+ ) : (
+ <>
+ {total === 1 ? "The one checked decision is" : `All ${total} checked decisions are`}{" "}
+ holding.
+ >
+ );
+ }
+ return (
+ <>
+ {joined(
+ failing.map((s) => (
+
+ {counts[s]} {STATUS[s].label.toLowerCase()}
+
+ )),
+ )}
+
+ {" — "}
+ {holding} of {total} still holding.
+
+ >
+ );
+}
+
+// ---- decisions ---------------------------------------------------------------------------
+
+/** The status bar and its legend, from the decisions' statuses at the end snapshot. */
+function StatusBar({ counts, total }: { counts: Record; total: number }) {
+ return (
+
+ `${counts[s]} ${STATUS[s].label.toLowerCase()}`).join(
+ ", ",
+ )}
+ >
+ {STATUS_ORDER.map(
+ (s) =>
+ counts[s] > 0 && (
+
+ ),
+ )}
+
+
+ {STATUS_ORDER.map((s) => (
+
+
+ {STATUS[s].label} {counts[s]}
+
+ ))}
+
+
+ );
+}
+
+/** The verdict and the status bar; the decisions themselves are one click away. */
+function DecisionList({ repo }: { repo: RepoBundle }) {
+ const counts = statusCounts(repo.decisions);
+ const total = repo.decisions.length;
+ return (
+
+ 0 && (
+
+ All {total} {total === 1 ? "decision" : "decisions"}{" "}
+
+
+ )
+ }
+ />
+
+
+
+ {total > 0 && }
+
+ );
+}
+
+/** Understandability: the main modules, then one request followed through them. */
+function HowItFits({ repo, journeys }: { repo: RepoBundle; journeys: JourneyBundle | null }) {
+ const first = journeys?.journeys[0];
+ return (
+
+
+ Open the full map
+
+ }
+ />
+
+ {journeys && first && (
+
+
+ How they work together: {first.name.toLowerCase()}
+
+ Play the {journeys.journeys.length} journeys{" "}
+
+
+
+
+
+
+
+ )}
+
+ );
+}
diff --git a/web/src/routes/RepoLayout.tsx b/web/src/routes/RepoLayout.tsx
new file mode 100644
index 00000000..5aa4bf22
--- /dev/null
+++ b/web/src/routes/RepoLayout.tsx
@@ -0,0 +1,238 @@
+import { Link, Outlet, useLocation, useOutletContext, useParams } from "react-router";
+import { type RepoTab, repoPath } from "../cx/address";
+import { fmt } from "../cx/meta";
+import type { RepoBundle } from "../cx/types";
+import { FOCUS, cn } from "../components/cx/cn";
+import { allFindings } from "../components/cx/finding-fix";
+import { SiteFooter, SiteHeader } from "../components/cx/site-header";
+import { useLoaded, useTitle } from "../components/cx/use-page";
+import { type JourneyBundle, loadJourneys } from "../data/journeys";
+import { loadRepo, loadRepoList } from "../data/repo";
+import { NotFound } from "./NotFound";
+
+interface RepoContext {
+ repo: RepoBundle;
+ journeys: JourneyBundle | null;
+}
+
+/**
+ * The repository every screen under `/r/:repo` shows, loaded once by the layout. Call it
+ * from any screen rendered inside the repository's routes.
+ */
+export function useRepo(): RepoBundle {
+ return useOutletContext().repo;
+}
+
+/** The repository's journeys, or null when its bundle folder holds none. */
+export function useJourneys(): JourneyBundle | null {
+ return useOutletContext().journeys;
+}
+
+/**
+ * The tab row. `also` lists the screens that are reached from a tab's page rather than from
+ * the row; while one of them is open, that tab is marked as current.
+ */
+const TABS: { tab?: RepoTab; label: string; also?: RepoTab[] }[] = [
+ { label: "Report", also: ["decisions"] },
+ { tab: "journeys", label: "Journeys" },
+ { tab: "findings", label: "Findings" },
+ { tab: "map", label: "Map", also: ["size"] },
+ { tab: "change", label: "Before and after" },
+ { tab: "trust", label: "Approach" },
+];
+
+type Load =
+ { state: "missing" } | { state: "found"; repo: RepoBundle; journeys: JourneyBundle | null };
+
+export function RepoLayout() {
+ const id = useParams().repo ?? "";
+ const loaded = useLoaded(async () => {
+ const list = await loadRepoList();
+ if (!list.some((b) => b.repo_id === id)) return { state: "missing" };
+ const [repo, journeys] = await Promise.all([loadRepo(id), loadJourneys(id)]);
+ return { state: "found", repo, journeys };
+ }, id);
+
+ const found = loaded.state === "ready" && loaded.value.state === "found" ? loaded.value : null;
+ const repo = found ? found.repo : null;
+ // Once the repository is loaded, each screen sets its own title.
+ useTitle(
+ loaded.state === "ready" && loaded.value.state === "missing"
+ ? "Not found"
+ : repo
+ ? undefined
+ : id,
+ );
+
+ if (loaded.state === "ready" && loaded.value.state === "missing") {
+ return (
+
+
+
+
+
+
+
+ );
+ }
+
+ return (
+
+
+ {loaded.state === "loading" && (
+
+
+ Loading the {id} report…
+
+
+ )}
+ {loaded.state === "failed" && (
+
+
+ The {id} report could not be loaded.
+ {loaded.why}
+
+ Back to all reports
+
+
+
+ )}
+ {found && }
+
+ );
+}
+
+function RepoBody({ repo, journeys }: { repo: RepoBundle; journeys: JourneyBundle | null }) {
+ const modules = repo.modules.filter((m) => m.presentAtEnd).length;
+ // Two names and a count keep the line short; the full list is the line's tooltip.
+ const langs =
+ repo.languages.length > 2
+ ? `${repo.languages.slice(0, 2).join(" + ")} +${repo.languages.length - 2}`
+ : repo.languages.join(" + ");
+ const facts = [
+ repo.host ? repo.host.replace(/^[a-z]+:\/\//i, "").replace(/\/+$/, "") : "private repository",
+ langs || null,
+ `${fmt(repo.prodLoc)} production lines`,
+ `${fmt(modules)} ${modules === 1 ? "module" : "modules"}`,
+ ].filter(Boolean);
+ const context: RepoContext = { repo, journeys };
+ return (
+ <>
+
+
+
+
+
+ {repo.name}
+
+
+ {facts.map((f, i) => (
+
+ {i > 0 && "· "}
+ {f}
+
+ ))}
+
+
+
+
+ snapshot
+ {repo.snapshotDate}
+
+
+ commit
+
+ {repo.endSha.slice(0, 10)}
+
+
+
+
+ {repo.synthetic && (
+
+ Synthetic fixture data. {" "}
+
+ This bundle is made up to test the pipeline and the screens. It describes no real
+ project.
+
+
+ )}
+
+
+
+
+
+
+
+ Every number on this page comes from a stored result for commit{" "}
+ {repo.endSha.slice(0, 7)} . Text marked AI is checked
+ against those results.
+
+ >
+ );
+}
+
+function RepoNav({
+ repoId,
+ counts,
+ hide,
+}: {
+ repoId: string;
+ counts: Partial>;
+ hide: RepoTab[];
+}) {
+ const path = useLocation().pathname;
+ const base = repoPath(repoId);
+ const under = (tab: RepoTab) => {
+ const href = repoPath(repoId, tab);
+ return path === href || path.startsWith(`${href}/`);
+ };
+ return (
+
+ {TABS.filter((t) => !t.tab || !hide.includes(t.tab)).map((t) => {
+ const href = repoPath(repoId, t.tab);
+ const active =
+ (t.tab ? under(t.tab) : path === base || path === `${base}/`) ||
+ (t.also ?? []).some(under);
+ const count = t.tab ? counts[t.tab] : undefined;
+ return (
+
+ {t.label}
+ {count !== undefined && (
+
+ {fmt(count)}
+
+ )}
+
+ );
+ })}
+
+ );
+}
diff --git a/web/src/routes/Size.tsx b/web/src/routes/Size.tsx
new file mode 100644
index 00000000..50d85bea
--- /dev/null
+++ b/web/src/routes/Size.tsx
@@ -0,0 +1,479 @@
+import { ArrowDown, ArrowLeft, ArrowUp, ArrowUpDown, X } from "lucide-react";
+import { type ReactNode, useMemo } from "react";
+import { Link, useSearchParams } from "react-router";
+import { ComputedMark } from "../components/cx/badges";
+import { FOCUS, cn } from "../components/cx/cn";
+import { Eyebrow, Panel, SectionHead } from "../components/cx/primitives";
+import { useTitle } from "../components/cx/use-page";
+import { repoPath } from "../cx/address";
+import { fmt, pct } from "../cx/meta";
+import type { FileSize, RepoBundle } from "../cx/types";
+import { ShareLegend, Swatch } from "./size/scale";
+import {
+ type Scope,
+ type SizeRow,
+ type SizeState,
+ type SortKey,
+ buildTree,
+ fileShare,
+ readSizeState,
+ sizeParams,
+ sizeRows,
+ sortRows,
+} from "./size/tree";
+import { SizeTreemap } from "./size/treemap";
+import { ShowMoreButton, useShowMore } from "./decisions/show-more";
+import { useRepo } from "./RepoLayout";
+
+/** Modules listed in "where the new lines landed". */
+const LANDED_SHOWN = 8;
+/** Largest files listed for the selected module. */
+const FILES_SHOWN = 10;
+/** Table rows shown before "Show all". */
+const ROWS_SHOWN = 15;
+
+/** A table cell with no stored value stays empty apart from a dash. */
+const EMPTY = – ;
+const num = (v: number | null) => (v === null ? EMPTY : fmt(v));
+const share = (v: number | null) => (v === null ? EMPTY : pct(v, 0));
+
+/** The Size screen (spec.md §10.2 screen 6): code mass, where new code landed, and the table. */
+export function Size() {
+ const repo = useRepo();
+ useTitle(`Size · ${repo.name}`);
+ const sponsor = repo.sponsorDate ?? repo.beforeDate;
+ const present = useMemo(() => repo.modules.filter((m) => m.presentAtEnd), [repo.modules]);
+ const ids = useMemo(() => present.map((m) => m.id), [present]);
+ const [params, setParams] = useSearchParams();
+ const state = readSizeState(params, ids);
+ const update = (patch: Partial) =>
+ setParams(sizeParams({ ...state, ...patch }), { replace: true });
+
+ const tree = useMemo(
+ () => buildTree(present, repo.fileSizes, state.scope),
+ [present, repo.fileSizes, state.scope],
+ );
+ const rows = useMemo(() => sizeRows(present, repo.fileSizes), [present, repo.fileSizes]);
+ const inScope =
+ repo.fileSizes?.filter((f) => state.scope === "all" || f.kind === "production").length ?? null;
+ const gone = repo.modules.length - present.length;
+ const selected = state.module ? (rows.find((r) => r.m.id === state.module) ?? null) : null;
+ const toggle = (id: string) => update({ module: id === state.module ? null : id });
+
+ return (
+
+
+
+ Back to the map
+
+ Size
+
+ How big each module is
+
+ {tree.value > 0 && (
+
+ Each rectangle is a file, grouped by module; its area is lines of code and its colour
+ the share of lines that arrived after {sponsor}. {fmt(present.length)} modules
+ and {fmt(tree.value)} lines
+ {inScope !== null && (
+ <>
+ {" "}
+ in {fmt(inScope)} {state.scope === "production" ? "production files" : "files"}
+ >
+ )}{" "}
+ at {repo.snapshotDate}
+ {gone > 0 &&
+ `; the ${fmt(gone)} ${gone === 1 ? "module" : "modules"} that exist only at ${repo.beforeDate} ${gone === 1 ? "is" : "are"} left out`}
+ .
+
+ )}
+
+
+ {tree.value === 0 ? (
+
+ This run stored no size numbers for this repository.
+
+ ) : (
+ <>
+
+
+
+ {repo.fileSizes !== null && (
+ update({ scope })} />
+ )}
+
+
+
+ Line origin is read for production files only, and a line counts from the last change
+ that touched it.
+
+
+
+ {selected && (
+ update({ module: null })}
+ />
+ )}
+
+ update({ module: id })} />
+
+ update({ sort, descending })}
+ onSelect={toggle}
+ />
+ >
+ )}
+
+ );
+}
+
+function ScopeSwitch({ scope, onChange }: { scope: Scope; onChange: (s: Scope) => void }) {
+ const options: [Scope, string][] = [
+ ["production", "Production files"],
+ ["all", "All files"],
+ ];
+ return (
+
+ {options.map(([value, label]) => (
+ onChange(value)}
+ className={cn(
+ "rounded-sm px-2.5 py-1 text-xs",
+ scope === value
+ ? "bg-ink text-ink-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ FOCUS,
+ )}
+ >
+ {label}
+
+ ))}
+
+ );
+}
+
+function Selected({
+ repo,
+ row,
+ sponsor,
+ onClear,
+}: {
+ repo: RepoBundle;
+ row: SizeRow;
+ sponsor: string;
+ onClear: () => void;
+}) {
+ const m = row.m;
+ const own: FileSize[] = (repo.fileSizes ?? [])
+ .filter((f) => f.module === m.id)
+ .sort((a, b) => b.loc - a.loc || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
+ .slice(0, FILES_SHOWN);
+ const all: [string, number | null, (v: number) => string][] = [
+ ["lines", m.loc, fmt],
+ ["production lines", row.prodLoc, fmt],
+ ["files", m.files, fmt],
+ ["links in", m.linksIn, fmt],
+ ["links out", m.linksOut, fmt],
+ ["changes, 12 months", m.changes12m, fmt],
+ [`share after ${sponsor}`, m.postMarchShare, (v) => pct(v, 0)],
+ [`lines after ${sponsor}`, row.afterLines, (v) => fmt(Math.round(v))],
+ ];
+ const stats: [string, ReactNode][] = all.flatMap(([k, v, f]) =>
+ v === null ? [] : [[k, f(v)] as [string, ReactNode]],
+ );
+ return (
+
+
+
+
+ Selected module
+
+ {m.name}
+
+
+ {m.path}
+ {m.kind && ` · ${m.kind}`}
+
+
+
+ Clear
+
+
+
+ {stats.map(([k, v]) => (
+
+ {k}
+ {v}
+
+ ))}
+
+ {own.length > 0 && (
+
+ Largest files, every kind
+
+ {own.map((f) => {
+ const s = fileShare(f);
+ return (
+
+
+ {f.path}
+ {f.kind !== "production" && (
+ {f.kind}
+ )}
+
+
+ {fmt(f.loc)}
+
+
+ {s === null ? "no value" : pct(s, 0)}
+
+
+
+ );
+ })}
+
+
+ )}
+
+
+ );
+}
+
+function Landed({
+ rows,
+ sponsor,
+ onSelect,
+}: {
+ rows: SizeRow[];
+ sponsor: string;
+ onSelect: (id: string) => void;
+}) {
+ const shown = sortRows(rows, "afterLines", true)
+ .filter((r) => (r.afterLines ?? 0) > 0)
+ .slice(0, LANDED_SHOWN);
+ const total = rows.reduce((s, r) => s + (r.afterLines ?? 0), 0);
+ const max = Math.max(...shown.map((r) => r.afterLines ?? 0), 1);
+ if (rows.every((r) => r.afterLines === null)) return null;
+ return (
+
+
+ production lines × share after the date
+
+ }
+ />
+ {shown.length === 0 ? (
+
+ No module has lines that arrived after {sponsor} in this run.
+
+ ) : (
+
+ {shown.map((r) => {
+ const lines = r.afterLines ?? 0;
+ return (
+
+ onSelect(r.m.id)}
+ className={cn(
+ "grid w-full grid-cols-[minmax(0,9rem)_1fr_auto] items-center gap-3 rounded-sm text-left text-sm hover:bg-muted sm:grid-cols-[minmax(0,16rem)_1fr_auto]",
+ FOCUS,
+ )}
+ >
+
+ {r.m.name}
+
+
+
+
+
+ {fmt(Math.round(lines))}{" "}
+
+ ({pct(total > 0 ? lines / total : 0, 0)})
+
+
+
+
+ );
+ })}
+
+ )}
+
+ Percentages are of all {fmt(Math.round(total))} production lines that arrived after{" "}
+ {sponsor}.
+
+
+ );
+}
+
+const COLUMNS: { key: SortKey; label: (sponsor: string) => string; numeric: boolean }[] = [
+ { key: "name", label: () => "module", numeric: false },
+ { key: "kind", label: () => "kind", numeric: false },
+ { key: "files", label: () => "files", numeric: true },
+ { key: "loc", label: () => "lines", numeric: true },
+ { key: "prodLoc", label: () => "prod. lines", numeric: true },
+ { key: "linksIn", label: () => "links in", numeric: true },
+ { key: "linksOut", label: () => "links out", numeric: true },
+ { key: "changes12m", label: () => "changes 12 mo", numeric: true },
+ { key: "postMarchShare", label: (s) => `share after ${s.slice(0, 7)}`, numeric: true },
+ { key: "afterLines", label: (s) => `lines after ${s.slice(0, 7)}`, numeric: true },
+];
+
+function ModuleTable({
+ rows,
+ sponsor,
+ state,
+ onSort,
+ onSelect,
+}: {
+ rows: SizeRow[];
+ sponsor: string;
+ state: SizeState;
+ onSort: (key: SortKey, descending: boolean) => void;
+ onSelect: (id: string) => void;
+}) {
+ const sorted = sortRows(rows, state.sort, state.descending);
+ const total = rows.reduce((s, r) => s + (r.m.loc ?? 0), 0);
+ const { shown: first, all, toggle } = useShowMore(sorted, ROWS_SHOWN);
+ // A module picked in the size map stays visible even when it sorts below the first rows.
+ const picked = all ? null : sorted.slice(ROWS_SHOWN).find((r) => r.m.id === state.module);
+ const shown = picked ? [...first, picked] : first;
+ return (
+
+
+
+
+
+
+ {COLUMNS.map((c) => {
+ const active = state.sort === c.key;
+ const Icon = active ? (state.descending ? ArrowDown : ArrowUp) : ArrowUpDown;
+ return (
+
+ onSort(c.key, active ? !state.descending : c.numeric)}
+ className={cn(
+ "inline-flex items-center gap-1 rounded-sm whitespace-nowrap hover:text-foreground",
+ active && "text-foreground",
+ FOCUS,
+ )}
+ >
+ {c.label(sponsor)}
+
+
+
+ );
+ })}
+
+
+
+ {shown.map(({ m, prodLoc, afterLines }) => {
+ const isSel = m.id === state.module;
+ return (
+
+
+ onSelect(m.id)}
+ aria-pressed={isSel}
+ title={m.path}
+ className={cn(
+ "max-w-[20rem] truncate rounded-sm text-left font-sans text-sm hover:underline",
+ isSel && "font-semibold",
+ FOCUS,
+ )}
+ >
+ {m.name}
+
+
+ {m.kind ?? "–"}
+ {num(m.files)}
+
+ {num(m.loc)}
+ {m.loc !== null && total > 0 && (
+ {pct(m.loc / total, 1)}
+ )}
+
+ {num(prodLoc)}
+ {num(m.linksIn)}
+ {num(m.linksOut)}
+ {num(m.changes12m)}
+
+
+
+ {share(m.postMarchShare)}
+
+
+
+ {afterLines === null ? EMPTY : fmt(Math.round(afterLines))}
+
+
+ );
+ })}
+
+
+
+
+
+ Lines and files count every file kind, while the share and lines after the date count
+ production lines only .
+
+
+ );
+}
diff --git a/web/src/routes/Trust.tsx b/web/src/routes/Trust.tsx
new file mode 100644
index 00000000..e6f8586e
--- /dev/null
+++ b/web/src/routes/Trust.tsx
@@ -0,0 +1,375 @@
+import { Check, Minus } from "lucide-react";
+import type { ReactNode } from "react";
+import { ComputedMark, NotMeasured } from "../components/cx/badges";
+import { FOCUS, cn } from "../components/cx/cn";
+import { Panel, SectionHead } from "../components/cx/primitives";
+import { useTitle } from "../components/cx/use-page";
+import { commitLink, fmt, pct } from "../cx/meta";
+import type { RepoBundle, StabilityRow } from "../cx/types";
+import { ShowMoreButton, useShowMore } from "./decisions/show-more";
+import { useRepo } from "./RepoLayout";
+import { AiUse, usd } from "./trust/ai-use";
+import { Ranking } from "./trust/ranking";
+import { Stages } from "./trust/stages";
+
+/** Limits shown before "Show all". */
+const LIMITS_SHOWN = 5;
+/** The stability target: at least 4 of the top 5 unchanged. */
+const TARGET_TOP5 = 4;
+
+/** The stability tests, by stored id. */
+const TESTS: Record = {
+ identical_rerun: { label: "Identical re-run", shows: "Same output, byte for byte" },
+ fresh_ai_run: {
+ label: "Fresh AI run, cache off",
+ shows: "How stable the AI's verdicts are; ranking cannot change",
+ },
+ commits_removed_5pct: {
+ label: "5% of commits removed at random, fixed seed",
+ shows: "Sensitivity to history",
+ },
+ end_date_minus_1_month: {
+ label: "End date moved back one month",
+ shows: "Sensitivity to the cut-off",
+ },
+ weights_changed_20pct: {
+ label: "Each weight changed by 20%",
+ shows: "Sensitivity to our own judgement",
+ },
+};
+
+/** The Approach screen: how the report was made, where a model is used, and how far to trust it. */
+export function Trust() {
+ const repo = useRepo();
+ useTitle(`Approach · ${repo.name}`);
+ const files = repo.coverage.reduce((s, c) => s + c.files, 0);
+ const cost = repo.usage.reduce((s, u) => s + u.cost, 0);
+ const rerun = repo.stability.find((r) => r.test === "identical_rerun");
+ // Only the tiles whose value the bundle holds.
+ const tiles: [string, string][] = [
+ ...(repo.coverage.length > 0 ? [["files read", fmt(files)] as [string, string]] : []),
+ ...(rerun
+ ? [
+ ["top 10 unchanged on an identical re-run", `${Math.round(rerun.top10 * 10)} of 10`] as [
+ string,
+ string,
+ ],
+ ]
+ : []),
+ ...(repo.usage.length > 0 ? [["AI cost", usd(cost)] as [string, string]] : []),
+ ];
+
+ return (
+
+
+
+ Approach
+
+ How this report was made, where an AI model is used, and how much of it stays the same
+ when the run is repeated.
+
+
+ {tiles.length > 0 && (
+
+ {tiles.map(([k, v]) => (
+
+ {k}
+ {v}
+
+ ))}
+
+ )}
+
+
+
+
+
+
+
+
+
+
+ );
+}
+
+type CoverageRow = RepoBundle["coverage"][number];
+
+/** A coverage column: heading, hint, the cell, and for an agreement check its stored value. */
+interface CoverageColumn {
+ head: string;
+ hint: string;
+ cell: (c: CoverageRow) => ReactNode;
+ /** Agreement checks may be absent from a run; the column is dropped when no row has a value. */
+ value?: (c: CoverageRow) => number | null;
+ /** How the note under the table names the check when it was not measured. */
+ missing?: string;
+ strong?: boolean;
+}
+
+const share = (v: number | null) => (v === null ? : pct(v));
+
+const COVERAGE: CoverageColumn[] = [
+ { head: "files read", hint: "", cell: (c) => fmt(c.files) },
+ {
+ head: "with unread parts",
+ hint: "Files the reader could not read completely.",
+ cell: (c) => fmt(c.unread),
+ },
+ {
+ head: "imports linked",
+ hint: "Share of imports linked to a file in the project.",
+ cell: (c) => pct(c.linked),
+ },
+ {
+ head: "imports outside",
+ hint: "Share of imports left outside the project, to a declared dependency.",
+ cell: (c) => pct(c.outside),
+ },
+ {
+ head: "unexplained imports",
+ hint: "Imports that match neither a project file nor a declared dependency.",
+ cell: (c) => fmt(c.unexplained),
+ strong: true,
+ },
+ {
+ head: "link agreement",
+ hint: "Agreement with a compiler-accurate index, where the project builds.",
+ cell: (c) => share(c.linkAgreement),
+ value: (c) => c.linkAgreement,
+ missing: "agreement with a compiler-accurate index",
+ },
+ {
+ head: "file links agree",
+ hint: "Agreement with a separate comparison linker, file links.",
+ cell: (c) => share(c.fileAgreement),
+ value: (c) => c.fileAgreement,
+ missing: "file-link agreement with a separate linker",
+ },
+ {
+ head: "module links agree",
+ hint: "Agreement with a separate comparison linker, module links.",
+ cell: (c) => share(c.moduleAgreement),
+ value: (c) => c.moduleAgreement,
+ missing: "module-link agreement with a separate linker",
+ },
+];
+
+function Coverage({ repo }: { repo: RepoBundle }) {
+ const measured = (col: CoverageColumn) =>
+ !col.value || repo.coverage.some((c) => col.value!(c) !== null);
+ const cols = COVERAGE.filter(measured);
+ const dropped = COVERAGE.filter((col) => !measured(col)).map((col) => col.missing!);
+ return (
+
+ } />
+ {repo.coverage.length === 0 ? (
+ No coverage record is stored in this run.
+ ) : (
+
+
+
+
+
+ language
+
+ {cols.map((col) => (
+
+ {col.head}
+
+ ))}
+
+
+
+ {repo.coverage.map((c) => (
+
+
+ {c.language}
+
+ {cols.map((col) => (
+
+ {col.cell(c)}
+
+ ))}
+
+ ))}
+
+
+
+ )}
+
+ Unexplained imports match neither a project file nor a declared dependency.
+ {dropped.length > 0 && ` Not measured in this run: ${joinList(dropped)}.`}
+
+
+ );
+}
+
+/** "a", "a and b", "a, b and c". */
+function joinList(items: string[]): string {
+ if (items.length < 2) return items.join("");
+ return `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
+}
+
+function Limits({ repo }: { repo: RepoBundle }) {
+ const { shown, all, toggle } = useShowMore(repo.blindSpots, LIMITS_SHOWN);
+ return (
+
+
+ {repo.blindSpots.length === 0 ? (
+ No limit is stated in this bundle.
+ ) : (
+
+ {shown.map((b, i) => (
+
+
+ {b}
+
+ ))}
+
+ )}
+
+
+ );
+}
+
+function Stability({ rows }: { rows: StabilityRow[] }) {
+ return (
+
+ }
+ />
+
+
+ Each test repeats the run with one thing changed. Target: at least {TARGET_TOP5} of the
+ top 5 unchanged. RBO is rank-biased overlap at p = 0.9.
+
+
+ meets the target
+
+
+ below the target
+
+
+ {rows.length === 0 ? (
+ No stability test is stored in this run.
+ ) : (
+
+ {rows.map((s) => {
+ const t = TESTS[s.test];
+ const top5 = Math.round(s.top5 * 5);
+ const top10 = Math.round(s.top10 * 10);
+ const meets = top5 >= TARGET_TOP5;
+ return (
+
+
+
+ {meets ? (
+
+ ) : (
+
+ )}
+ {t?.label ?? s.test}
+
+
+ top-5 {top5} of 5 · top-10 {top10} of 10 · RBO{" "}
+ {s.rbo.toFixed(3)}
+
+
+
+
+ {s.note ?? t?.shows ?? ""}
+ {!meets && " · below the target"}
+
+
+ );
+ })}
+
+ )}
+
+ );
+}
+
+function RunIdentity({ repo }: { repo: RepoBundle }) {
+ const commit = commitLink(repo, repo.endSha);
+ const rows: [string, ReactNode][] = [
+ ["snapshot date", repo.snapshotDate],
+ [
+ "commit",
+ commit ? (
+
+ {repo.endSha}
+
+ ) : (
+ repo.endSha
+ ),
+ ],
+ ["params hash", repo.paramsHash],
+ ...(repo.rulesHash ? [["rules hash", repo.rulesHash] as [string, ReactNode]] : []),
+ ];
+ return (
+
+
+
+
+ {rows.map(([k, v]) => (
+
+ {k}
+ {v}
+
+ ))}
+
+
+
+ );
+}
diff --git a/web/src/routes/change/drift.tsx b/web/src/routes/change/drift.tsx
new file mode 100644
index 00000000..2d06eb1f
--- /dev/null
+++ b/web/src/routes/change/drift.tsx
@@ -0,0 +1,237 @@
+// Architectural drift (spec.md §12.2): the project yardsticks and each decision's numbers at
+// the before date and now, with their stored series. Values are read, never recounted.
+import { ComputedMark } from "../../components/cx/badges";
+import { Panel, SectionHead, StatusPill } from "../../components/cx/primitives";
+import { SeriesChart, SeriesLegend } from "../../components/cx/series-chart";
+import { STATUS, fmt, pct } from "../../cx/meta";
+import type { Decision, RepoBundle, SeriesPoint, Yardstick } from "../../cx/types";
+import { ShowMoreButton, useShowMore } from "../decisions/show-more";
+
+const byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
+
+const YARDSTICKS: {
+ key: keyof RepoBundle["yardsticks"];
+ label: string;
+ hint: string;
+}[] = [
+ {
+ key: "againstGrainShare",
+ label: "Backward links",
+ hint: "Share of links between modules that point backwards, from shared code up to the features that use it.",
+ },
+ {
+ key: "twoWayPairs",
+ label: "Two-way dependencies",
+ hint: "Pairs of modules that use each other, so neither can be changed or tested alone.",
+ },
+ {
+ key: "perKloc",
+ label: "Rule breaks per 1,000 lines",
+ hint: "Code that goes against a recorded decision, per 1,000 lines of production code.",
+ },
+];
+
+/** Formats a yardstick value; both values of one yardstick share the number of decimals. */
+function formatter(y: Yardstick): (v: number) => string {
+ if (y.unit === "share") return (v) => pct(v);
+ if (y.unit === "pairs" || y.unit === "links" || y.unit === "decisions") return (v) => fmt(v);
+ const values = [y.now, y.before, ...y.series.map((p) => p.value)].filter(
+ (v): v is number => v !== null,
+ );
+ const decimals = values.some((v) => v !== 0 && Math.abs(v) < 0.1) ? 3 : 2;
+ return (v) => v.toFixed(decimals);
+}
+
+/** The first stored point on or after a date, before the last point; null when there is none. */
+export function pointAfter(series: SeriesPoint[], date: string | null): SeriesPoint | null {
+ if (!date || series.length < 2) return null;
+ const p = series.find((s) => s.date >= date);
+ return p && p !== series.at(-1) ? p : null;
+}
+
+function YardstickCard({
+ repo,
+ label,
+ hint,
+ y,
+}: {
+ repo: RepoBundle;
+ label: string;
+ hint: string;
+ y: Yardstick;
+}) {
+ const f = formatter(y);
+ const end = y.series.at(-1);
+ const adoption = pointAfter(y.series, repo.adoptionDate);
+ return (
+
+
+
+
+ {y.now !== null && (
+ {f(y.now)}
+ )}
+ {y.before !== null && (
+
+ {f(y.before)} at {repo.beforeDate}
+
+ )}
+
+
+
+ {adoption && end && (
+
+ After adoption, from the {adoption.date} snapshot to {end.date}, it changed from{" "}
+ {f(adoption.value)} to{" "}
+ {f(end.value)} .{" "}
+
+
+ )}
+
+ );
+}
+
+/** Decisions shown before "Show all". */
+const RULES_SHOWN = 5;
+
+/** The stored check at the before date, or null when the rule was not checked then. */
+const beforePoint = (repo: RepoBundle, d: Decision) =>
+ d.series.find((p) => p.date === repo.beforeDate) ?? null;
+
+/** Not holding, or its conformance reads differently at the before date and now. */
+function needsAttention(repo: RepoBundle, d: Decision): boolean {
+ const before = beforePoint(repo, d);
+ return (
+ d.status !== "holding" || (before !== null && pct(before.conformance) !== pct(d.conformance))
+ );
+}
+
+function DecisionDrift({ repo }: { repo: RepoBundle }) {
+ // Decisions that need attention first, then by status and id.
+ const list = [...repo.decisions].sort(
+ (a, b) =>
+ Number(needsAttention(repo, b)) - Number(needsAttention(repo, a)) ||
+ STATUS[a.status].order - STATUS[b.status].order ||
+ byText(a.id, b.id),
+ );
+ const { shown, all, toggle } = useShowMore(list, RULES_SHOWN);
+ if (list.length === 0) {
+ return (
+ No decision could be checked in this run.
+ );
+ }
+ const th = "px-4 py-2.5 font-normal whitespace-nowrap";
+ return (
+
+
+
+
+ Each decision's conformance and exceptions per 1,000 lines at {repo.beforeDate} and at
+ the end snapshot
+
+
+
+
+ decision
+
+
+ status now
+
+
+ code that keeps it
+
+ {repo.beforeDate} → now
+
+
+ over time
+
+
+
+
+ {shown.map((d) => {
+ const before = beforePoint(repo, d);
+ const values = d.series.map((p) => p.conformance);
+ return (
+
+
+ {d.statement}
+
+
+
+
+
+ {before ? (
+ pct(before.conformance)
+ ) : (
+ no check
+ )}{" "}
+ → {pct(d.conformance)}
+
+
+
+ ({ date: p.date, value: p.conformance }))}
+ sponsorDate={repo.sponsorDate}
+ adoptionDate={repo.adoptionDate}
+ height={30}
+ color={STATUS[d.status].color}
+ domain={[Math.min(0.8, ...values), 1]}
+ label={`Conformance of ${d.id}`}
+ className="w-[208px]"
+ />
+
+
+ );
+ })}
+
+
+
+
+
+ );
+}
+
+export function Drift({ repo }: { repo: RepoBundle }) {
+ return (
+
+ }
+ />
+
+ {YARDSTICKS.filter((k) => {
+ const y = repo.yardsticks[k.key];
+ return y.now !== null || y.series.length > 0;
+ }).map((k) => (
+
+ ))}
+
+ Each decision, then and now
+
+
+ );
+}
diff --git a/web/src/routes/change/events.tsx b/web/src/routes/change/events.tsx
new file mode 100644
index 00000000..9f8a76b3
--- /dev/null
+++ b/web/src/routes/change/events.tsx
@@ -0,0 +1,239 @@
+// Structural events between the two compared dates (spec.md §12.3), grouped by kind. Each
+// carries its label, the basis for it and the evidence records behind it.
+import { AiBadge, ComputedMark } from "../../components/cx/badges";
+import { cn } from "../../components/cx/cn";
+import { Chip, SectionHead } from "../../components/cx/primitives";
+import { fmt } from "../../cx/meta";
+import type { RepoBundle, StructuralEvent } from "../../cx/types";
+import { ShowMoreButton, useShowMore } from "../decisions/show-more";
+import { EvidenceList } from "./evidence";
+
+export const LABEL: Record = {
+ planned: "planned",
+ no_stated_intent: "unexplained",
+};
+
+export const BASIS: Record, string> = {
+ same_code_old_layout: "same code, old layout",
+ restructuring_commit: "restructuring commit",
+ decision_document: "decision document",
+ pr_goal: "pull request goal",
+};
+
+const GROUPS: { kind: StructuralEvent["kind"]; title: string; noun: string }[] = [
+ { kind: "restructuring", title: "Restructurings", noun: "restructurings" },
+ { kind: "module_added", title: "Modules added", noun: "modules added" },
+ { kind: "module_removed", title: "Modules removed", noun: "modules removed" },
+ { kind: "link_added", title: "Links added between modules", noun: "links added" },
+ { kind: "link_removed", title: "Links removed between modules", noun: "links removed" },
+];
+
+const byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
+
+/** Events shown per group before "Show all". */
+const FIRST = 5;
+
+export function LabelChip({ label }: { label: StructuralEvent["label"] }) {
+ return {LABEL[label]} ;
+}
+
+function Dot({ label }: { label: StructuralEvent["label"] }) {
+ return (
+
+ );
+}
+
+export function labelCounts(events: StructuralEvent[]) {
+ const planned = events.filter((e) => e.label === "planned").length;
+ return { planned, none: events.length - planned };
+}
+
+function EventItem({ repo, e }: { repo: RepoBundle; e: StructuralEvent }) {
+ return (
+
+
+
+
+
+ {e.fromDate && e.date && (
+
+ {e.fromDate} → {e.date}
+
+ )}
+
+
+ {e.basis ? `basis: ${BASIS[e.basis]}` : "no basis found"}
+
+ {e.source === "ai" ? : }
+
+
+ {e.title}
+
+
+
+ );
+}
+
+function Group({
+ repo,
+ title,
+ noun,
+ kind,
+ events,
+}: {
+ repo: RepoBundle;
+ title: string;
+ noun: string;
+ kind: StructuralEvent["kind"];
+ events: StructuralEvent[];
+}) {
+ const first = FIRST;
+ const { shown, all, toggle } = useShowMore(events, first);
+ const c = labelCounts(events);
+ const id = `events-${kind}`;
+ return (
+
+
+ {title}
+
+ {fmt(events.length)} · {fmt(c.planned)} planned · {fmt(c.none)} unexplained
+
+
+
+ {shown.map((e) => (
+
+ ))}
+
+
+
+ );
+}
+
+export function StructuralEvents({ repo }: { repo: RepoBundle }) {
+ const c = labelCounts(repo.events);
+ // Restructurings by interval, the rest in stored order.
+ const byKind = (kind: StructuralEvent["kind"]) => {
+ const list = repo.events.filter((e) => e.kind === kind);
+ return kind === "restructuring"
+ ? [...list].sort((a, b) => byText(a.fromDate ?? "", b.fromDate ?? "") || byText(a.id, b.id))
+ : list;
+ };
+ const rows = GROUPS.map((g) => ({ ...g, events: byKind(g.kind) })).filter(
+ (g) => g.events.length > 0,
+ );
+ const th = "px-4 py-2.5 text-right font-normal whitespace-nowrap";
+ return (
+
+
+ {fmt(repo.events.length)} {repo.events.length === 1 ? "change" : "changes"}
+
+ }
+ />
+
+ Drift is not automatically bad. A change counts as planned when a restructuring commit, a
+ decision document or a pull request explains it. A change without one is not called a
+ mistake, only unexplained.
+
+ {repo.events.length === 0 ? (
+
+ No structural change was found between the two dates in this run.
+
+ ) : (
+ <>
+
+
+ Structural changes by kind and by stated intent
+
+
+
+ Kind of change
+
+
+ Total
+
+
+
+ Planned
+
+
+
+
+ Unexplained
+
+
+
+
+
+ {rows.map((g) => {
+ const k = labelCounts(g.events);
+ return (
+
+
+ {g.title}
+
+
+ {fmt(g.events.length)}
+
+ {fmt(k.planned)}
+
+ {fmt(k.none)}
+
+
+ );
+ })}
+
+
+
+
+ All changes
+
+
+ {fmt(repo.events.length)}
+
+ {fmt(c.planned)}
+ {fmt(c.none)}
+
+
+
+
+
+
+ Show every change with its evidence
+
+
+
+
+ built from stored facts
+
+
+ written by an AI model, citations checked
+
+
+ {rows.map((g) => (
+
+ ))}
+
+
+ >
+ )}
+
+ );
+}
diff --git a/web/src/routes/change/evidence.tsx b/web/src/routes/change/evidence.tsx
new file mode 100644
index 00000000..3fcb3156
--- /dev/null
+++ b/web/src/routes/change/evidence.tsx
@@ -0,0 +1,81 @@
+// Evidence records (spec.md §4.4) as short, linked references: a commit hash or "path:lines".
+import { FOCUS, cn } from "../../components/cx/cn";
+import { commitLink, hostLink } from "../../cx/meta";
+import type { Evidence, RepoBundle } from "../../cx/types";
+
+const refCls = cn(
+ "rounded-sm font-mono text-[11px] text-foreground underline decoration-border underline-offset-2 hover:decoration-foreground",
+ FOCUS,
+);
+
+function Ref({ href, title, children }: { href: string | null; title: string; children: string }) {
+ return href ? (
+
+ {children}
+
+ ) : (
+
+ {children}
+
+ );
+}
+
+/** "path:12-18", linked to the host at the evidence's own snapshot commit. */
+export function lineRef(e: Evidence): string {
+ if (!e.path) return "";
+ if (e.startLine === null) return e.path;
+ return e.endLine !== null && e.endLine !== e.startLine
+ ? `${e.path}:${e.startLine}-${e.endLine}`
+ : `${e.path}:${e.startLine}`;
+}
+
+export function EvidenceList({
+ repo,
+ evidence,
+ className,
+}: {
+ repo: RepoBundle;
+ evidence: Evidence[];
+ className?: string;
+}) {
+ if (evidence.length === 0) return null;
+ return (
+
+ {evidence.map((e) => (
+
+ {e.kind === "lines" && e.path ? (
+ <>
+ [
+ {lineRef(e)}
+ ]
+ {e.role && <> · {e.role}>}
+ >
+ ) : (
+ <>
+ {e.commits.map((sha, i) => (
+
+ {i > 0 && ", "}
+ [
+ {sha.slice(0, 7)}
+ ]
+
+ ))}
+ {e.role && <> · {e.role}>}
+ >
+ )}
+
+ ))}
+
+ );
+}
diff --git a/web/src/routes/change/impact.tsx b/web/src/routes/change/impact.tsx
new file mode 100644
index 00000000..133fff87
--- /dev/null
+++ b/web/src/routes/change/impact.tsx
@@ -0,0 +1,369 @@
+// The impact at a glance: each stored measure at the comparison date against now, drawn as two
+// dots on one line, with whether that is better or worse and how fast it moved before and after.
+// Every value is a stored series point; this file only compares two of them.
+import { ComputedMark } from "../../components/cx/badges";
+import { cn } from "../../components/cx/cn";
+import { allFindings } from "../../components/cx/finding-fix";
+import { STATUS, fmt, pct } from "../../cx/meta";
+import type { Finding, RepoBundle, SeriesPoint } from "../../cx/types";
+
+const WORSE = STATUS.slipping.color;
+const BETTER = STATUS.holding.color;
+/** A move smaller than this share of the old value reads as "about the same". */
+const SAME = 0.03;
+
+type Verdict = "worse" | "better" | "same";
+
+interface Measure {
+ /** Stored yardstick name. */
+ series: string;
+ label: string;
+ question: string;
+ lowerIsBetter: boolean;
+ format: (v: number) => string;
+ /** Formats a change per month. */
+ pace: (v: number) => string;
+}
+
+const sign = (v: number) => (v > 0 ? "+" : v < 0 ? "−" : "±");
+
+const MEASURES: Measure[] = [
+ {
+ series: "against_grain_share",
+ label: "Backward links",
+ question: "Does shared code reach back up into features?",
+ lowerIsBetter: true,
+ format: (v) => pct(v),
+ pace: (v) => `${sign(v)}${Math.abs(v * 100).toFixed(2)} pts`,
+ },
+ {
+ series: "two_way_module_pairs",
+ label: "Two-way dependencies",
+ question: "Are modules more tangled with each other?",
+ lowerIsBetter: true,
+ format: (v) => fmt(Math.round(v)),
+ pace: (v) => `${sign(v)}${Math.abs(v).toFixed(1)}`,
+ },
+ {
+ series: "exceptions_per_kloc",
+ label: "Rule breaks per 1,000 lines",
+ question: "Does new code break the recorded decisions more often?",
+ lowerIsBetter: true,
+ format: (v) => v.toFixed(2),
+ pace: (v) => `${sign(v)}${Math.abs(v).toFixed(3)}`,
+ },
+ {
+ series: "decisions_holding",
+ label: "Decisions still holding",
+ question: "How many architecture decisions are still kept?",
+ lowerIsBetter: false,
+ format: (v) => fmt(Math.round(v)),
+ pace: (v) => `${sign(v)}${Math.abs(v).toFixed(2)}`,
+ },
+];
+
+/** The stored point on the date, or the last one before it. */
+function pointAt(series: SeriesPoint[], date: string): SeriesPoint | null {
+ let hit: SeriesPoint | null = null;
+ for (const p of series) if (p.date <= date) hit = p;
+ return hit;
+}
+
+/** Months between two ISO dates, at least a tenth of a month. */
+function months(a: string, b: string): number {
+ const d = (Date.parse(b) - Date.parse(a)) / (1000 * 60 * 60 * 24 * 30.44);
+ return Math.max(0.1, d);
+}
+
+function verdictOf(m: Measure, before: number, now: number): Verdict {
+ const base = Math.max(Math.abs(before), 1e-9);
+ if (Math.abs(now - before) / base < SAME) return "same";
+ const rose = now > before;
+ return rose === m.lowerIsBetter ? "worse" : "better";
+}
+
+interface Row {
+ m: Measure;
+ before: SeriesPoint;
+ now: SeriesPoint;
+ verdict: Verdict;
+ /** Change per month before the comparison date and after it; null without enough points. */
+ paceBefore: number | null;
+ paceAfter: number;
+}
+
+function rowsOf(repo: RepoBundle, compareDate: string): Row[] {
+ return MEASURES.flatMap((m) => {
+ const s = repo.yardstickSeries[m.series] ?? [];
+ const before = pointAt(s, compareDate);
+ const now = s.at(-1);
+ if (!before || !now || now === before) return [];
+ const first = s[0];
+ const paceBefore =
+ first && first !== before
+ ? (before.value - first.value) / months(first.date, before.date)
+ : null;
+ const paceAfter = (now.value - before.value) / months(before.date, now.date);
+ return [
+ { m, before, now, verdict: verdictOf(m, before.value, now.value), paceBefore, paceAfter },
+ ];
+ });
+}
+
+const VERDICT_TEXT: Record = {
+ worse: "Worse",
+ better: "Better",
+ same: "About the same",
+};
+
+function VerdictTag({ v }: { v: Verdict }) {
+ return (
+
+
+ {VERDICT_TEXT[v]}
+
+ );
+}
+
+/** Two dots on one line: hollow is then, filled is now. The line between them carries the verdict. */
+function Dumbbell({ row }: { row: Row }) {
+ const { before, now, verdict } = row;
+ const hi = Math.max(before.value, now.value) * 1.12 || 1;
+ const x = (v: number) => 8 + (v / hi) * 284;
+ const color =
+ verdict === "worse" ? WORSE : verdict === "better" ? BETTER : "var(--muted-foreground)";
+ const a = x(before.value);
+ const b = x(now.value);
+ const dir = b >= a ? 1 : -1;
+ return (
+
+
+
+
+
+
+ );
+}
+
+function paceText(row: Row): string | null {
+ const { paceBefore: pb, paceAfter: pa, m } = row;
+ if (pb === null) return null;
+ const word = (v: number) => (Math.abs(v) < 1e-9 ? "flat" : `${m.pace(v)} a month`);
+ return `Before: ${word(pb)}. After: ${word(pa)}.`;
+}
+
+/** How the pace after the comparison date compares with the pace before it. */
+function momentum(row: Row): string | null {
+ const { paceBefore: pb, paceAfter: pa } = row;
+ if (pb === null || Math.abs(pa) < 1e-9) return null;
+ if (Math.abs(pb) < 1e-9) return pa > 0 ? "started rising" : "started falling";
+ if (Math.sign(pb) !== Math.sign(pa)) return pa > 0 ? "turned upward" : "turned downward";
+ const r = Math.abs(pa) / Math.abs(pb);
+ if (r >= 1.25) return "moving faster than before";
+ if (r <= 0.8) return "moving slower than before";
+ return "same pace as before";
+}
+
+function MeasureRow({ row, compact }: { row: Row; compact: boolean }) {
+ const { m, before, now, verdict } = row;
+ const pace = compact ? null : paceText(row);
+ return (
+
+
+ {m.label}
+
+ {m.question}{" "}
+
+ ({m.lowerIsBetter ? "lower" : "higher"} is better)
+
+
+ {pace && {pace} }
+
+
+ {m.format(before.value)}
+
+
+
+ {m.format(before.value)}
+
+
+
+ {m.format(now.value)}
+
+
+
+ {m.format(now.value)}
+
+
+
+ {!compact && momentum(row) && (
+ {momentum(row)}
+ )}
+
+
+ );
+}
+
+const TREND_PARTS: { key: Finding["trend"]["status"]; label: string; color: string }[] = [
+ { key: "new_since_2025_03", label: "new since March 2025", color: "var(--foreground)" },
+ { key: "worse", label: "getting worse", color: WORSE },
+ { key: "unchanged", label: "unchanged", color: "var(--border)" },
+ { key: "better", label: "improving", color: BETTER },
+];
+
+/** Every ranked problem, split by how it moved over the snapshots. */
+function ProblemTrend({ repo }: { repo: RepoBundle }) {
+ const all = allFindings(repo);
+ if (all.length === 0) return null;
+ const counts = TREND_PARTS.map((p) => ({
+ ...p,
+ n: all.filter((f) => f.trend.status === p.key).length,
+ }));
+ return (
+
+ The {fmt(all.length)} problems found, by how they moved
+ `${c.n} ${c.label}`).join(", ")}
+ >
+ {counts.map(
+ (c) =>
+ c.n > 0 && (
+
+ ),
+ )}
+
+
+ {counts.map((c) => (
+
+
+ {fmt(c.n)} {" "}
+ {c.label}
+
+ ))}
+
+
+ );
+}
+
+/** "3 measures got worse and 1 got better." */
+function Headline({ rows }: { rows: Row[] }) {
+ const n = (v: Verdict) => rows.filter((r) => r.verdict === v).length;
+ const parts: { v: Verdict; text: string }[] = [];
+ if (n("worse")) parts.push({ v: "worse", text: `${n("worse")} got worse` });
+ if (n("better")) parts.push({ v: "better", text: `${n("better")} got better` });
+ if (n("same")) parts.push({ v: "same", text: `${n("same")} stayed about the same` });
+ return (
+
+ Of {rows.length} measures,{" "}
+ {parts.map((p, i) => (
+
+ {i > 0 && (i === parts.length - 1 ? " and " : ", ")}
+
+ {p.text}
+
+
+ ))}
+ .
+
+ );
+}
+
+export function Impact({
+ repo,
+ compareDate,
+ compact = false,
+}: {
+ repo: RepoBundle;
+ compareDate: string;
+ compact?: boolean;
+}) {
+ const rows = rowsOf(repo, compareDate);
+ if (rows.length === 0) return null;
+ const nowDate = rows[0].now.date;
+ const size = repo.yardstickSeries.cross_module_links ?? [];
+ const sizeBefore = pointAt(size, compareDate);
+ const sizeNow = size.at(-1);
+ const grew =
+ sizeBefore && sizeNow && sizeBefore.value > 0
+ ? (sizeNow.value - sizeBefore.value) / sizeBefore.value
+ : null;
+ return (
+
+
+
+
+ measure
+ {compareDate}
+
+
+
+
+ then
+
+
+
+ now
+
+ {nowDate}
+ since then
+
+
+ {rows.map((r) => (
+
+ ))}
+
+ {!compact && }
+
+
+ {grew !== null && grew > 0.05 && (
+ <>
+ The code itself grew: links between modules went from {fmt(sizeBefore!.value)} to{" "}
+ {fmt(sizeNow!.value)} ({sign(grew)}
+ {Math.round(Math.abs(grew) * 100)}%). Backward links and rule breaks per 1,000 lines are
+ rates, so they already allow for that.{" "}
+ >
+ )}
+ These are stored measurements at two dates. They show what changed, not that AI caused it.{" "}
+
+
+
+ );
+}
diff --git a/web/src/routes/decisions/show-more.tsx b/web/src/routes/decisions/show-more.tsx
new file mode 100644
index 00000000..09ab7792
--- /dev/null
+++ b/web/src/routes/decisions/show-more.tsx
@@ -0,0 +1,56 @@
+// A long list shows its first few items and a button for the rest.
+import { ChevronDown } from "lucide-react";
+import { useState } from "react";
+import { FOCUS, cn } from "../../components/cx/cn";
+import { fmt } from "../../cx/meta";
+
+export function useShowMore(items: readonly T[], first: number) {
+ const [all, setAll] = useState(false);
+ return {
+ shown: all ? items : items.slice(0, first),
+ all,
+ toggle: () => setAll((v) => !v),
+ more: items.length > first,
+ };
+}
+
+export function ShowMoreButton({
+ total,
+ first,
+ all,
+ onToggle,
+ noun,
+ controls,
+ className,
+}: {
+ total: number;
+ first: number;
+ all: boolean;
+ onToggle: () => void;
+ /** Plural noun, for example "statements". */
+ noun: string;
+ /** Id of the list the button opens. */
+ controls: string;
+ className?: string;
+}) {
+ if (total <= first) return null;
+ return (
+
+ {all ? `Show the first ${fmt(first)}` : `Show all ${fmt(total)} ${noun}`}
+
+
+ );
+}
diff --git a/web/src/routes/finding/Rail.tsx b/web/src/routes/finding/Rail.tsx
new file mode 100644
index 00000000..083c782f
--- /dev/null
+++ b/web/src/routes/finding/Rail.tsx
@@ -0,0 +1,303 @@
+// The side rail of a finding page: close-up, priority with its formula, the finding over
+// time with where its lines came from, and the decision it breaks. The stored facts, shown
+// at the top of the main column, are defined here too.
+import { ChevronRight } from "lucide-react";
+import { Link } from "react-router";
+import { ComputedMark } from "../../components/cx/badges";
+import { FOCUS, cn } from "../../components/cx/cn";
+import { Closeup, CloseupLegend } from "../../components/cx/closeup";
+import { weightOf } from "../../components/cx/finding-fix";
+import { Panel, StatusPill } from "../../components/cx/primitives";
+import { Sparkline, markIndex } from "../../components/cx/sparkline";
+import { repoPath } from "../../cx/address";
+import { FACT_LABEL, FACT_SHARE, STATUS, fmt, pct } from "../../cx/meta";
+import type { Decision, Fact, Finding, RepoBundle } from "../../cx/types";
+
+const PRIORITY: ["S" | "R" | "P" | "A" | "ease", string, string][] = [
+ ["S", "Size", "Size of the breach, as a percentile within the finding type"],
+ ["R", "Reach", "How much code depends on it, as a percentile"],
+ ["P", "Change pressure", "Changes to the affected code in 12 months, as a percentile"],
+ ["A", "Authority", "How firmly the rule is held; 0.8 for pressure points"],
+ ["ease", "Ease", "How cheap the fix is: 1.0 for 1 to 3 places, less for more"],
+];
+
+const panelHead = "text-xs font-medium";
+
+export function CloseupPanel({ repo, f }: { repo: RepoBundle; f: Finding }) {
+ return (
+
+ Close-up
+
+ {f.layout && f.layout.length > 0 && (
+ <>
+
+
+ Numbers count the links between modules; only links that touch this finding’s
+ modules are drawn.
+
+ >
+ )}
+
+ );
+}
+
+export function PriorityPanel({ repo, f }: { repo: RepoBundle; f: Finding }) {
+ const p = f.priority;
+ const ws = weightOf(repo, "S");
+ const wr = weightOf(repo, "R");
+ const wp = weightOf(repo, "P");
+ const impact =
+ ws !== null && wr !== null && wp !== null ? p.A * (ws * p.S + wr * p.R + wp * p.P) : null;
+ const n2 = (v: number) => v.toFixed(2);
+ const w1 = (v: number | null) => (v === null ? "–" : v.toFixed(1));
+ return (
+
+
+ Priority
+
+ {p.score.toFixed(2)}
+
+
+
+ {PRIORITY.map(([k, label, hint]) => (
+
+
+ {label} ({k === "ease" ? "ease" : k})
+
+
+
+
+ {n2(p[k])}
+
+ ))}
+
+
+
+
+ How this score is computed
+
+
+
+ impact = A × ({w1(ws)}·S + {w1(wr)}·R + {w1(wp)}·P)
+
+ {impact !== null && (
+
+ = {n2(p.A)} × ({w1(ws)}·{n2(p.S)} + {w1(wr)}·{n2(p.R)} + {w1(wp)}·{n2(p.P)}) ={" "}
+ {impact.toFixed(3)}
+
+ )}
+
+ priority = impact × ease
+ {impact !== null && (
+
+ {" "}
+ = {impact.toFixed(3)} × {n2(p.ease)} → {p.score.toFixed(2)}
+
+ )}
+
+
+ Weights from the run; order by priority, then finding id.
+
+
+
+
+ );
+}
+
+export function TrendPanel({ repo, f }: { repo: RepoBundle; f: Finding }) {
+ const series = f.trend.series;
+ const values = series.map((s) => s.value);
+ const compareDate = repo.sponsorDate ?? repo.beforeDate;
+ const first = values.find((v) => v > 0) ?? values[0];
+ const last = values.at(-1);
+ return (
+
+
+ Over time
+ {first !== undefined && last !== undefined && (
+
+ {fmt(first)} → {fmt(last)}
+
+ )}
+
+ {values.length >= 2 ? (
+ s.date),
+ compareDate,
+ )}
+ width={300}
+ height={64}
+ area
+ color="var(--accent)"
+ label={`Size of finding ${f.rank} at each snapshot`}
+ className="w-full"
+ />
+ ) : (
+
+ {values.length === 1 ? "One snapshot only." : "No series is stored for this finding."}
+
+ )}
+
+ {series[0]?.date.slice(0, 7) ?? ""}
+ first seen {f.trend.firstSeen.slice(0, 7)}
+ {series.at(-1)?.date.slice(0, 7) ?? ""}
+
+
+
+ dashed line: {compareDate.slice(0, 7)}
+
+
+
+ lines after 2025-03
+ {pct(f.origin.linesAfter, 0)}
+
+
+ AI-marked lines, a lower bound
+ {pct(f.origin.linesAiMarked, 0)}
+
+
+
+ The AI share counts explicit markers only, so it is a lower bound, and lines without a
+ marker carry no AI signal.
+
+
+ );
+}
+
+/** A stored fact has a value worth showing: not empty, not a number that failed to compute. */
+function hasValue(x: Fact): boolean {
+ const v = x.value as Fact["value"] | null | undefined;
+ if (v === null || v === undefined) return false;
+ if (typeof v === "string") return v.trim().length > 0;
+ if (typeof v === "number") return Number.isFinite(v);
+ return true;
+}
+
+function factValue(x: Fact): string {
+ const v = x.value;
+ if (typeof v === "number") return FACT_SHARE.has(x.key) ? pct(v, 0) : fmt(v);
+ if (typeof v === "boolean") return v ? "yes" : "no";
+ return v;
+}
+
+/** Grammar only: a plural unit after the number 1 reads singular ("1 link"); the stored unit is unchanged. */
+function factUnit(v: number | string | boolean, unit: string): string {
+ return v === 1 && unit.length > 1 && unit.endsWith("s") ? unit.slice(0, -1) : unit;
+}
+
+const factLabel = (key: string) => {
+ const label = FACT_LABEL[key] ?? key.replace(/_/g, " ");
+ return label.charAt(0).toUpperCase() + label.slice(1);
+};
+
+/** The finding's stored facts with readable labels and units; facts with no value are left out. */
+export function FactsPanel({ f }: { f: Finding }) {
+ // Counts first, in stored order, then names and lists, which take a full row each.
+ const present = f.facts.filter(hasValue);
+ const facts = [
+ ...present.filter((x) => typeof x.value !== "string"),
+ ...present.filter((x) => typeof x.value === "string"),
+ ];
+ const lq = f.linkQuality;
+ return (
+
+
+
+ Facts
+
+
+
+ {facts.length === 0 && !lq ? (
+ This finding stores no fact.
+ ) : (
+
+
+ {facts.map((x) => (
+
+ {factLabel(x.key)}
+
+ {factValue(x)}
+ {x.unit && typeof x.value !== "string" && (
+
+ {" "}
+ {factUnit(x.value, x.unit)}
+
+ )}
+
+
+ ))}
+ {lq && (
+
+ Links found by
+
+ {lq.how}
+ {lq.agreement !== null && (
+
+ {" "}
+ · {pct(lq.agreement, 0)} agreement
+
+ )}
+
+
+ )}
+
+
+ )}
+
+ );
+}
+
+export function DecisionCard({ repo, decision }: { repo: RepoBundle; decision: Decision }) {
+ return (
+
+
+ {decision.statement}
+
+ {decision.id} ·{" "}
+ {pct(decision.conformance)} {" "}
+ conformance
+
+
+ );
+}
diff --git a/web/src/routes/finding/Reading.tsx b/web/src/routes/finding/Reading.tsx
new file mode 100644
index 00000000..452f763d
--- /dev/null
+++ b/web/src/routes/finding/Reading.tsx
@@ -0,0 +1,251 @@
+// The judgement of a finding page: job B's reading of the code when one passed every check
+// (spec.md §8.4), otherwise the computed summary (§8.7). Then why the finding type matters,
+// the proposed fix once, and what the stored simulation can be said to show (§8.5).
+import { ArrowRight, Check, Map as MapIcon, TriangleAlert, Wand2 } from "lucide-react";
+import type { ReactNode } from "react";
+import { Link } from "react-router";
+import { AiBadge, ComputedMark, NotMeasured } from "../../components/cx/badges";
+import { FOCUS, cn } from "../../components/cx/cn";
+import { LegitimateBadge } from "../../components/cx/finding-list-row";
+import {
+ type ProposedFix,
+ fixOf,
+ hasSimulatedFix,
+ moduleLabel,
+} from "../../components/cx/finding-fix";
+import { Chip, Panel, Prose } from "../../components/cx/primitives";
+import { repoPath } from "../../cx/address";
+import { ACTION, NO_FIX_TEXT, SIMULATION, STATUS, TYPE, VERDICT, fmt } from "../../cx/meta";
+import type { Finding, RepoBundle } from "../../cx/types";
+
+const GOOD = STATUS.holding.color;
+
+const headCls = "text-sm font-semibold text-foreground";
+
+/**
+ * The computed summary without the template's fix sentence when the fix is shown on its own
+ * below it, so the same sentence is not printed twice. The stored text is otherwise unchanged.
+ */
+export function summaryWithoutFix(f: Finding): string {
+ const fix = fixOf(f);
+ if (!fix || fix.source !== "computed" || !f.summary.includes(fix.text)) return f.summary;
+ return f.summary.replace(fix.text, "").trim();
+}
+
+export function Reading({ repo, f }: { repo: RepoBundle; f: Finding }) {
+ const j = f.judgement;
+ const fix = fixOf(f);
+ const summary = summaryWithoutFix(f);
+ return (
+
+
+ Judgement
+
+
+ {j ? (
+ <>
+
+
+
+ Reading of the code
+
+ {j.verdict === "legitimate_wiring" ? (
+
+ ) : (
+
+ {VERDICT[j.verdict]}
+
+ )}
+ confidence {j.confidence}
+
+
+
+
+ {j.votes && <>{j.votes} votes · >}
+ {j.citationsChecked} of {j.citations} citations checked
+
+
+
+
+
+
+
+ Written by {j.model ?? "an AI model"} from the cited lines, with every number and
+ name checked against the facts and the code.
+
+
+
+ >
+ ) : (
+ <>
+
+
+ Computed summary
+
+
+
+
+ {summary && }
+
+ No AI reading is shown for this finding, so this text is built from the stored facts
+ by fixed rules.
+
+
+ >
+ )}
+
+
+
+ Why it matters
+
+
+ {TYPE[f.type].why}
+
+ {fix ? (
+
+ ) : (
+
+ )}
+
+
+
+
+ );
+}
+
+function FixBlock({
+ repo,
+ fix,
+ symbol = null,
+ from = null,
+ to = null,
+}: {
+ repo: RepoBundle;
+ fix: ProposedFix;
+ symbol?: string | null;
+ from?: string | null;
+ to?: string | null;
+}) {
+ return (
+
+
+ Proposed fix · {ACTION[fix.action]}
+ {symbol && {symbol} }
+ {from && to && (
+
+ {moduleLabel(repo, from)} {" "}
+ {moduleLabel(repo, to)}
+
+ )}
+ {fix.source === "ai" ? : }
+
+
+
+ );
+}
+
+function NoFix({ note }: { note: string | null }) {
+ return (
+
+ {NO_FIX_TEXT}
+ {note && (
+
+ )}
+
+ );
+}
+
+const linkBtn = cn(
+ "inline-flex items-center gap-1.5 rounded-md border bg-card px-3 py-1.5 text-sm font-medium hover:border-foreground/30",
+ FOCUS,
+);
+
+function SimulationStrip({ repo, f }: { repo: RepoBundle; f: Finding }) {
+ const fix = fixOf(f);
+ const sim = f.simulation;
+ const kind = sim?.kind ?? "not-simulated";
+ const shown =
+ fix !== null && sim !== null && kind !== "not-simulated" && kind !== "nothing-changed";
+ const mapBase = repoPath(repo.id, "map");
+
+ return (
+
+
+
+ Simulation
+
+ {fix ? SIMULATION[kind].long : NO_FIX_TEXT}
+
+
+
+
+
+ Show on map
+
+ {hasSimulatedFix(f) && (
+
+ Try the fix
+
+ )}
+
+
+ {shown && sim && (
+
+
+ {sim.loopsBefore === null || sim.loopsAfter === null ? (
+
+ ) : (
+ `${fmt(sim.loopsBefore)} → ${fmt(sim.loopsAfter)}`
+ )}
+ |
+ 0}>
+ {fmt(sim.linksRemoved)}
+ |
+ {fmt(sim.linksAdded)} |
+
+ {sim.targetLinkRemoved ? "yes" : "no"}
+ |
+
+ )}
+ {shown && sim && sim.newExceptions.length > 0 && (
+
+
+ This fix would create new exceptions: {sim.newExceptions.join(", ")}
+
+ )}
+
+ );
+}
+
+function Cell({ k, good = false, children }: { k: string; good?: boolean; children: ReactNode }) {
+ return (
+
+ {k}
+
+ {children}
+
+
+ );
+}
diff --git a/web/src/routes/map/CellPanel.tsx b/web/src/routes/map/CellPanel.tsx
new file mode 100644
index 00000000..0c08b47d
--- /dev/null
+++ b/web/src/routes/map/CellPanel.tsx
@@ -0,0 +1,269 @@
+import { ArrowRight, ExternalLink, SquareCode, X } from "lucide-react";
+import { useState } from "react";
+import { Link } from "react-router";
+import { findingPath, type MapView } from "../../cx/address";
+import { readCloneRoot, writeCloneRoot } from "../../cx/clone";
+import { cellKey } from "../../cx/grid";
+import { editorLink, fmt, hostLink } from "../../cx/meta";
+import type { Finding, RepoBundle } from "../../cx/types";
+import { FOCUS, cn } from "../../components/cx/cn";
+
+const plainLinks = (v: number) => (v === 1 ? "1 link" : `${fmt(v)} links`);
+
+/** The links behind one selected cell, each one click from the code (spec.md §10.3). */
+export function CellPanel({
+ repo,
+ cell: [i, j],
+ view,
+ values,
+ redrawn,
+ change,
+ changeSource,
+ finding,
+ onClose,
+}: {
+ repo: RepoBundle;
+ cell: [number, number];
+ view: MapView | "fix";
+ values: number[][];
+ redrawn: boolean;
+ change?: { before: number; after: number };
+ changeSource: string;
+ finding?: Finding;
+ onClose: () => void;
+}) {
+ const [root, setRoot] = useState(() => readCloneRoot(repo.id));
+ const src = repo.modules[i]!;
+ const dst = repo.modules[j]!;
+ const links = repo.cellLinks[cellKey(src.id, dst.id)];
+ const now = repo.matrix[i]![j]!;
+ const shown = values[i]![j]!;
+ const back = values[j]![i]!;
+ const against = i > j;
+ const refs = (links?.refs ?? []).filter((r) => r.kind === "lines" && r.path);
+
+ if (i === j) return null;
+
+ const viewCount =
+ view === "before"
+ ? `${plainLinks(shown)} at ${repo.beforeDate}`
+ : redrawn
+ ? `${plainLinks(shown)} after the simulated change`
+ : `${plainLinks(shown)} at ${repo.snapshotDate}`;
+
+ return (
+
+
+
+
+ {src.name} {" "}
+ {dst.name}
+
+
+ {src.path}
+ → {dst.path}
+
+
+ {viewCount}
+ {shown > 0 && (
+ <>
+ {" · "}
+
+ {against ? "backward link" : "forward link"}
+
+ >
+ )}
+
+ {change && (
+
+ {fmt(change.before)} → {fmt(change.after)} {changeSource}
+
+ )}
+
+ The other way round, {dst.name} uses {src.name}{" "}
+ {back === 0 ? "not at all" : back === 1 ? "once" : `${fmt(back)} times`}
+ {view === "before" ? ` at ${repo.beforeDate}` : ""}.
+
+ {(!src.presentAtEnd || !dst.presentAtEnd) && (
+
+ {!src.presentAtEnd ? src.name : dst.name} exists only at the before date.
+
+ )}
+
+
+
+
+
+
+ {finding && (
+
+
+ #{finding.rank} {finding.title}
+
+
+
+ )}
+
+
+
+ Links at {repo.snapshotDate}
+ {view !== "now" && (
+
+ {" "}
+ · the file list is stored for the end snapshot only
+
+ )}
+
+ {now === 0 || !links ? (
+
+ No links in this cell at {repo.snapshotDate}.
+
+ ) : (
+
+ showing {fmt(refs.length)} of {plainLinks(links.count)}
+ {refs.length < links.count && " · the pipeline keeps a few lines per cell"}
+
+ )}
+
+
+ {refs.length > 0 && (
+
+ {refs.map((r) => {
+ const lines =
+ r.startLine === null
+ ? ""
+ : r.endLine && r.endLine !== r.startLine
+ ? `:${r.startLine}-${r.endLine}`
+ : `:${r.startLine}`;
+ const host = hostLink(repo, r.path!, r.startLine, r.endLine);
+ const editor = editorLink(root, r.path!, r.startLine);
+ const short = r.path!.split("/").slice(-2).join("/");
+ return (
+
+
+
+ {host && (
+
+
+
+ )}
+ {editor && (
+
+
+
+ )}
+
+
+ );
+ })}
+
+ )}
+
+ {refs.length > 0 && }
+
+ );
+}
+
+/** The reader's clone folder, for editor links; kept in this browser only. */
+function CloneFolder({
+ repoId,
+ root,
+ onSave,
+}: {
+ repoId: string;
+ root: string | null;
+ onSave: (root: string | null) => void;
+}) {
+ const [draft, setDraft] = useState(root ?? "");
+ return (
+
+
+ {root ? "Editor links use your clone folder" : "Add editor links: give your clone folder"}
+
+
+
+ );
+}
diff --git a/web/src/routes/map/ChangePanels.tsx b/web/src/routes/map/ChangePanels.tsx
new file mode 100644
index 00000000..6cf7bcd9
--- /dev/null
+++ b/web/src/routes/map/ChangePanels.tsx
@@ -0,0 +1,347 @@
+import { ArrowRight, X } from "lucide-react";
+import type { ReactNode } from "react";
+import { Link } from "react-router";
+import { NotMeasured } from "../../components/cx/badges";
+import { FOCUS, cn } from "../../components/cx/cn";
+import { type PlacedChange, offGridCounts } from "../../components/cx/map-model";
+import { findingPath } from "../../cx/address";
+import { SIMULATION, TYPE, fmt } from "../../cx/meta";
+import type { Batch, Finding, RepoBundle } from "../../cx/types";
+
+const closeCls = cn(
+ "rounded-md p-1 text-muted-foreground hover:bg-muted hover:text-foreground",
+ FOCUS,
+);
+
+/**
+ * Why a stored simulation is not drawn on the grid, with the counts that show it. The grid
+ * counts link lines between production files only (the map's module edges); the
+ * simulation's cells come from its own module link counts.
+ */
+export function OffGridNote({ changes }: { changes: readonly PlacedChange[] }) {
+ const { total, notOnGrid, otherCount } = offGridCounts(changes);
+ const parts: string[] = [];
+ if (otherCount > 0)
+ parts.push(
+ `${fmt(otherCount)} of the ${fmt(total)} changed cells start from a different count than the grid shows`,
+ );
+ if (notOnGrid > 0)
+ parts.push(
+ `${fmt(notOnGrid)} ${notOnGrid === 1 ? "names a module" : "name a module"} that is not on the grid`,
+ );
+ return (
+
+ The grid is not recoloured. It counts only links
+ between production files, while the simulation counted module links on a different basis
+ {parts.length ? `: ${parts.join(", and ")}` : ""}. The Now colours stay; the changed cells are
+ outlined with a dashed line and their counts are listed below.
+
+ );
+}
+
+function Stat({ k, v }: { k: string; v: ReactNode }) {
+ return (
+
+ {k}
+ {v}
+
+ );
+}
+
+/** The stored fix batch, shown with the After view (spec.md §8.5). */
+export function BatchPanel({
+ repo,
+ batch,
+ changes,
+}: {
+ repo: RepoBundle;
+ batch: Batch;
+ changes: readonly PlacedChange[];
+}) {
+ return (
+
+
+
+
+ Simulated fix batch
+
+
+ Every cheap-loop fix whose own simulation succeeded with no new exception, applied
+ together on a copy of the module map. Nothing is applied to the code.
+ {batch.newExceptions.length > 0 &&
+ ` The batch creates ${fmt(batch.newExceptions.length)} new ${batch.newExceptions.length === 1 ? "exception" : "exceptions"}.`}
+
+
+
+
+
+
+
+
+
+
+ {repo.matrixFixed ? (
+
+ The grid is recoloured with the batch’s stored after-counts; the cells it changed
+ have a dashed outline.
+
+ ) : (
+
+ )}
+
+ );
+}
+
+/** "Try the fix" for one finding: its stored simulation on the grid. */
+export function FixPanel({
+ repo,
+ finding,
+ changes,
+ onClose,
+}: {
+ repo: RepoBundle;
+ finding: Finding;
+ changes: readonly PlacedChange[];
+ onClose: () => void;
+}) {
+ const s = finding.simulation;
+ return (
+
+
+
+
+ Trying the fix · #{finding.rank} · {TYPE[finding.type].label}
+
+
+ {finding.title}
+
+ {s && {SIMULATION[s.kind].long} }
+
+
+
+
+
+ {s?.simulated ? (
+ <>
+
+
+ loops
+
+ {s.loopsBefore === null || s.loopsAfter === null ? (
+
+ ) : (
+ `${fmt(s.loopsBefore)} → ${fmt(s.loopsAfter)}`
+ )}
+
+
+
+ links removed
+ {fmt(s.linksRemoved)}
+
+
+ links added
+ {fmt(s.linksAdded)}
+
+
+ new exceptions
+ {fmt(s.newExceptions.length)}
+
+
+ {s.onGrid ? (
+
+ The grid is redrawn with the simulation’s after-counts; the cells it changed
+ have a dashed outline. Nothing is applied to the code.
+
+ ) : (
+
+ )}
+ >
+ ) : (
+
+ This finding has no stored simulation, so the grid shows Now.
+
+ )}
+
+ );
+}
+
+/** The finding whose cells are brought forward on the grid. */
+export function FindingBanner({
+ repo,
+ finding,
+ cellsOnGrid,
+ onTryFix,
+ onClose,
+ trying,
+}: {
+ repo: RepoBundle;
+ finding: Finding;
+ cellsOnGrid: number;
+ onTryFix: () => void;
+ onClose: () => void;
+ trying: boolean;
+}) {
+ const s = finding.simulation;
+ const canTry = !!s?.simulated && s.cellChanges.length > 0;
+ return (
+
+
+
+ Finding #{finding.rank} · {TYPE[finding.type].label}
+
+
+ {finding.title}
+
+
+ {cellsOnGrid > 0
+ ? `${fmt(cellsOnGrid)} ${cellsOnGrid === 1 ? "cell" : "cells"} of this finding ${cellsOnGrid === 1 ? "is" : "are"} brought forward; the rest of the grid is dimmed.`
+ : "This finding has no cell between two modules on the grid."}
+
+
+
+ {canTry ? (
+
+ {trying ? "Showing the fix" : "Try the fix"}
+
+ ) : (
+
+ {s ? SIMULATION[s.kind].short : SIMULATION["not-simulated"].short}
+
+ )}
+
+
+
+
+
+ );
+}
+
+const nameOf = (repo: RepoBundle, id: string, i: number | null) =>
+ i !== null ? repo.modules[i]!.name : id.replace(/^M:/, "");
+
+/** Every stored cell change with the simulation's own counts. */
+export function ChangeList({
+ repo,
+ changes,
+ onPick,
+ title,
+}: {
+ repo: RepoBundle;
+ changes: readonly PlacedChange[];
+ onPick: (cell: [number, number]) => void;
+ title: string;
+}) {
+ return (
+
+
+ {title}{" "}
+ {fmt(changes.length)}
+
+
+
+
+
+
+
+
+
+
+
+ cell
+
+
+ simulation
+
+
+ grid now
+
+
+
+
+ {changes.map((c) => {
+ const on = c.i !== null && c.j !== null;
+ const label = (
+ <>
+ {nameOf(repo, c.src, c.i)} → {" "}
+ {nameOf(repo, c.dst, c.j)}
+ >
+ );
+ return (
+
+
+ {on ? (
+ onPick([c.i!, c.j!])}
+ title={`${c.src} → ${c.dst}`}
+ className={cn(
+ "block max-w-full truncate rounded-sm text-left hover:underline",
+ FOCUS,
+ )}
+ >
+ {label}
+
+ ) : (
+
+ {label}
+
+ )}
+
+
+ {fmt(c.before)} → {fmt(c.after)}
+
+
+ {c.gridCount === null ? "not on the grid" : fmt(c.gridCount)}
+
+
+ );
+ })}
+
+
+
+
+ );
+}
diff --git a/web/src/routes/map/ModulePanel.tsx b/web/src/routes/map/ModulePanel.tsx
new file mode 100644
index 00000000..725265e9
--- /dev/null
+++ b/web/src/routes/map/ModulePanel.tsx
@@ -0,0 +1,164 @@
+import { X } from "lucide-react";
+import { AiBadge, ComputedMark } from "../../components/cx/badges";
+import { FOCUS, cn } from "../../components/cx/cn";
+import { Prose } from "../../components/cx/primitives";
+import { fmt } from "../../cx/meta";
+import type { ModuleInfo, RepoBundle } from "../../cx/types";
+
+const pad = (i: number, n: number) => String(i + 1).padStart(n >= 100 ? 3 : 2, "0");
+
+function Source({ source }: { source: "ai" | "computed" }) {
+ return source === "ai" ? : ;
+}
+
+/**
+ * The numbered module list; picking a module highlights its row and column. Modules that
+ * exist only at the before date are listed only when `beforeOnly` is set.
+ */
+export function ModulePanel({
+ repo,
+ picked,
+ onPick,
+ beforeOnly,
+}: {
+ repo: RepoBundle;
+ picked: number | null;
+ onPick: (index: number | null) => void;
+ beforeOnly: boolean;
+}) {
+ const n = repo.modules.length;
+ const m = picked === null ? null : (repo.modules[picked] ?? null);
+ const listed = repo.modules
+ .map((mm, i) => ({ mm, i }))
+ .filter(({ mm }) => beforeOnly || mm.presentAtEnd);
+ return (
+
+ {m ? (
+ onPick(null)} />
+ ) : (
+
+ Modules
+
+ The numbers match the grid. Pick a module to highlight its row and column.
+
+
+ )}
+
+ {listed.map(({ mm, i }) => (
+
+ onPick(picked === i ? null : i)}
+ aria-pressed={picked === i}
+ title={mm.path}
+ className={cn(
+ "flex w-full flex-col gap-0.5 rounded px-1.5 py-1.5 text-left hover:bg-muted",
+ picked === i && "bg-primary/10",
+ FOCUS,
+ )}
+ >
+
+ {pad(i, n)}
+
+ {mm.name}
+
+ {!mm.presentAtEnd && (
+ before only
+ )}
+
+ {mm.description && (
+
+
+ {mm.description.text}
+
+ )}
+
+
+ ))}
+
+
+ );
+}
+
+function ModuleCard({
+ repo,
+ m,
+ n,
+ onClose,
+}: {
+ repo: RepoBundle;
+ m: ModuleInfo;
+ n: number;
+ onClose: () => void;
+}) {
+ const rows: [string, number | null, number][] = [
+ ["lines", m.loc, 0],
+ ["files", m.files, 0],
+ ["instability", m.instability, 2],
+ ["used by", m.linksIn, 0],
+ ["uses", m.linksOut, 0],
+ ["changes 12m", m.changes12m, 0],
+ ];
+ const stats = rows.filter((row): row is [string, number, number] => row[1] !== null);
+ return (
+
+
+
+ module {pad(m.index, n)}
+
+ {m.name}
+
+ {m.path}
+
+
+
+
+
+ {!m.presentAtEnd && (
+
+ This module exists only at the before date ({repo.beforeDate}). It has no numbers at the
+ end snapshot.
+
+ )}
+ {m.description && (
+
+ )}
+ {stats.length > 0 && (
+ <>
+
+ {stats.map(([k, v, digits]) => (
+
+ {k}
+ {digits ? v.toFixed(digits) : fmt(v)}
+
+ ))}
+
+
+ “Used by” and “uses” count link lines at {repo.snapshotDate}.{" "}
+
+
+ >
+ )}
+
+ );
+}
diff --git a/web/src/routes/overview/BeforeAfter.tsx b/web/src/routes/overview/BeforeAfter.tsx
new file mode 100644
index 00000000..f09b80e7
--- /dev/null
+++ b/web/src/routes/overview/BeforeAfter.tsx
@@ -0,0 +1,64 @@
+import { ArrowRight } from "lucide-react";
+import { Link } from "react-router";
+import { FOCUS, cn } from "../../components/cx/cn";
+import { SectionHead } from "../../components/cx/primitives";
+import { repoPath } from "../../cx/address";
+import type { RepoBundle } from "../../cx/types";
+import { Impact } from "../change/impact";
+
+const MONTHS = [
+ "January",
+ "February",
+ "March",
+ "April",
+ "May",
+ "June",
+ "July",
+ "August",
+ "September",
+ "October",
+ "November",
+ "December",
+];
+
+/** "2025-03-01" as "March 2025"; the date itself when it has no readable month. */
+export function monthYear(date: string): string {
+ const m = /^(\d{4})-(\d{2})/.exec(date);
+ const name = m ? MONTHS[Number(m[2]) - 1] : undefined;
+ return m && name ? `${name} ${m[1]}` : date;
+}
+
+/** The report's view of the bonus question: the impact panel, short form. */
+export function BeforeAfter({ repo, compareDate }: { repo: RepoBundle; compareDate: string }) {
+ return (
+
+
+ Full comparison
+
+ }
+ />
+
+ {repo.adoptionDate ? (
+ <>
+ The team adopted AI coding tools around{" "}
+ {repo.adoptionDate.slice(0, 7)} . Here
+ is how the structure moved from {monthYear(compareDate)} to now.
+ >
+ ) : (
+ <>How the structure moved from {monthYear(compareDate)} to now.>
+ )}
+
+
+
+ );
+}
diff --git a/web/src/routes/overview/FixFirst.tsx b/web/src/routes/overview/FixFirst.tsx
new file mode 100644
index 00000000..ec097d05
--- /dev/null
+++ b/web/src/routes/overview/FixFirst.tsx
@@ -0,0 +1,123 @@
+import { ArrowRight, ArrowUpRight } from "lucide-react";
+import { Link } from "react-router";
+import { AiBadge } from "../../components/cx/badges";
+import { FOCUS, cn } from "../../components/cx/cn";
+import { allFindings } from "../../components/cx/finding-fix";
+import { TREND } from "../../components/cx/finding-row";
+import { SectionHead } from "../../components/cx/primitives";
+import { Sparkline, markIndex } from "../../components/cx/sparkline";
+import { findingPath, repoPath } from "../../cx/address";
+import { TYPE, VERDICT, fmt } from "../../cx/meta";
+import type { Finding, RepoBundle } from "../../cx/types";
+
+/** How many findings the overview lists before linking to all of them. */
+const SHOWN = 5;
+
+const linkCls = cn(
+ "inline-flex items-center gap-1 rounded-sm text-foreground hover:underline",
+ FOCUS,
+);
+
+/** Vermilion is kept for code that goes against a decision; other findings use plain ink. */
+function trendStyle(f: Finding): { className: string; color?: string; line: string } {
+ const t = TREND[f.trend.status];
+ const against = TYPE[f.type].group === "Decision exception";
+ const className =
+ !against && t.cls === "text-accent" ? "text-foreground" : t.cls || "text-muted-foreground";
+ return {
+ className,
+ color: t.color,
+ line: against ? "var(--accent)" : "var(--foreground)",
+ };
+}
+
+/** One finding: rank, the stored headline, why it matters, and where it is heading. */
+function Row({ repoId, f, compareDate }: { repoId: string; f: Finding; compareDate: string }) {
+ const t = TREND[f.trend.status];
+ const ts = trendStyle(f);
+ const series = f.trend.series;
+ return (
+
+
+
+ {f.rank}
+
+
+
+ {f.title}
+
+
+ {TYPE[f.type].label}. {TYPE[f.type].why}
+ {f.judgement && (
+
+
+ {VERDICT[f.judgement.verdict]}
+
+
+
+ )}
+
+
+
+ p.value)}
+ mark={markIndex(
+ series.map((p) => p.date),
+ compareDate,
+ )}
+ width={96}
+ height={24}
+ color={ts.line}
+ label={`Trend for finding ${f.rank}`}
+ />
+
+ {t.label}
+
+
+
+
+
+ );
+}
+
+/** The top findings, ranked. Facts, evidence and the proposed fix are on each finding's page. */
+export function FixFirst({ repo, compareDate }: { repo: RepoBundle; compareDate: string }) {
+ const total = allFindings(repo).length;
+ return (
+
+ 0 && (
+
+ All {fmt(total)} {total === 1 ? "finding" : "findings"}{" "}
+
+
+ )
+ }
+ />
+ {repo.findings.length === 0 ? (
+ No finding was ranked in this run.
+ ) : (
+
+ {repo.findings.slice(0, SHOWN).map((f) => (
+
+ ))}
+
+ )}
+
+ );
+}
diff --git a/web/src/routes/overview/Structure.tsx b/web/src/routes/overview/Structure.tsx
new file mode 100644
index 00000000..f1cd2386
--- /dev/null
+++ b/web/src/routes/overview/Structure.tsx
@@ -0,0 +1,139 @@
+import { AiBadge, ComputedMark } from "../../components/cx/badges";
+import { OverviewMap } from "../../components/cx/overview-map";
+import { SectionHead } from "../../components/cx/primitives";
+import { fmt } from "../../cx/meta";
+import type { ModuleInfo, RepoBundle } from "../../cx/types";
+
+/** How many modules the structure list shows. */
+const MODULES_SHOWN = 8;
+/** How many the report's short list shows. */
+const MODULES_SHORT = 6;
+
+/** The module's number as the Map's axes show it. */
+const pad = (i: number, n: number) => String(i + 1).padStart(n >= 100 ? 3 : 2, "0");
+
+const links = (m: ModuleInfo) => (m.linksIn ?? 0) + (m.linksOut ?? 0);
+
+/** Production modules at the end snapshot that have at least one link, largest first. */
+function mainModules(repo: RepoBundle): ModuleInfo[] {
+ return repo.modules
+ .filter((m) => m.presentAtEnd && m.kind === "production" && links(m) > 0)
+ .sort((a, b) => (b.loc ?? -1) - (a.loc ?? -1) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
+}
+
+function Stat({ value, label }: { value: number | null; label: string }) {
+ if (value === null) return null;
+ return (
+
+ {fmt(value)}
+ {label}
+
+ );
+}
+
+function Caption({ shown, total }: { shown: number; total: number }) {
+ if (total === 0) return <>No production module with links is stored in this run.>;
+ if (shown === total)
+ return (
+ <>
+ {total === 1
+ ? "The one production module with links."
+ : `The ${fmt(total)} production modules with links, largest first.`}
+ >
+ );
+ return (
+ <>
+ The {fmt(shown)} largest of {fmt(total)} production modules with links.
+ >
+ );
+}
+
+/** The main modules beside the small map, so a new reader sees the parts and their links. */
+export function Structure({ repo }: { repo: RepoBundle }) {
+ const all = mainModules(repo);
+ const shown = all.slice(0, MODULES_SHOWN);
+ const n = repo.modules.length;
+ return (
+
+
+
+
+
+ Numbers match the map.{" "}
+
+
+ {shown.length > 0 && (
+
+ {shown.map((m) => (
+
+
+ {pad(m.index, n)}
+
+
+
+ {m.name}
+
+ {m.description && (
+
+ {m.description.source === "ai" ? (
+
+ ) : (
+
+ )}
+ {m.description.text}
+
+ )}
+
+
+
+
+
+
+
+ ))}
+
+ )}
+
+
+
+
+
+
+ );
+}
+
+/** The report's short list: the six largest modules, what each does, and how linked it is. */
+export function MainModules({ repo }: { repo: RepoBundle }) {
+ const all = mainModules(repo);
+ const shown = all.slice(0, MODULES_SHORT);
+ if (shown.length === 0) return null;
+ return (
+
+ {shown.map((m) => (
+
+
+
+ {m.name}
+
+
+ {m.loc !== null ? `${fmt(Math.round(m.loc / 1000))}k lines` : ""}
+
+
+ {m.description && (
+
+ {m.description.source === "ai" && }
+ {m.description.text}
+
+ )}
+
+
+
+
+
+ ))}
+
+ );
+}
diff --git a/web/src/routes/overview/TrustStrip.tsx b/web/src/routes/overview/TrustStrip.tsx
new file mode 100644
index 00000000..1a57debe
--- /dev/null
+++ b/web/src/routes/overview/TrustStrip.tsx
@@ -0,0 +1,140 @@
+import { ArrowRight } from "lucide-react";
+import type { ReactNode } from "react";
+import { Link } from "react-router";
+import { ComputedMark } from "../../components/cx/badges";
+import { FOCUS, cn } from "../../components/cx/cn";
+import { SectionHead } from "../../components/cx/primitives";
+import { repoPath } from "../../cx/address";
+import { fmt } from "../../cx/meta";
+import type { RepoBundle } from "../../cx/types";
+
+/** The stored re-run tests, in the order a reader can follow them. */
+const TESTS: { test: string; label: string }[] = [
+ { test: "identical_rerun", label: "Run again, same input" },
+ { test: "fresh_ai_run", label: "Run again with fresh AI text" },
+ { test: "commits_removed_5pct", label: "5% of commits left out" },
+ { test: "weights_changed_20pct", label: "Ranking weights moved by 20%" },
+ { test: "end_date_minus_1_month", label: "Snapshot one month earlier" },
+];
+
+function Block({
+ title,
+ lead,
+ children,
+}: {
+ title: string;
+ lead: ReactNode;
+ children?: ReactNode;
+}) {
+ return (
+
+ {title}
+ {lead}
+ {children}
+
+ );
+}
+
+/** Robustness and efficiency, the two judging points a reader cannot see in the findings. */
+export function TrustStrip({ repo }: { repo: RepoBundle }) {
+ const byTest = new Map(repo.stability.map((s) => [s.test, s]));
+ const tests = TESTS.flatMap((t) => {
+ const s = byTest.get(t.test);
+ return s ? [{ ...t, kept: Math.round(s.top10 * 10) }] : [];
+ });
+ const rerun = byTest.get("identical_rerun");
+ const files = repo.coverage.reduce((s, c) => s + c.files, 0);
+ const unread = repo.coverage.reduce((s, c) => s + c.unread, 0);
+ const calls = repo.usage.reduce((s, u) => s + u.calls, 0);
+ const cost = repo.usage.reduce((s, u) => s + u.cost, 0);
+ const limits = repo.blindSpots.length;
+
+ return (
+
+
+ How it works
+
+ }
+ />
+
+
+ Run twice, the top 10 stays the same:{" "}
+ {Math.round(rerun.top10 * 10)} of 10 .
+ >
+ ) : (
+ "No re-run was stored for this report."
+ )
+ }
+ >
+ {tests.length > 1 && (
+
+ {tests.map((t) => (
+
+ {t.label}
+
+ {Array.from({ length: 10 }, (_, i) => (
+
+ ))}
+
+ {t.kept} of 10
+
+ ))}
+
+ )}
+
+ How many of the top 10 findings stay in the top 10 under each change.{" "}
+
+
+
+ Finding, counting and ranking use no AI model. AI only reads and writes text.>}
+ >
+
+
+ AI calls for this report
+
+ {repo.usage.length === 0 ? "none" : fmt(calls)}
+
+
+
+ Total AI cost
+ ${cost.toFixed(2)}
+
+ {repo.coverage.length > 0 && (
+
+ Files read
+ {fmt(files)}
+ {fmt(unread)} with unread parts
+
+ )}
+
+ Limits stated openly
+ {fmt(limits)}
+
+
+
+
+
+ );
+}
diff --git a/web/src/routes/size/scale.tsx b/web/src/routes/size/scale.tsx
new file mode 100644
index 00000000..c6b32213
--- /dev/null
+++ b/web/src/routes/size/scale.tsx
@@ -0,0 +1,57 @@
+// The one colour scale of the size screen: cividis for the share of lines that arrived after
+// the comparison date (spec.md §10.5), shown as ten flat steps so no gradient is drawn.
+import { interpolateCividis } from "d3-scale-chromatic";
+import { cn } from "../../components/cx/cn";
+
+const STEPS = 10;
+
+/** The step colour for a share from 0 to 1. */
+export function shareColor(share: number): string {
+ const clamped = Math.max(0, Math.min(1, share));
+ const step = Math.min(STEPS - 1, Math.floor(clamped * STEPS));
+ return interpolateCividis((step + 0.5) / STEPS);
+}
+
+export function Swatch({ share, className }: { share: number | null; className?: string }) {
+ return (
+
+ );
+}
+
+export function ShareLegend({ sponsor, className }: { sponsor: string; className?: string }) {
+ return (
+
+ area: lines of code
+
+ colour: share of lines that arrived after {sponsor}
+
+ 0%
+
+ {Array.from({ length: STEPS }, (_, i) => (
+
+ ))}
+
+ 100%
+
+
+
+ no value (test or generated file)
+
+
+ );
+}
diff --git a/web/src/routes/size/tree.ts b/web/src/routes/size/tree.ts
new file mode 100644
index 00000000..2c206343
--- /dev/null
+++ b/web/src/routes/size/tree.ts
@@ -0,0 +1,168 @@
+// Pure helpers for the size screen: the module -> file tree, the table rows and sort, and the
+// address-bar state. Everything is read from stored sizes; nothing is measured here.
+//
+// Line origin is read for production files only: other files are stored with a share of 0
+// that means "not read", so they are shown as having no value, and the module share (stored
+// over production lines) is multiplied by production lines only.
+import type { FileSize, ModuleInfo } from "../../cx/types";
+
+export interface SizeNode {
+ id: string;
+ label: string;
+ /** Lines of code; for a module, the sum of its files, or its own count with no files. */
+ value: number;
+ share: number | null;
+ children: SizeNode[];
+}
+
+export type Scope = "production" | "all";
+
+const byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
+
+/** The share a file can be coloured by: production files only. */
+export const fileShare = (f: FileSize): number | null =>
+ f.kind === "production" ? f.postMarchShare : null;
+
+/** Modules present at the end snapshot, each with its files in scope, sorted by id. */
+export function buildTree(modules: ModuleInfo[], files: FileSize[] | null, scope: Scope): SizeNode {
+ const byModule = new Map();
+ for (const f of files ?? []) {
+ if (f.loc <= 0 || (scope === "production" && f.kind !== "production")) continue;
+ const list = byModule.get(f.module) ?? [];
+ list.push(f);
+ byModule.set(f.module, list);
+ }
+ const children = modules
+ .filter((m) => m.presentAtEnd)
+ .map((m): SizeNode => {
+ const kids = (byModule.get(m.id) ?? [])
+ .map((f) => ({
+ id: `F:${f.path}`,
+ label: f.path,
+ value: f.loc,
+ share: fileShare(f),
+ children: [],
+ }))
+ .sort((a, b) => byText(a.id, b.id));
+ // Without file nodes the module is drawn whole, from its own stored numbers.
+ const value = files === null ? (m.loc ?? 0) : kids.reduce((s, k) => s + k.value, 0);
+ return { id: m.id, label: m.name, value, share: m.postMarchShare, children: kids };
+ })
+ .filter((m) => m.value > 0)
+ .sort((a, b) => byText(a.id, b.id));
+ return {
+ id: "root",
+ label: "",
+ value: children.reduce((s, c) => s + c.value, 0),
+ share: null,
+ children,
+ };
+}
+
+/** One table row: the module's stored numbers plus two sums over its stored file sizes. */
+export interface SizeRow {
+ m: ModuleInfo;
+ /** Lines in the module's production files; null without file nodes. */
+ prodLoc: number | null;
+ /** Production lines that arrived after the comparison date: production lines × stored share. */
+ afterLines: number | null;
+}
+
+export function sizeRows(modules: ModuleInfo[], files: FileSize[] | null): SizeRow[] {
+ const prod = new Map();
+ if (files) {
+ for (const f of files) {
+ if (f.kind === "production") prod.set(f.module, (prod.get(f.module) ?? 0) + f.loc);
+ }
+ }
+ return modules.map((m) => {
+ const prodLoc = files ? (prod.get(m.id) ?? 0) : null;
+ return {
+ m,
+ prodLoc,
+ afterLines: prodLoc !== null && m.postMarchShare !== null ? prodLoc * m.postMarchShare : null,
+ };
+ });
+}
+
+export const SORT_KEYS = [
+ "name",
+ "kind",
+ "files",
+ "loc",
+ "prodLoc",
+ "linksIn",
+ "linksOut",
+ "changes12m",
+ "postMarchShare",
+ "afterLines",
+] as const;
+export type SortKey = (typeof SORT_KEYS)[number];
+
+function valueOf(r: SizeRow, key: SortKey): number | string | null {
+ switch (key) {
+ case "name":
+ return r.m.name;
+ case "kind":
+ return r.m.kind;
+ case "prodLoc":
+ return r.prodLoc;
+ case "afterLines":
+ return r.afterLines;
+ default:
+ return r.m[key];
+ }
+}
+
+/** A new array sorted by one column. Missing values go last; ties keep module-id order. */
+export function sortRows(rows: SizeRow[], key: SortKey, descending: boolean): SizeRow[] {
+ return [...rows].sort((a, b) => {
+ const va = valueOf(a, key);
+ const vb = valueOf(b, key);
+ if (va === null && vb !== null) return 1;
+ if (vb === null && va !== null) return -1;
+ let diff = 0;
+ if (typeof va === "number" && typeof vb === "number") diff = va - vb;
+ else if (va !== null && vb !== null) diff = byText(String(va), String(vb));
+ if (descending) diff = -diff;
+ return diff !== 0 ? diff : byText(a.m.id, b.m.id);
+ });
+}
+
+export interface SizeState {
+ sort: SortKey;
+ descending: boolean;
+ module: string | null;
+ scope: Scope;
+}
+
+export const DEFAULT_SORT: SortKey = "loc";
+
+const naturalDescending = (key: SortKey) => key !== "name" && key !== "kind";
+
+/** Reads `sort`, `dir`, `module` and `files` from the address; unknown values read as defaults. */
+export function readSizeState(params: URLSearchParams, moduleIds: readonly string[]): SizeState {
+ const s = params.get("sort");
+ const sort = (SORT_KEYS as readonly string[]).includes(s ?? "") ? (s as SortKey) : DEFAULT_SORT;
+ const dir = params.get("dir");
+ const descending = dir === "asc" ? false : dir === "desc" ? true : naturalDescending(sort);
+ const m = params.get("module");
+ return {
+ sort,
+ descending,
+ module: m && moduleIds.includes(m) ? m : null,
+ scope: params.get("files") === "all" ? "all" : "production",
+ };
+}
+
+/** The search parameters for a size state; defaults are left out. */
+export function sizeParams(state: SizeState): URLSearchParams {
+ const out = new URLSearchParams();
+ if (state.scope === "all") out.set("files", "all");
+ if (state.sort !== DEFAULT_SORT) out.set("sort", state.sort);
+ if (state.descending !== naturalDescending(state.sort)) {
+ out.set("dir", state.descending ? "desc" : "asc");
+ }
+ if (state.module) out.set("module", state.module);
+ return out;
+}
diff --git a/web/src/routes/size/treemap.tsx b/web/src/routes/size/treemap.tsx
new file mode 100644
index 00000000..40cdc744
--- /dev/null
+++ b/web/src/routes/size/treemap.tsx
@@ -0,0 +1,162 @@
+// Where the code mass is (spec.md §10.2 screen 6): one rectangle per file, grouped by module,
+// area is lines of code and colour the share of lines that arrived after the comparison date.
+// Drawn on canvas with d3-hierarchy; the positions depend only on the stored sizes.
+import { type HierarchyRectangularNode, hierarchy, treemap } from "d3-hierarchy";
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { fmt, pct } from "../../cx/meta";
+import { shareColor } from "./scale";
+import type { SizeNode } from "./tree";
+
+const HEADER = 18;
+
+function token(name: string, fallback: string): string {
+ if (typeof window === "undefined") return fallback;
+ const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
+ return v || fallback;
+}
+
+const byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
+
+export function SizeTreemap({
+ tree,
+ selected,
+ onModule,
+ sponsor,
+}: {
+ tree: SizeNode;
+ selected: string | null;
+ onModule: (id: string) => void;
+ sponsor: string;
+}) {
+ const wrap = useRef(null);
+ const canvas = useRef(null);
+ const [width, setWidth] = useState(960);
+ const [hover, setHover] = useState<{
+ node: HierarchyRectangularNode;
+ x: number;
+ y: number;
+ } | null>(null);
+ const height = width < 640 ? 420 : 560;
+
+ useLayoutEffect(() => {
+ const el = wrap.current;
+ if (!el || typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(([entry]) => {
+ if (entry) setWidth(Math.max(200, Math.floor(entry.contentRect.width)));
+ });
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, []);
+
+ const root = useMemo(() => {
+ const h = hierarchy(tree, (d) => d.children)
+ .sum((d) => (d.children.length === 0 ? d.value : 0))
+ .sort((a, b) => (b.value ?? 0) - (a.value ?? 0) || byText(a.data.id, b.data.id));
+ return treemap()
+ .size([width, height])
+ .paddingOuter(2)
+ .paddingTop((d) => (d.depth === 1 ? HEADER : 0))
+ .paddingInner(1)
+ .round(true)(h);
+ }, [tree, width, height]);
+
+ const modules = useMemo(() => root.children ?? [], [root]);
+ const leaves = useMemo(() => root.leaves(), [root]);
+
+ useEffect(() => {
+ const el = canvas.current;
+ const ctx = el?.getContext?.("2d");
+ if (!el || !ctx) return;
+ const ratio = window.devicePixelRatio || 1;
+ el.width = width * ratio;
+ el.height = height * ratio;
+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
+ ctx.clearRect(0, 0, width, height);
+ const card = token("--card", "#fafaf7");
+ const fg = token("--foreground", "#14181f");
+ const muted = token("--muted", "#e6e8e2");
+ const border = token("--muted-foreground", "#5a616d");
+
+ for (const leaf of leaves) {
+ const share = leaf.data.share;
+ ctx.fillStyle = share === null ? muted : shareColor(share);
+ ctx.fillRect(leaf.x0, leaf.y0, leaf.x1 - leaf.x0, leaf.y1 - leaf.y0);
+ }
+ ctx.font = "600 11px 'Instrument Sans Variable', system-ui, sans-serif";
+ for (const m of modules) {
+ const w = m.x1 - m.x0;
+ const h = m.y1 - m.y0;
+ if (m.children) {
+ ctx.fillStyle = card;
+ ctx.fillRect(m.x0, m.y0, w, Math.min(HEADER - 1, h));
+ }
+ const isSel = m.data.id === selected;
+ ctx.strokeStyle = isSel ? fg : border;
+ ctx.lineWidth = isSel ? 2.5 : 1;
+ ctx.strokeRect(m.x0 + 0.5, m.y0 + 0.5, w - 1, h - 1);
+ const text = m.data.label;
+ if (m.children && ctx.measureText(text).width + 10 < w) {
+ ctx.fillStyle = fg;
+ ctx.fillText(text, m.x0 + 5, m.y0 + 13);
+ }
+ }
+ }, [leaves, modules, width, height, selected]);
+
+ const nodeAt = (x: number, y: number) =>
+ leaves.find((l) => x >= l.x0 && x < l.x1 && y >= l.y0 && y < l.y1) ??
+ modules.find((m) => x >= m.x0 && x < m.x1 && y >= m.y0 && y < m.y1);
+ const moduleOf = (n: HierarchyRectangularNode) =>
+ n.ancestors().find((a) => a.depth === 1) ?? null;
+ const point = (e: React.MouseEvent) => {
+ const r = e.currentTarget.getBoundingClientRect();
+ return { x: e.clientX - r.left, y: e.clientY - r.top };
+ };
+
+ const hovered = hover?.node;
+ const hoveredModule = hovered ? moduleOf(hovered) : null;
+
+ return (
+
+ {
+ const p = point(e);
+ const node = nodeAt(p.x, p.y);
+ setHover(node ? { node, ...p } : null);
+ }}
+ onMouseLeave={() => setHover(null)}
+ onClick={(e) => {
+ const p = point(e);
+ const node = nodeAt(p.x, p.y);
+ const m = node && moduleOf(node);
+ if (m) onModule(m.data.id);
+ }}
+ />
+ {hovered && hover && (
+
+
+ {hovered.data.label}
+
+ {hoveredModule && hoveredModule !== hovered && (
+ in {hoveredModule.data.label}
+ )}
+
+ {fmt(hovered.value ?? 0)} lines
+ {hovered.data.share !== null && ` · ${pct(hovered.data.share, 0)} after ${sponsor}`}
+
+
+ )}
+
+ );
+}
diff --git a/web/src/routes/trust/ai-use.tsx b/web/src/routes/trust/ai-use.tsx
new file mode 100644
index 00000000..7f3fd05d
--- /dev/null
+++ b/web/src/routes/trust/ai-use.tsx
@@ -0,0 +1,194 @@
+// Where a model is used: the three jobs, the checks a judgement passes before it is shown,
+// and the usage ledger with every logged call, its tokens and its cost.
+import type { ReactNode } from "react";
+import { AiBadge, ComputedMark } from "../../components/cx/badges";
+import { Panel, SectionHead } from "../../components/cx/primitives";
+import { fmt } from "../../cx/meta";
+import type { UsageRow } from "../../cx/types";
+
+/** The three jobs a model does, by stored job letter. */
+export const JOBS: Record = {
+ A: "Read written decisions",
+ B: "Judge an exception",
+ C: "Describe a module",
+};
+
+const JOB_DETAIL: { job: UsageRow["job"]; given: string; returns: string }[] = [
+ {
+ job: "A",
+ given: "One decision source at a time.",
+ returns:
+ "A proposed rule in one of four fixed shapes, or “not checkable”. Each rule is tested by code and reviewed by a person before it can produce a finding.",
+ },
+ {
+ job: "B",
+ given:
+ "One finding at a time: its facts, the strongest links around it, its history and a few numbered code slices.",
+ returns:
+ "A verdict, one checkable claim and one structured fix. The verdict is the majority of three calls.",
+ },
+ {
+ job: "C",
+ given: "The module's public names, its neighbouring modules and its most-changed files.",
+ returns: "Two sentences and three cited responsibilities.",
+ },
+];
+
+const CHECKS = [
+ "The answer ended normally and has the fixed shape.",
+ "The verdict is one allowed for the finding's type.",
+ "Every citation points at lines inside the code it was given.",
+ "Every number equals a stored fact or a cited line number.",
+ "Every code name appears in the cited code, a path or the facts.",
+ "Length and wording stay within fixed limits.",
+];
+
+export const usd = (n: number) => `$${n.toFixed(3)}`;
+
+export function AiUse({ rows }: { rows: UsageRow[] }) {
+ return (
+
+
+
+ Three jobs, each one where reading prose is needed. Text a model wrote carries the{" "}
+ badge; everything else is{" "}
+ .
+
+
+ {JOB_DETAIL.map((j) => (
+
+
+ {j.job} · {JOBS[j.job]}
+
+
+
+ Given: {j.given}
+
+
+ Returns: {j.returns}
+
+
+
+ ))}
+
+
+
+ Before a judgement is shown, it must pass every check
+
+
+ {CHECKS.map((c) => (
+
+
+ {c}
+
+ ))}
+
+
+ A failed check gets one retry, except a wrong number, which is rejected. An answer that
+ still fails is replaced by the computed sentence. Answers are cached, so a re-run with the
+ same inputs returns the same text.
+
+
+
+
+ );
+}
+
+function Usage({ rows }: { rows: UsageRow[] }) {
+ const sorted = [...rows].sort((a, b) =>
+ a.job < b.job ? -1 : a.job > b.job ? 1 : a.model < b.model ? -1 : a.model > b.model ? 1 : 0,
+ );
+ const sum = (k: "calls" | "cached" | "tokensIn" | "tokensOut" | "cachedInputTokens" | "cost") =>
+ rows.reduce((s, u) => s + u[k], 0);
+ const cell = "px-4 py-3 text-right tabular";
+ const head = [
+ "job",
+ "model",
+ "calls",
+ "cached calls",
+ "tokens in",
+ "tokens out",
+ "cached input tokens",
+ "cost (USD)",
+ ];
+ const row = (k: string, cells: ReactNode[], strong = false) => (
+
+ {cells.map((c, i) => (
+
+ {c}
+
+ ))}
+
+ );
+ return (
+
+
+ Every call, logged and priced
+ {rows.length > 0 && (
+
+ {fmt(sum("calls"))} calls · {usd(sum("cost"))} total
+
+ )}
+
+ {rows.length === 0 ? (
+ No AI call is logged in this run.
+ ) : (
+ <>
+
+
+
+
+ {head.map((h, i) => (
+
+ {h}
+
+ ))}
+
+
+
+ {sorted.map((u) =>
+ row(`${u.job}-${u.model}`, [
+
+ {u.job} · {JOBS[u.job]}
+ ,
+ {u.model} ,
+ fmt(u.calls),
+ fmt(u.cached),
+ fmt(u.tokensIn),
+ fmt(u.tokensOut),
+ fmt(u.cachedInputTokens),
+ usd(u.cost),
+ ]),
+ )}
+ {row(
+ "total",
+ [
+ Total ,
+ "",
+ fmt(sum("calls")),
+ fmt(sum("cached")),
+ fmt(sum("tokensIn")),
+ fmt(sum("tokensOut")),
+ fmt(sum("cachedInputTokens")),
+ usd(sum("cost")),
+ ],
+ true,
+ )}
+
+
+
+
+ A job without a row has no call logged in this run's ledger.
+
+ >
+ )}
+
+ );
+}
diff --git a/web/src/routes/trust/ranking.tsx b/web/src/routes/trust/ranking.tsx
new file mode 100644
index 00000000..f793c5fd
--- /dev/null
+++ b/web/src/routes/trust/ranking.tsx
@@ -0,0 +1,48 @@
+// How the rank is computed, with the weights stored with the run.
+import { ComputedMark } from "../../components/cx/badges";
+import { weightOf } from "../../components/cx/finding-fix";
+import { Panel, SectionHead } from "../../components/cx/primitives";
+import type { RepoBundle } from "../../cx/types";
+
+/** One decimal, or a dash when the weight is not stored. */
+const w = (v: number | null) => (v === null ? "–" : v.toFixed(1));
+
+const LETTERS = [
+ ["S", "Size"],
+ ["R", "Reach"],
+ ["P", "Change pressure"],
+ ["A", "Authority"],
+ ["ease", "Ease"],
+] as const;
+
+export function Ranking({ repo }: { repo: RepoBundle }) {
+ return (
+
+ } />
+
+
+
+ impact = A × ({w(weightOf(repo, "S"))}·S + {w(weightOf(repo, "R"))}·R +{" "}
+ {w(weightOf(repo, "P"))}·P)
+
+ priority = impact × ease, rounded to 2 places
+ order: priority, then finding id
+
+
+
+ {LETTERS.map(([k, label]) => (
+
+ {k}
+ {label}
+
+ ))}
+
+
+ The weights are stored with the run; they are a judgement, not a standard. The top 10
+ then holds at most 3 findings of one type and 2 from one module.
+
+
+
+
+ );
+}
diff --git a/web/src/routes/trust/stages.tsx b/web/src/routes/trust/stages.tsx
new file mode 100644
index 00000000..1e9f0f79
--- /dev/null
+++ b/web/src/routes/trust/stages.tsx
@@ -0,0 +1,176 @@
+// How the report was made: the seven stages, the five computed ones apart from the two on
+// top, each with this run's stored numbers where the bundle holds them.
+import type { ReactNode } from "react";
+import { ComputedMark } from "../../components/cx/badges";
+import { Chip, Panel, SectionHead } from "../../components/cx/primitives";
+import { fmt } from "../../cx/meta";
+import type { RepoBundle } from "../../cx/types";
+
+interface Stage {
+ n: number;
+ name: string;
+ does: string;
+ /** Stored numbers for this run, as [value, noun]; an empty list shows none. */
+ numbers: (repo: RepoBundle) => [number, string][];
+ ai?: boolean;
+}
+
+const plural = (n: number, one: string, many: string) => (n === 1 ? one : many);
+
+/** Numbers that are present in the bundle; a list that is empty in this run shows nothing. */
+const when = (ok: boolean, value: number, noun: string): [number, string][] =>
+ ok ? [[value, noun]] : [];
+
+const COMPUTED: Stage[] = [
+ {
+ n: 1,
+ name: "Repository",
+ does: "Reads the full history of the default branch with renames followed, flags bot, oversized and restructuring commits without deleting them, notes explicit AI markers, and fixes each dated snapshot to a commit.",
+ numbers: (r) =>
+ when(
+ r.snapshots.length > 0,
+ r.snapshots.length,
+ plural(r.snapshots.length, "snapshot", "snapshots"),
+ ),
+ },
+ {
+ n: 2,
+ name: "Parse",
+ does: "Reads each file with an off-the-shelf grammar chosen by its extension, then links files by import paths and by names shared within a folder. No code is written per language.",
+ numbers: (r) => {
+ const files = r.coverage.reduce((s, c) => s + c.files, 0);
+ return [
+ ...when(r.coverage.length > 0, files, "files read"),
+ ...when(
+ r.coverage.length > 0,
+ r.coverage.length,
+ plural(r.coverage.length, "language", "languages"),
+ ),
+ ];
+ },
+ },
+ {
+ n: 3,
+ name: "Model",
+ does: "Builds one nested map per snapshot, from modules down to functions, with names that stay the same across dates so two snapshots can be compared. Modules come from build units or folders.",
+ numbers: (r) => {
+ const now = r.modules.filter((m) => m.presentAtEnd).length;
+ return when(now > 0, now, plural(now, "module", "modules"));
+ },
+ },
+ {
+ n: 4,
+ name: "Visualize",
+ does: "Shows the map as this static page: a grid of modules, close-ups of single findings and the code behind each claim. It reads stored files only and never calls a model.",
+ numbers: () => [],
+ },
+ {
+ n: 5,
+ name: "Analyze",
+ does: "Checks each decision against the map at every snapshot, finds pressure points from links and change history, and measures the project yardsticks and what changed between dates.",
+ numbers: (r) =>
+ when(
+ r.decisions.length > 0,
+ r.decisions.length,
+ plural(r.decisions.length, "decision checked", "decisions checked"),
+ ),
+ },
+];
+
+const ON_TOP: Stage[] = [
+ {
+ n: 6,
+ name: "LLM Judge",
+ does: "A model reads written decisions into proposed rules, judges whether an exception looks deliberate, and describes modules. It never detects, counts or ranks.",
+ numbers: (r) => {
+ const calls = r.usage.reduce((s, u) => s + u.calls, 0);
+ return when(r.usage.length > 0, calls, plural(calls, "AI call", "AI calls"));
+ },
+ ai: true,
+ },
+ {
+ n: 7,
+ name: "Explain",
+ does: "Orders findings by fixed arithmetic and writes this report. Text from the model appears beside a finding with its badge and does not change its place.",
+ numbers: (r) => {
+ const ranked = r.findings.length + r.supporting.length;
+ return when(ranked > 0, ranked, plural(ranked, "finding ranked", "findings ranked"));
+ },
+ },
+];
+
+function StageRow({ repo, s }: { repo: RepoBundle; s: Stage }) {
+ const numbers = s.numbers(repo);
+ return (
+
+ {s.n}
+
+ {s.name}
+ {s.ai ? uses a model : null}
+
+
+ {s.does}
+
+ {numbers.length > 0 && (
+
+ {numbers.map(([v, noun]) => (
+
+ {noun}
+ {fmt(v)}
+
+ ))}
+
+ )}
+
+ );
+}
+
+function Group({
+ repo,
+ title,
+ note,
+ stages,
+}: {
+ repo: RepoBundle;
+ title: string;
+ note: ReactNode;
+ stages: Stage[];
+}) {
+ return (
+
+
+ {title}
+ {note}
+
+
+ {stages.map((s) => (
+
+ ))}
+
+
+ );
+}
+
+export function Stages({ repo }: { repo: RepoBundle }) {
+ return (
+
+
+
+ no AI model
+ >
+ }
+ stages={COMPUTED}
+ />
+
+
+ );
+}
diff --git a/web/src/screens.ts b/web/src/screens.ts
deleted file mode 100644
index 72129822..00000000
--- a/web/src/screens.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-// The screens of spec.md §10.2, in order, plus the report of §11.4. The path is part of
-// every permanent link, so renaming one breaks links people have already shared.
-import type { ComponentType } from "react";
-import type { Bundle } from "./data/bundle";
-import { BeforeAfter } from "./screens/BeforeAfter";
-import { CloseUp } from "./screens/CloseUp";
-import { CodePane } from "./screens/CodePane";
-import { Decisions } from "./screens/Decisions";
-import { Grid } from "./screens/Grid";
-import { Report } from "./screens/Report";
-import { SizeMap } from "./screens/SizeMap";
-
-export interface ScreenInfo {
- path: string;
- label: string;
- spec: string;
- shows: string;
- /** Every screen takes the whole bundle and nothing else; the rest is in the address. */
- component: ComponentType<{ bundle: Bundle }>;
-}
-
-// The screen files import `screenInfo` from here and this file imports them, so a screen
-// may read SCREENS only while rendering, never when its module loads.
-export const SCREENS: ScreenInfo[] = [
- {
- path: "decisions",
- label: "Decisions",
- spec: "§10.2 screen 1",
- shows:
- "Each decision with its source, status and exception count; below it, the ranked exceptions to fix first.",
- component: Decisions,
- },
- {
- path: "grid",
- label: "Structure grid",
- spec: "§10.2 screen 2",
- shows:
- "Modules down the side and across the top, ordered so normal dependencies fall on one side. Cells against the grain stand out. Clicking a cell lists the links behind it.",
- component: Grid,
- },
- {
- path: "close-up",
- label: "Close-up",
- spec: "§10.2 screen 3",
- shows: "Boxes and arrows for only the modules in one finding.",
- component: CloseUp,
- },
- {
- path: "code",
- label: "Code",
- spec: "§10.2 screen 4",
- shows:
- "The file with the evidence lines highlighted, fact chips, and links to the host and to the editor.",
- component: CodePane,
- },
- {
- path: "before-after",
- label: "Before and after",
- spec: "§10.2 screen 5",
- shows: "A switch on the same layout; each change labelled planned or unplanned.",
- component: BeforeAfter,
- },
- {
- path: "size",
- label: "Size map and table",
- spec: "§10.2 screen 6",
- shows: "Where the code mass is, where post-March-2025 code landed, and sortable numbers.",
- component: SizeMap,
- },
- {
- path: "report",
- label: "Report",
- spec: "§11.4",
- shows:
- "The project yardsticks and ranking weights, the batch simulation, what was read and what was not, the stability table and the AI usage ledger.",
- component: Report,
- },
-];
-
-/** The entry for one screen path. Call it while rendering, not at module load. */
-export function screenInfo(path: string): ScreenInfo {
- const screen = SCREENS.find((candidate) => candidate.path === path);
- if (!screen) throw new Error(`No screen has the path "${path}"`);
- return screen;
-}
diff --git a/web/src/screens/BeforeAfter.tsx b/web/src/screens/BeforeAfter.tsx
deleted file mode 100644
index a99f5c27..00000000
--- a/web/src/screens/BeforeAfter.tsx
+++ /dev/null
@@ -1,145 +0,0 @@
-// Screen 5, before and after (spec.md §10.2, §12): the same grid at two dates, what
-// changed and whether it was planned, and each decision tracked across every snapshot.
-import "./beforeafter/beforeafter.css";
-import { useMemo } from "react";
-import { formatDate } from "../components/Shell";
-import { type Bundle, sponsorDate } from "../data/bundle";
-import { useSetView, useView } from "../data/view";
-import { Changes } from "./beforeafter/Changes";
-import {
- type Side,
- cellsAt,
- changedCells,
- changedFrom,
- yardstickLabel,
- yardstickValue,
-} from "./beforeafter/compare";
-import { DecisionSeries, SeriesKey, YardstickSeriesList } from "./beforeafter/DecisionSeries";
-import { Switch } from "./beforeafter/Switch";
-import { MatrixCanvas } from "./grid/MatrixCanvas";
-
-export function BeforeAfter({ bundle }: { bundle: Bundle }) {
- const view = useView();
- const setView = useSetView();
- const file = bundle.beforeAfter;
- const side: Side = view.snapshot === file.before.date ? "before" : "after";
- const date = side === "before" ? file.before.date : file.after.date;
- const sponsor = sponsorDate(bundle.index);
-
- const labels = useMemo(() => {
- const out: Record = {};
- for (const node of bundle.map.nodes) if (node.level === "module") out[node.id] = node.path;
- // A module that existed only at the earlier date has no node in today's map.
- for (const id of file.module_order) out[id] ??= id.replace(/^M:/, "");
- return out;
- }, [bundle.map.nodes, file.module_order]);
-
- const changes = useMemo(() => changedCells(file), [file]);
- const cells = useMemo(() => cellsAt(file, side), [file, side]);
- const changed = useMemo(() => changedFrom(changes, side), [changes, side]);
- const order = useMemo(
- () => new Map(bundle.index.snapshots.map((s, i) => [s.sha, i])),
- [bundle.index.snapshots],
- );
- const figures = file.yardsticks.flatMap((y) => {
- const point = y.series.find((p) => p.snapshot_date === date);
- return point ? [{ name: y.name, value: point.value }] : [];
- });
- const linksAdded = file.cells.filter((c) => c.before === 0 && c.after > 0).length;
- const linksRemoved = file.cells.filter((c) => c.before > 0 && c.after === 0).length;
-
- return (
-
-
-
-
- {figures.map((f) => (
-
- {yardstickLabel(f.name)}
- {yardstickValue(f.name, f.value)}
-
- ))}
-
- Module links added since {formatDate(file.before.date)}
- {linksAdded}
-
-
- Module links removed
- {linksRemoved}
-
-
-
-
-
-
-
-
-
- Links, few to many
-
-
-
- Against the grain
-
-
-
- Count differs between the dates
-
-
-
- Absent here, present at the other date
-
-
-
-
-
-
- What changed, and was it planned
-
-
-
- A change with no restructuring commit, decision document or stated goal behind it is
- labelled "no stated intent". It is never called anything worse by default.
-
-
-
-
-
-
- Each decision over time
-
-
-
- The project yardsticks
-
-
-
- );
-}
diff --git a/web/src/screens/CloseUp.tsx b/web/src/screens/CloseUp.tsx
deleted file mode 100644
index 946516a0..00000000
--- a/web/src/screens/CloseUp.tsx
+++ /dev/null
@@ -1,197 +0,0 @@
-// Screen 3, the close-up (spec.md §10.2): only the modules of one finding and the links
-// between them, at positions computed when the bundle was built.
-import "./closeup/closeup.css";
-import { useMemo, useState } from "react";
-import { Link } from "react-router";
-import type { Bundle } from "../data/bundle";
-import { useSetView, useView, viewLink } from "../data/view";
-import { type GraphEdge, type GraphNode, Graph } from "./closeup/Graph";
-import { closeUpEdges, closeUpModules } from "./closeup/select";
-import { ModuleText } from "./grid/CellLinks";
-import { againstGrain, cellKey, findingModules, splitCellKey } from "./grid/cells";
-
-export function CloseUp({ bundle }: { bundle: Bundle }) {
- const view = useView();
- const setView = useSetView();
- const { map, index } = bundle;
- const repoId = index.repo_id;
- const order = map.module_order;
- const finding = bundle.findings.findings.find((f) => f.id === view.finding);
- const [selectedNode, setSelectedNode] = useState();
-
- const labels = useMemo(() => {
- const out: Record = {};
- for (const node of map.nodes) if (node.level === "module") out[node.id] = node.path;
- return out;
- }, [map.nodes]);
- const descriptions = useMemo(
- () => new Map(map.descriptions.map((d) => [d.node_id, d])),
- [map.descriptions],
- );
-
- const graph = useMemo(() => {
- if (!finding) return null;
- const layout = bundle.layouts.layouts.find((l) => l.finding_id === finding.id);
- const modules = layout?.positions.length
- ? layout.positions.map((p) => p.node_id)
- : closeUpModules(finding, map.nodes, map.edges, order);
- const at = new Map(layout?.positions.map((p) => [p.node_id, p]) ?? []);
- const primary = findingModules(finding, map.nodes);
- const nodes: GraphNode[] = modules.map((id, i) => ({
- id,
- label: labels[id] ?? id.replace(/^M:/, ""),
- // A module the build did not place falls back to a fixed row, never a random spot.
- x: at.get(id)?.x ?? i * 200,
- y: at.get(id)?.y ?? 0,
- primary: primary.has(id),
- }));
- const edges: GraphEdge[] = closeUpEdges(modules, order, map.edges)
- .map((e) => ({
- id: cellKey(e.src, e.dst),
- src: e.src,
- dst: e.dst,
- count: e.count,
- against: againstGrain(order, e.src, e.dst),
- }))
- .sort(
- (a, b) =>
- Number(b.against) - Number(a.against) || b.count - a.count || a.id.localeCompare(b.id),
- );
- return { nodes, edges, placed: Boolean(layout) };
- }, [finding, bundle.layouts, map.nodes, map.edges, order, labels]);
-
- if (!finding || !graph) {
- const top = bundle.findings.findings.slice(0, 10);
- return (
-
- Close-up
-
- {view.finding
- ? "That finding is not in this repository's report. Choose one below."
- : "A close-up draws only the modules of one finding and the links between them. Choose a finding."}
-
-
- {top.map((f) => (
-
-
- {f.priority.rank}
- {f.title}
-
-
- ))}
-
-
- );
- }
-
- const cell = view.cell ? splitCellKey(view.cell) : null;
- const edge = cell ? graph.edges.find((e) => e.src === cell[0] && e.dst === cell[1]) : undefined;
- const name = (id: string) => labels[id] ?? id;
-
- return (
-
- Close-up
-
- Finding {finding.priority.rank}
- {finding.title}
-
-
- Back to the finding
-
-
- Show on grid
-
-
-
-
-
-
- {
- setSelectedNode(undefined);
- setView({ cell: e.id });
- }}
- onNode={(id) => setSelectedNode(id)}
- />
-
- Only the modules of this finding and their strongest neighbours are drawn. Modules of
- the finding have an ink border; links against the grain are vermilion. Positions were
- computed when the bundle was built, so the picture is the same on every visit.
-
-
-
-
- {selectedNode && (
-
- {name(selectedNode)}
-
-
- )}
- {!selectedNode && edge && (
-
-
- {name(edge.src)} uses {name(edge.dst)}
-
-
-
- {edge.count} {edge.count === 1 ? "link" : "links"}
-
- {edge.against ? "Against the grain" : "With the grain"}
-
-
- See the lines on the grid
-
-
- )}
- {!selectedNode && !edge && (
-
- Select an arrow to see its links, or a box to read what the module is for.
-
- )}
-
- Links in this close-up
- {graph.edges.length === 0 ? (
- No links between these modules.
- ) : (
-
- {graph.edges.map((e) => (
-
- {
- setSelectedNode(undefined);
- setView({ cell: e.id });
- }}
- >
-
- {name(e.src)} uses {name(e.dst)}
-
- {e.count}
-
-
- ))}
-
- )}
-
-
-
- );
-}
diff --git a/web/src/screens/CodePane.tsx b/web/src/screens/CodePane.tsx
deleted file mode 100644
index fb00c0aa..00000000
--- a/web/src/screens/CodePane.tsx
+++ /dev/null
@@ -1,291 +0,0 @@
-// Screen 4, the code pane (spec.md §10.2): the file with the evidence lines highlighted,
-// fact chips, and links to the host and to the editor.
-import "./code/code.css";
-import { type FormEvent, useEffect, useMemo, useState } from "react";
-import { Link } from "react-router";
-import { Badge } from "../components/Badge";
-import type { CodeFile, Evidence } from "../contracts/generated";
-import { type Bundle, loadCode } from "../data/bundle";
-import { useView, viewLink } from "../data/view";
-import { factLabel } from "./decisions/words";
-import { Highlighted, type LineMark } from "./code/Highlighted";
-import { atOf, editorLink, hostLink, parseAt } from "./code/links";
-
-type Loaded =
- { state: "loading" } | { state: "ready"; code: CodeFile } | { state: "failed"; why: string };
-
-const rootKey = (repoId: string) => `codexray.root.${repoId}`;
-
-function readRoot(repoId: string): string {
- try {
- return localStorage.getItem(rootKey(repoId)) ?? "";
- } catch {
- return "";
- }
-}
-
-function lineEvidence(evidence: Evidence[]): Evidence[] {
- return evidence.filter(
- (e) => e.kind === "lines" && e.blob_sha && e.start_line !== null && e.end_line !== null,
- );
-}
-
-export function CodePane({ bundle }: { bundle: Bundle }) {
- const view = useView();
- const { index } = bundle;
- const repoId = index.repo_id;
- const finding = bundle.findings.findings.find((f) => f.id === view.finding);
- const cited = finding ? lineEvidence(finding.evidence) : [];
-
- // Without a range in the address, a finding opens at its first cited lines.
- const first = cited[0];
- const at =
- view.at ?? (first ? atOf(first.blob_sha!, first.start_line!, first.end_line!) : undefined);
- const range = at ? parseAt(at) : null;
-
- const [loaded, setLoaded] = useState({ state: "loading" });
- useEffect(() => {
- if (!range) return;
- let current = true;
- setLoaded({ state: "loading" });
- loadCode(bundle, range.blobSha).then(
- (code) => current && setLoaded({ state: "ready", code }),
- (error: unknown) => current && setLoaded({ state: "failed", why: String(error) }),
- );
- return () => {
- current = false;
- };
- }, [bundle, range?.blobSha]);
-
- const marks = useMemo(() => {
- const out = new Map();
- if (!range) return out;
- const mark = (start: number, end: number, role: string | undefined, focus: boolean) => {
- const kind: LineMark["kind"] = role && /^offending/i.test(role) ? "against" : "evidence";
- for (let line = start; line <= end; line++) {
- if (out.has(line) && !focus) continue;
- out.set(line, { kind, role: line === start ? role : undefined, focus });
- }
- };
- // Other cited ranges of the same finding in this file, then the addressed range on top.
- for (const e of cited) {
- if (e.blob_sha === range.blobSha) mark(e.start_line!, e.end_line!, e.role, false);
- }
- const own = cited.find(
- (e) =>
- e.blob_sha === range.blobSha && e.start_line === range.start && e.end_line === range.end,
- );
- mark(range.start, range.end, own?.role, true);
- return out;
- }, [range?.blobSha, range?.start, range?.end, cited]);
-
- if (!range) {
- return (
-
- Code
-
- No lines selected
-
- {at
- ? `The address names "${at}", which is not a line range.`
- : "Open a finding's evidence or a cell's lines to see the code behind them."}
-
-
-
- Go to the decisions
-
-
-
-
- );
- }
-
- const code = loaded.state === "ready" ? loaded.code : null;
- const path = code?.path ?? cited.find((e) => e.blob_sha === range.blobSha)?.path ?? "";
- const host = code
- ? hostLink(index.host_url, index.end_sha, code.path, range.start, range.end)
- : null;
- const lines =
- range.start === range.end ? `line ${range.start}` : `lines ${range.start} to ${range.end}`;
-
- return (
-
-
-
- Decisions
-
- {view.finding && (
-
- Grid
-
- )}
-
-
-
-
-
-
- {loaded.state === "failed" && (
-
- This file could not be loaded
- {loaded.why}
-
- )}
- {loaded.state === "loading" && Loading the file… }
- {code && }
- {code && (
-
-
- Every cited file and line exists at the pinned commit. Lines are counted from 1.
-
- )}
-
-
- {finding && (
-
- )}
-
-
- );
-}
-
-/** The editor link needs the reader's own clone, so the folder is asked for once. */
-function EditorLink({ repoId, path, line }: { repoId: string; path: string; line: number }) {
- const [root, setRoot] = useState(() => readRoot(repoId));
- const [editing, setEditing] = useState(false);
- const [draft, setDraft] = useState(root);
-
- const save = (event: FormEvent) => {
- event.preventDefault();
- const value = draft.trim();
- try {
- if (value) localStorage.setItem(rootKey(repoId), value);
- else localStorage.removeItem(rootKey(repoId));
- } catch {
- // Storage can be blocked; the link still works for this visit.
- }
- setRoot(value);
- setEditing(false);
- };
-
- if (root && !editing) {
- return (
-
-
- Open in editor
-
-
-
-
- {
- setDraft(root);
- setEditing(true);
- }}
- title={root}
- >
- Change folder
-
-
- );
- }
-
- return (
-
- );
-}
diff --git a/web/src/screens/Decisions.tsx b/web/src/screens/Decisions.tsx
deleted file mode 100644
index e2c5a2dc..00000000
--- a/web/src/screens/Decisions.tsx
+++ /dev/null
@@ -1,170 +0,0 @@
-// Screen 1, the opening screen (spec.md §10.2): the verdict, the decisions with their
-// status, and the ranked exceptions to fix first.
-import "./decisions/decisions.css";
-import { Link, useSearchParams } from "react-router";
-import { formatDate } from "../components/Shell";
-import { STATUSES, StatusGlyph } from "../components/Status";
-import type { Decision, DecisionCheck } from "../contracts/generated";
-import { type Bundle, sponsorDate } from "../data/bundle";
-import { useView, viewLink } from "../data/view";
-import { DecisionsTable, Healthy } from "./decisions/DecisionsTable";
-import { FixFirst } from "./decisions/FixFirst";
-import { TYPE_LABEL } from "./decisions/words";
-import { Yardsticks } from "./decisions/Yardsticks";
-
-export function verdictSentence(decisions: Decision[], checksAtEnd: DecisionCheck[]): string {
- const checkable = decisions.filter((decision) => decision.shape !== null).length;
- const holding = checksAtEnd.filter((check) => check.status === "holding").length;
- if (checkable === 0) return "No checkable decisions were found.";
- return `${holding} of ${checkable} checkable decisions ${holding === 1 ? "is" : "are"} holding.`;
-}
-
-export function Decisions({ bundle }: { bundle: Bundle }) {
- const [params, setParams] = useSearchParams();
- const view = useView();
- const aiOff = view.ai === "off";
- const selectedId = params.get("finding");
-
- const { index } = bundle;
- const { decisions, checks } = bundle.decisions;
- const order = new Map(index.snapshots.map((snapshot, i) => [snapshot.sha, i]));
- const atEnd = new Map(
- checks
- .filter((check) => check.snapshot_sha === index.end_sha)
- .map((check) => [check.decision_id, check]),
- );
- const series = new Map();
- for (const check of [...checks].sort(
- (a, b) => (order.get(a.snapshot_sha) ?? 0) - (order.get(b.snapshot_sha) ?? 0),
- )) {
- series.set(check.decision_id, [...(series.get(check.decision_id) ?? []), check]);
- }
- const marks = index.snapshots.filter((s) => s.role === "sponsor_date").map((s) => s.date);
- const endDate = index.snapshots.find((s) => s.sha === index.end_sha)?.date;
- const findings = bundle.findings.findings;
- const notCheckable = decisions.filter((d) => d.shape === null).length;
-
- const select = (id: string | null) =>
- setParams(
- (previous) => {
- const next = new URLSearchParams(previous);
- if (id) next.set("finding", id);
- else next.delete("finding");
- return next;
- },
- { replace: true },
- );
-
- const top = findings[0];
- const openTop = () => {
- if (!top) return;
- select(top.id);
- // Wait for the row to open, then bring it into view and give it keyboard focus.
- requestAnimationFrame(() => {
- const row = [...document.querySelectorAll("[data-finding]")].find(
- (element) => element.dataset.finding === top.id,
- );
- row?.scrollIntoView?.({ behavior: "smooth", block: "start" });
- row?.focus({ preventScroll: true });
- });
- };
-
- return (
-
-
-
- {verdictSentence(decisions, [...atEnd.values()])}
-
- {index.repo} at commit{" "}
- {index.end_sha.slice(0, 7)}
- {endDate && <>, {formatDate(endDate)}>}. {decisions.length} decisions found,{" "}
- {decisions.length - notCheckable} of them checkable by machine.
-
-
- {STATUSES.map((status) => {
- const count = [...atEnd.values()].filter((c) => c.status === status.key).length;
- return (
-
-
-
- {status.label}
-
- {count}
-
- );
- })}
- {notCheckable > 0 && (
-
- Not machine-checkable
- {notCheckable}
-
- )}
-
-
- {top && (
-
-
- Open the top exception
-
-
-
-
-
- Rank 1
- {TYPE_LABEL[top.type]}, priority {top.priority.score.toFixed(2)}
-
-
- )}
-
-
-
-
-
-
- Decisions
-
-
- {marks.length > 0 && (
-
- The dashed line in each chart marks {formatDate(marks[0]!)}, the date the before and
- after comparison uses.
-
- )}
-
-
-
-
-
- Fix first
-
-
- {findings.length} {findings.length === 1 ? "finding" : "findings"}, ranked by priority
-
-
- {bundle.report.batch_simulation && (
-
-
- Applying all {bundle.report.batch_simulation.fixes_applied} cheap-loop fixes: loops{" "}
- {bundle.report.batch_simulation.loops_before} to{" "}
- {bundle.report.batch_simulation.loops_after}
-
-
- See it on the grid
-
-
- )}
-
-
-
-
-
- );
-}
diff --git a/web/src/screens/Grid.tsx b/web/src/screens/Grid.tsx
deleted file mode 100644
index 8f2eb85d..00000000
--- a/web/src/screens/Grid.tsx
+++ /dev/null
@@ -1,211 +0,0 @@
-// Screen 2, the structure grid (spec.md §10.2): modules by modules, ordered so normal
-// dependencies fall above the diagonal; anything below it points against the grain.
-import "./grid/grid.css";
-import { useMemo } from "react";
-import { Link } from "react-router";
-import type { Bundle } from "../data/bundle";
-import { useSetView, useView, viewLink } from "../data/view";
-import {
- againstGrain,
- cellKey,
- findingCells,
- findingModules,
- moduleEdges,
- splitCellKey,
-} from "./grid/cells";
-import { applyChanges, changeMap } from "./grid/applyFix";
-import { CellLinks, ModuleText } from "./grid/CellLinks";
-import { FixPanel } from "./grid/FixPanel";
-import { MatrixCanvas } from "./grid/MatrixCanvas";
-
-export function Grid({ bundle }: { bundle: Bundle }) {
- const view = useView();
- const setView = useSetView();
- const { map, index } = bundle;
- const order = map.module_order;
-
- const edges = useMemo(() => moduleEdges(order, map.edges), [order, map.edges]);
- const byKey = useMemo(() => new Map(edges.map((e) => [cellKey(e.src, e.dst), e])), [edges]);
- const labels = useMemo(() => {
- const out: Record = {};
- for (const node of map.nodes) if (node.level === "module") out[node.id] = node.path;
- return out;
- }, [map.nodes]);
- const descriptions = useMemo(
- () => new Map(map.descriptions.map((d) => [d.node_id, d])),
- [map.descriptions],
- );
- const cells = useMemo(
- () => edges.map((e) => ({ src: e.src, dst: e.dst, count: e.count })),
- [edges],
- );
-
- const finding = bundle.findings.findings.find((f) => f.id === view.finding);
- const highlight = useMemo(
- () => (finding ? findingCells(finding, map.nodes, edges) : undefined),
- [finding, map.nodes, edges],
- );
- const emphasis = useMemo(
- () => (finding ? findingModules(finding, map.nodes) : undefined),
- [finding, map.nodes],
- );
-
- // A simulated fix from the address: the open finding's ("one") or the batch ("all").
- const batch = bundle.report.batch_simulation;
- const changes = useMemo(() => {
- if (view.fix === "one" && finding?.simulation?.simulated)
- return finding.simulation.cell_changes;
- if (view.fix === "all" && batch) return batch.cell_changes;
- return [];
- }, [view.fix, finding, batch]);
- const shown = useMemo(() => applyChanges(cells, changes), [cells, changes]);
- const changed = useMemo(() => (changes.length > 0 ? changeMap(changes) : undefined), [changes]);
-
- const selected = view.cell ? splitCellKey(view.cell) : null;
- const validSelection = selected && labels[selected[0]] && labels[selected[1]] ? selected : null;
-
- const against = shown
- .filter((c) => againstGrain(order, c.src, c.dst))
- .sort(
- (a, b) => b.count - a.count || cellKey(a.src, a.dst).localeCompare(cellKey(b.src, b.dst)),
- );
- const name = (id: string) => labels[id] ?? id;
- const repoId = index.repo_id;
-
- return (
-
-
-
- {finding && (
-
- Finding {finding.priority.rank}
- {finding.title}
- {highlight && highlight.size === 0 && (
- It sits inside one module, so no cell is outlined.
- )}
-
-
- Back to the finding
-
- setView({ finding: undefined })}
- >
- Clear
-
-
-
- )}
-
- setView({ fix })} />
-
-
-
- setView({ cell: key })}
- labelTip={(id) => }
- />
-
-
-
-
- {validSelection && changed?.has(cellKey(validSelection[0], validSelection[1])) && (
-
- In the simulated fix this cell goes from{" "}
- {changed.get(cellKey(validSelection[0], validSelection[1]))!.before} to{" "}
- {changed.get(cellKey(validSelection[0], validSelection[1]))!.after} links.
-
- )}
- {validSelection ? (
-
- ) : (
-
- Select a cell to list the lines behind it, or a module name to read what it is for.
-
- )}
-
-
-
- Against the grain {against.length}
-
- {against.length === 0 ? (
- Every link between modules points with the grain.
- ) : (
-
- {against.map((edge) => {
- const key = cellKey(edge.src, edge.dst);
- const on = view.cell === key;
- return (
-
- setView({ cell: key })}
- >
-
- {name(edge.src)} uses {name(edge.dst)}
-
- {edge.count}
-
-
- );
- })}
-
- )}
-
-
-
-
- );
-}
-
-function Legend() {
- return (
-
-
-
- Links, few to many
-
-
-
- Against the grain
-
-
-
- Cells of the open finding
-
-
-
- No links
-
-
- );
-}
diff --git a/web/src/screens/Placeholder.tsx b/web/src/screens/Placeholder.tsx
deleted file mode 100644
index f31f3047..00000000
--- a/web/src/screens/Placeholder.tsx
+++ /dev/null
@@ -1,12 +0,0 @@
-import type { ScreenInfo } from "../screens";
-
-/** Stands in for a screen that has not been built. Replace it in App.tsx when it is. */
-export function Placeholder({ screen }: { screen: ScreenInfo }) {
- return (
-
- {screen.label}
- Not built yet. spec.md {screen.spec}.
- {screen.shows}
-
- );
-}
diff --git a/web/src/screens/Report.tsx b/web/src/screens/Report.tsx
deleted file mode 100644
index 267e7cca..00000000
--- a/web/src/screens/Report.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-// The written report (spec.md §11.4): what the tool measured, what it could not see, how
-// stable its ranking is, and what the AI did. It prints as the report.
-import "./report/report.css";
-import { formatDate } from "../components/Shell";
-import type { Bundle } from "../data/bundle";
-import {
- Coverage,
- Healthy,
- Hotspots,
- Section,
- Stability,
- Usage,
- Yardsticks,
-} from "./report/Sections";
-
-export function Report({ bundle }: { bundle: Bundle }) {
- const { report, index, decisions } = bundle;
- const atEnd = new Map(
- decisions.checks.filter((c) => c.snapshot_sha === index.end_sha).map((c) => [c.decision_id, c]),
- );
- const date = index.snapshots.find((s) => s.sha === index.end_sha)?.date;
-
- return (
-
-
- Report
-
- {index.repo} at commit {index.end_sha.slice(0, 7)}
- {date && <>, {formatDate(date)}>}. Every figure on this page is computed by ordinary
- code from the repository.
-
- window.print()}>
- Print the report
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- );
-}
diff --git a/web/src/screens/SizeMap.tsx b/web/src/screens/SizeMap.tsx
deleted file mode 100644
index b6e61e05..00000000
--- a/web/src/screens/SizeMap.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-// Screen 6, size map and table (spec.md §10.2): where the code mass is, where code changed
-// after March 2025 landed, and the numbers behind both.
-import "./size/size.css";
-import { useMemo, useState } from "react";
-import { type Bundle, sponsorDate } from "../data/bundle";
-import { StatsTable } from "./size/StatsTable";
-import { Treemap, TreemapLegend } from "./size/Treemap";
-import { type SortKey, buildTree } from "./size/tree";
-
-export function SizeMap({ bundle }: { bundle: Bundle }) {
- const { map, index } = bundle;
- const sponsor = sponsorDate(index);
- const tree = useMemo(() => buildTree(map.nodes), [map.nodes]);
- const stats = useMemo(() => new Map(map.stats.map((s) => [s.node_id, s])), [map.stats]);
- const moduleIds = useMemo(
- () => new Set(map.nodes.filter((n) => n.level === "module").map((n) => n.id)),
- [map.nodes],
- );
- const labels = useMemo(() => {
- const out: Record = {};
- for (const node of map.nodes) out[node.id] = node.path;
- return out;
- }, [map.nodes]);
- const rows = map.stats.filter((s) => moduleIds.has(s.node_id));
- const [sort, setSort] = useState<{ key: SortKey; descending: boolean }>({
- key: "loc",
- descending: true,
- });
- const [selected, setSelected] = useState();
-
- const focusRow = (id: string) => {
- setSelected(id);
- requestAnimationFrame(() =>
- [...document.querySelectorAll("[data-module]")]
- .find((row) => row.dataset.module === id)
- ?.scrollIntoView?.({ behavior: "smooth", block: "center" }),
- );
- };
-
- return (
-
- Size
-
- {rows.length} modules, {tree.value.toLocaleString("en-US")} lines of code. Each rectangle is
- a file, grouped by module. Click a module to find it in the table.
-
-
- {rows.length === 0 ? (
-
- Not measured in this run
- The bundle has no size numbers.
-
- ) : (
- <>
-
-
- Numbers per module
-
-
- Changes are non-bot changes in the 12 months before the snapshot. No figure here ranks a
- person.
-
- >
- )}
-
- );
-}
diff --git a/web/src/screens/beforeafter/Changes.tsx b/web/src/screens/beforeafter/Changes.tsx
deleted file mode 100644
index 353ad27b..00000000
--- a/web/src/screens/beforeafter/Changes.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-// What changed between the two dates, each labelled planned (with its basis) or "no
-// stated intent". Drift is not automatically bad (spec.md §12.3), so nothing is labelled
-// worse by default.
-import { Link } from "react-router";
-import { Badge } from "../../components/Badge";
-import type { StructuralChange } from "../../contracts/generated";
-import { viewLink } from "../../data/view";
-
-const KIND: Record = {
- restructuring: "Restructuring",
- link_added: "Link added",
- link_removed: "Link removed",
- module_added: "Module added",
- module_removed: "Module removed",
-};
-
-const BASIS: Record, string> = {
- same_code_old_layout: "same code under the old layout",
- restructuring_commit: "restructuring commit",
- decision_document: "decision document",
- pr_goal: "stated goal of the pull request",
-};
-
-export function Changes({ changes, repoId }: { changes: StructuralChange[]; repoId: string }) {
- if (changes.length === 0) {
- return No structural change between the two dates. ;
- }
- return (
-
- {changes.map((change) => (
-
-
- {KIND[change.kind]}
-
- {change.label === "planned" ? "Planned" : "No stated intent"}
-
-
-
-
- {change.title}
-
-
- {change.label === "planned"
- ? change.basis
- ? `Basis: ${BASIS[change.basis]}.`
- : "Marked planned; no basis was recorded."
- : "No restructuring commit, decision document or stated pull request goal explains it."}
-
- {change.evidence.length > 0 && (
-
- {change.evidence.map((e) => {
- const where =
- e.kind === "commits"
- ? `${e.commits.length} commit${e.commits.length === 1 ? "" : "s"}`
- : e.start_line === e.end_line
- ? `${e.path}:${e.start_line}`
- : `${e.path}:${e.start_line}-${e.end_line}`;
- const linkable =
- e.kind === "lines" && e.blob_sha && e.start_line !== null && e.end_line !== null;
- return (
-
- {linkable ? (
-
- {where}
- {e.role}
-
- ) : (
-
- {where}
- {e.role}
-
- )}
-
- );
- })}
-
- )}
-
- ))}
-
- );
-}
diff --git a/web/src/screens/beforeafter/DecisionSeries.tsx b/web/src/screens/beforeafter/DecisionSeries.tsx
deleted file mode 100644
index 684656f1..00000000
--- a/web/src/screens/beforeafter/DecisionSeries.tsx
+++ /dev/null
@@ -1,209 +0,0 @@
-// Conformance per decision and the project yardsticks at every snapshot date, with the
-// sponsor date and the repository's own adoption date marked (spec.md §12.1, §12.2).
-import { formatDate, formatSponsorDate } from "../../components/Shell";
-import { StatusGlyph } from "../../components/Status";
-import type { Decision, DecisionCheck, YardstickSeries } from "../../contracts/generated";
-import { percent } from "../decisions/words";
-import { yardstickLabel, yardstickValue } from "./compare";
-
-interface Point {
- date: string;
- value: number;
-}
-
-const W = 260;
-const H = 52;
-const PAD = 6;
-
-/** One series over time with the two date markers, drawn only inside the series' range. */
-function SeriesLine({
- points,
- sponsor,
- adoption,
- label,
-}: {
- points: Point[];
- sponsor: string | null;
- adoption: string | null;
- label: string;
-}) {
- if (points.length === 0) return null;
- const times = points.map((p) => Date.parse(p.date));
- const t0 = Math.min(...times);
- const t1 = Math.max(...times);
- let lo = Math.min(...points.map((p) => p.value));
- let hi = Math.max(...points.map((p) => p.value));
- if (hi - lo < 1e-9) {
- lo -= 1;
- hi += 1;
- }
- const x = (t: number) => (t1 === t0 ? W / 2 : PAD + ((t - t0) / (t1 - t0)) * (W - 2 * PAD));
- const y = (v: number) => PAD + (1 - (v - lo) / (hi - lo)) * (H - 2 * PAD);
- const marker = (date: string | null) => {
- if (!date) return null;
- const t = Date.parse(date);
- return t >= t0 && t <= t1 ? x(t) : null;
- };
- const sponsorAt = marker(sponsor);
- const adopted = marker(adoption);
- const last = points[points.length - 1]!;
-
- return (
-
- {sponsorAt !== null && (
-
- )}
- {adopted !== null && (
-
- )}
- {points.length > 1 && (
- `${x(times[i]!).toFixed(1)},${y(p.value).toFixed(1)}`)
- .join(" ")}
- />
- )}
- {points.map((p, i) => (
-
- ))}
-
- );
-}
-
-/** `sponsor` and `adoption` are ISO dates from the bundle, or null when it has none. */
-export function SeriesKey({
- sponsor,
- adoption,
-}: {
- sponsor: string | null;
- adoption: string | null;
-}) {
- return (
-
- {sponsor && (
-
-
- {formatSponsorDate(sponsor)}, the sponsor date
-
- )}
- {adoption && (
-
-
- {formatDate(adoption)}, adoption detected in this repository
-
- )}
-
- );
-}
-
-export function DecisionSeries({
- decisions,
- checks,
- order,
- sponsor,
- adoption,
-}: {
- decisions: Decision[];
- checks: DecisionCheck[];
- order: Map;
- sponsor: string | null;
- adoption: string | null;
-}) {
- const rows = decisions.flatMap((decision) => {
- const series = checks
- .filter((c) => c.decision_id === decision.id)
- .sort((a, b) => (order.get(a.snapshot_sha) ?? 0) - (order.get(b.snapshot_sha) ?? 0));
- return series.length > 0 ? [{ decision, series }] : [];
- });
- if (rows.length === 0)
- return No decision was checked at these dates. ;
-
- return (
-
- {rows.map(({ decision, series }) => {
- const first = series[0]!;
- const last = series[series.length - 1]!;
- return (
-
-
-
- {decision.statement}
-
- ({ date: c.snapshot_date, value: c.conformance }))}
- sponsor={sponsor}
- adoption={adoption}
- label={`Conformance of "${decision.statement}": ${series
- .map((c) => `${percent(c.conformance)} on ${c.snapshot_date}`)
- .join(", ")}`}
- />
-
- {percent(last.conformance)}
-
- {first === last
- ? "one snapshot"
- : `was ${percent(first.conformance)} on ${formatDate(first.snapshot_date)}`}
-
-
-
- );
- })}
-
- );
-}
-
-export function YardstickSeriesList({
- yardsticks,
- sponsor,
- adoption,
-}: {
- yardsticks: YardstickSeries[];
- sponsor: string | null;
- adoption: string | null;
-}) {
- if (yardsticks.length === 0) return null;
- return (
-
- {yardsticks.map((y) => {
- const points = y.series.map((p) => ({ date: p.snapshot_date, value: p.value }));
- const first = points[0];
- const last = points[points.length - 1];
- return (
-
- {yardstickLabel(y.name)}
- `${yardstickValue(y.name, p.value)} on ${p.date}`)
- .join(", ")}`}
- />
-
- {last && {yardstickValue(y.name, last.value)} }
- {first && last && first !== last && (
-
- was {yardstickValue(y.name, first.value)} on {formatDate(first.date)}
-
- )}
-
-
- );
- })}
-
- );
-}
diff --git a/web/src/screens/beforeafter/Switch.tsx b/web/src/screens/beforeafter/Switch.tsx
deleted file mode 100644
index e441fae0..00000000
--- a/web/src/screens/beforeafter/Switch.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-import { formatDate } from "../../components/Shell";
-import type { SnapshotRef } from "../../contracts/generated";
-import type { Side } from "./compare";
-
-const ROLE: Record = {
- sponsor_date: "sponsor date",
- end: "pinned commit",
- quarter: "quarter",
- adoption: "adoption detected",
-};
-
-interface Props {
- before: SnapshotRef;
- after: SnapshotRef;
- side: Side;
- onChange: (side: Side) => void;
-}
-
-/** Two dates on one layout. Only the colours change when you switch (spec.md §10.4). */
-export function Switch({ before, after, side, onChange }: Props) {
- const option = (which: Side, ref: SnapshotRef) => (
- onChange(which)}
- >
- {formatDate(ref.date)}
- {ROLE[ref.role] ?? ref.role}
-
- );
- return (
-
- {option("before", before)}
- {option("after", after)}
-
- );
-}
diff --git a/web/src/screens/beforeafter/beforeafter.css b/web/src/screens/beforeafter/beforeafter.css
deleted file mode 100644
index d1f4d6fc..00000000
--- a/web/src/screens/beforeafter/beforeafter.css
+++ /dev/null
@@ -1,333 +0,0 @@
-/* Before and after: one layout, two dates; only colours change. */
-
-.ba-head {
- display: flex;
- flex-wrap: wrap;
- align-items: flex-end;
- justify-content: space-between;
- gap: var(--space-4) var(--space-8);
-}
-
-.ba-head__lede {
- max-width: 74ch;
- margin-top: 6px;
-}
-
-.date-switch {
- display: inline-flex;
- gap: 2px;
- padding: 3px;
- border-radius: 10px;
- background: var(--shell);
-}
-
-.date-switch__option {
- display: flex;
- flex-direction: column;
- align-items: flex-start;
- min-width: 140px;
- padding: var(--space-2) var(--space-4);
- border: 0;
- border-radius: 8px;
- background: none;
- font: inherit;
- text-align: left;
- color: var(--ink-muted);
- cursor: pointer;
- transition:
- background 0.15s,
- color 0.15s;
-}
-
-.date-switch__option:hover {
- color: var(--ink);
-}
-
-.date-switch__option.is-on {
- background: var(--ground);
- color: var(--ink);
- box-shadow:
- 0 1px 2px rgba(0, 0, 0, 0.14),
- 0 0 0 1px rgba(0, 0, 0, 0.04);
-}
-
-.date-switch__date {
- font-weight: 600;
-}
-
-.date-switch__role {
- font-size: 0.75rem;
-}
-
-.ba-figures {
- display: flex;
- flex-wrap: wrap;
- gap: var(--space-4) var(--space-10);
- margin: var(--space-8) 0 0;
- padding-top: var(--space-4);
- border-top: 1px solid var(--hairline);
-}
-
-.ba-figures dt {
- font-size: 0.8125rem;
- color: var(--ink-muted);
-}
-
-.ba-figures dd {
- font-size: 1.375rem;
- font-weight: 600;
- letter-spacing: -0.01em;
- color: var(--ink);
-}
-
-.ba-body {
- display: flex;
- flex-wrap: wrap;
- align-items: flex-start;
- gap: var(--space-8) var(--space-10);
- margin-top: var(--space-8);
-}
-
-.ba-body__grid {
- flex: 999 1 600px;
- min-width: 0;
-}
-
-.ba-body__changes {
- flex: 1 1 340px;
- max-width: 460px;
- min-width: 0;
-}
-
-@media (max-width: 1023px) {
- .ba-body__changes {
- max-width: none;
- }
-}
-
-.ba-first-head {
- margin-top: 0;
-}
-
-.ba-swatch {
- position: relative;
- display: inline-block;
- width: 14px;
- height: 14px;
- border-radius: 2px;
-}
-
-.ba-swatch--corner {
- background: rgb(173, 164, 118);
-}
-
-.ba-swatch--corner::after {
- content: "";
- position: absolute;
- top: 0;
- right: 0;
- border-top: 6px solid var(--ink);
- border-left: 6px solid transparent;
-}
-
-.ba-swatch--absent {
- background: var(--ground);
- outline: 1.25px dashed var(--ink);
- outline-offset: -2px;
-}
-
-/* The changes */
-
-.changes {
- margin: 0;
- padding: 0;
- list-style: none;
- border-top: 1px solid var(--ink);
-}
-
-.change {
- padding: var(--space-4) 0;
- border-bottom: 1px solid var(--hairline);
-}
-
-.change__head {
- display: flex;
- flex-wrap: wrap;
- align-items: center;
- justify-content: space-between;
- gap: var(--space-2);
-}
-
-.intent {
- padding: 1px var(--space-2);
- border-radius: 6px;
- font-size: 0.8125rem;
- font-weight: 600;
- white-space: nowrap;
-}
-
-.intent--planned {
- background: var(--ink);
- color: var(--ground);
-}
-
-.intent--no_stated_intent {
- background: var(--ground);
- color: var(--ink);
- box-shadow: inset 0 0 0 1px var(--ink);
-}
-
-.change__title {
- margin-top: var(--space-2);
- font-weight: 600;
- color: var(--ink);
-}
-
-.change__title + p {
- margin-top: 2px;
-}
-
-.change__evidence {
- margin: var(--space-2) 0 0;
- padding: 0;
- list-style: none;
-}
-
-.change__ref {
- display: flex;
- flex-wrap: wrap;
- align-items: baseline;
- gap: 0 var(--space-3);
- padding: 3px var(--space-2);
- border-radius: 6px;
- color: var(--ink);
- text-decoration: none;
- overflow-wrap: anywhere;
-}
-
-a.change__ref:hover {
- background: var(--shell-hover);
-}
-
-/* Series over time */
-
-.ba-series {
- margin-top: var(--space-16);
-}
-
-.ba-series__second {
- margin-top: var(--space-12);
-}
-
-.series-key {
- display: flex;
- flex-wrap: wrap;
- gap: var(--space-1) var(--space-6);
- margin: var(--space-2) 0 var(--space-3);
-}
-
-.series-key span {
- display: inline-flex;
- align-items: center;
- gap: var(--space-2);
-}
-
-.series-key i {
- display: inline-block;
- width: 0;
- height: 14px;
-}
-
-.series-key__sponsor {
- border-left: 1.5px dashed #8a929b;
-}
-
-.series-key__adoption {
- border-left: 1.5px solid var(--ink-muted);
-}
-
-.series-rows {
- margin: 0;
- padding: 0;
- list-style: none;
- border-top: 1px solid var(--ink);
-}
-
-.series-row {
- display: grid;
- grid-template-columns: minmax(220px, 440px) 260px minmax(140px, 1fr);
- gap: var(--space-5);
- align-items: center;
- padding: var(--space-2) 0;
- border-bottom: 1px solid var(--hairline);
-}
-
-.series-row__name {
- display: inline-flex;
- align-items: center;
- gap: var(--space-2);
- font-weight: 500;
- color: var(--ink);
-}
-
-.series-row__value {
- display: flex;
- flex-direction: column;
- align-items: flex-end;
- text-align: right;
-}
-
-.series-row__value b {
- font-size: 1.0625rem;
- font-weight: 600;
- color: var(--ink);
-}
-
-@media (max-width: 760px) {
- .series-row {
- grid-template-columns: minmax(0, 1fr) auto;
- grid-template-areas:
- "name value"
- "line line";
- }
-
- .series-row__name {
- grid-area: name;
- }
-
- .series-row__value {
- grid-area: value;
- }
-
- .series {
- grid-area: line;
- width: 100%;
- }
-}
-
-.series {
- display: block;
- overflow: visible;
-}
-
-.series__line {
- fill: none;
- stroke: var(--ink);
- stroke-width: 1.5;
- stroke-linejoin: round;
-}
-
-.series__dot {
- fill: var(--ink);
-}
-
-.series__sponsor {
- stroke: #8a929b;
- stroke-width: 1.25;
- stroke-dasharray: 3 2;
-}
-
-.series__adoption {
- stroke: var(--ink-muted);
- stroke-width: 1.25;
-}
diff --git a/web/src/screens/beforeafter/compare.ts b/web/src/screens/beforeafter/compare.ts
deleted file mode 100644
index a3a7d7c0..00000000
--- a/web/src/screens/beforeafter/compare.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-// Pure helpers for the before-and-after screen (spec.md §12). Both dates share one
-// module order, so switching dates changes colours only, never positions (§10.4).
-import type { BeforeAfterFile } from "../../contracts/generated";
-import { cellKey } from "../grid/cells";
-import type { MatrixCell } from "../grid/MatrixCanvas";
-
-export type Side = "before" | "after";
-
-/** The cells at one date; zero-count cells dropped. */
-export function cellsAt(file: BeforeAfterFile, which: Side): MatrixCell[] {
- return file.cells
- .map((cell) => ({ src: cell.src, dst: cell.dst, count: cell[which] }))
- .filter((cell) => cell.count > 0);
-}
-
-/** Every cell whose count differs between the two dates. */
-export function changedCells(
- file: BeforeAfterFile,
-): Map {
- const out = new Map();
- for (const cell of file.cells) {
- if (cell.before !== cell.after) {
- out.set(cellKey(cell.src, cell.dst), { before: cell.before, after: cell.after });
- }
- }
- return out;
-}
-
-/**
- * The change markers as seen from one side. MatrixCanvas empties a cell whose `after` is 0,
- * so on the earlier date the pair is flipped: a dashed cell then means "absent here, present
- * at the other date" on both sides, and a corner mark means "the count differs".
- */
-export function changedFrom(
- changes: Map,
- which: Side,
-): Map {
- if (which === "after") return changes;
- const out = new Map();
- for (const [key, change] of changes) out.set(key, { before: change.after, after: change.before });
- return out;
-}
-
-/** "against_the_grain_share" to "Against-the-grain share", for yardstick names. */
-export function yardstickLabel(name: string): string {
- const words = name
- .replace(/_/g, " ")
- .replace(/against the grain/, "against-the-grain")
- .replace(/two way/, "two-way")
- .replace(/\bper kloc\b/, "per 1,000 lines");
- return words.charAt(0).toUpperCase() + words.slice(1);
-}
-
-/** Shares print as percentages, counts as whole numbers. */
-export function yardstickValue(name: string, value: number): string {
- if (/share|ratio/.test(name)) return `${(value * 100).toFixed(value < 0.1 ? 2 : 1)}%`;
- return Number.isInteger(value) ? value.toLocaleString("en-US") : value.toFixed(2);
-}
diff --git a/web/src/screens/closeup/Graph.tsx b/web/src/screens/closeup/Graph.tsx
deleted file mode 100644
index 091f86ca..00000000
--- a/web/src/screens/closeup/Graph.tsx
+++ /dev/null
@@ -1,184 +0,0 @@
-// Boxes and arrows for the modules of one finding (spec.md §10.2 screen 3), drawn with
-// Cytoscape from positions computed at build time: no physics, nothing moves (§10.4).
-// Cytoscape loads only when this screen opens, so the main bundle does not carry it.
-import type { Core, ElementDefinition } from "cytoscape";
-import { useEffect, useRef, useState } from "react";
-
-export interface GraphNode {
- id: string;
- label: string;
- x: number;
- y: number;
- /** A module of the finding's own targets, drawn with an ink border. */
- primary: boolean;
-}
-
-export interface GraphEdge {
- id: string;
- src: string;
- dst: string;
- count: number;
- /** Source later than target in the module order: drawn in vermilion. */
- against: boolean;
-}
-
-interface Props {
- nodes: GraphNode[];
- edges: GraphEdge[];
- selectedEdge?: string;
- selectedNode?: string;
- onEdge: (edge: GraphEdge) => void;
- onNode: (id: string) => void;
-}
-
-function token(name: string, fallback: string): string {
- const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
- return value || fallback;
-}
-
-export function Graph({ nodes, edges, selectedEdge, selectedNode, onEdge, onNode }: Props) {
- const host = useRef(null);
- const cy = useRef(null);
- const handlers = useRef({ onEdge, onNode });
- handlers.current = { onEdge, onNode };
- const [failed, setFailed] = useState(false);
-
- useEffect(() => {
- const element = host.current;
- if (!element) return;
- let cancelled = false;
- let observer: ResizeObserver | null = null;
- import("cytoscape").then(
- ({ default: cytoscape }) => {
- if (cancelled) return;
- const ink = token("--ink", "#000000");
- const against = token("--against-decision", "#d55e00");
- const muted = "#69727c";
- const max = Math.max(1, ...edges.map((e) => e.count));
- const elements: ElementDefinition[] = [
- ...nodes.map((n) => ({
- data: { id: n.id, label: n.label, w: Math.max(88, n.label.length * 9 + 36) },
- position: { x: n.x, y: n.y },
- classes: n.primary ? "primary" : "",
- })),
- ...edges.map((e) => ({
- data: {
- id: e.id,
- source: e.src,
- target: e.dst,
- label: `${e.count}`,
- width: 1.5 + 4.5 * (Math.log(e.count + 1) / Math.log(max + 1)),
- },
- classes: e.against ? "against" : "",
- })),
- ];
- const instance = cytoscape({
- container: element,
- elements,
- layout: { name: "preset", fit: true, padding: 48 },
- autoungrabify: true,
- userZoomingEnabled: false,
- userPanningEnabled: false,
- boxSelectionEnabled: false,
- minZoom: 0.3,
- // A close-up of two modules should not fill the screen with two giant boxes.
- maxZoom: 1.4,
- style: [
- {
- selector: "node",
- style: {
- shape: "round-rectangle",
- width: "data(w)",
- height: 40,
- "background-color": "#ffffff",
- "border-width": 1,
- "border-color": "#cbd0d6",
- label: "data(label)",
- "text-valign": "center",
- "text-halign": "center",
- "font-family": "Hanken Grotesk Variable, system-ui, sans-serif",
- "font-size": 14,
- "font-weight": 600,
- color: ink,
- },
- },
- { selector: "node.primary", style: { "border-width": 2, "border-color": ink } },
- {
- selector: "edge",
- style: {
- "curve-style": "bezier",
- width: "data(width)",
- "line-color": muted,
- "target-arrow-color": muted,
- "target-arrow-shape": "triangle",
- "arrow-scale": 1.1,
- label: "data(label)",
- "font-family": "Hanken Grotesk Variable, system-ui, sans-serif",
- "font-size": 12,
- "font-weight": 600,
- color: ink,
- "text-background-color": "#ffffff",
- "text-background-opacity": 1,
- "text-background-padding": "3px",
- },
- },
- {
- selector: "edge.against",
- style: { "line-color": against, "target-arrow-color": against, color: against },
- },
- {
- selector: ".is-selected",
- style: { "overlay-color": ink, "overlay-opacity": 0.12, "overlay-padding": 6 },
- },
- ],
- });
- instance.on("tap", "edge", (event) => {
- const edge = edges.find((e) => e.id === event.target.id());
- if (edge) handlers.current.onEdge(edge);
- });
- instance.on("tap", "node", (event) => handlers.current.onNode(event.target.id()));
- cy.current = instance;
- // Measure the box once it is laid out, and again whenever it changes size.
- const refit = () => {
- instance.resize();
- instance.fit(undefined, 48);
- };
- requestAnimationFrame(refit);
- if (typeof ResizeObserver !== "undefined") {
- observer = new ResizeObserver(() => refit());
- observer.observe(element);
- }
- },
- () => !cancelled && setFailed(true),
- );
- return () => {
- cancelled = true;
- observer?.disconnect();
- cy.current?.destroy();
- cy.current = null;
- };
- }, [nodes, edges]);
-
- // Selection is a style class only; positions never change.
- useEffect(() => {
- const instance = cy.current;
- if (!instance) return;
- instance.elements().removeClass("is-selected");
- if (selectedEdge) instance.getElementById(selectedEdge).addClass("is-selected");
- if (selectedNode) instance.getElementById(selectedNode).addClass("is-selected");
- });
-
- if (failed) {
- return (
- The drawing could not be loaded. The links are listed beside it.
- );
- }
- return (
-
- );
-}
diff --git a/web/src/screens/closeup/closeup.css b/web/src/screens/closeup/closeup.css
deleted file mode 100644
index 1d862259..00000000
--- a/web/src/screens/closeup/closeup.css
+++ /dev/null
@@ -1,115 +0,0 @@
-/* Close-up: the drawing leads, details and the keyboard route sit beside it. */
-
-.closeup-lede {
- max-width: 74ch;
- margin-top: 6px;
-}
-
-.closeup-body {
- display: flex;
- flex-wrap: wrap;
- align-items: flex-start;
- gap: var(--space-8) var(--space-10);
- margin-top: var(--space-8);
-}
-
-.closeup-body__graph {
- flex: 999 1 640px;
- min-width: 0;
-}
-
-.closeup-body__side {
- flex: 1 1 320px;
- max-width: 420px;
- min-width: 0;
-}
-
-@media (max-width: 1023px) {
- .closeup-body__side {
- max-width: none;
- }
-}
-
-.closeup-graph {
- width: 100%;
- height: min(520px, 64vh);
- min-height: 320px;
- border: 1px solid var(--hairline);
- border-radius: 12px;
- background: #fafbfc;
-}
-
-.closeup-detail {
- padding-bottom: var(--space-5);
- border-bottom: 1px solid var(--hairline);
-}
-
-.closeup-detail .button {
- margin-top: var(--space-4);
- text-decoration: none;
-}
-
-.closeup-links,
-.closeup-pick {
- margin: 0;
- padding: 0;
- list-style: none;
- border-top: 1px solid var(--hairline);
-}
-
-.closeup-links__row {
- display: flex;
- justify-content: space-between;
- align-items: baseline;
- gap: var(--space-4);
- width: 100%;
- padding: var(--space-2);
- border: 0;
- border-bottom: 1px solid var(--hairline);
- background: none;
- font: inherit;
- font-size: 0.875rem;
- text-align: left;
- color: var(--ink);
- cursor: pointer;
- transition: background 0.12s;
-}
-
-.closeup-links__row:hover {
- background: var(--shell-hover);
-}
-
-.closeup-links__row.is-on {
- background: var(--shell);
- font-weight: 600;
-}
-
-.closeup-links__row:focus-visible {
- outline-offset: -2px;
-}
-
-.closeup-pick {
- max-width: 880px;
- margin-top: var(--space-6);
- border-top-color: var(--ink);
-}
-
-.closeup-pick__row {
- display: grid;
- grid-template-columns: 40px 1fr;
- gap: var(--space-3);
- padding: var(--space-3) var(--space-2);
- border-bottom: 1px solid var(--hairline);
- font-weight: 600;
- color: var(--ink);
- text-decoration: none;
- transition: background 0.12s;
-}
-
-.closeup-pick__row:hover {
- background: var(--shell-hover);
-}
-
-.closeup-pick__rank {
- font-size: 1.125rem;
-}
diff --git a/web/src/screens/closeup/select.ts b/web/src/screens/closeup/select.ts
deleted file mode 100644
index 051a92aa..00000000
--- a/web/src/screens/closeup/select.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-// Which modules and links belong to one finding's close-up (spec.md §10.2 screen 3).
-// web/scripts/layout.mjs mirrors `closeUpModules` in plain JavaScript; keep them in step.
-import type { Edge, Finding, Node } from "../../contracts/generated";
-import { moduleEdges, moduleOf } from "../grid/cells";
-
-export const MAX_MODULES = 8;
-
-/**
- * The modules of the finding's targets, then their strongest neighbours by total link
- * count in either direction, up to `max`. Ties are broken by node id, so the choice is
- * the same on every run.
- */
-export function closeUpModules(
- finding: Finding,
- nodes: Node[],
- edges: Edge[],
- order: string[],
- max = MAX_MODULES,
-): string[] {
- const chosen: string[] = [];
- for (const target of finding.targets) {
- const module = moduleOf(nodes, target.node_id);
- if (module && !chosen.includes(module)) chosen.push(module);
- }
- if (chosen.length === 0) return [];
-
- const weight = new Map();
- for (const edge of moduleEdges(order, edges)) {
- const inSrc = chosen.includes(edge.src);
- const inDst = chosen.includes(edge.dst);
- if (inSrc && !inDst) weight.set(edge.dst, (weight.get(edge.dst) ?? 0) + edge.count);
- if (inDst && !inSrc) weight.set(edge.src, (weight.get(edge.src) ?? 0) + edge.count);
- }
- const neighbours = [...weight.entries()]
- .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
- .map(([id]) => id);
- return [...chosen, ...neighbours].slice(0, Math.max(max, chosen.length));
-}
-
-/** Module-to-module edges with both ends in the given set. */
-export function closeUpEdges(modules: string[], order: string[], edges: Edge[]): Edge[] {
- const set = new Set(modules);
- return moduleEdges(order, edges).filter((e) => set.has(e.src) && set.has(e.dst));
-}
diff --git a/web/src/screens/code/Highlighted.tsx b/web/src/screens/code/Highlighted.tsx
deleted file mode 100644
index 9fd8ba2c..00000000
--- a/web/src/screens/code/Highlighted.tsx
+++ /dev/null
@@ -1,182 +0,0 @@
-// Read-only code with line numbers (spec.md §10.5: Shiki). Shiki and the one grammar a
-// file needs load on demand, so the main bundle does not carry them.
-import { type CSSProperties, useEffect, useRef, useState } from "react";
-import type { HighlighterCore, ThemedToken, ThemeRegistration } from "shiki/core";
-
-export interface LineMark {
- /** "against": code that goes against a decision (vermilion); "evidence": other cited lines. */
- kind: "against" | "evidence";
- /** Shown at the end of the first line of the range, such as "offending import". */
- role?: string;
- /** The range the address points at, scrolled into view. */
- focus?: boolean;
-}
-
-interface Props {
- text: string;
- language: string | null;
- marks: Map | |