Skip to content

feat(pool): seed ignored files from .worktreeinclude - #48

Closed
nikolauska wants to merge 37 commits into
kunchenguid:mainfrom
nikolauska:feature/worktreeinclude
Closed

nikolauska wants to merge 37 commits into
kunchenguid:mainfrom
nikolauska:feature/worktreeinclude

Conversation

@nikolauska

@nikolauska nikolauska commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Add .worktreeinclude support so newly created pooled worktrees can be seeded from explicitly listed repository files while preserving Treehouse's safety guarantees across Git and Jujutsu backends. Seed only ignored files, validate and authenticate persisted seed inventories, fail closed or quarantine unsafe, corrupt, unknown, or legacy inventory state, recover cleanly from state-persistence and missing-state failures, keep reset/release/prune/destroy behavior safe, document the feature and recovery constraints, and retain Linux, macOS, and Windows compatibility.

What Changed

  • Seed ignored files selected by a committed .worktreeinclude into newly created and reused Git worktrees and Jujutsu workspaces.
  • Track authenticated seed inventories so reset and release remove only trusted seeded paths, with rooted filesystem and symlink protections across platforms.
  • Quarantine worktrees when seeding or state persistence is unsafe, and recover missing, corrupt, legacy, or unauthenticated state without allowing silent reuse.

Risk Assessment

⚠️ Medium: The change is broad and touches destructive cross-platform worktree lifecycle paths, but the reviewed code now consistently fails closed and no remaining concrete defect was substantiated.

Testing

Focused Git, Jujutsu, pool-state, quarantine, recovery, persistence-failure, symlink-safety, and Windows compilation checks passed; the saved end-to-end CLI transcript demonstrates selected ignored-file seeding and refresh on reuse.

Evidence: CLI seeding and reuse transcript
=== first acquire ===
A new version of treehouse is available: v1.8.1-0.20260822164524-fa1052c977a0 → v2.2.1
Run "treehouse update" to update

🌳 Setting up worktree...
🌳 Leased worktree at ~/.no-mistakes/worktrees/0748481d5e3b/01M0N3RZQK5T81R0A3RQEKTWGA/.tmp-cli-seed-e2e-01M0N3RZ/pool/.treehouse/repo-88ce0d/1/repo. Run 'treehouse return ~/.no-mistakes/worktrees/0748481d5e3b/01M0N3RZQK5T81R0A3RQEKTWGA/.tmp-cli-seed-e2e-01M0N3RZ/pool/.treehouse/repo-88ce0d/1/repo' to release it.
{"path":"/home/nlehto/.no-mistakes/worktrees/0748481d5e3b/01M0N3RZQK5T81R0A3RQEKTWGA/.tmp-cli-seed-e2e-01M0N3RZ/pool/.treehouse/repo-88ce0d/1/repo","lease_id":"68ea603f511b5a3e92b51f3381a8736c","lease_holder":"","leased_at":"2026-08-22T19:48:23.849943984+03:00"}
seeded .env: API_TOKEN=first
non-selected ignored file present: no
A new version of treehouse is available: v1.8.1-0.20260822164524-fa1052c977a0 → v2.2.1
Run "treehouse update" to update

🌳 Worktree returned to pool.

=== reuse after source refresh ===
A new version of treehouse is available: v1.8.1-0.20260822164524-fa1052c977a0 → v2.2.1
Run "treehouse update" to update

🌳 Setting up worktree...
🌳 Leased worktree at ~/.no-mistakes/worktrees/0748481d5e3b/01M0N3RZQK5T81R0A3RQEKTWGA/.tmp-cli-seed-e2e-01M0N3RZ/pool/.treehouse/repo-88ce0d/1/repo. Run 'treehouse return ~/.no-mistakes/worktrees/0748481d5e3b/01M0N3RZQK5T81R0A3RQEKTWGA/.tmp-cli-seed-e2e-01M0N3RZ/pool/.treehouse/repo-88ce0d/1/repo' to release it.
{"path":"/home/nlehto/.no-mistakes/worktrees/0748481d5e3b/01M0N3RZQK5T81R0A3RQEKTWGA/.tmp-cli-seed-e2e-01M0N3RZ/pool/.treehouse/repo-88ce0d/1/repo","lease_id":"a2770b7370c6d70f79808fb5e44f60e9","lease_holder":"","leased_at":"2026-08-22T19:48:23.980056034+03:00"}
same pooled worktree reused: yes
refreshed .env: API_TOKEN=refreshed
non-selected ignored file present: no
A new version of treehouse is available: v1.8.1-0.20260822164524-fa1052c977a0 → v2.2.1
Run "treehouse update" to update

🌳 Worktree returned to pool.

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 1 issue found → auto-fixed (9) ✅
  • 🚨 internal/vcs/jjvcs/jjvcs.go:334 - Intent requires safety “across Git and Jujutsu backends,” but a seeded jj workspace cannot be released or reused. ResetWorktreeWithSeededPaths resets the workspace and then calls gitvcs.RemoveSeededPaths; that helper requires a regular .git marker and backlink, while pooled jj workspaces are .jj-only. Sequence: acquire a jj workspace with one selected ignored file → call return or reacquire it → cleanup returns “refusing to clean unregistered worktree” → the seed remains and the workspace stays unavailable. Add backend-aware cleanup authentication at the shared cleanup boundary, validating jj’s .jj/repo pointer for jj workspaces, and cover a successful seeded jj reset/release (current tests cover only cleanup after reset failures).

🔧 Fix: Authenticate Jujutsu workspaces during seeded cleanup
1 error still open:

  • 🚨 internal/vcs/gitvcs/gitvcs.go:789 - The required safety guarantee “across Git and Jujutsu backends” remains incomplete. authenticateJJWorkspace accepts any directory containing a regular .jj/repo pointer to an existing store; unlike Git cleanup, it never proves that the marker belongs to this managed path. Sequence: replace a managed jj workspace before return with another directory containing a copied .jj marker and a user file whose name is in the signed seed inventory → jj reset can recognize the copied workspace metadata → this guard succeeds → cleanup silently deletes that user file. Authenticate the workspace against its expected registration/identity at the earliest cleanup boundary, and add the jj equivalent of the existing unregistered-replacement test.

🔧 Fix: Bind Jujutsu cleanup to original workspace identity
2 errors still open:

  • 🚨 internal/vcs/gitvcs/gitvcs.go:764 - The required “safety guarantees across Git and Jujutsu backends” are violated because this unconditionally deletes an adjacent path that was never authenticated as Treehouse-owned. Sequence: a file already exists at <workspace>.treehouse-jj-seed-auth → destroying any jj workspace calls RemoveWorktree → the workspace is removed and this function silently deletes that unrelated file. Create authentication state in a collision-safe managed location and remove it only after verifying its identity/ownership.
  • 🚨 internal/vcs/jjvcs/jjvcs.go:202 - The requirement to “fail closed or quarantine unsafe” state is contradicted because a failed authentication-sidecar creation discards the partial seed inventory. Sequence: seeding copies one or more files → PrepareJJSeededCleanup fails (for example, the sidecar path already exists) → this returns nil, err → if worktree removal also fails, pool quarantine records a verified empty inventory → a later return can release the workspace without deleting the copied ignored files. Return seeded, err so quarantine preserves every path already copied.

🔧 Fix: Secure Jujutsu authentication state and preserve inventory
1 warning still open:

  • ⚠️ internal/vcs/jjvcs/jjvcs.go:288 - A seeded jj workspace deleted outside Treehouse leaves its hard-linked authentication file behind. The next get self-heals the stale workspace registration and recreates the workspace at the same path, but PrepareJJSeededCleanup rejects the stale authentication link; cleanup then reaches this call, which also rejects it because it does not match the new .jj/repo, leaving the recreated workspace quarantined and the slot unusable. Handle authentication state for an already-missing workspace at the managed cleanup boundary so stale state cannot block safe path reuse.

🔧 Fix: Clean authenticated stale Jujutsu state before recreation
1 error still open:

  • 🚨 internal/vcs/gitvcs/gitvcs.go:821 - The required criterion to preserve “safety guarantees across Git and Jujutsu backends” is still contradicted by return os.Remove(authPath): ownership is inferred only from attacker-controlled file contents. Sequence: while the workspace path is absent, create the predictable auth file as an ordinary user file containing this repository’s valid jj store path → AddWorktree calls this helper → every check succeeds → Treehouse silently deletes the unrelated file. The new wrong-store test misses this same-store forgery. Authenticate stale state using signed pool-owned metadata at the managed pool boundary before deleting it; otherwise fail closed.

🔧 Fix: Authorize stale Jujutsu cleanup with signed state
1 error still open:

  • 🚨 internal/pool/pool.go:629 - The required “recover cleanly from ... missing-state failures” behavior remains broken because stale jj authentication is cleaned only at the start of acquire. Concrete sequence: a seeded jj workspace is deleted externally → status, prune, or destroy calls healState and persists the state without the missing entry (or return clears its signed inventory) → the authentication hard link remains but its signed authorization is lost → the next get recreates the same path, seeding collides with the stale link, and removal refuses the mismatched new workspace, leaving the slot quarantined. Move authenticated stale cleanup to the shared boundary before every operation that discards a missing entry or its inventory; otherwise preserve the signed entry until cleanup succeeds.

🔧 Fix: Consume stale authorization before healing state
1 error still open:

  • 🚨 internal/pool/pool.go:654 - The required safety guarantee is violated because signed seed inventory authenticates the worktree entry, not the file being deleted. Concrete path: a seeded Git worktree is deleted externally, and an unrelated regular file exists at its predictable .treehouse-jj-seed-auth/<digest> path → healState cannot determine the missing worktree’s backend and calls this helper for every signed non-empty inventory → RemoveStaleJJSeedAuthentication deletes that file solely because it is regular. The same replacement is possible for a jj auth hard link after workspace deletion. Persist authenticated auth-file identity/backend metadata and verify it before deletion; otherwise fail closed. The new test currently codifies the unsafe result by replacing the auth link with forged user data and then expecting List to delete it.

🔧 Fix: Authenticate stale Jujutsu files by signed identity
1 error still open:

  • 🚨 internal/vcs/gitvcs/gitvcs.go:817 - The required “safety guarantees across Git and Jujutsu backends” remain vulnerable to a pathname race. RemoveStaleJJSeedAuthentication verifies the file’s identity, checks that the workspace is absent, and then deletes by pathname; a concurrent process can replace the authentication path after verification, causing os.Remove(authPath) to delete the replacement without error. RemoveJJSeedAuthentication has the same check-then-remove sequence for live workspaces. Move and verify the exact file through a pinned directory handle or otherwise make identity verification and removal one safe operation; add a regression that swaps the path between verification and deletion.

🔧 Fix: Quarantine authentication files before verified deletion
1 error still open:

  • 🚨 internal/vcs/gitvcs/gitvcs.go:738 - The required “safety guarantees across Git and Jujutsu backends” remain violated on the normal reset/release path. RemoveSeededPathsFromJJWorkspace authenticates and removes the seeded files, then deletes the authentication pathname directly. Sequence: another local process replaces that authentication path after authentication but before line 738 → os.Remove silently deletes the replacement. The new quarantine logic covers destroy and stale cleanup only. Route this deletion through RemoveJJSeedAuthentication (or the same quarantine-and-verify boundary) and cover the reset/release path with the concurrent-replacement regression.

🔧 Fix: Quarantine release authentication before deletion
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • go test ./internal/pool -run 'Test(Acquire.*(Seed|StateWrite|Quarantine)|Release.*(Seed|Quarantine|Recovered)|ReadState_.*(Inventory|Integrity|Recovered)|StaleJJAuthentication|AcquireDoesNotExecuteSeedFilter|AcquireIgnoresBrokenRequiredSeedFilter)' -count=1
  • go test ./internal/vcs/gitvcs -run 'Test(Seed|ResetWorktree.*Seed|EmptySeedInventory|RemoveSeeded|PrepareJJSeeded|RemoveJJSeed|RemoveStaleJJSeed)' -count=1
  • go test ./internal/vcs/jjvcs -run 'Test(Seed|ResetWorktree.*Seed)' -count=1
  • Built the CLI and exercised treehouse get --lease --json --no-fetch plus treehouse return --force across initial creation and reuse in an isolated Git repository.
  • GOOS=windows GOARCH=amd64 go test -c for ./internal/pool, ./internal/vcs/gitvcs, and ./internal/vcs/jjvcs.
  • Verified git status --short was clean after removing transient test artifacts.
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@mbrookson mbrookson left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nice implementation — using git ls-files + check-ignore for pattern matching is the right call over rolling our own glob expansion. A few observations from independently building the same feature (closed #50 in favour of this):

Seeding runs inside the state lock

Both call sites invoke SeedWorktree inside the WithStateLock closure, which means the flock is held for the duration of the file copies. For repos with large ignored files this could block concurrent treehouse commands unnecessarily. The post-create hooks already run after the lock is released — seeding feels like it belongs there too, since it's not mutating pool state. Something like:

// after WithStateLock returns, before hooks.Run
if err := git.SeedWorktree(repoRoot, acquired); err != nil {
    fmt.Fprintf(os.Stderr, "warning: .worktreeinclude: %v\n", err)
}

(Whether to warn or hard-fail is a separate question — see below.)

excludedIncludeSubtree only handles !dir/ negations, not !file

The custom parser skips lines matching !<dir>/ but a bare negation like !.env.local won't be excluded. Given the function comment says "Git does not descend into an excluded directory", I think this is intentional — but it's worth a doc comment clarifying that file-level negations aren't supported so users don't write !secrets/prod.json and wonder why it still gets copied.

Seed errors abort acquire for the missing-file case

If .worktreeinclude lists .env but a contributor doesn't have that file locally (common on a fresh clone), git ls-files returns nothing for it and the seed silently skips it — so this is actually fine in practice. The error path that would bite is an OS-level failure mid-copy. Current behaviour (abort acquire) is defensible, though a warning-and-continue would be more resilient. Worth a deliberate decision either way.

@nikolauska

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I moved seeding outside the state lock and changed OS-level copy failures to warn without failing the acquire. I also clarified that Git handles file-level negations directly and added coverage for !.env.local.

@nikolauska
nikolauska force-pushed the feature/worktreeinclude branch from f7b2fe2 to 4f7b2a7 Compare July 7, 2026 18:13
@kunchenguid

kunchenguid commented Jul 20, 2026 •

Copy link
Copy Markdown
Owner

Automated reminder: thanks for the PR! This branch currently has a merge conflict with the base branch.

When you get a chance, please rebase onto (or merge) the latest base branch, resolve the conflict, and push. After that, checks will re-run and the PR will get looked at again.

Noted for treehouse#48 at 2bdbbfe7.

@nikolauska
nikolauska force-pushed the feature/worktreeinclude branch from 2bdbbfe to c650ff6 Compare July 20, 2026 21:08
@nikolauska

nikolauska commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Rebased onto the latest main and fixed several issues found during review of .worktreeinclude seeding:

  • Symlink safety: Reused worktrees preserve ignored files. If a seeded destination had been replaced with a symlink, the next acquire could follow it and overwrite a file outside the worktree. Seeding now rejects paths containing symlinks.
  • Tracked-file protection: Seed candidates were selected using the source checkout’s index. When the acquired worktree targeted a different branch, a candidate could be tracked there and get overwritten. Candidates are now checked against the acquired worktree’s index first.
  • Pattern precedence: A directory negation such as !local/archive/ permanently excluded that subtree, even when a later pattern explicitly included a file within it. Later matching patterns now take precedence as expected.
  • Manifest handling: .worktreeinclude was checked and then read separately. It is now read once, removing the redundant filesystem operation.

@kunchenguid kunchenguid removed the wheelhouse:pending-contributor-action Managed by Wheelhouse label Jul 20, 2026
@mbrookson

Copy link
Copy Markdown

@kunchenguid can this be added to the next release? 🙏

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: this branch currently has a merge conflict with main (mergeable_state: dirty). Please rebase onto latest main, resolve, and push so CI can re-run. The .worktreeinclude seeding is opt-in (missing manifest is a no-op) so I am not closing it; I will not merge until it is conflict-free and CI is green on current main.

@nikolauska
nikolauska force-pushed the feature/worktreeinclude branch from eacd8c8 to 7f6df41 Compare August 19, 2026 19:44
@greptile-apps

greptile-apps Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Reviews (45): Last reviewed commit: "no-mistakes(review): Quarantine release ..." | Re-trigger Greptile

Comment thread internal/git/git.go Resolved
Comment thread internal/git/git.go Resolved
@nikolauska
nikolauska force-pushed the feature/worktreeinclude branch 2 times, most recently from f2cc1b9 to a1a6e95 Compare August 19, 2026 21:49
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks for the rebase. This is now mergeable (not dirty). I approved fork CI for a1a6e953. Greptile is 5/5 on that SHA.

no-mistakes is red: "This PR was not raised through no-mistakes." Contributions need git push no-mistakes so the body gets the ## Pipeline section. That is blocking here (#51 is the only known pre-requirement exception). I will not merge until that gate is green. OS tests are still running.

@nikolauska nikolauska changed the title feat(pool): Add .worktreeinclude support feat(pool): seed gitignored files into pooled worktrees Aug 20, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: newer activity is the no-mistakes raise (Pipeline section is now on the body) plus Greptile still 5/5 on 573e7c6. Opt-in .worktreeinclude remains in scope.

VISION (per rule):

  • Isolation and reuse: aligns if seeding does not change ownership or recycle a dirty/in-use slot.
  • Safe lifecycle operations: aligns only if destinations stay inside the worktree (symlink-safe) and tracked files are not overwritten.
  • Ownership and interface: aligns as opt-in manifest; missing file is a no-op.
  • Scope and evaluation: aligns as optional local seeding, not a Git workflow manager. Repository-controlled code must not execute automatically; this copies files, it does not run them.

Approved current-head CI 32408269816 and no-mistakes 32408269766. Not merging until those runs are actually green. Helping this PR; not opening a second path for #39.

@nikolauska nikolauska changed the title feat(pool): seed gitignored files into pooled worktrees feat(git): seed ignored files into acquired worktrees Aug 20, 2026
Comment thread internal/git/git.go Resolved
Comment thread internal/pool/pool.go Resolved
Comment thread internal/pool/pool.go Resolved
Comment thread internal/git/git.go Resolved
Comment thread internal/pool/pool.go Resolved
Comment thread internal/git/git.go Resolved
Comment thread internal/pool/pool.go Resolved
Comment thread internal/git/git.go Resolved
Comment thread internal/git/git.go Resolved
Comment thread internal/git/git.go Resolved
@nikolauska
nikolauska force-pushed the feature/worktreeinclude branch from 2821c7d to bbe58c4 Compare August 20, 2026 22:37
Comment thread internal/git/git.go Resolved
@greptile-apps

greptile-apps Bot commented Aug 20, 2026

Copy link
Copy Markdown

Want your agent to iterate on Greptile's feedback? Try greploops.

@nikolauska
nikolauska force-pushed the feature/worktreeinclude branch from bbe58c4 to 52e6b80 Compare August 20, 2026 22:45
@nikolauska
nikolauska force-pushed the feature/worktreeinclude branch from 4875fc3 to c2c9479 Compare August 22, 2026 15:54
@nikolauska nikolauska changed the title feat(pool): seed ignored files into worktrees feat(pool): add .worktreeinclude seeding Aug 22, 2026
@nikolauska nikolauska changed the title feat(pool): add .worktreeinclude seeding feat(pool): seed ignored files from .worktreeinclude Aug 22, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: newer head fa1052c (title now .worktreeinclude; many review commits since 4875fc3). I reviewed the new files (no .github/workflows). Greptile Review is success on this SHA. I approved fork CI 32585895091 and Require no-mistakes 32585895088 / 32585922517. Not merging until those runs are actually green.

Inspected on this SHA:

  • HMAC inventory now binds name, cleaned path, backend, and jj SeedAuthIdentity (validSeedMetadata / seedInventoryDigest in internal/pool/state.go). Bad digest clears inventory instead of trusting it.
  • jj seed: SeedWorktree copies via the git store then PrepareJJSeededCleanup; a prepare failure returns the already-copied seeded list so quarantine can keep them.
  • jj reset/release: AuthenticateJJSeededCleanup before reset; RemoveSeededPathsFromJJWorkspace after; RemoveJJSeedAuthentication before workspace delete.

VISION (per rule):

  • Isolation and reuse: aligns in intent. Untrusted or unsigned inventories still fail closed. Seeded jj workspaces are authenticated before cleanup rather than treated as ordinary git worktrees.
  • Safe lifecycle operations: cannot tell fully until CI is green. The new jj auth helpers are fail-closed on the paths I read; green matrix is still the proof.
  • Ownership and interface: aligns as opt-in .worktreeinclude; missing manifest stays a no-op.
  • Scope and evaluation: aligns as optional local file copy. The key is pool-local integrity, not a remote secret. No repo-controlled code execution.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: stale-restamp pass. This is not a 14-day author close — last author push was 2026-08-22, and the last triage stamp was waiting-ci (CI later went green on fa1052c). Main has since moved (~7 commits); the PR is now CONFLICTING/DIRTY. Feature is still absent on latest main; #39 remains open. Per charter, merge conflicts on an otherwise auto-merge-ready opt-in PR are ours to resolve on the existing branch (maintainer-can-modify). Not waiting on you.

contract-class: opt-in (missing .worktreeinclude stays a no-op; unconfigured acquire path unchanged).

VISION (per rule, pre-resolve):

  • Isolation and reuse: aligns in intent — seed inventories + quarantine on untrusted/incomplete state; must not silently recycle dirty/leased slots. Will re-verify after rebase onto current main (incl. feat(pool): support configurable base branch for get #119 base branch / feat(pool): add lease command to durably lease an existing worktree #128 lease).
  • Safe lifecycle operations: aligns in intent on the Aug 22 head (rooted copies, HMAC inventory, jj auth before cleanup). Inconclusive against current main until conflicts are resolved and CI is green again.
  • Ownership and interface: aligns — opt-in manifest; warnings/diagnostics separate from machine output.
  • Scope and evaluation: aligns — optional local file copy, not a Git workflow manager; no repo-controlled code execution.

Resolving conflicts now; will re-approve fork CI and continue toward merge only if still opt-in + green + safe Greptile.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: closing in favor of last-resort port #129, which just landed on main as 0e87c62b. Thank you @nikolauska — really appreciate you taking the time on the original implementation and the extensive safety review. The fork branch could not be updated with current main (workflow files), so we ported your work rather than leave it conflicted.

@kunchenguid kunchenguid closed this Sep 5, 2026
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.

3 participants