Skip to content

fix: argv panic, format-flag, state-write enforcement, deprecated-config preservation - #2788

Merged
max-sixty merged 6 commits into
mainfrom
clawpatch
May 20, 2026
Merged

max-sixty merged 6 commits into
mainfrom
clawpatch

Conversation

@max-sixty

@max-sixty max-sixty commented May 17, 2026 •

Copy link
Copy Markdown
Owner

Summary

Four standalone correctness fixes, each independent of the others, each with a regression test. Originally this branch was a large approval-boundary hardening PR (the "Group B" work); since then #2806 landed on main and structurally closed that entire TOCTOU class, deleting the point-fix scaffolding this branch had built. The branch has been rebaselined onto current main and reduced to the leftover orthogonal fixes that #2806 doesn't cover.

What's in this PR

Fix Why
Non-Unicode argv panic (src/help.rs, src/main.rs, src/invocation.rs) std::env::args() panics on non-UTF-8 argv; the help renderer, command-line logger, and the three invocation.rs accessors (binary_name, invocation_path, was_invoked_with_explicit_path) all used it. Switched to args_os() + to_string_lossy(), closing the class. Regression test in tests/integration_tests/custom.rs.
Format-flag rejection on write state actions (src/main.rs) guard_format_on_write called clap::Error::exit(), killing the process before the verbose diagnostic and output epilogue ran. Now returns a Result so the conflict error flows through normal error handling. Parameterised regression test (flag before/after, all four state kinds) in tests/integration_tests/config_state.rs.
StateWrite compiler-enforced format-on-write guard (src/cli/config.rs, src/cli/mod.rs, src/main.rs) Follows the above. The hand-placed guard_format_on_write(...) at 5 write-arm sites was opt-in — a future write variant could silently accept --format. Replaced with a StateWrite trait co-located with the action enums; exhaustive (no-wildcard) write_verb() impls make the classification a compile-time obligation. Behaviour byte-identical.
Don't drop deprecated config when the canonical parent is scalar (src/config/deprecation.rs) Three data-loss edges in compute_migrated_content: commit = "x" + [commit-generation] had nowhere to insert [commit.generation], same shape for switch = "x" + [select], and args = [1, "--ok"] silently filtered the non-string element while removing args. Added a can_host_subtable guard and an all-strings check. Regression tests for all three.

Why the diff is small now

The big "approval-boundary hardening" Group B that gave this PR its original title was a point-fix-per-call-site approach to the post-approval config-reload TOCTOU. After surfacing the structural alternative, a separate session built it as #2806, which landed on main and made the point-fixes redundant (it deletes most of the scaffolding they added). Force-pushed to rebaseline rather than carry the dead weight; the previous draft's review threads are on the prior history (0fd7d4db8) which is no longer the branch HEAD.

The "human security review of Group B" gate that kept this PR a draft is now moot — Group B's RCE-class code is on main via #2806's own review, not here.

Test plan

  • cargo build + cargo clippy --bins --features shell-integration-tests clean
  • Survivor tests pass on the new base (argv, format-flag, StateWrite, deprecation — 119 config_state + 150 deprecation tests, plus the new regression cases)
  • Required CI green: test (linux/macos/windows); codecov/patch 100%

This was written by Claude Code on behalf of Maximilian Roos

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewing as a draft — flagging anything that looks worth a quick fix. Mark ready for a full review.

A few non-blocking observations on the way past:

  • Orphaned docstring in tests/integration_tests/merge.rs. Two regression docstrings are stacked above test_merge_post_switch_introduced_on_feature_branch_does_not_run (lines 663–680). The post-merge regression description (lines 663–673) is misplaced — test_merge_post_merge_introduced_on_feature_branch_does_not_run at line 720 has no docstring. The fix is to keep only the post-switch description above the post-switch test and move the post-merge description above the post-merge test. Inline suggestions below.

  • src/commands/process.rs:739 — \ line continuation in the dirty-guard format string. The rendered shell is correct, but the source uses \ + indent which CLAUDE.md → "Multiline String Literals" calls out as the phantom-indentation pitfall: the reader sees if … ; then \ / echo … and parses it as block structure, when the actual emitted command is a single then echo … line. Inline suggestion below.

The substantive logic in Group B looks consistent: DestinationConfig::Pinned vs Reload is correctly chosen at each call site (merge → Pinned, picker/remove/prune → Reload), and removal_hooks_approved reads pre-remove from disk (worktree still present) but reads post-remove from the RemoveResult snapshot (worktree gone) — matching what the executor does. No issue noted there.

Comment thread src/commands/process.rs Resolved
Comment thread tests/integration_tests/merge.rs Resolved
Comment thread tests/integration_tests/merge.rs Resolved

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewing as a draft — still flagging anything that looks worth a quick fix. Mark ready for a full review.

Two stale references the DestinationConfig collapse left behind:

  • src/commands/picker/mod.rs:379-380 — the docstring bullet still describes a reload fallback that no longer exists. Suggested replacement (lines are outside the diff hunks, so this is body-only):

    /// - `post-switch` runs from the same pinned destination snapshot the
    ///   executor consumes (always pinned at approval time; never reloaded
    ///   from disk — a concurrent writer could otherwise swap in an
    ///   unapproved hook).
    
  • Existing thread on tests/integration_tests/merge.rs:680 — that earlier suggestion's replacement text ends with `DestinationConfig::Pinned` makes the empty-at-approval case explicit. After this commit DestinationConfig no longer exists; if you apply the suggestion, drop that closing sentence (or rephrase to "the always-pinned destination_project_config makes the empty-at-approval case explicit").

The substantive refactor reads cleanly — the gate and the executor now both consume the snapshot from the same RemoveResult field, and prepare_worktree_removal pins the destination config alongside the removed_project_config snapshot before any approval check runs. Stronger guarantee than the previous Reload branch.

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewing as a draft — flagging anything that looks worth a quick fix. Mark ready for a full review.

One observation on the new test in src/commands/picker/mod.rs:

  • test_removal_hooks_approved_checks_pinned_post_switch doesn't actually discriminate post-switch checking. The name and docstring promise the gate is verified to see the pinned post-switch, but the setup makes pre-remove, post-remove, and post-switch all unapproved at once. The function returns false if any of the three hits the gate, so the test would still pass if the post-switch block at picker/mod.rs:417-422 were deleted outright — pre-remove alone is enough to flip the return to false. For a hardening test on a security-critical path, the assertion should pin only what its name claims. Two ways to tighten:

    1. Strip the other two sources from the setup — drop the .config/wt.toml + git add + git commit block and set removed_project_config: None. The gate then sees only the destination snapshot, and the test fails the moment post-switch checking is removed.
    2. Or keep the all-three setup but add a second assertion that isolates post-switch (only destination_project_config: Some(...), everything else None).

    Variant (1) is the smaller change; variant (2) better matches the existing test pair's one-hook-per-test pattern.

The other changes in this push read cleanly: the #[cfg(unix)] gating on removed_project_config() / destination_project_config() accessors matches the picker's #[cfg(unix)] on mod picker and the only callers are in removal_hooks_approved; struct-field destructuring elsewhere keeps working on Windows. The picker docstring at picker/mod.rs:382-388 and the merge-test docstring placement now match the code.

max-sixty and others added 5 commits May 19, 2026 12:28
The help pre-scan and command-line logging paths used std::env::args(),
which panics on Unix when any argv element contains invalid UTF-8. This
could crash the process before dispatch_command runs, even for valid
invocations with non-UTF-8 forwarded arguments to custom subcommands.

Changed both paths to consume std::env::args_os() and convert each
OsString lossily with to_string_lossy(), preserving the clap dispatch
path that already handles OsString correctly. Added a Unix regression
test that launches a custom subcommand with an invalid-UTF-8 argument.
Make guard_format_on_write return a Result so the clap conflict error propagates through normal error handling. This ensures finish_command writes the verbose diagnostic and output termination even when a format flag is rejected on a write action like `wt -vv config state marker set foo --format=json`. Add a focused regression test for this post-dispatch error path.
The guard rejecting `--format` on write actions (set/clear) was
hand-placed at 5 call sites in handle_state_command — opt-in, so a new
write variant silently accepts the flag unless the author remembers it.

