From 3325fd48e5b25584022d6b9981db143c978bf6bb Mon Sep 17 00:00:00 2001 From: Pranav Mathad Date: Sun, 29 Nov 2026 05:01:09 +0100 Subject: [PATCH 01/18] Add the new design tokens and the bundle adapter for the web app --- web/index.html | 5 + web/package-lock.json | 471 +++++++++++++++++++++++++++++ web/package.json | 4 + web/src/cx/clone.ts | 27 ++ web/src/cx/grid.ts | 103 +++++++ web/src/cx/meta.ts | 160 ++++++++++ web/src/cx/types.ts | 415 +++++++++++++++++++++++++ web/src/data/adapt.ts | 598 +++++++++++++++++++++++++++++++++++++ web/src/data/bundle.ts | 33 +- web/src/data/repo.ts | 116 +++++++ web/src/main.tsx | 2 + web/src/styles/globals.css | 145 +++++++++ web/vite.config.ts | 3 +- 13 files changed, 2078 insertions(+), 4 deletions(-) create mode 100644 web/src/cx/clone.ts create mode 100644 web/src/cx/grid.ts create mode 100644 web/src/cx/meta.ts create mode 100644 web/src/cx/types.ts create mode 100644 web/src/data/adapt.ts create mode 100644 web/src/data/repo.ts create mode 100644 web/src/styles/globals.css 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..45a5901d 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -9,18 +9,21 @@ "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", @@ -33,6 +36,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" @@ -354,6 +358,15 @@ "url": "https://github.com/sponsors/ayuhito" } }, + "node_modules/@fontsource-variable/instrument-sans": { + "version": "5.3.0", + "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" + } + }, "node_modules/@fontsource-variable/jetbrains-mono": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/@fontsource-variable/jetbrains-mono/-/jetbrains-mono-5.3.0.tgz", @@ -363,6 +376,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 +415,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 +835,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", @@ -1794,6 +2198,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 +2285,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 +2367,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 +2750,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 +3330,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..da157c68 100644 --- a/web/package.json +++ b/web/package.json @@ -15,18 +15,21 @@ }, "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", @@ -39,6 +42,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/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..74be63e4 --- /dev/null +++ b/web/src/cx/meta.ts @@ -0,0 +1,160 @@ +// 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: "Conformance below 90%" }, + slipping: { + label: "Slipping", + color: "#E69F00", + order: 1, + hint: "Fell by more than 1 point over the last two snapshots", + }, + spreading: { + label: "Spreading", + color: "#CC79A7", + order: 2, + hint: "The number of modules the rule covers is growing", + }, + mostly_holding: { + label: "Mostly holding", + color: "#56B4E9", + order: 3, + hint: "90% to 98%, stable", + }, + holding: { label: "Holding", color: "#009E73", order: 4, hint: "Conformance at least 98%" }, + }; + +export const STATUS_ORDER: Status[] = [ + "broken", + "slipping", + "spreading", + "mostly_holding", + "holding", +]; + +export const TYPE: Record = { + broken_rule: { label: "Broken rule", group: "Decision exception" }, + cheap_loop: { label: "Cheap loop to cut", group: "Decision exception" }, + foundation_on_features: { label: "Foundation on features", group: "Decision exception" }, + shaky_foundation: { label: "Shaky foundation", group: "Pressure point" }, + hidden_partners: { label: "Hidden partners", group: "Pressure point" }, + overloaded_class: { label: "Overloaded class", group: "Inside a file" }, + large_complex_changed: { label: "Large, complex, often changed", group: "Supporting detail" }, +}; + +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."; + +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}`; +} + +/** + * "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..4f42eb65 --- /dev/null +++ b/web/src/cx/types.ts @@ -0,0 +1,415 @@ +// 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; +} + +/** 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[]; +} + +/** 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[]; +} + +/** 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; +} diff --git a/web/src/data/adapt.ts b/web/src/data/adapt.ts new file mode 100644 index 00000000..fd4e3a1b --- /dev/null +++ b/web/src/data/adapt.ts @@ -0,0 +1,598 @@ +// 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, + 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}`; + +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}.`; +} + +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 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: f.title, + summary: 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)!), + }; + }; + 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.", + }); + 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 stored = new Map(report.yardsticks.map((y) => [y.name, y])); + const yardstickSeries: Record = {}; + for (const y of [...ba.yardsticks].sort((a, b) => byText(a.name, b.name))) { + yardstickSeries[y.name] = seriesOf(y.series); + } + const yardstick = (name: string): Yardstick => { + const series = yardstickSeries[name] ?? []; + return { + name, + unit: stored.get(name)?.unit ?? null, + now: stored.get(name)?.value ?? null, + before: series.find((p) => p.date === ba.before.date)?.value ?? null, + series, + }; + }; + + 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"); + 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: [...new Set(report.coverage.map((c) => c.language))].sort(byText), + 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), + }; +} diff --git a/web/src/data/bundle.ts b/web/src/data/bundle.ts index 897899ce..605503ef 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,28 @@ 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 }; +} + // Keyed by file URL. A blob's content never changes, so a cached file stays correct. const codeCache = new Map>(); @@ -106,14 +128,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/repo.ts b/web/src/data/repo.ts new file mode 100644 index 00000000..dacc13e4 --- /dev/null +++ b/web/src/data/repo.ts @@ -0,0 +1,116 @@ +// 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 { RepoBundle, RepoSummary } from "../cx/types"; +import { adaptBundle, decisionStatusCounts } from "./adapt"; +import { + type FetchJson, + loadBundle, + loadBundleList, + loadBundleSummary, + loadCodeAt, +} 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; +} + +/** 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 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))); + + return { list, summaries: all, summary, repo }; +} + +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 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/main.tsx b/web/src/main.tsx index 790b7b75..8a89a2a5 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -1,5 +1,7 @@ +import "@fontsource-variable/instrument-sans"; import "@fontsource-variable/hanken-grotesk"; import "@fontsource-variable/jetbrains-mono"; +import "./styles/globals.css"; import "./styles/tokens.css"; import "./styles/base.css"; diff --git a/web/src/styles/globals.css b/web/src/styles/globals.css new file mode 100644 index 00000000..449d6f7e --- /dev/null +++ b/web/src/styles/globals.css @@ -0,0 +1,145 @@ +@import 'tailwindcss'; + +@theme inline { + --font-sans: 'Instrument Sans Variable', 'Instrument Sans', ui-sans-serif, system-ui, sans-serif; + --font-mono: 'JetBrains Mono Variable', 'JetBrains Mono', ui-monospace, monospace; + + --color-background: var(--background); + --color-foreground: var(--foreground); + --color-card: var(--card); + --color-card-foreground: var(--card-foreground); + --color-popover: var(--popover); + --color-popover-foreground: var(--popover-foreground); + --color-primary: var(--primary); + --color-primary-foreground: var(--primary-foreground); + --color-secondary: var(--secondary); + --color-secondary-foreground: var(--secondary-foreground); + --color-muted: var(--muted); + --color-muted-foreground: var(--muted-foreground); + --color-accent: var(--accent); + --color-accent-foreground: var(--accent-foreground); + --color-destructive: var(--destructive); + --color-border: var(--border); + --color-input: var(--input); + --color-ring: var(--ring); + --color-grain: var(--grain); + --color-against: var(--against); + --color-ink: var(--ink); + --color-ink-foreground: var(--ink-foreground); + + --radius-sm: calc(var(--radius) * 0.6); + --radius-md: calc(var(--radius) * 0.8); + --radius-lg: var(--radius); + --radius-xl: calc(var(--radius) * 1.4); +} + +:root { + --radius: 0.375rem; + --background: #f2f3ef; + --foreground: #14181f; + --card: #fafaf7; + --card-foreground: #14181f; + --popover: #fafaf7; + --popover-foreground: #14181f; + /* cyanotype blue: the "with the grain" direction */ + --primary: #1f4e8c; + --primary-foreground: #f7f8f4; + --secondary: #e6e8e2; + --secondary-foreground: #14181f; + --muted: #e6e8e2; + --muted-foreground: #5a616d; + /* vermilion: "against the grain" */ + --accent: #d55e00; + --accent-foreground: #fffaf5; + --destructive: #d55e00; + --border: #d6d9d1; + --input: #d6d9d1; + --ring: #1f4e8c; + --grain: #1f4e8c; + --against: #d55e00; + --ink: #14181f; + --ink-foreground: #eef0ea; +} + +@layer base { + * { + @apply border-border outline-ring/50; + } + html { + @apply bg-background; + } + body { + @apply bg-background text-foreground font-sans; + font-feature-settings: 'ss01', 'cv11'; + } + ::selection { + background: color-mix(in oklab, var(--primary) 22%, transparent); + } +} + +@utility tabular { + font-variant-numeric: tabular-nums; +} + +/* faint measuring-grid backdrop used on hero bands */ +@utility graph-paper { + background-image: + linear-gradient(to right, color-mix(in oklab, var(--foreground) 6%, transparent) 1px, transparent 1px), + linear-gradient(to bottom, color-mix(in oklab, var(--foreground) 6%, transparent) 1px, transparent 1px); + background-size: 24px 24px; +} + +/* shiki output */ +.cx-code pre { + background: transparent !important; + margin: 0; + padding: 0.75rem 0; + font-size: 12.5px; + line-height: 1.65; + overflow-x: auto; +} +.cx-code code { + display: grid; + min-width: max-content; +} +.cx-code .line { + display: block; + padding-right: 1.25rem; + border-left: 2px solid transparent; +} +.cx-code .line::before { + content: attr(data-n); + display: inline-block; + width: 3.25rem; + padding-right: 1rem; + text-align: right; + color: color-mix(in oklab, var(--foreground) 32%, transparent); + user-select: none; +} +.cx-code .line.hl { + background: color-mix(in oklab, var(--accent) 9%, transparent); + border-left-color: var(--accent); +} +.cx-code .line.hl::before { + color: var(--accent); + font-weight: 600; +} + +@keyframes cx-rise { + from { + opacity: 0; + transform: translateY(6px); + } + to { + opacity: 1; + transform: none; + } +} +.cx-rise { + animation: cx-rise 0.5s cubic-bezier(0.2, 0.7, 0.2, 1) both; +} +@media (prefers-reduced-motion: reduce) { + .cx-rise { + animation: none; + } +} diff --git a/web/vite.config.ts b/web/vite.config.ts index 75529217..a7fc61ad 100644 --- a/web/vite.config.ts +++ b/web/vite.config.ts @@ -1,10 +1,11 @@ +import tailwindcss from "@tailwindcss/vite"; import react from "@vitejs/plugin-react"; import { defineConfig } from "vitest/config"; export default defineConfig({ // Relative asset paths, so the built bundle works from any folder or static host. base: "./", - plugins: [react()], + plugins: [react(), tailwindcss()], test: { environment: "jsdom", }, From 04494e36e17a78c4f473ad3d8546dee5f3b9d688 Mon Sep 17 00:00:00 2001 From: Pranav Mathad Date: Sun, 29 Nov 2026 05:13:13 +0100 Subject: [PATCH 02/18] Add the new shell, landing page and overview screen --- web/src/App.tsx | 103 ++---- web/src/components/cx/badges.tsx | 48 +++ web/src/components/cx/cn.ts | 8 + web/src/components/cx/finding-row.tsx | 103 ++++++ web/src/components/cx/overview-map.tsx | 51 +++ web/src/components/cx/primitives.tsx | 146 ++++++++ web/src/components/cx/site-header.tsx | 117 +++++++ web/src/components/cx/sparkline.tsx | 78 +++++ web/src/components/cx/use-page.ts | 43 +++ web/src/cx/address.ts | 92 +++++ web/src/cx/types.ts | 19 ++ web/src/data/adapt.ts | 66 +++- web/src/data/bundle.ts | 37 ++ web/src/data/repo.ts | 64 +++- web/src/main.tsx | 2 - web/src/routes/Change.tsx | 15 + web/src/routes/Decisions.tsx | 15 + web/src/routes/FindingDetail.tsx | 33 ++ web/src/routes/Findings.tsx | 15 + web/src/routes/Landing.tsx | 258 ++++++++++++++ web/src/routes/MapPage.tsx | 15 + web/src/routes/NotFound.tsx | 30 ++ web/src/routes/Overview.tsx | 450 +++++++++++++++++++++++++ web/src/routes/RepoLayout.tsx | 223 ++++++++++++ web/src/routes/Size.tsx | 15 + web/src/routes/Trust.tsx | 15 + 26 files changed, 1974 insertions(+), 87 deletions(-) create mode 100644 web/src/components/cx/badges.tsx create mode 100644 web/src/components/cx/cn.ts create mode 100644 web/src/components/cx/finding-row.tsx create mode 100644 web/src/components/cx/overview-map.tsx create mode 100644 web/src/components/cx/primitives.tsx create mode 100644 web/src/components/cx/site-header.tsx create mode 100644 web/src/components/cx/sparkline.tsx create mode 100644 web/src/components/cx/use-page.ts create mode 100644 web/src/cx/address.ts create mode 100644 web/src/routes/Change.tsx create mode 100644 web/src/routes/Decisions.tsx create mode 100644 web/src/routes/FindingDetail.tsx create mode 100644 web/src/routes/Findings.tsx create mode 100644 web/src/routes/Landing.tsx create mode 100644 web/src/routes/MapPage.tsx create mode 100644 web/src/routes/NotFound.tsx create mode 100644 web/src/routes/Overview.tsx create mode 100644 web/src/routes/RepoLayout.tsx create mode 100644 web/src/routes/Size.tsx create mode 100644 web/src/routes/Trust.tsx diff --git a/web/src/App.tsx b/web/src/App.tsx index 51759dd3..282f5d07 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -1,71 +1,42 @@ -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 { 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/components/cx/badges.tsx b/web/src/components/cx/badges.tsx new file mode 100644 index 00000000..f4ca4d42 --- /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 AI-written sentence 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/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/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/overview-map.tsx b/web/src/components/cx/overview-map.tsx new file mode 100644 index 00000000..bacc05c4 --- /dev/null +++ b/web/src/components/cx/overview-map.tsx @@ -0,0 +1,51 @@ +import { ArrowRight } from "lucide-react"; +import { Link } from "react-router"; +import { repoPath } from "../../cx/address"; +import { fmt, pct } from "../../cx/meta"; +import type { RepoBundle } from "../../cx/types"; +import { NotMeasured } from "./badges"; +import { FOCUS, cn } from "./cn"; +import { SectionHead } from "./primitives"; + +/** The small map on the Overview. For now: the stored grain numbers and a link to the Map. */ +export function OverviewMap({ repo }: { repo: RepoBundle }) { + const share = repo.yardsticks.againstGrainShare.now; + const pairs = repo.yardsticks.twoWayPairs.now; + return ( +
    + + Open map + + } + /> +

    + + against grain{" "} + {share === null ? ( + + ) : ( + {pct(share)} + )} + + + two-way pairs{" "} + {pairs === null ? ( + + ) : ( + {fmt(pairs)} + )} + +

    +
    + ); +} diff --git a/web/src/components/cx/primitives.tsx b/web/src/components/cx/primitives.tsx new file mode 100644 index 00000000..3e7c4500 --- /dev/null +++ b/web/src/components/cx/primitives.tsx @@ -0,0 +1,146 @@ +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 }: { children: ReactNode; className?: 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/site-header.tsx b/web/src/components/cx/site-header.tsx new file mode 100644 index 00000000..3947b844 --- /dev/null +++ b/web/src/components/cx/site-header.tsx @@ -0,0 +1,117 @@ +import type { ReactNode } from "react"; +import { Link } from "react-router"; +import { repoPath } from "../../cx/address"; +import { STATUS } from "../../cx/meta"; +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, one button per real repository in the order of `bundles/index.json`, + * and the synthetic bundles as a small, secondary group at the end. + */ +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); + const fixtures = all.filter((r) => r.synthetic); + return ( +
    +
    + + + CodeXray + + +
    + + pipeline v1 · offline, deterministic +
    +
    +
    + ); +} + +/** The bottom line of every page: what the numbers rest on, and the project credit. */ +export function SiteFooter({ children }: { children: ReactNode }) { + return ( +
    +
    +

    {children}

    +

    CodeXray · CHECK24 × hackaTUM

    +
    +
    + ); +} + +/** A page outside any repository: header, content, footer. */ +export function SitePage({ children, current }: { children: ReactNode; current?: string }) { + return ( +
    + +
    + {children} +
    + Deterministic numbers, cited AI. Same commit, same report. +
    + ); +} 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<T> = + { 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<T>(load: () => Promise<T>, key: string): Loaded<T> { + const [result, setResult] = useState<{ key: string; loaded: Loaded<T> }>({ + 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..5d45a01d --- /dev/null +++ b/web/src/cx/address.ts @@ -0,0 +1,92 @@ +// 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 = "decisions" | "findings" | "map" | "change" | "trust" | "size"; + +const seg = (s: string) => encodeURIComponent(s); + +/** "/r/<repo>" for the overview, "/r/<repo>/<tab>" for any other tab. */ +export function repoPath(repoId: string, tab?: RepoTab): string { + return tab ? `/r/${seg(repoId)}/${tab}` : `/r/${seg(repoId)}`; +} + +/** "/r/<repo>/findings/<slug>". */ +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; +} + +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=<srcModuleId>,<dstModuleId>`. 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; +} + +export function readMapState( + search: string | URLSearchParams, + moduleIds: readonly string[], +): MapState { + return { view: readMapView(search), cell: readMapCell(search, moduleIds) }; +} + +// 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 and an empty cell are left out; with nothing to say it returns "". + */ +export function mapSearch(state: Partial<MapState>): 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]}`)}`); + 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<MapState>, +): string { + return mapSearch({ ...readMapState(search, moduleIds), ...patch }); +} + +/** "/r/<repo>/map" with the given view and cell. */ +export function mapPath(repoId: string, state: Partial<MapState> = {}): string { + return `${repoPath(repoId, "map")}${mapSearch(state)}`; +} diff --git a/web/src/cx/types.ts b/web/src/cx/types.ts index 4f42eb65..05e30dfb 100644 --- a/web/src/cx/types.ts +++ b/web/src/cx/types.ts @@ -413,3 +413,22 @@ export interface RepoSummary { snapshotDate: string | null; statusCounts: Record<Status, number>; } + +/** + * 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 index fd4e3a1b..d0360b41 100644 --- a/web/src/data/adapt.ts +++ b/web/src/data/adapt.ts @@ -234,6 +234,53 @@ function healthySentence(d: Decision, date: string): string { 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<string, SeriesPoint[]> { + const out: Record<string, SeriesPoint[]> = {}; + 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<string, SeriesPoint[]>, + 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: top.title, slug }; +} + export function adaptBundle(bundle: Bundle): RepoBundle { const { index, map, beforeAfter: ba, report, decisions: decisionsFile } = bundle; const order = ba.module_order; @@ -456,21 +503,8 @@ export function adaptBundle(bundle: Bundle): RepoBundle { .map((d) => ({ decisionId: d.id, evidence: healthySentence(d, snapshotDate) })); // Yardsticks: the stored values, never recounted from the grid. - const stored = new Map(report.yardsticks.map((y) => [y.name, y])); - const yardstickSeries: Record<string, SeriesPoint[]> = {}; - for (const y of [...ba.yardsticks].sort((a, b) => byText(a.name, b.name))) { - yardstickSeries[y.name] = seriesOf(y.series); - } - const yardstick = (name: string): Yardstick => { - const series = yardstickSeries[name] ?? []; - return { - name, - unit: stored.get(name)?.unit ?? null, - now: stored.get(name)?.value ?? null, - before: series.find((p) => p.date === ba.before.date)?.value ?? null, - series, - }; - }; + const yardstickSeries = yardstickSeriesOf(ba); + const yardstick = (name: string): Yardstick => yardstickFrom(report, ba, yardstickSeries, name); const batch: Batch | null = batchFile ? { @@ -525,7 +559,7 @@ export function adaptBundle(bundle: Bundle): RepoBundle { synthetic: index.synthetic, host: index.host_url, folder: bundle.folder, - languages: [...new Set(report.coverage.map((c) => c.language))].sort(byText), + languages: languagesOf(report), endSha: index.end_sha, snapshotDate, paramsHash: index.params_hash, diff --git a/web/src/data/bundle.ts b/web/src/data/bundle.ts index 605503ef..668391af 100644 --- a/web/src/data/bundle.ts +++ b/web/src/data/bundle.ts @@ -120,6 +120,43 @@ export async function loadBundleSummary( 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<Pick<Bundle, "index" | "decisions" | "report" | "beforeAfter" | "folder">> { + const { index, decisions, folder } = await loadBundleSummary(indexPath, root, get); + const part = async <T extends { schema: string }>(key: string, schema: T["schema"]) => { + const file = index.files[key]; + if (!file) throw new Error(`${folder}index.json lists no "${key}" file`); + return expectSchema<T>(await get(folder + file), schema, folder + file); + }; + const [report, beforeAfter] = await Promise.all([ + part<ReportFile>("report", "codexray.report/1"), + part<BeforeAfterFile>("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<FindingsFile> { + const indexUrl = `${root}${indexPath}`; + const folder = indexUrl.slice(0, indexUrl.lastIndexOf("/") + 1); + const index = expectSchema<BundleIndex>(await get(indexUrl), "codexray.bundle/1", indexUrl); + const file = index.files["findings"]; + if (!file) throw new Error(`${indexUrl} lists no "findings" file`); + return expectSchema<FindingsFile>(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<string, Promise<CodeFile>>(); diff --git a/web/src/data/repo.ts b/web/src/data/repo.ts index dacc13e4..cb50b1f0 100644 --- a/web/src/data/repo.ts +++ b/web/src/data/repo.ts @@ -3,14 +3,23 @@ // or screens never fetches the same bundle twice. import type { BundleListEntry, CodeFile } from "../contracts/generated"; import { statusCounts } from "../cx/meta"; -import type { RepoBundle, RepoSummary } from "../cx/types"; -import { adaptBundle, decisionStatusCounts } from "./adapt"; +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 { @@ -22,6 +31,10 @@ export interface RepoSource { summary(id: string): Promise<RepoSummary>; /** The full repository, adapted for the screens. */ repo(id: string): Promise<RepoBundle>; + /** A landing-page card: four small files, never the map or the findings. */ + card(id: string): Promise<RepoCard>; + /** The rank-1 finding, from the findings file alone; null when there is none. */ + fixFirst(id: string): Promise<FixFirst | null>; } /** Keeps a promise per key; a failed load is dropped so the screen can try again. */ @@ -42,6 +55,8 @@ export function createRepoSource(root?: string, get?: FetchJson): RepoSource { let listing: Promise<BundleListEntry[]> | null = null; const fulls = new Map<string, Promise<RepoBundle>>(); const summaries = new Map<string, Promise<RepoSummary>>(); + const cards = new Map<string, Promise<RepoCard>>(); + const tops = new Map<string, Promise<FixFirst | null>>(); const list = (): Promise<BundleListEntry[]> => { if (!listing) { @@ -93,7 +108,46 @@ export function createRepoSource(root?: string, get?: FetchJson): RepoSource { const all = async (): Promise<RepoSummary[]> => Promise.all((await list()).map((b) => summary(b.repo_id))); - return { list, summaries: all, summary, repo }; + const card = (id: string): Promise<RepoCard> => + 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<FixFirst | null> => + 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; @@ -104,6 +158,10 @@ export const loadRepoList = (): Promise<BundleListEntry[]> => source().list(); /** Summaries for the landing page and the repository switcher. */ export const loadRepoSummaries = (): Promise<RepoSummary[]> => source().summaries(); export const loadRepoSummary = (id: string): Promise<RepoSummary> => source().summary(id); +/** One landing-page card per id, without the map or the findings. */ +export const loadRepoCard = (id: string): Promise<RepoCard> => source().card(id); +/** The rank-1 finding of one repository, loaded after its card. */ +export const loadRepoFixFirst = (id: string): Promise<FixFirst | null> => source().fixFirst(id); /** One full repository, fetched once per id. */ export const loadRepo = (id: string): Promise<RepoBundle> => source().repo(id); diff --git a/web/src/main.tsx b/web/src/main.tsx index 8a89a2a5..ab88bad8 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -2,8 +2,6 @@ import "@fontsource-variable/instrument-sans"; import "@fontsource-variable/hanken-grotesk"; import "@fontsource-variable/jetbrains-mono"; import "./styles/globals.css"; -import "./styles/tokens.css"; -import "./styles/base.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..aced1218 --- /dev/null +++ b/web/src/routes/Change.tsx @@ -0,0 +1,15 @@ +import { SectionHead } from "../components/cx/primitives"; +import { useTitle } from "../components/cx/use-page"; +import { useRepo } from "./RepoLayout"; + +/** The Change screen of one repository. */ +export function Change() { + const repo = useRepo(); + useTitle(`Change · ${repo.name}`); + return ( + <section className="flex flex-col gap-4" aria-labelledby="screen-title"> + <SectionHead eyebrow={repo.name} title="Change" id="screen-title" /> + <p className="text-sm text-muted-foreground">This screen is being built.</p> + </section> + ); +} diff --git a/web/src/routes/Decisions.tsx b/web/src/routes/Decisions.tsx new file mode 100644 index 00000000..7e404008 --- /dev/null +++ b/web/src/routes/Decisions.tsx @@ -0,0 +1,15 @@ +import { SectionHead } from "../components/cx/primitives"; +import { useTitle } from "../components/cx/use-page"; +import { useRepo } from "./RepoLayout"; + +/** The Decisions screen of one repository. */ +export function Decisions() { + const repo = useRepo(); + useTitle(`Decisions · ${repo.name}`); + return ( + <section className="flex flex-col gap-4" aria-labelledby="screen-title"> + <SectionHead eyebrow={repo.name} title="Decisions" id="screen-title" /> + <p className="text-sm text-muted-foreground">This screen is being built.</p> + </section> + ); +} diff --git a/web/src/routes/FindingDetail.tsx b/web/src/routes/FindingDetail.tsx new file mode 100644 index 00000000..ca7c810b --- /dev/null +++ b/web/src/routes/FindingDetail.tsx @@ -0,0 +1,33 @@ +import { useParams } from "react-router"; +import { SectionHead } from "../components/cx/primitives"; +import { useTitle } from "../components/cx/use-page"; +import { NotFound } from "./NotFound"; +import { 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 <NotFound what={`${repo.name} has no finding "${slug}".`} />; + return <FindingDetailBody title={finding.title} rank={finding.rank} repoName={repo.name} />; +} + +function FindingDetailBody({ + title, + rank, + repoName, +}: { + title: string; + rank: number; + repoName: string; +}) { + useTitle(`Finding ${rank} · ${repoName}`); + return ( + <section className="flex flex-col gap-4" aria-labelledby="screen-title"> + <SectionHead eyebrow={`Finding ${rank}`} title={title} id="screen-title" /> + <p className="text-sm text-muted-foreground">This screen is being built.</p> + </section> + ); +} diff --git a/web/src/routes/Findings.tsx b/web/src/routes/Findings.tsx new file mode 100644 index 00000000..376401e7 --- /dev/null +++ b/web/src/routes/Findings.tsx @@ -0,0 +1,15 @@ +import { SectionHead } from "../components/cx/primitives"; +import { useTitle } from "../components/cx/use-page"; +import { useRepo } from "./RepoLayout"; + +/** The Findings screen of one repository. */ +export function Findings() { + const repo = useRepo(); + useTitle(`Findings · ${repo.name}`); + return ( + <section className="flex flex-col gap-4" aria-labelledby="screen-title"> + <SectionHead eyebrow={repo.name} title="Findings" id="screen-title" /> + <p className="text-sm text-muted-foreground">This screen is being built.</p> + </section> + ); +} diff --git a/web/src/routes/Landing.tsx b/web/src/routes/Landing.tsx new file mode 100644 index 00000000..0b023927 --- /dev/null +++ b/web/src/routes/Landing.tsx @@ -0,0 +1,258 @@ +import { ArrowUpRight } from "lucide-react"; +import { Link } from "react-router"; +import { NotMeasured } from "../components/cx/badges"; +import { FOCUS, cn } from "../components/cx/cn"; +import { Eyebrow, StatusDot } from "../components/cx/primitives"; +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"; + +const STEPS = [ + [ + "Read the rules", + "Pull decisions from build checks, architecture docs and habits the code measurably keeps.", + ], + [ + "Check every link", + "Resolve imports and calls into a module graph and test each rule against it, snapshot by snapshot.", + ], + [ + "Rank the exceptions", + "Score by size, reach, change pressure, the rule’s authority and ease of the fix. AI reads the code only where numbers can’t decide.", + ], + [ + "Replay the fix", + "Apply each proposed fix to a copy of the module map and report the loops it changes before anyone touches code.", + ], +] as const; + +export function Landing() { + useTitle(null); + const summaries = useLoaded<RepoSummary[]>(() => loadRepoSummaries(), "summaries"); + const all = summaries.state === "ready" ? summaries.value : []; + const real = all.filter((r) => !r.synthetic); + const fixtures = all.filter((r) => r.synthetic); + const dates = [...new Set(real.map((r) => r.snapshotDate).filter((d): d is string => !!d))]; + + return ( + <div className="flex min-h-dvh flex-col"> + <SiteHeader /> + <main id="main" className="flex-1"> + <section className="graph-paper border-b"> + <div className="mx-auto grid max-w-[1320px] gap-10 px-4 py-16 md:px-6 md:py-24 lg:grid-cols-[1.3fr_1fr] lg:items-end"> + <div className="cx-rise flex flex-col gap-6"> + <Eyebrow>Architecture decisions · checked against the code</Eyebrow> + <h1 className="max-w-3xl text-4xl leading-[1.05] font-semibold tracking-tight text-balance md:text-6xl"> + Your team wrote down how the code should fit together.{" "} + <span className="text-accent">Is it still true?</span> + </h1> + <p className="max-w-xl text-lg leading-relaxed text-pretty text-muted-foreground"> + CodeXray measures how well a codebase keeps its own architecture decisions over + time, before and after the team adopted AI coding tools, and tells you which + exceptions to fix first. + </p> + </div> + <ol className="grid gap-px overflow-hidden rounded-lg border bg-border sm:grid-cols-2"> + {STEPS.map(([t, d], i) => ( + <li + key={t} + className="cx-rise flex flex-col gap-1.5 bg-card p-4" + style={{ animationDelay: `${120 + i * 70}ms` }} + > + <span className="font-mono text-[11px] text-muted-foreground">step {i + 1}</span> + <span className="text-sm font-semibold">{t}</span> + <span className="text-xs leading-relaxed text-muted-foreground">{d}</span> + </li> + ))} + </ol> + </div> + </section> + + <section + className="mx-auto flex max-w-[1320px] flex-col gap-6 px-4 py-14 md:px-6" + aria-labelledby="repos" + > + <div className="flex items-end justify-between gap-4 border-b pb-3"> + <h2 id="repos" className="text-xl font-semibold tracking-tight"> + Reports + </h2> + {summaries.state === "ready" && ( + <p className="font-mono text-xs text-muted-foreground"> + {real.length} {real.length === 1 ? "repository" : "repositories"} + {dates.length === 1 && ` · snapshot ${dates[0]}`} + </p> + )} + </div> + {summaries.state === "loading" && ( + <p className="font-mono text-xs text-muted-foreground" aria-live="polite"> + Loading the list of reports… + </p> + )} + {summaries.state === "failed" && ( + <p role="alert" className="text-sm"> + The list of reports could not be loaded.{" "} + <span className="font-mono text-xs text-muted-foreground">{summaries.why}</span> + </p> + )} + {summaries.state === "ready" && real.length === 0 && ( + <p className="text-sm text-muted-foreground"> + No report of a real repository is in bundles/index.json. + </p> + )} + {real.length > 0 && ( + <ul className="grid gap-5 lg:grid-cols-3"> + {real.map((r, i) => ( + <li key={r.id} className="cx-rise" style={{ animationDelay: `${i * 80}ms` }}> + <RepoCardView id={r.id} summary={r} /> + </li> + ))} + </ul> + )} + {fixtures.length > 0 && ( + <p className="font-mono text-[11px] text-muted-foreground"> + Synthetic fixtures, for testing the screens:{" "} + {fixtures.map((r, i) => ( + <span key={r.id}> + {i > 0 && " · "} + <Link + to={repoPath(r.id)} + className={cn("rounded-sm underline hover:text-foreground", FOCUS)} + > + {r.label} + </Link> + </span> + ))} + </p> + )} + </section> + </main> + <SiteFooter>Deterministic numbers, cited AI. Same commit, same report.</SiteFooter> + </div> + ); +} + +function RepoCardView({ id, summary }: { id: string; summary: RepoSummary }) { + const card = useLoaded<RepoCard>(() => loadRepoCard(id), id); + // Loaded after the card's own files, so the card appears without waiting for it. + const top = useLoaded<FixFirst | null>( + () => 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 grain = c?.againstGrainShare ?? null; + const rising = grain && grain.now !== null && grain.before !== null && grain.now > grain.before; + const falling = grain && grain.now !== null && grain.before !== null && grain.now < grain.before; + 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 ( + <Link + to={repoPath(id)} + className={cn( + "group flex h-full flex-col gap-5 rounded-lg border bg-card p-5 transition-shadow hover:shadow-[0_1px_0_var(--border),0_12px_32px_-16px_color-mix(in_oklab,var(--foreground)_30%,transparent)]", + FOCUS, + )} + > + <div className="flex items-start justify-between gap-3"> + <div className="flex min-w-0 flex-col gap-1"> + <span className="text-lg font-semibold tracking-tight break-words">{summary.name}</span> + <span className="flex min-h-4 flex-wrap gap-x-1.5 font-mono text-[11px] text-muted-foreground"> + {[langs, summary.snapshotDate && `snapshot ${summary.snapshotDate}`] + .filter(Boolean) + .map((part, i) => ( + <span key={i} className="whitespace-nowrap"> + {i > 0 && "· "} + {part} + </span> + ))} + </span> + </div> + <ArrowUpRight + className="size-5 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5 group-hover:-translate-y-0.5 group-hover:text-foreground" + aria-hidden + /> + </div> + + <div className="flex min-h-[76px] items-end justify-between gap-4"> + <div className="flex flex-col gap-1"> + <span className="text-xs text-muted-foreground">against the grain</span> + {card.state === "failed" ? ( + <span className="font-mono text-[11px] text-muted-foreground">could not be loaded</span> + ) : !grain ? ( + <span className="font-mono text-3xl font-semibold text-muted-foreground/40">…</span> + ) : grain.now === null ? ( + <NotMeasured /> + ) : ( + <span className="font-mono text-3xl font-semibold tabular">{pct(grain.now)}</span> + )} + {grain && grain.before !== null && grain.now !== null && ( + <span + className={cn( + "font-mono text-[11px] tabular", + rising ? "text-accent" : "text-muted-foreground", + )} + style={falling ? { color: STATUS.holding.color } : undefined} + title={compareDate ? `Value at ${compareDate}` : undefined} + > + {rising ? "▲ " : falling ? "▼ " : ""} + {rising || falling ? "from" : "unchanged from"} {pct(grain.before)} + {compareDate && ` at ${compareDate.slice(0, 7)}`} + </span> + )} + </div> + {grain && ( + <Sparkline + values={grain.series.map((p) => p.value)} + mark={markIndex( + grain.series.map((p) => p.date), + compareDate, + )} + width={130} + height={44} + area + color="var(--accent)" + label={`${summary.name}: against-the-grain share at each snapshot`} + /> + )} + </div> + + <ul className="flex flex-wrap items-center gap-1.5"> + {present.flatMap((s) => + Array.from({ length: counts[s] }, (_, k) => ( + <li key={`${s}-${k}`} title={STATUS[s].label}> + <StatusDot status={s} className="size-2.5" /> + </li> + )), + )} + <li className="ml-1 text-[11px] text-muted-foreground"> + {present.length === 0 + ? "no decision checked" + : present.map((s) => `${counts[s]} ${STATUS[s].label.toLowerCase()}`).join(" · ")} + </li> + </ul> + + <div className="mt-auto flex flex-col gap-1 border-t pt-4"> + <span className="font-mono text-[11px] text-muted-foreground">fix first</span> + <span className="text-sm leading-snug text-pretty"> + {top.state === "ready" ? ( + (top.value?.title ?? "No finding was ranked in this run.") + ) : top.state === "failed" ? ( + <span className="text-muted-foreground">could not be loaded</span> + ) : ( + <span className="text-muted-foreground">Loading…</span> + )} + </span> + </div> + </Link> + ); +} diff --git a/web/src/routes/MapPage.tsx b/web/src/routes/MapPage.tsx new file mode 100644 index 00000000..889d94a6 --- /dev/null +++ b/web/src/routes/MapPage.tsx @@ -0,0 +1,15 @@ +import { SectionHead } from "../components/cx/primitives"; +import { useTitle } from "../components/cx/use-page"; +import { useRepo } from "./RepoLayout"; + +/** The Map screen of one repository. */ +export function MapPage() { + const repo = useRepo(); + useTitle(`Map · ${repo.name}`); + return ( + <section className="flex flex-col gap-4" aria-labelledby="screen-title"> + <SectionHead eyebrow={repo.name} title="Map" id="screen-title" /> + <p className="text-sm text-muted-foreground">This screen is being built.</p> + </section> + ); +} diff --git a/web/src/routes/NotFound.tsx b/web/src/routes/NotFound.tsx new file mode 100644 index 00000000..0f6ffe75 --- /dev/null +++ b/web/src/routes/NotFound.tsx @@ -0,0 +1,30 @@ +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. */ +export function NotFound({ what }: { what?: string }) { + useTitle("Not found"); + return ( + <section className="flex max-w-2xl flex-col gap-4 py-6" aria-labelledby="not-found"> + <Eyebrow>Not found</Eyebrow> + <h1 id="not-found" className="text-3xl font-semibold tracking-tight text-balance"> + There is no page at this address. + </h1> + <p className="text-sm leading-relaxed text-muted-foreground"> + {what ?? "The link may be from another version of the report, or mistyped."} + </p> + <Link + to="/" + className={cn( + "inline-flex items-center gap-1 self-start rounded-sm text-sm font-medium hover:underline", + FOCUS, + )} + > + All reports <ArrowRight className="size-3.5" aria-hidden /> + </Link> + </section> + ); +} diff --git a/web/src/routes/Overview.tsx b/web/src/routes/Overview.tsx new file mode 100644 index 00000000..5e154073 --- /dev/null +++ b/web/src/routes/Overview.tsx @@ -0,0 +1,450 @@ +import { ArrowRight } from "lucide-react"; +import { Fragment, type ReactNode } from "react"; +import { Link } from "react-router"; +import { ComputedMark, NotMeasured } from "../components/cx/badges"; +import { FOCUS, cn } from "../components/cx/cn"; +import { FindingRow } from "../components/cx/finding-row"; +import { OverviewMap } from "../components/cx/overview-map"; +import { Eyebrow, Panel, SectionHead, StatusDot, StatusPill } from "../components/cx/primitives"; +import { Sparkline, markIndex } from "../components/cx/sparkline"; +import { useTitle } from "../components/cx/use-page"; +import { repoPath } from "../cx/address"; +import { STATUS, STATUS_ORDER, fmt, pct, statusCounts } from "../cx/meta"; +import type { Batch, RepoBundle, Status, Yardstick } from "../cx/types"; +import { useRepo } from "./RepoLayout"; + +/** How many "got right" cards the overview shows before linking to all decisions. */ +const HEALTHY_SHOWN = 6; +/** 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(); + useTitle(`Overview · ${repo.name}`); + const compareDate = repo.sponsorDate ?? repo.beforeDate; + + return ( + <div className="flex flex-col gap-14"> + <VerdictBand repo={repo} compareDate={compareDate} /> + + <section className="grid gap-10 xl:grid-cols-[1fr_auto]"> + <DecisionList repo={repo} compareDate={compareDate} /> + <div className="xl:w-[460px]"> + <OverviewMap repo={repo} /> + </div> + </section> + + <BatchBand batch={repo.batch} /> + + <section className="flex flex-col gap-2" aria-labelledby="top-findings"> + <SectionHead + eyebrow="Ranked by size, reach, change pressure, authority and ease" + title="What to fix first" + id="top-findings" + aside={ + <Link to={repoPath(repo.id, "findings")} className={linkCls}> + All {repo.findings.length} findings <ArrowRight className="size-3.5" aria-hidden /> + </Link> + } + /> + {repo.findings.length === 0 ? ( + <p className="py-4 text-sm text-muted-foreground">No finding was ranked in this run.</p> + ) : ( + <ol className="-mx-4 divide-y"> + {repo.findings.slice(0, 5).map((f) => ( + <FindingRow key={f.id} repoId={repo.id} f={f} sponsorDate={compareDate} /> + ))} + </ol> + )} + </section> + + <Healthy repo={repo} /> + </div> + ); +} + +// ---- verdict ---------------------------------------------------------------------------- + +/** "a", "a and b", "a, b and c". */ +function joined(items: ReactNode[]): ReactNode { + return items.map((item, i) => ( + <Fragment key={i}> + {item} + {i < items.length - 2 ? ", " : i === items.length - 2 ? " and " : ""} + </Fragment> + )); +} + +function VerdictSentence({ counts, total }: { counts: Record<Status, number>; 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) => ( + <span key={s} style={{ color: STATUS[s].color }}> + {counts[s]} {STATUS[s].label.toLowerCase()} + </span> + )), + )} + <span className="text-muted-foreground"> + {" — "} + {holding} of {total} still holding. + </span> + </> + ); +} + +/** 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].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); +} + +function YardstickRow({ + label, + hint, + y, + compareDate, +}: { + label: string; + hint: string; + y: Yardstick; + compareDate: string; +}) { + const f = formatter(y); + const change = + y.now === null || y.before === null + ? null + : y.now > y.before + ? "up" + : y.now < y.before + ? "down" + : "same"; + const values = y.series.map((p) => p.value); + return ( + <div className="flex items-center justify-between gap-4 bg-card p-5"> + <div className="flex min-w-0 flex-col gap-1"> + <dt className="text-sm font-medium">{label}</dt> + <p className="text-xs leading-relaxed text-muted-foreground">{hint}</p> + </div> + <dd className="flex shrink-0 flex-col items-end gap-1"> + <Sparkline + values={values} + mark={markIndex( + y.series.map((p) => p.date), + compareDate, + )} + width={84} + height={22} + color={change === "up" ? "var(--accent)" : "var(--primary)"} + label={`${label} at each snapshot, ${y.series[0]?.date ?? ""} to ${y.series.at(-1)?.date ?? ""}`} + /> + {y.now === null ? ( + <NotMeasured /> + ) : ( + <span className="font-mono text-2xl font-semibold tabular">{f(y.now)}</span> + )} + {y.before === null ? ( + <span className="font-mono text-[11px] text-muted-foreground"> + no value at {compareDate.slice(0, 7)} + </span> + ) : ( + <span + title={`Value at ${compareDate}`} + className={cn( + "font-mono text-[11px] tabular", + change === "up" ? "text-accent" : "text-muted-foreground", + )} + style={change === "down" ? { color: STATUS.holding.color } : undefined} + > + {change === "up" ? "▲ " : change === "down" ? "▼ " : ""} + {change === "same" ? "unchanged from" : "from"} {f(y.before)} + </span> + )} + </dd> + </div> + ); +} + +function VerdictBand({ repo, compareDate }: { repo: RepoBundle; compareDate: string }) { + const counts = statusCounts(repo.decisions); + const total = repo.decisions.length; + const y = repo.yardsticks; + return ( + <section className="cx-rise grid gap-8 lg:grid-cols-[1.15fr_1fr]" aria-labelledby="verdict"> + <div className="flex flex-col gap-6"> + <Eyebrow> + Verdict · {total} {total === 1 ? "decision" : "decisions"} checked + </Eyebrow> + <h2 + id="verdict" + className="text-3xl leading-[1.12] font-semibold tracking-tight text-balance md:text-[2.6rem]" + > + <VerdictSentence counts={counts} total={total} /> + </h2> + {total > 0 && ( + <div className="flex flex-col gap-2"> + <div + className="flex h-2.5 overflow-hidden rounded-full bg-muted" + role="img" + aria-label={STATUS_ORDER.map( + (s) => `${counts[s]} ${STATUS[s].label.toLowerCase()}`, + ).join(", ")} + > + {STATUS_ORDER.map( + (s) => + counts[s] > 0 && ( + <div + key={s} + style={{ + width: `${(counts[s] / total) * 100}%`, + background: STATUS[s].color, + }} + className="border-r-2 border-background last:border-r-0" + /> + ), + )} + </div> + <ul className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground"> + {STATUS_ORDER.map((s) => ( + <li key={s} className="flex items-center gap-1.5" title={STATUS[s].hint}> + <StatusDot status={s} /> + {STATUS[s].label}{" "} + <span className="font-mono text-foreground tabular">{counts[s]}</span> + </li> + ))} + </ul> + </div> + )} + <p className="max-w-xl text-sm leading-relaxed text-muted-foreground"> + {repo.adoptionDate ? ( + <> + The team adopted AI coding tools around{" "} + <span className="font-mono text-foreground">{repo.adoptionDate.slice(0, 7)}</span> + .{" "} + </> + ) : ( + <>No adoption date of AI coding tools was detected in this run. </> + )} + Everything below compares the code before and after{" "} + <span className="font-mono text-foreground">{compareDate.slice(0, 7)}</span>. + </p> + </div> + + <dl className="grid gap-px self-start overflow-hidden rounded-lg border bg-border"> + <YardstickRow + label="Links against the grain" + hint="Share of links between modules that point against the main direction of dependencies." + y={y.againstGrainShare} + compareDate={compareDate} + /> + <YardstickRow + label="Module pairs using each other" + hint="Two modules that depend on each other cannot be changed or tested alone." + y={y.twoWayPairs} + compareDate={compareDate} + /> + <YardstickRow + label="Exceptions per 1,000 lines" + hint="Decision exceptions per 1,000 lines of code, for the decisions that apply." + y={y.perKloc} + compareDate={compareDate} + /> + </dl> + </section> + ); +} + +// ---- decisions -------------------------------------------------------------------------- + +function DecisionList({ repo, compareDate }: { repo: RepoBundle; compareDate: string }) { + const ordered = [...repo.decisions].sort( + (a, b) => + STATUS[a.status].order - STATUS[b.status].order || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0), + ); + return ( + <div className="flex min-w-0 flex-col gap-4"> + <SectionHead + eyebrow="Decisions" + title="Rules the code is meant to keep" + aside={ + <Link to={repoPath(repo.id, "decisions")} className={linkCls}> + Details <ArrowRight className="size-3.5" aria-hidden /> + </Link> + } + /> + {ordered.length === 0 ? ( + <p className="text-sm text-muted-foreground">No decision could be checked in this run.</p> + ) : ( + <ul className="flex flex-col divide-y"> + {ordered.map((d) => { + const values = d.series.map((s) => s.conformance); + const lo = Math.min(0.75, ...values); + return ( + <li + key={d.id} + className="grid grid-cols-[1fr_auto] items-center gap-x-4 gap-y-1 py-3 sm:grid-cols-[7.5rem_1fr_auto_auto]" + > + <span className="order-3 sm:order-none"> + <StatusPill status={d.status} /> + </span> + <p className="text-sm leading-snug text-pretty">{d.statement}</p> + <span className="hidden w-[72px] sm:block"> + <Sparkline + values={values} + mark={markIndex( + d.series.map((s) => s.date), + compareDate, + )} + width={72} + height={20} + color={STATUS[d.status].color} + domain={[lo, 1]} + label={`Conformance at each snapshot for ${d.id}`} + /> + {values.length < 2 && ( + <span className="font-mono text-[10px] text-muted-foreground"> + {values.length === 1 ? "one snapshot" : "no series"} + </span> + )} + </span> + <span className="text-right font-mono text-sm font-semibold tabular"> + {pct(d.conformance)} + </span> + </li> + ); + })} + </ul> + )} + </div> + ); +} + +// ---- simulated fix batch ---------------------------------------------------------------- + +function BatchBand({ batch }: { batch: Batch | null }) { + return ( + <section aria-labelledby="batch"> + <Panel className="graph-paper grid gap-6 bg-ink p-6 text-ink-foreground md:grid-cols-[1fr_auto] md:items-center md:p-8"> + <div className="flex flex-col gap-2"> + <p className="flex items-center gap-3 font-mono text-[11px] tracking-[0.14em] uppercase opacity-60"> + Simulated fix batch + </p> + {batch ? ( + <> + <h2 id="batch" className="text-2xl font-semibold tracking-tight text-balance"> + Apply the {fmt(batch.fixesApplied)} simulated{" "} + {batch.fixesApplied === 1 ? "fix" : "fixes"} and module loops{" "} + {batch.loopsAfter === batch.loopsBefore + ? `stay at ${fmt(batch.loopsBefore)}` + : `go from ${fmt(batch.loopsBefore)} to ${fmt(batch.loopsAfter)}`} + . + </h2> + <p className="max-w-2xl text-sm leading-relaxed opacity-70"> + Every cheap-loop fix whose own simulation succeeded with no new exception is applied + together, on a copy of the module map. Nothing is applied to the code. + {batch.fixesSkipped > 0 && + ` ${fmt(batch.fixesSkipped)} ${batch.fixesSkipped === 1 ? "fix was" : "fixes were"} left out.`} + {batch.newExceptions.length > 0 && + ` The batch creates ${fmt(batch.newExceptions.length)} new ${batch.newExceptions.length === 1 ? "exception" : "exceptions"}.`} + </p> + </> + ) : ( + <h2 id="batch" className="text-2xl font-semibold tracking-tight text-balance"> + Not simulated in this run. + </h2> + )} + </div> + {batch && ( + <dl className="grid grid-cols-3 gap-x-6 gap-y-4 font-mono sm:grid-cols-5"> + {( + [ + ["loops", `${fmt(batch.loopsBefore)}→${fmt(batch.loopsAfter)}`], + ["links cut", fmt(batch.linksRemoved)], + ["links added", fmt(batch.linksAdded)], + ["applied", fmt(batch.fixesApplied)], + ["skipped", fmt(batch.fixesSkipped)], + ] as const + ).map(([k, v]) => ( + <div key={k} className="flex flex-col gap-1"> + <dt className="text-[11px] opacity-60">{k}</dt> + <dd className="text-2xl font-semibold tabular">{v}</dd> + </div> + ))} + </dl> + )} + </Panel> + </section> + ); +} + +// ---- healthy ---------------------------------------------------------------------------- + +function Healthy({ repo }: { repo: RepoBundle }) { + if (repo.healthy.length === 0) return null; + const shown = repo.healthy.slice(0, HEALTHY_SHOWN); + return ( + <section className="flex flex-col gap-4" aria-labelledby="healthy"> + <SectionHead + eyebrow="Still holding" + title="What the team got right" + id="healthy" + aside={ + repo.healthy.length > shown.length && ( + <Link to={repoPath(repo.id, "decisions")} className={linkCls}> + All {repo.healthy.length} holding decisions{" "} + <ArrowRight className="size-3.5" aria-hidden /> + </Link> + ) + } + /> + <ul className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3"> + {shown.map((h) => { + const d = repo.decisions.find((x) => x.id === h.decisionId); + return ( + <li + key={h.decisionId} + className="flex min-w-0 flex-col gap-2 rounded-lg border bg-card p-4" + > + <div className="flex items-center justify-between gap-2"> + {d && <StatusPill status={d.status} />} + {d && ( + <span className="font-mono text-sm font-semibold tabular"> + {pct(d.conformance)} + </span> + )} + </div> + <p className="text-sm font-medium text-pretty">{d?.statement ?? h.decisionId}</p> + <p className="text-xs leading-relaxed text-muted-foreground [overflow-wrap:anywhere]"> + {h.evidence} <ComputedMark className="ml-0.5 align-middle" /> + </p> + </li> + ); + })} + </ul> + </section> + ); +} diff --git a/web/src/routes/RepoLayout.tsx b/web/src/routes/RepoLayout.tsx new file mode 100644 index 00000000..d1e5bf74 --- /dev/null +++ b/web/src/routes/RepoLayout.tsx @@ -0,0 +1,223 @@ +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 { SiteFooter, SiteHeader } from "../components/cx/site-header"; +import { useLoaded, useTitle } from "../components/cx/use-page"; +import { loadRepo, loadRepoList } from "../data/repo"; +import { NotFound } from "./NotFound"; + +interface RepoContext { + repo: RepoBundle; +} + +/** + * 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<RepoContext>().repo; +} + +const TABS: { tab?: RepoTab; label: string }[] = [ + { label: "Overview" }, + { tab: "decisions", label: "Decisions" }, + { tab: "findings", label: "Findings" }, + { tab: "map", label: "Map" }, + { tab: "change", label: "Change" }, + { tab: "trust", label: "Trust" }, + { tab: "size", label: "Size" }, +]; + +type Load = { state: "missing" } | { state: "found"; repo: RepoBundle }; + +export function RepoLayout() { + const id = useParams().repo ?? ""; + const loaded = useLoaded<Load>(async () => { + const list = await loadRepoList(); + if (!list.some((b) => b.repo_id === id)) return { state: "missing" }; + return { state: "found", repo: await loadRepo(id) }; + }, id); + + const repo = + loaded.state === "ready" && loaded.value.state === "found" ? loaded.value.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 ( + <div className="flex min-h-dvh flex-col"> + <SiteHeader /> + <main className="mx-auto w-full max-w-[1320px] flex-1 px-4 py-8 md:px-6 md:py-10"> + <NotFound what={`No repository "${id}" is listed in bundles/index.json.`} /> + </main> + <SiteFooter>Deterministic numbers, cited AI. Same commit, same report.</SiteFooter> + </div> + ); + } + + return ( + <div className="flex min-h-dvh flex-col"> + <SiteHeader current={id} /> + {loaded.state === "loading" && ( + <main className="mx-auto w-full max-w-[1320px] flex-1 px-4 py-10 md:px-6"> + <p className="font-mono text-xs text-muted-foreground" aria-live="polite"> + Loading the {id} report… + </p> + </main> + )} + {loaded.state === "failed" && ( + <main className="mx-auto w-full max-w-[1320px] flex-1 px-4 py-10 md:px-6"> + <div role="alert" className="flex max-w-2xl flex-col gap-2 rounded-lg border bg-card p-5"> + <p className="font-semibold">The {id} report could not be loaded.</p> + <p className="font-mono text-xs text-muted-foreground">{loaded.why}</p> + <Link to="/" className={cn("self-start rounded-sm text-sm underline", FOCUS)}> + Back to all reports + </Link> + </div> + </main> + )} + {repo && <RepoBody repo={repo} />} + </div> + ); +} + +function RepoBody({ repo }: { repo: RepoBundle }) { + const modules = repo.modules.filter((m) => m.presentAtEnd).length; + const langs = + repo.languages.length > 3 + ? `${repo.languages.slice(0, 3).join(" + ")} +${repo.languages.length - 3}` + : 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 }; + return ( + <> + <div className="border-b"> + <div className="mx-auto flex max-w-[1320px] flex-col gap-4 px-4 pt-6 md:px-6"> + <div className="flex flex-col gap-3 md:flex-row md:items-end md:justify-between"> + <div className="flex min-w-0 flex-col gap-1.5"> + <h1 className="text-2xl font-semibold tracking-tight break-words md:text-3xl"> + {repo.name} + </h1> + <p + className="flex flex-wrap gap-x-1.5 font-mono text-xs text-muted-foreground" + title={repo.languages.join(", ")} + > + {facts.map((f, i) => ( + <span key={i} className="whitespace-nowrap"> + {i > 0 && "· "} + {f} + </span> + ))} + </p> + </div> + <dl className="flex shrink-0 flex-wrap gap-x-5 gap-y-1 font-mono text-[11px] text-muted-foreground"> + <div className="flex gap-1.5"> + <dt>snapshot</dt> + <dd className="text-foreground tabular">{repo.snapshotDate}</dd> + </div> + <div className="flex gap-1.5"> + <dt>commit</dt> + <dd className="text-foreground tabular" title={repo.endSha}> + {repo.endSha.slice(0, 10)} + </dd> + </div> + <div className="flex gap-1.5"> + <dt>params</dt> + <dd className="text-foreground tabular" title={repo.paramsHash}> + {repo.paramsHash.slice(0, 8)} + </dd> + </div> + <div className="flex gap-1.5"> + <dt>rules</dt> + {repo.rulesHash ? ( + <dd className="text-foreground tabular" title={repo.rulesHash}> + {repo.rulesHash.slice(0, 8)} + </dd> + ) : ( + <dd className="italic">not in bundle</dd> + )} + </div> + </dl> + </div> + {repo.synthetic && ( + <p + role="note" + className="rounded-md border border-dashed border-foreground/40 bg-muted px-3 py-2 text-sm" + > + <strong className="font-semibold">Synthetic fixture data.</strong>{" "} + <span className="text-muted-foreground"> + This bundle is made up to test the pipeline and the screens. It describes no real + project. + </span> + </p> + )} + <RepoNav + repoId={repo.id} + counts={{ Decisions: repo.decisions.length, Findings: repo.findings.length }} + /> + </div> + </div> + <main id="main" className="mx-auto w-full max-w-[1320px] flex-1 px-4 py-8 md:px-6 md:py-10"> + <Outlet context={context} /> + </main> + <SiteFooter> + Every number on this page comes from a stored result for commit{" "} + <span title={repo.endSha}>{repo.endSha.slice(0, 7)}</span>. AI text is cited and checked. + </SiteFooter> + </> + ); +} + +function RepoNav({ repoId, counts }: { repoId: string; counts: Record<string, number> }) { + const path = useLocation().pathname; + const base = repoPath(repoId); + return ( + <nav aria-label="Report sections" className="-mb-px flex gap-1 overflow-x-auto"> + {TABS.map((t) => { + const href = repoPath(repoId, t.tab); + const active = t.tab + ? path === href || path.startsWith(`${href}/`) + : path === base || path === `${base}/`; + return ( + <Link + key={t.label} + to={href} + aria-current={active ? "page" : undefined} + className={cn( + "flex items-center gap-1.5 border-b-2 px-3 py-2.5 text-sm whitespace-nowrap transition-colors", + active + ? "border-foreground font-medium text-foreground" + : "border-transparent text-muted-foreground hover:text-foreground", + FOCUS, + )} + > + {t.label} + {counts[t.label] !== undefined && ( + <span + className={cn( + "rounded-sm px-1 font-mono text-[10px] tabular", + active ? "bg-foreground text-background" : "bg-muted", + )} + > + {counts[t.label]} + </span> + )} + </Link> + ); + })} + </nav> + ); +} diff --git a/web/src/routes/Size.tsx b/web/src/routes/Size.tsx new file mode 100644 index 00000000..51b9d771 --- /dev/null +++ b/web/src/routes/Size.tsx @@ -0,0 +1,15 @@ +import { SectionHead } from "../components/cx/primitives"; +import { useTitle } from "../components/cx/use-page"; +import { useRepo } from "./RepoLayout"; + +/** The Size screen of one repository. */ +export function Size() { + const repo = useRepo(); + useTitle(`Size · ${repo.name}`); + return ( + <section className="flex flex-col gap-4" aria-labelledby="screen-title"> + <SectionHead eyebrow={repo.name} title="Size" id="screen-title" /> + <p className="text-sm text-muted-foreground">This screen is being built.</p> + </section> + ); +} diff --git a/web/src/routes/Trust.tsx b/web/src/routes/Trust.tsx new file mode 100644 index 00000000..4f43cb9a --- /dev/null +++ b/web/src/routes/Trust.tsx @@ -0,0 +1,15 @@ +import { SectionHead } from "../components/cx/primitives"; +import { useTitle } from "../components/cx/use-page"; +import { useRepo } from "./RepoLayout"; + +/** The Trust screen of one repository. */ +export function Trust() { + const repo = useRepo(); + useTitle(`Trust · ${repo.name}`); + return ( + <section className="flex flex-col gap-4" aria-labelledby="screen-title"> + <SectionHead eyebrow={repo.name} title="Trust" id="screen-title" /> + <p className="text-sm text-muted-foreground">This screen is being built.</p> + </section> + ); +} From c9e0a95ac5b28eab134a3a146ea3d43909b46653 Mon Sep 17 00:00:00 2001 From: Pranav Mathad <pranavmathad807@gmail.com> Date: Sun, 29 Nov 2026 05:41:06 +0100 Subject: [PATCH 03/18] Add the findings, map, decisions, change, trust and size screens --- web/src/components/cx/closeup.tsx | 256 ++++++ web/src/components/cx/code-block.tsx | 509 ++++++++++++ web/src/components/cx/code-highlight.ts | 85 ++ web/src/components/cx/finding-fix.ts | 56 ++ web/src/components/cx/finding-list-row.tsx | 191 +++++ web/src/components/cx/map-controls.tsx | 276 +++++++ web/src/components/cx/map-model.ts | 155 ++++ web/src/components/cx/matrix.tsx | 900 +++++++++++++++++++++ web/src/components/cx/overview-map.tsx | 77 +- web/src/components/cx/series-chart.tsx | 273 +++++++ web/src/cx/address.ts | 26 +- web/src/cx/meta.ts | 6 + web/src/cx/types.ts | 21 + web/src/data/adapt.ts | 22 + web/src/routes/Change.tsx | 388 ++++++++- web/src/routes/Decisions.tsx | 338 +++++++- web/src/routes/FindingDetail.tsx | 168 +++- web/src/routes/Findings.tsx | 241 +++++- web/src/routes/MapPage.tsx | 210 ++++- web/src/routes/Size.tsx | 457 ++++++++++- web/src/routes/Trust.tsx | 370 ++++++++- web/src/routes/change/drift.tsx | 242 ++++++ web/src/routes/change/events.tsx | 177 ++++ web/src/routes/change/evidence.tsx | 81 ++ web/src/routes/decisions/show-more.tsx | 56 ++ web/src/routes/finding/Rail.tsx | 235 ++++++ web/src/routes/finding/Reading.tsx | 212 +++++ web/src/routes/map/CellPanel.tsx | 269 ++++++ web/src/routes/map/ChangePanels.tsx | 347 ++++++++ web/src/routes/map/ModulePanel.tsx | 161 ++++ web/src/routes/size/scale.tsx | 57 ++ web/src/routes/size/tree.ts | 168 ++++ web/src/routes/size/treemap.tsx | 162 ++++ 33 files changed, 7115 insertions(+), 77 deletions(-) create mode 100644 web/src/components/cx/closeup.tsx create mode 100644 web/src/components/cx/code-block.tsx create mode 100644 web/src/components/cx/code-highlight.ts create mode 100644 web/src/components/cx/finding-fix.ts create mode 100644 web/src/components/cx/finding-list-row.tsx create mode 100644 web/src/components/cx/map-controls.tsx create mode 100644 web/src/components/cx/map-model.ts create mode 100644 web/src/components/cx/matrix.tsx create mode 100644 web/src/components/cx/series-chart.tsx create mode 100644 web/src/routes/change/drift.tsx create mode 100644 web/src/routes/change/events.tsx create mode 100644 web/src/routes/change/evidence.tsx create mode 100644 web/src/routes/decisions/show-more.tsx create mode 100644 web/src/routes/finding/Rail.tsx create mode 100644 web/src/routes/finding/Reading.tsx create mode 100644 web/src/routes/map/CellPanel.tsx create mode 100644 web/src/routes/map/ChangePanels.tsx create mode 100644 web/src/routes/map/ModulePanel.tsx create mode 100644 web/src/routes/size/scale.tsx create mode 100644 web/src/routes/size/tree.ts create mode 100644 web/src/routes/size/treemap.tsx diff --git a/web/src/components/cx/closeup.tsx b/web/src/components/cx/closeup.tsx new file mode 100644 index 00000000..a0ff4538 --- /dev/null +++ b/web/src/components/cx/closeup.tsx @@ -0,0 +1,256 @@ +// 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 ( + <p className="py-6 text-sm leading-relaxed text-muted-foreground"> + The bundle holds no stored layout for this finding, so no close-up is drawn. + </p> + ); + } + 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 ( + <svg + viewBox={`0 0 ${W} ${H}`} + className="h-auto w-full" + role="img" + aria-label={`Close-up of ${boxes.map((b) => b.label).join(", ")}: ${arrows.length} links between them`} + > + <defs> + <marker + id="cx-closeup-ah" + viewBox="0 0 8 8" + refX="7" + refY="4" + markerUnits="userSpaceOnUse" + markerWidth="8" + markerHeight="8" + orient="auto-start-reverse" + > + <path d="M0,0 L8,4 L0,8 z" fill="context-stroke" /> + </marker> + </defs> + {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 ( + <g key={cellKey(e.src, e.dst)} opacity={e.hot ? 1 : 0.35}> + <title>{`${at.get(e.src)!.label} uses ${at.get(e.dst)!.label}: ${e.count} ${e.count === 1 ? "link" : "links"}, ${e.against ? "against" : "with"} the grain`} + + + {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 +
    • +
    • + + with the grain +
    • +
    • + + against the grain +
    • + {partners && ( +
    • + + changed together, no link +
    • + )} +
    + ); +} diff --git a/web/src/components/cx/code-block.tsx b/web/src/components/cx/code-block.tsx new file mode 100644 index 00000000..db7ddd83 --- /dev/null +++ b/web/src/components/cx/code-block.tsx @@ -0,0 +1,509 @@ +// 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 askRoot = () => setEditing(true); + const shown = files.slice(0, OPEN_FILES); + const listed = files.slice(OPEN_FILES); + + 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 && ( +
    +

    + {listed.length} more {listed.length === 1 ? "file" : "files"} · open one to read its + lines +

    +
      + {listed.map((g) => { + const open = opened.has(g.key); + return ( +
    • + + {open && ( +
      + +
      + )} +
    • + ); + })} +
    +
    + )} + {commits.map((ev) => ( + + ))} +
    + ); +} + +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}. + )} + +

    + ); + } + const submit = (e: FormEvent) => { + e.preventDefault(); + onSave(draft); + }; + return ( +
    + + setDraft(e.target.value)} + placeholder="/home/you/src/project" + spellCheck={false} + className={cn( + "min-w-0 flex-1 rounded-md border bg-card px-2 py-1 font-mono text-xs sm:max-w-sm", + FOCUS, + )} + /> + + + + Kept in this browser only. The bundle holds no local path. + +
    + ); +} + +function FileBlock({ + repo, + group, + root, + onAskRoot, +}: { + repo: RepoBundle; + group: FileGroup; + root: string | null; + onAskRoot: () => void; +}) { + 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)} +
    +
    + {host && repo.host && ( + + + {hostName(repo.host)} @ {repo.endSha.slice(0, 7)} + + )} + {editor ? ( + + + Editor + + ) : ( + + )} +
    +
    + {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 && ( +
    + + +
    + )} + + ); +} + +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 && ( +
    + +
    + )} +
    + ); +} diff --git a/web/src/components/cx/code-highlight.ts b/web/src/components/cx/code-highlight.ts new file mode 100644 index 00000000..86472ba1 --- /dev/null +++ b/web/src/components/cx/code-highlight.ts @@ -0,0 +1,85 @@ +// 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..f261b1b3 --- /dev/null +++ b/web/src/components/cx/finding-list-row.tsx @@ -0,0 +1,191 @@ +// 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/map-controls.tsx b/web/src/components/cx/map-controls.tsx new file mode 100644 index 00000000..4fdbfc61 --- /dev/null +++ b/web/src/components/cx/map-controls.tsx @@ -0,0 +1,276 @@ +// 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 { NotMeasured } from "./badges"; +import { FOCUS, cn } from "./cn"; + +export const GRID_ORDER_NOTE = + "The grid uses one module order for both dates so the picture does not move. Yardstick totals use each date's own order, so they can differ from a count of the cells below the diagonal."; + +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 ( + + ); + })} +
    + {!repo.batch && ( + + after fixes: not simulated in this run + + )} +
    + ); +} + +function Value({ + value, + format, + className, +}: { + value: number | null; + format: (v: number) => string; + className?: string; +}) { + return value === null ? ( + + ) : ( + {format(value)} + ); +} + +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. + */ +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; + return ( +
    +
    +
    loops in this simulation
    +
    + {s.loopsBefore === null || s.loopsAfter === null ? ( + + ) : ( + + {fmt(s.loopsBefore)} → {fmt(s.loopsAfter)} + + )} +
    +
    +
    + ); + } + if (view === "after") { + const b = repo.batch; + return ( +
    +
    +
    loops, simulation's count
    +
    + {b ? ( + + {fmt(b.loopsBefore)} → {fmt(b.loopsAfter)} + + ) : ( + + )} +
    +
    +
    +
    against grain after fixes
    +
    + +
    +
    +
    + ); + } + const share = at(y.againstGrainShare, view); + const links = at(y.againstGrain, view); + const pairs = at(y.twoWayPairs, view); + return ( +
    +
    +
    against grain
    +
    + pct(v)} className="text-accent" /> + {!small && links !== null && ( + · {fmt(links)} links + )} +
    +
    +
    +
    two-way 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 ( +
      +
    • + with the grain +
    • +
    • + against the grain +
    • +
    • + + + + + 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..f2a47e44 --- /dev/null +++ b/web/src/components/cx/matrix.tsx @@ -0,0 +1,900 @@ +// 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 ? "against" : "with"} the grain`; + 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]) => ( + + ))} +
    +
    + )} +
    +
    +
    +
    +
    + + {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 ? "against the grain" : "with the grain"} + + + )} + {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 ? "against the grain" : "with the grain"} + + )} + + )} +

    + {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 index bacc05c4..a3f9e1c3 100644 --- a/web/src/components/cx/overview-map.tsx +++ b/web/src/components/cx/overview-map.tsx @@ -1,16 +1,21 @@ import { ArrowRight } from "lucide-react"; -import { Link } from "react-router"; -import { repoPath } from "../../cx/address"; -import { fmt, pct } from "../../cx/meta"; +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 { NotMeasured } from "./badges"; import { FOCUS, cn } from "./cn"; +import { GridNumbers, MapLegend, ViewToggle, viewLabel } from "./map-controls"; +import { gridMax, pictureFor, topFindingCells } from "./map-model"; +import { Matrix } from "./matrix"; import { SectionHead } from "./primitives"; -/** The small map on the Overview. For now: the stored grain numbers and a link to the Map. */ +/** The small grid on the Overview; a cell opens the Map with that cell selected. */ export function OverviewMap({ repo }: { repo: RepoBundle }) { - const share = repo.yardsticks.againstGrainShare.now; - const pairs = repo.yardsticks.twoWayPairs.now; + 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 (
    } /> -

    - - against grain{" "} - {share === null ? ( - - ) : ( - {pct(share)} - )} - - - two-way pairs{" "} - {pairs === null ? ( - - ) : ( - {fmt(pairs)} - )} - -

    +
    + + +
    +
    + { + 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. +

    + )} +
    +

    + Hover or focus a cell. Rows use columns. Click to open it on the Map. +

    + 0} /> +
    ); } diff --git a/web/src/components/cx/series-chart.tsx b/web/src/components/cx/series-chart.tsx new file mode 100644 index 00000000..aa116a97 --- /dev/null +++ b/web/src/components/cx/series-chart.tsx @@ -0,0 +1,273 @@ +// A small line chart over dated snapshots with two labelled vertical marks: the sponsor 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"; + 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 ("sponsor", "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", + day: dayOf(sponsorDate), + label: compact ? "sponsor" : `sponsor ${sponsorDate}`, + dash: "3 3", + }); + } + if (adoptionDate) { + marks.push({ + key: "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.key} date marked`), + ...outside.map((m) => `${m.key} 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")} + sponsor date{" "} + {sponsorDate ?? "not in the bundle"} +
    • +
    • + {sample("1 2")} + detected adoption date{" "} + {adoptionDate ? ( + {adoptionDate} + ) : ( + not detected in this run + )} +
    • +
    + ); +} diff --git a/web/src/cx/address.ts b/web/src/cx/address.ts index 5d45a01d..875c740a 100644 --- a/web/src/cx/address.ts +++ b/web/src/cx/address.ts @@ -24,6 +24,10 @@ 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 => @@ -55,11 +59,26 @@ export function readMapCell( 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) }; + 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. @@ -68,12 +87,15 @@ const queryValue = (v: string) => /** * The search string for a Map state, for example "?view=before&cell=M:a,M:b". The default - * view and an empty cell are left out; with nothing to say it returns "". + * 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("&")}` : ""; } diff --git a/web/src/cx/meta.ts b/web/src/cx/meta.ts index 74be63e4..0a103066 100644 --- a/web/src/cx/meta.ts +++ b/web/src/cx/meta.ts @@ -132,6 +132,12 @@ export function hostLink( 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. diff --git a/web/src/cx/types.ts b/web/src/cx/types.ts index 05e30dfb..9cddc96d 100644 --- a/web/src/cx/types.ts +++ b/web/src/cx/types.ts @@ -121,6 +121,20 @@ export interface WrittenDecision { 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`. */ @@ -221,6 +235,11 @@ export interface Finding { 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. */ @@ -401,6 +420,8 @@ export interface RepoBundle { 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. */ diff --git a/web/src/data/adapt.ts b/web/src/data/adapt.ts index d0360b41..29610802 100644 --- a/web/src/data/adapt.ts +++ b/web/src/data/adapt.ts @@ -11,6 +11,7 @@ import type { Decision, DecisionPoint, Evidence, + FileSize, Finding, Judgement, ModuleInfo, @@ -353,6 +354,7 @@ export function adaptBundle(bundle: Bundle): RepoBundle { 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) { @@ -420,6 +422,8 @@ export function adaptBundle(bundle: Bundle): RepoBundle { 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); @@ -458,6 +462,7 @@ export function adaptBundle(bundle: Bundle): RepoBundle { 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; } @@ -550,6 +555,22 @@ export function adaptBundle(bundle: Bundle): RepoBundle { }); 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 { @@ -628,5 +649,6 @@ export function adaptBundle(bundle: Bundle): RepoBundle { })), healthy, snapshots: index.snapshots.map((s) => s.date).sort(byText), + fileSizes: fileSizes.length > 0 ? fileSizes : null, }; } diff --git a/web/src/routes/Change.tsx b/web/src/routes/Change.tsx index aced1218..14ca7544 100644 --- a/web/src/routes/Change.tsx +++ b/web/src/routes/Change.tsx @@ -1,15 +1,393 @@ -import { SectionHead } from "../components/cx/primitives"; +import { ArrowRight } from "lucide-react"; +import { Link } from "react-router"; +import { AiBadge, ComputedMark, NotMeasured } from "../components/cx/badges"; +import { FOCUS, cn } from "../components/cx/cn"; +import { Eyebrow, 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 { LabelChip, StructuralEvents, labelCounts } from "./change/events"; +import { ShowMoreButton, useShowMore } from "./decisions/show-more"; import { useRepo } from "./RepoLayout"; -/** The Change screen of one repository. */ +/** Hotspots and new links shown before "Show all". */ +const FIRST = 8; + +const pathLinkCls = cn("rounded-sm hover:underline decoration-border underline-offset-2", FOCUS); + +/** The Change screen: before and after the sponsor date (spec.md §12), descriptive only. */ export function Change() { const repo = useRepo(); useTitle(`Change · ${repo.name}`); return ( -
    - -

    This screen is being built.

    +
    +
    + + + +
    + + +
    + +
    + ); +} + +function Header({ repo }: { repo: RepoBundle }) { + const series = repo.aiShareSeries; + return ( +
    +
    + Change +

    + What moved in the structure around the sponsor date, and whether anyone meant it to. +

    +
    +
    +
    Sponsor date:
    +
    + {repo.sponsorDate ?? } +
    +
    +
    +
    Detected adoption date:
    +
    + {repo.adoptionDate ?? ( + not detected in this run + )} +
    +
    +
    +
    Adoption evidence:
    +
    {repo.adoptionEvidence ?? }
    +
    +
    +
    + +
    +

    Share of commits with an explicit AI marker

    + {series && series.length > 0 && ( +

    + {pct(series.at(-1)!.value, 0)} +

    + )} +
    + {series ? ( + p.value), 0.1)]} + label="Share of commits with an explicit AI marker" + /> + ) : ( +
    + +
    + )} +

    + Markers are a lower bound: a commit without one has no AI signal, nothing more. +

    +
    +
    + ); +} + +function Note() { + return ( + + ); +} + +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 ( +
    + +
    +

    + Rule (spec §12.2): z = (recent − prior) ÷ √(prior + 1) of at least 3, with at least 2 + changes per month recently; new files and restructuring commits are left out. +

    +

    + recent: changes in the last 3 months.{" "} + prior: expected changes in 3 months, + from the months before. The bar is z. +

    +
    + {repo.hotspots.length === 0 ? ( +

    No file met the rule in this run.

    + ) : ( + <> +
      + {shown.map((h) => { + const parts = h.path.split("/"); + const file = parts.pop() ?? h.path; + const dir = parts.join("/"); + const href = hostLink(repo, h.path); + return ( +
    • +
      + + {href ? ( + + {file} + + ) : ( + file + )} + + + prior {h.prior.toFixed(2)}{" "} + {" "} + recent{" "} + {fmt(h.recent)} + +
      + {dir && ( + + {dir}/ + + )} +
      + + {h.moduleName ?? "no module"} + + + + + + z {h.z.toFixed(1)} + +
      +
    • + ); + })} +
    + + + )} +
    + ); +} + +/** 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); + return ( +
    + +
    +

    + {fmt(added.length)} new {added.length === 1 ? "link" : "links"} between modules:{" "} + {fmt(c.planned)} planned, {fmt(c.none)} with no stated intent. Each one's evidence is + listed under structural events. +

    +

    + Against the written plan (expected and found, found but not expected, expected but + missing): +

    +
    + {added.length === 0 ? ( +

    No new link between modules in this run.

    + ) : ( + <> + + + + )} +
    + ); +} + +function AiRisk({ repo }: { repo: RepoBundle }) { + const sponsor = repo.sponsorDate ?? repo.beforeDate; + return ( +
    +
    + + {repo.aiRisk === null ? ( + + +

    + The comparison of AI-marked and no-signal changes by size band is not in this bundle. +

    +
    + ) : ( +
    + + + + + + + + + + {repo.aiRisk.map((r) => ( + + + + + + ))} + +
    change sizeAI-markedno signal
    {r.band} + {r.aiMarked.toFixed(3)}{" "} + n={fmt(r.aiCount)} + + {r.noSignal.toFixed(3)}{" "} + n={fmt(r.noSignalCount)} +
    +
    + )} +
    + +
    + } + /> +

    + Each evidence line is credited to the last change that touched it, which is not always the + change that first wrote it. The marked share counts explicit AI markers only, so it is a + lower bound. +

    + {repo.findings.length === 0 ? ( +

    No finding was ranked in this run.

    + ) : ( + + + + + + + + + + + + {repo.findings.map((f) => ( + + + + + + + ))} + +
    + rank + + finding + + lines last changed after {sponsor} + + lines with an AI marker (lower bound) +
    + {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 index 7e404008..e6cd1588 100644 --- a/web/src/routes/Decisions.tsx +++ b/web/src/routes/Decisions.tsx @@ -1,15 +1,343 @@ -import { SectionHead } from "../components/cx/primitives"; +import { ArrowRight } from "lucide-react"; +import { Link } from "react-router"; +import { AiBadge, ComputedMark, NotMeasured } from "../components/cx/badges"; +import { FOCUS, cn } from "../components/cx/cn"; +import { FindingRow } from "../components/cx/finding-row"; +import { Chip, Eyebrow, SectionHead, 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"; -/** The Decisions screen of one repository. */ +/** Written, not checkable statements shown before "Show all". */ +const WRITTEN_SHOWN = 10; +/** Ranked findings shown below the decisions. */ +const FINDINGS_SHOWN = 5; + +const byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0); + +const linkCls = cn( + "inline-flex items-center gap-1 rounded-sm text-foreground hover:underline", + FOCUS, +); +const sourceLinkCls = cn( + "rounded-sm text-foreground underline decoration-border underline-offset-2 hover:decoration-foreground", + FOCUS, +); + +/** The Decisions screen (spec.md §10.2 screen 1): every rule, then what to fix first. */ export function Decisions() { const repo = useRepo(); useTitle(`Decisions · ${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 ( +
    +
    + + Decisions · {fmt(list.length)} checked + {repo.written.length > 0 && ` · ${fmt(repo.written.length)} not checkable`} + +

    + Each rule is one of four shapes, checked against every link in the code. +

    +

    + Rules come from what the project enforces in its build, what its docs say, and habits the + code measurably keeps. Conformance is the share of links where the rule could apply and is + kept. +

    +
    + + + + {list.length === 0 ? ( +

    No decision could be checked in this run.

    + ) : ( +
      + {list.map((d) => ( + + ))} +
    + )} + +
    + 0 && ( + + All {fmt(repo.findings.length)} findings{" "} + + + ) + } + /> + {repo.findings.length === 0 ? ( +

    No finding was ranked in this run.

    + ) : ( +
      + {repo.findings.slice(0, FINDINGS_SHOWN).map((f) => ( + + ))} +
    + )} +
    + + +
    + ); +} + +function StatusLegend({ decisions, compareDate }: { decisions: Decision[]; compareDate: string }) { + const counts = statusCounts(decisions); + return ( +
    +

    + Legend +

    +
      + {STATUS_ORDER.map((s) => ( +
    • + + + + {STATUS[s].label}{" "} + {counts[s]} + + {STATUS[s].hint} + +
    • + ))} +
    +

    + Statuses are checked in this order and the first match wins (spec §9.2). Each trend line + runs over the stored snapshots; the dashed line marks{" "} + {compareDate}. +

    +
    + ); +} + +function Provenance({ d }: { d: Pick }) { + if (d.proposedBy === "ai") { + return ( + + + {d.reviewed ? "AI-proposed · reviewed" : "AI-proposed · unreviewed"} + + + + ); + } + return {d.proposedBy === "computed" ? "computed" : "written 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 DecisionCard({ + repo, + d, + compareDate, +}: { + repo: RepoBundle; + d: Decision; + compareDate: string; +}) { + const findings = repo.findings.filter((f) => f.decisionId === d.id); + const values = d.series.map((s) => s.conformance); + const dates = d.series.map((s) => s.date); + const mark = markIndex(dates, compareDate); + const width = 240; + // Where the sparkline draws the dashed mark, as a share of its width. + const markAt = + mark !== undefined && values.length > 1 + ? (2 + (mark * (width - 4)) / (values.length - 1)) / width + : null; return ( -
    - -

    This screen is being built.

    +
  • +
    +
    + + {SHAPE[d.shape]} + {SOURCE[d.source.kind]} + +
    +

    + {d.statement} +

    +

    + {d.id} · source{" "} + {" "} + · authority{" "} + {d.authority === null ? ( + + ) : ( + {d.authority.toFixed(2)} + )} +

    + {d.argList.length > 0 && ( +
    + {d.argList.map(({ key, values: v }) => ( +
    +
    {key} =
    +
    {v.join(", ")}
    +
    + ))} +
    + )} +
    + {( + [ + ["exceptions", fmt(d.exceptions)], + ["opportunities", fmt(d.opportunities)], + ["per 1,000 lines", d.perKloc.toFixed(2)], + ["modules covered", fmt(d.modulesCovered)], + ["allowed exceptions", fmt(d.allowed)], + ] as const + ).map(([k, v]) => ( +
    +
    {k}
    +
    {v}
    +
    + ))} +
    + {findings.length > 0 && ( +
      + {findings.map((f) => ( +
    • + + #{f.rank} + {f.title} + +
    • + ))} +
    + )} +
    +
    +
    +
    + Conformance + + {pct(d.conformance)} + +
    +

    + {fmt(d.exceptions)} of {fmt(d.opportunities)} links break it +

    +
    + {values.length > 1 ? ( +
    + +
    + {dates[0]!.slice(0, 7)} + {markAt !== null && markAt > 0.3 && markAt < 0.7 && ( + + {compareDate.slice(0, 7)} + + )} + {dates.at(-1)!.slice(0, 7)} +
    +
    + ) : ( +

    + {values.length === 1 ? `one check only, at ${dates[0]}` : "no stored checks"} +

    + )} +
    +
  • + ); +} + +function Written({ repo }: { repo: RepoBundle }) { + const { shown, all, toggle } = useShowMore(repo.written, WRITTEN_SHOWN); + if (repo.written.length === 0) return null; + return ( +
    + +
      + {shown.map((w) => ( + + ))} +
    +
    ); } + +function WrittenCard({ 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 index ca7c810b..675eb4af 100644 --- a/web/src/routes/FindingDetail.tsx +++ b/web/src/routes/FindingDetail.tsx @@ -1,6 +1,16 @@ -import { useParams } from "react-router"; -import { SectionHead } from "../components/cx/primitives"; +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, Eyebrow, Prose } from "../components/cx/primitives"; import { useTitle } from "../components/cx/use-page"; +import { findingPath, repoPath } from "../cx/address"; +import { TYPE } from "../cx/meta"; +import type { Finding, RepoBundle } from "../cx/types"; +import { Reading } from "./finding/Reading"; +import { CloseupPanel, DecisionCard, FactsPanel, PriorityPanel, TrendPanel } from "./finding/Rail"; import { NotFound } from "./NotFound"; import { useRepo } from "./RepoLayout"; @@ -11,23 +21,147 @@ export function FindingDetail() { const finding = repo.findings.find((f) => f.slug === slug) ?? repo.supporting.find((f) => f.slug === slug); if (!finding) return ; - return ; + return ; } -function FindingDetailBody({ - title, - rank, - repoName, -}: { - title: string; - rank: number; - repoName: string; -}) { - useTitle(`Finding ${rank} · ${repoName}`); +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); + return ( -
    - -

    This screen is being built.

    -
    +
    + + +
    +
    + {String(f.rank).padStart(2, "0")} +
    +
    +
    + {TYPE[f.type].label} + + · + + {TYPE[f.type].group} + + rank {f.rank} of {all.length} + + {!inTop && below the top {repo.findings.length}} +
    +

    + {f.title} +

    +
    + + +
    +
    +
    + +
    +
    + + + + {f.caveats.length > 0 && ( +
    +

    + Caveats +

    +
      + {f.caveats.map((c) => ( +
    • + + +
    • + ))} +
    +
    + )} + + {related.length > 0 && ( +
    + +

    Findings that share a target.

    +
      + {related.map((r) => ( +
    • + + + #{r.rank} + + + + {TYPE[r.type].label} + {" "} + {r.title} + + +
    • + ))} +
    +
    + )} +
    + + +
    +
    ); } diff --git a/web/src/routes/Findings.tsx b/web/src/routes/Findings.tsx index 376401e7..41c6eb38 100644 --- a/web/src/routes/Findings.tsx +++ b/web/src/routes/Findings.tsx @@ -1,15 +1,244 @@ -import { SectionHead } from "../components/cx/primitives"; +import { EyeOff } from "lucide-react"; +import { useSearchParams } from "react-router"; +import { ComputedMark } from "../components/cx/badges"; +import { FOCUS, cn } from "../components/cx/cn"; +import { weightOf } from "../components/cx/finding-fix"; +import { FindingCompactRow, FindingListRow } from "../components/cx/finding-list-row"; +import { Eyebrow, Panel, SectionHead } from "../components/cx/primitives"; import { useTitle } from "../components/cx/use-page"; +import { TYPE, fmt } from "../cx/meta"; +import type { Batch, Finding, RepoBundle } from "../cx/types"; import { useRepo } from "./RepoLayout"; -/** The Findings screen of one repository. */ +/** 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 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 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 groups = Array.from(new Set(repo.findings.map((f) => TYPE[f.type].group))); + + return ( +
    +
    +
    + Findings · {repo.findings.length} ranked +

    + One list, ranked by what pays back first. +

    +

    + The order is arithmetic on stored numbers: how large the problem is, how far it + reaches, how much change pressure sits on it, how firmly the rule is held and how + cheap the fix is. No AI model changes the order. Each finding carries its own + evidence and caveats. +

    +
    + {groups.length > 0 && ( +
      + {groups.map((g) => ( +
    • + {g}{" "} + + {repo.findings.filter((f) => TYPE[f.type].group === g).length} + +
    • + ))} +
    + )} +
    + + + +
    +
    +
    + Top {repo.findings.length} · in stored rank order +

    + What to fix first +

    +
    +
    + + + {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) => ( + + ))} +
    + )} +
    + + {repo.supporting.length > 0 && ( +
    + + {rest.length} of {restAll.length} shown + + } + /> +

    + The same ranking continues here. The top 10 is limited to a few findings per type and + per module, so some of these have a higher score than a finding above them. +

    +
      + {rest.map((f) => ( + + ))} +
    + {restAll.length > SUPPORTING_SHOWN && ( +
    + +
    + )} +
    + )} +
    + ); +} + +/** 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; + +function Formula({ repo }: { repo: RepoBundle }) { + return ( + +
    +

    + How the rank is computed +

    +
    +

    + 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. +

    +
    +
    + ); +} + +function BatchStrip({ batch }: { batch: Batch | null }) { return ( -
    - -

    This screen is being built.

    -
    +
    +

    + Simulated fix batch +

    + {batch ? ( + <> +
    + {( + [ + ["loops", `${fmt(batch.loopsBefore)} → ${fmt(batch.loopsAfter)}`], + ["links cut", fmt(batch.linksRemoved)], + ["links added", fmt(batch.linksAdded)], + ["applied", fmt(batch.fixesApplied)], + ["skipped", fmt(batch.fixesSkipped)], + ] as const + ).map(([k, v]) => ( +
    +
    {k}
    +
    {v}
    +
    + ))} +
    +

    + Every cheap-loop fix whose own simulation succeeded with no new exception, applied + together on a copy of the 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"}.`} +

    + + ) : ( +

    Not simulated in this run.

    + )} +
    ); } diff --git a/web/src/routes/MapPage.tsx b/web/src/routes/MapPage.tsx index 889d94a6..037d32cf 100644 --- a/web/src/routes/MapPage.tsx +++ b/web/src/routes/MapPage.tsx @@ -1,15 +1,213 @@ -import { SectionHead } from "../components/cx/primitives"; +import { useEffect, useMemo, useState } from "react"; +import { useLocation, useNavigate } from "react-router"; +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 { Eyebrow } from "../components/cx/primitives"; import { useTitle } from "../components/cx/use-page"; +import { type MapState, type MapView, readMapState, 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 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]); + + 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(picked === 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 ( -
    - -

    This screen is being built.

    -
    +
    +
    + + Map · {fmt(present)} {present === 1 ? "module" : "modules"} + {beforeOnly > 0 && ` · ${fmt(beforeOnly)} more only at the before date`} + +

    + Modules ordered foundation-last. Anything below the diagonal points against the grain. +

    +

    + Each row uses the columns it has links into. Switch between the code at the before date, + now, and now with the simulated fix batch; the layout stays the same and only the colours + change. +

    +
    + + {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" + } + /> + )} +
    + + +
    +
    ); } diff --git a/web/src/routes/Size.tsx b/web/src/routes/Size.tsx index 51b9d771..9e71de4d 100644 --- a/web/src/routes/Size.tsx +++ b/web/src/routes/Size.tsx @@ -1,15 +1,462 @@ -import { SectionHead } from "../components/cx/primitives"; +import { ArrowDown, ArrowUp, ArrowUpDown, X } from "lucide-react"; +import { useMemo } from "react"; +import { useSearchParams } from "react-router"; +import { ComputedMark, NotMeasured } 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 { 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 { useRepo } from "./RepoLayout"; -/** The Size screen of one repository. */ +/** Modules listed in "where the new lines landed". */ +const LANDED_SHOWN = 8; +/** Largest files listed for the selected module. */ +const FILES_SHOWN = 10; + +const num = (v: number | null) => (v === null ? : fmt(v)); +const share = (v: number | null) => (v === null ? : 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 ( +
    +
    + Size +

    + Where the code mass is, and where code from after {sponsor.slice(0, 7)} landed. +

    +

    + {fmt(tree.children.length)} modules, {fmt(tree.value)} lines + {inScope !== null && <> in {fmt(inScope)} files} at {repo.snapshotDate},{" "} + {state.scope === "production" ? "production files only" : "every file kind"}. Each + rectangle is a file, grouped by module. Select a module in the map or the table. + {gone > 0 && + ` ${fmt(gone)} ${gone === 1 ? "module exists" : "modules exist"} only at ${repo.beforeDate} and ${gone === 1 ? "is" : "are"} left out.`} +

    +
    + + {tree.value === 0 ? ( + + +

    The bundle holds no size numbers.

    +
    + ) : ( + <> +
    + + files: + + ) : ( + update({ scope })} /> + ) + } + /> + + +

    + Line origin is read for production files only, so test and generated files have no + value. A line counts from the last change that touched it, which is not always the + change that first wrote 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]) => ( + + ))} +
    + ); +} + +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); + return ( +
    + +
    +
    + Selected module +

    + {m.name} +

    +

    + {m.path} + {m.kind && ` · ${m.kind}`} +

    +
    + +
    +
    + {( + [ + ["lines", num(m.loc)], + ["production lines", num(row.prodLoc)], + ["files", num(m.files)], + ["links in", num(m.linksIn)], + ["links out", num(m.linksOut)], + ["changes, 12 months", num(m.changes12m)], + [`share after ${sponsor}`, share(m.postMarchShare)], + [ + `lines after ${sponsor}`, + row.afterLines === null ? : fmt(Math.round(row.afterLines)), + ], + ] as const + ).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); + const missing = rows.every((r) => r.afterLines === null); + return ( +
    + + production lines × share after the date + + } + /> + {missing ? ( + + ) : shown.length === 0 ? ( +

    + No module has lines that arrived after {sponsor} in this run. +

    + ) : ( +
      + {shown.map((r) => { + const lines = r.afterLines ?? 0; + return ( +
    • + +
    • + ); + })} +
    + )} + {!missing && ( +

    + 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); return ( -
    - -

    This screen is being built.

    +
    + + + + + + {COLUMNS.map((c) => { + const active = state.sort === c.key; + const Icon = active ? (state.descending ? ArrowDown : ArrowUp) : ArrowUpDown; + return ( + + ); + })} + + + + {sorted.map(({ m, prodLoc, afterLines }) => { + const isSel = m.id === state.module; + return ( + + + + + + + + + + + + + ); + })} + +
    + +
    + + {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 ? : fmt(Math.round(afterLines))} +
    +
    +

    + Lines and files count every file kind; the share after the date is over production lines, + and lines after the date are production lines × that share{" "} + . Changes are the module's changes in the 12 + months before the snapshot. No figure here ranks a person. +

    ); } diff --git a/web/src/routes/Trust.tsx b/web/src/routes/Trust.tsx index 4f43cb9a..2d791c80 100644 --- a/web/src/routes/Trust.tsx +++ b/web/src/routes/Trust.tsx @@ -1,15 +1,375 @@ -import { SectionHead } from "../components/cx/primitives"; +import { Check, Minus } from "lucide-react"; +import type { ReactNode } from "react"; +import { AiBadge, NotMeasured } from "../components/cx/badges"; +import { Eyebrow, Panel, SectionHead } from "../components/cx/primitives"; import { useTitle } from "../components/cx/use-page"; +import { fmt, pct } from "../cx/meta"; +import type { RepoBundle, StabilityRow, UsageRow } from "../cx/types"; +import { ShowMoreButton, useShowMore } from "./decisions/show-more"; import { useRepo } from "./RepoLayout"; -/** The Trust screen of one repository. */ +/** Blind spots shown before "Show all". */ +const BLIND_SHOWN = 10; +/** The stability target of spec.md §11.3: at least 4 of the top 5 unchanged. */ +const TARGET_TOP5 = 4; + +/** The tests of spec.md §11.3, 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 three AI jobs of spec.md §8.1. */ +const JOBS: Record = { + A: "Read written decisions", + B: "Judge an exception", + C: "Describe a module", +}; + +const usd = (n: number) => `$${n.toFixed(3)}`; + +/** The Trust screen: what was read, how stable the ranking is, and what the AI did and cost. */ export function Trust() { const repo = useRepo(); useTitle(`Trust · ${repo.name}`); + const files = repo.coverage.reduce((s, c) => s + c.files, 0); + const unread = repo.coverage.reduce((s, c) => s + c.unread, 0); + const cost = repo.usage.reduce((s, u) => s + u.cost, 0); + + return ( +
    +
    +
    + Trust +

    + How much of the code was read, how stable the ranking is, and what the run cost. +

    +

    + A report is only as good as what it could see. This page lists the gaps before anyone + acts on the findings. +

    +
    +
    + {( + [ + ["files read", fmt(files)], + ["with unread parts", fmt(unread)], + ["silent-miss share", repo.silentMiss === null ? null : pct(repo.silentMiss)], + ["AI cost", usd(cost)], + ] as const + ).map(([k, v]) => ( +
    +
    {k}
    +
    + {v === null ? : v} +
    +
    + ))} +
    +
    + + + +
    + + +
    + + +
    + ); +} + +function Coverage({ repo }: { repo: RepoBundle }) { + const share = (v: number | null) => (v === null ? : pct(v)); + const head: [string, string][] = [ + ["language", ""], + ["files read", ""], + ["files with unread parts", "Files the reader could not read completely."], + ["imports linked", "Share of imports linked to a file in the project."], + ["imports outside", "Share of imports left outside the project, to a declared dependency."], + [ + "unexplained imports", + "Imports that match neither a project file nor a declared dependency: the silent-miss count.", + ], + ["link agreement", "Agreement with a compiler-accurate index, where the project builds."], + ["file links agree", "Agreement with a separate language-specific linker, file links."], + ["module links agree", "Agreement with a separate language-specific linker, module links."], + ]; + return ( +
    + +
    + + + + {head.map(([h, hint], i) => ( + + ))} + + + + {repo.coverage.map((c) => ( + + + + + + + + + + + + ))} + +
    0 ? "text-right" : ""}`} + > + {h} +
    + {c.language} + {fmt(c.files)}{fmt(c.unread)}{pct(c.linked)}{pct(c.outside)}{fmt(c.unexplained)}{share(c.linkAgreement)}{share(c.fileAgreement)}{share(c.moduleAgreement)}
    +
    +
    + {head + .filter(([, hint]) => hint) + .map(([h, hint]) => ( +
    +
    {h}
    +
    {hint}
    +
    + ))} +
    +
    + ); +} + +function BlindSpots({ repo }: { repo: RepoBundle }) { + const { shown, all, toggle } = useShowMore(repo.blindSpots, BLIND_SHOWN); + return ( +
    + + {repo.blindSpots.length === 0 ? ( +

    No limit is stated in this bundle.

    + ) : ( +
      + {shown.map((b, i) => ( +
    • + + {b} +
    • + ))} +
    + )} + +
    + ); +} + +function Stability({ rows }: { rows: StabilityRow[] }) { + return ( +
    + +

    + + Target: at least {TARGET_TOP5} of the top 5 unchanged under each test. 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 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 ( -
    - -

    This screen is being built.

    +
    + +

    + Text written by an AI model carries the badge: + proposed rules (job A), verdicts, claims and fixes on findings (job B), and module + descriptions (job C). Detection, counting and ranking use no AI. +

    + {rows.length === 0 ? ( + + No AI call is logged in this run. + + ) : ( + + + + + {head.map((h, i) => ( + + ))} + + + + {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, + )} + +
    + {h} +
    +
    + )} +

    + A job without a row has no call logged in this run's ledger. +

    ); } diff --git a/web/src/routes/change/drift.tsx b/web/src/routes/change/drift.tsx new file mode 100644 index 00000000..992a2de8 --- /dev/null +++ b/web/src/routes/change/drift.tsx @@ -0,0 +1,242 @@ +// 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, NotMeasured } 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 { RepoBundle, SeriesPoint, Yardstick } from "../../cx/types"; + +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: "Against-the-grain share", + hint: "Share of cross-module links that point against the main direction of dependencies.", + }, + { + key: "againstGrain", + label: "Against-the-grain links", + hint: "Cross-module links that point against the main direction.", + }, + { + key: "twoWayPairs", + label: "Two-way module pairs", + hint: "Pairs of modules that use each other.", + }, + { + key: "perKloc", + label: "Exceptions per 1,000 lines", + hint: "Decision exceptions per 1,000 lines of production code, for the decisions that apply.", + }, + { + key: "crossModule", + label: "Cross-module links", + hint: "File-to-file links that cross a module boundary.", + }, +]; + +/** 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); + const name = label.charAt(0).toLowerCase() + label.slice(1); + return ( + +
    +
    +

    {label}

    +

    {hint}

    +
    +
    + {y.now === null ? ( + + ) : ( + {f(y.now)} + )} + + {y.before === null + ? `no value at ${repo.beforeDate}` + : `${f(y.before)} at ${repo.beforeDate}`} + +
    +
    + +

    + {y.before !== null && end ? ( + <> + From {repo.beforeDate} to {end.date}, {name} changed from{" "} + {f(y.before)} to{" "} + {f(end.value)}. + {adoption && ( + <> + {" "} + After adoption, from the {adoption.date} snapshot to {end.date}, it changed from{" "} + {f(adoption.value)} to{" "} + {f(end.value)}. + + )}{" "} + + ) : ( + <>No stored value at {repo.beforeDate}, so there is no comparison. + )} + +

    +
    + ); +} + +function DecisionDrift({ repo }: { repo: RepoBundle }) { + const list = [...repo.decisions].sort( + (a, b) => STATUS[a.status].order - STATUS[b.status].order || byText(a.id, b.id), + ); + 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 ( + + + + + + + + + + + + + + {list.map((d) => { + const before = d.series.find((p) => p.date === repo.beforeDate) ?? null; + const values = d.series.map((p) => p.conformance); + return ( + + + + + + + + ); + })} + +
    + Each decision's conformance and exceptions per 1,000 lines at {repo.beforeDate} and at the + end snapshot +
    + decision + + status now + + conformance +
    + {repo.beforeDate} → now +
    + per 1,000 lines +
    + {repo.beforeDate} → now +
    + conformance at each snapshot +
    + {d.statement} + {d.id} + + + + {before ? ( + pct(before.conformance) + ) : ( + no check + )}{" "} + → {pct(d.conformance)} + + {before ? ( + before.perKloc.toFixed(3) + ) : ( + no check + )}{" "} + → {d.perKloc.toFixed(3)} + + ({ 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.map((k) => ( + + ))} +
    +

    Per decision

    + +
    + ); +} diff --git a/web/src/routes/change/events.tsx b/web/src/routes/change/events.tsx new file mode 100644 index 00000000..dd88116c --- /dev/null +++ b/web/src/routes/change/events.tsx @@ -0,0 +1,177 @@ +// 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: "no stated intent", +}; + +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 of the other kinds shown before "Show all". */ +const FIRST = 3; + +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 = kind === "restructuring" ? events.length : 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)} no stated intent + +

    +
      + {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; + }; + return ( +
    + + {fmt(repo.events.length)} {repo.events.length === 1 ? "event" : "events"} ·{" "} + {fmt(c.planned)} planned · {fmt(c.none)} no stated intent + + } + /> +
      +
    • + planned: a basis was found +
    • +
    • + no stated intent: no basis was found, which does not make + it unintended +
    • +
    • + built from stored facts +
    • +
    • + written by an AI model, citations checked +
    • +
    + {repo.events.length === 0 ? ( +

    + No structural event was found between the two dates in this run. +

    + ) : ( + GROUPS.map((g) => { + const events = byKind(g.kind); + return events.length === 0 ? null : ( + + ); + }) + )} +
    + ); +} 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/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 ( + + ); +} diff --git a/web/src/routes/finding/Rail.tsx b/web/src/routes/finding/Rail.tsx new file mode 100644 index 00000000..04c70ca7 --- /dev/null +++ b/web/src/routes/finding/Rail.tsx @@ -0,0 +1,235 @@ +// The side rail of a finding page: close-up, priority with its formula, the finding over +// time with where its lines came from, the stored facts, and the decision it breaks. +import { Link } from "react-router"; +import { ComputedMark, NotMeasured } 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 { STATUS, fmt, pct } from "../../cx/meta"; +import type { Decision, 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 are links between modules. Vermilion goes against the grain. Only links + that touch this finding’s modules are drawn. Positions were stored when the + bundle was built. +

    + + )} +
    + ); +} + +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])} +
    • + ))} +
    +
    +

    + 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)}
    +
    +
    +

    + {f.origin.note} Lines without an explicit marker carry no AI signal.{" "} + +

    +
    + ); +} + +function factValue(v: number | string | boolean): string { + if (typeof v === "number") return fmt(v); + if (typeof v === "boolean") return v ? "yes" : "no"; + return v; +} + +export function FactsPanel({ f }: { f: Finding }) { + return ( + +
    +

    Facts

    + +
    +
    + {f.facts.map((x) => ( +
    +
    {x.key}
    +
    + {factValue(x.value)} + {x.unit && {x.unit}} +
    +
    + ))} +
    +
    link quality
    +
    + {f.linkQuality ? ( + <> + {f.linkQuality.how} ·{" "} + {f.linkQuality.agreement === null ? ( + + ) : ( + pct(f.linkQuality.agreement, 0) + )} + + ) : ( + + )} +
    +
    +
    +
    + ); +} + +export function DecisionCard({ repo, decision }: { repo: RepoBundle; decision: Decision }) { + return ( + +
    +

    Breaks decision

    + +
    +

    {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..50d6cc50 --- /dev/null +++ b/web/src/routes/finding/Reading.tsx @@ -0,0 +1,212 @@ +// The text panel of a finding page: job B's reading of the code when one passed every check +// (spec.md §8.4), otherwise the computed summary and the template's fix (§8.7). Below it, +// 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, VERDICT, fmt } from "../../cx/meta"; +import type { Finding, RepoBundle } from "../../cx/types"; + +const GOOD = STATUS.holding.color; + +const headCls = + "font-mono text-[11px] tracking-[0.14em] text-muted-foreground uppercase"; + +export function Reading({ repo, f }: { repo: RepoBundle; f: Finding }) { + const j = f.judgement; + const fix = fixOf(f); + return ( + + {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; every + number and name in it was checked against the facts and the code. +

    + {fix ? ( + + ) : ( + + )} +
    + + ) : ( + <> +
    +
    + Computed summary + +
    + + no AI reading + +
    +
    +

    + The summary above is the fixed sentence for this finding type, filled in with the + stored facts. This finding has no AI reading that passed every check: the model + does not read pressure points or supporting detail, and a reading that fails a + check is not shown. Every sentence on this page is computed. +

    + {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-2.5 py-1 text-xs 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"); + const links = ( +
    + + Show on map + + {hasSimulatedFix(f) && ( + + Try the fix + + )} +
    + ); + + return ( +
    +
    +

    + Simulation + + {fix ? SIMULATION[kind].long : NO_FIX_TEXT} + + +

    + {links} +
    + {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..6383dfd5 --- /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 ? "against the grain" : "with the grain"} + + + )} +

    + {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 ? ( + + {short} + {lines} + + ) : ( + + {short} + {lines} + + )} + + {r.path} + + {r.role} +
      + + {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"} + +
    { + event.preventDefault(); + writeCloneRoot(repoId, draft); + onSave(draft.trim() || null); + }} + > + + setDraft(event.target.value)} + placeholder="/path/to/your/clone" + className={cn( + "min-w-0 flex-1 rounded-md border bg-background px-2 py-1 font-mono", + FOCUS, + )} + /> + +
    +
    + ); +} 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 ? ( + + ) : ( + + {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)} +

    +
    + + + + + + + + + + + + + + + {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 ( + + + + + + ); + })} + +
    + cell + + simulation + + grid now +
    + {on ? ( + + ) : ( + + {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..9e7cb43b --- /dev/null +++ b/web/src/routes/map/ModulePanel.tsx @@ -0,0 +1,161 @@ +import { X } from "lucide-react"; +import { AiBadge, ComputedMark, NotMeasured } 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. */ +export function ModulePanel({ + repo, + picked, + onPick, +}: { + repo: RepoBundle; + picked: number | null; + onPick: (index: number | null) => void; +}) { + const n = repo.modules.length; + const m = picked === null ? null : (repo.modules[picked] ?? null); + return ( +
    + {m ? ( + onPick(null)} /> + ) : ( +
    +

    Modules

    +

    + The numbers match the grid’s axes. Pick a module to highlight its row and column + and read what it does. Click a cell to list the code links behind it. +

    +
    + )} +
      + {repo.modules.map((mm, i) => ( +
    • + +
    • + ))} +
    +
    + ); +} + +function ModuleCard({ + repo, + m, + n, + onClose, +}: { + repo: RepoBundle; + m: ModuleInfo; + n: number; + onClose: () => void; +}) { + const num = (v: number | null, digits = 0) => + v === null ? : digits ? v.toFixed(digits) : fmt(v); + 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 ? ( +
    + + + + +
    + ) : ( +

    No description of this module in this run.

    + )} +
    + {( + [ + ["lines", num(m.loc)], + ["files", num(m.files)], + ["instability", num(m.instability, 2)], + ["used by", num(m.linksIn)], + ["uses", num(m.linksOut)], + ["changes 12m", num(m.changes12m)], + ] as const + ).map(([k, v]) => ( +
    +
    {k}
    +
    {v}
    +
    + ))} +
    +

    + “Used by” and “uses” count link lines at {repo.snapshotDate}.{" "} + +

    +
    + ); +} diff --git a/web/src/routes/size/scale.tsx b/web/src/routes/size/scale.tsx new file mode 100644 index 00000000..627ba99a --- /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 sponsor 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..f36c5553 --- /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 sponsor 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..e7815ac3 --- /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 sponsor 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}`} + +
    + )} +
    + ); +} From 5215c50c23c65712a83f1deaa12dd6b133bbe75f Mon Sep 17 00:00:00 2001 From: Pranav Mathad Date: Sun, 29 Nov 2026 06:04:18 +0100 Subject: [PATCH 04/18] Remove the old web screens and document the new web app --- CONTRIBUTING.md | 6 +- README.md | 71 +- web/package-lock.json | 47 -- web/package.json | 5 - web/src/App.tsx | 2 +- web/src/app.test.tsx | 57 +- web/src/components/AiSwitch.tsx | 26 - web/src/components/Badge.tsx | 15 - web/src/components/RepoSwitcher.tsx | 93 --- web/src/components/Shell.tsx | 112 --- web/src/components/Sparkline.tsx | 63 -- web/src/components/Status.tsx | 70 -- web/src/components/cx/badges.tsx | 2 +- web/src/components/cx/closeup.tsx | 32 +- web/src/components/cx/code-block.tsx | 64 +- web/src/components/cx/code-highlight.ts | 18 +- web/src/components/cx/finding-list-row.tsx | 4 +- web/src/components/cx/matrix.tsx | 3 +- web/src/components/cx/primitives.tsx | 21 +- web/src/components/cx/site-header.tsx | 6 +- web/src/cx/meta.ts | 4 + web/src/data/adapt.ts | 3 +- web/src/data/context.tsx | 22 - web/src/data/testing.ts | 31 +- web/src/data/view.ts | 78 -- web/src/main.tsx | 1 - web/src/routes/FindingDetail.tsx | 17 +- web/src/routes/Findings.tsx | 21 +- web/src/routes/NotFound.tsx | 13 +- web/src/routes/Overview.tsx | 22 +- web/src/routes/RepoLayout.tsx | 22 +- web/src/routes/Trust.tsx | 16 +- web/src/routes/change/events.tsx | 5 +- web/src/routes/finding/Rail.tsx | 17 +- web/src/routes/finding/Reading.tsx | 41 +- web/src/screens.ts | 85 -- web/src/screens/BeforeAfter.tsx | 145 ---- web/src/screens/CloseUp.tsx | 197 ----- web/src/screens/CodePane.tsx | 291 ------- web/src/screens/Decisions.tsx | 170 ---- web/src/screens/Grid.tsx | 211 ----- web/src/screens/Placeholder.tsx | 12 - web/src/screens/Report.tsx | 86 -- web/src/screens/SizeMap.tsx | 82 -- web/src/screens/beforeafter/Changes.tsx | 87 -- .../screens/beforeafter/DecisionSeries.tsx | 209 ----- web/src/screens/beforeafter/Switch.tsx | 38 - web/src/screens/beforeafter/beforeafter.css | 333 -------- web/src/screens/beforeafter/compare.ts | 58 -- web/src/screens/closeup/Graph.tsx | 184 ----- web/src/screens/closeup/closeup.css | 115 --- web/src/screens/closeup/select.ts | 44 - web/src/screens/code/Highlighted.tsx | 182 ----- web/src/screens/code/code.css | 236 ------ web/src/screens/code/links.ts | 39 - web/src/screens/decisions/DecisionsTable.tsx | 149 ---- web/src/screens/decisions/FixFirst.tsx | 489 ------------ web/src/screens/decisions/Yardsticks.tsx | 55 -- web/src/screens/decisions/decisions.css | 749 ------------------ web/src/screens/decisions/words.ts | 106 --- web/src/screens/grid/CellLinks.tsx | 137 ---- web/src/screens/grid/FixPanel.tsx | 113 --- web/src/screens/grid/MatrixCanvas.tsx | 320 -------- web/src/screens/grid/applyFix.ts | 36 - web/src/screens/grid/cells.ts | 71 -- web/src/screens/grid/grid.css | 412 ---------- web/src/screens/report/Sections.tsx | 279 ------- web/src/screens/report/format.ts | 73 -- web/src/screens/report/report.css | 179 ----- web/src/screens/size/StatsTable.tsx | 111 --- web/src/screens/size/Treemap.tsx | 162 ---- web/src/screens/size/size.css | 169 ---- web/src/screens/size/tree.ts | 46 -- web/src/styles/base.css | 634 --------------- web/src/styles/globals.css | 25 +- web/src/styles/tokens.css | 47 -- 76 files changed, 379 insertions(+), 7817 deletions(-) delete mode 100644 web/src/components/AiSwitch.tsx delete mode 100644 web/src/components/Badge.tsx delete mode 100644 web/src/components/RepoSwitcher.tsx delete mode 100644 web/src/components/Shell.tsx delete mode 100644 web/src/components/Sparkline.tsx delete mode 100644 web/src/components/Status.tsx delete mode 100644 web/src/data/context.tsx delete mode 100644 web/src/data/view.ts delete mode 100644 web/src/screens.ts delete mode 100644 web/src/screens/BeforeAfter.tsx delete mode 100644 web/src/screens/CloseUp.tsx delete mode 100644 web/src/screens/CodePane.tsx delete mode 100644 web/src/screens/Decisions.tsx delete mode 100644 web/src/screens/Grid.tsx delete mode 100644 web/src/screens/Placeholder.tsx delete mode 100644 web/src/screens/Report.tsx delete mode 100644 web/src/screens/SizeMap.tsx delete mode 100644 web/src/screens/beforeafter/Changes.tsx delete mode 100644 web/src/screens/beforeafter/DecisionSeries.tsx delete mode 100644 web/src/screens/beforeafter/Switch.tsx delete mode 100644 web/src/screens/beforeafter/beforeafter.css delete mode 100644 web/src/screens/beforeafter/compare.ts delete mode 100644 web/src/screens/closeup/Graph.tsx delete mode 100644 web/src/screens/closeup/closeup.css delete mode 100644 web/src/screens/closeup/select.ts delete mode 100644 web/src/screens/code/Highlighted.tsx delete mode 100644 web/src/screens/code/code.css delete mode 100644 web/src/screens/code/links.ts delete mode 100644 web/src/screens/decisions/DecisionsTable.tsx delete mode 100644 web/src/screens/decisions/FixFirst.tsx delete mode 100644 web/src/screens/decisions/Yardsticks.tsx delete mode 100644 web/src/screens/decisions/decisions.css delete mode 100644 web/src/screens/decisions/words.ts delete mode 100644 web/src/screens/grid/CellLinks.tsx delete mode 100644 web/src/screens/grid/FixPanel.tsx delete mode 100644 web/src/screens/grid/MatrixCanvas.tsx delete mode 100644 web/src/screens/grid/applyFix.ts delete mode 100644 web/src/screens/grid/cells.ts delete mode 100644 web/src/screens/grid/grid.css delete mode 100644 web/src/screens/report/Sections.tsx delete mode 100644 web/src/screens/report/format.ts delete mode 100644 web/src/screens/report/report.css delete mode 100644 web/src/screens/size/StatsTable.tsx delete mode 100644 web/src/screens/size/Treemap.tsx delete mode 100644 web/src/screens/size/size.css delete mode 100644 web/src/screens/size/tree.ts delete mode 100644 web/src/styles/base.css delete mode 100644 web/src/styles/tokens.css 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..5f33eafd 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: Overview, Decisions, Findings and finding detail, Map, Change, Trust, Size | 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 its verdict and the finding to fix first | +| `/r/` | Overview: verdict, yardsticks, decisions, the simulated fix batch, the top findings | +| `/r//decisions` | Decisions: 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` | Change: before and after the compared date, structural events, hotspots | +| `/r//trust` | Trust: coverage, limits, stability of the ranking, AI calls and their cost | +| `/r//size` | Size: 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/package-lock.json b/web/package-lock.json index 45a5901d..c12fe143 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -8,12 +8,9 @@ "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", @@ -25,9 +22,7 @@ "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", @@ -349,15 +344,6 @@ } } }, - "node_modules/@fontsource-variable/hanken-grotesk": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/@fontsource-variable/hanken-grotesk/-/hanken-grotesk-5.3.0.tgz", - "integrity": "sha512-DOd0FqL+3cH2dfNy0JtSq9tUfxBz5mLmHMjTU0DOr3E9Zo6wxuatCl53DIPNrSPgCsnuKyM739BTIG5glCLirw==", - "license": "OFL-1.1", - "funding": { - "url": "https://github.com/sponsors/ayuhito" - } - }, "node_modules/@fontsource-variable/instrument-sans": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/@fontsource-variable/instrument-sans/-/instrument-sans-5.3.0.tgz", @@ -1251,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", @@ -1265,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", @@ -1282,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", @@ -2017,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", diff --git a/web/package.json b/web/package.json index da157c68..a13aac8a 100644 --- a/web/package.json +++ b/web/package.json @@ -14,12 +14,9 @@ "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", @@ -31,9 +28,7 @@ "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", diff --git a/web/src/App.tsx b/web/src/App.tsx index 282f5d07..3aa764fb 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -27,7 +27,7 @@ export function App() { } /> } /> } /> - } /> + } /> { }); }); -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 - - - - ); -} 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 ( -
    - - {open && ( -
      - {bundles.map((bundle) => { - const current = bundle.repo_id === index.repo_id; - return ( -
    • - setOpen(false)} - > - - - {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)}} - -
    - -
    -
    - - {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 index f4ca4d42..55865eff 100644 --- a/web/src/components/cx/badges.tsx +++ b/web/src/components/cx/badges.tsx @@ -1,4 +1,4 @@ -// Where a sentence or a value comes from (spec.md §10.3): every AI-written sentence carries +// 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"; diff --git a/web/src/components/cx/closeup.tsx b/web/src/components/cx/closeup.tsx index a0ff4538..fe85b554 100644 --- a/web/src/components/cx/closeup.tsx +++ b/web/src/components/cx/closeup.tsx @@ -57,7 +57,10 @@ export function closeupPicture(repo: RepoBundle, finding: Finding) { 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), + 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), }; }); @@ -69,10 +72,7 @@ export function closeupPicture(repo: RepoBundle, finding: Finding) { // 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)), + ids.has(c.src) && ids.has(c.dst) && c.count > 0 && (core.has(c.src) || core.has(c.dst)), ) .map((c) => ({ src: c.src, @@ -81,13 +81,14 @@ export function closeupPicture(repo: RepoBundle, finding: Finding) { 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), + 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)), + Number(a.hot) - Number(b.hot) || cellKey(a.src, a.dst).localeCompare(cellKey(b.src, b.dst)), ); return { boxes, arrows, H }; } @@ -96,7 +97,10 @@ export function closeupPicture(repo: RepoBundle, finding: Finding) { 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)); + 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 }; } @@ -234,7 +238,10 @@ export function CloseupLegend({ partners }: { partners: boolean }) { this finding
  • - + neighbour
  • @@ -247,7 +254,10 @@ export function CloseupLegend({ partners }: { partners: boolean }) {
  • {partners && (
  • - + changed together, no link
  • )} diff --git a/web/src/components/cx/code-block.tsx b/web/src/components/cx/code-block.tsx index db7ddd83..792f6e05 100644 --- a/web/src/components/cx/code-block.tsx +++ b/web/src/components/cx/code-block.tsx @@ -3,7 +3,13 @@ // 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 { + 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"; @@ -59,7 +65,9 @@ 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}`, + 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(", "); @@ -98,7 +106,8 @@ export function EvidencePane({ repo, evidence }: { repo: RepoBundle; evidence: E {evidence.length} {evidence.length === 1 ? "record" : "records"} - {files.length > 0 && ` in ${files.length} ${files.length === 1 ? "file" : "files"}`} @{" "} + {files.length > 0 && + ` in ${files.length} ${files.length === 1 ? "file" : "files"}`} @{" "} {repo.endSha.slice(0, 7)}
    @@ -156,7 +165,10 @@ export function EvidencePane({ repo, evidence }: { repo: RepoBundle; evidence: E {g.path} :{rangesText(g.records)} - · {rolesText(g.records)} + + {" "} + · {rolesText(g.records)} + {open && ( @@ -209,7 +221,10 @@ function CloneFolder({ @@ -239,7 +254,10 @@ function CloneFolder({ /> @@ -315,9 +333,7 @@ function FileBlock({ ); } -type Row = - | { kind: "line"; n: number; hl: boolean } - | { kind: "gap"; from: number; to: number }; +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][] { @@ -355,7 +371,8 @@ function FileCode({ 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 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()); @@ -382,7 +399,9 @@ function FileCode({ }, [code, blobSha, windowKey]); if (loaded.state === "loading") { - return

    Loading the cited lines…

    ; + return ( +

    Loading the cited lines…

    + ); } if (loaded.state === "failed") { return ( @@ -393,7 +412,9 @@ function FileCode({ } const cited = (n: number) => - records.some((r) => r.startLine !== null && n >= r.startLine && n <= (r.endLine ?? r.startLine)); + 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]; @@ -439,14 +460,20 @@ function FileCode({ @@ -469,7 +496,9 @@ function CommitsBlock({ repo, ev }: { repo: RepoBundle; ev: Evidence }) { · {ev.role} {!base && ( - No public host: open the commits in your clone. + + No public host: open the commits in your clone. + )}
      @@ -498,7 +527,10 @@ function CommitsBlock({ repo, ev }: { repo: RepoBundle; ev: Evidence }) { type="button" aria-expanded={all} onClick={() => setAll((on) => !on)} - className={cn("rounded-sm font-medium text-foreground underline-offset-2 hover:underline", FOCUS)} + 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 index 86472ba1..ed837912 100644 --- a/web/src/components/cx/code-highlight.ts +++ b/web/src/components/cx/code-highlight.ts @@ -9,13 +9,11 @@ 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"), - ], - ); + 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: [], @@ -76,7 +74,11 @@ export function splitLines(text: string): string[] { } /** 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 } { +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"; diff --git a/web/src/components/cx/finding-list-row.tsx b/web/src/components/cx/finding-list-row.tsx index f261b1b3..b7712489 100644 --- a/web/src/components/cx/finding-list-row.tsx +++ b/web/src/components/cx/finding-list-row.tsx @@ -171,7 +171,9 @@ export function FindingCompactRow({ repoId, f }: { repoId: string; f: Finding }) {TYPE[f.type].label} - {f.title} + + {f.title} + {f.judgement?.verdict === "legitimate_wiring" && ( diff --git a/web/src/components/cx/matrix.tsx b/web/src/components/cx/matrix.tsx index f2a47e44..c747874f 100644 --- a/web/src/components/cx/matrix.tsx +++ b/web/src/components/cx/matrix.tsx @@ -291,7 +291,8 @@ export function Matrix({ ref={scrollRef} className={cn( "relative max-w-full", - !compact && "overflow-auto overscroll-contain", + // A grid wider than its panel scrolls inside it, never the page. + compact ? "overflow-x-auto overscroll-x-contain" : "overflow-auto overscroll-contain", !compact && density === "names" && "max-h-[78vh]", )} > diff --git a/web/src/components/cx/primitives.tsx b/web/src/components/cx/primitives.tsx index 3e7c4500..f61b39ac 100644 --- a/web/src/components/cx/primitives.tsx +++ b/web/src/components/cx/primitives.tsx @@ -123,8 +123,25 @@ export function Chip({ ); } -export function Panel({ children, className }: { children: ReactNode; className?: string }) { - 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. */ diff --git a/web/src/components/cx/site-header.tsx b/web/src/components/cx/site-header.tsx index 3947b844..84264836 100644 --- a/web/src/components/cx/site-header.tsx +++ b/web/src/components/cx/site-header.tsx @@ -21,7 +21,7 @@ export function SiteHeader({ current }: { current?: string }) { const fixtures = all.filter((r) => r.synthetic); return (
      -
      +
      {groups.length > 0 && ( @@ -91,7 +90,10 @@ export function Findings() { type="button" aria-pressed={hideLegit} onClick={() => setParam(HIDE_PARAM, hideLegit ? null : HIDE_VALUE)} - className={cn(buttonCls, hideLegit && "border-foreground bg-ink text-ink-foreground hover:bg-ink")} + className={cn( + buttonCls, + hideLegit && "border-foreground bg-ink text-ink-foreground hover:bg-ink", + )} > Hide legitimate wiring @@ -197,8 +199,8 @@ function Formula({ repo }: { repo: RepoBundle }) { ))}

      - 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. + 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.

      @@ -233,7 +235,8 @@ function BatchStrip({ batch }: { batch: Batch | null }) { Every cheap-loop fix whose own simulation succeeded with no new exception, applied together on a copy of the 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"}.`} + ` The batch creates ${fmt(batch.newExceptions.length)} new ${batch.newExceptions.length === 1 ? "exception" : "exceptions"}.`}{" "} + {BATCH_LOOPS_NOTE}

      ) : ( diff --git a/web/src/routes/NotFound.tsx b/web/src/routes/NotFound.tsx index 0f6ffe75..4549afb0 100644 --- a/web/src/routes/NotFound.tsx +++ b/web/src/routes/NotFound.tsx @@ -4,15 +4,20 @@ 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. */ -export function NotFound({ what }: { what?: string }) { +/** + * 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."}

      diff --git a/web/src/routes/Overview.tsx b/web/src/routes/Overview.tsx index 5e154073..674ec08e 100644 --- a/web/src/routes/Overview.tsx +++ b/web/src/routes/Overview.tsx @@ -9,7 +9,7 @@ import { Eyebrow, Panel, SectionHead, StatusDot, StatusPill } from "../component import { Sparkline, markIndex } from "../components/cx/sparkline"; import { useTitle } from "../components/cx/use-page"; import { repoPath } from "../cx/address"; -import { STATUS, STATUS_ORDER, fmt, pct, statusCounts } from "../cx/meta"; +import { BATCH_LOOPS_NOTE, STATUS, STATUS_ORDER, fmt, pct, statusCounts } from "../cx/meta"; import type { Batch, RepoBundle, Status, Yardstick } from "../cx/types"; import { useRepo } from "./RepoLayout"; @@ -32,7 +32,7 @@ export function Overview() {
      -
      +
      @@ -80,7 +80,14 @@ function joined(items: ReactNode[]): ReactNode { )); } -function VerdictSentence({ counts, total }: { counts: Record; total: number }) { +/** 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; @@ -306,12 +313,14 @@ function DecisionList({ repo, compareDate }: { repo: RepoBundle; compareDate: st return (
    • -

      {d.statement}

      +

      + {d.statement} +

      0 && ` ${fmt(batch.fixesSkipped)} ${batch.fixesSkipped === 1 ? "fix was" : "fixes were"} left out.`} {batch.newExceptions.length > 0 && - ` The batch creates ${fmt(batch.newExceptions.length)} new ${batch.newExceptions.length === 1 ? "exception" : "exceptions"}.`} + ` The batch creates ${fmt(batch.newExceptions.length)} new ${batch.newExceptions.length === 1 ? "exception" : "exceptions"}.`}{" "} + {BATCH_LOOPS_NOTE}

      ) : ( diff --git a/web/src/routes/RepoLayout.tsx b/web/src/routes/RepoLayout.tsx index d1e5bf74..b7adc011 100644 --- a/web/src/routes/RepoLayout.tsx +++ b/web/src/routes/RepoLayout.tsx @@ -91,9 +91,10 @@ export function RepoLayout() { function RepoBody({ repo }: { repo: RepoBundle }) { 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 > 3 - ? `${repo.languages.slice(0, 3).join(" + ")} +${repo.languages.length - 3}` + 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", @@ -147,7 +148,18 @@ function RepoBody({ repo }: { repo: RepoBundle }) { {repo.rulesHash.slice(0, 8)} ) : ( -
      not in bundle
      + // Short visible text keeps the header on one line; the full wording is + // the tooltip and what a screen reader announces. +
      + + not measured in this run +
      )}
    • @@ -201,7 +213,9 @@ function RepoNav({ repoId, counts }: { repoId: string; counts: Record {t.label} diff --git a/web/src/routes/Trust.tsx b/web/src/routes/Trust.tsx index 2d791c80..a0271d7b 100644 --- a/web/src/routes/Trust.tsx +++ b/web/src/routes/Trust.tsx @@ -1,6 +1,6 @@ import { Check, Minus } from "lucide-react"; import type { ReactNode } from "react"; -import { AiBadge, NotMeasured } from "../components/cx/badges"; +import { AiBadge, ComputedMark, NotMeasured } from "../components/cx/badges"; import { Eyebrow, Panel, SectionHead } from "../components/cx/primitives"; import { useTitle } from "../components/cx/use-page"; import { fmt, pct } from "../cx/meta"; @@ -117,7 +117,12 @@ function Coverage({ repo }: { repo: RepoBundle }) { eyebrow="Coverage" title="Files read and linked, by language" id="coverage" - aside="File and module agreement are against comparison linkers, not a compiler." + aside={ + + File and module agreement are against comparison linkers, not a compiler. + + + } />
      @@ -215,6 +220,7 @@ function Stability({ rows }: { rows: StabilityRow[] }) { eyebrow="Stability" title="Does the ranking survive perturbation?" id="stability" + aside={} />

      @@ -307,7 +313,11 @@ function Usage({ rows }: { rows: UsageRow[] }) { eyebrow="AI usage ledger" title="Every AI call, logged and priced" id="usage" - aside={`${fmt(sum("calls"))} calls · ${usd(sum("cost"))} total`} + aside={ + + {fmt(sum("calls"))} calls · {usd(sum("cost"))} total + + } />

      Text written by an AI model carries the badge: diff --git a/web/src/routes/change/events.tsx b/web/src/routes/change/events.tsx index dd88116c..974fad9c 100644 --- a/web/src/routes/change/events.tsx +++ b/web/src/routes/change/events.tsx @@ -30,7 +30,8 @@ const GROUPS: { kind: StructuralEvent["kind"]; title: string; noun: string }[] = const byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0); -/** Events of the other kinds shown before "Show all". */ +/** Events shown before "Show all": restructurings, then every other kind. */ +const FIRST_RESTRUCTURINGS = 8; const FIRST = 3; export function LabelChip({ label }: { label: StructuralEvent["label"] }) { @@ -93,7 +94,7 @@ function Group({ kind: StructuralEvent["kind"]; events: StructuralEvent[]; }) { - const first = kind === "restructuring" ? events.length : FIRST; + const first = kind === "restructuring" ? FIRST_RESTRUCTURINGS : FIRST; const { shown, all, toggle } = useShowMore(events, first); const c = labelCounts(events); const id = `events-${kind}`; diff --git a/web/src/routes/finding/Rail.tsx b/web/src/routes/finding/Rail.tsx index 04c70ca7..a7a74b30 100644 --- a/web/src/routes/finding/Rail.tsx +++ b/web/src/routes/finding/Rail.tsx @@ -30,9 +30,9 @@ export function CloseupPanel({ repo, f }: { repo: RepoBundle; f: Finding }) { <>

      - Numbers are links between modules. Vermilion goes against the grain. Only links - that touch this finding’s modules are drawn. Positions were stored when the - bundle was built. + Numbers are links between modules. Vermilion goes against the grain. Only links that + touch this finding’s modules are drawn. Positions were stored when the bundle was + built.

      )} @@ -145,7 +145,10 @@ export function TrendPanel({ repo, f }: { repo: RepoBundle; f: Finding }) { {series.at(-1)?.date.slice(0, 7) ?? ""}

      - + dashed line: {compareDate.slice(0, 7)}

      @@ -181,7 +184,11 @@ export function FactsPanel({ f }: { f: Finding }) {
      {f.facts.map((x) => ( -
      +
      {x.key}
      {factValue(x.value)} diff --git a/web/src/routes/finding/Reading.tsx b/web/src/routes/finding/Reading.tsx index 50d6cc50..b9f26355 100644 --- a/web/src/routes/finding/Reading.tsx +++ b/web/src/routes/finding/Reading.tsx @@ -7,7 +7,12 @@ 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 { + 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, VERDICT, fmt } from "../../cx/meta"; @@ -15,19 +20,20 @@ import type { Finding, RepoBundle } from "../../cx/types"; const GOOD = STATUS.holding.color; -const headCls = - "font-mono text-[11px] tracking-[0.14em] text-muted-foreground uppercase"; +const headCls = "font-mono text-[11px] tracking-[0.14em] text-muted-foreground uppercase"; export function Reading({ repo, f }: { repo: RepoBundle; f: Finding }) { const j = f.judgement; const fix = fixOf(f); return ( - + {j ? ( <>
      - Reading of the code + + Reading of the code + {j.verdict === "legitimate_wiring" ? ( ) : ( @@ -49,8 +55,8 @@ export function Reading({ repo, f }: { repo: RepoBundle; f: Finding }) {

      - Written by {j.model ?? "an AI model"} from the cited lines; every - number and name in it was checked against the facts and the code. + Written by {j.model ?? "an AI model"} from the cited lines; every number + and name in it was checked against the facts and the code.

      {fix ? ( @@ -63,19 +69,19 @@ export function Reading({ repo, f }: { repo: RepoBundle; f: Finding }) { <>
      - Computed summary + + Computed summary +
      - - no AI reading - + no AI reading

      The summary above is the fixed sentence for this finding type, filled in with the - stored facts. This finding has no AI reading that passed every check: the model - does not read pressure points or supporting detail, and a reading that fails a - check is not shown. Every sentence on this page is computed. + stored facts. This finding has no AI reading that passed every check: the model does + not read pressure points or supporting detail, and a reading that fails a check is not + shown. Every sentence on this page is computed.

      {fix ? : }
      @@ -140,7 +146,8 @@ 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 shown = + fix !== null && sim !== null && kind !== "not-simulated" && kind !== "nothing-changed"; const mapBase = repoPath(repo.id, "map"); const links = (
      @@ -172,7 +179,9 @@ function SimulationStrip({ repo, f }: { repo: RepoBundle; f: Finding }) { {sim.loopsBefore === null || sim.loopsAfter === null ? ( 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 ( -
      -
      -
      -

      Before and after

      -

      - The structure at {formatDate(file.before.date)} and {formatDate(file.after.date)}, on - one layout. This panel describes what changed. Three repositories with no comparison - group cannot show cause, so it does not say why. -

      -
      - - setView({ snapshot: next === "before" ? file.before.date : file.after.date }) - } - /> -
      - -
      - {figures.map((f) => ( -
      -
      {yardstickLabel(f.name)}
      -
      {yardstickValue(f.name, f.value)}
      -
      - ))} -
      -
      Module links added since {formatDate(file.before.date)}
      -
      {linksAdded}
      -
      -
      -
      Module links removed
      -
      {linksRemoved}
      -
      -
      - -
      -
      - -
      - - - -
      StatusDecisionSourceConformanceOver timeExceptions
      - {check ? ( - - ) : ( - - {checkable - ? "Not checked at this snapshot" - : "Written, not machine-checkable"} - - )} - - {decision.statement} - {checkable && ( - - {decision.shape}({argsText(decision.args)}) - - )} - - {SOURCE_LABEL[decision.source.kind]} - {location && ( - - {location} - - )} - - {check ? percent(check.conformance) : ""} - - {check && points.length > 0 && ( - `${percent(p.value)} on ${p.date}`).join(", ")}`} - /> - )} - 0 ? "exceptions--some" : "muted"}`} - data-label={ - check ? (check.exceptions === 1 ? "exception" : "exceptions") : undefined - } - > - {check ? num(check.exceptions) : ""} -