opencrabs 0.5.11

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Recommended: the 40MB prebuilt binary for macOS, Linux and Windows: https://github.com/opencrabs/opencrabs/releases
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
name: CI

# Trigger model (single-maintainer OSS, GitHub Flow):
#   - pull_request: full gate on contributions — required to review
#     external PRs safely.
#   - push to main: catch direct pushes and keep main provably green.
#     Docs-only commits are skipped via paths-ignore so they don't burn
#     the matrix; rapid pushes cancel older runs via `concurrency`. The
#     heavy cross-platform BUILD job is gated off routine main pushes
#     (see its `if:`) so a normal commit only pays for lint + Linux test
#     + audit (~5-8 min, cached, cancellable). This replaces the old
#     opt-out `[skip ci]`-on-every-commit toil with sensible defaults.
#   - workflow_dispatch: run the build matrix on demand (e.g. to verify
#     macOS before cutting a release tag; Windows is validated by release.yml).
# CI deliberately does NOT run on tags — the release workflow owns tags
# and trusts the commit already passed CI on its way to main. That also
# kills the old double-build where ci.yml and release.yml both compiled
# Windows/macOS on the same tag event.
on:
  pull_request:
  push:
    branches: [main]
    paths-ignore:
      - '**.md'
      - 'LICENSE*'
      - '.gitignore'
      - 'docs/**'
  workflow_dispatch:

concurrency:
  group: ci-${{ github.ref }}
  cancel-in-progress: true

permissions:
  contents: read

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: 1
  CARGO_INCREMENTAL: 0

jobs:
  # ── Stage 1: Lint (fast gate — fails early before burning compute) ────────
  # Pattern lifted from ZeroClaw: run fmt + clippy first. If either fails,
  # every downstream job is skipped. Avoids burning ~25 min on the
  # cross-platform build/test matrix for a PR that won't lint anyway.
  lint:
    name: Lint
    runs-on: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork) && 'ubuntu-latest' || 'self-hosted' }}
    # 25: hosted Lint ran 13:43 of its 15 cap on a fork PR (run
    # 36069934718); one noisy neighbor on the hosted fleet is a false red.
    timeout-minutes: 25
    steps:
      - uses: actions/checkout@v5

      - name: Refuse to administer the host's rustup
        # dtolnay/rust-toolchain manages rustup on whatever machine it runs
        # on, and defaults CARGO_HOME to ~/.cargo when it is unset. On a
        # self-hosted runner that is somebody's workstation, so CI installs
        # toolchains into their installation: it removed the rustup binary
        # itself once, leaving every shim in ~/.cargo/bin dangling and no
        # working cargo for the machine owner (#1162).
        #
        # The runner sets CARGO_HOME and RUSTUP_HOME to its own directories.
        # This fails the job if that ever stops being true, rather than
        # letting the damage be discovered at the owner's next build.
        if: runner.environment == 'self-hosted'
        shell: bash
        run: |
          for var in CARGO_HOME RUSTUP_HOME; do
            value="${!var}"
            if [ -z "$value" ]; then
              echo "::error::$var is unset, so rustup would manage the host's own installation. Set it in the runner service environment."
              exit 1
            fi
            case "$value" in
              "$HOME/.cargo"|"$HOME/.rustup")
                echo "::error::$var points at the host's own installation ($value). CI must not administer it."
                exit 1
                ;;
            esac
            echo "$var=$value"
          done

      - name: Install Rust (from rust-toolchain.toml)
        uses: dtolnay/rust-toolchain@master
        with:
          toolchain: stable
          components: rustfmt, clippy

      - uses: swatinem/rust-cache@v2
        with:
          cache-on-failure: true
          save-if: ${{ github.ref == 'refs/heads/main' }}

      - name: Install ALSA dev (for local-stt feature)
        # Linux-only: ALSA does not exist on macOS, where cpal uses CoreAudio.
        # Left ungated, this ran `apt-get` on the self-hosted Mac and failed on
        # sudo before any Rust work started.
        if: runner.os == 'Linux'
        run: sudo apt-get update -qq && sudo apt-get install -y libasound2-dev

      - name: Check formatting
        # Soft-fail: legacy un-formatted code blocks shouldn't block PRs
        # yet. Promote to hard-fail once a fmt sweep lands on main.
        continue-on-error: true
        run: cargo fmt --all -- --check

      - name: Clippy
        run: cargo clippy --locked --lib --bins --tests --examples --all-features -- -D warnings

  # ── Stage 2: Build verification (parallel, gated on lint + audit) ────────
  # Cross-platform BUILD on macOS confirms target compatibility without
  # running tests there (tests run on Linux only — see `test` below).
  # Windows is not built here (#627) — it chronically hit the 40m cap and
  # release.yml already validates it at tag time. Most of our test surface
  # is platform-independent; if a macOS-specific test ever regresses we can
  # promote it via the matrix.
  build:
    name: Build (${{ matrix.target }})
    needs: [lint, audit]
    # Cross-platform build verification. Runs where it pays off — on PRs
    # (gate contributions) and on-demand (workflow_dispatch, e.g. before a
    # release tag) — but NOT on every routine push to main. Direct main
    # pushes still get lint + Linux test + audit.
    #
    # Windows is intentionally NOT built here (#627): it builds --all-features
    # with rust-cache skipped (always cold), so it chronically hit the 40m cap
    # and blocked otherwise-green PRs. It is build-only (no tests) and
    # release.yml's build-release matrix already builds + validates Windows
    # before any tag is published, so a platform regression cannot reach a
    # release unnoticed.
    if: github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch'
    runs-on: ${{ matrix.os }}
    timeout-minutes: 40
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: self-hosted
            target: aarch64-apple-darwin
            features: --all-features
    steps:
      - uses: actions/checkout@v5

      - name: Refuse to administer the host's rustup
        # dtolnay/rust-toolchain manages rustup on whatever machine it runs
        # on, and defaults CARGO_HOME to ~/.cargo when it is unset. On a
        # self-hosted runner that is somebody's workstation, so CI installs
        # toolchains into their installation: it removed the rustup binary
        # itself once, leaving every shim in ~/.cargo/bin dangling and no
        # working cargo for the machine owner (#1162).
        #
        # The runner sets CARGO_HOME and RUSTUP_HOME to its own directories.
        # This fails the job if that ever stops being true, rather than
        # letting the damage be discovered at the owner's next build.
        if: runner.environment == 'self-hosted'
        shell: bash
        run: |
          for var in CARGO_HOME RUSTUP_HOME; do
            value="${!var}"
            if [ -z "$value" ]; then
              echo "::error::$var is unset, so rustup would manage the host's own installation. Set it in the runner service environment."
              exit 1
            fi
            case "$value" in
              "$HOME/.cargo"|"$HOME/.rustup")
                echo "::error::$var points at the host's own installation ($value). CI must not administer it."
                exit 1
                ;;
            esac
            echo "$var=$value"
          done

      - name: Install Rust (from rust-toolchain.toml)
        uses: dtolnay/rust-toolchain@master
        with:
          toolchain: stable
          targets: ${{ matrix.target }}

      - uses: swatinem/rust-cache@v2
        with:
          cache-on-failure: true
          save-if: ${{ github.ref == 'refs/heads/main' }}

      - name: Build (macOS)
        env:
          CFLAGS: -march=armv8-a+crypto
          CXXFLAGS: -march=armv8-a+crypto
        run: cargo build --locked --profile ci --target ${{ matrix.target }} ${{ matrix.features }}

  # ── Stage 2a2: Windows path filter (decides whether Stage 2b runs) ────────
  # Path filter, fail-open. A 51-minute GitHub-hosted build on every push
  # to every PR is the cost that got the original job deleted (#627), and
  # most PRs here cannot break Windows. Fire on the paths that have
  # actually produced Windows-only breakage: the dependency graph and
  # toolchain, the platform abstraction, the spawn and read paths, and
  # this workflow itself. Anything we cannot determine builds anyway, and
  # a `windows` label forces a build for the cases this list misses.
  # Deliberate gap: a new cfg(windows) block in an unlisted file is not
  # caught here. release.yml's matrix still builds Windows before any tag
  # ships, which is the coverage #627 relied on; Stage 2b only moves that
  # signal earlier for the paths where it pays for itself.
  #
  # Its own job rather than a step inside Stage 2b (#1831). A step-level
  # `if:` skips the steps but the job still concludes success, so the merge
  # box and `gh pr checks` rendered "Build (windows): pass" on a run that
  # had compiled nothing. A job-level gate on this output is the only shape
  # that renders the honest "skipped". Hosted Linux because it is a clone
  # plus a grep: no toolchain, no cache, seconds.
  windows-filter:
    name: Windows path filter
    # Carries the event gate Stage 2b used to own. On a main push neither
    # job is evaluated, so a routine commit still pays for lint + test +
    # audit only.
    if: github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch'
    runs-on: ubuntu-latest
    timeout-minutes: 10
    outputs:
      run: ${{ steps.relevant.outputs.run }}
    steps:
      # fetch-depth 0: the filter below diffs against the PR base sha.
      - uses: actions/checkout@v5
        with:
          fetch-depth: 0

      - name: Windows-relevant changes?
        id: relevant
        shell: bash
        run: |
          set -u
          if [[ "${{ github.event_name }}" != "pull_request" ]]; then
            echo "not a pull_request, building"
            echo "run=true" >> "$GITHUB_OUTPUT"
            exit 0
          fi
          if [[ "${{ contains(github.event.pull_request.labels.*.name, 'windows') }}" == "true" ]]; then
            echo "windows label present, building"
            echo "run=true" >> "$GITHUB_OUTPUT"
            exit 0
          fi
          base="${{ github.event.pull_request.base.sha }}"
          if ! git cat-file -e "${base}^{commit}" 2>/dev/null; then
            echo "base sha ${base} not in this clone, building (fail open)"
            echo "run=true" >> "$GITHUB_OUTPUT"
            exit 0
          fi
          files=$(git diff --name-only "$base" HEAD)
          echo "changed files:"
          echo "$files"
          # The last two paths are #1823: the files whose tests assert
          # Windows behaviour, so the runtime lane fires when they change.
          # src/cli/service_windows.rs is deliberately NOT listed: that
          # carrier belongs to #1821 and does not exist on this tree yet, so
          # listing it would be a promise this repo cannot keep. Add it in
          # the PR that adds the file.
          pattern='^(Cargo\.toml|Cargo\.lock|rust-toolchain\.toml|build\.rs|\.github/workflows/ci\.yml|src/utils/(shell|cwd)\.rs|src/brain/tools/(bash|read)\.rs|src/tui/app/input\.rs|src/config/(winlock|profile)\.rs)$'
          if echo "$files" | grep -qE "$pattern"; then
            echo "run=true" >> "$GITHUB_OUTPUT"
          else
            echo "no Windows-relevant paths touched, skipping the build"
            echo "run=false" >> "$GITHUB_OUTPUT"
          fi

  # ── Stage 2b: Windows build (gated on lint, audit, path filter) ─────────
  # Windows is where platform-specific regressions actually ship: the `sh -c`
  # hardcode in four child-spawn sites lived for months with CI green,
  # because tests run on Linux (where `sh` exists) and Windows was never
  # built here (#627 — the old job chronically hit the 40m cap with
  # --all-features and cold caches). It catches spawn-path and cfg(windows)
  # compile breakage at PR time, and since #1823 it also EXECUTES the binary
  # it built: the --version smoke step below is the first signal in this
  # repo's history that opencrabs.exe actually starts, because compile-green
  # was never starts-green (#1759). Still no full test suite: the ci-gate job
  # comment carries the #627 cost history behind that decision. The
  # release recipe (CMake + NASM) compiles the llama-cpp-sys-2 C++ wrapper;
  # `--profile ci` (thin LTO, 16 codegen units) plus rust-cache keep the
  # wall-clock inside the cap that killed the original job.
  windows-build:
    name: Build (windows)
    needs: [lint, audit, windows-filter]
    # Job-level, not step-level (#1831): when the filter says no, GitHub
    # concludes this job skipped. A needed job that was skipped or failed
    # also lands here, since outputs.run stays empty.
    if: needs.windows-filter.outputs.run == 'true'
    runs-on: windows-latest
    # 60 min: a COLD windows-latest run needs ~48 (33 compile incl. llama's
    # cmake C++ + ~15 for the thin-LTO link of a 4-vCPU runner); warm runs
    # from rust-cache land near 10. The original 40 cap killed a build that
    # was minutes from linking. Keep a cap so a true hang can't burn 360.
    # 90 (not 60) while the scoped-test step rides along: the cfg(test) lib
    # compiles on top of the build. The job is NOT in the required gate, so
    # the extra ceiling is a priced trade for the first-ever Windows
    # execution receipts, not silent drift.
    timeout-minutes: 90
    steps:
      - uses: actions/checkout@v5

      - name: Install Rust (from rust-toolchain.toml)
        uses: dtolnay/rust-toolchain@master
        with:
          toolchain: stable
          components: rustfmt, clippy

      # No `save-if` restriction: this job only runs on PRs and
      # workflow_dispatch, so a `refs/heads/main`-only save-if never fires —
      # the cache would stay cold forever. Saving in the run's own scope
      # lets the 2nd..Nth push of a PR hit warm artifacts.
      - uses: swatinem/rust-cache@v2
        with:
          cache-on-failure: true

      - name: Install CMake (Windows)
        uses: lukka/get-cmake@latest

      - name: Install NASM (Windows)
        uses: ilammy/setup-nasm@v1

      - name: Build
        shell: bash
        env:
          AWS_LC_SYS_CMAKE_BUILDER: '1'
        # NOTE: local DEBUG-profile Windows builds hit LNK2038: esaxx-rs
        # 0.1.10's default `cpp` feature compiles /MT (build.rs
        # .static_crt(true)) while cmake-rs injects "-MD" into
        # CMAKE_C/CXX_FLAGS (it skips that injection only when the build
        # script already defines those vars). RUSTFLAGS
        # crt-static does NOT fix this — it flips the cc crates but never
        # reaches cmake-rs. Verified workaround for local debug builds
        # (llama-cpp-sys-2 forwards every CMAKE_* env var as a -D define):
        #   CMAKE_C_FLAGS=/O2 /DNDEBUG /Ob2 -nologo -MT -Brepro -W0
        #   CMAKE_CXX_FLAGS=/O2 /DNDEBUG /Ob2 -nologo -MT -Brepro -W0
        #   CMAKE_C_FLAGS_RELEASE=... (same, VS generator reads these)
        #   CMAKE_CXX_FLAGS_RELEASE=... (same)
        # This job uses the release-shaped profile, where the linker
        # doesn't pull the esaxx object — the shape that ships releases.
        run: cargo build --locked --profile ci --target x86_64-pc-windows-msvc --all-features

      # No step-level `if:` on either step below, deliberately. This job is
      # gated at job level on needs.windows-filter.outputs.run (#1831) and
      # has no `steps.relevant` context: the fork this is harvested from
      # keeps the filter as a step inside this job, where that expression
      # does resolve. Copied verbatim, both steps would evaluate falsy, be
      # skipped, and the job would still conclude success, which is the
      # exact fake-green shape #1855 removed from this file.
      - name: "Smoke (windows): execute the binary it built"
        shell: bash
        run: |
          # Actions' bash runs with -e: without the guard, a failing exe
          # would die AT the substitution and the echo below would never
          # run, which is precisely the case whose diagnostic we want.
          # stderr rides in too (DLL-load failures land there).
          set +e
          ver=$(./target/x86_64-pc-windows-msvc/ci/opencrabs.exe --version 2>&1)
          status=$?
          set -e
          echo "exit=$status version=$ver"
          [ "$status" -eq 0 ] || exit 1
          echo "$ver" | grep -qi opencrabs

      # Scoped execution: only the modules whose tests assert platform
      # behaviour. Full-suite Windows was rejected twice (#627 cost, and
      # POSIX-semantics failures that are not bugs). Every member below
      # exists on this tree, so Windows gives real receipts on day 1 instead
      # of a zero-match tripwire:
      #   config::winlock                     3 tests, cross-handle
      #                                       contention and fail-closed
      #                                       terminate proof, cfg(windows):
      #                                       these run nowhere else
      #   tests::utils_shell_test            12 tests, the shell_pair probe
      #                                       contract
      #   tests::utils_cwd_test               5 tests, drive-letter and
      #                                       lookalike dirs
      #   tests::browser_default_windows_test  6 tests, browser path
      #                                       detection
      #   tests::profile_test                67 tests, lock-owner stamp
      #                                       parsing and reused-PID
      #                                       resolution. The round-9
      #                                       finding (a Windows-only test
      #                                       failure) lived in exactly this
      #                                       module, and no CI job could
      #                                       have seen it: Windows ran no
      #                                       tests.
      # cli::service_windows is NOT in the slice yet: its carrier belongs to
      # #1821 and does not exist here, so listing it would make this step
      # permanently red on a zero-match and defeat the flip noted below.
      # continue-on-error: true is the honest day-1 state, not a dodge: 93
      # tests here have never executed on Windows in this repo's history, so
      # their outcome is unknown and must not block a PR. The smoke step
      # above is NOT soft, because a binary that does not start is a hard
      # fail. Flip continue-on-error to false once the receipts are green,
      # in the PR that reports them.
      - name: "Scoped tests (windows): platform-behaviour slice"
        continue-on-error: true
        shell: bash
        run: |
          # One filter per module, each individually judged. A combined
          # `cargo test -- a b c` that silently matches nothing looks green;
          # per-module zero-detection here is a SCREAM (a module renamed by a
          # sibling PR), not a pass, the same anti-fake-green principle the
          # footgun gate's --self-test enforces.
          # Actions' bash runs with -e, so an unguarded substitution exits AT
          # the assignment and `rc=$?` below is never reached: the loop would
          # abort on the first failing module, print none of the captured
          # output, and skip every module after it. The smoke step carries
          # the same guard for the same reason. One more trap: with `--lib`,
          # cargo writes "test result: FAILED. N passed" on failure, so
          # parsing $out must not assume the ok-form.
          status=0
          for m in config::winlock tests::utils_shell_test \
                   tests::utils_cwd_test tests::browser_default_windows_test \
                   tests::profile_test; do
            set +e
            out=$(cargo test --locked --profile ci --target x86_64-pc-windows-msvc \
                    --lib -- "$m" 2>&1)
            rc=$?
            set -e
            n=$(printf '%s\n' "$out" | sed -n 's/^test result: [a-z]*\. \([0-9]*\) passed.*/\1/p' | head -n1)
            failed=$(printf '%s\n' "$out" | sed -n 's/.*; \([0-9]*\) failed.*/\1/p' | head -n1)
            if [ $rc -ne 0 ]; then
              echo "::warning::Windows slice FAILS (rc=$rc, failed=${failed:-?}): $m"
              printf '%s\n' "$out" | tail -20
              status=1
            elif [ -z "$n" ] || [ "$n" -eq 0 ]; then
              echo "::warning::Windows slice ZERO-MATCH: $m names no tests here (renamed by a sibling PR)"
              status=1
            else
              echo "Windows slice PASS: $m ($n tests)"
            fi
          done
          exit $status

  # ── Windows footgun gate (static, cheap, blocks the merge) ─────────────
  # The only python step in this workflow, and deliberately not part of the
  # Windows build lane: it scans source text, so it costs seconds instead
  # of the 51m09s that keeps windows-build out of the required gate below.
  # A footgun finding blocks the PR rather than scrolling by as advisory,
  # which is the whole point of running it on every push.
  #
  # `--self-test` runs FIRST and on its own line: it plants every rule and
  # every cfg shape, so a linter regression fails here instead of turning
  # the scan green by matching nothing. That is the difference between a
  # gate and decoration.
  windows-footguns:
    name: Windows footguns
    timeout-minutes: 10
    runs-on: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork) && 'ubuntu-latest' || 'self-hosted' }}
    steps:
      - uses: actions/checkout@v5

      - name: Linter proves its own teeth
        run: python3 scripts/check-windows-footguns.py --self-test

      - name: Scan the tree
        run: python3 scripts/check-windows-footguns.py --root src

  # ── Stage 3: Test on Linux (gated on lint + audit, parallel with build) ──
  # Tests run on Linux only — macOS gets build verification via
  # the `build` job above. ZeroClaw uses the same split because the
  # cross-platform matrix triples wall-clock for little extra coverage
  # on this codebase (most tests are platform-independent).
  #
  # Stays on `cargo test` for now: a few timing-sensitive tests
  # (rate_limiter pacing) rely on cargo test's threadpool semantics
  # and fail under nextest's process-per-test isolation. nextest
  # migration is a follow-up once those tests are made portable.
  # Runs on the Mac only. Linux is covered where it costs nothing: the
  # release matrix builds both Linux targets at tag time, and the suite runs
  # locally on demand. Paying for a hosted Linux run on every push buys very
  # little, since almost the entire suite is platform independent.
  test:
    name: Test
    needs: [lint, audit]
    runs-on: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork) && 'ubuntu-latest' || 'self-hosted' }}
    # 60: fork PRs run this on hosted runners at roughly 3x self-hosted
    # speed, and the 30 cap killed cold-cache fork runs twice (runs
    # 36078125556 and 36069934718, both cancelled at ~30 while green code
    # waited). Warm hosted fits in 20; 60 is the cold-cache ceiling.
    timeout-minutes: 60
    steps:
      - uses: actions/checkout@v5

      - name: Refuse to administer the host's rustup
        # dtolnay/rust-toolchain manages rustup on whatever machine it runs
        # on, and defaults CARGO_HOME to ~/.cargo when it is unset. On a
        # self-hosted runner that is somebody's workstation, so CI installs
        # toolchains into their installation: it removed the rustup binary
        # itself once, leaving every shim in ~/.cargo/bin dangling and no
        # working cargo for the machine owner (#1162).
        #
        # The runner sets CARGO_HOME and RUSTUP_HOME to its own directories.
        # This fails the job if that ever stops being true, rather than
        # letting the damage be discovered at the owner's next build.
        if: runner.environment == 'self-hosted'
        shell: bash
        run: |
          for var in CARGO_HOME RUSTUP_HOME; do
            value="${!var}"
            if [ -z "$value" ]; then
              echo "::error::$var is unset, so rustup would manage the host's own installation. Set it in the runner service environment."
              exit 1
            fi
            case "$value" in
              "$HOME/.cargo"|"$HOME/.rustup")
                echo "::error::$var points at the host's own installation ($value). CI must not administer it."
                exit 1
                ;;
            esac
            echo "$var=$value"
          done

      - name: Install Rust (from rust-toolchain.toml)
        uses: dtolnay/rust-toolchain@master
        with:
          toolchain: stable

      - uses: swatinem/rust-cache@v2
        with:
          cache-on-failure: true
          save-if: ${{ github.ref == 'refs/heads/main' }}

      - name: Install mold + ALSA dev (Linux)
        # Linux-only toolchain extras; macOS uses the Xcode linker.
        if: runner.os == 'Linux'
        run: sudo apt-get update -qq && sudo apt-get install -y mold clang libasound2-dev

      - name: Run tests
        env:
          CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang
          CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUSTFLAGS: "-C link-arg=-fuse-ld=mold"
        # #1936: the suite can freeze with every test-thread slot blocked;
        # before, the job just burned timeout-minutes and died with no
        # verdict. The wrapper detects the silence, dumps thread stacks of
        # cargo and its test children, kills the tree, and fails in ~5
        # minutes instead of 60. The command it runs is unchanged.
        run: bash scripts/test-stall-watchdog.sh cargo test --locked --profile ci --all-features --verbose

  # ── Stage 1b: Security (fast gate — runs alongside lint, before build/test)
  # cargo-audit only scans Cargo.lock; it needs no compile, so it runs in
  # PARALLEL with lint as a second fast gate rather than after it. build/test/
  # coverage all `needs: [lint, audit]`, so a fresh advisory (this fails in
  # ~4s) skips the ~22-min Linux test and the cross-platform build matrix
  # instead of racing them. Lockfile-only fix → no recompile to re-gate.

  audit:
    name: Cargo Audit
    runs-on: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork) && 'ubuntu-latest' || 'self-hosted' }}
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v5

      - name: Refuse to administer the host's rustup
        # dtolnay/rust-toolchain manages rustup on whatever machine it runs
        # on, and defaults CARGO_HOME to ~/.cargo when it is unset. On a
        # self-hosted runner that is somebody's workstation, so CI installs
        # toolchains into their installation: it removed the rustup binary
        # itself once, leaving every shim in ~/.cargo/bin dangling and no
        # working cargo for the machine owner (#1162).
        #
        # The runner sets CARGO_HOME and RUSTUP_HOME to its own directories.
        # This fails the job if that ever stops being true, rather than
        # letting the damage be discovered at the owner's next build.
        if: runner.environment == 'self-hosted'
        shell: bash
        run: |
          for var in CARGO_HOME RUSTUP_HOME; do
            value="${!var}"
            if [ -z "$value" ]; then
              echo "::error::$var is unset, so rustup would manage the host's own installation. Set it in the runner service environment."
              exit 1
            fi
            case "$value" in
              "$HOME/.cargo"|"$HOME/.rustup")
                echo "::error::$var points at the host's own installation ($value). CI must not administer it."
                exit 1
                ;;
            esac
            echo "$var=$value"
          done

      - name: Install Rust (from rust-toolchain.toml)
        uses: dtolnay/rust-toolchain@master
        with:
          toolchain: stable

      - name: Install cargo-audit
        uses: taiki-e/install-action@v2
        with:
          tool: cargo-audit

      - name: Run cargo audit
        # Ignored advisories. Every one is a TRANSITIVE dependency: none is
        # declared in our Cargo.toml, so the lever is always an upstream crate,
        # never a version bump we can make here. Re-checked 2026-09-04 (#1344).
        #
        # Six of the nine trace to ONE dependency, `rwhisper` (the local-stt
        # feature), whose tree is still on reqwest 0.11 / hyper 0.14 / candle
        # 0.8. rwhisper 0.4.1 is the latest published release, so there is
        # nothing to move to. If local-stt is ever dropped or rwhisper updates,
        # most of this list goes with it.
        #
        #   RUSTSEC-2026-0258  h2 — VULNERABILITY (low, DoS): unbounded empty
        #                      DATA frames. Our direct h2 is patched (0.4.17);
        #                      the hit is h2 0.3.27 via rwhisper -> kalosm-common
        #                      -> reqwest 0.11 -> hyper 0.14. The 0.3 line has no
        #                      fixed release. We are an HTTP *client*, so the
        #                      described flood requires a hostile endpoint we are
        #                      already talking to. Drop when rwhisper moves to a
        #                      reqwest on hyper 1.x.
        #   RUSTSEC-2026-0253  lru — unsound pop() panic safety   \
        #   RUSTSEC-2026-0002  lru — unsound IterMut               | via rwhisper
        #   RUSTSEC-2025-0134  rustls-pemfile — unmaintained       | ->kalosm
        #   RUSTSEC-2025-0119  number_prefix — unmaintained        | (indicatif
        #   RUSTSEC-2024-0436  paste — unmaintained (candle/gemm)  /  -> hf-hub)
        #
        #   RUSTSEC-2025-0141  bincode — unmaintained. Two paths, both needed:
        #                      syntect's `dump-load` (how we load the bundled
        #                      syntax/theme dumps) and printpdf -> azul-layout
        #                      -> hyphenation.
        #   RUSTSEC-2026-0192  ttf-parser — unmaintained, via pdf-extract -> lopdf.
        #                      pdf-extract 0.12.0 is the latest release.
        #   RUSTSEC-2026-0173  proc-macro-error2 — unmaintained, via
        #                      teloxide -> aquamarine. teloxide 0.17.0 is latest.
        #
        # Cleared 2026-09-04, do not re-add without evidence:
        #   RUSTSEC-2024-0320  yaml-rust — gone. syntect no longer pulls it: we
        #                      only ever load the bundled binary dumps, so the
        #                      YAML syntax loader was dead weight and the feature
        #                      set was narrowed off `default-fancy`.
        #   RUSTSEC-2026-0187  lopdf — gone. printpdf 0.12.7 moved off lopdf 0.39;
        #                      the ignore had been stale.
        #   chacha20 (yanked)  gone. `cargo update` moved it 0.10.1 -> 0.10.2.
        #                      It never had an ignore: audit does not fail on
        #                      yanked, so it had been passing silently.
        #
        # The nine below are each at their upstream's LATEST published release,
        # verified against crates.io on 2026-09-04, so there is no version to
        # move to from here. A routine `cargo update` will not shift them; only
        # an upstream release or dropping the dependency will.
        run: cargo audit --ignore RUSTSEC-2024-0436 --ignore RUSTSEC-2025-0119 --ignore RUSTSEC-2025-0134 --ignore RUSTSEC-2025-0141 --ignore RUSTSEC-2026-0002 --ignore RUSTSEC-2026-0173 --ignore RUSTSEC-2026-0192 --ignore RUSTSEC-2026-0253 --ignore RUSTSEC-2026-0258

  # ── Stage 5: Coverage (on-demand only) ───────────────────────────────────
  # Tarpaulin is the slowest job (~12 min). Running it on every main push
  # would re-add the cost we just trimmed, so it's on-demand: trigger the
  # CI workflow manually (workflow_dispatch) when you want a fresh coverage
  # report. PRs and pushes still get full test coverage via the `test` job;
  # this job only publishes the percentage report.
  coverage:
    name: Code Coverage
    needs: [lint, audit]
    if: github.event_name == 'workflow_dispatch'
    # On the Mac, where tarpaulin finishes the whole suite in ~15 min. A
    # hosted runner needed well over 30 for the same work and cost minutes
    # for it, which is not a trade worth making for a metric job.
    runs-on: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork) && 'ubuntu-latest' || 'self-hosted' }}
    timeout-minutes: 30
    steps:
      - uses: actions/checkout@v5

      - uses: swatinem/rust-cache@v2
        with:
          cache-on-failure: true
          save-if: ${{ github.ref == 'refs/heads/main' }}

      - name: Refuse to administer the host's rustup
        # dtolnay/rust-toolchain manages rustup on whatever machine it runs
        # on, and defaults CARGO_HOME to ~/.cargo when it is unset. On a
        # self-hosted runner that is somebody's workstation, so CI installs
        # toolchains into their installation: it removed the rustup binary
        # itself once, leaving every shim in ~/.cargo/bin dangling and no
        # working cargo for the machine owner (#1162).
        #
        # The runner sets CARGO_HOME and RUSTUP_HOME to its own directories.
        # This fails the job if that ever stops being true, rather than
        # letting the damage be discovered at the owner's next build.
        if: runner.environment == 'self-hosted'
        shell: bash
        run: |
          for var in CARGO_HOME RUSTUP_HOME; do
            value="${!var}"
            if [ -z "$value" ]; then
              echo "::error::$var is unset, so rustup would manage the host's own installation. Set it in the runner service environment."
              exit 1
            fi
            case "$value" in
              "$HOME/.cargo"|"$HOME/.rustup")
                echo "::error::$var points at the host's own installation ($value). CI must not administer it."
                exit 1
                ;;
            esac
            echo "$var=$value"
          done

      - name: Install Rust (from rust-toolchain.toml)
        uses: dtolnay/rust-toolchain@master
        with:
          toolchain: stable

      - name: Install ALSA dev
        if: runner.os == 'Linux'
        run: sudo apt-get update -qq && sudo apt-get install -y libasound2-dev

      - name: Install tarpaulin
        uses: taiki-e/install-action@v2
        with:
          tool: cargo-tarpaulin

      - name: Generate coverage
        run: cargo tarpaulin --locked --out Xml --no-default-features --features "telegram,whatsapp,discord,slack,trello"
        # Note: local-stt excluded — tarpaulin uses rust-lld which can't handle
        # duplicate ggml symbols from whisper-rs-sys + llama-cpp-sys-2.
        # local-tts added when feature lands on main.

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v5
        with:
          files: ./cobertura.xml

  # ── Required gate ────────────────────────────────────────────────────────
  # Single status check for branch protection. Internal job structure
  # can change without touching branch protection settings.
  # Coverage is intentionally excluded — it's main-only.
  ci-gate:
    name: CI Required Gate
    if: always()
    # windows-build is deliberately NOT in the required set. It is the only
    # GitHub-hosted job here (everything else runs on the self-hosted Mac),
    # it measured 51m09s cold, and at ~160 PR runs a fortnight that is ~136h
    # of 2x-billed runner time against the 3 Windows builds release.yml
    # actually ran in the same window. #627 removed the original job from the
    # gate for exactly that reason. It stays as an advisory signal; Windows
    # remains release-blocking via release.yml's build matrix before any tag.
    # windows-footguns IS in the required set, which is not in tension with
    # the paragraph above: same class of finding (Windows-specific) at a
    # python-pass cost, so blocking on it buys certainty for seconds.
    needs: [lint, build, test, audit, windows-footguns]
    runs-on: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork) && 'ubuntu-latest' || 'self-hosted' }}
    steps:
      - name: Check results
        run: |
          if [[ "${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }}" == "true" ]]; then
            echo "::error::One or more CI jobs failed or were cancelled"
            exit 1
          fi