diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 80837a0..90cbb91 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -10,6 +10,119 @@ permissions:
contents: read
jobs:
+ duplication:
+ name: Duplication ratchet
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - name: Checkout candidate
+ uses: actions/checkout@v7
+ with:
+ path: candidate
+ fetch-depth: 0
+ persist-credentials: false
+ - name: Checkout trusted comparison base
+ uses: actions/checkout@v7
+ with:
+ ref: ${{ github.event.pull_request.base.sha || github.event.before }}
+ path: base
+ fetch-depth: 0
+ persist-credentials: false
+ - uses: actions/setup-node@v6
+ with:
+ node-version: "24"
+ cache: npm
+ cache-dependency-path: candidate/tools/duplication/package-lock.json
+ - name: Test duplication tooling
+ run: |
+ npm ci --prefix candidate/tools/duplication --ignore-scripts --no-audit --no-fund
+ npm --prefix candidate/tools/duplication test
+ - name: Measure and compare production duplication
+ id: duplication-policy
+ shell: bash
+ run: |
+ policy_dir="$GITHUB_WORKSPACE/base/tools/duplication"
+ if [[ -f "$policy_dir/policy.json" ]]; then
+ echo "trusted=true" >> "$GITHUB_OUTPUT"
+ npm ci --prefix "$policy_dir" --ignore-scripts --no-audit --no-fund
+ else
+ # One-time bootstrap: the base branch has no duplication policy yet.
+ policy_dir="$GITHUB_WORKSPACE/candidate/tools/duplication"
+ fi
+ node "$policy_dir/check.mjs" --root "$GITHUB_WORKSPACE/candidate" \
+ --base "$GITHUB_WORKSPACE/base" --output "$RUNNER_TEMP/duplication-report"
+ - name: Validate proposed checker and policy against master
+ if: steps.duplication-policy.outputs.trusted == 'true'
+ run: |
+ node "$GITHUB_WORKSPACE/base/tools/duplication/verify.mjs" \
+ --root "$GITHUB_WORKSPACE/candidate" --base "$GITHUB_WORKSPACE/base" \
+ --output "$RUNNER_TEMP/duplication-report"
+ - name: Preserve actionable duplication reports
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: duplication-report
+ path: ${{ runner.temp }}/duplication-report
+ retention-days: 30
+ if-no-files-found: warn
+
+ duplication-baseline:
+ name: Update duplication baseline
+ needs: [duplication, test]
+ if: github.event_name == 'push' && github.ref == 'refs/heads/master'
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ permissions:
+ contents: write
+ concurrency:
+ group: duplication-baseline-master
+ cancel-in-progress: false
+ steps:
+ - uses: actions/checkout@v7
+ with:
+ ref: ${{ github.sha }}
+ fetch-depth: 0
+ - uses: actions/setup-node@v6
+ with:
+ node-version: "24"
+ - name: Persist initial baseline or tighter limits
+ shell: bash
+ run: |
+ git fetch --no-tags origin master
+ if [[ "$(git rev-parse FETCH_HEAD)" != "$GITHUB_SHA" ]]; then
+ echo "A newer master commit exists; its successful CI run will update the baseline."
+ exit 0
+ fi
+ npm ci --prefix tools/duplication --ignore-scripts --no-audit --no-fund
+ node tools/duplication/check.mjs --update-baseline --output "$RUNNER_TEMP/duplication-ratchet"
+ if git diff --quiet -- tools/duplication/baseline.json; then
+ echo "No improved limits; baseline left unchanged."
+ exit 0
+ fi
+ git config user.name "github-actions[bot]"
+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
+ git add -- tools/duplication/baseline.json
+ git commit -m "CHORE: ratchet duplication baseline"
+ # Normal non-force push: never overwrite a concurrently advanced master.
+ # GITHUB_TOKEN pushes do not recursively start another CI run.
+ if ! git push origin HEAD:master; then
+ git fetch --no-tags origin master
+ if [[ "$(git rev-parse FETCH_HEAD)" != "$GITHUB_SHA" ]]; then
+ echo "Master advanced during the update; leaving its newer content untouched."
+ exit 0
+ fi
+ echo "Baseline push failed; check repository Actions permissions and branch rules."
+ exit 1
+ fi
+ - name: Preserve measured baseline for manual recovery
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: duplication-baseline-candidate
+ path: ${{ runner.temp }}/duplication-ratchet
+ retention-days: 30
+ if-no-files-found: ignore
+
test:
name: Go ${{ matrix.os }}
runs-on: ${{ matrix.os }}
@@ -30,7 +143,7 @@ jobs:
- name: Setup Bats
if: runner.os == 'Linux'
- uses: bats-core/bats-action@4.0.0
+ uses: bats-core/bats-action@4.1.0
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
support-install: false
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 05207af..2e4364a 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -92,7 +92,7 @@ jobs:
cache: true
- name: Setup Bats
if: runner.os == 'Linux'
- uses: bats-core/bats-action@4.0.0
+ uses: bats-core/bats-action@4.1.0
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
support-install: false
diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml
index 95bd85b..e71e7d9 100644
--- a/.github/workflows/security.yml
+++ b/.github/workflows/security.yml
@@ -26,4 +26,4 @@ jobs:
# Do not silently scan a newer toolchain instead of the project's Go version.
env:
GOTOOLCHAIN: local
- run: go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
+ run: go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 ./...
diff --git a/.gitignore b/.gitignore
index 69ad870..c853d19 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,3 +4,5 @@
/theme.yml
*.test
coverage.out
+/tools/duplication/node_modules/
+/tools/duplication/reports/
diff --git a/README.md b/README.md
index 3f16344..35610c1 100644
--- a/README.md
+++ b/README.md
@@ -5,7 +5,7 @@
[](go.mod)
[](LICENSE)
-Termcourse is a Go 1.27.2 terminal UI for browsing and posting to Discourse forums. It replaces the original Ruby implementation while retaining its browsing, posting, realtime, rendering, localization, theming, and image features.
+Termcourse is a Go 1.27.3 terminal UI for browsing and posting to Discourse forums. It replaces the original Ruby implementation while retaining its browsing, posting, realtime, rendering, localization, theming, and image features.
## Features
@@ -89,7 +89,7 @@ If no credentials are configured, Termcourse prompts for the missing username an
### Install with Go
-Go 1.27.2 or newer is required when installing from source. `go install` compiles Termcourse locally:
+Go 1.27.3 or newer is required when installing from source. `go install` compiles Termcourse locally:
```sh
go install github.com/merefield/termcourse/cmd/termcourse@latest
@@ -343,10 +343,12 @@ Each uses the same full-width block lettering at the vertical centre, then shrin
## Implementation
-The Security workflow scans reachable Go standard-library and dependency vulnerabilities on PRs, pushes to master, weekly, and manual dispatch. It pins `govulncheck` to v1.8.0 and disables automatic toolchain switching to scan the Go version in `go.mod`. Advisory-service failures fail the check. The scan currently covers the Linux build; it adds no application startup work or runtime dependency. Repeat locally with:
+The [Duplication ratchet](tools/duplication/README.md) checks production Go code for copy-paste regressions. Normalised matches and test duplication are reported for review.
+
+The Security workflow scans reachable Go standard-library and dependency vulnerabilities on PRs, pushes to master, weekly, and manual dispatch. It pins `govulncheck` to v1.9.0 and disables automatic toolchain switching to scan the Go version in `go.mod`. Advisory-service failures fail the check. The scan currently covers the Linux build; it adds no application startup work or runtime dependency. Repeat locally with:
```sh
-GOTOOLCHAIN=go1.27.2 go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
+GOTOOLCHAIN=go1.27.3 go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 ./...
```
The interface runs on the current Charm v2 stack. Bubble Tea owns raw mode, the alternate screen, synchronized incremental rendering, resize events, cursor state, terminal queries, color downsampling, window metadata, and supported native progress metadata. Bubbles supplies the themed single-line editor and multiline composer, including bracketed paste, word navigation, soft wrapping, cursor behavior, and viewport scrolling. Lip Gloss v2 provides pure theme/layout styles, while Glamour v2/Goldmark renders GFM and `x/ansi` provides ANSI-safe grapheme measurement, truncation, Kitty graphics encoding, capability responses, and virtual image placement. `x/term` remains limited to pre-TUI password input, terminal detection, and sizing fallback.
diff --git a/go.mod b/go.mod
index dae00d4..cdd105a 100644
--- a/go.mod
+++ b/go.mod
@@ -1,43 +1,47 @@
module github.com/merefield/termcourse
-go 1.27.2
+go 1.27.3
require (
charm.land/bubbles/v2 v2.2.1
- charm.land/bubbletea/v2 v2.0.10
+ charm.land/bubbletea/v2 v2.1.1
charm.land/glamour/v2 v2.0.1
charm.land/lipgloss/v2 v2.0.6
github.com/charmbracelet/colorprofile v0.4.3
- github.com/charmbracelet/ultraviolet v0.0.0-20260812204455-68fa937c71be
- github.com/charmbracelet/x/ansi v0.11.8
+ github.com/charmbracelet/ultraviolet v0.0.0-20261023060817-a45b7c86333f
+ github.com/charmbracelet/x/ansi v0.11.9
github.com/charmbracelet/x/term v0.2.2
github.com/joho/godotenv v1.5.1
- github.com/yuin/goldmark v1.7.17
- golang.org/x/image v0.45.0
- golang.org/x/sys v0.48.0
- golang.org/x/text v0.42.0
+ github.com/yuin/goldmark v1.8.7
+ golang.org/x/image v0.47.0
+ golang.org/x/sys v0.49.0
+ golang.org/x/text v0.43.0
gopkg.in/yaml.v3 v3.0.1
)
require (
- github.com/alecthomas/chroma/v2 v2.20.0 // indirect
+ github.com/alecthomas/chroma/v2 v2.27.0 // indirect
+ github.com/alecthomas/repr v0.5.4 // indirect
github.com/atotto/clipboard v0.1.4 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
- github.com/charmbracelet/x/exp/golden v0.0.0-20260816001655-68d539dca504 // indirect
- github.com/charmbracelet/x/exp/slice v0.0.0-20260816001655-68d539dca504 // indirect
+ github.com/charmbracelet/x/exp/golden v0.1.0 // indirect
+ github.com/charmbracelet/x/exp/slice v0.1.0 // indirect
github.com/charmbracelet/x/termios v0.1.1 // indirect
github.com/charmbracelet/x/windows v0.2.2 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
- github.com/dlclark/regexp2 v1.11.5 // indirect
+ github.com/dlclark/regexp2/v2 v2.13.0 // indirect
github.com/gorilla/css v1.0.1 // indirect
+ github.com/kr/pretty v0.3.1 // indirect
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
- github.com/mattn/go-runewidth v0.0.27 // indirect
+ github.com/mattn/go-runewidth v0.0.31 // indirect
github.com/microcosm-cc/bluemonday v1.0.27 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
- github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
+ github.com/rogpeppe/go-internal v1.16.0 // indirect
+ github.com/xo/terminfo v1.3.1 // indirect
github.com/yuin/goldmark-emoji v1.0.6 // indirect
- golang.org/x/net v0.39.0 // indirect
- golang.org/x/sync v0.23.0 // indirect
+ golang.org/x/net v0.62.0 // indirect
+ golang.org/x/sync v0.24.0 // indirect
+ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
)
diff --git a/go.sum b/go.sum
index 5a59748..a20421e 100644
--- a/go.sum
+++ b/go.sum
@@ -1,7 +1,7 @@
charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU=
charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc=
-charm.land/bubbletea/v2 v2.0.10 h1:oolvo20VBpI0PfqE7iFjkZ1bx0WpmXGfnKz5Yldjq5o=
-charm.land/bubbletea/v2 v2.0.10/go.mod h1:QOatcnhOjYIfxzUSTz6raF7Ex4R/rIuHa3SnBdCCpMc=
+charm.land/bubbletea/v2 v2.1.1 h1:S1S9l37pCZGrj1JexBcr9x4Nr3MVeM42InqCYM/tDpU=
+charm.land/bubbletea/v2 v2.1.1/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU=
charm.land/glamour/v2 v2.0.1 h1:xl+r00A4aJWU0z8fgwKd9fQQ4rsphqGUzuEiXZP5n+c=
charm.land/glamour/v2 v2.0.1/go.mod h1:jo9z8XqVKPeEFMVdvCRLGk++RyJ3CdUwgNr7EvXLw3k=
charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=
@@ -10,10 +10,10 @@ github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0=
github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
-github.com/alecthomas/chroma/v2 v2.20.0 h1:sfIHpxPyR07/Oylvmcai3X/exDlE8+FA820NTz+9sGw=
-github.com/alecthomas/chroma/v2 v2.20.0/go.mod h1:e7tViK0xh/Nf4BYHl00ycY6rV7b8iXBksI9E359yNmA=
-github.com/alecthomas/repr v0.5.1 h1:E3G4t2QbHTSNpPKBgMTln5KLkZHLOcU7r37J4pXBuIg=
-github.com/alecthomas/repr v0.5.1/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
+github.com/alecthomas/chroma/v2 v2.27.0 h1:FodwmyOBgJULFYmDqibcp9pvfDLWdtPRh9v/r5BXYZs=
+github.com/alecthomas/chroma/v2 v2.27.0/go.mod h1:NjJ3ciIgrqBNeIkWZ4e46nseoLDslxU1LmfCoL+wcY8=
+github.com/alecthomas/repr v0.5.4 h1:OVP7JEcuzU9CCDsT6STCr3rg17oQfWILtPWd2EG0uN4=
+github.com/alecthomas/repr v0.5.4/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o=
@@ -22,14 +22,14 @@ github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuP
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q=
github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q=
-github.com/charmbracelet/ultraviolet v0.0.0-20260812204455-68fa937c71be h1:qEvkJy1sjJXP+yf8IH2o13NV+Rh4nIUHjaLNJ+pWxpI=
-github.com/charmbracelet/ultraviolet v0.0.0-20260812204455-68fa937c71be/go.mod h1:nAw0d9PhFp1qdzi2xhQU5YOu5sVpDIHWlaW2Uz/bCro=
-github.com/charmbracelet/x/ansi v0.11.8 h1:JMFwp0CgDC2+jcOB162HH5k7I3FVbgFSMMYg7dSPBQQ=
-github.com/charmbracelet/x/ansi v0.11.8/go.mod h1:ZNN+3mXny/516oTQPLMPIBeSINvNJJQ8uQXDgbeJxY0=
-github.com/charmbracelet/x/exp/golden v0.0.0-20260816001655-68d539dca504 h1:6OnDxYzAjEAzuWmF1AFnqy3AoFOQBcnTCLfE9LZjc5Y=
-github.com/charmbracelet/x/exp/golden v0.0.0-20260816001655-68d539dca504/go.mod h1:6fMpcW6iwN/kX+xJ52eqVWsDiBTe0UJD24JLoHFe+P0=
-github.com/charmbracelet/x/exp/slice v0.0.0-20260816001655-68d539dca504 h1:Z0hBPQ9hslsfpFRRdMn+4cjnb3LK6FQH58hQkXrXv0A=
-github.com/charmbracelet/x/exp/slice v0.0.0-20260816001655-68d539dca504/go.mod h1:vqEfX6xzqW1pKKZUUiFOKg0OQ7bCh54Q2vR/tserrRA=
+github.com/charmbracelet/ultraviolet v0.0.0-20261023060817-a45b7c86333f h1:D2JpB65eehsnkEwEG401dMBSNYtTDgvKXZZSl7ZCxWI=
+github.com/charmbracelet/ultraviolet v0.0.0-20261023060817-a45b7c86333f/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio=
+github.com/charmbracelet/x/ansi v0.11.9 h1:kIrqLBxtTVbLyyHO2Evoi93EjQo1mylWmpNEsfPxXAM=
+github.com/charmbracelet/x/ansi v0.11.9/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w=
+github.com/charmbracelet/x/exp/golden v0.1.0 h1:qgUxGaHX4I8Fg077vD+54+qFmDWrgO19lTCQLblHWko=
+github.com/charmbracelet/x/exp/golden v0.1.0/go.mod h1:6fMpcW6iwN/kX+xJ52eqVWsDiBTe0UJD24JLoHFe+P0=
+github.com/charmbracelet/x/exp/slice v0.1.0 h1:m46dwuDf3M5SFYMRhxYkLC6z9WnENGVKbcbJlp13/og=
+github.com/charmbracelet/x/exp/slice v0.1.0/go.mod h1:vqEfX6xzqW1pKKZUUiFOKg0OQ7bCh54Q2vR/tserrRA=
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
@@ -40,43 +40,54 @@ github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSE
github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
-github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
-github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
+github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
+github.com/dlclark/regexp2/v2 v2.13.0 h1:sGPfGE1Bx7H3F9vcCdLrKUFvnau7DGiQZxHPQ6rMMs4=
+github.com/dlclark/regexp2/v2 v2.13.0/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU=
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
+github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
+github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
+github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss=
github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
-github.com/mattn/go-runewidth v0.0.27 h1:Feg/Oou5zI/wnpgDF6omIU0OokC9GxLC/WRknhVlIR0=
-github.com/mattn/go-runewidth v0.0.27/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8=
+github.com/mattn/go-runewidth v0.0.31 h1:1oCV4ReTlosDBc6rYRw5cL8S/4y8iv5oRl4SJ5IBgwo=
+github.com/mattn/go-runewidth v0.0.31/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8=
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
+github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
-github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
-github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
-github.com/yuin/goldmark v1.7.17 h1:p36OVWwRb246iHxA/U4p8OPEpOTESm4n+g+8t0EE5uA=
-github.com/yuin/goldmark v1.7.17/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
+github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
+github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g=
+github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs=
+github.com/xo/terminfo v1.3.1 h1:4ZwPCuu4PEFw0PkNp3Hv/x3gqvgLCzYhurszsj101cM=
+github.com/xo/terminfo v1.3.1/go.mod h1:lGzkSo8Fe7IRh/w+Gqz7n5mDog4FVXCj3gy/DYTBqio=
+github.com/yuin/goldmark v1.8.7 h1:XT/tNqCIbabh0ln675w4x3dv04kQBKi8NwYqi9IJaxI=
+github.com/yuin/goldmark v1.8.7/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
github.com/yuin/goldmark-emoji v1.0.6 h1:QWfF2FYaXwL74tfGOW5izeiZepUDroDJfWubQI9HTHs=
github.com/yuin/goldmark-emoji v1.0.6/go.mod h1:ukxJDKFpdFb5x0a5HqbdlcKtebh086iJpI31LTKmWuA=
-golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
-golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
-golang.org/x/image v0.45.0 h1:FMb1nTbH5H9vF55SriQHgFw5GnNL9Jg6L25BwXKzhB0=
-golang.org/x/image v0.45.0/go.mod h1:n62x/7RqlwXDvGsSU4u6IUTUf6KghUZ9Bt7cG/T9Fx4=
-golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=
-golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=
-golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
-golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
-golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
-golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
-golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
-golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
-gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
+golang.org/x/image v0.47.0 h1:za/8gVz++PPZqmZJBNSISICN5Rrj5zixP/8K++fgmqo=
+golang.org/x/image v0.47.0/go.mod h1:IkN5o4A7vq55vXN8FWjjnhg9Rs2GOtffqsSi9mWAKYE=
+golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
+golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
+golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
+golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
+golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
+golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
+golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
+golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/tools/duplication/README.md b/tools/duplication/README.md
new file mode 100644
index 0000000..9d9a32d
--- /dev/null
+++ b/tools/duplication/README.md
@@ -0,0 +1,31 @@
+# Duplication ratchet
+
+Termcourse uses the CI jobs and checker from [Codexometer](https://github.com/merefield/codexometer/tree/20c5f98198d27fb5342742759498bb8f72f488a0/tools/duplication), with a Go-only policy. The pinned jscpd scanner runs on tracked Go files. Vendored and generated files are excluded.
+
+| Production scan | Minimum tokens and lines | CI policy |
+| --- | --- | --- |
+| `exact-50` | 50 tokens, 5 lines | Gated |
+| `exact-100` | 100 tokens, 10 lines | Gated separately |
+| `renamed-50` and `renamed-100` | Same thresholds, with consistent identifier and literal normalisation | Report-only |
+
+Each exact scan independently limits clone count, duplicated lines and duplicated tokens. Test files have a separate report with the 50-token scans. The `duplication-report` artifact contains the per-scan totals, source locations and matched fragments.
+
+## Baseline lifecycle
+
+The first successful CI push on `master` writes the initial numerical baseline after the duplication check and the Go test matrix pass. Later checks use the checker, policy and stored baseline from the PR base or the commit before the push. For each gated metric, they use the lower of the stored limit and the freshly measured base value. Successful `master` builds commit tighter limits when the measurements improve.
+
+The writer is the only job with repository write access. It commits `baseline.json` alone, skips stale builds and uses a normal non-force push. Repository rules must allow that push. A failed write leaves a `duplication-baseline-candidate` artifact for diagnosis.
+
+## Local checks
+
+Run from the repository root with Node 24:
+
+```sh
+npm ci --prefix tools/duplication --ignore-scripts
+npm --prefix tools/duplication test
+npm --prefix tools/duplication run check
+```
+
+For an exact PR comparison, use a separate worktree at the PR base and run that worktree's checker with `--base` pointing to it and `--root` pointing to the candidate checkout. The check scans tracked files, so stage any new Go files before running it.
+
+When checker code changes, CI verifies that the candidate reproduces the trusted checker's results. For a policy change, run `node tools/duplication/verify.mjs --prepare-migration --root "$PWD" --base /path/to/base-worktree --reason "Explain the change"` and commit the resulting migration record. CI checks the change under both policies, and the baseline writer adopts the new measurements after merge.
diff --git a/tools/duplication/baseline.json b/tools/duplication/baseline.json
new file mode 100644
index 0000000..8f43452
--- /dev/null
+++ b/tools/duplication/baseline.json
@@ -0,0 +1,4 @@
+{
+ "schemaVersion": 1,
+ "status": "pending-bootstrap"
+}
diff --git a/tools/duplication/check.mjs b/tools/duplication/check.mjs
new file mode 100644
index 0000000..61a131d
--- /dev/null
+++ b/tools/duplication/check.mjs
@@ -0,0 +1,421 @@
+import { execFileSync } from "node:child_process";
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ readFileSync,
+ realpathSync,
+ writeFileSync,
+ appendFileSync,
+} from "node:fs";
+import { dirname, isAbsolute, relative, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { parseArgs } from "node:util";
+import {
+ commandData,
+ commandProperty,
+ limits,
+ metrics,
+ policyHash,
+ ratchet,
+ regressions,
+ relativeClone,
+ validateBaseline,
+ validateMigration,
+} from "./metrics.mjs";
+
+const directory = dirname(fileURLToPath(import.meta.url));
+const read = (path) => JSON.parse(readFileSync(path, "utf8"));
+const write = (path, data) =>
+ writeFileSync(path, JSON.stringify(data, null, 2) + "\n");
+const git = (root, ...args) =>
+ execFileSync("git", ["-C", root, ...args], { encoding: "utf8" }).trim();
+
+export function sourceFiles(root, policy, cohort) {
+ const tracked = execFileSync("git", ["-C", root, "ls-files", "-z"], {
+ encoding: "utf8",
+ })
+ .split("\0")
+ .filter(Boolean)
+ .sort();
+ return tracked.filter((file) => {
+ if (
+ !policy[cohort].some((pattern) => new RegExp(pattern).test(file)) ||
+ policy.exclude.some((pattern) => new RegExp(pattern).test(file)) ||
+ (cohort === "production" && file.endsWith("_test.go"))
+ )
+ return false;
+ const path = resolve(root, file),
+ within = relative(root, realpathSync(path));
+ if (
+ isAbsolute(within) ||
+ within.startsWith("..") ||
+ !lstatSync(path).isFile()
+ )
+ throw new Error(`Refusing non-regular/outside source: ${file}`);
+ if (lstatSync(path).size > policy.maxBytes)
+ throw new Error(`Source exceeds scanner size limit: ${file}`);
+ return !/(^|\n)\/\/ Code generated [^\n]*DO NOT EDIT\./.test(
+ readFileSync(path, "utf8").slice(0, 4096),
+ );
+ });
+}
+
+function scan(
+ root,
+ policy,
+ cohort,
+ spec,
+ artifactRoot,
+ {
+ group = cohort,
+ nativeBaseline,
+ seed = false,
+ scanner = resolve(directory, "node_modules/jscpd/run-jscpd.js"),
+ } = {},
+) {
+ const destination = resolve(artifactRoot, group, spec.id);
+ mkdirSync(destination, { recursive: true });
+ const files = sourceFiles(root, policy, cohort);
+ if (!files.length) throw new Error(`No ${cohort} sources selected`);
+ const config = resolve(destination, "config.json");
+ write(config, policy.jscpd);
+ write(resolve(destination, "inputs.json"), {
+ commit: git(root, "rev-parse", "HEAD"),
+ files,
+ });
+ const args = [
+ scanner,
+ "--config",
+ config,
+ "--workers",
+ "1",
+ "--absolute",
+ "--no-colors",
+ "--no-tips",
+ "--fail-on-empty",
+ "--min-tokens",
+ String(spec.minTokens),
+ "--min-lines",
+ String(spec.minLines),
+ "--output",
+ destination,
+ ...(spec.renamed
+ ? ["--ignore-identifiers=consistent", "--ignore-literals"]
+ : []),
+ ...(nativeBaseline
+ ? ["--baseline", nativeBaseline, ...(seed ? ["--update-baseline"] : [])]
+ : []),
+ ...files,
+ ];
+ execFileSync(process.execPath, args, {
+ cwd: root,
+ encoding: "utf8",
+ maxBuffer: 16 * 1024 * 1024,
+ });
+ const path = resolve(destination, "jscpd-report.json"),
+ report = read(path);
+ report.duplicates = report.duplicates.map((clone) =>
+ relativeClone(clone, root),
+ );
+ write(path, report);
+ return {
+ metrics: metrics(report),
+ report: relative(artifactRoot, path).replaceAll("\\", "/"),
+ clones: report.duplicates,
+ };
+}
+
+export function markdown(result) {
+ const value = (scan, metric) =>
+ `${scan.metrics[metric]} / ${scan.limits?.[metric] ?? "initial"}`;
+ const table = (scans, reportOnly = false) => {
+ const headings = [
+ "Scan",
+ "Clones",
+ "Duplicated lines",
+ "Duplicated tokens",
+ "Result",
+ ];
+ const rows = scans.map((scan) => [
+ scan.id,
+ ...["clones", "duplicatedLines", "duplicatedTokens"].map((metric) =>
+ reportOnly ? String(scan.metrics[metric]) : value(scan, metric),
+ ),
+ reportOnly
+ ? "REPORT ONLY"
+ : scan.regressions.length
+ ? "FAIL"
+ : result.bootstrap
+ ? "BOOTSTRAP"
+ : "PASS",
+ ]);
+ const line = (row) => `| ${row.join(" | ")} |`;
+ return [
+ line(headings),
+ "| --- | ---: | ---: | ---: | --- |",
+ ...rows.map(line),
+ ];
+ };
+ const locations = result.scans
+ .flatMap((scan) =>
+ scan.clones
+ .filter((clone) => clone.isNew)
+ .map((clone) => ({ scan, clone })),
+ )
+ .slice(0, 20);
+ const safe = (text) =>
+ String(text)
+ .replaceAll("&", "&")
+ .replaceAll("<", "<")
+ .replaceAll(">", ">")
+ .replaceAll("|", "|")
+ .replaceAll("`", "`")
+ .replaceAll("\n", " ");
+ return [
+ result.migration
+ ? "## Duplication ratchet — proposed policy"
+ : "## Duplication ratchet",
+ result.bootstrap
+ ? "Initial measurement: no historical limit applied. The first successful master build persists the baseline."
+ : "Production must not increase clone counts, duplicated lines or duplicated tokens in either exact scan.",
+ "",
+ "Values below are actual / limit; percentages are informational only.",
+ "",
+ ...table(result.scans),
+ ...(result.advisory?.length
+ ? [
+ "",
+ "### Normalised production duplication (report-only)",
+ "",
+ ...table(result.advisory, true),
+ ]
+ : []),
+ ...(result.tests?.length
+ ? [
+ "",
+ "### Test-source duplication (report-only)",
+ "",
+ ...table(result.tests, true),
+ ]
+ : []),
+ "",
+ ...result.scans.flatMap((scan) =>
+ scan.regressions.map(
+ (v) =>
+ `- **${scan.id}: ${v.metric} ${v.limit} → ${v.actual} (+${v.increase})**`,
+ ),
+ ),
+ "",
+ "### New clone candidates relative to the PR base",
+ ...locations.map(
+ ({ scan, clone }) =>
+ `- ${scan.id}: ${safe(clone.firstFile.name)}:${clone.firstFile.start}-${clone.firstFile.end} ↔ ${safe(clone.secondFile.name)}:${clone.secondFile.start}-${clone.secondFile.end}`,
+ ),
+ "",
+ "Download the duplication-report artifact: result.json contains limits/deltas and clone pairs; each jscpd-report.json contains exact source fragments. Tests are report-only. Normalised matches are candidates, not proof of equivalent behaviour.",
+ "Reproduce: npm ci --prefix tools/duplication --ignore-scripts && npm --prefix tools/duplication run check",
+ "",
+ ].join("\n");
+}
+
+export function run(options = {}) {
+ const root = realpathSync(
+ resolve(options.root || resolve(directory, "../..")),
+ );
+ const base = options.base ? realpathSync(resolve(options.base)) : null;
+ const output = resolve(options.output || resolve(directory, "reports"));
+ mkdirSync(output, { recursive: true });
+ const policy = read(
+ resolve(options.policy || resolve(directory, "policy.json")),
+ );
+ const baselinePath =
+ options.baseline ||
+ options.baselinePath ||
+ resolve(directory, "baseline.json");
+ const baseline = read(baselinePath);
+ const migration =
+ baseline.status === "established" &&
+ baseline.policyHash !== policyHash(policy)
+ ? validateMigration(
+ read(resolve(root, "tools/duplication/migration.json")),
+ baseline,
+ policy,
+ )
+ : null;
+ if (!migration) validateBaseline(baseline, policy);
+ const scanner = resolve(
+ options.scanner || resolve(directory, "node_modules/jscpd/run-jscpd.js"),
+ );
+ const version = execFileSync(process.execPath, [scanner, "--version"], {
+ encoding: "utf8",
+ }).trim();
+ if (version !== `jscpd ${policy.toolVersion}`)
+ throw new Error(`Unexpected scanner version: ${version}`);
+ const baseHasPolicy =
+ base && existsSync(resolve(base, "tools/duplication/policy.json"));
+ const bootstrap = baseline.status === "pending-bootstrap" && !baseHasPolicy;
+ if (
+ baseHasPolicy &&
+ !readFileSync(resolve(root, "tools/duplication/baseline.json")).equals(
+ readFileSync(resolve(base, "tools/duplication/baseline.json")),
+ )
+ ) {
+ throw new Error("The baseline is owned by master CI; PRs must not edit it");
+ }
+ if (migration && !base && !options["update-baseline"])
+ throw new Error(
+ "A policy migration requires an actual master-base comparison",
+ );
+ const sourceCommit = git(root, "rev-parse", "HEAD");
+ const result = {
+ schemaVersion: 1,
+ toolVersion: policy.toolVersion,
+ policyHash: policyHash(policy),
+ sourceCommit,
+ baseCommit: base ? git(base, "rev-parse", "HEAD") : null,
+ bootstrap,
+ migration: migration
+ ? {
+ fromPolicyHash: policyHash(migration.fromPolicy),
+ toPolicyHash: policyHash(policy),
+ reason: migration.reason,
+ }
+ : null,
+ scans: [],
+ advisory: [],
+ tests: [],
+ };
+ for (const spec of policy.scans) {
+ const native = resolve(output, `base-${spec.id}.json`);
+ const previous = base
+ ? scan(base, policy, "production", spec, output, {
+ group: "base",
+ nativeBaseline: native,
+ seed: true,
+ scanner,
+ })
+ : null;
+ const current = scan(root, policy, "production", spec, output, {
+ nativeBaseline: base ? native : null,
+ scanner,
+ });
+ const ceiling =
+ baseline.status === "established" && !migration
+ ? baseline.scans[spec.id]
+ : null;
+ const baseMetrics = bootstrap ? null : previous?.metrics;
+ result.scans.push({
+ id: spec.id,
+ ...current,
+ ceiling,
+ baseMetrics,
+ limits: limits(ceiling, baseMetrics),
+ regressions: regressions(current.metrics, ceiling, baseMetrics),
+ });
+ }
+ for (const spec of policy.advisoryScans || []) {
+ result.advisory.push({
+ id: spec.id,
+ ...scan(root, policy, "production", spec, output, {
+ group: "advisory",
+ scanner,
+ }),
+ });
+ }
+ const testScans = [...policy.scans, ...(policy.advisoryScans || [])].filter(
+ (spec) => spec.minTokens === 50,
+ );
+ for (const spec of testScans) {
+ if (sourceFiles(root, policy, "tests").length)
+ result.tests.push({
+ id: spec.id,
+ ...scan(root, policy, "tests", spec, output, { scanner }),
+ });
+ }
+ const observed = Object.fromEntries(
+ result.scans.map((scan) => [scan.id, scan.metrics]),
+ );
+ const failed = result.scans.some((scan) => scan.regressions.length);
+ write(resolve(output, "result.json"), result);
+ write(resolve(output, "baseline.json"), {
+ schemaVersion: 1,
+ status: "established",
+ toolVersion: policy.toolVersion,
+ policyHash: policyHash(policy),
+ sourceCommit,
+ scans: observed,
+ });
+ const summary = markdown(result);
+ writeFileSync(resolve(output, "summary.md"), summary);
+ if (
+ !options["no-summary"] &&
+ options.reportToGitHub !== false &&
+ process.env.GITHUB_STEP_SUMMARY
+ )
+ appendFileSync(process.env.GITHUB_STEP_SUMMARY, summary);
+ process.stdout.write(
+ process.env.GITHUB_ACTIONS || options["no-summary"]
+ ? `Duplication check ${failed ? "failed" : "passed"}; see the job summary and duplication-report artifact.\n`
+ : summary + "\n",
+ );
+ let annotations = 0;
+ for (const scan of result.scans.filter((scan) => scan.regressions.length)) {
+ const message = `${scan.id}: ${scan.regressions.map((v) => `${v.metric} ${v.limit} → ${v.actual}`).join("; ")}`;
+ const candidates = scan.clones.filter((clone) => clone.isNew);
+ for (const clone of (candidates.length ? candidates : scan.clones).slice(
+ 0,
+ 5,
+ )) {
+ if (
+ annotations++ >= 20 ||
+ options.reportToGitHub === false ||
+ !process.env.GITHUB_ACTIONS
+ )
+ break;
+ process.stdout.write(
+ `::error file=${commandProperty(clone.firstFile.name)},line=${clone.firstFile.start}::${commandData(message + `; matching code: ${clone.secondFile.name}:${clone.secondFile.start}`)}\n`,
+ );
+ }
+ }
+ if (failed)
+ throw new Error(
+ "Duplication regressed; see result.json and source-location reports. Do not raise the baseline to make CI pass.",
+ );
+ if (options["update-baseline"]) {
+ if (base)
+ throw new Error("Baseline updates are not allowed during PR comparisons");
+ const next = ratchet(
+ migration ? { schemaVersion: 1, status: "pending-bootstrap" } : baseline,
+ observed,
+ sourceCommit,
+ policy,
+ );
+ if (next) write(baselinePath, next);
+ }
+ return result;
+}
+
+if (
+ process.argv[1] &&
+ resolve(process.argv[1]) === fileURLToPath(import.meta.url)
+) {
+ try {
+ const { values } = parseArgs({
+ options: {
+ root: { type: "string" },
+ base: { type: "string" },
+ output: { type: "string" },
+ policy: { type: "string" },
+ baseline: { type: "string" },
+ scanner: { type: "string" },
+ "no-summary": { type: "boolean" },
+ "update-baseline": { type: "boolean" },
+ },
+ });
+ run(values);
+ } catch (error) {
+ console.error(error.message);
+ process.exitCode = 1;
+ }
+}
diff --git a/tools/duplication/check.test.mjs b/tools/duplication/check.test.mjs
new file mode 100644
index 0000000..86b83a1
--- /dev/null
+++ b/tools/duplication/check.test.mjs
@@ -0,0 +1,593 @@
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import {
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+ mkdirSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import test from "node:test";
+import { markdown, run as check, sourceFiles } from "./check.mjs";
+import { changedTooling, prepareMigration, verify } from "./verify.mjs";
+import {
+ commandData,
+ commandProperty,
+ metrics,
+ policyHash,
+ ratchet,
+ regressions,
+ relativeClone,
+ validateBaseline,
+ validateMigration,
+} from "./metrics.mjs";
+
+const policy = JSON.parse(
+ readFileSync(new URL("./policy.json", import.meta.url), "utf8"),
+);
+const pending = { schemaVersion: 1, status: "pending-bootstrap" };
+const counts = { clones: 4, duplicatedLines: 40, duplicatedTokens: 400 };
+const observed = () =>
+ Object.fromEntries(policy.scans.map((scan) => [scan.id, { ...counts }]));
+const baseline = () => ratchet(pending, observed(), "a".repeat(40), policy);
+// Expected regression fixtures must not emit real CI errors or job summaries.
+const run = (options) => check({ ...options, reportToGitHub: false });
+
+test("first measurement establishes the benchmark without an arbitrary limit", () => {
+ const current = observed();
+ current["exact-50"] = {
+ clones: 999,
+ duplicatedLines: 9999,
+ duplicatedTokens: 99999,
+ };
+ const established = ratchet(pending, current, "a".repeat(40), policy);
+ assert.equal(established.status, "established");
+ assert.deepEqual(established.scans, current);
+ assert.deepEqual(regressions(current["exact-50"]), []);
+ assert.equal(validateBaseline(established, policy), established);
+});
+
+test("every metric must be equal or lower, independently of other improvements", () => {
+ assert.deepEqual(regressions(counts, counts), []);
+ for (const metric of Object.keys(counts)) {
+ const current = {
+ clones: 0,
+ duplicatedLines: 0,
+ duplicatedTokens: 0,
+ [metric]: counts[metric] + 1,
+ };
+ assert.deepEqual(regressions(current, counts), [
+ {
+ metric,
+ actual: counts[metric] + 1,
+ limit: counts[metric],
+ increase: 1,
+ },
+ ]);
+ }
+ assert.equal(regressions(counts, { ...counts, clones: 3 }).length, 1);
+});
+
+test("actual base metrics prevent stale committed ceilings from hiding regressions", () => {
+ const stale = { clones: 10, duplicatedLines: 100, duplicatedTokens: 1000 };
+ assert.equal(
+ regressions({ ...counts, duplicatedLines: 41 }, stale, counts)[0].limit,
+ 40,
+ );
+});
+
+test("ratcheting only tightens and unchanged metrics do not rewrite provenance", () => {
+ const original = baseline();
+ assert.equal(ratchet(original, observed(), "b".repeat(40), policy), null);
+ const improved = observed();
+ improved["exact-50"].duplicatedTokens--;
+ const tighter = ratchet(original, improved, "b".repeat(40), policy);
+ assert.equal(tighter.sourceCommit, "b".repeat(40));
+ assert.equal(tighter.scans["exact-50"].duplicatedTokens, 399);
+ improved["exact-100"].clones++;
+ assert.throws(
+ () => ratchet(original, improved, "b".repeat(40), policy),
+ /Refusing to increase/,
+ );
+});
+
+test("missing, corrupt and incompatible baselines fail rather than rebootstrap", () => {
+ for (const invalid of [
+ null,
+ {},
+ { ...pending, scans: {} },
+ { ...baseline(), policyHash: "wrong" },
+ { ...baseline(), sourceCommit: "not-a-sha" },
+ { ...baseline(), scans: {} },
+ ]) {
+ assert.throws(() => validateBaseline(invalid, policy));
+ }
+ for (const invalid of [null, -1, NaN, Infinity, 1.5, "4"]) {
+ assert.throws(() =>
+ metrics({ statistics: { total: { ...counts, clones: invalid } } }),
+ );
+ }
+ assert.notEqual(
+ policyHash(policy),
+ policyHash({ ...policy, maxBytes: policy.maxBytes + 1 }),
+ );
+});
+
+test("policy migrations preserve the old master ceiling and require exact provenance", () => {
+ const next = { ...policy, toolVersion: "5.4.3" };
+ const migration = {
+ schemaVersion: 1,
+ fromPolicy: policy,
+ toPolicyHash: policyHash(next),
+ reason: "Upgrade the pinned scanner",
+ };
+ assert.equal(validateMigration(migration, baseline(), next), migration);
+ for (const invalid of [
+ null,
+ { ...migration, reason: " " },
+ { ...migration, toPolicyHash: "wrong" },
+ { ...migration, fromPolicy: next },
+ { ...migration, fromPolicy: { ...policy, maxBytes: 1 } },
+ ]) {
+ assert.throws(() => validateMigration(invalid, baseline(), next));
+ }
+});
+
+test("reports retain actionable paths, ranges and exact source payload", () => {
+ const clone = {
+ kind: "renamed",
+ fragment: 'const text = "unchanged";\n',
+ firstFile: { name: "/repo/a.go", start: 3, end: 9 },
+ secondFile: { name: "/repo/b.go", start: 13, end: 19 },
+ };
+ const relative = relativeClone(clone, "/repo");
+ assert.deepEqual(relative, {
+ ...clone,
+ firstFile: { ...clone.firstFile, name: "a.go" },
+ secondFile: { ...clone.secondFile, name: "b.go" },
+ });
+ assert.throws(() =>
+ relativeClone(
+ { ...clone, firstFile: { ...clone.firstFile, name: "/outside/a.go" } },
+ "/repo",
+ ),
+ );
+ const result = {
+ bootstrap: false,
+ scans: [
+ {
+ id: "exact-50",
+ metrics: counts,
+ regressions: [{ metric: "clones", limit: 3, actual: 4, increase: 1 }],
+ clones: [{ ...relative, isNew: true }],
+ },
+ ],
+ };
+ const summary = markdown(result);
+ assert.match(summary, /clones 3 → 4/);
+ assert.match(summary, /a.go:3-9/);
+ assert.match(summary, /b.go:13-19/);
+ assert.match(summary, /source fragments/);
+ assert.match(
+ summary,
+ /\| Scan \| Clones \| Duplicated lines \| Duplicated tokens \| Result \|/,
+ );
+ assert.match(
+ summary,
+ /\| exact-50 \| 4 \/ initial \| 40 \/ initial \| 400 \/ initial \| FAIL \|/,
+ );
+ const withTests = markdown({
+ ...result,
+ tests: [{ id: "exact-50", metrics: counts }],
+ });
+ assert.match(withTests, /Test-source duplication \(report-only\)/);
+ assert.match(withTests, /REPORT ONLY/);
+});
+
+test("untrusted names cannot inject workflow commands or summary HTML", () => {
+ assert.equal(commandData("x%\r\n::error::bad"), "x%25%0D%0A::error::bad");
+ assert.equal(commandProperty("a,b:1\nx"), "a%2Cb%3A1%0Ax");
+ const result = {
+ bootstrap: false,
+ scans: [
+ {
+ id: "exact-50",
+ metrics: counts,
+ regressions: [],
+ clones: [
+ {
+ isNew: true,
+ firstFile: { name: "