Skip to content

test(bats): isolate worktree.bats and tighten the BATS suite - #1709

Merged
c-vigo merged 10 commits into
devfrom
bugfix/1694-worktree-bats-isolation
Sep 25, 2026
Merged

c-vigo merged 10 commits into
devfrom
bugfix/1694-worktree-bats-isolation

Conversation

@c-vigo

@c-vigo c-vigo commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

Description

Four tests-only issues in one PR. The load-bearing one is #1694: tests/bats/worktree.bats
drove just worktree-clean against the repository's live <repo>-worktrees sibling
directory, and that recipe force-removes every entry in it and git branch -Ds its branch.
On 2026-09-25 a local full-suite run deleted three agent worktrees and their branches
mid-work. The file now drives every recipe against a throwaway git init fixture under
BATS_TEST_TMPDIR, which also lets it drop its CI=true skips and rejoin bats -j's
within-file parallelism. The other three tighten the same suite: a per-file
bats_require_minimum_version declaration with a pytest guard (#1697), concurrent fixture
rendering in init-workspace.bats's setup_file (#1695), and the settled
_upgrade ≡ _scaffold equivalence that collapses the last pure-setup renders (#1696).

No product code changes: justfile.worktree, its scaffolded mirror and
assets/init-workspace.sh are untouched. The only non-test file is
CHANGELOG.md (plus its synced mirror), where an unreleased #1687 sentence
had to be corrected — see Changelog Entry.

Review fixes are appended as their own commits rather than folded into the
reviewed history.

Type of Change

  • feat -- New feature
  • fix -- Bug fix
  • docs -- Documentation only
  • chore -- Maintenance task (deps, config, etc.)
  • refactor -- Code restructuring (no behavior change)
  • test -- Adding or updating tests
  • ci -- CI/CD pipeline changes
  • build -- Build system or dependency changes
  • revert -- Reverts a previous commit
  • style -- Code style (formatting, whitespace)

Modifiers

  • Breaking change (!) -- This change breaks backward compatibility

Changes Made

#1694 — worktree.bats no longer touches the live worktrees directory

  • _wt_assert_throwaway (committed red-first) asserts the base is non-empty and under
    $BATS_TEST_TMPDIR before any recipe runs or any directory is created. 6 of the 10 tests
    were red against the old wiring.
  • _wt_fixture git inits a one-commit throwaway repo at $BATS_TEST_TMPDIR/fixture;
    _wt_just runs the recipes with --justfile "$WT_MAIN" --working-directory "$FIX".
    _wt_base is ../<basename $(git rev-parse --show-toplevel)>-worktrees resolved against
    just's working directory, so that one flag moves the whole base to $FIX-worktrees —
    no product knob, and the #1463 tests in the same file already used the idiom.
  • The five [ "${CI:-}" = "true" ] && skip lines go: tmux reaches the CI PATH via
    setup-env and tmux new-session -d needs no TTY. The command -v tmux/just/claude
    skips stay.
  • setup_file's BATS_NO_PARALLELIZE_WITHIN_FILE (added by chore(ci): cut the BATS suite runtime #1690) goes too — it was a
    symptom of the shared base, not of the tmux server. Issue numbers carry a
    $$-$BATS_TEST_NUMBER tag so derived session names stay unique.
  • /tmp/bats-claude-$$ and a mktemp -d move under BATS_TEST_TMPDIR, which retires the
    manual rm -rf / rmdir cleanups.
  • tests/bats/worktree-claude-cli.bats needs no change: pure recipe-grep, no directories,
    no recipe invocations, no tmux.

#1697 — bats_require_minimum_version in every file

  • New tests/test_bats_shape.py: one parametrized case per tests/bats/*.bats asserting
    the declaration is the file's first statement, plus a discovery guard so a zero-file glob
    cannot pass silently. Committed red (20 failures) before the fix.
  • The declaration is added to the 20 files that lacked it; githooks.bats already had it.

#1695 — concurrent setup_file renders

  • The fixture list is declarative (one <name> <mode> [extra args] line each), marker
    seeding moves into _seed_shared, and all renders are backgrounded and waited on, with
    every failed fixture's log dumped rather than the first.
  • Two new fixtures (cargo-both, nix-module-both) now that a fixture costs ~0 wall time;
    the four Cargo.toml / nix/module.nix seed-group tests clone them. The two nix tests
    create $ws instead of $ws/nix — _clone_shared refuses a non-empty target.

#1696 — collapse the pure-setup _upgrade both renders

  • The _upgrade ≡ _scaffold question is settled by evidence (below) and the verdict is
    written into _clone_shared's CONTRACT comment so it is not re-litigated.
  • The 5 pure-setup sites clone the both fixture: the first run of the #878 stock test
    (whose subject is the second run) and the four #886 --preview setups. The other 30 of
    the 35 _upgrade tests seed a consumer file first or assert on the run itself and keep
    their real invocation.

Review round

  • The guard pinned WT_BASE, which no recipe reads — the recipes derive
    ../<basename $(git rev-parse --show-toplevel)>-worktrees from just's working directory,
    and that is FIX. FIX is now pinned first (the WT_BASE asserts stay, so the two cannot
    drift), and _wt_fixture runs the guard before its git init: that helper
    git add -As and commits inside FIX, so it mutates a real checkout before any recipe
    would. _run_wt_start — the file's one other real-recipe path, and the one that actually
    git worktree adds — runs the same guard against its own sandbox.
  • A teardown() reaps leaked tmux sessions: only a wt- name ending in this test's unique
    WT_TAG, or the claude probe's PID-tagged name. An unset WT_TAG matches nothing, so
    wt-* can never sweep a developer's real sessions.
  • Test 1 gave a backgrounded just exactly 2 s before a single has-session; it now polls
    up to 5 s, so a cold runner is a slow pass rather than a false negative.
  • Both asserts in tests/test_bats_shape.py name the offending file, the exact line required
    and where it goes.
  • CHANGELOG.md: the unreleased [CHORE] BATS runtime: parallelize the suite, batch the init-workspace.sh fork loops, collapse redundant scaffolds #1687 sub-bullet is corrected (below).

Changelog Entry

No changelog needed for the work itself. All four issues are labelled "No changelog needed":
the change is confined to tests/ and alters no consumer-visible behaviour, no scaffolded
asset and no recipe.

What this PR does touch is a correction to an existing, still-unreleased sentence, not a
new entry. The #1687 bullet under ## Unreleased claimed the opposite of what is now true:

  - GNU parallel now rides with the bats wrapper in `nix/bats.nix` — … and both entry
    points, `just test-bats` and the `test-project` composite action, run
    `bats -j "$(nproc)"`. `worktree.bats` first opted out of within-file jobs, because its
    tests drove real tmux sessions against the repository's own sibling worktrees directory;
    it now drives an isolated per-test fixture repo instead, so it runs under `-j` and in CI
    like every other file
    ([#1694](https://github.com/vig-os/devkit/issues/1694))

Nothing below ## Unreleased is touched. assets/workspace/.devcontainer/CHANGELOG.md is
the hook-synced mirror, regenerated by sync-manifest.

Testing

  • Tests pass locally (just test)
  • Manual testing performed (describe below)

Manual Testing Details

#1694 red-first pin — bats tests/bats/worktree.bats, CI unset:

not ok 1 worktree-attach restarts stopped session when worktree dir exists
# expression : [ /…/devkit-worktrees/1694-worktrees != /…/devkit-worktrees/1694-worktrees ]
ok   2 claude CLI launches in tmux without an interactive trust prompt
not ok 3 worktree-attach errors when neither worktree dir nor session exists   # [ -n  ]
not ok 4 worktree-clean stopped-only skips worktrees with running tmux session
not ok 5 worktree-clean all removes worktrees with running tmux sessions
not ok 6 wt-clean alias works for stopped-only and all                         # [ -n  ]
not ok 7 worktree-clean rejects invalid mode                                   # [ -n  ]
ok   8-10 (#1203, #1463 x2)

The pin fires before the mkdir and before the recipe, so nothing was created outside a
tmpdir and no worktree or branch was removed. Note test 6 (wt-clean alias) had no
CI skip — it ran just wt-clean against the real base even under CI=true.

#1694 green — worktree.bats 10/10 with 0 skips serially (CI unset), 10/10 under
CI=true bats -j 8, and 10/10 on five consecutive bats -j 8 runs — 0 flakes. The five
worktrees of this checkout (devkit, 1692, 1693, 1694, 1698) are listed unchanged
before and after every run.

#1697 — before: exactly one BW02, from init-workspace.bats:1801
(run --separate-stderr), printed in a trailing warnings block rather than interleaved.
After: bats -j 8 tests/bats/ 2>&1 | grep -c BW02 = 0, 602/602 unchanged.
pytest tests/test_bats_shape.py 22 passed.

#1695 — setup_file wall time, measured with EPOCHREALTIME inside bats -j 8 runs on
an 8-core host (instrumentation not committed):

run 1 run 2 run 3
before (7 fixtures, serial) 4.849 s 5.814 s 6.245 s
after (9 fixtures, concurrent) 0.643 s 0.607 s 0.578 s

init-workspace.sh invocations per file run (counting shim, not committed): 250 -> 248.
init-workspace.bats 300/300 under bats -j 8 and 300/300 sequentially.

Multi-failure diagnostics proved by temporarily breaking two fixtures (direnv, bare):

not ok 1 setup_file failed
# shared direnv scaffold failed:
# Unknown option: --bogus-flag
# shared bare scaffold failed:
# Unknown option: --bogus-flag

#1696 equivalence verdict — identical. _upgrade both and _scaffold both rendered
into empty directories, three rounds:

=== round 1 ===   DIFF CLEAN   MODES CLEAN
=== round 2 ===   DIFF CLEAN   MODES CLEAN
=== round 3 ===   DIFF CLEAN   MODES CLEAN

diff -r is clean and the find -printf '%m %y %p' | sort listings are identical in every
round. Only stdout differs — the workspace path echo, rsync's byte counters, and the extra
line the real just produces:

196a197
> just sync: no pyproject.toml — skipping

Invocations after the conversion: 248 -> 243. init-workspace.bats 300/300.

Review round — the FIX assert is load-bearing. Temporarily pointing FIX at
$PROJECT_ROOT (not committed): the guard fires from _wt_fixture at the line before
git init, so nothing is created, staged or committed.

not ok 1 worktree-attach restarts stopped session when worktree dir exists
#  from function `_wt_fixture' in file tests/bats/worktree.bats, line 65,
#   `_wt_fixture' failed
# expression : [ /…/devkit-worktrees/1694 != /…/devkit-worktrees/1694 ]
…  (same for tests 3, 4, 5, 6, 7; tests 2, 8, 9, 10 pass)

That is why the guard moved into _wt_fixture: the reviewed version protected only the
recipes, and _wt_fixture itself does git add -A + commit inside FIX.

Review round — green. worktree.bats 10/10 on three consecutive bats -j 8 runs with
0 skips, and 10/10 under CI=true bats -j 8. tmux list-sessions | grep -c '^wt-' = 0
after every run, so the new teardown leaks nothing.

Review round — the assertion message. With the declaration removed from just.bats:

AssertionError: tests/bats/just.bats must declare `bats_require_minimum_version 1.5.0` as
its first statement (after the header comment, before setup); found 'setup() {'

Whole suite — bats -j 8 tests/bats/: 602/602, 0 failures, grep -c BW02 = 0, and
0 skipped tests (grep -c '# skip' = 0). An earlier draft of this body said "19 skips";
that number came from grep -c skip, which counts test names containing the word — e.g.
init-precommit.sh skips cleanly when no config is present (#854). Nothing in the suite
skips.
prek run --all-files: 53 hooks, every one Passed, exit 0, in both hook roots (. and
assets/workspace).

Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have updated the documentation accordingly (edit docs/templates/, then run just docs)
  • I have updated CHANGELOG.md in the [Unreleased] section (and pasted the entry above)
  • My changes generate no new warnings or errors
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published

Additional Notes

Three of the four issues carry factual corrections, posted separately as issue comments:
#1694 misses that test 6 was unguarded by the CI skip and asserts a TTY requirement that
does not exist; #1697 states that no file declares the version and implies many warnings,
where githooks.bats already declared it and the suite emitted exactly one; #1696 estimates
~13 convertible sites where 5 qualify under WP3's conversion rule.

The #1694 fix is what makes the rest of this PR safe to run: until it landed, any local
bats tests/bats/ or just test-bats could delete a sibling worktree.

Refs: #1694, #1697, #1695, #1696

`just worktree-clean` force-removes every entry in its `<repo>-worktrees`
base and `git branch -D`s each branch, so the tests that point it at the real
sibling directory delete a developer's or an agent's live worktrees. Assert
the base lives under BATS_TEST_TMPDIR before any recipe runs and before any
directory is created; 6 of the 10 tests are red against the current wiring.

Refs: #1694
`_wt_base` is `../<basename $(git rev-parse --show-toplevel)>-worktrees`
resolved against just's working directory, so `--working-directory "$FIX"` on a
throwaway `git init` fixture under BATS_TEST_TMPDIR moves the whole base into
the test's own tmpdir. No product change: justfile.worktree and its scaffolded
mirror are untouched, and the #1463 tests in this file already used the idiom.

Consequences: the fixtures can no longer collide with a real worktree, so the
five `CI=true` skips go (tmux is on the CI PATH via setup-env and
`tmux new-session -d` needs no TTY) and the file rejoins bats' within-file
parallelism — the #1687 `BATS_NO_PARALLELIZE_WITHIN_FILE` opt-out was a
symptom of the shared base, not of the tmux server. Per-test issue numbers
carry a `$$-$BATS_TEST_NUMBER` tag so derived tmux session names stay unique.
The two remaining host paths (`/tmp/bats-claude-$$`, `mktemp -d`) move under
BATS_TEST_TMPDIR, which also retires the manual `rm -rf`/`rmdir` cleanups.

Refs: #1694
bats 1.5 gates the `run` flags behind `bats_require_minimum_version` and warns
(BW02) on every use without one. The declaration has to sit at file top level,
so it cannot be centralised in test_helper.bash — a per-file rule that only
review enforces. Pin it instead: one parametrized case per `tests/bats/*.bats`,
asserting the declaration is the file's first statement. 20 of the 21 files are
red; githooks.bats already declares it.

Refs: #1697
One line per file, the first statement after the header comment, satisfying the
guard added with the previous commit. githooks.bats already carried it, so the
other 20 files gain it; no test body changes.

Today the suite emits exactly one BW02 (init-workspace.bats:1801,
`run --separate-stderr`), so the value here is drift-proofing rather than log
volume: the next `run -0` in any of the 21 files cannot reintroduce the warning.

Refs: #1697
setup_file rendered seven fixtures one after another, and that prologue is pure
critical path under `bats -j`: no test in the file can start until it finishes
while the other cores idle. Each render already wrote to its own log, so the
only serial element was the `|| return 1` short-circuit. Background them all,
`wait` on each pid, and dump EVERY failed fixture's log rather than the first.
Measured in `-j 8` runs on an 8-core host: 4.85/5.81/6.25 s before,
0.58/0.64/0.61 s after — with nine fixtures instead of seven.

The fixture list becomes declarative (one `<name> <mode> [extra args]` line
each) so the next cluster that needs a shared tree adds a line instead of a
per-test render, and marker seeding moves into a `_seed_shared` helper.

A fixture now costs ~0 wall time, which is what #1687 (WP3) was waiting for
before giving the two-test Cargo.toml and nix/module.nix seed groups their own
fixtures: cargo-both and nix-module-both are added and the four tests clone
them (250 -> 248 renders). The two nix tests pre-created `$ws/nix`, so they now
create only `$ws` — `_clone_shared` refuses a non-empty target by contract.

No red-first test: this is test infrastructure whose contract is the suite
itself. Evidence instead — 300/300 under `-j 8` and sequentially, the
invocation count above, and a deliberate two-fixture break confirming both
failures are reported.

Refs: #1695
`_upgrade` and `_scaffold` differ only in their stubs: `_scaffold` stubs `just`
so the tail `just sync` never runs, `_upgrade` keeps the real `just` with `uv`
stubbed so the recipe runs and no-ops. Nobody had checked whether that leaves a
trace, so the `_upgrade both` sites kept re-rendering.

Settled by evidence: rendered into empty directories three times over, the two
trees are `diff -r` clean with identical `find -printf '%m %y %p'` listings. The
only difference is on stdout — the extra `just sync: no pyproject.toml —
skipping` line (plus the workspace path and rsync's byte counters). The verdict
is recorded in `_clone_shared`'s CONTRACT so it is not re-litigated.

So the 5 pure-setup sites clone the `both` fixture instead (the first run of the
#878 stock test, whose subject is the second run, and the four #886 `--preview`
setups): 248 -> 243 renders. The other 30 of the 35 `_upgrade` tests seed a
consumer file first or assert on the run itself and keep their real invocation.

Refs: #1696
Three review fixes on the #1694 isolation.

The guard pinned WT_BASE, which no recipe reads: the recipes derive
`../<basename $(git rev-parse --show-toplevel)>-worktrees` from just's working
directory, and that is FIX. Pin FIX first, keep the WT_BASE asserts so the two
cannot drift, and call the guard from `_wt_fixture` before its `git init` —
that helper `git add -A`s and commits inside FIX, so it mutates a real checkout
before any recipe would run. Proven by temporarily pointing FIX at
PROJECT_ROOT: the assert fires from `_wt_fixture`, index untouched.

`_run_wt_start` is the file's one other real-recipe path; worktree-start
creates `<main>-worktrees/<issue>`, so it now runs the same guard against its
own sandbox.

The tmux server is process-global, so an assertion failing before a test
reaches its own `kill-session` leaked a session — now that the file runs in CI
and under `-j`, into the runner and its peers. A teardown reaps only what the
test derived: a `wt-` name ending in this test's unique WT_TAG, or the claude
probe's PID-tagged name. An unset WT_TAG matches nothing, so `wt-*` can never
sweep a developer's real sessions.

Test 1 gave a backgrounded `just` exactly 2 s before a single `has-session`,
which on a cold runner is a false negative rather than a slow pass. Poll up to
5 s instead.

Refs: #1694
A bare `assert` left the failure as `assert 'setup() {' == 'bats_require…'`,
which does not say which file or what to add. Both asserts now name the file
relative to the repo root, the exact line required and where it goes.

Refs: #1697
The Unreleased #1687 entry still says worktree.bats "opts out of within-file
jobs: its tests drive real tmux sessions and the repo's sibling worktrees
directory". Both halves are now false: the tests drive an isolated fixture repo
under BATS_TEST_TMPDIR and the file runs under `-j` and in CI. This corrects an
unreleased sentence in place rather than adding an entry — the isolation work
itself is changelog-exempt. The synced mirror is regenerated by sync-manifest.

Refs: #1694
@c-vigo c-vigo self-assigned this Sep 25, 2026
@c-vigo

c-vigo commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

Verification on the first CI run

Run 36124206119: all 15 checks green, Test Summary passed.

Claim Evidence Verdict
worktree.bats runs in CI, no skips (#1694) Project BATS log: tests 597–606 all ok, including the seven tmux/recipe tests that used to skip under CI=true and the wt-clean alias test that had no skip at all; # skip count over the whole lane: 0 holds
The suite never touches a live worktree base (#1694) Every recipe path and the fixture's own git init/add -A run behind _wt_assert_throwaway (FIX and WT_BASE both under BATS_TEST_TMPDIR); the red-first commit fails 6 tests before any destructive act; locally git worktree list unchanged across 3× -j 8 runs, CI=true, and the full suite holds
Within-file parallelism restored BATS_NO_PARALLELIZE_WITHIN_FILE gone; 3× bats -j 8 tests/bats/worktree.bats 10/10, 0 flakes locally; CI lane ran the file under -j 4 green holds
Zero BW02 warnings (#1697) grep -c BW02 over the CI BATS log: 0; tests/test_bats_shape.py pins the declaration as first statement in all 21 files (22 passed) holds
Concurrent setup_file (#1695) 9 fixtures rendered concurrently; local setup_file ~5s → ~0.6s under load, 3.5× in the spike; multi-failure diagnostics dump every failed fixture's log holds
_upgrade both ≡ _scaffold both (#1696) Verified three times by implementer and reviewer independently: diff -r clean, modes identical, only stdout differs; 5 pure-setup sites converted, invocation count 250 → 243 holds
Test count 1..606 in CI: 602 before this PR + 4 added by #1707 (merged into this branch); this PR adds none and removes none holds

Lane timing: Project BATS 4m04s on this run (3m43s–4m08s across today's four PRs), so within-file parallelism for worktree.bats did not move the lane — the win here is safety and CI coverage, as the PR body says.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant