Skip to content

feat: adopt existing worktrees with private env files (v0.4.0) - #12

Merged
EdoMon93 merged 11 commits into
mainfrom
feat/adopt-existing-worktree
Oct 19, 2026
Merged

EdoMon93 merged 11 commits into
mainfrom
feat/adopt-existing-worktree

Conversation

@EdoMon93

@EdoMon93 EdoMon93 commented Oct 19, 2026 •

Copy link
Copy Markdown
Owner

T3 Code creates linked worktrees before running project setup, so create cannot generate their per-worktree environment files. Add mkwt adopt to validate an existing linked worktree, record its caller-supplied identity in Git registration metadata, and generate a fresh private env file without changing the checkout.

Retries return already_configured only when the stored ID, recorded env path, exact generated bytes, invoking-user ownership, and mode 0600 match. Changed files, ownership, permissions, missing files, path changes, and symlink destinations fail with ENV_PATH_COLLISION; a different stored ID fails with IDENTITY_FAILED. Adoption shares removal's validation for both absolute and relative Git registrations, retains existing staged/unstaged changes, and never runs checkout hooks or creates symlinks.

Initial adoption checks path hazards and collisions before reserving an identity, so correcting those failures permits a fresh attempt. It records the intended env path before writing the file, making an interrupted complete write recognizable on retry. Partial metadata and incomplete files still require inspection. Retries check registered duplicate IDs without allocating or scanning unrelated legacy env files.

Inaccessible worktree paths are skipped during legacy scans, while their readable registration metadata continues to reserve IDs and slots. One inaccessible directory therefore does not interrupt creation, adoption, or human setup in another worktree. Unreadable legacy-only markers cannot reserve a slot until accessible again.

Unattended create and adopt reserve a numeric slot only for templates containing {n}. Other templates store slot 0, while duplicate-ID checks and identity persistence still require the caller-held repository lock. Update the README with the T3/Rails configuration, dotenv 3.x overwrite and development/test loading guidance verified against upstream docs and source, and bump the executable to 0.4.0.

Design choices differing from the original brief

  • The command is mkwt adopt instead of mkwt env, as agreed in the follow-up discussion. The name describes taking ownership of an existing registered worktree more clearly. No env alias is added; the human branch-name workflow stays available.
  • Following review, retries additionally require invoking-user ownership and mode 0600, strengthening the original ID/path/content matching condition to preserve the private-file guarantee. Ownership uses Bash's -O; mode inspection uses the standard ls utility from the base system, without requiring an additional package or language runtime.
  • Adoption records its intended env path before writing the env file, closing the interruption window identified in review. create retains its previous post-write path recording. The JSON field is still populated only after a successful initial write; retries and removal can report a previously recorded path, which alone does not imply a valid file.

There are no other departures from the brief. The JSON envelope remains schema version 1, existing stable error codes are reused, configuration is never sourced by automation, and the Bash 4.4+/Git 2.48+ requirements are unchanged.

Validation

  • bash -n bin/mkwt setup.sh tests/test_open_in_vscode_config.sh
  • bash tests/test_open_in_vscode_config.sh — all 4 checks passed.
  • python3 -m unittest discover -s tests -p test_automation.py — 75 tests: 74 passed, 1 root-only ownership fixture skipped. Running that fixture locally was blocked by the host's sudo policy; the production ownership check is present, and ordinary owner/mode success cases ran in the full suite.
  • Temporary reverted-code checks confirmed that the first-adoption alias test, human alias test, and strengthened relative-backlink human test each fail when the corresponding fixes are removed. No temporary mutations were made to the checked-out executable.

Coverage includes successful adoption, unchanged retries, byte changes including trailing newlines and NULs, changed IDs and paths, duplicate IDs on initial adoption and retries, main/unregistered/stale/locked worktrees, mismatched Git metadata, symlinked env parents, no-slot templates for both operations, and preserved legacy workflows.

Review follow-up

Each of the eight findings has a separate commit and regression coverage:

  1. 0e1008f: Preflight adoption destinations before identity persistence; recognize completed env writes after interruption.
  2. 88a9d17: Resolve relative backlinks against their registration directory for adoption and removal.
  3. d1ac730: Canonicalize identity backlink paths so registered identities are not counted again as legacy markers.
  4. e03d39b: Canonicalize listed paths before self-skips and legacy comparisons, including symlink aliases.
  5. e69c2dc: Report partial or interrupted identity writes as partial_failure, while retaining error if no mutation occurred.
  6. 3ce9982: Reject altered env-file permissions on retries without silently changing them.
  7. d778eb8: Validate retries without allocation or unrelated legacy env-file reads, while retaining registered duplicate-ID checks.
  8. 1b72b45: Keep only the absent-target fast path before shared removal validation, preserving symlink and registration error codes.

The re-review follow-up in 1c0c0b7 fixes the inaccessible-path allocation regression while preserving reserved registration identities, adds the first-adoption alias and human legacy-scan regression cases, checks env ownership, and explicitly documents the remaining parent-creation, destination-opening, and pre-open interruption recovery limits.

This PR targets main. Tagging and publishing v0.4.0 remain with the maintainer.

@EdoMon93

Copy link
Copy Markdown
Owner Author

Review of the adopt flow. I ran findings 1 and 2 against this branch and both fail as described. Findings 3 to 8 come from reading the code and weren't run.

Fix before merging

  1. bin/mkwt:533: a failed adopt leaves the worktree permanently stuck. adopt writes mkwt-identity before the env-path collision and parent checks. Repro: a linked worktree already has .env.worktree, and mkwt adopt --worktree-id abc fails with ENV_PATH_COLLISION (partial_failure). After deleting the file, the same retry fails with "stored environment path differs". Changing WORKTREE_ENV_FILE fails the same way, and so do an UNSAFE_ENV_PATH parent or a SIGTERM between the env-file write and the mkwt-env-path write. The only recovery is deleting mkwt-identity by hand. Run all env-path validation before write_worktree_identity.
  2. bin/mkwt:312: relative-path worktrees are rejected. The validation shared by adopt and remove resolves the gitdir backlink against $PWD instead of .git/worktrees/<name>/. Repro: git -c worktree.useRelativePaths=true worktree add --detach ../wt leaves ../../../../wt/.git in the gitdir file, and mkwt adopt --path wt ... returns NOT_REGISTERED. That's a Git 2.48+ feature, and mkwt already requires 2.48+.

Should fix

  1. bin/mkwt:144: false duplicate IDs for relative-path worktrees. collect_worktree_identities stores raw relative backlinks in IDENTITY_PATHS. The legacy-marker scan compares those with the absolute paths from git worktree list, so they never match, and worktrees that already have an identity are also counted as legacy ones. Result: false DUPLICATE_WORKTREE_ID errors and skipped automatic IDs.
  2. bin/mkwt:173: adopt can collide with its own ID on retry. Its self-skip in the legacy scan compares the raw listed path with the canonical A_PATH. automation_snapshot runs automation_absolute_path on the listed path first. When the registered path is a symlink alias of the physical path, a numeric --worktree-id N hits DUPLICATE_WORKTREE_ID against itself.
  3. bin/mkwt:534: an interrupted identity write is reported as error. A_ADOPT_MUTATED is set only after write_worktree_identity returns. A partial write or a signal right after it is reported as error instead of partial_failure, although mkwt-identity was left behind.
  4. bin/mkwt:256: already_configured ignores permissions. It compares bytes only. An env file changed to 0644 still counts as matching, which breaks the 0600 private-file promise.

Cleanup

  1. bin/mkwt:526: retries do unneeded allocation work. On the already_configured path, automation_allocate_identity still scans every worktree's env file and allocates a slot and an ID, then discards both. Only the duplicate-ID check is needed there.
  2. bin/mkwt:540: remove checks twice. It repeats the symlink and registration checks that automation_validate_linked_worktree already runs. Keep only the A_REGISTERED == false → already_absent branch before the shared call.

Please add a regression test for each fix.

🤖 Generated with Claude Code

@EdoMon93

Copy link
Copy Markdown
Owner Author

Re-review at 3e104c0. Findings 2, 3, 5, 7 and 8 are fixed (2, 3 and 5 confirmed by running repros against 59245f6 and 3e104c0). 69 tests pass. One regression and a few gaps remain before merge.

Regression: one registered worktree that can't be resolved breaks allocation for the whole repo. bin/mkwt:184 (create/adopt legacy scan) and :840 (compute_worktree_index) now run automation_absolute_path ... || fail on every path in git worktree list. collect_worktree_identities hits the same failure through resolve_worktree_backlink (:150). Before, those entries were skipped. Repro: give another registered worktree's directory mode 000 and set WORKTREE_ENV. mkwt feat-x then exits 1 with "cannot resolve registered worktree path" after git worktree add, leaving a worktree with no env file, identity, symlinks or hook. mkwt create returns IDENTITY_FAILED. Use || continue in these loops, as automation_snapshot (:304) already does, and add a regression test.

Test gaps

  • Finding 4 has no covering test. Undoing e03d39b leaves the suite green. test_adopt_numeric_id_retry_ignores_its_own_symlinked_registration_path runs on the retry path, which no longer does the legacy scan after d778eb8. Add a first adopt through an aliased registration path: register a/wt, move a to b, make a a symlink to b, give the target a legacy marker 3 and no env generation, then run adopt --worktree-id 3. It should be configured. It's DUPLICATE_WORKTREE_ID without the fix.
  • test_relative_identity_paths_are_respected_by_human_allocation passes against the old bin/mkwt too, because index 1 is already counted through IDENTITY_INDICES. Make it cover the compute_worktree_index path changed by findings 3 and 4.

Smaller

  • Finding 6: the mode is checked now, the owner isn't (:276-278). Add [[ -O "$target" ]].
  • Finding 1: the listed variants now recover. These still get stuck with "stored environment path differs" or "recorded environment file is missing": a parent dir that can't be created (EACCES), a destination that can't be written, and a signal between writing mkwt-env-path and opening the file. Fine as documented limits, but name them in the README's recovery section.

🤖 Generated with Claude Code

@EdoMon93
EdoMon93 merged commit e5ea3c4 into main Oct 19, 2026
2 checks passed
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