Skip to content

wt config state marker under concurrency can rename the shared parent directory of many repos (CWD-recovery false-match / TOCTOU) #3552

Closed

Description

@4i3n6

Summary

Under a storm of concurrent wt config state marker calls, worktrunk renamed the
shared parent directory of ~180 sibling repos. The parent got renamed to a truncated
form of a child repo's name (a 9-char repo name; the parent ended up named after its
first 7 chars). Every repo under the parent became inaccessible and running agents
broke with NotFound. It was a single rename(2) — inode identity and mtime
preserved, only ctime changed — so nothing was deleted, but it is a data-loss-class
failure.

I never invoked wt switch/merge/remove. The only wt calls in play were
wt config state marker set, emitted automatically by the OpenCode activity-marker
plugin.

Environment

  • worktrunk 0.68.0
  • Harness: OpenCode with the bundled worktrunk activity-marker plugin
  • Layout: ~180 git repos as siblings under a single parent directory ($PARENT);
    one of them has 3 worktrees, also siblings under $PARENT.

Trigger

The plugin shells out to wt on every session event:

// session.status  -> wt config state marker set <marker>
// session.idle    -> wt config state marker set <marker>
// session.deleted -> wt config state marker clear

With N parallel agents, every status/idle transition spawns a wt process.
Process-launch logs show ~465 wt spawns in ~29s, all contending on worktrunk state
and CWD/worktree resolution.

Timeline (relative)

  • T-13s: agent healthy, cwd = $PARENT/<repo>
  • T+0s: burst of wt spawns begins (~465 over ~29s)
  • T+5s: $PARENT inode ctime changes -> rename($PARENT -> sibling <repo-truncated>);
    mtime unchanged, so a pure rename, not copy/delete
  • T+29s: harness reports NotFound: FileSystem.access ($PARENT/<repo>); git worktree ops fail

Suspected root cause

The CWD-recovery path (hardened in #1193, "prevent false matches when multiple repos
share a parent directory") still appears to mis-resolve under concurrency. When a wt
observes a transiently-missing worktree while hundreds of siblings share $PARENT,
recovery/relocate picks the wrong target and renames the parent. Looks TOCTOU,
consistent with the other rename/TOCTOU fixes in the changelog (#2870, #2849, #2808).

Impact

A shipped, automatic agent plugin (wt config state marker) — a command a user would
reasonably assume is read-mostly/telemetry — can rename the parent of every repo in a
workspace, with no explicit mutating subcommand from the user.

Asks

  1. wt config state marker (and any read-mostly/telemetry command) must never
    relocate/rename a directory. Gate relocation behind explicit mutating commands.
  2. Serialize/lock state mutations per repo so the marker storm cannot race CWD-recovery.
  3. Hard-refuse any recovery/relocate whose target is an ancestor of the repo or contains
    other repos.

I can attach the relevant process-launch and OpenCode logs on request.

Activity

  1. worktrunk-bot commented on Jul 23, 2026

    @worktrunk-bot
    Collaborator

    Thanks for the detailed, syscall-level report — a rename(2) of a parent holding ~180 repos is exactly the data-loss class we want to run down, so I traced the wt config state marker path end-to-end on main (0.68.0). Two findings worth sharing before we go further, because they narrow where the rename could have come from.

    1. wt config state marker set/clear has no directory-rename, -move, or -relocate anywhere in its path. handle_state_set resolves the repo read-only (Repository::current() → git rev-parse --git-common-dir), resolves the branch (require_current_branch), and writes a single git-config key worktrunk.state.<branch>.marker. That is the whole side-effect surface — a git config write, no filesystem entry is created, moved, or renamed. So your Ask #1 ("a read-mostly/telemetry command must never relocate a directory") is already satisfied by the code today; the marker command is write-only against git config.

    2. The CWD-recovery path you suspected is read-only, and the marker command never invokes it. recover_from_path walks ancestors and calls list_worktrees() to find the owning repo — it returns a Repository and never touches the filesystem (no rename/move/create). It's also only wired into wt list, wt switch, and the interactive picker, not wt config state. #1193 hardened which repo it selects, but even a mis-selection there can only cause wt to operate against the wrong repo's config — it has no relocation step to rename a parent with.

    The only code in the tree that renames/moves a worktree directory is wt step relocate (git worktree move) and wt step promote (fs::rename) — both explicit subcommands, neither reachable from marker, and you note you never ran them. I also checked the specific corruption shape (parent → 7-char prefix of a 9-char child): there's no path-truncation logic like that; sanitize_for_filename runs with truncate: false.

    So from the code I can't find a path by which the marker storm renamed $PARENT, which makes me want the one piece of evidence that would localize it decisively rather than guess: which process issued the rename(2), and with what exact arguments. If you can capture that — e.g. strace -f -e trace=rename,renameat,renameat2 -y (or dtruss/fs_usage on macOS) around the burst, or even just the process-launch log correlated to the ctime change — the PID + args tell us whether it was a wt process at all. If it was, that reopens this as a real bug and points straight at the offending call; if it wasn't, it points us at OpenCode/git/another tool. The OpenCode and process-launch logs you offered would help too.

    I couldn't reproduce this from CI (it needs the OpenCode plugin under a concurrency storm), so I'm not opening a speculative fix — a fix premised on a rename path I can't find in the code would be guessing. A maintainer will take a look, and the strace/PID evidence above would let us turn this around quickly.

    Sources (pinned to a3de0b0)
  2. max-sixty commented on Jul 23, 2026

    @max-sixty
    Owner

    @4i3n6 this would obv be very bad if it were Worktrunk that had done this

    but I can't see how — setting a marker doesn't rename any path

    you mentioned you had more logs — could you share them, either here or feel free to email me at m at maxroos dot com. It's possible I'm missing something, or possible something else has gone wrong that still implicates worktrunk

    (and regardless, thank you for submitting an issue)

  3. 4i3n6 commented on Jul 23, 2026

    @4i3n6
    ContributorAuthor

    Thanks for the earlier trace, by the way — it's what redirected this investigation somewhere
    more useful. Update in three parts: a correction of my own numbers, one concrete finding,
    and where I think this leaves us.

    Scale correction. Re-extracting the unified log over a wider window (structured parse
    this time): at least ~1950 distinct wt process launches across ~2m23s, in bursts that are
    consistently exact multiples of 15 — and the storm was still running at both edges of my
    extraction window. My earlier "~465 in 29s" undercounted; same event, wider lens.

    The finding. This pass looked at the integration layer rather than the Rust binary.
    Two things I can point to in code:

    1. In opencode's plugin host (packages/opencode/src/plugin/index.ts, current dev), the $
      handed to every plugin is the process-global Bun shell, shared by all plugins loaded in
      that process:

      $: typeof Bun === "undefined" ? undefined : Bun.$,
      
    2. The opencode plugin shipped with worktrunk (dev/opencode-plugin.ts — byte-identical to
      what was installed here) runs its commands on that shared instance, and doesn't currently
      scope a working directory:

      await $`wt config state marker set ${…} || true`.quiet();
      

    Per Bun's semantics, that means each command runs in whatever the process-wide cwd is at
    spawn time — and the shared instance's default cwd/env can also be shifted by any other
    consumer via $.cwd() / $.env(), since opencode loads its internal plugins plus every
    user plugin into the same process, all holding the same object. PluginInput does provide
    directory, so the ingredients for scoping are already there.

    Being upfront about the limits: even a marker-set that lands in the wrong directory is
    still just a git-config write wherever it lands — which is consistent with your trace and
    with my own read of the Rust side. So this doesn't complete the causal chain to the
    parent-directory rename, and I still can't attribute the rename syscall. What it does give
    us is the first verified mechanism by which this integration can run wt somewhere other
    than the directory the event came from, under the kind of concurrency parallel-agent
    setups naturally generate.

    A small fix that closes it regardless: scoping each invocation —

       await $`wt config state marker set ${…} || true`.cwd(directory).quiet()
    

    One subtlety worth flagging: it has to be the promise-level .cwd() — the instance-level
    $.cwd(directory) would shift the shared default for every plugin in the process. Happy to
    open a PR for this if you'd take it. The broader question (whether the host should inject a
    scoped shell instead of the global one) is arguably opencode's side of the fence; I can
    raise it upstream if you think it's worth it.

    You'd asked for the raw logs earlier — glad to attach the process-launch excerpts and the
    burst timeline here or by email, whichever you prefer.

  4. worktrunk-bot commented on Jul 23, 2026

    @worktrunk-bot
    Collaborator

    Confirmed your finding against the shipped file. dev/opencode-plugin.ts on main (a3de0b0) destructures only { $ } and issues each command unscoped:

    export default (async ({ $ }) => {
      return {
        event: async ({ event }) => {
          switch (event.type) {
            case "session.status":
              await $`wt config state marker set ${'🤖'} || true`.quiet();

    So the mechanism you describe is real: this is the process-global Bun $, and nothing here pins a cwd, so the marker write lands in whatever the shared instance's current directory happens to be. Under a parallel-agent storm that's a genuine correctness bug in our plugin — an event carries a directory and we throw it away.

    I agree with the scoped-invocation fix, and I'd take that PR — please do open it. Two things to bake in so it lands clean:

    • Pull directory from PluginInput — the factory needs ({ $, directory }), and session.deleted should scope the same way as set.
    • Promise-level .cwd(directory), never $.cwd(directory) — exactly as you flagged. Instance-level mutates the shared default for every plugin in the host process, which is the same footgun one level up.

    Worth a comment at the call site noting why the per-command .cwd is load-bearing (shared global $), so a future refactor doesn't "simplify" it back to the instance form.

    Being precise about scope, matching your own honesty: this hardens where the marker write lands, but a mis-scoped marker set is still just a git config write wherever it lands — it doesn't rename a parent directory. So this is a real fix on its own merits and closes the "runs wt in the wrong dir" mechanism, but it doesn't yet explain the rename(2). If you can still attach the process-launch excerpts / burst timeline (or the strace around the ctime change), that's the piece that would let us attribute — or rule out — the rename itself.

    Raising the "host should inject a scoped shell" question upstream with opencode sounds right to me too; that's the more durable fix on their side of the fence. Thanks for running this down.

  5. 4i3n6 commented on Jul 23, 2026

    @4i3n6
    ContributorAuthor

    Process-launch excerpts, as requested. Source: macOS unified log (structured extraction),
    filtered to exec events of the wt binary. Each line is one process launch; PIDs were 1:1
    with launches (1950 lines, 1950 distinct PIDs — no reuse in the window). Sample line,
    verbatim (kernel-emitted, per exec):

    ASP: Unable to apply provenance sandbox: 268451845, <pid>, /opt/homebrew/Cellar/worktrunk/0.68.0/bin/wt
    

    Timeline normalized to T+0 = first wt spawn observed (absolute times deliberately
    omitted). New wt processes per second:

    T+0s    135        T+61s    45        T+115s   60
    T+3s     45        T+62s    45        T+116s   60
    T+6s    120        T+74s    45        T+133s   60
    T+13s    45        T+75s    45        T+134s   60
    T+14s    45        T+81s   120        T+140s   60
    T+16s   135        T+82s    45        T+141s   60
    T+30s    45        T+85s    45        T+143s   45
    T+31s    45        T+91s   120
    T+37s    45        T+104s   45
    T+40s    45        T+105s   45
    T+53s   120        T+106s   90
                       T+107s   30
    

    Totals: 1950 launches across 143s, every burst an exact multiple of 15. The storm was
    already running at the start edge of my extraction window and still running at the end
    edge, so 1950 is a floor, not the full count.

    Correlated filesystem events, same clock:

    • T+58s — inode ctime change on $PARENT (mtime preserved, ctime bumped: a pure
      rename(2), not copy+delete). Falls 5s after the 120-spawn burst at T+53s.
    • T+82s — first NotFound: FileSystem.access ($PARENT/<repo>) from the harness.
    • T+121s — $PARENT recreated (empty scaffold) by the harness's session-continuation
      machinery.

    Context for the multiples of 15: the machine had roughly 15 repos/worktrees under agent
    management at the time, so N parallel sessions firing status/idle transitions on a shared
    tick is consistent with the burst shape.

    Honest limit, restated: no syscall-level auditing (strace/ESF) was running at the time, so
    these excerpts bound the "what and when" — they can't name the process that issued the
    rename(2). The tightest statement the data supports: the rename landed inside a sustained
    wt spawn storm, 5 seconds after a 120-process burst, and no other wt-invoking actor was
    found in any harness/shell log for that window.

  6. worktrunk-bot commented on Jul 23, 2026

    @worktrunk-bot
    Collaborator

    Thanks for pulling these — that's exactly the launch-level data I asked for, and it does firmly establish the spawn storm (~1950 execs of the Homebrew wt over 143s). Two of your own caveats are the important ones, and I want to build on them rather than restate: no syscall auditing was running, so nothing here names the process that issued the rename(2), and a mis-scoped marker set is still just a git config write. Three things I can add on top:

    1. The temporal correlation isn't discriminating. The storm is continuous for the full 143s, with bursts landing every few seconds (T+53, 61, 62, 74, 75, 81…). The ctime bump at T+58 falls in the 53→61 gap, so "5s after a 120-spawn burst" is just where any timestamp in that window would land — every second of it is within ~10s of a burst. With that base rate, temporal proximity to wt spawns can't distinguish wt from any other actor running concurrently; it's what we'd see regardless of cause.

    2. The only rename a marker set performs is the git-config lockfile commit — verified, not inferred. I ran the exact write under strace:

    $ strace -f -e trace=rename,renameat,renameat2 -y git config worktrunk.state.foo.marker '🤖'
    rename("/tmp/gcfg/.git/config.lock", "/tmp/gcfg/.git/config") = 0
    

    One rename(2), on a file inside .git, atomic-write style. Even if the shared-$ cwd bug lands that write in the wrong repo, the worst case is <wrong-repo>/.git/config.lock → <wrong-repo>/.git/config — a file, one level deep in some repo's .git. There is no code path in which wt config state marker renames a directory, let alone $PARENT. So the missing link isn't "which repo did the storm hit" — even granting the worst mis-resolution, the syscall shape doesn't match. The 9-char child → 7-char parent-prefix truncation still has no counterpart anywhere in the binary.

    3. The one actor your timeline shows mutating $PARENT directly is the harness. At T+121 you have "$PARENT recreated (empty scaffold) by the harness's session-continuation machinery" — so OpenCode's session layer demonstrably creates/scaffolds $PARENT. wt appears only as spawns; it's never shown touching $PARENT. That's the concrete lead I'd chase next: whatever code recreated the parent at T+121 is rename/scaffold-capable against exactly that path, and a truncated-sibling-name rename is far more consistent with a "derive a workspace dir name from a repo and move into place" step than with anything git-config does. If you can grep the OpenCode session-continuation / workspace-scaffold path for rename/mkdir/mv against the parent, that's likely where the rename(2) lives.

    None of this closes it without the syscall attribution you correctly flag as missing — but the mechanism analysis makes wt an implausible source (no directory-rename exists in the path, and the correlation is non-probative), and points at the harness's own parent-scaffold machinery as the thing to instrument. The scoped-.cwd() plugin fix is still worth landing on its own merits regardless of where the rename came from.

  7. 4i3n6 commented on Jul 23, 2026

    @4i3n6
    ContributorAuthor

    Thanks for taking the time to run this down with strace — that capture settles the mechanism question better than any amount of code reading, and I appreciate you verifying it rather than just asserting it. You're right on both counts:

    • The marker-set rename is file-level, inside .git. Even in the worst mis-scoped-cwd case, the blast radius is <wrong-repo>/.git/config — there's just no path from wt config state marker to a directory rename, let alone the child-to-truncated-parent pattern I saw. My hypothesis that the storm's marker writes could explain the parent rename doesn't hold up against that.
    • Fair point on the base rate, too. With bursts landing every few seconds across the whole window, "near a burst" doesn't discriminate anything — I was reading signal into what was just density.

    Which leaves the attribution right where you pointed: the only actor my own timeline shows touching $PARENT directly is the harness's session-continuation scaffolding (T+121). I'll chase that lead on my side — grep its scaffold/workspace path for rename-capable code, and now that I have filesystem auditing on those directories, catch the author in the act if it ever recurs. If I manage to attribute the syscall, I'll file it with the right project rather than here.

    So, honestly: nothing incontrovertible against wt on the rename, and I'm glad that's where the evidence landed. Feel free to close this issue, or keep it open to track the plugin fix through release — whatever works best for you. And thanks for taking #3554; scoping the plugin's commands was worth doing either way, and I appreciate the quick approval.

    Really enjoyed this exchange, for what it's worth. Tracing a scary-sounding report down to the syscall level instead of brushing it off is exactly what makes a project trustworthy — worktrunk stays in my toolbox (I use it on my other machines, and it's going back on this one). Thanks for the chance to contribute.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions