Skip to content

fix(config): keep template-variable migration in step with the template parser - #4124

Merged
max-sixty merged 12 commits into
mainfrom
fix/issue-4117
Sep 16, 2026
Merged

max-sixty merged 12 commits into
mainfrom
fix/issue-4117

Conversation

@worktrunk-bot

@worktrunk-bot worktrunk-bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Deprecated template variables are found with MiniJinja (undeclared_variables) and rewritten with a hand-rolled scanner. The two disagree in two places, and both disagreements are visible in the file worktrunk writes.

A quoted closing delimiter ended the tag. rewrite_template_var_identifiers located a tag's end with a plain find("}}") before handing the body to its quote-aware scanner. On

{{ "}} " ~ repo_root }}

the tag was cut at the delimiter inside the string, so the real repo_root became outside-tag text and no migration happened at all. The mirror case changes output text: in {{ "}} {{ repo_root }}" }}{{ repo_root }} the literal {{ repo_root }} inside the string was scanned as a tag and rewritten, while the actual reference beside it was not.

A shadowed name was renamed at every use. undeclared_variables answers whether a name is read before it is bound, not which occurrences are the global one, so

{{ repo_root }}{% set repo_root = "local" %}{{ repo_root }}

reports repo_root, and the scanner — which has no scope tracking — renamed the first and the last use. is_template_attribute_or_assignment skipped the assignment target only. The final expression then read repo_path where the template meant the local.

test_normalize_skips_set_assignment_target looked like coverage for the second case, but its name is local throughout, so undeclared_variables returns nothing and the scanner never runs.

This matters more than it did: on #4080 this rewrite becomes Structural, running on every config load rather than only under wt config update.

Solution

template_tag_end scans for the closing delimiter while skipping quoted strings, reusing the existing quoted_template_string_end. It replaces the plain find for {{ }} and {% %}. Comments keep the plain scan — MiniJinja does not tokenize strings inside {# #}.

For shadowing, the rewriter is not taught scopes; a deprecated name bound anywhere in the template is dropped from the replacement set instead. template_block_bindings reads the binding keywords and returns the names they bind. Those are set, for, and with: Cargo.toml takes MiniJinja with default-features = false, so macro and call are not statements at all and a template using one fails to parse before the scan runs. A name merely used in a block tag — {% if repo_root %} — still migrates.

Over-reporting is the safer of the two error directions, but it is not free: because detection reads the same set, a name this scan claims stops warning as well as stops migrating. So the scan is kept as close to MiniJinja's own reading as a scanner can be. Targets are read the way parse_assignment reads them, nested parenthesized tuples included; block keywords are split with + whitespace control honored alongside -; a binding-shaped tag inside {% raw %} binds nothing; and a set's targets end at its =, since the comma after it builds a tuple value rather than starting another target the way a with pair's comma does.

The filter sits in deprecated_vars_in_template, which feeds both detection and rewriting, so the framework invariant holds: a shadowed template produces no warning and no rewrite.

Testing

  • test_normalize_ignores_delimiters_inside_quoted_strings — both reported cases plus a single-quoted %} in a block tag.
  • test_normalize_skips_names_bound_by_a_block — set, for, and with; each must return Cow::Borrowed and raise no deprecation warning.
  • test_normalize_bails_on_a_tag_it_cannot_terminate — {% raw %} content is literal to MiniJinja, so a template can parse while holding what this scanner reads as an unterminated tag. The whole template is then left alone rather than guessed at, which is what the pre-existing ? already did.
  • test_normalize_rewrites_names_used_but_not_bound_in_blocks — the migration a too-broad bail-out would have lost.
  • test_warning_fires_iff_update_changes gains the quoted-delimiter template as rewritten and the shadowed one as untouched.

All fail before the change. cargo test --lib passes apart from copy::tests::test_copy_dir_recursive_does_not_count_a_non_regular_file, which fails on main in this sandbox too (socket(AF_UNIX, …) is blocked). cargo clippy --all-targets and cargo fmt --check are clean.

Both branches touch src/config/deprecation.rs in different functions from #4080's edits, so this is based on main rather than stacked.

Reported by @zach-hammad-vs from source inspection; the reproduction above confirms both cases.

Closes #4117 — automated triage

Two places where the hand-rolled rewriter disagreed with MiniJinja about
what a tag is: a quoted `}}` was taken as the tag end, and a name bound by
a block was renamed at uses that read the local rather than the global.

Closes #4117
MiniJinja is built with default-features = false, so `macro` and `call`
are not statements and a template using one fails to parse before the
binding scan runs. Pin the fail-closed path for a tag the scanner cannot
terminate instead.

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Three findings, all reproduced against this head with a scratch unit test; the first two are the same double-rename this PR fixes, surviving on inputs the new scanner reads differently from MiniJinja.

{%+ … %} bypasses the binding scan. MiniJinja treats + and - identically as whitespace-control markers — Whitespace::from_byte maps b'-' to Remove and b'+' to Preserve, and the block-end match is matches!(rest.get(..1), Some("-" | "+")). template_block_bindings strips only -, so {%+ set … %} yields an empty keyword and binds nothing:

{{ repo_root }}{%+ set repo_root = "local" %}{{ repo_root }}
  =>  {{ repo_path }}{%+ set repo_root = "local" %}{{ repo_path }}

The trailing use is renamed and now reads the global — the exact case test_normalize_skips_names_bound_by_a_block pins for {%-. template_block_name has the same gap outside the diff (it strips '-' then trim_start), which is why {{ repo_root }}{%+ raw %}{{ repo_root }}{%+ endraw %} rewrites the literal inside the raw block.

Bindings inside {% raw %} count. template_bound_names walks tags without the in_raw state the rewriter keeps, so jinja-looking text inside a raw block registers as a binding. That reverses a migration that works on main today:

{% raw %}{% set repo_root = "x" %}{% endraw %}{{ repo_root }}
  =>  unchanged, and detect_deprecations returns []

The {{ repo_root }} is a real global use; after #4080 stops supplying the variable it renders undefined, with no warning ever having fired.

The doc comments describe the opposite of the behavior. Both new functions say a bound name "keeps warning" / "keeps its warning". The filter sits in deprecated_vars_in_template, which is also what migrate_template_vars_doc reads, so a bound name produces no warning — this PR's own test asserts detect_deprecations(…).is_empty(), and the CHANGELOG entry says so correctly. The stated reason for choosing over-reporting is the part that doesn't hold: over-reporting silences the deprecation rather than preserving it. The direction is still right (a half-renamed scope changes what renders), but the comments should say what it costs, since that cost is what the warning fires iff update changes invariant forces.

Underneath all three: template_bound_names is a third scanner over the same tag grammar, re-deriving the tag walk, the comment special-case, and the whitespace-control stripping that rewrite_template_var_identifiers and template_block_name already do — and it has drifted from them on raw and on + before the PR has even merged. Routing the keyword-and-whitespace parse through one helper is the minimum; sharing the whole tag walk would be better.

I'll push fixes for all three.

Comment thread src/config/deprecation.rs Resolved
Comment thread src/config/deprecation.rs Resolved
Comment thread src/config/deprecation.rs Resolved
Comment thread src/config/deprecation.rs Resolved
Two scanner-vs-parser gaps found reviewing the binding scan this branch
added.

`+` is whitespace control just as `-` is (`Whitespace::from_byte` maps
both, and the tag-end match accepts either), but `template_block_name`
and `template_block_bindings` each stripped only `-`. So `{%+ raw %}`
was not recognized as a raw block and its literal contents were
rewritten, and `{%+ set repo_root = … %}` bound nothing — leaving the
name it shadows renamed at every use, the case this branch set out to
fix. Both readers now split the keyword through one `split_block_keyword`
helper, which strips either marker from either end.

`template_bound_names` also walked tags without the `in_raw` state the
rewriter keeps, so a binding-shaped tag inside `{% raw %}` — literal text
to MiniJinja, which binds nothing — held back a genuine use elsewhere in
the template, silently dropping both its migration and its warning.

The doc comments on both new functions claimed a bound name "keeps
warning". It does not: the filter sits in `deprecated_vars_in_template`,
which detection reads too, so such a template neither migrates nor warns
— as the branch's own test and CHANGELOG entry already said.
@max-sixty

Copy link
Copy Markdown
Owner

@worktrunk-bot The new binding scanner still misses parenthesized tuple targets that MiniJinja 2.24 accepts. In {{ repo_root }}{% for (repo_root, x) in items %}{{ repo_root }}{% endfor %}, binding_targets records no repo_root binding, so both the global and loop-local uses are rewritten to repo_path. Please parse nested assignment targets or derive bindings from MiniJinja's parsed representation, and add for, set, and with destructuring regressions.

This was written by Codex on behalf of max-sixty

Reported by @max-sixty: `{% for (repo_root, x) in items %}` bound
nothing, so the global and the loop-local were both renamed.

`binding_targets` split the target list on commas and kept only parts
that were bare identifiers, which threw away every parenthesized tuple —
`(repo_root` is not an identifier. MiniJinja's `parse_assignment` accepts
those for `for`, `set`, and `with` alike, and nests them arbitrarily.

It now scans the target region for identifiers instead, tracking bracket
depth and quoted strings to find where the targets end: the `in` keyword
for `for`, each top-level `=` for `set` and `with`, with a top-level
comma starting the next `with` pair's target. A dotted target is skipped
— `{% set repo_root.x = … %}` mutates an attribute of the global rather
than binding it, so the global still migrates.

Regressions cover the destructuring forms for all three keywords, and
the value-side shapes the target scan must not claim: a `for` if-filter,
a `==` comparison, a collection literal, and `{% for c in commits %}`,
the squash-template migration.
@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

Confirmed and fixed in 5fe6476 — all three keywords, not just for: {% set (repo_root, x) = items %} and {% with (repo_root, x) = items %} parse the same way and were renaming the shadowed use too.

Deriving the bindings from MiniJinja's own parse would need unstable_machinery, so binding_targets now scans the target region for identifiers instead of splitting it on commas, tracking bracket depth and quoted strings to find where the targets end: the in keyword for for, each top-level = for set and with, with a top-level comma starting the next with pair's target. That covers arbitrary nesting — {% for (a, (repo_root, x)) in items %} — since a nested tuple is just more identifiers inside the same region. A dotted target is skipped: {% set repo_root.x = 1 %} mutates an attribute of the global rather than binding it, so the global still migrates.

Regressions for the destructuring forms of for, set, and with are in test_normalize_skips_names_bound_by_a_block, with the parenthesized for added to the test_warning_fires_iff_update_changes battery. Because a scan that errs toward collecting would silently stop migrating real uses, test_normalize_rewrites_names_used_but_not_bound_in_blocks now pins the value-side shapes it must not claim — a for if-filter, a == comparison, a collection literal, and {% for c in commits %}, the squash-template migration.

Two other parser disagreements turned up in the same review and are fixed in 28ea3f2: + whitespace control was ignored where - was honored (so {%+ raw %} wasn't recognized as a raw block and its literal contents were rewritten), and the binding scan counted tags inside {% raw %}, which MiniJinja treats as literal text.

CI is still queued on this head. Locally: cargo test --lib --bins passes except copy::tests::test_copy_dir_recursive_does_not_count_a_non_regular_file, which fails on main in this sandbox too (socket(AF_UNIX, …) is blocked); cargo test --test integration config is 560/560; clippy and fmt are clean.

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two findings on the new commits; I'll push both fixes.

set's value region re-opens the target scan at a top-level comma. TargetsEndAt::Assign treats every top-level , as the start of the next target. That is right for {% with a = 1, b = 2 %}, but set takes exactly one assignment, so a top-level comma after its = builds a tuple value. {% set a = 1, repo_root %}{{ repo_root }} therefore records repo_root as bound, and the trailing use — a genuine global read, which MiniJinja renders as the global — is left unmigrated and, since detection reads the same set, unwarned. That is this branch's own failure mode arriving from the over-collecting side: once #4080 stops supplying the variable, the template renders undefined with no warning ever having fired. The keyword split already exists; set just needs the comma not to re-open the target region.

A test doc comment still carries the claim 28ea3f23 corrected. test_normalize_skips_names_bound_by_a_block says "Not migrating keeps the warning", three lines above its own detect_deprecations(…).is_empty() assertion. Suggestion inline.

How the first case was confirmed

Built the head and ran the config::deprecation unit tests (171 pass), then probed with a scratch test:

in     = {% set a = 1, repo_root %}{{ repo_root }}
out    = {% set a = 1, repo_root %}{{ repo_root }}   (unchanged)
render = Ok("R")                                     (repo_root supplied as "R")

The parenthesized form {% set a = (1, repo_root) %} migrates correctly today — the comma is inside brackets, so depth protects it.

Comment thread src/config/deprecation.rs Resolved
A top-level comma re-opened the target region for `set` as well as `with`,
but MiniJinja's `set` takes exactly one assignment — a comma after its `=`
builds a tuple value. So `{% set a = 1, repo_root %}` recorded `repo_root`
as bound and the global read beside it was left unmigrated and, since
detection reads the same set, unwarned: this branch's own failure mode
arriving from the over-collecting side.

`with`, whose comma really does start the next pair's target, keeps that
behavior under its own `TargetsEndAt` variant.

Also corrects the one doc comment 28ea3f2 missed: the test asserting a
bound name raises no deprecation still said not migrating "keeps the
warning".

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One finding on the new commits. The set-value fix itself is right, and checks out against MiniJinja 2.24's own parser: parse_set parses a comma-separated tuple on the RHS explicitly, while parse_with_block requires target = expr pairs separated by commas — so the Assign/AssignPairs split matches both. The same over-collection survives one step further along.

A set block's filter chain is scanned as target region. parse_set accepts {% set x | filter %}…{% endset %}, and with no = to close the target region binding_targets keeps collecting through the chain — including a filter's arguments, since collection is gated on in_targets and not on depth:

{% set x | default(repo_root) %}b{% endset %}{{ repo_root }}
  =>  unchanged, and detect_deprecations returns []

repo_root is recorded as bound, so the trailing use — a genuine global read — is left unmigrated and, since detection reads the same set, unwarned. That is this branch's own failure mode arriving from the over-collecting side, the same one f603a110 fixed for the comma; adding the template to the rewritten battery makes test_warning_fires_iff_update_changes fail, which is the invariant catching it rather than a judgment call.

One arm fixes it — a top-level | ends the target region for every keyword, since for's is already closed by in and a with target can't hold one — plus regressions in test_normalize_rewrites_names_used_but_not_bound_in_blocks and in the invariant battery. Pushing that.

`parse_set` accepts a filter on the block form — `{% set x | default(y) %}…
{% endset %}` — and that form has no `=` to close the target region, so
`binding_targets` kept collecting through the chain. Collection is gated on
`in_targets` rather than on `depth` (a parenthesized tuple target has to
count), so a filter's arguments were collected too:
`{% set x | default(repo_root) %}b{% endset %}{{ repo_root }}` recorded
`repo_root` as bound, leaving the trailing global read unmigrated and —
since detection reads the same set — unwarned.

A top-level `|` now ends the target region for every keyword: `for`'s is
already closed by `in`, and a `with` target can't hold one, so the arm needs
no variant condition.

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One finding on the new commit. The | arm itself is right, and matches MiniJinja 2.24's own parser: parse_set closes the target region on Assign | Pipe | BlockEnd, parse_with_block demands an Assign after each target, and parse_for_stmt closes on Ident("in") — so a top-level | can only follow a complete target list, for every keyword. The gap is one step to the side.

The binding check is made against the deprecated name but not the canonical one. deprecated_vars_in_template filters on !bound.contains(old), so a template that binds repo_path — the name the rewrite produces — passes the gate, and the rename walks a genuine global read into that binding. That is this branch's own failure mode arriving from the replacement side:

{{ repo_root }}{% for repo_path in items %}{{ repo_root }}{% endfor %}
  =>  {{ repo_path }}{% for repo_path in items %}{{ repo_path }}{% endfor %}

With the global supplied, RRR becomes Ri1i2 — the inner use reads the loop variable now. And it warns (detect_deprecations returns one), so this is not the quiet-but-unmigrated direction the design accepts: wt config update writes that rewrite into the user's config. Every pair collides the same way; {% for commit_details in items %}{{ commits }}{% endfor %} is the squash-template shape of it, CC to i1i2.

Extending the filter to !bound.contains(new) closes it within the policy already here — the pair drops out of the replacement set, so such a template neither migrates nor warns. The cost is that {% for commit_details in commits %} stops migrating too, even though the rename is harmless there because the iterable is evaluated before the binding takes; separating those needs the scope tracking this branch deliberately doesn't build.

Secondary: set's block form has no entry in test_normalize_skips_names_bound_by_a_block, so the target side of the new | boundary — {% set repo_root | default(1) %}…{% endset %} binding repo_root — is unpinned while only the value side is asserted. Adding it alongside.

Pushing both.

How this was confirmed

Built dead77d4a and probed with a scratch test, rendering each template before migration with the deprecated name supplied and after with the canonical one (items = ["i1", "i2"]):

in     = {{ repo_root }}{% for repo_path in items %}{{ repo_root }}{% endfor %}
out    = {{ repo_path }}{% for repo_path in items %}{{ repo_path }}{% endfor %}
before = Ok("RRR")   after = Ok("Ri1i2")   warns = 1

in     = {% for commit_details in items %}{{ commits }}{% endfor %}
out    = {% for commit_details in items %}{{ commit_details }}{% endfor %}
before = Ok("CC")    after = Ok("i1i2")    warns = 1

The set and with forms of the same collision rewrite identically (RR to RL). Reverting only the filter change fails the new test_normalize_skips_names_bound_by_a_block entries; with it, config::deprecation is 170/170, clippy and fmt clean.

`deprecated_vars_in_template` dropped a pair only when the *deprecated* name
was bound, so a template that binds the name the rewrite produces passed the
gate and the rename walked a genuine global read into that binding:
`{{ repo_root }}{% for repo_path in items %}{{ repo_root }}{% endfor %}`
rewrote every use to `repo_path`, and the inner one — the global today —
became the loop variable. The pair warns, so `wt config update` wrote that
into the user's config rather than leaving it alone.

Both names are checked against the bound set now, which drops the pair the
same way the deprecated-name case does: such a template neither migrates nor
warns. `{% for commit_details in commits %}` stops migrating as a result even
though its rename is harmless (the iterable is evaluated before the binding
takes); telling the two apart needs the scope tracking this does not build.

Also pins `set`'s block form in `test_normalize_skips_names_bound_by_a_block`,
so the target side of the filter-chain boundary is asserted and not just the
value side.
Drop this PR's CHANGELOG.md entry. Changelog entries are written from the commits at release time (CLAUDE.md, Releases), so an open PR carrying an entry drops it rather than resolving a conflict on it.

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two findings on the new commit, both prose-vs-code rather than behavior — the !bound.contains(new) filter itself is the right closure, and every shape it has to cover lands where the design says it should.

deprecated_vars_in_template's contract doc no longer describes what it returns. It still reads "the deprecated (old, new) pairs used as variables in template… Empty when none appear (or the template doesn't parse)… only genuine variable uses, which is exactly what the rewrite replaces." Both halves are now false, and the line three rows below the doc is what falsifies them: the enumerated empty conditions omit the bound-name filter — the whole point of this PR, and now applied twice — and a genuinely-used deprecated name is no longer always returned, since either half of the pair being bound drops it. A reader taking the contract at face value concludes the opposite of what the function does. Same doc-vs-code shape this branch already corrected on template_bound_names and template_block_bindings; this one was missed because it predates the branch rather than arriving with it.

The canonical-binding case isn't in the test_warning_fires_iff_update_changes battery. Every earlier edge case on this branch got an entry there — the {%+ %} binding and the parenthesized tuple in untouched, the quoted delimiter and the set comma and the filter chain in rewritten — and CLAUDE.md asks for exactly that under Config Deprecation ("add new edge cases to its battery"). Right now the case is pinned only by test_normalize_skips_names_bound_by_a_block, which asserts the no-warning half but runs through normalize_template_vars, so the half that matters to a user — that wt config update writes nothing — goes through compute_migrated_content unasserted. It is a live pin, not a formality: adding worktree-path = "{{ repo_root }}{% for repo_path in items %}{{ repo_root }}{% endfor %}" to untouched and reverting !bound.contains(new) fails the battery on no warning expected for:.

Pushing both.

What the pass checked on the binding scan

Built this head and probed normalize_template_vars, detect_deprecations, and template_bound_names against the shapes the new filter has to cover, rendering before and after with the globals supplied. All land as designed: the canonical-name collision in set/for/with and in the commits/commit_details pair, {% for a, b in … %}, {% with a = x|d, repo_path = 2 %}, {% set repo_path %}…{% endset %}, {%+ set repo_path = 1 %}, a binding nested inside a for body, {% set ns = namespace(v=1) %}, a canonical name in the iterable position ({% for x in repo_path %}, still migrates), {% if repo_path %} (reads, doesn't bind), a binding inside {% raw %} (binds nothing), and {% set repo_path.x = 1 %} (dotted, binds nothing).

The doc's claim that set, for, and with are the only binding statements this build has checks out directly — with default-features = false, macro, call, import, from, include, extends, and block each fail template_from_str with syntax error: unknown statement …, so an unmodeled binding keyword can't reach the scan at all. filter and autoescape parse and bind nothing.

cargo test --lib config::deprecation is 171/171 on this head; cargo fmt --check and cargo clippy --all-targets are clean.

The contract doc still described the pre-branch behavior: "the deprecated
`(old, new)` pairs used as variables in `template` … Empty when none appear (or
the template doesn't parse) … only genuine variable uses". Both halves stopped
being true once the bound-name filter landed — the empty conditions omit it, and
a genuinely-used deprecated name now drops out whenever a block binds either
half of the pair. Say so, and point at `template_bound_names` for why.

Also pins the canonical-binding case in `test_warning_fires_iff_update_changes`,
where every earlier edge case on this branch has an entry.
`test_normalize_skips_names_bound_by_a_block` asserts the no-warning half but
goes through `normalize_template_vars`, so the half a user sees — that
`wt config update` writes nothing — was unasserted. Reverting
`!bound.contains(new)` with the entry in place fails the battery.
@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

Both review findings are pushed as 36c26ff79. Every required check is green on that commit — test (linux), test (macos), test (windows), fast-checks, lint — along with code-coverage, codecov/patch, and codecov/project.

The one red mark, affected tests (windows, advisory), is a ConPTY render race in test_switch_picker_abort_with_escape, not a regression. The same test passed on this same commit in the required test (windows) leg, which runs the full suite including shell-integration-tests, so the two runs disagree on identical code. The snapshot diff says why: the capture caught the picker's prompt line and nothing else — no header row, no main row — i.e. the frame was snapshotted mid-paint.

    1       │->
    2       │-    Branch  Status      HEAD±     main↕    main…±    Remote
    3       │-> @ main        ^
          1 │+>

That's the flake class tests/integration_tests/switch_picker.rs's own module doc describes under Capture-Before-Abort Pattern — the capture-before-abort ordering removes the teardown race but not this one, where the pre-abort frame itself hasn't finished painting. It's the first occurrence I can find (no open or closed issue names this test, and the job passed on the parent commit 59f26a769 in 8m55s), so it isn't worth a pin or a retry knob yet; a second sighting would be.

worktrunk-bot added a commit that referenced this pull request Sep 16, 2026
The delegation rule cited #4085 and #4124 as failures to ask the library, but
both evaluated delegation and kept the re-derived rule: zsh has no "where
should the config file go" to ask, and MiniJinja exposes no binding list
without unstable_machinery. As written an agent would read zsh_config_dir's
absolute-only guard - which keeps the whole-file uninstall rewrite out of the
invocation directory - as outstanding debt.

Also gives "don't defend improbable environments" its own heading, since it
has nothing to do with using existing dependencies, and pins that dropping a
fallback still means returning an error rather than .expect().
@max-sixty

Copy link
Copy Markdown
Owner

Can we simplify all of this? Do we need our own minijinja hand-rolled scanner? I'd really like to move this sort of thing out of worktrunk

@max-sixty max-sixty mentioned this pull request Sep 16, 2026
@max-sixty
max-sixty merged commit f108bf6 into main Sep 16, 2026
37 checks passed
@max-sixty
max-sixty deleted the fix/issue-4117 branch September 16, 2026 17:52
max-sixty added a commit that referenced this pull request Sep 16, 2026
Brings in #4124 (template-variable scanner), #4122 (deprecated keys in an
inline [projects] scope), #4136 (PTY snapshot diagnostic), and #4134 (tend
workflows).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request Sep 16, 2026
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request Sep 16, 2026
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request Sep 16, 2026
The previous commit spliced the rewrite at offsets computed before an
earlier replacement in the same file, so the entry's opening and link
were mangled.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

No, we don't — #4141 deletes it. MiniJinja ships its parser behind the unstable_machinery feature, so the migration can walk the real AST instead of re-deriving the grammar: the reads are the Expr::Var nodes and the bindings are the statements' own targets, and the rewrite splices at the byte ranges the parser gave them. Seventeen functions — the tag walker, the target-list reader, the quote and identifier scanners, the {% raw %} state — come out for nine short visitor methods, and detection and migration collapse into one call instead of two functions sharing a predicate. Every test on this PR passes unchanged except the one that pinned a scanner limitation the parser doesn't have.

Two costs I'd rather you weigh than discover: unstable_machinery carries no semver guarantee (MiniJinja last moved it in a patch release, so a version bound wouldn't reliably help), and it pulls in internal_debug for ~116KB of release binary, ~67KB stripped — measured by building both ways. The failure mode of the first is a compile error naming the node to handle, because both AST matches are exhaustive; it can't mis-migrate silently. If the binary cost is the wrong trade for a config-load path, say so and I'll close it — the scanner as merged here is correct on everything we've tested.

