link-assistant-router 1.4.2

Link.Assistant.Router — Claude MAX OAuth proxy and token gateway for Anthropic APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
name: CI/CD Pipeline

on:
  push:
    branches:
      - main
  pull_request:
    types: [opened, synchronize, reopened, labeled, unlabeled]
  workflow_dispatch:
    inputs:
      release_mode:
        description: 'Manual release mode'
        required: true
        type: choice
        default: 'instant'
        options:
          - instant
          - changelog-pr
      bump_type:
        description: 'Version bump type'
        required: true
        type: choice
        options:
          - patch
          - minor
          - major
      description:
        description: 'Release description (optional)'
        required: false
        type: string

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  # PR checks are disposable; release-capable main/manual runs must finish once
  # they start or cancellation can leave tags, crates, and releases out of sync.
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}

permissions:
  contents: read

env:
  CARGO_TERM_COLOR: always
  CARGO_NET_RETRY: '10'
  CARGO_HTTP_MULTIPLEXING: 'false'
  GIT_CONFIG_COUNT: '1'
  GIT_CONFIG_KEY_0: init.defaultBranch
  GIT_CONFIG_VALUE_0: main
  RUSTFLAGS: -Dwarnings
  # Support both CARGO_REGISTRY_TOKEN (cargo's native env var) and CARGO_TOKEN (for backwards compatibility)
  CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN || secrets.CARGO_TOKEN }}
  DOCKERHUB_IMAGE: konard/link-assistant-router