Introduce a StateWrite trait co-located with the action enums, with
exhaustive (no-wildcard) write_verb() impls for CiStatus/Marker/Logs/
Hints actions. Adding a variant now fails to compile until classified.
handle_state_command derives the guard from the trait and calls it once
per parent arm instead of at each write arm. Behavior is byte-identical
(same guard, same verbs, both flag positions); all 10
test_format_rejected_on_write_actions cases unchanged.

Co-Authored-By: Claude <[email protected]>
…s scalar

Three data-loss edges in `compute_migrated_content`:

- `commit = "x"` + `[commit-generation]`: `doc.contains_key("commit")` was
  true so no table was created, then `doc["commit"].as_table_mut()` was None,
  so the migrated `[commit.generation]` was never inserted — but the source
  was already removed. Same shape for `switch = "x"` + `[select]`.
- `args = [1, "--ok"]`: the string filter silently discarded the non-string
  element while removing `args`.

Add `can_host_subtable` (parent absent or table) and gate source removal on
it for both top-level and project-level commit-generation and for select.
Require every `args` element be a string before merging; otherwise preserve
`args` unchanged. Regression tests for all three.

Reconstructed against current main: the original clawpatch implementation
sat on a divergent #2783 baseline and its 4-commit Group C stack would not
3-way-merge cleanly on top of #2806/#2783 main without hand-merging
config-migration logic — the exact code where silent corruption is the
defect. Re-derived as one focused change.

Co-Authored-By: Claude <[email protected]>
@max-sixty max-sixty changed the title fix: approval-boundary hardening + argv/format/config-loss fixes (review) fix: argv panic, format-flag, state-write enforcement, deprecated-config preservation May 19, 2026
@max-sixty
max-sixty marked this pull request as ready for review May 20, 2026 03:43

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The four fixes read cleanly and each comes with a regression test that exercises the bug. One observation, one nit.

Observation, outside the diff — the src/help.rs + src/main.rs::main() argv-panic fix scopes itself to two call sites, but src/invocation.rs has three more std::env::args() users in the same panic class: binary_name(), invocation_path(), and was_invoked_with_explicit_path(). They each call .next() on std::env::args(), which panics if argv[0] is non-UTF-8 (e.g. wt installed at a path containing non-UTF-8 bytes). All three are called early — main.rs (lines 569, 722), commands/init.rs, commands/config/show.rs, output/shell_integration.rs. Less likely than non-UTF-8 forwarded user args in practice (install paths are usually ASCII), but it's the same fix shape (args_os().next().map(|a| a.to_string_lossy().into_owned())) and would close the class. Happy to push a follow-up if you want it in this PR, or leave it as a separate fix.

Nit, inside the diff — the inline // Filter to string args only (non-strings are dropped) at src/config/deprecation.rs:1192 is now stale: the new precondition guarantees every element is a string, so the filter_map is defensive, not active. Worth rewording or dropping the comment. (Inline suggestion below updates the function's doc-comment contract; the body comment is outside the hunk.)

Comment thread src/config/deprecation.rs
@@ -1144,8 +1164,13 @@ pub fn copy_approved_commands_to_approvals_file(
/// - `command` is missing or not a string
/// - `args` is not an array

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
/// - `args` is not an array
/// - `args` is not an array
/// - any element of `args` is not a string

Keeps the function's preservation contract in sync with the new precondition added in this PR (every element must be a string).

…comment

Addresses worktrunk-bot review on #2788.

The argv-panic fix covered help and command-line logging but left three
more `std::env::args()` callers in the same panic class: `binary_name`,
`invocation_path`, and `was_invoked_with_explicit_path` each call `.next()`
on `args()`, which panics when `argv[0]` is non-UTF-8. Switch all three to
`args_os()` (with `to_string_lossy()` where a `str` is needed), closing the
class.

Also reword a now-stale comment in `merge_args_into_command`: the
all-strings precondition added for the scalar-parent fix makes the
`filter_map` an extraction, not a filter.

Co-Authored-By: Claude <[email protected]>
@max-sixty
max-sixty merged commit 5cbc5b4 into main May 20, 2026
32 of 33 checks passed
@max-sixty
max-sixty deleted the clawpatch branch May 20, 2026 04:37
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.

2 participants