max-sixty added a commit that referenced this pull request Sep 16, 2026
…obable environments (#4137)

Four times in the last 24 hours, `max-sixty` asked a bot PR for less
code, and
each time the ask was the same one in a different costume: stop encoding
another tool's rules in `wt`, and stop defending environments that are
already
broken. Nothing in `CLAUDE.md` said either, so each PR re-learned it in
review.
The first extends **Code Quality → Use Existing Dependencies**, which
already
tells you to reach for a dependency before hand-rolling a utility; the
second
gets its own heading beside it, since defending an environment has
nothing to
do with dependencies.

Both cases the delegation rule came from resolved *into* its exception
rather
than out of it — #4085 established that zsh has no "where should the
config
file go" to ask, and #4124 that MiniJinja exposes no binding list
without
`unstable_machinery`. The guidance names neither: cited as examples,
they read
as debt still to pay off, and the zsh decision already lives in
`zsh_config_dir`'s docstring, which is where the rule says that
reasoning
belongs.

The generalisation is the maintainer's, not an inference from the diffs
—
on #4085: *"can we try to remove as much as possible from our code that
attempts to interpret the internals of other libraries?"*, prefaced with
*"we hit this on some of the sibling issues"*. #4106 is the standing
backlog
that same instinct produced.

**Second half, the anxiety one.** On #4104: *"this is totally fine;
we're an
order of magnitude too anxious here. if someone doesn't have a
resolvable home
dir, then honoring the xdg config in worktrunk is the least of their
problems"* — the wording here is close to his deliberately. The earlier
instance is #4107, where a bot self-review invented a scan of a stranded
fish
config directory and he cut it: *"if someone moves the config dir, then
we'll
miss the uninstall, that's fine"*. The **Data Safety** carve-out is
explicit
because that section rules the opposite way on purpose, and this
paragraph
must not be read as licensing a silent loss.

**Why now rather than at the next instance.** The behaviour is
stochastic, so
it carries a 5-occurrence floor; the window took it to six (#4085,
#4104,
#4123, #4124 here, plus #4104's `nu-config` round and #4107 recorded on
2026-09-15 in #3980). The bot also has seven PRs open, over the
self-initiated
budget — this one is filed anyway because the cost class is a wrong
outward
action, not compute: #4124 shipped a hand-rolled MiniJinja binding
scanner
whose correctness gap the maintainer had to find himself.

<details><summary>The four corrections, and what each one cost</summary>

| PR | Correction | Outcome |
|----|-----------|---------|
| [#4085](#4085) | "can we
just ask `zsh` for whether the config file should go?" | Bot showed the
`zsh -f -c` probe relocates the rule rather than removing it, deleted
the zsh-source docstring, and gave `zsh_config_dir` the absolute-only
guard the module already applied to `$XDG_DATA_HOME`. The rule itself
stays in `wt`. Merged. |
| [#4104](#4104) | "we're an
order of magnitude too anxious here" | Taken as a precondition in
`c4089e3c`; `read_tea_config`'s two home-directory resolutions collapsed
into one candidate list. Merged. |
| [#4123](#4123) | "can't we
just delegate all toml parsing to serde?" | Bot tested `serde_ignored`
in a scratch crate and reported where `#[serde(flatten)]` blinds it,
rather than answering from reasoning. Open. |
| [#4124](#4124) | "the new
binding scanner still misses parenthesized tuple targets that MiniJinja
2.24 accepts" | Fixed in `5fe64767` across `for`/`set`/`with`; deriving
bindings from MiniJinja's parse needs `unstable_machinery`. Open. |

Only the last is a correctness defect — the other three are complexity
the
maintainer declined to carry. The bot absorbed all four within hours, so
the
gap is not in how it responds but in it not knowing beforehand.

Evidence for this run is appended to the `review-runs-tracking` issue
[#3980](#3980); the prior
two
occurrences are under `Run 34943713746`.

</details>

`CLAUDE.md` is hand-edited, not generated, so no mirror regenerates from
it and
`test_docs_are_in_sync` is unaffected.

---------

Co-authored-by: worktrunk-bot <[email protected]>
Co-authored-by: worktrunk-bot <[email protected]>
Co-authored-by: Maximilian Roos <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request Sep 16, 2026
The #4136 filter matched the diagnostic only at a line start. On macOS CI
(actions/runs/35132033122) bash wrote it straight after the capture's
trailing `\x1b[0m`, with no newline between, so
test_bash_shell_integration_hint_suppressed failed on a snapshot diff.
The filter now also matches right after an SGR escape and keeps the
escape. The filter test gains that shape, and fails on the old pattern.

Also, in the changelog, note that a #4124 template binding a retired
name gets no deprecation warning.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request Sep 16, 2026
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
max-sixty pushed a commit that referenced this pull request Sep 16, 2026
…parser (#4141)

## Problem

Follow-up to @max-sixty's question on #4124: *"Do we need our own
minijinja hand-rolled scanner?"*

No. `src/config/deprecation.rs` located the identifiers it migrates with
a scanner that re-derived MiniJinja's grammar from the raw string —
where a tag ends, how whitespace control is spelled, what a quoted
string is, what `{% raw %}` makes literal, and how `set`/`for`/`with`
target lists are shaped. Every place that second reading disagreed with
the parser was visible in the file worktrunk writes: #4117 was a `}}`
inside a string ending a tag early, and the two review rounds on #4124
added parenthesized tuple targets, `+` whitespace control, and tags
inside `{% raw %}`. Each fix made the scanner longer and the next
disagreement harder to rule out, because nothing structurally tied it to
what MiniJinja actually does.

## Solution

Enable MiniJinja's `unstable_machinery` and parse the template instead
of scanning it.

`TemplateVars` walks the AST once and collects two things: the reads,
which are the `Expr::Var` nodes — by construction the set the renderer
resolves against the context — and the bound names, which are the
statements' own target expressions. The rewrite then splices at the byte
ranges the parser gave those nodes. Everything the scanner had to decide
for itself is now the parser's answer: quoted delimiters, whitespace
control, comments, `{% raw %}` contents, attribute names,
keyword-argument names, nested tuple targets.

That deletes seventeen functions — the tag walker, the target-list
reader with its `TargetsEndAt` modes, the quote and identifier scanners,
the `{% raw %}` state machine — for nine short visitor methods. It also
collapses detection and migration into one call (`migrate_retired_vars`)
instead of two functions sharing a predicate, so the framework invariant
is now structural rather than maintained.

The shadowing policy is unchanged: a retired or canonical name bound
anywhere still drops the whole pair rather than renaming per scope. The
AST would now support real scope tracking, but that is a behavior
change, not a simplification, so it stays out of this PR.

## What this costs

Two things worth weighing against the deletion, both stated up front:

- **`unstable_machinery` has no semver guarantee.** MiniJinja last
changed it in a *patch* release (1.0.16 moved `tokenize`/`parse`
signatures), so a version bound wouldn't reliably prevent a break. The
coupling here is to the AST's shape alone and both matches are
exhaustive, so the failure mode is a compile error naming the node to
handle — never a silent mis-migration. CI catches it on a bump; a `cargo
install` against a future MiniJinja would fail to build rather than
misbehave.
- **~116KB of release binary** (~67KB stripped), measured by building
both ways. `unstable_machinery` pulls in `internal_debug`, which derives
`Debug` across the AST and instruction types. The `Cargo.toml` comment
now records this against the ~200KB the trimmed feature set saves.

## Behavior change

One, and it is a fix: `{{ repo_root }}{% raw %}{{ " {% endraw %}` now
migrates. The scanner had to find that tag's end itself, couldn't, and
left the whole template alone; MiniJinja reads the raw block as the
literal it is. `test_normalize_bails_on_a_tag_it_cannot_terminate`
pinned the old behavior and is replaced by
`test_normalize_migrates_past_a_tag_opened_inside_a_raw_block` plus
`test_normalize_leaves_an_unparsable_template_untouched`, which pins
what the bail-out is actually for.

## Testing

Every existing test in the module passes unchanged apart from that one,
including the whole `test_warning_fires_iff_update_changes` battery and
the edge cases #4124 added. New pins for what the parser now decides:

- `test_normalize_skips_identifiers_that_are_not_reads` — a
keyword-argument name and a map key.
- `test_normalize_rewrites_reads_out_of_visit_order` — the AST hands
reads back test-first for a conditional and keys-before-values for a
map, so two migrations in one tag must still splice coherently. Removing
the sort makes this panic.
- `test_normalize_rewrites_inside_a_do_statement` — `{% do %}` is its
own statement, not an emitted expression.
- `test_normalize_rewrites_reads_in_every_expression_shape` — one case
per AST node the walk descends, since a missed visitor arm loses a
migration silently rather than failing.
- `test_warning_fires_iff_update_changes` gains an unparseable template
to `untouched`.

`cargo test --lib --bins` passes except
`copy::tests::test_copy_dir_recursive_does_not_count_a_non_regular_file`,
which fails on `main` in this sandbox too (`socket(AF_UNIX, …)` is
blocked — verified by stashing the change and re-running). `cargo test
--test integration config` is 582/582. `cargo clippy --all-targets` and
`cargo fmt --check` are clean.

---------

Co-authored-by: worktrunk-bot <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: worktrunk-bot <[email protected]>
max-sixty added a commit that referenced this pull request Sep 16, 2026
max-sixty added a commit that referenced this pull request Sep 16, 2026
Version bump to 0.78.0 plus the changelog section for this release, a comment-preservation fix the release review turned up, a PTY test-filter fix, and merges of `main` (commits that landed during the review, including #4124, #4122, #4141, #4140 and #4145).

**Bump level**: minor. `cargo semver-checks` reports 2 breaking library changes — a new `leftover_branch` field on the `GitError::WorktreeCreationFailed` struct variant, and `DEPRECATED_TEMPLATE_VARS` removed. Pre-1.0, so a breaking change takes a minor bump.

## Comment-preservation fix

A config save — declining the commit-generation offer, say — dropped the trailing comment on every value it rewrote. That was already true in v0.77.0 for a line the save itself changed (`skip-commit-generation-prompt = false  # note` → `true`, reproduced on the v0.77.0 binary). #4080 widened it to lines the command never touched: retired template variables now migrate on every load, so the next unrelated save rewrote any line naming one. #4080's own PR said this "needs a call before merge" and merged without one.

- `replace_keeping_decor` keeps the value's decor (spacing after `=`, trailing comment) when `merge_tables` replaces a scalar. Comments *above* a line sit on the key and were never at risk.
- `main`'s #4120 independently reworked the inline-table arm and moved a key's leading comment onto the rewritten header, but documented that a trailing comment after the closing brace "is still dropped". `replace_inline_with_table` now carries it after the header's `]`, so both of its callers keep it.
- Tests: the existing comment-preservation test goes back to a retired name (the only fixture that exercises the replacement) and adds a comment on the mutated line; a new test snapshots and re-parses an inline `[projects]` entry. Each fails without its half of the fix.

Not fixed, and identical on v0.77.0: a save deletes an explicitly written *default* value (e.g. `skip-commit-generation-prompt = false  # note`) as a stale key, comment included.

## `--help` correction

#4104 moved the OpenCode plugin path to etcetera's `Xdg` strategy, which uses `$XDG_CONFIG_HOME` only when absolute — a deliberate, documented choice — but `wt config plugins opencode --help` still said install mirrors OpenCode's precedence. OpenCode reads a relative value as-is, so the help now says an empty `$OPENCODE_CONFIG_DIR` and an empty or relative `$XDG_CONFIG_HOME` are ignored.

## Data-loss surface review

Independent finders swept the full diff, including the five commits merged from `main`. Nothing holds the tag; candidates were adjudicated against v0.77.0 binaries:

- **Fixed in this release, reproduced on v0.77.0**: #4104 stops `wt config shell install` (with Nushell) deleting a `nushell/vendor/autoload/wt.nu` under the current directory when `$XDG_CONFIG_HOME` is empty or relative; #4120 stops a save or migration from writing an inline section's comment inside `[commit]` brackets, which made the config unparseable, and from dropping unknown keys.
- **`wt step prune --min-age` doesn't apply where no reflog exists** — pre-existing, proven by building the pre-#4077 binary. `git clone --bare` and `git fetch` into `refs/heads/*` write no reflog, so in the bare layout `tips-patterns.md` recommends every branch starts unprotected. Docstring corrected here; behavioral fix is follow-up.
- **`wt config update --output <path>` replaces any named file whole**, no existence check or prompt — pre-existing, follow-up.
- **`wt config shell install fish --yes` replaces a hand-written wrapper at the XDG path** — accepted ("ownership is the path", predates #3602), newly reachable only for users with `$XDG_CONFIG_HOME` set. The FAQ's delete inventory now cross-references it.
- **`--var <retired-name>` binds a name nothing references** after #4080 — inert, no shipped usage; follow-up.
- **#4135 migrates nothing**: an existing oh-my-pi hook stays put, `pi uninstall` points at `omp uninstall`. `PI_CODING_AGENT_DIR='~/x'` is used literally (Pi expands `~`) — creates a stray directory, deletes nothing; follow-up.

## Changelog

37 entries; each new or edited entry was re-verified against v0.77.0 until a pass came back clean (six passes in all). Passes caught, among others: the OpenCode `-x` recipe was wrong since 0.76.0, not 0.75.0; #4080's JSON reaches every hook, not just `pre-start`/`post-start`; a quoted git error string git never prints; a copy-button overlap that existed only inside this release; #4104's relative-`XDG_CONFIG_HOME` OpenCode change described as a fix when OpenCode reads that path as-is; and which commands a broken inline section stopped. **Fixed** leads with the data-loss entries.

## Open PRs checked against v0.77.0

- **#4124** fixed a bug new in this release, caused by #4080, and has landed and been merged in here. The hand-rolled template-variable scanner it extends is slated for removal; see its commit message.
- **#4112** — no data-loss regression vs v0.77.0; two small non-safety regressions from #4111 (an uncapped auto-staging file list, a narrow `Nothing to commit` refusal under `status.showUntrackedFiles = no`). Not merged, by decision.
- **#4122** (merged in) and **#4123** — pre-existing bugs, identical on v0.77.0.

## PTY filter fix

`test (macos)` failed once on a shell's failed-`setpgid` diagnostic that landed straight after the capture's trailing `\x1b[0m`, with no newline between, so #4136's line-anchored filter missed it. The filter now also matches right after an SGR escape and keeps the escape; its test gains that shape and fails on the old pattern.

## Validation

- `cargo run -- hook pre-merge --yes` — 4930 tests passed, 1 skipped; clippy, fmt, doc-sync, snapshot and lockfile checks green
- Nightly on the original cut-from tip (https://github.com/max-sixty/worktrunk/actions/runs/35060617020): green across `full-tests` on linux/macos/windows, `feature-powerset`, all `release-target`s, `nix-flake`, `minimal-versions`, `link-check`

> _This was written by Claude Code on behalf of max-sixty_

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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.

config: template variable rewriting loses tag and binding semantics

2 participants