jobs:
  # === DETECT CHANGES - determines which jobs should run ===
  detect-changes:
    name: Detect Changes
    runs-on: ubuntu-latest
    timeout-minutes: 15
    if: github.event_name != 'workflow_dispatch'
    outputs:
      rs-changed: ${{ steps.changes.outputs.rs-changed }}
      toml-changed: ${{ steps.changes.outputs.toml-changed }}
      docs-changed: ${{ steps.changes.outputs.docs-changed }}
      workflow-changed: ${{ steps.changes.outputs.workflow-changed }}
      any-code-changed: ${{ steps.changes.outputs.any-code-changed }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          fetch-depth: 0

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable
        with:
          toolchain: 1.98.1

      - name: Install rust-script
        run: cargo install rust-script --version 0.36.0 --locked

      - name: Detect changes
        id: changes
        env:
          GITHUB_EVENT_NAME: ${{ github.event_name }}
          GITHUB_BASE_SHA: ${{ github.event.pull_request.base.sha }}
          GITHUB_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
        run: rust-script scripts/detect-code-changes.rs

  # === CHANGELOG CHECK - only runs on PRs with code changes ===
  # Docs-only PRs (./docs folder, markdown files) don't require changelog fragments
  changelog:
    name: Changelog Fragment Check
    runs-on: ubuntu-latest
    timeout-minutes: 15
    needs: [detect-changes]
    if: github.event_name == 'pull_request' && needs.detect-changes.outputs.any-code-changed == 'true'
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          fetch-depth: 0

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable
        with:
          toolchain: 1.98.1

      - name: Install rust-script
        run: cargo install rust-script --version 0.36.0 --locked

      - name: Check for changelog fragments
        env:
          GITHUB_BASE_REF: ${{ github.base_ref }}
        run: rust-script scripts/check-changelog-fragment.rs

  # === VERSION CHECK - prevents manual version modification in PRs ===
  # This ensures versions are only modified by the automated release pipeline
  version-check:
    name: Version Modification Check
    runs-on: ubuntu-latest
    timeout-minutes: 15
    if: github.event_name == 'pull_request'
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          fetch-depth: 0

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable
        with:
          toolchain: 1.98.1

      - name: Install rust-script
        run: cargo install rust-script --version 0.36.0 --locked

      - name: Check for manual version changes
        env:
          GITHUB_EVENT_NAME: ${{ github.event_name }}
          GITHUB_HEAD_REF: ${{ github.head_ref }}
          GITHUB_BASE_REF: ${{ github.base_ref }}
        run: rust-script scripts/check-version-modification.rs

  # Build and execute the separately shipped reverse-tunnel image. The echo
  # transport verifies entrypoint validation and the final autossh argv without
  # opening an external SSH connection.
  tunnel-image-smoke:
    name: Tunnel Image Smoke Test
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - name: Build tunnel image
        run: docker build --file docker/tunnel/Dockerfile --tag router-tunnel:test .
      - name: Missing configuration fails closed
        shell: bash
        run: |
          if docker run --rm router-tunnel:test 2>tunnel-error.log; then
            echo "tunnel image unexpectedly started without configuration" >&2
            exit 1
          fi
          grep -Fq "TUNNEL_SSH_HOST" tunnel-error.log
      - name: Complete configuration reaches autossh
        run: >-
          docker run --rm
          -e TUNNEL_SSH_HOST=far.example
          -e TUNNEL_SSH_USER=router
          -e TUNNEL_REMOTE_PORT=18080
          -e TUNNEL_SSH_KEY=/dev/null
          -e TUNNEL_KNOWN_HOSTS=/etc/hosts
          -e AUTOSSH_BIN=/bin/echo
          router-tunnel:test

  # === LINT AND FORMAT CHECK ===
  # Lint runs independently of changelog check - it's a fast check that should always run
  # See: https://github.com/link-assistant/hive-mind/pull/1024 for why this dependency was removed
  lint:
    name: Lint and Format Check
    runs-on: ubuntu-latest
    timeout-minutes: 30
    needs: [detect-changes]
    # Note: always() is required because detect-changes is skipped on workflow_dispatch,
    # and without always(), this job would also be skipped even though its condition includes workflow_dispatch.
    # See: https://github.com/actions/runner/issues/491
    if: |
      always() && !cancelled() && (
        github.event_name == 'push' ||
        github.event_name == 'workflow_dispatch' ||
        needs.detect-changes.outputs.any-code-changed == 'true' ||
        needs.detect-changes.outputs.docs-changed == 'true' ||
        needs.detect-changes.outputs.workflow-changed == 'true'
      )
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable
        with:
          toolchain: 1.98.1
          components: rustfmt, clippy

      - name: Install rust-script
        run: cargo install rust-script --version 0.36.0 --locked

      # Compilation-level cache, complementing the artifact cache below.
      # `actions/cache` is keyed on `Cargo.lock`, so a single dependency bump
      # misses the whole `target/` directory; sccache keys on each compilation
      # unit and still hits. Its GHA backend stores in the same Actions cache,
      # so no extra infrastructure is involved.
      - name: Set up sccache
        uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11

      # Scoped to this job rather than the workflow: a job without the step
      # above has no `sccache` binary, and `RUSTC_WRAPPER` pointing at a missing
      # executable fails every cargo invocation outright.
      - name: Route compilation through sccache
        run: |
          echo "SCCACHE_GHA_ENABLED=true" >> "$GITHUB_ENV"
          echo "RUSTC_WRAPPER=sccache" >> "$GITHUB_ENV"

      - name: Cache cargo registry
        uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            target
          key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: |
            ${{ runner.os }}-cargo-

      - name: Check formatting
        run: cargo fmt --all -- --check

      - name: Verify Cargo.lock is current
        run: cargo check --locked --all-targets --all-features

      - name: Run Clippy
        run: cargo clippy --locked --all-targets --all-features

      - name: Build documentation
        env:
          RUSTDOCFLAGS: -D warnings
        run: cargo doc --locked --no-deps --all-features

      - name: Setup Node
        uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
        with:
          node-version: '24'
          cache: npm
          cache-dependency-path: ui/package-lock.json

      - name: Install admin console dependencies
        working-directory: ui
        run: npm ci

      - name: Build admin console
        working-directory: ui
        shell: bash
        run: |
          set -o pipefail
          npm run build 2>&1 | tee /tmp/admin-ui-build.log
          if grep -E '(^|[[:space:]])\(!\)|[Ww]arn(ing)?' /tmp/admin-ui-build.log; then
            echo "::error::Admin console build emitted a warning"
            exit 1
          fi

      - name: Verify embedded admin console bundle is current
        run: git diff --exit-code -- ui/dist

      - name: Check file size limit
        run: rust-script scripts/check-file-size.rs

      # This project's data structure is a links network, and the wording is
      # load-bearing rather than stylistic -- see the terminology section of
      # CONTRIBUTING.md. Rejected in identifiers and prose alike, any language.
      - name: Check terminology
        run: rust-script scripts/check-terminology.rs

      - name: Test release automation
        run: |
          rust-script --test scripts/version-and-commit.rs
          rust-script --test scripts/check-docker-platforms.rs
          rust-script --test scripts/check-github-releases.rs
          rust-script --test scripts/check-coverage.rs
          rust-script --test scripts/detect-code-changes.rs
          rust-script --test scripts/check-changelog-fragment.rs
          rust-script --test scripts/check-release-provenance.rs
          rust-script --test scripts/check-terminology.rs
          rust-script --test scripts/create-github-release.rs
          rust-script scripts/check-release-workflow.rs

  # === DEPENDENCY AUDIT ===
  # Both dependency surfaces the router carries: the Rust crates and the JS
  # toolchain that builds the admin console. Deliberately *not* in `build`'s
  # `needs`, because an advisory can be published against an unchanged tree —
  # that must raise a red check, not block an unrelated release.
  # See docs/security/review-2026-08.md for the review this job came from.
  audit:
    name: Dependency Audit
    runs-on: ubuntu-latest
    timeout-minutes: 30
    needs: [detect-changes]
    # Note: always() is required because detect-changes is skipped on workflow_dispatch.
    if: |
      always() && !cancelled() && (
        github.event_name == 'push' ||
        github.event_name == 'workflow_dispatch' ||
        needs.detect-changes.outputs.any-code-changed == 'true' ||
        needs.detect-changes.outputs.workflow-changed == 'true'
      )
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable
        with:
          toolchain: 1.98.1

      # Compilation-level cache, complementing the artifact cache below.
      # `actions/cache` is keyed on `Cargo.lock`, so a single dependency bump
      # misses the whole `target/` directory; sccache keys on each compilation
      # unit and still hits. Its GHA backend stores in the same Actions cache,
      # so no extra infrastructure is involved.
      - name: Set up sccache
        uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11

      # Scoped to this job rather than the workflow: a job without the step
      # above has no `sccache` binary, and `RUSTC_WRAPPER` pointing at a missing
      # executable fails every cargo invocation outright.
      - name: Route compilation through sccache
        run: |
          echo "SCCACHE_GHA_ENABLED=true" >> "$GITHUB_ENV"
          echo "RUSTC_WRAPPER=sccache" >> "$GITHUB_ENV"

      - name: Cache cargo registry
        uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            ~/.cargo/bin
          key: ${{ runner.os }}-cargo-audit-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: |
            ${{ runner.os }}-cargo-audit-

      - name: Install cargo-audit
        run: cargo install cargo-audit --version 0.22.2 --locked --force

      - name: Audit Rust dependencies
        run: cargo audit

      - name: Setup Node
        uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
        with:
          node-version: '24'

      - name: Audit admin console dependencies
        working-directory: ui
        run: npm audit --audit-level=high

  # === TEST ===
  # Test runs independently of changelog check
  test:
    name: Test (${{ matrix.os }})
    runs-on: ${{ matrix.os }}
    timeout-minutes: 45
    needs: [detect-changes, changelog]
    # Run if: push event, OR changelog succeeded, OR changelog was skipped (docs-only PR)
    if: always() && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || needs.changelog.result == 'success' || needs.changelog.result == 'skipped')
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, macos-latest, windows-latest]
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable
        with:
          toolchain: 1.98.1

      # Compilation-level cache, complementing the artifact cache below.
      # `actions/cache` is keyed on `Cargo.lock`, so a single dependency bump
      # misses the whole `target/` directory; sccache keys on each compilation
      # unit and still hits. Its GHA backend stores in the same Actions cache,
      # so no extra infrastructure is involved.
      - name: Set up sccache
        uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11

      # Scoped to this job rather than the workflow: a job without the step
      # above has no `sccache` binary, and `RUSTC_WRAPPER` pointing at a missing
      # executable fails every cargo invocation outright.
      - name: Route compilation through sccache
        run: |
          echo "SCCACHE_GHA_ENABLED=true" >> "$GITHUB_ENV"
          echo "RUSTC_WRAPPER=sccache" >> "$GITHUB_ENV"

      - name: Cache cargo registry
        uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            target
          key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: |
            ${{ runner.os }}-cargo-

      - name: Run tests
        if: runner.os != 'Windows'
        run: cargo test --locked --all-features --verbose

      - name: Compile Windows tests
        if: runner.os == 'Windows'
        run: cargo test --locked --all-features --verbose --no-run

      - name: Run Windows library and binary tests
        if: runner.os == 'Windows'
        run: cargo test --locked --all-features --verbose --lib --bins -- --test-threads=1

      - name: Run Windows integration tests with bounded targets
        if: runner.os == 'Windows'
        shell: pwsh
        run: |
          $ErrorActionPreference = 'Stop'
          $testFiles = Get-ChildItem tests -File -Filter '*_test.rs' | Sort-Object Name
          foreach ($testFile in $testFiles) {
            $target = $testFile.BaseName
            Write-Host "::group::Windows integration target $target"
            $arguments = @(
              'test', '--locked', '--all-features', '--verbose',
              '--test', $target, '--', '--test-threads=1'
            )
            $process = Start-Process -FilePath cargo -ArgumentList $arguments -NoNewWindow -PassThru
            if (-not $process.WaitForExit(180000)) {
              Stop-Process -Id $process.Id -Force -ErrorAction SilentlyContinue
              Write-Host '::endgroup::'
              throw "Windows integration target $target exceeded 180 seconds"
            }
            $exitCode = $process.ExitCode
            Write-Host '::endgroup::'
            if ($exitCode -ne 0) {
              exit $exitCode
            }
          }

      - name: Run doc tests
        run: cargo test --locked --doc --verbose

  # === COVERAGE ===
  # Instrument once on Linux; platform-specific behavior remains covered by the test matrix.
  coverage:
    name: Test Coverage
    runs-on: ubuntu-latest
    timeout-minutes: 45
    needs: [detect-changes, changelog]
    if: always() && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || needs.changelog.result == 'success' || needs.changelog.result == 'skipped')
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          fetch-depth: 0

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable
        with:
          toolchain: 1.98.1
          components: llvm-tools-preview

      - name: Cache coverage tools
        uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            ~/.cargo/bin
            ~/.cargo/.crates.toml
            ~/.cargo/.crates2.json
          key: ${{ runner.os }}-cargo-coverage-v2-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: |
            ${{ runner.os }}-cargo-coverage-v2-

      - name: Install coverage tools
        run: |
          if ! cargo llvm-cov --version 2>/dev/null | grep -Fqx 'cargo-llvm-cov 0.9.0'; then
            cargo install cargo-llvm-cov --version 0.9.0 --locked --force
          fi
          command -v rust-script >/dev/null || cargo install rust-script --version 0.36.0 --locked

      - name: Test coverage gate behavior
        run: rust-script --test scripts/check-coverage.rs

      - name: Run instrumented tests
        run: |
          cargo llvm-cov clean --workspace
          cargo llvm-cov --locked --all-features --workspace --no-report

      - name: Generate coverage reports
        run: |
          cargo llvm-cov report --json --summary-only --output-path coverage-summary.json
          cargo llvm-cov report --lcov --output-path lcov.info

      - name: Read default-branch baseline
        id: base-coverage
        shell: bash
        env:
          BASE_REF: ${{ github.base_ref }}
        run: |
          if [ -n "$BASE_REF" ] && git show "origin/${BASE_REF}:coverage-baseline.txt" > /tmp/base-coverage-baseline.txt 2>/dev/null; then
            echo "argument=--previous-baseline /tmp/base-coverage-baseline.txt" >> "$GITHUB_OUTPUT"
          fi

      - name: Enforce coverage floor and ratchet
        shell: bash
        env:
          BASELINE_ARGUMENT: ${{ steps.base-coverage.outputs.argument }}
          COVERAGE_EXCEPTION: ${{ contains(github.event.pull_request.labels.*.name, 'coverage-exception') }}
        run: |
          args=(--report coverage-summary.json --baseline coverage-baseline.txt --summary "$GITHUB_STEP_SUMMARY")
          if [ -n "$BASELINE_ARGUMENT" ]; then
            args+=(--previous-baseline /tmp/base-coverage-baseline.txt)
          fi
          if [ "$COVERAGE_EXCEPTION" = "true" ]; then
            args+=(--allow-decrease)
          fi
          rust-script scripts/check-coverage.rs "${args[@]}"

      - name: Require reviewable baseline update
        shell: bash
        run: |
          if ! git diff --exit-code -- coverage-baseline.txt; then
            echo "::error::Coverage changed the baseline. Commit coverage-baseline.txt so the ratchet update is reviewable."
            exit 1
          fi

      - name: Upload coverage report
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
        with:
          name: rust-lcov
          path: lcov.info
          if-no-files-found: error

  # === BUILD ===
  # Build package - only runs if lint and test pass
  build:
    name: Build Package
    runs-on: ubuntu-latest
    timeout-minutes: 30
    needs: [lint, test, coverage]
    if: always() && !cancelled() && needs.lint.result == 'success' && needs.test.result == 'success' && needs.coverage.result == 'success'
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable
        with:
          toolchain: 1.98.1

      # Compilation-level cache, complementing the artifact cache below.
      # `actions/cache` is keyed on `Cargo.lock`, so a single dependency bump
      # misses the whole `target/` directory; sccache keys on each compilation
      # unit and still hits. Its GHA backend stores in the same Actions cache,
      # so no extra infrastructure is involved.
      - name: Set up sccache
        uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11

      # Scoped to this job rather than the workflow: a job without the step
      # above has no `sccache` binary, and `RUSTC_WRAPPER` pointing at a missing
      # executable fails every cargo invocation outright.
      - name: Route compilation through sccache
        run: |
          echo "SCCACHE_GHA_ENABLED=true" >> "$GITHUB_ENV"
          echo "RUSTC_WRAPPER=sccache" >> "$GITHUB_ENV"

      - name: Cache cargo registry
        uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            target
          key: ${{ runner.os }}-cargo-build-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: |
            ${{ runner.os }}-cargo-build-

      - name: Build release
        run: cargo build --locked --release --verbose

      - name: Check package
        run: cargo package --locked --list

  # === AUTO RELEASE ===
  # Automatic release on push to main using changelog fragments
  # This job automatically bumps version based on fragments in changelog.d/
  auto-release:
    name: Auto Release
    needs: [lint, test, build]
    outputs:
      should-release: ${{ steps.check.outputs.should_release }}
      release-version: ${{ steps.current_version.outputs.version }}
    # Note: always() ensures consistent behavior with other jobs that depend on jobs using always().
    if: |
      always() && !cancelled() &&
      github.event_name == 'push' &&
      github.ref == 'refs/heads/main' &&
      needs.build.result == 'success'
    runs-on: ubuntu-latest
    timeout-minutes: 60
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable
        with:
          toolchain: 1.98.1

      - name: Install rust-script
        run: cargo install rust-script --version 0.36.0 --locked

      - name: Configure git
        run: rust-script scripts/git-config.rs

      - name: Determine bump type from changelog fragments
        id: bump_type
        run: rust-script scripts/get-bump-type.rs

      - name: Check if version already released or no fragments
        id: check
        env:
          HAS_FRAGMENTS: ${{ steps.bump_type.outputs.has_fragments }}
        run: rust-script scripts/check-release-needed.rs

      - name: Collect changelog and bump version
        id: version
        if: steps.check.outputs.should_release == 'true' && steps.check.outputs.skip_bump != 'true'
        run: |
          rust-script scripts/version-and-commit.rs \
            --bump-type "${{ steps.bump_type.outputs.bump_type }}"

      - name: Get current version
        id: current_version
        if: steps.check.outputs.should_release == 'true'
        run: rust-script scripts/get-version.rs

      - name: Build release
        if: steps.check.outputs.should_release == 'true'
        run: cargo build --locked --release

      - name: Publish to Crates.io
        if: steps.check.outputs.should_release == 'true'
        id: publish-crate
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN || secrets.CARGO_TOKEN }}
        run: rust-script scripts/publish-crate.rs

      - name: Wait for Crate availability on Crates.io
        if: steps.check.outputs.should_release == 'true'
        run: rust-script scripts/wait-for-crate.rs --release-version "${{ steps.current_version.outputs.version }}"

  # === MANUAL INSTANT RELEASE ===
  # Manual release via workflow_dispatch - only after CI passes
  manual-release:
    name: Instant Release
    needs: [lint, test, build]
    outputs:
      should-release: ${{ steps.version.outputs.version_committed == 'true' || steps.version.outputs.already_released == 'true' }}
      release-version: ${{ steps.version.outputs.new_version }}
    # Note: always() is required to evaluate the condition when dependencies use always().
    # The build job ensures lint and test passed before this job runs.
    if: |
      always() && !cancelled() &&
      github.event_name == 'workflow_dispatch' &&
      github.event.inputs.release_mode == 'instant' &&
      needs.build.result == 'success'
    runs-on: ubuntu-latest
    timeout-minutes: 60
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable
        with:
          toolchain: 1.98.1

      - name: Install rust-script
        run: cargo install rust-script --version 0.36.0 --locked

      - name: Configure git
        run: rust-script scripts/git-config.rs

      - name: Collect changelog fragments
        run: rust-script scripts/collect-changelog.rs

      - name: Version and commit
        id: version
        env:
          BUMP_TYPE: ${{ github.event.inputs.bump_type }}
          DESCRIPTION: ${{ github.event.inputs.description }}
        run: rust-script scripts/version-and-commit.rs --bump-type "${{ github.event.inputs.bump_type }}" --description "${{ github.event.inputs.description }}"

      - name: Build release
        if: steps.version.outputs.version_committed == 'true' || steps.version.outputs.already_released == 'true'
        run: cargo build --locked --release

      - name: Publish to Crates.io
        if: steps.version.outputs.version_committed == 'true' || steps.version.outputs.already_released == 'true'
        id: publish-crate
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN || secrets.CARGO_TOKEN }}
        run: rust-script scripts/publish-crate.rs

      - name: Wait for Crate availability on Crates.io
        if: steps.version.outputs.version_committed == 'true' || steps.version.outputs.already_released == 'true'
        run: rust-script scripts/wait-for-crate.rs --release-version "${{ steps.version.outputs.new_version }}"

  # Build every image variant and architecture on a native runner. Each matrix
  # leg pushes a digest; the following job gives those digests their tags.
  publish-docker-images:
    name: Build Docker Image (${{ matrix.variant }} / ${{ matrix.arch }})
    needs: [create-github-release]
    if: always() && !cancelled() && needs.create-github-release.result == 'success'
    strategy:
      fail-fast: false
      matrix:
        include:
          - arch: amd64
            platform: linux/amd64
            runner: ubuntu-latest
            variant: runtime
            target: runtime
          - arch: arm64
            platform: linux/arm64
            runner: ubuntu-24.04-arm
            variant: runtime
            target: runtime
    runs-on: ${{ matrix.runner }}
    timeout-minutes: 45
    permissions:
      contents: read
      packages: write
      id-token: write
      attestations: write
      artifact-metadata: write
    env:
      RELEASE_VERSION: ${{ needs.create-github-release.outputs.release-version }}
      RELEASE_COMMIT: ${{ needs.create-github-release.outputs.release-commit }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ needs.create-github-release.outputs.release-commit }}

      - name: Verify the workspace is the release tag commit
        shell: bash
        run: test "$(git rev-parse HEAD)" = "$RELEASE_COMMIT"

      - name: Log in to GitHub Container Registry
        uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Log in to Docker Hub
        uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
        with:
          username: konard
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4.3.0

      - name: Extract Docker metadata
        id: docker-meta
        uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
        with:
          images: |
            ghcr.io/${{ github.repository }}
            ${{ env.DOCKERHUB_IMAGE }}
          tags: type=raw,value=${{ env.RELEASE_VERSION }}
          labels: |
            org.opencontainers.image.version=${{ env.RELEASE_VERSION }}
            org.opencontainers.image.source=https://github.com/link-assistant/router

      # metadata-action always emits org.opencontainers.image.revision=github.sha, which on a
      # release push is the merge commit *before* the release commit. Passing a second value
      # for the same key would leave the winner up to label ordering, so drop the generated
      # entry and append the commit the release tag actually resolves to.
      - name: Pin the image revision to the release tag commit
        id: image-labels
        shell: bash
        env:
          GENERATED_LABELS: ${{ steps.docker-meta.outputs.labels }}
        run: |
          {
            echo 'labels<<LABELS_EOF'
            grep -v '^org.opencontainers.image.revision=' <<<"$GENERATED_LABELS"
            echo "org.opencontainers.image.revision=${RELEASE_COMMIT}"
            echo 'LABELS_EOF'
          } >> "$GITHUB_OUTPUT"

      - name: Build and push image by digest
        id: build-image
        uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
        with:
          context: .
          target: ${{ matrix.target }}
          platforms: ${{ matrix.platform }}
          labels: ${{ steps.image-labels.outputs.labels }}
          outputs: type=image,"name=ghcr.io/${{ github.repository }},${{ env.DOCKERHUB_IMAGE }}",push-by-digest=true,name-canonical=true,push=true
          cache-from: type=gha,scope=${{ matrix.arch }}-${{ matrix.variant }}
          cache-to: type=gha,mode=max,scope=${{ matrix.arch }}-${{ matrix.variant }}
          provenance: mode=max
          sbom: true

      # Fail before the digest is ever tagged if the built config still carries the
      # workflow-context revision instead of the tag commit.
      - name: Verify image labels record the release tag commit
        env:
          IMAGE_DIGEST: ${{ steps.build-image.outputs.digest }}
        shell: bash
        run: |
          labels="$(docker buildx imagetools inspect \
            "ghcr.io/${{ github.repository }}@${IMAGE_DIGEST}" --format '{{json .Image}}' | jq '.config.Labels')"
          echo "$labels"
          test "$(jq -r '."org.opencontainers.image.revision"' <<<"$labels")" = "$RELEASE_COMMIT"
          test "$(jq -r '."org.opencontainers.image.version"' <<<"$labels")" = "$RELEASE_VERSION"

      - name: Attest GHCR image provenance
        uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
        with:
          subject-name: ghcr.io/${{ github.repository }}
          subject-digest: ${{ steps.build-image.outputs.digest }}
          push-to-registry: true

      - name: Verify published image attestation
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: gh attestation verify "oci://ghcr.io/${{ github.repository }}@${{ steps.build-image.outputs.digest }}" --repo "${{ github.repository }}"

      - name: Export image digest
        env:
          IMAGE_DIGEST: ${{ steps.build-image.outputs.digest }}
        run: |
          mkdir -p "/tmp/digests/${{ matrix.variant }}"
          touch "/tmp/digests/${{ matrix.variant }}/${IMAGE_DIGEST#sha256:}"

      - name: Upload image digest
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
        with:
          name: ${{ matrix.variant }}-${{ matrix.arch }}
          path: /tmp/digests/${{ matrix.variant }}/*
          if-no-files-found: error
          retention-days: 1

  publish-docker-manifests:
    name: Publish Multi-Platform Docker Manifests
    needs: [create-github-release, publish-docker-images]
    if: always() && !cancelled() && needs.publish-docker-images.result == 'success'
    runs-on: ubuntu-latest
    timeout-minutes: 20
    permissions:
      contents: read
      packages: write
    env:
      RELEASE_VERSION: ${{ needs.create-github-release.outputs.release-version }}
      RELEASE_COMMIT: ${{ needs.create-github-release.outputs.release-commit }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ needs.create-github-release.outputs.release-commit }}
          fetch-depth: 0

      - name: Verify the workspace is the release tag commit
        shell: bash
        run: test "$(git rev-parse HEAD)" = "$RELEASE_COMMIT"

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable
        with:
          toolchain: 1.98.1

      - name: Install rust-script
        run: cargo install rust-script --version 0.36.0 --locked

      - name: Log in to GitHub Container Registry
        uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Log in to Docker Hub
        uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
        with:
          username: konard
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4.3.0

      - name: Download runtime digests
        # v8's bundled unzip chain (unzip-stream -> binary/buffers) still calls the
        # deprecated `Buffer()` constructor, so Node 24 prints DEP0005 on every
        # download (upstream actions/download-artifact#484, still open). The
        # artifacts here are zips, so the extraction path cannot be avoided with
        # `skip-decompress`; silencing the deprecation notice for this one step
        # keeps the log clean without pinning away from v8's stricter defaults --
        # a digest mismatch now fails the run instead of warning, which is exactly
        # what should stop a release.
        env:
          NODE_OPTIONS: --no-deprecation
        uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
        with:
          pattern: runtime-*
          path: /tmp/digests/runtime
          merge-multiple: true

      - name: Create multi-platform manifests
        shell: bash
        run: |
          ghcr_runtime=()
          dockerhub_runtime=()
          for digest in /tmp/digests/runtime/*; do
            hash="$(basename "$digest")"
            ghcr_runtime+=("ghcr.io/${{ github.repository }}@sha256:$hash")
            dockerhub_runtime+=("${{ env.DOCKERHUB_IMAGE }}@sha256:$hash")
          done
          docker buildx imagetools create \
            -t "ghcr.io/${{ github.repository }}:latest" \
            -t "ghcr.io/${{ github.repository }}:${RELEASE_VERSION}" \
            "${ghcr_runtime[@]}"
          docker buildx imagetools create \
            -t "${{ env.DOCKERHUB_IMAGE }}:latest" \
            -t "${{ env.DOCKERHUB_IMAGE }}:${RELEASE_VERSION}" \
            "${dockerhub_runtime[@]}"

      - name: Verify GHCR package is publicly pullable
        env:
          GHCR_IMAGE: ghcr.io/link-assistant/router
        run: bash scripts/verify-ghcr-visibility.sh

      - name: Verify multi-platform Docker manifests
        run: |
          rust-script scripts/check-docker-platforms.rs \
            "ghcr.io/${{ github.repository }}:latest" \
            "ghcr.io/${{ github.repository }}:${{ env.RELEASE_VERSION }}" \
            "${{ env.DOCKERHUB_IMAGE }}:latest" \
            "${{ env.DOCKERHUB_IMAGE }}:${{ env.RELEASE_VERSION }}"

      # Post-publication guard: re-resolve the annotated tag and compare it against the
      # revision every published platform manifest claims.
      - name: Verify published image provenance
        run: |
          rust-script scripts/check-release-provenance.rs \
            --release-version "${RELEASE_VERSION}" \
            --expected-commit "${RELEASE_COMMIT}" \
            --repository "${{ github.repository }}" \
            --image "ghcr.io/${{ github.repository }}:${RELEASE_VERSION}" \
            --image "ghcr.io/${{ github.repository }}:latest" \
            --image "${{ env.DOCKERHUB_IMAGE }}:${RELEASE_VERSION}" \
            --image "${{ env.DOCKERHUB_IMAGE }}:latest"

  create-github-release:
    name: Create GitHub Release
    needs: [auto-release, manual-release]
    if: |
      always() && !cancelled() && (
        (needs.auto-release.result == 'success' && needs.auto-release.outputs.should-release == 'true') ||
        (needs.manual-release.result == 'success' && needs.manual-release.outputs.should-release == 'true')
      )
    outputs:
      release-version: ${{ needs.auto-release.outputs.release-version || needs.manual-release.outputs.release-version }}
      release-commit: ${{ steps.tag-commit.outputs.commit }}
    runs-on: ubuntu-latest
    timeout-minutes: 15
    permissions:
      contents: write
    env:
      RELEASE_VERSION: ${{ needs.auto-release.outputs.release-version || needs.manual-release.outputs.release-version }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: refs/tags/v${{ env.RELEASE_VERSION }}
          fetch-depth: 0

      # Every packaging job must build the immutable tag commit, not the commit that
      # triggered this run: the release commit is created *after* the trigger, so
      # github.sha still names the previous merge commit (issue #191).
      - name: Resolve release tag commit
        id: tag-commit
        shell: bash
        run: |
          git fetch --force --tags --quiet
          commit="$(git rev-parse "refs/tags/v${RELEASE_VERSION}^{commit}")"
          if [ "$commit" != "$(git rev-parse HEAD)" ]; then
            echo "::error::v${RELEASE_VERSION} resolves to $commit but the workspace is $(git rev-parse HEAD)"
            exit 1
          fi
          echo "commit=$commit" >> "$GITHUB_OUTPUT"
          echo "v${RELEASE_VERSION} -> $commit" >> "$GITHUB_STEP_SUMMARY"

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable
        with:
          toolchain: 1.98.1

      - name: Install rust-script
        run: cargo install rust-script --version 0.36.0 --locked

      # Surface orphan tags left by earlier runs *before* anything is published, so the
      # log names them while they can still be fixed without a half-finished release.
      # They only warn here: an unrelated historical orphan must not block today's images.
      # The scheduled verify-releases workflow still fails hard on them.
      - name: Report pre-existing release drift
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: rust-script scripts/check-github-releases.rs --repository "${{ github.repository }}" --default-branch main --historical-orphans warn

      - name: Create GitHub Release
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: rust-script scripts/create-github-release.rs --release-version "${{ env.RELEASE_VERSION }}" --repository "${{ github.repository }}" --crates-io-url "https://crates.io/crates/link-assistant-router" --docker-hub-url "https://hub.docker.com/r/konard/link-assistant-router"

      # Scoped to the version just published: this run is responsible for that release only.
      - name: Verify GitHub Releases
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: rust-script scripts/check-github-releases.rs --repository "${{ github.repository }}" --default-branch main --release-version "${{ env.RELEASE_VERSION }}" --historical-orphans warn

  publish-release-artifacts:
    name: Publish attested binaries (${{ matrix.os }}-${{ matrix.arch }})
    needs: [create-github-release]
    if: always() && !cancelled() && needs.create-github-release.result == 'success'
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: linux
            arch: amd64
            runner: ubuntu-latest
            target: x86_64-unknown-linux-gnu
          - os: linux
            arch: arm64
            runner: ubuntu-24.04-arm
            target: aarch64-unknown-linux-gnu
          # Both Darwin slices are produced on the Apple Silicon runner: the
          # Xcode SDK it ships builds either architecture, so the x86_64 asset
          # does not depend on the shrinking pool of Intel macOS runners.
          - os: darwin
            arch: arm64
            runner: macos-latest
            target: aarch64-apple-darwin
          - os: darwin
            arch: amd64
            runner: macos-latest
            target: x86_64-apple-darwin
    runs-on: ${{ matrix.runner }}
    timeout-minutes: 30
    permissions:
      contents: write
      id-token: write
      attestations: write
    env:
      RELEASE_VERSION: ${{ needs.create-github-release.outputs.release-version }}
      RELEASE_COMMIT: ${{ needs.create-github-release.outputs.release-commit }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ needs.create-github-release.outputs.release-commit }}
          fetch-depth: 0

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable
        with:
          toolchain: 1.98.1
          targets: ${{ matrix.target }}

      - name: Verify tag and package version
        shell: bash
        run: |
          package_version="$(cargo metadata --locked --no-deps --format-version 1 | jq -r '.packages[] | select(.name == "link-assistant-router") | .version')"
          test "$package_version" = "$RELEASE_VERSION"
          test "$(git rev-parse HEAD)" = "$RELEASE_COMMIT"
          test "$(git rev-parse "v${RELEASE_VERSION}^{commit}")" = "$RELEASE_COMMIT"

      - name: Build release binaries
        run: cargo build --locked --release --bins --target ${{ matrix.target }}

      - name: Install pinned CycloneDX generator
        run: cargo install cargo-cyclonedx --version 0.5.9 --locked

      - name: Package binaries, checksums, and CycloneDX SBOM
        shell: bash
        env:
          PLATFORM: ${{ matrix.os }}-${{ matrix.arch }}
        run: |
          mkdir -p dist/package
          # `router` is the canonical command (issue #222); the other two names
          # ship beside it so existing scripts and deployment units keep working.
          # A name missing here is absent from every published archive, which is
          # how `router` shipped in v0.92.0 without reaching anyone who installs
          # from a release rather than with `cargo install`.
          cp "target/${{ matrix.target }}/release/router" \
            "target/${{ matrix.target }}/release/link-assistant-router" \
            "target/${{ matrix.target }}/release/with-router" dist/package/
          cp LICENSE README.md dist/package/
          cargo cyclonedx --format json --all-features --all --spec-version 1.5 \
            --override-filename link-assistant-router.cdx
          mv link-assistant-router.cdx.json \
            "dist/link-assistant-router-${RELEASE_VERSION}-${PLATFORM}.cdx.json"
          jq -e '.bomFormat == "CycloneDX" and (.components | length > 1) and (.dependencies | length > 0)' \
            "dist/link-assistant-router-${RELEASE_VERSION}-${PLATFORM}.cdx.json" >/dev/null
          tar -C dist/package -czf "dist/link-assistant-router-${RELEASE_VERSION}-${PLATFORM}.tar.gz" .
          rm -rf dist/package
          # macOS ships `shasum` instead of GNU coreutils' `sha256sum`; both
          # emit the same "<digest>  <path>" lines consumers verify against.
          # Digest the assets from inside dist/ so the recorded names are the flat
          # names `gh release download` writes; a `dist/` prefix makes a consumer's
          # `sha256sum -c` fail with "No such file or directory".
          (
            cd dist
            if command -v sha256sum >/dev/null 2>&1; then
              sha256sum *.tar.gz *.cdx.json
            else
              shasum -a 256 *.tar.gz *.cdx.json
            fi
          ) > "dist/link-assistant-router-${RELEASE_VERSION}-${PLATFORM}.sha256"
          # Smoke test the published checksum file the way a consumer runs it: flat,
          # in the directory the assets were downloaded into.
          (
            cd dist
            if command -v sha256sum >/dev/null 2>&1; then
              sha256sum -c "link-assistant-router-${RELEASE_VERSION}-${PLATFORM}.sha256"
            else
              shasum -a 256 -c "link-assistant-router-${RELEASE_VERSION}-${PLATFORM}.sha256"
            fi
          )

      - name: Attest release artifacts
        uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
        with:
          subject-path: dist/*

      - name: Upload assets to the GitHub release
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: gh release upload "v${RELEASE_VERSION}" dist/* --clobber

      - name: Verify attestations and release asset identity
        shell: bash
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          for artifact in dist/*; do
            gh attestation verify "$artifact" --repo "${{ github.repository }}"
          done
          assets="$(gh release view "v${RELEASE_VERSION}" --repo "${{ github.repository }}" --json assets --jq '.assets[].name')"
          for expected in \
            "link-assistant-router-${RELEASE_VERSION}-${{ matrix.os }}-${{ matrix.arch }}.tar.gz" \
            "link-assistant-router-${RELEASE_VERSION}-${{ matrix.os }}-${{ matrix.arch }}.cdx.json" \
            "link-assistant-router-${RELEASE_VERSION}-${{ matrix.os }}-${{ matrix.arch }}.sha256"; do
            grep -Fqx "$expected" <<<"$assets"
          done

  # === POST-PUBLICATION PROVENANCE GUARD ===
  # Everything above trusts the release-commit output computed at tag time. This job
  # starts from the default branch, re-resolves the annotated tag itself, and compares
  # that commit against what was actually published: the labels on both platform
  # manifests in both registries, and the attestations of the downloadable archives.
  # It also runs the consumer's own `sha256sum -c` in the download directory.
  verify-release-provenance:
    name: Verify published release provenance
    needs: [create-github-release, publish-docker-manifests, publish-release-artifacts]
    if: |
      always() && !cancelled() &&
      needs.publish-docker-manifests.result == 'success' &&
      needs.publish-release-artifacts.result == 'success'
    runs-on: ubuntu-latest
    timeout-minutes: 30
    permissions:
      contents: read
      packages: read
    env:
      RELEASE_VERSION: ${{ needs.create-github-release.outputs.release-version }}
      RELEASE_COMMIT: ${{ needs.create-github-release.outputs.release-commit }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          fetch-depth: 0

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable
        with:
          toolchain: 1.98.1

      - name: Install rust-script
        run: cargo install rust-script --version 0.36.0 --locked

      - name: Log in to GitHub Container Registry
        uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Log in to Docker Hub
        uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
        with:
          username: konard
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4.3.0

      # The guard resolves the release tag and its parent locally: the tag is created
      # after this run started, so a plain checkout does not have it yet.
      - name: Fetch the release tag
        run: |
          git fetch --force --tags --quiet
          git rev-parse "refs/tags/v${RELEASE_VERSION}^{commit}" >/dev/null
          git rev-parse "refs/tags/v${RELEASE_VERSION}^{commit}^1" >/dev/null

      - name: Download the published release assets
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          mkdir -p published
          gh release download "v${RELEASE_VERSION}" --repo "${{ github.repository }}" --dir published --clobber

      - name: Verify checksums exactly as a consumer does
        shell: bash
        run: |
          cd published
          shopt -s nullglob
          checksums=(*.sha256)
          if [ "${#checksums[@]}" -eq 0 ]; then
            echo "::error::the release published no checksum files"
            exit 1
          fi
          for checksum in "${checksums[@]}"; do
            sha256sum -c "$checksum"
          done

      - name: Verify every artifact points at the release tag commit
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          rust-script scripts/check-release-provenance.rs \
            --release-version "${RELEASE_VERSION}" \
            --expected-commit "${RELEASE_COMMIT}" \
            --repository "${{ github.repository }}" \
            --image "ghcr.io/${{ github.repository }}:${RELEASE_VERSION}" \
            --image "${{ env.DOCKERHUB_IMAGE }}:${RELEASE_VERSION}" \
            --asset-dir published

  # === MACOS HOST CLI LIFECYCLE ===
  verify-macos-client-lifecycle:
    name: Verify macOS client lifecycle
    needs: [create-github-release, publish-release-artifacts]
    if: always() && !cancelled() && needs.publish-release-artifacts.result == 'success'
    runs-on: macos-latest
    timeout-minutes: 30
    permissions:
      contents: read
    env:
      RELEASE_VERSION: ${{ needs.create-github-release.outputs.release-version }}
      RELEASE_COMMIT: ${{ needs.create-github-release.outputs.release-commit }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ needs.create-github-release.outputs.release-commit }}

      - name: Verify the workspace is the release tag commit
        shell: bash
        run: test "$(git rev-parse HEAD)" = "$RELEASE_COMMIT"

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable
        with:
          toolchain: 1.98.1

      - name: Download and verify the published darwin-arm64 asset
        shell: bash
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          PLATFORM: darwin-arm64
        run: |
          mkdir -p dist
          gh release download "v${RELEASE_VERSION}" --repo "${{ github.repository }}" --dir dist \
            --pattern "link-assistant-router-${RELEASE_VERSION}-${PLATFORM}.*"
          (cd dist && shasum -a 256 -c "link-assistant-router-${RELEASE_VERSION}-${PLATFORM}.sha256")
          mkdir -p dist/package
          tar -C dist/package -xzf "dist/link-assistant-router-${RELEASE_VERSION}-${PLATFORM}.tar.gz"
          # The shipped binaries must run natively before the lifecycle is
          # tried. `router` is checked first: it is the canonical command, and
          # asserting it here is what would have caught its absence from the
          # v0.92.0 archives (issue #222).
          dist/package/router --version
          dist/package/link-assistant-router --version
          dist/package/with-router --help >/dev/null

      - name: Forward the remote router to a localhost port
        id: forward
        shell: bash
        env:
          ROUTER_SSH_TARGET: ${{ secrets.ROUTER_SSH_TARGET }}
          ROUTER_SSH_KEY: ${{ secrets.ROUTER_SSH_KEY }}
          ROUTER_REMOTE_ADDRESS: ${{ secrets.ROUTER_REMOTE_ADDRESS }}
        run: |
          if [ -z "$ROUTER_SSH_TARGET" ] || [ -z "$ROUTER_SSH_KEY" ] || [ -z "$ROUTER_REMOTE_ADDRESS" ]; then
            echo "SSH secrets are absent; skipping the remote lifecycle."
            echo "forwarded=false" >> "$GITHUB_OUTPUT"
            exit 0
          fi
          install -m 700 -d ~/.ssh
          printf '%s\n' "$ROUTER_SSH_KEY" > ~/.ssh/router_release
          chmod 600 ~/.ssh/router_release
          ssh-keyscan -H "${ROUTER_SSH_TARGET#*@}" >> ~/.ssh/known_hosts
          ssh -i ~/.ssh/router_release -f -N -o ExitOnForwardFailure=yes \
            -L "18080:${ROUTER_REMOTE_ADDRESS}" "$ROUTER_SSH_TARGET"
          echo "forwarded=true" >> "$GITHUB_OUTPUT"

      - name: Run the host CLI lifecycle against the forwarded router
        if: steps.forward.outputs.forwarded == 'true'
        env:
          ROUTER_HOST_CLI_TESTS: "1"
          ROUTER_HOST_CLI_URL: http://127.0.0.1:18080
          ROUTER_HOST_CLI_TOKEN: ${{ secrets.ROUTER_HOST_CLI_TOKEN }}
        run: cargo test --locked --test host_client_lifecycle_test -- --nocapture

  # === MANUAL CHANGELOG PR ===
  changelog-pr:
    name: Create Changelog PR
    if: github.event_name == 'workflow_dispatch' && github.event.inputs.release_mode == 'changelog-pr'
    runs-on: ubuntu-latest
    timeout-minutes: 20
    permissions:
      contents: write
      pull-requests: write
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          fetch-depth: 0

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable
        with:
          toolchain: 1.98.1

      - name: Install rust-script
        run: cargo install rust-script --version 0.36.0 --locked

      - name: Create changelog fragment
        env:
          BUMP_TYPE: ${{ github.event.inputs.bump_type }}
          DESCRIPTION: ${{ github.event.inputs.description }}
        run: rust-script scripts/create-changelog-fragment.rs --bump-type "${{ github.event.inputs.bump_type }}" --description "${{ github.event.inputs.description }}"

      - name: Create Pull Request
        uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          commit-message: 'chore: add changelog for manual ${{ github.event.inputs.bump_type }} release'
          branch: changelog-manual-release-${{ github.run_id }}
          delete-branch: true
          title: 'chore: manual ${{ github.event.inputs.bump_type }} release'
          body: |
            ## Manual Release Request

            This PR was created by a manual workflow trigger to prepare a **${{ github.event.inputs.bump_type }}** release.

            ### Release Details
            - **Type:** ${{ github.event.inputs.bump_type }}
            - **Description:** ${{ github.event.inputs.description || 'Manual release' }}
            - **Triggered by:** @${{ github.actor }}

            ### Next Steps
            1. Review the changelog fragment in this PR
            2. Merge this PR to main
            3. The automated release workflow will publish to crates.io and create a GitHub release