Skip to content

fix(pool): reuse a pooled worktree only for the clone that owns it - #145

Merged
kunchenguid merged 6 commits into
kunchenguid:mainfrom
MrGTV-love:fm/treehouse-pool-clone-identity-clean
Sep 23, 2026
Merged

kunchenguid merged 6 commits into
kunchenguid:mainfrom
MrGTV-love:fm/treehouse-pool-clone-identity-clean

Conversation

@MrGTV-love

@MrGTV-love MrGTV-love commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Intent

The captain commissioned an investigation into why git operations were costing the recovery workstream so much time. It proved two separate root causes, and on 2026-09-21 he ruled: "Both corrections - recommended. Stable retry placement in Vernant and clone-correct reuse in Treehouse."

You are the Treehouse half. The Vernant half is a different repository and is already in flight; it is not yours.

THE PROBLEM, PROVED. Two distinct local clones of the same remote project share one worktree pool, and the pool hands one clone a slot that belongs to the other. The receiving clone's tooling then correctly refuses to trust it, and that lane's work stops. This is deterministic sharing, not a rare hash collision.

THE NAMED WRONG DECISIONS, each read from source and reproduced with the real Treehouse binary:

  1. internal/config/config.go:119-136 resolves the pool root by hashing the ORIGIN URL, not the physical clone. Two clones with the same origin and basename therefore resolve to the same pool by design.
  2. internal/pool/pool.go:152-209 - acquire() selects a candidate slot by backend, lease and process activity, dirt, and safe-reset state. It never compares the candidate slot's Git common directory to the requesting repository's. The decisive reuse is ResetWorktreeToRef at :191 and acquired = leaseInfoFromEntry(...) at :197.
  3. A returned slot stays registered to its original clone's Git common directory, internal/pool/pool.go:335-370, and fetching the new caller at :126-129 cannot reassign an already-existing worktree linked to the other clone.

The investigation reproduced this with two throwaway clones of one local origin using the actual Treehouse shell path: clone B received the identical path clone A had just returned, and Git still identified that worktree as A's. Three controls passed and are the counterexamples that bound the defect: A reusing its own slot works; separate pool roots for A and B work; and one shared pool with no idle foreign slot allocates correctly.

WHAT IS EXPLICITLY NOT THE FIX. The investigation examined and rejected relaxing the consuming tool's trust check. That check is correctly protecting a real difference: equal origin URL does not make two clones' refs, hooks, clone-local configuration or ownership claims identical. A separate task that took that approach has been stood down on the captain's word. Do not weaken any trust or identity check to make this pass.

HIS CONSTRAINTS. Robustness, quality and accuracy far above speed. No broker, clone registry, allocation wrapper, policy layer or custom verifier - the investigation hard-filtered those, because standard Git identity already answers the question being asked. Correct the wrong decision; do not build machinery around it.

Substance of the selected Treehouse recommendation in that report: reuse an available slot only when its physical Git common directory matches the requesting clone; otherwise skip that slot and use/create one belonging to the caller. Keep the existing shared pool directory, state format, old slots, leases, and trust checks. Place the eligibility condition in the existing allocator before candidate reset or acquisition. Use the existing vcs.CommonGitDir operation with standard physical-path normalization, compute the requester identity once, and leave different or unresolvable candidates intact for their owning clone. The interface has a colocated-JJ implementation, which needs corresponding regression coverage. The existing shared max_trees limit still applies: exhaustion must be explicit rather than allowing a foreign slot or destroying it. Do not re-key pools by clone, rename or migrate them, add machinery, or weaken downstream trust equality.

The report's acceptance for this correction: same-clone reuse remains possible, different clones never exchange slots, and symlink aliases of the same physical clone do not split identity. Dirty, locked/leased, in-use, and unlanded slots remain protected; capacity exhaustion is reported without removal or cross-clone reuse. Both ordinary and durable acquisition traverse the corrected selector, and return still finds recorded existing slots. Port the real two-clone shared-origin regression into Treehouse's native pool tests. No Vernant changes or retained-worktree cleanup belong to this correction.

What Changed

  • acquire in internal/pool/pool.go now checks which clone owns a slot before it resets or hands the slot out. It gets the requesting clone's physical, symlink-resolved vcs.CommonGitDir once, through the new acquisitionCommonGitDir. It then compares that value with each candidate slot's value. A slot from another clone is skipped and left as it is. A slot is also skipped when its identity cannot be read, or when the requester's own identity cannot be read. Non-colocated jj workspaces are in this group because they have no Git common directory. A new slot can still be created up to max_trees. When the pool is full, the error counts the foreign slots and the unverifiable slots. Ordinary and durable (--lease) acquisition both go through this check. The pool key, the state format, leases, and the downstream trust checks do not change.

  • New regression tests. internal/pool/pool_test.go builds two real clones of one shared origin and tests these cases:

    • A clone can reuse its own slot. A slot from the other clone is never swapped in.
    • A full pool gives an explicit error. It does not remove or reuse the other clone's slot.
    • A symlinked path to the same clone counts as that clone.
    • A candidate slot with an unreadable identity is skipped.
    • return still finds existing recorded slots.

    The new internal/pool/clone_identity_jj_test.go covers jj. Colocated jj clones are told apart correctly, and a colocated slot whose identity cannot be resolved is skipped. A non-colocated jj repository never reuses a workspace, including a workspace from a second clone.

  • README now lists clone-correct reuse as a feature and updates the acquire flow diagram. The AGENTS.md acquire rule now describes the ownership check.

Risk Assessment

✅ Low: The change is one narrow eligibility check in the existing allocator. It runs before any reset. Both identities are normalized through filepath.Abs and EvalSymlinks. It fails closed when an identity cannot be read. The fix round did what the user decided: it removed the empty-identity mode, it counts unverifiable candidates in the capacity error, and it still allows fresh allocation. The tests cover same-clone reuse, cross-clone refusal, capacity without removal, symlink aliases, colocated jj, and return of existing slots.

Testing

I drove the real treehouse CLI against two throwaway clones of one local origin that share one pool. The base binary reproduces the reported cross-clone slot exchange. The fixed binary does not exchange slots. It also keeps these working: reuse by the same clone, reuse through a symlink alias, ordinary get, durable get, and return by name. Dirty, unlanded, in-use, leased, and broken-pointer slots stay protected. A full pool fails with an explicit message and removes nothing. The new Git regression tests pass, and they fail when run against the old allocator. The regression-test check is unit-level, so it is recorded as untested live. The colocated-jj cases could not run because jj is not installed on this host, so those tests skip. All scenarios I could drive live passed.

  • Live validation: ✅ go - 12 of 14 scenarios driven live against the product
Scenario Result Live Evidence
Two clones share one origin and one pool. A returns its slot, then B runs get --lease. B must NOT receive A's slot. On the base binary it does. ✅ pass live 01-baseline-bug-repro.txt (base: B got slot 1, owned by a/proj/.git) vs 02-fixed-shared-pool-scenarios.txt (fixed: B got slot 2, owned by b/proj/.git; slot 1 is still A's)
Same-clone reuse: A runs get --lease again and receives its own returned slot ✅ pass live 02-fixed-shared-pool-scenarios.txt S2
A symlink alias of clone A (a-alias/proj, under /tmp → /private/tmp) reuses A's slot, so identity does not split ✅ pass live 02-fixed-shared-pool-scenarios.txt S3
B reuses its own returned slot in the shared pool ✅ pass live 02-fixed-shared-pool-scenarios.txt S4
Ordinary (subshell) get also uses the corrected selector: B's shell lands in B's own slot, and A reuses A's slot ✅ pass live 03-fixed-ordinary-get-return-capacity.txt S6/S6b
return <name> still finds the recorded existing slot ✅ pass live 03-fixed-ordinary-get-return-capacity.txt S7
Capacity: a third clone C with max_trees=2 and both slots foreign gets an explicit 'belong to another clone' error (exit 1) from get --lease, get --lease --json and ordinary get. No slot is removed or… ✅ pass live 03-fixed-ordinary-get-return-capacity.txt S9/S9b/S9c
The clone's own slot is dirty (an untracked file). get skips it and keeps the file. ✅ pass live 04-fixed-protections.txt S10
The clone's own slot has an unlanded commit. get skips it and keeps the commit. ✅ pass live 04-fixed-protections.txt S11
The clone's own slot has a live process inside. get skips it. ✅ pass live 04-fixed-protections.txt S12
A leased slot is never handed to either clone ✅ pass live 04-fixed-protections.txt S13
A slot whose clone identity cannot be read (broken .git pointer), with max_trees=1: get is refused with an explicit 'cannot be verified' message, and the slot stays on disk ✅ pass live 05-fixed-unverifiable-slot.txt S14
The new Git regression tests fail before the fix and pass after it ⏸️ untested no The prior payload did not establish a live result for this scenario. It was checked only with Go unit tests (logs 06-go-targeted-tests.txt and 07-regression-test-fails-on-base-allocator.txt), not agai…
Colocated-jj clones: same-clone reuse works, a different colocated-jj clone is refused, and non-colocated jj reuse is refused ⏸️ untested no The jj binary is not on PATH on this host. The jj tests skip, and the CLI jj backend cannot be driven. To run it, install jj (for example brew install jj) and re-run `go test ./internal/pool/ -run…
Evidence: Baseline binary reproduces the bug: B receives A's returned slot, still owned by A
######## binary: treehouse-base ########
== S1 cross-clone: A get --lease, A return, B get --lease
A got:  /tmp/th-live.VQAD/w-base/home/.treehouse/proj-a679b8/1/proj  owner=/private/tmp/th-live.VQAD/w-base/a/proj/.git
A return exit=0
B got:  /tmp/th-live.VQAD/w-base/home/.treehouse/proj-a679b8/1/proj  exit=0  owner=/private/tmp/th-live.VQAD/w-base/a/proj/.git
RESULT S1: FAIL - B RECEIVED A's SLOT

== S2 same-clone reuse: A get --lease again
A got:  /tmp/th-live.VQAD/w-base/home/.treehouse/proj-a679b8/1/proj
RESULT S2: A reused its own slot

== S3 symlink alias of A (cd /tmp/th-live.VQAD/w-base/a-alias/proj): get --lease
pwd=/tmp/th-live.VQAD/w-base/a-alias/proj
alias got: /tmp/th-live.VQAD/w-base/home/.treehouse/proj-a679b8/1/proj
RESULT S3: alias reused A's slot (identity not split)

== S4 B reuses its OWN returned slot
B got: /tmp/th-live.VQAD/w-base/home/.treehouse/proj-a679b8/1/proj
RESULT S4: B reused its own slot

== S5 status after returns
base  main  (repository default)
1     available    ~/.treehouse/proj-a679b8/1/proj  (detached)
Evidence: Fixed binary: no cross-clone exchange; same-clone, symlink-alias and B own-slot reuse
######## binary: treehouse-new ########
== S1 cross-clone: A get --lease, A return, B get --lease
A got:  /tmp/th-live.VQAD/w-new/home/.treehouse/proj-3c2cc3/1/proj  owner=/private/tmp/th-live.VQAD/w-new/a/proj/.git
A return exit=0
B got:  /tmp/th-live.VQAD/w-new/home/.treehouse/proj-3c2cc3/2/proj  exit=0  owner=/private/tmp/th-live.VQAD/w-new/b/proj/.git
RESULT S1: B got a different slot; A's slot owner still /private/tmp/th-live.VQAD/w-new/a/proj/.git

== S2 same-clone reuse: A get --lease again
A got:  /tmp/th-live.VQAD/w-new/home/.treehouse/proj-3c2cc3/1/proj
RESULT S2: A reused its own slot

== S3 symlink alias of A (cd /tmp/th-live.VQAD/w-new/a-alias/proj): get --lease
pwd=/tmp/th-live.VQAD/w-new/a-alias/proj
alias got: /tmp/th-live.VQAD/w-new/home/.treehouse/proj-3c2cc3/1/proj
RESULT S3: alias reused A's slot (identity not split)

== S4 B reuses its OWN returned slot
B got: /tmp/th-live.VQAD/w-new/home/.treehouse/proj-3c2cc3/2/proj
RESULT S4: B reused its own slot

== S5 status after returns
base  main  (repository default)
1     available    ~/.treehouse/proj-3c2cc3/1/proj  (detached)
2     available    ~/.treehouse/proj-3c2cc3/2/proj  (detached)
Evidence: Fixed binary: ordinary get, return by name, capacity refusal for get/--lease/--json
######## binary: treehouse-new ########
== S6 ordinary (interactive-shell) get: A then B, via SHELL=/bin/sh with scripted stdin
A's ordinary get shell cwd: /private/tmp/th-live.VQAD/w2-new/home/.treehouse/proj-29bede/1/proj  exit=0
B's ordinary get shell cwd: /private/tmp/th-live.VQAD/w2-new/home/.treehouse/proj-29bede/2/proj
   owner of B's cwd: /private/tmp/th-live.VQAD/w2-new/b/proj/.git
RESULT S6: ordinary get gave B its own slot
A ordinary get again: /private/tmp/th-live.VQAD/w2-new/home/.treehouse/proj-29bede/1/proj
RESULT S6b: A ordinary get reused own slot

== S7 return by NAME from B's clone (slot 2 belongs to B)
B leased /tmp/th-live.VQAD/w2-new/home/.treehouse/proj-29bede/2/proj
🌳 Worktree returned to pool.
return 2 exit=0
base  main  (repository default)
1     available    ~/.treehouse/proj-29bede/1/proj  (detached)
2     available    ~/.treehouse/proj-29bede/2/proj  (detached)

== S8 A's own DIRTY returned slot is not reused; A leases slot 1, dirties it, returns? (return discards) -> instead: lease, dirty, then B & A get
base  main  (repository default)
1     available    ~/.treehouse/proj-29bede/1/proj  (detached)
2     available    ~/.treehouse/proj-29bede/2/proj  (detached)

== S9 capacity: max_trees=2, both slots belong to others' clones; C (3rd clone) get
🌳 Setting up worktree...
all 2 worktrees are in use, dirty, or not provably this clone's (2 belong to another clone; 0 whose clone identity cannot be verified; max_trees = 2). A worktree is reused only by the clone it belongs to. Run 'treehouse status' to see details, or increase max_trees in treehouse.toml
C get exit=1
   slots after refusal:
   /tmp/th-live.VQAD/w2-new/home/.treehouse/proj-29bede/1/proj exists=yes owner=/private/tmp/th-live.VQAD/w2-new/a/proj/.git
   /tmp/th-live.VQAD/w2-new/home/.treehouse/proj-29bede/2/proj exists=yes owner=/private/tmp/th-live.VQAD/w2-new/b/proj/.git
base  main  (repository default)
1     available    ~/.treehouse/proj-29bede/1/proj  (detached)
2     available    ~/.treehouse/proj-29bede/2/proj  (detached)
== S9b get --lease --json also refused
🌳 Setting up worktree...
all 2 worktrees are in use, dirty, or not provably this clone's (2 belong to another clone; 0 whose clone identity cannot be verified; max_trees = 2). A worktree is reused only by the clone it belongs to. Run 'treehouse status' to see details, or increase max_trees in treehouse.toml
exit=1
== S9c ordinary get also refused
🌳 Setting up worktree...
all 2 worktrees are in use, dirty, or not provably this clone's (2 belong to another clone; 0 whose clone identity cannot be verified; max_trees = 2). A worktree is reused only by the clone it belongs to. Run 'treehouse status' to see details, or increase max_trees in treehouse.toml
exit=1
Evidence: Fixed binary: dirty/unlanded/in-use/leased slots stay protected
######## binary: treehouse-new ########
A's slot: /tmp/th-live.VQAD/w3-new/home/.treehouse/proj-276055/1/proj (returned, available)

== S10 A's own slot made DIRTY (untracked file) -> A get must not reuse it
A got /tmp/th-live.VQAD/w3-new/home/.treehouse/proj-276055/2/proj
RESULT S10: dirty slot skipped, work.txt preserved

== S11 A's own slot has an UNLANDED commit -> A get must not reuse it
A got /tmp/th-live.VQAD/w3-new/home/.treehouse/proj-276055/2/proj
RESULT S11: unlanded slot skipped, commit 0adb104c97fda5eac6dea4d89a8b3444cfbb2879 kept

== S12 A's own slot IN USE (process running inside) -> A get must not reuse it
A got /tmp/th-live.VQAD/w3-new/home/.treehouse/proj-276055/2/proj
RESULT S12: in-use slot skipped

== S13 A's slot LEASED -> neither A nor B gets it
A leased /tmp/th-live.VQAD/w3-new/home/.treehouse/proj-276055/1/proj
A got /tmp/th-live.VQAD/w3-new/home/.treehouse/proj-276055/2/proj, B got /tmp/th-live.VQAD/w3-new/home/.treehouse/proj-276055/3/proj
RESULT S13: leased slot protected
base  main  (repository default)
1     leased       ~/.treehouse/proj-276055/1/proj  (detached)
2     leased       ~/.treehouse/proj-276055/2/proj  (detached)
3     leased       ~/.treehouse/proj-276055/3/proj  (detached)
Evidence: Fixed binary: broken-pointer slot refused with explicit unverifiable-identity message, left intact
######## binary: treehouse-new ########
== S14 slot with a broken .git pointer, max_trees=1 -> refused, explicit reason, slot left intact
🌳 Setting up worktree...
all 1 worktrees are in use, dirty, or not provably this clone's (0 belong to another clone; 1 whose clone identity cannot be verified; max_trees = 1). A worktree is reused only by the clone it belongs to. Run 'treehouse status' to see details, or increase max_trees in treehouse.toml
exit=1
slot still on disk: yes ; .git = gitdir: /tmp/th-live.VQAD/w4-new/nowhere/.git/worktrees/x
Evidence: Targeted Go tests (git pass, jj skip: no jj binary)
=== RUN   TestAcquireColocatedJJCloneIdentity
=== RUN   TestAcquireColocatedJJCloneIdentity/ordinary
=== RUN   TestAcquireColocatedJJCloneIdentity/lease
--- PASS: TestAcquireColocatedJJCloneIdentity (0.00s)
    --- SKIP: TestAcquireColocatedJJCloneIdentity/ordinary (0.00s)
    --- SKIP: TestAcquireColocatedJJCloneIdentity/lease (0.00s)
=== RUN   TestAcquireNonColocatedJJRefusesReuse
=== RUN   TestAcquireNonColocatedJJRefusesReuse/ordinary
=== RUN   TestAcquireNonColocatedJJRefusesReuse/lease
--- PASS: TestAcquireNonColocatedJJRefusesReuse (0.00s)
    --- SKIP: TestAcquireNonColocatedJJRefusesReuse/ordinary (0.00s)
    --- SKIP: TestAcquireNonColocatedJJRefusesReuse/lease (0.00s)
=== RUN   TestAcquireSkipsUnresolvableColocatedJJIdentity
--- SKIP: TestAcquireSkipsUnresolvableColocatedJJIdentity (0.00s)
=== RUN   TestAcquireNonColocatedJJRefusesIdentifiableWorkspace
--- SKIP: TestAcquireNonColocatedJJRefusesIdentifiableWorkspace (0.00s)
=== RUN   TestAcquireSecondNonColocatedJJCloneRefusedForeignWorkspace
--- SKIP: TestAcquireSecondNonColocatedJJCloneRefusedForeignWorkspace (0.00s)
=== RUN   TestAcquire_CloneIdentity
=== RUN   TestAcquire_CloneIdentity/leased=false
=== RUN   TestAcquire_CloneIdentity/leased=true
--- PASS: TestAcquire_CloneIdentity (7.09s)
=== RUN   TestAcquire_CloneIdentityCapacity
=== RUN   TestAcquire_CloneIdentityCapacity/leased=false
=== RUN   TestAcquire_CloneIdentityCapacity/leased=true
--- PASS: TestAcquire_CloneIdentityCapacity (2.80s)
=== RUN   TestAcquire_CloneIdentitySymlinkAlias
--- PASS: TestAcquire_CloneIdentitySymlinkAlias (2.08s)
=== RUN   TestAcquire_CloneIdentityUnreadableCandidate
--- PASS: TestAcquire_CloneIdentityUnreadableCandidate (1.29s)
=== RUN   TestRelease_CloneIdentityExistingState
--- PASS: TestRelease_CloneIdentityExistingState (0.92s)
PASS
ok  	github.com/kunchenguid/treehouse/internal/pool	14.418s
Evidence: New regression tests fail against the base allocator
--- FAIL: TestAcquire_CloneIdentity (3.92s)
    --- FAIL: TestAcquire_CloneIdentity/leased=false (1.89s)
        pool_test.go:82: slot ~/tmp/TestAcquire_CloneIdentityleased=false3008312549/001/shared/.treehouse/myrepo-de0427/1/myrepo belongs to ~/tmp/TestAcquire_CloneIdentityleased=false3008312549/001/myrepo/.git, want requesting clone ~/tmp/TestAcquire_CloneIdentityleased=false3008312549/001/other/myrepo/.git
    --- FAIL: TestAcquire_CloneIdentity/leased=true (2.02s)
        pool_test.go:82: slot ~/tmp/TestAcquire_CloneIdentityleased=true19225512/001/shared/.treehouse/myrepo-851e89/1/myrepo belongs to ~/tmp/TestAcquire_CloneIdentityleased=true19225512/001/myrepo/.git, want requesting clone ~/tmp/TestAcquire_CloneIdentityleased=true19225512/001/other/myrepo/.git
--- FAIL: TestAcquire_CloneIdentityCapacity (2.25s)
    --- FAIL: TestAcquire_CloneIdentityCapacity/leased=false (1.17s)
        pool_test.go:120: expected explicit capacity failure, got path="~/tmp/TestAcquire_CloneIdentityCapacityleased=false1436321634/001/shared/.treehouse/myrepo-f8224a/1/myrepo" err=<nil>
    --- FAIL: TestAcquire_CloneIdentityCapacity/leased=true (1.08s)
        pool_test.go:120: expected explicit capacity failure, got path="~/tmp/TestAcquire_CloneIdentityCapacityleased=true2318496571/001/shared/.treehouse/myrepo-d7a1a6/1/myrepo" err=<nil>
FAIL
FAIL	github.com/kunchenguid/treehouse/internal/pool	8.320s
FAIL
Evidence: Scenario driver scripts
#!/bin/bash
set -u
BIN=$1; W=$2
rm -rf $W; mkdir -p $W/home
export HOME=$W/home XDG_CONFIG_HOME=$W/home/.config TREEHOUSE_NO_UPDATE_CHECK=1 GIT_CONFIG_GLOBAL=$W/home/.gitconfig
git config --global user.email t@t; git config --global user.name t; git config --global init.defaultBranch main
T="$(dirname $0)/$BIN"
cd_() { cd "$1" || exit 9; }
gcd() { git -C "$1" rev-parse --path-format=absolute --git-common-dir 2>&1; }
git init -q --bare $W/origin.git
git clone -q $W/origin.git $W/seed 2>/dev/null; (cd $W/seed && echo x > f && git add f && git commit -qm init && git push -q origin main)
mkdir -p $W/a $W/b
git clone -q $W/origin.git $W/a/proj; git clone -q $W/origin.git $W/b/proj
ln -s $W/a $W/a-alias
echo "######## binary: $BIN ########"
echo "== S1 cross-clone: A get --lease, A return, B get --lease"
cd_ $W/a/proj; PA=$($T get --lease 2>/dev/null); echo "A got:  $PA  owner=$(gcd $PA)"
$T return "$PA" >/dev/null 2>&1; echo "A return exit=$?"
cd_ $W/b/proj; PB=$($T get --lease 2>$W/err); echo "B got:  $PB  exit=$?  owner=$(gcd $PB)"
[ "$PA" = "$PB" ] && echo "RESULT S1: FAIL - B RECEIVED A's SLOT" || echo "RESULT S1: B got a different slot; A's slot owner still $(gcd $PA)"
$T return "$PB" >/dev/null 2>&1
echo
echo "== S2 same-clone reuse: A get --lease again"
cd_ $W/a/proj; PA2=$($T get --lease 2>/dev/null); echo "A got:  $PA2"
[ "$PA2" = "$PA" ] && echo "RESULT S2: A reused its own slot" || echo "RESULT S2: A did NOT reuse its slot"
$T return "$PA2" >/dev/null 2>&1
echo
echo "== S3 symlink alias of A (cd $W/a-alias/proj): get --lease"
cd_ $W/a-alias/proj; echo "pwd=$(pwd)"; PA3=$($T get --lease 2>/dev/null); echo "alias got: $PA3"
[ "$PA3" = "$PA" ] && echo "RESULT S3: alias reused A's slot (identity not split)" || echo "RESULT S3: alias did NOT reuse A's slot"
$T return "$PA3" >/dev/null 2>&1
echo
echo "== S4 B reuses its OWN returned slot"
cd_ $W/b/proj; PB2=$($T get --lease 2>/dev/null); echo "B got: $PB2"
[ "$PB2" = "$PB" ] && echo "RESULT S4: B reused its own slot" || echo "RESULT S4: B did NOT reuse its own slot"
$T return "$PB2" >/dev/null 2>&1
echo
echo "== S5 status after returns"; cd_ $W/a/proj; $T status 2>&1

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 1 info
  • ⚠️ internal/pool/pool.go:345 - This finding is about the intent, not a code crash. The intent says "different clones never exchange slots". It also says to "leave different or unresolvable candidates intact for their owning clone". The new acquisitionCommonGitDir does something else for non-colocated jj. It returns an empty identity (&#34;&#34;, nil) when the main root has no .git (pool.go:345-353). Then candidateDir != commonDir is false for every non-colocated jj workspace (pool.go:465-471). Result: two different non-colocated jj clones of one origin share one pool and still exchange workspaces. That is the same defect this change is meant to fix. A test locks the behavior in: TestAcquireSecondNonColocatedJJCloneSharesUnidentifiableClass (internal/pool/clone_identity_jj_test.go:203-223) asserts that clone jj-second receives the workspace that jj-first returned. vcs.CommonGitDir cannot resolve these candidates (jjvcs.go:127-137 returns an error), so the intent's rule would skip them. This empty-identity mode is an extra component that no intent requirement needs. The smallest honest remedy is to remove it: treat a non-colocated jj identity as unresolvable, so those slots are skipped and never exchanged. The trade-off is that non-colocated jj pools lose all reuse. The user must choose between strict intent conformance (no reuse) and the author's choice (reuse kept, cross-clone exchange allowed for non-colocated jj).
  • ℹ️ internal/pool/pool.go:466 - A candidate whose identity cannot be read is skipped with continue (pool.go:466-467), but it is not counted anywhere. Example: pool with max_trees=1. The only slot has a broken .git gitdir pointer. get fails with "all 1 worktrees are in use or dirty". The slot is not in use and not dirty, so the message gives the wrong reason. Fix: count these candidates (for example, in otherClone, or in a separate counter for unverifiable identity), and name that reason in the capacity error.

🔧 Fix applied.
1 info still open:

  • ℹ️ internal/pool/clone_identity_jj_test.go:220 - TestAcquireSecondNonColocatedJJCloneRefusedForeignWorkspace passes because the requester (a non-colocated jj clone) has no provable identity, so acquire refuses every candidate, including its own. The test would still pass if foreign and own workspaces were never compared. This is the honest limit of the authorized behavior (non-colocated jj reuses nothing), not a defect. The real cross-clone discrimination is covered by TestAcquire_CloneIdentity* (git) and TestAcquireColocatedJJCloneIdentity. No action needed. Be aware that the test name overstates what it proves.
✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 12 of 14 scenarios driven live against the product
Scenario Result Live Evidence
Two clones share one origin and one pool. A returns its slot, then B runs get --lease. B must NOT receive A's slot. On the base binary it does. ✅ pass live 01-baseline-bug-repro.txt (base: B got slot 1, owned by a/proj/.git) vs 02-fixed-shared-pool-scenarios.txt (fixed: B got slot 2, owned by b/proj/.git; slot 1 is still A's)
Same-clone reuse: A runs get --lease again and receives its own returned slot ✅ pass live 02-fixed-shared-pool-scenarios.txt S2
A symlink alias of clone A (a-alias/proj, under /tmp → /private/tmp) reuses A's slot, so identity does not split ✅ pass live 02-fixed-shared-pool-scenarios.txt S3
B reuses its own returned slot in the shared pool ✅ pass live 02-fixed-shared-pool-scenarios.txt S4
Ordinary (subshell) get also uses the corrected selector: B's shell lands in B's own slot, and A reuses A's slot ✅ pass live 03-fixed-ordinary-get-return-capacity.txt S6/S6b
return <name> still finds the recorded existing slot ✅ pass live 03-fixed-ordinary-get-return-capacity.txt S7
Capacity: a third clone C with max_trees=2 and both slots foreign gets an explicit 'belong to another clone' error (exit 1) from get --lease, get --lease --json and ordinary get. No slot is removed or… ✅ pass live 03-fixed-ordinary-get-return-capacity.txt S9/S9b/S9c
The clone's own slot is dirty (an untracked file). get skips it and keeps the file. ✅ pass live 04-fixed-protections.txt S10
The clone's own slot has an unlanded commit. get skips it and keeps the commit. ✅ pass live 04-fixed-protections.txt S11
The clone's own slot has a live process inside. get skips it. ✅ pass live 04-fixed-protections.txt S12
A leased slot is never handed to either clone ✅ pass live 04-fixed-protections.txt S13
A slot whose clone identity cannot be read (broken .git pointer), with max_trees=1: get is refused with an explicit 'cannot be verified' message, and the slot stays on disk ✅ pass live 05-fixed-unverifiable-slot.txt S14
The new Git regression tests fail before the fix and pass after it ⏸️ untested no The prior payload did not establish a live result for this scenario. It was checked only with Go unit tests (logs 06-go-targeted-tests.txt and 07-regression-test-fails-on-base-allocator.txt), not agai…
Colocated-jj clones: same-clone reuse works, a different colocated-jj clone is refused, and non-colocated jj reuse is refused ⏸️ untested no The jj binary is not on PATH on this host. The jj tests skip, and the CLI jj backend cannot be driven. To run it, install jj (for example brew install jj) and re-run `go test ./internal/pool/ -run…
  • Built treehouse-base from 99f4db2 and treehouse-new from 68897e6 with go build, isolated HOME/GIT_CONFIG_GLOBAL, two clones of one local bare origin with the same basename (run.sh)
  • S1-S5 with both binaries: A get --lease → return → B get --lease; same-clone reuse; symlink alias reuse; B own-slot reuse; status (run.sh)
  • S6-S9c with the new binary: ordinary get (SHELL=/bin/sh, scripted stdin) for A then B; return &lt;name&gt;; third clone C with max_trees=2 via get --lease, get --lease --json and ordinary get (run2.sh)
  • S10-S13 with the new binary: own slot dirty / with an unlanded commit / with a live sleep process inside / leased (run3.sh)
  • S14 with the new binary: slot whose .git gitdir pointer is broken, max_trees=1 (run4.sh)
  • go test ./internal/pool/ -run 'CloneIdentity|JJCloneIdentity|NonColocatedJJ|UnresolvableColocatedJJ' -v -count=1
  • Swapped in the base-commit pool.go (plus a helper stub) for a short time and ran go test ./internal/pool/ -run &#39;TestAcquire_CloneIdentity$|TestAcquire_CloneIdentitySymlinkAlias|TestAcquire_CloneIdentityCapacity&#39;. The tests fail on the old allocator. Restored the source afterwards and confirmed a clean git status.
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Compare physical Git common directories before resetting or acquiring a
shared-pool slot. Resolve the requester once, normalize symlinks, and
leave foreign or unreadable candidates intact. Explain foreign-clone
capacity exhaustion without misreporting clean slots as dirty or busy.

Apply the comparison symmetrically: an unsupported empty identity only
matches another empty identity. Preserve non-colocated JJ reuse, including
its existing unidentified-clone sharing, without adding a JJ identity
mechanism. Git and colocated JJ require matching physical identities.

Keep pool locations, state, trust checks, and cleanup behavior unchanged.
Cover both acquire modes, capacity, symlinks, unreadable candidates,
existing-state return, and colocated/non-colocated JJ combinations.
@greptile-apps

greptile-apps Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

The clone-isolation fix appears safe to merge; restoring the generated graft-cache exclusion is worthwhile but non-blocking.

Reviews (3) · Last reviewed commit: "no-mistakes(ci): Removed stray graft ign..."

Comment thread internal/pool/pool.go Resolved

@kunchenguid kunchenguid left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Speaking as Kun's firstmate: first-time fork review — no security risk in the diff (clone-scoped reuse, fail-closed on unverifiable identity). Approving so required checks can run. Not a merge vote.

Greptile's P1 still blocks merge: clone identity uses string compare after EvalSymlinks; on case-insensitive filesystems that can mis-class the same physical Git dir as foreign. Please compare filesystem identity (e.g. os.SameFile) rather than path strings, per AGENTS.md Windows path-handling. Waiting on that fix and green CI — this is waiting on the author, not a captain-decision hold.

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: triage stamp.

VISION per-rule (tip 686f00d vs main 02d9f5c):

  • Isolation and reuse: aligns. Acquire now refuses another clone's slot and refuses unverifiable identity (including non-colocated jj). Matches "each acquisition must receive a worktree that no other acquisition can claim" and "unverifiable worktrees must not be silently recycled." Evidence: acquisitionCommonGitDir + skip in acquire (internal/pool/pool.go).
  • Safe lifecycle operations: aligns. This PR does not widen prune/destroy; reuse skip is fail-closed, not a new delete path.
  • Ownership and interface: aligns. Foreign vs unverifiable counts are now in the max_trees error; status still shows slots. Human 🌳 branding unchanged.
  • Scope and evaluation: aligns. Local CLI pool correctness; no daemon/orchestration; tests added in internal/pool/pool_test.go and clone_identity_jj_test.go.

contract-class=restore (the already-promised isolation/reuse default was broken for shared origin-keyed pools; this restores it. Skipping unverifiable is the existing fail-closed recycle bar, not a new always-on surface.)

Fork CI approved this pass. Greptile P1 (case-sensitive path compare) still blocks merge. Waiting on the author — not a captain-decision hold. No auto-merge until that finding is cleared and CI is green.

…mitted for the executor. I did not push, and I did not touch the PR. 1. Windows CI failure (TestAcquire_CloneIdentityCapacity, pool_test.go:128). The cause was in the test only. Git on Windows checks README out as "hi\r\n", and the test compared it with the literal "hi\n". The test now reads the README bytes BEFORE the rejected foreign acquisition and compares them AFTER. The two new jj tests that compared with the same literal get the same snapshot change: TestAcquireSkipsUnresolvableColocatedJJIdentity and TestAcquireSecondNonColocatedJJCloneRefusedForeignWorkspace. Product behaviour does not change. Proof: with core.autocrlf=true (set through the GIT_CONFIG_COUNT env), the old test fails with the exact CI message ("hi\r\n") for leased=false and leased=true. The new test passes under the same setting. 2. Greptile finding at pool.go:461 (it is a real finding, not a service failure). The code compared clone identity as path strings (candidateDir != commonDir). On a case-insensitive filesystem, one physical clone spelled with different letter case read as "another clone", so the clone could not reuse its own slot. Fix: acquisitionCommonGitDir now returns os.Stat(vcs.CommonGitDir(dir)), and the selector compares with os.SameFile. os.Stat follows symlinks, so symlink aliases still resolve to one identity. The filepath.Abs and EvalSymlinks steps are now redundant, so I removed them. The requester identity is still computed once, outside the loop. Any identity error on either side still means skip (unverifiedClone). Capacity messages are the same. Non-colocated jj still gets no reuse. Nothing is lowercased. The jj test failure messages now print the identity with %v. New regression: TestAcquire_CloneIdentityCaseAlias covers ordinary and durable (lease) acquisition. It rewrites the slot's commondir to an upper-cased spelling and asks as both repo and REPO. It skips only when os.Stat plus os.SameFile shows the filesystem is case-sensitive. Before the fix, both subtests failed on macOS with "1 belong to another clone". After the fix, both pass. The symlink alias, distinct-clone and unreadable-candidate tests still pass. Docs: I made one-line accuracy updates to AGENTS.md (the identity uses os.SameFile, not a string compare) and to the README Clone-correct reuse line (differently cased paths on a case-insensitive filesystem count as one clone). Validation, all local on macOS: - Native go build ./... and go vet ./... pass. - GOOS=windows go build ./... and go vet ./... pass. - Full go test ./... -count=1 passes with the real jj on PATH. All jj clone-identity tests ran; none skipped. No prune/destroy/trust-check changes. No cleanup changes. No new jj identity mechanism
… no-mistakes" (run 35838744065) ended as action_required with zero jobs, so no step ran and nothing failed. The other runs on the same PR head 2a00a9a are in the same state: "CI" (35838743988) and "Nix flake" (35838744043) are both action_required with no jobs. That is GitHub holding workflow runs on a PR from a fork until a maintainer approves them. The new pipeline push created these runs, and none has been approved yet. The local HEAD equals the PR head, so the runs point at the current code but have not executed it. This failure is outside the code under review. Action for the outer executor or owner: a kunchenguid/treehouse maintainer must click "Approve and run workflows" on PR kunchenguid#145. The .gitignore and .ignore changes in the working tree are local graft-cache artifacts and must not be committed
…gnore to base content and deleted .ignore, which does not exist on base. PR diff vs base is now exactly AGENTS.md, README.md, internal/pool/clone_identity_jj_test.go, internal/pool/pool.go, internal/pool/pool_test.go. graft/ stays ignored by the repo-local info/exclude. No product or test changes. go build and internal/pool tests pass. CI, Nix flake and Require no-mistakes are action_required with 0 jobs: they wait for a maintainer to approve fork workflow runs on kunchenguid#145. No code fault

@kunchenguid kunchenguid left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Speaking as Kun's firstmate: re-review on tip d9fb0a1 (not a merge vote).

VISION per-rule (vs main 02d9f5c):

  • Isolation and reuse: aligns. Acquire refuses another clone's slot and refuses unverifiable identity (incl. non-colocated jj). Matches "each acquisition must receive a worktree that no other acquisition can claim" and "unverifiable worktrees must not be silently recycled." Evidence: acquisitionCommonGitDir + os.SameFile compare in acquire.
  • Safe lifecycle operations: aligns. No widen of prune/destroy here.
  • Ownership and interface: aligns. Foreign vs unverifiable counts in max_trees error.
  • Scope and evaluation: aligns. Local CLI pool correctness; tests in pool_test.go / clone_identity_jj_test.go.

contract-class=restore (already-promised isolation for shared origin-keyed pools).

Newer activity: Greptile P1 (case-sensitive path compare) addressed via os.SameFile; Greptile now 5/5. Graft-ignore artifacts removed from the diff. Fork CI re-approved this pass — waiting on green CI before auto-merge. Overlap with #146 cleared on the #146 side (reclaim-only now).

@kunchenguid
kunchenguid merged commit 1185dc6 into kunchenguid:main Sep 23, 2026
7 checks passed

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: merged — thank you @MrGTV-love for restoring clone-correct worktree reuse (os.SameFile identity). Much appreciated.

kunchenguid added a commit to MrGTV-love/treehouse that referenced this pull request Sep 23, 2026
Keep reclaim helpers from this branch and clone-identity tests from main.
Leave fork workflow files unchanged.
kunchenguid added a commit that referenced this pull request Sep 24, 2026
…in a shared pool (#146)

* fix(pool): enforce clone identity when reusing Git worktrees

Compare physical Git common directories before resetting or acquiring a
shared-pool slot. Resolve the requester once, normalize symlinks, and
leave foreign or unreadable candidates intact. Explain foreign-clone
capacity exhaustion without misreporting clean slots as dirty or busy.

Apply the comparison symmetrically: an unsupported empty identity only
matches another empty identity. Preserve non-colocated JJ reuse, including
its existing unidentified-clone sharing, without adding a JJ identity
mechanism. Git and colocated JJ require matching physical identities.

Keep pool locations, state, trust checks, and cleanup behavior unchanged.
Cover both acquire modes, capacity, symlinks, unreadable candidates,
existing-state return, and colocated/non-colocated JJ combinations.

* no-mistakes(review): Refuse worktree reuse when clone identity cannot be verified

* no-mistakes(document): Document clone-correct worktree reuse in README and AGENTS

* fix(pool): enforce clone identity when reusing Git worktrees

Compare physical Git common directories before resetting or acquiring a
shared-pool slot. Resolve the requester once, normalize symlinks, and
leave foreign or unreadable candidates intact. Explain foreign-clone
capacity exhaustion without misreporting clean slots as dirty or busy.

Apply the comparison symmetrically: an unsupported empty identity only
matches another empty identity. Preserve non-colocated JJ reuse, including
its existing unidentified-clone sharing, without adding a JJ identity
mechanism. Git and colocated JJ require matching physical identities.

Keep pool locations, state, trust checks, and cleanup behavior unchanged.
Cover both acquire modes, capacity, symlinks, unreadable candidates,
existing-state return, and colocated/non-colocated JJ combinations.

* no-mistakes(review): Refuse worktree reuse when clone identity cannot be verified

* no-mistakes(document): Document clone-correct worktree reuse in README and AGENTS

* fix(pool): reclaim foreign-clone worktrees

Resolve cleanup context and VCS removal ownership from each managed
worktree path so shared pools can prune and destroy slots from multiple
clones while unresolved paths remain untouched and reported.

* no-mistakes(document): Document per-worktree repository resolution for prune and destroy

* no-mistakes(ci): Fixed Greptile finding ci-5 with the smallest change. What I changed: 1. internal/pool/prune.go, `worktreePruneContextResolver`: when fetch or default-ref resolution fails, it now returns `pruneContext{RepoRoot: repoRoot}` with the error. It used to return an empty context. The cached-error path does the same thing now. DefaultRef stays empty. 2. internal/pool/destroy.go:214: I updated the comment. It now says that a failure leaves the default ref empty. 3. internal/pool/pool_test.go: I added `TestWorktreePruneContextResolverKeepsRootWhenFetchFails`. It points origin at a missing path and calls the resolver two times. The second call reads the cached error. Each call must return an error, the resolved root, and an empty DefaultRef. Effect: `classifyForDestroy` gets the root again, so it can set `OtherFlavor` and show the "destroy it and migrate the pool" hint. With an empty DefaultRef the slot is still `DestroyUnverified`, so deletion is still refused. Prune does not change: at prune.go:704 it throws away the context when there is an error. No new resolver or abstraction was added. Checks I ran: - Without the fix, the new test fails (`got RepoRoot:""`). With the fix, it passes. - `go test ./... -count=1`: all packages pass. - `go vet ./internal/pool/` passes. `gofmt -l` finds nothing. `GOOS=windows go build ./...` passes. I did not commit the changes. They are in the working tree

* no-mistakes(ci): Fixed both real failures. The changes are left uncommitted for the executor. I did not push, and I did not touch the PR. 1. Windows CI failure (TestAcquire_CloneIdentityCapacity, pool_test.go:128). The cause was in the test only. Git on Windows checks README out as "hi\r\n", and the test compared it with the literal "hi\n". The test now reads the README bytes BEFORE the rejected foreign acquisition and compares them AFTER. The two new jj tests that compared with the same literal get the same snapshot change: TestAcquireSkipsUnresolvableColocatedJJIdentity and TestAcquireSecondNonColocatedJJCloneRefusedForeignWorkspace. Product behaviour does not change. Proof: with core.autocrlf=true (set through the GIT_CONFIG_COUNT env), the old test fails with the exact CI message ("hi\r\n") for leased=false and leased=true. The new test passes under the same setting. 2. Greptile finding at pool.go:461 (it is a real finding, not a service failure). The code compared clone identity as path strings (candidateDir != commonDir). On a case-insensitive filesystem, one physical clone spelled with different letter case read as "another clone", so the clone could not reuse its own slot. Fix: acquisitionCommonGitDir now returns os.Stat(vcs.CommonGitDir(dir)), and the selector compares with os.SameFile. os.Stat follows symlinks, so symlink aliases still resolve to one identity. The filepath.Abs and EvalSymlinks steps are now redundant, so I removed them. The requester identity is still computed once, outside the loop. Any identity error on either side still means skip (unverifiedClone). Capacity messages are the same. Non-colocated jj still gets no reuse. Nothing is lowercased. The jj test failure messages now print the identity with %v. New regression: TestAcquire_CloneIdentityCaseAlias covers ordinary and durable (lease) acquisition. It rewrites the slot's commondir to an upper-cased spelling and asks as both repo and REPO. It skips only when os.Stat plus os.SameFile shows the filesystem is case-sensitive. Before the fix, both subtests failed on macOS with "1 belong to another clone". After the fix, both pass. The symlink alias, distinct-clone and unreadable-candidate tests still pass. Docs: I made one-line accuracy updates to AGENTS.md (the identity uses os.SameFile, not a string compare) and to the README Clone-correct reuse line (differently cased paths on a case-insensitive filesystem count as one clone). Validation, all local on macOS: - Native go build ./... and go vet ./... pass. - GOOS=windows go build ./... and go vet ./... pass. - Full go test ./... -count=1 passes with the real jj on PATH. All jj clone-identity tests ran; none skipped. No prune/destroy/trust-check changes. No cleanup changes. No new jj identity mechanism

* no-mistakes(ci): No code change is needed. The failing check "Require no-mistakes" (run 35838744065) ended as action_required with zero jobs, so no step ran and nothing failed. The other runs on the same PR head 2a00a9a are in the same state: "CI" (35838743988) and "Nix flake" (35838744043) are both action_required with no jobs. That is GitHub holding workflow runs on a PR from a fork until a maintainer approves them. The new pipeline push created these runs, and none has been approved yet. The local HEAD equals the PR head, so the runs point at the current code but have not executed it. This failure is outside the code under review. Action for the outer executor or owner: a kunchenguid/treehouse maintainer must click "Approve and run workflows" on PR #145. The .gitignore and .ignore changes in the working tree are local graft-cache artifacts and must not be committed

* no-mistakes(ci): Removed stray graft ignore artifacts: restored .gitignore to base content and deleted .ignore, which does not exist on base. PR diff vs base is now exactly AGENTS.md, README.md, internal/pool/clone_identity_jj_test.go, internal/pool/pool.go, internal/pool/pool_test.go. graft/ stays ignored by the repo-local info/exclude. No product or test changes. go build and internal/pool tests pass. CI, Nix flake and Require no-mistakes are action_required with 0 jobs: they wait for a maintainer to approve fork workflow runs on #145. No code fault

* no-mistakes(ci): Fixed Greptile ci-4 (clone identity is out of scope). The changes are left uncommitted in the working tree so the executor can make one forward commit. I did no rebase, reset, amend or force-push, and I did not push. What I removed (clone-identity work from PR 145): 1. internal/pool/pool.go: restored to the base version (38f8192). This removes acquisitionCommonGitDir, the otherClone/unverifiedClone skip in acquire, and the clone-identity capacity error. The reclaim commits never changed pool.go. 2. internal/pool/clone_identity_jj_test.go: deleted (git rm). It held only clone-identity jj acquire tests. 3. internal/pool/pool_test.go: removed assertCloneCommonDir, TestAcquire_CloneIdentity, TestAcquire_CloneIdentityCapacity, TestAcquire_CloneIdentitySymlinkAlias, TestAcquire_CloneIdentityCaseAlias, TestAcquire_CloneIdentityUnreadableCandidate and TestRelease_CloneIdentityExistingState. Also removed the vcs import, which nothing else uses. 4. AGENTS.md: the "Acquire reuses a slot only when..." line is back to the base text. 5. README.md: the reuse flow diagram is back to the base text, and the "Clone-correct reuse" bullet is gone. What I kept (reclaim work): - The per-worktree root resolution in destroy.go and prune.go, and the fix that keeps the root when fetch fails. - Their tests: TestDestroyPoolRemovesWorktreesOwnedByDifferentClones, TestDestroyPoolRefusesUnattributableWorktreePerPath, TestPruneRemovesWorktreesOwnedByDifferentClones, TestWorktreePruneContextResolverKeepsRootWhenFetchFails, and the updated executeDestroy tests. - Their docs: the AGENTS.md prune/destroy line and the README prune/destroy paragraphs. - The shared test helper setupSharedClonePool, because the reclaim tests need it. I changed only its comment. acquireDisposableFromEachClone does not need clone identity: clone B gets a new slot because clone A's slot is still reserved. The diff against base 38f8192 now touches only AGENTS.md, README.md, internal/pool/destroy.go, internal/pool/prune.go, internal/pool/pool_test.go and internal/pool/worktree_path_test.go. .gitignore and .ignore are not in it. The separation was clean, with no conflicts. Checks run on macOS: - go build ./... passed. - go vet ./... passed. - GOOS=windows go build ./... and GOOS=windows go vet ./... passed. - gofmt -l printed nothing. - go test ./... -count=1 passed in every package. - All reclaim tests ran and passed (verbose run). Gap: I could not run the real-jj tests. jj is not on PATH on this machine, and the workspace rules do not let me install it, so 23 jj tests skipped. The jj tests I deleted covered clone identity only. No jj code path changed in this round

* Restore upstream workflow exemption after merge

Keep the PR diff scoped to foreign-slot reclaim by restoring the
kunchenguid exemption already present on upstream main.

* fix(pool): avoid resolving markerless destroy targets

Keep damaged slots out of per-path repository resolution so destroy cannot
fetch an unrelated repository enclosing the pool. Restore real Git removal
refusal coverage for state and owner-reservation recovery.

---------

Co-authored-by: Kun Chen <[email protected]>
MrGTV-love added a commit to MrGTV-love/treehouse that referenced this pull request Oct 6, 2026
* ci: pin require-no-mistakes to v1.80.1 for live PR lookup (kunchenguid#144)

* ci: pin require-no-mistakes to v1.80.1 for live PR lookup

The v1.80.1 verifier reads body and head from one API response and
fails closed without pull-requests: read, so drop the Fetch current
PR body step and its cached event-payload inputs.

* test: lock v1.80.1 live PR lookup on the required-check caller

A pin-only assertion stayed green if the workflow restored cached
PR inputs, restored the fetch step, or dropped pull-requests: read.

* ci: exempt kunchenguid from no-mistakes-required gate (kunchenguid#147)

* fix(pool): reuse a pooled worktree only for the clone that owns it (kunchenguid#145)

* fix(pool): enforce clone identity when reusing Git worktrees

Compare physical Git common directories before resetting or acquiring a
shared-pool slot. Resolve the requester once, normalize symlinks, and
leave foreign or unreadable candidates intact. Explain foreign-clone
capacity exhaustion without misreporting clean slots as dirty or busy.

Apply the comparison symmetrically: an unsupported empty identity only
matches another empty identity. Preserve non-colocated JJ reuse, including
its existing unidentified-clone sharing, without adding a JJ identity
mechanism. Git and colocated JJ require matching physical identities.

Keep pool locations, state, trust checks, and cleanup behavior unchanged.
Cover both acquire modes, capacity, symlinks, unreadable candidates,
existing-state return, and colocated/non-colocated JJ combinations.

* no-mistakes(review): Refuse worktree reuse when clone identity cannot be verified

* no-mistakes(document): Document clone-correct worktree reuse in README and AGENTS

* no-mistakes(ci): Fixed both real failures. The changes are left uncommitted for the executor. I did not push, and I did not touch the PR. 1. Windows CI failure (TestAcquire_CloneIdentityCapacity, pool_test.go:128). The cause was in the test only. Git on Windows checks README out as "hi\r\n", and the test compared it with the literal "hi\n". The test now reads the README bytes BEFORE the rejected foreign acquisition and compares them AFTER. The two new jj tests that compared with the same literal get the same snapshot change: TestAcquireSkipsUnresolvableColocatedJJIdentity and TestAcquireSecondNonColocatedJJCloneRefusedForeignWorkspace. Product behaviour does not change. Proof: with core.autocrlf=true (set through the GIT_CONFIG_COUNT env), the old test fails with the exact CI message ("hi\r\n") for leased=false and leased=true. The new test passes under the same setting. 2. Greptile finding at pool.go:461 (it is a real finding, not a service failure). The code compared clone identity as path strings (candidateDir != commonDir). On a case-insensitive filesystem, one physical clone spelled with different letter case read as "another clone", so the clone could not reuse its own slot. Fix: acquisitionCommonGitDir now returns os.Stat(vcs.CommonGitDir(dir)), and the selector compares with os.SameFile. os.Stat follows symlinks, so symlink aliases still resolve to one identity. The filepath.Abs and EvalSymlinks steps are now redundant, so I removed them. The requester identity is still computed once, outside the loop. Any identity error on either side still means skip (unverifiedClone). Capacity messages are the same. Non-colocated jj still gets no reuse. Nothing is lowercased. The jj test failure messages now print the identity with %v. New regression: TestAcquire_CloneIdentityCaseAlias covers ordinary and durable (lease) acquisition. It rewrites the slot's commondir to an upper-cased spelling and asks as both repo and REPO. It skips only when os.Stat plus os.SameFile shows the filesystem is case-sensitive. Before the fix, both subtests failed on macOS with "1 belong to another clone". After the fix, both pass. The symlink alias, distinct-clone and unreadable-candidate tests still pass. Docs: I made one-line accuracy updates to AGENTS.md (the identity uses os.SameFile, not a string compare) and to the README Clone-correct reuse line (differently cased paths on a case-insensitive filesystem count as one clone). Validation, all local on macOS: - Native go build ./... and go vet ./... pass. - GOOS=windows go build ./... and go vet ./... pass. - Full go test ./... -count=1 passes with the real jj on PATH. All jj clone-identity tests ran; none skipped. No prune/destroy/trust-check changes. No cleanup changes. No new jj identity mechanism

* no-mistakes(ci): No code change is needed. The failing check "Require no-mistakes" (run 35838744065) ended as action_required with zero jobs, so no step ran and nothing failed. The other runs on the same PR head 2a00a9a are in the same state: "CI" (35838743988) and "Nix flake" (35838744043) are both action_required with no jobs. That is GitHub holding workflow runs on a PR from a fork until a maintainer approves them. The new pipeline push created these runs, and none has been approved yet. The local HEAD equals the PR head, so the runs point at the current code but have not executed it. This failure is outside the code under review. Action for the outer executor or owner: a kunchenguid/treehouse maintainer must click "Approve and run workflows" on PR kunchenguid#145. The .gitignore and .ignore changes in the working tree are local graft-cache artifacts and must not be committed

* no-mistakes(ci): Removed stray graft ignore artifacts: restored .gitignore to base content and deleted .ignore, which does not exist on base. PR diff vs base is now exactly AGENTS.md, README.md, internal/pool/clone_identity_jj_test.go, internal/pool/pool.go, internal/pool/pool_test.go. graft/ stays ignored by the repo-local info/exclude. No product or test changes. go build and internal/pool tests pass. CI, Nix flake and Require no-mistakes are action_required with 0 jobs: they wait for a maintainer to approve fork workflow runs on kunchenguid#145. No code fault

* fix(pool): let prune and destroy reclaim worktrees from other clones in a shared pool (kunchenguid#146)

* fix(pool): enforce clone identity when reusing Git worktrees

Compare physical Git common directories before resetting or acquiring a
shared-pool slot. Resolve the requester once, normalize symlinks, and
leave foreign or unreadable candidates intact. Explain foreign-clone
capacity exhaustion without misreporting clean slots as dirty or busy.

Apply the comparison symmetrically: an unsupported empty identity only
matches another empty identity. Preserve non-colocated JJ reuse, including
its existing unidentified-clone sharing, without adding a JJ identity
mechanism. Git and colocated JJ require matching physical identities.

Keep pool locations, state, trust checks, and cleanup behavior unchanged.
Cover both acquire modes, capacity, symlinks, unreadable candidates,
existing-state return, and colocated/non-colocated JJ combinations.

* no-mistakes(review): Refuse worktree reuse when clone identity cannot be verified

* no-mistakes(document): Document clone-correct worktree reuse in README and AGENTS

* fix(pool): enforce clone identity when reusing Git worktrees

Compare physical Git common directories before resetting or acquiring a
shared-pool slot. Resolve the requester once, normalize symlinks, and
leave foreign or unreadable candidates intact. Explain foreign-clone
capacity exhaustion without misreporting clean slots as dirty or busy.

Apply the comparison symmetrically: an unsupported empty identity only
matches another empty identity. Preserve non-colocated JJ reuse, including
its existing unidentified-clone sharing, without adding a JJ identity
mechanism. Git and colocated JJ require matching physical identities.

Keep pool locations, state, trust checks, and cleanup behavior unchanged.
Cover both acquire modes, capacity, symlinks, unreadable candidates,
existing-state return, and colocated/non-colocated JJ combinations.

* no-mistakes(review): Refuse worktree reuse when clone identity cannot be verified

* no-mistakes(document): Document clone-correct worktree reuse in README and AGENTS

* fix(pool): reclaim foreign-clone worktrees

Resolve cleanup context and VCS removal ownership from each managed
worktree path so shared pools can prune and destroy slots from multiple
clones while unresolved paths remain untouched and reported.

* no-mistakes(document): Document per-worktree repository resolution for prune and destroy

* no-mistakes(ci): Fixed Greptile finding ci-5 with the smallest change. What I changed: 1. internal/pool/prune.go, `worktreePruneContextResolver`: when fetch or default-ref resolution fails, it now returns `pruneContext{RepoRoot: repoRoot}` with the error. It used to return an empty context. The cached-error path does the same thing now. DefaultRef stays empty. 2. internal/pool/destroy.go:214: I updated the comment. It now says that a failure leaves the default ref empty. 3. internal/pool/pool_test.go: I added `TestWorktreePruneContextResolverKeepsRootWhenFetchFails`. It points origin at a missing path and calls the resolver two times. The second call reads the cached error. Each call must return an error, the resolved root, and an empty DefaultRef. Effect: `classifyForDestroy` gets the root again, so it can set `OtherFlavor` and show the "destroy it and migrate the pool" hint. With an empty DefaultRef the slot is still `DestroyUnverified`, so deletion is still refused. Prune does not change: at prune.go:704 it throws away the context when there is an error. No new resolver or abstraction was added. Checks I ran: - Without the fix, the new test fails (`got RepoRoot:""`). With the fix, it passes. - `go test ./... -count=1`: all packages pass. - `go vet ./internal/pool/` passes. `gofmt -l` finds nothing. `GOOS=windows go build ./...` passes. I did not commit the changes. They are in the working tree

* no-mistakes(ci): Fixed both real failures. The changes are left uncommitted for the executor. I did not push, and I did not touch the PR. 1. Windows CI failure (TestAcquire_CloneIdentityCapacity, pool_test.go:128). The cause was in the test only. Git on Windows checks README out as "hi\r\n", and the test compared it with the literal "hi\n". The test now reads the README bytes BEFORE the rejected foreign acquisition and compares them AFTER. The two new jj tests that compared with the same literal get the same snapshot change: TestAcquireSkipsUnresolvableColocatedJJIdentity and TestAcquireSecondNonColocatedJJCloneRefusedForeignWorkspace. Product behaviour does not change. Proof: with core.autocrlf=true (set through the GIT_CONFIG_COUNT env), the old test fails with the exact CI message ("hi\r\n") for leased=false and leased=true. The new test passes under the same setting. 2. Greptile finding at pool.go:461 (it is a real finding, not a service failure). The code compared clone identity as path strings (candidateDir != commonDir). On a case-insensitive filesystem, one physical clone spelled with different letter case read as "another clone", so the clone could not reuse its own slot. Fix: acquisitionCommonGitDir now returns os.Stat(vcs.CommonGitDir(dir)), and the selector compares with os.SameFile. os.Stat follows symlinks, so symlink aliases still resolve to one identity. The filepath.Abs and EvalSymlinks steps are now redundant, so I removed them. The requester identity is still computed once, outside the loop. Any identity error on either side still means skip (unverifiedClone). Capacity messages are the same. Non-colocated jj still gets no reuse. Nothing is lowercased. The jj test failure messages now print the identity with %v. New regression: TestAcquire_CloneIdentityCaseAlias covers ordinary and durable (lease) acquisition. It rewrites the slot's commondir to an upper-cased spelling and asks as both repo and REPO. It skips only when os.Stat plus os.SameFile shows the filesystem is case-sensitive. Before the fix, both subtests failed on macOS with "1 belong to another clone". After the fix, both pass. The symlink alias, distinct-clone and unreadable-candidate tests still pass. Docs: I made one-line accuracy updates to AGENTS.md (the identity uses os.SameFile, not a string compare) and to the README Clone-correct reuse line (differently cased paths on a case-insensitive filesystem count as one clone). Validation, all local on macOS: - Native go build ./... and go vet ./... pass. - GOOS=windows go build ./... and go vet ./... pass. - Full go test ./... -count=1 passes with the real jj on PATH. All jj clone-identity tests ran; none skipped. No prune/destroy/trust-check changes. No cleanup changes. No new jj identity mechanism

* no-mistakes(ci): No code change is needed. The failing check "Require no-mistakes" (run 35838744065) ended as action_required with zero jobs, so no step ran and nothing failed. The other runs on the same PR head 2a00a9a are in the same state: "CI" (35838743988) and "Nix flake" (35838744043) are both action_required with no jobs. That is GitHub holding workflow runs on a PR from a fork until a maintainer approves them. The new pipeline push created these runs, and none has been approved yet. The local HEAD equals the PR head, so the runs point at the current code but have not executed it. This failure is outside the code under review. Action for the outer executor or owner: a kunchenguid/treehouse maintainer must click "Approve and run workflows" on PR kunchenguid#145. The .gitignore and .ignore changes in the working tree are local graft-cache artifacts and must not be committed

* no-mistakes(ci): Removed stray graft ignore artifacts: restored .gitignore to base content and deleted .ignore, which does not exist on base. PR diff vs base is now exactly AGENTS.md, README.md, internal/pool/clone_identity_jj_test.go, internal/pool/pool.go, internal/pool/pool_test.go. graft/ stays ignored by the repo-local info/exclude. No product or test changes. go build and internal/pool tests pass. CI, Nix flake and Require no-mistakes are action_required with 0 jobs: they wait for a maintainer to approve fork workflow runs on kunchenguid#145. No code fault

* no-mistakes(ci): Fixed Greptile ci-4 (clone identity is out of scope). The changes are left uncommitted in the working tree so the executor can make one forward commit. I did no rebase, reset, amend or force-push, and I did not push. What I removed (clone-identity work from PR 145): 1. internal/pool/pool.go: restored to the base version (38f8192). This removes acquisitionCommonGitDir, the otherClone/unverifiedClone skip in acquire, and the clone-identity capacity error. The reclaim commits never changed pool.go. 2. internal/pool/clone_identity_jj_test.go: deleted (git rm). It held only clone-identity jj acquire tests. 3. internal/pool/pool_test.go: removed assertCloneCommonDir, TestAcquire_CloneIdentity, TestAcquire_CloneIdentityCapacity, TestAcquire_CloneIdentitySymlinkAlias, TestAcquire_CloneIdentityCaseAlias, TestAcquire_CloneIdentityUnreadableCandidate and TestRelease_CloneIdentityExistingState. Also removed the vcs import, which nothing else uses. 4. AGENTS.md: the "Acquire reuses a slot only when..." line is back to the base text. 5. README.md: the reuse flow diagram is back to the base text, and the "Clone-correct reuse" bullet is gone. What I kept (reclaim work): - The per-worktree root resolution in destroy.go and prune.go, and the fix that keeps the root when fetch fails. - Their tests: TestDestroyPoolRemovesWorktreesOwnedByDifferentClones, TestDestroyPoolRefusesUnattributableWorktreePerPath, TestPruneRemovesWorktreesOwnedByDifferentClones, TestWorktreePruneContextResolverKeepsRootWhenFetchFails, and the updated executeDestroy tests. - Their docs: the AGENTS.md prune/destroy line and the README prune/destroy paragraphs. - The shared test helper setupSharedClonePool, because the reclaim tests need it. I changed only its comment. acquireDisposableFromEachClone does not need clone identity: clone B gets a new slot because clone A's slot is still reserved. The diff against base 38f8192 now touches only AGENTS.md, README.md, internal/pool/destroy.go, internal/pool/prune.go, internal/pool/pool_test.go and internal/pool/worktree_path_test.go. .gitignore and .ignore are not in it. The separation was clean, with no conflicts. Checks run on macOS: - go build ./... passed. - go vet ./... passed. - GOOS=windows go build ./... and GOOS=windows go vet ./... passed. - gofmt -l printed nothing. - go test ./... -count=1 passed in every package. - All reclaim tests ran and passed (verbose run). Gap: I could not run the real-jj tests. jj is not on PATH on this machine, and the workspace rules do not let me install it, so 23 jj tests skipped. The jj tests I deleted covered clone identity only. No jj code path changed in this round

* Restore upstream workflow exemption after merge

Keep the PR diff scoped to foreign-slot reclaim by restoring the
kunchenguid exemption already present on upstream main.

* fix(pool): avoid resolving markerless destroy targets

Keep damaged slots out of per-path repository resolution so destroy cannot
fetch an unrelated repository enclosing the pool. Restore real Git removal
refusal coverage for state and owner-reservation recovery.

---------

Co-authored-by: Kun Chen <[email protected]>

* feat: add opt-in branch creation to treehouse get (kunchenguid#150)

* feat(get): create branches on acquisition

Add an opt-in branch flag so agents can commit on a named branch immediately. Preserve hook output and quarantine unsafe slots when branch creation fails.

* fix(get): quarantine failed branch hook output

Inspect recycled slots after branch creation fails so ignored hook files cannot leak into the next acquisition. Keep clean branch-name collisions reusable and cover the rejecting hook path.

* no-mistakes(review): Preserve branch-failure diagnostics and hook-modified seeds

* no-mistakes(review): Keep recycled slots reusable and limit checkout diagnostics

* no-mistakes(review): Preserve checkout diagnostics and validate branch base before handoff

* no-mistakes(review): Report checkout hook diagnostics without changing lease output

* no-mistakes(review): Remove hook-bypassing detach retry

* no-mistakes(review): Restore ordinary detach hook failure reporting

* no-mistakes(document): Clarify branch acquisition and return documentation

* no-mistakes(ci): The Windows test failure came from hook detection relying on Unix executable permission bits. Git for Windows can run the reference-transaction hook even though those bits are not exposed, so the failed branch creation removed a slot that should have been quarantined. Hook detection now treats a regular hook file as runnable on Windows. The two targeted reference-transaction tests pass locally, and the project cross-compiles for Windows. The failing scenario has not been rerun on Windows

* no-mistakes(ci): Fixed the branch-name collision race: when branch creation fails before checkout, a post-checkout hook’s presence no longer quarantines an otherwise clean slot. Reference-transaction hook output remains protected. Added a regression that creates the collision after the initial check and confirms a max_trees=1 pool remains usable. Gated Unix-shell hook fixtures on Windows; non-hook branch coverage remains enabled. Relevant Go packages passed locally, and their tests cross-compiled for Windows. The tests were not executed on Windows

* feat(get): create branches on acquisition

Add an opt-in branch flag so agents can commit on a named branch immediately. Preserve hook output and quarantine unsafe slots when branch creation fails.

* no-mistakes(review): Restore detach errors and remove unused output inspection

* no-mistakes(review): Preserve checkout hook stderr in branch failure diagnostics

* no-mistakes(review): Restore failed Git command output behavior

* no-mistakes(document): Clarify branch collision and base-name guidance

* docs: trim agent guide and preserve design notes (kunchenguid#152)

* docs: trim AGENTS.md to every-session rules, move design notes to docs/design.md

AGENTS.md: 123 lines / 5177 words / 35817 bytes -> 48 lines / 469 words / 3305 bytes.
The Key Design Decisions and Contribution Gate maintainer detail moved verbatim
(em dashes normalized, README links re-rooted) to docs/design.md.

* no-mistakes(document): Correct pruning documentation and pass lint

* no-mistakes(ci): Updated AGENTS.md to distinguish confirmed dirty returns from fail-closed reuse and cleanup, and to document the inspected, named-destroy path for recovered quarantined slots. git diff --check and go test ./... passed

* feat(fileclone): add opt-in APFS sharing for fresh Git worktrees (kunchenguid#153)

* feat: add opt-in APFS sharing for fresh Git slots

* no-mistakes(document): Correct APFS metadata guidance and consolidate config documentation

* no-mistakes(ci): Fixed the Windows test failure by making the tracked test asset binary, preventing Git CRLF conversion from changing its checkout bytes. Reproduced the failure before the fix and passed the APFS CLI tests with CRLF conversion enabled afterward. Related package tests and the Windows build passed

* no-mistakes(ci): Made APFS sharing check configured Git hook paths explicitly for both checkout and reference-transaction hooks, and replaced the hardcoded hook separator with filepath.Join. Added end-to-end tests for absolute and relative hooksPath settings. The configured-hook test also passed before the change because Git’s existing path resolution respected hooksPath. Relevant tests and the Windows build pass

* fix: resolve effective Git hooks before APFS sharing

* no-mistakes(document): Clarify APFS sharing documentation and verify lint

* chore(main): release 3.0.0 (kunchenguid#117)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* fix(pool): adopt pre-3.0 state instead of quarantining it as recovered (kunchenguid#156)

* fix(pool): adopt pre-3.0 state on upgrade and free slots 3.0.0 wrongly quarantined

treehouse 3.0.0 treated every valid pre-3.0 state file as untrusted: its
first run leased every worktree in every pool as "recovered: state file was
corrupt or truncated; verify before reuse", so idle slots were never reused
and each new get created a fresh slot instead. The regression came from the
seed-inventory integrity check added in 0e87c62 (kunchenguid#129), which quarantined any
state without the new version and HMAC key.

Pre-3.0 releases never seeded ignored files, so unversioned state with no
treehouse-state.key beside it is now adopted as is on the first run: idle
slots stay available and leases keep their holders. Unversioned state beside
a key was rewritten by an older binary after 3.0 ran and stays quarantined.

Pools that 3.0.0 already rewrote recover on their own. A slot that was idle
or in use before the upgrade is relabeled "quarantined by the 3.0.0 upgrade"
and returns to the pool as soon as the next status or get proves it detached,
clean, merged into its base, and free of running processes; until then it
stays leased. A slot that was leased before the upgrade is relabeled "leased
before the 3.0.0 upgrade" and is never released automatically. Both can be
returned with `treehouse return`. Genuinely corrupt or truncated state is
still quarantined as before.

State is now written as version 5 so a version-4 file is known to come from
3.0.0; treehouse 3.0.0 refuses to read version-5 state rather than
misreading it.

* no-mistakes(review): Keep 3.0.0-quarantined slots leased until explicitly returned

* no-mistakes(review): Treat all 3.0.0-relabeled slots alike; skip them in return --all

* no-mistakes(review): Return recovered slots only by name, never automatically

* no-mistakes(review): Refuse recovered slots under lock in return --all

* no-mistakes(review): Adopt unversioned 2.x rewrites beside key; fix stale return docs

* no-mistakes(review): Document adoption of 2.x rewrites beside key in README

* no-mistakes(review): Rewrite stale return --all recovered-slot skip bullet in README

* no-mistakes(document): Fix stale recovered-slot release doc comments

* no-mistakes(ci): The only failing check is Greptile Review, which raised two findings. Both are fixed with documentation edits only; no Go code changed. - **ci-1 (lost seed inventory after a 2.x rewrite):** Per your decision, I made no code change and documented this as a known limitation. README.md (Recovering missing pool state) and docs/design.md already described the case. Both now label it "known limitation" and state the outcome plainly: if a still-running 2.x binary rewrites the state after 3.x seeded `.worktreeinclude` files into a slot, the record of those files is lost. A later reset won't remove them, so they stay in the slot when it is reused. - **ci-2 (AGENTS.md out of date on recovered slots):** AGENTS.md said to remove a recovered slot with `destroy <path> --include-leased --yes`. I replaced that invariant line with one matching docs/design.md: only a named `return <path>` releases a recovered slot (it warns that seeded files may remain), `destroy <path> --include-leased --yes` removes it instead, and `return --all` skips it. I kept it to one line. I didn't run tests or the linter because the change only touches three Markdown files (one line each)

* chore(main): release 3.0.1 (kunchenguid#157)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* feat(pool): automatically free safe recovered slots (kunchenguid#159)

* fix: auto-recover provably safe quarantined slots

Treehouse 3.0.2 recovers idle, clean, landed Git slots automatically. Untracked files are moved to retained backups; unsafe recoveries remain quarantined with status guidance.

* no-mistakes(review): Run safe recovery on every locked pool command

* no-mistakes(review): Block recovery on submodule edits; name partial backup path

* no-mistakes(review): Reuse one derived backup folder per recovered slot

* no-mistakes(review): Refuse symlinked backups; name backups on state-write failure

* no-mistakes(review): Drop backup naming from state-write errors; document backup path

* no-mistakes(document): Correct stale recovery guidance and verify lint

* no-mistakes(document): Clarify recovered lease guidance and stale return comments

* no-mistakes(review): Keep recovery backup folders owner-only before moving files

* no-mistakes(review): Keep recovered Windows slots with untracked files leased

* no-mistakes(document): Clarify recovery backup guidance and stale comments

* no-mistakes(review): Keep recovered slots with index-hidden tracked edits leased

* no-mistakes(review): Check index-hidden edits inside submodules before freeing slots

* no-mistakes(document): Clarify recovered-slot guidance and pass lint checks

* no-mistakes(document): Clarify recovered-slot documentation and backup comment

* no-mistakes(document): Clarify ordinary lease behavior in README

* no-mistakes(ci): Fixed all three Greptile findings: recovery Git operations now go through internal/vcs; modified or untracked initialized submodules keep recovered slots leased with a specific status reason; backup moves cannot overwrite an occupied destination. Added behavioral tests, passed go test ./... and the Windows build, and replied to each Greptile comment

* chore(main): release 3.1.0 (kunchenguid#160)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* fix(vcs): check recovered HEAD containment with a single rev-list walk (kunchenguid#164)

* fix(pool): check recovered HEAD containment with one rev-list walk

Recovery runs under the state lock before every pool command, and 3.1.0
checked HEAD against each remote-tracking ref with its own merge-base call.
With thousands of remote refs and an unpushed slot HEAD, status/get/return
took ~40 minutes and blocked every other treehouse command (kunchenguid#163).

Ask one question instead: is any commit reachable from HEAD but from no
remote-tracking ref and not from the verified base branch? HEAD is contained
exactly when rev-list succeeds and prints nothing, so the containment answer
is unchanged and git errors still keep the slot quarantined.

* no-mistakes(ci): Added the regression test from the Greptile finding. It lives in internal/vcs/gitvcs/recovery_test.go and is called TestRecoveryHeadContainedGitCallsDoNotGrowWithRemoteRefs. Production code was not changed. The test builds two repos where HEAD has a commit that isn't pushed: one repo has 1 remote-tracking ref and the other has 200, all pointing at main. It creates the 200 refs with a single `git update-ref --stdin` call. It then puts a fake `git` shell script first on PATH, which writes one log line per call and then runs the real git, and calls RecoveryHeadContained(repo, "main") in each repo. The test fails if HEAD is reported as contained, or if the number of git processes differs between the two repos. There are no timing checks, and the test is skipped on Windows because the wrapper is a POSIX shell script. Verification: `go test ./internal/vcs/gitvcs/ -count=1` passes, and so do all the existing RecoveryHeadContained tests. `gofmt -l` reports nothing and `GOOS=windows go vet` is clean. I also swapped in the old per-ref recovery.go from base commit c099281 for one run, then restored it: the new test failed with 'git processes: 5 with 1 remote ref, 204 with 200; want the same count'. So the test catches the old per-ref slowdown

* chore(main): release 3.1.1 (kunchenguid#166)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* fix: add /v3 major version suffix to module path (kunchenguid#167)

Restore Go module path to github.com/kunchenguid/treehouse/v3 so go install @latest delivers the current major (fixes kunchenguid#62).

Mechanical rename across go.mod, all in-repo imports, and the README install line.

* chore(main): release 3.1.2 (kunchenguid#168)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Document shared clone allocation cap and clarify regression coverage

* fix(pool): reclaim safe idle foreign slots at the shared cap

* fix(pool): preserve paused Git operations during reclamation

* no-mistakes(review): Correct foreign-slot reclamation safety and remote containment

* no-mistakes(review): Preserve replacement trees and unseeded ignored data during reclamation

* no-mistakes(document): Consolidate clone allocation and reclamation documentation

* no-mistakes(ci): Fixed ci-1’s two observed failures. The fresh-checkout assertion now uses the existing CRLF-aware assertFileContents helper; sibling checkout assertions already used it, and byte-preservation checks remain unchanged. CI and make test now use an explicit 20-minute per-package timeout instead of Go’s default 10 minutes, retaining all coverage and OS targets. Documented the test budget in CONTRIBUTING.md. No production reclamation behavior changed. Verification passed: all foreign-reclamation tests with core.autocrlf=true (486.829s); go test -timeout 20m ./... (pool package: 874.940s); and GOOS=windows GOARCH=amd64 go build ./.... A real CLI smoke also confirmed foreign feature reclamation, removal of the old checkout, caller ownership of the replacement, and exact base-file bytes hi\r\n. Smoke artifacts were removed. Native Windows test execution remains for the outer CI executor

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Niko Lehtovirta <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Andrew Smith <[email protected]>
MrGTV-love added a commit to MrGTV-love/treehouse that referenced this pull request Oct 8, 2026
* ci: pin require-no-mistakes to v1.80.1 for live PR lookup (kunchenguid#144)

* ci: pin require-no-mistakes to v1.80.1 for live PR lookup

The v1.80.1 verifier reads body and head from one API response and
fails closed without pull-requests: read, so drop the Fetch current
PR body step and its cached event-payload inputs.

* test: lock v1.80.1 live PR lookup on the required-check caller

A pin-only assertion stayed green if the workflow restored cached
PR inputs, restored the fetch step, or dropped pull-requests: read.

* ci: exempt kunchenguid from no-mistakes-required gate (kunchenguid#147)

* fix(pool): reuse a pooled worktree only for the clone that owns it (kunchenguid#145)

* fix(pool): enforce clone identity when reusing Git worktrees

Compare physical Git common directories before resetting or acquiring a
shared-pool slot. Resolve the requester once, normalize symlinks, and
leave foreign or unreadable candidates intact. Explain foreign-clone
capacity exhaustion without misreporting clean slots as dirty or busy.

Apply the comparison symmetrically: an unsupported empty identity only
matches another empty identity. Preserve non-colocated JJ reuse, including
its existing unidentified-clone sharing, without adding a JJ identity
mechanism. Git and colocated JJ require matching physical identities.

Keep pool locations, state, trust checks, and cleanup behavior unchanged.
Cover both acquire modes, capacity, symlinks, unreadable candidates,
existing-state return, and colocated/non-colocated JJ combinations.

* no-mistakes(review): Refuse worktree reuse when clone identity cannot be verified

* no-mistakes(document): Document clone-correct worktree reuse in README and AGENTS

* no-mistakes(ci): Fixed both real failures. The changes are left uncommitted for the executor. I did not push, and I did not touch the PR. 1. Windows CI failure (TestAcquire_CloneIdentityCapacity, pool_test.go:128). The cause was in the test only. Git on Windows checks README out as "hi\r\n", and the test compared it with the literal "hi\n". The test now reads the README bytes BEFORE the rejected foreign acquisition and compares them AFTER. The two new jj tests that compared with the same literal get the same snapshot change: TestAcquireSkipsUnresolvableColocatedJJIdentity and TestAcquireSecondNonColocatedJJCloneRefusedForeignWorkspace. Product behaviour does not change. Proof: with core.autocrlf=true (set through the GIT_CONFIG_COUNT env), the old test fails with the exact CI message ("hi\r\n") for leased=false and leased=true. The new test passes under the same setting. 2. Greptile finding at pool.go:461 (it is a real finding, not a service failure). The code compared clone identity as path strings (candidateDir != commonDir). On a case-insensitive filesystem, one physical clone spelled with different letter case read as "another clone", so the clone could not reuse its own slot. Fix: acquisitionCommonGitDir now returns os.Stat(vcs.CommonGitDir(dir)), and the selector compares with os.SameFile. os.Stat follows symlinks, so symlink aliases still resolve to one identity. The filepath.Abs and EvalSymlinks steps are now redundant, so I removed them. The requester identity is still computed once, outside the loop. Any identity error on either side still means skip (unverifiedClone). Capacity messages are the same. Non-colocated jj still gets no reuse. Nothing is lowercased. The jj test failure messages now print the identity with %v. New regression: TestAcquire_CloneIdentityCaseAlias covers ordinary and durable (lease) acquisition. It rewrites the slot's commondir to an upper-cased spelling and asks as both repo and REPO. It skips only when os.Stat plus os.SameFile shows the filesystem is case-sensitive. Before the fix, both subtests failed on macOS with "1 belong to another clone". After the fix, both pass. The symlink alias, distinct-clone and unreadable-candidate tests still pass. Docs: I made one-line accuracy updates to AGENTS.md (the identity uses os.SameFile, not a string compare) and to the README Clone-correct reuse line (differently cased paths on a case-insensitive filesystem count as one clone). Validation, all local on macOS: - Native go build ./... and go vet ./... pass. - GOOS=windows go build ./... and go vet ./... pass. - Full go test ./... -count=1 passes with the real jj on PATH. All jj clone-identity tests ran; none skipped. No prune/destroy/trust-check changes. No cleanup changes. No new jj identity mechanism

* no-mistakes(ci): No code change is needed. The failing check "Require no-mistakes" (run 35838744065) ended as action_required with zero jobs, so no step ran and nothing failed. The other runs on the same PR head 2a00a9a are in the same state: "CI" (35838743988) and "Nix flake" (35838744043) are both action_required with no jobs. That is GitHub holding workflow runs on a PR from a fork until a maintainer approves them. The new pipeline push created these runs, and none has been approved yet. The local HEAD equals the PR head, so the runs point at the current code but have not executed it. This failure is outside the code under review. Action for the outer executor or owner: a kunchenguid/treehouse maintainer must click "Approve and run workflows" on PR kunchenguid#145. The .gitignore and .ignore changes in the working tree are local graft-cache artifacts and must not be committed

* no-mistakes(ci): Removed stray graft ignore artifacts: restored .gitignore to base content and deleted .ignore, which does not exist on base. PR diff vs base is now exactly AGENTS.md, README.md, internal/pool/clone_identity_jj_test.go, internal/pool/pool.go, internal/pool/pool_test.go. graft/ stays ignored by the repo-local info/exclude. No product or test changes. go build and internal/pool tests pass. CI, Nix flake and Require no-mistakes are action_required with 0 jobs: they wait for a maintainer to approve fork workflow runs on kunchenguid#145. No code fault

* fix(pool): let prune and destroy reclaim worktrees from other clones in a shared pool (kunchenguid#146)

* fix(pool): enforce clone identity when reusing Git worktrees

Compare physical Git common directories before resetting or acquiring a
shared-pool slot. Resolve the requester once, normalize symlinks, and
leave foreign or unreadable candidates intact. Explain foreign-clone
capacity exhaustion without misreporting clean slots as dirty or busy.

Apply the comparison symmetrically: an unsupported empty identity only
matches another empty identity. Preserve non-colocated JJ reuse, including
its existing unidentified-clone sharing, without adding a JJ identity
mechanism. Git and colocated JJ require matching physical identities.

Keep pool locations, state, trust checks, and cleanup behavior unchanged.
Cover both acquire modes, capacity, symlinks, unreadable candidates,
existing-state return, and colocated/non-colocated JJ combinations.

* no-mistakes(review): Refuse worktree reuse when clone identity cannot be verified

* no-mistakes(document): Document clone-correct worktree reuse in README and AGENTS

* fix(pool): enforce clone identity when reusing Git worktrees

Compare physical Git common directories before resetting or acquiring a
shared-pool slot. Resolve the requester once, normalize symlinks, and
leave foreign or unreadable candidates intact. Explain foreign-clone
capacity exhaustion without misreporting clean slots as dirty or busy.

Apply the comparison symmetrically: an unsupported empty identity only
matches another empty identity. Preserve non-colocated JJ reuse, including
its existing unidentified-clone sharing, without adding a JJ identity
mechanism. Git and colocated JJ require matching physical identities.

Keep pool locations, state, trust checks, and cleanup behavior unchanged.
Cover both acquire modes, capacity, symlinks, unreadable candidates,
existing-state return, and colocated/non-colocated JJ combinations.

* no-mistakes(review): Refuse worktree reuse when clone identity cannot be verified

* no-mistakes(document): Document clone-correct worktree reuse in README and AGENTS

* fix(pool): reclaim foreign-clone worktrees

Resolve cleanup context and VCS removal ownership from each managed
worktree path so shared pools can prune and destroy slots from multiple
clones while unresolved paths remain untouched and reported.

* no-mistakes(document): Document per-worktree repository resolution for prune and destroy

* no-mistakes(ci): Fixed Greptile finding ci-5 with the smallest change. What I changed: 1. internal/pool/prune.go, `worktreePruneContextResolver`: when fetch or default-ref resolution fails, it now returns `pruneContext{RepoRoot: repoRoot}` with the error. It used to return an empty context. The cached-error path does the same thing now. DefaultRef stays empty. 2. internal/pool/destroy.go:214: I updated the comment. It now says that a failure leaves the default ref empty. 3. internal/pool/pool_test.go: I added `TestWorktreePruneContextResolverKeepsRootWhenFetchFails`. It points origin at a missing path and calls the resolver two times. The second call reads the cached error. Each call must return an error, the resolved root, and an empty DefaultRef. Effect: `classifyForDestroy` gets the root again, so it can set `OtherFlavor` and show the "destroy it and migrate the pool" hint. With an empty DefaultRef the slot is still `DestroyUnverified`, so deletion is still refused. Prune does not change: at prune.go:704 it throws away the context when there is an error. No new resolver or abstraction was added. Checks I ran: - Without the fix, the new test fails (`got RepoRoot:""`). With the fix, it passes. - `go test ./... -count=1`: all packages pass. - `go vet ./internal/pool/` passes. `gofmt -l` finds nothing. `GOOS=windows go build ./...` passes. I did not commit the changes. They are in the working tree

* no-mistakes(ci): Fixed both real failures. The changes are left uncommitted for the executor. I did not push, and I did not touch the PR. 1. Windows CI failure (TestAcquire_CloneIdentityCapacity, pool_test.go:128). The cause was in the test only. Git on Windows checks README out as "hi\r\n", and the test compared it with the literal "hi\n". The test now reads the README bytes BEFORE the rejected foreign acquisition and compares them AFTER. The two new jj tests that compared with the same literal get the same snapshot change: TestAcquireSkipsUnresolvableColocatedJJIdentity and TestAcquireSecondNonColocatedJJCloneRefusedForeignWorkspace. Product behaviour does not change. Proof: with core.autocrlf=true (set through the GIT_CONFIG_COUNT env), the old test fails with the exact CI message ("hi\r\n") for leased=false and leased=true. The new test passes under the same setting. 2. Greptile finding at pool.go:461 (it is a real finding, not a service failure). The code compared clone identity as path strings (candidateDir != commonDir). On a case-insensitive filesystem, one physical clone spelled with different letter case read as "another clone", so the clone could not reuse its own slot. Fix: acquisitionCommonGitDir now returns os.Stat(vcs.CommonGitDir(dir)), and the selector compares with os.SameFile. os.Stat follows symlinks, so symlink aliases still resolve to one identity. The filepath.Abs and EvalSymlinks steps are now redundant, so I removed them. The requester identity is still computed once, outside the loop. Any identity error on either side still means skip (unverifiedClone). Capacity messages are the same. Non-colocated jj still gets no reuse. Nothing is lowercased. The jj test failure messages now print the identity with %v. New regression: TestAcquire_CloneIdentityCaseAlias covers ordinary and durable (lease) acquisition. It rewrites the slot's commondir to an upper-cased spelling and asks as both repo and REPO. It skips only when os.Stat plus os.SameFile shows the filesystem is case-sensitive. Before the fix, both subtests failed on macOS with "1 belong to another clone". After the fix, both pass. The symlink alias, distinct-clone and unreadable-candidate tests still pass. Docs: I made one-line accuracy updates to AGENTS.md (the identity uses os.SameFile, not a string compare) and to the README Clone-correct reuse line (differently cased paths on a case-insensitive filesystem count as one clone). Validation, all local on macOS: - Native go build ./... and go vet ./... pass. - GOOS=windows go build ./... and go vet ./... pass. - Full go test ./... -count=1 passes with the real jj on PATH. All jj clone-identity tests ran; none skipped. No prune/destroy/trust-check changes. No cleanup changes. No new jj identity mechanism

* no-mistakes(ci): No code change is needed. The failing check "Require no-mistakes" (run 35838744065) ended as action_required with zero jobs, so no step ran and nothing failed. The other runs on the same PR head 2a00a9a are in the same state: "CI" (35838743988) and "Nix flake" (35838744043) are both action_required with no jobs. That is GitHub holding workflow runs on a PR from a fork until a maintainer approves them. The new pipeline push created these runs, and none has been approved yet. The local HEAD equals the PR head, so the runs point at the current code but have not executed it. This failure is outside the code under review. Action for the outer executor or owner: a kunchenguid/treehouse maintainer must click "Approve and run workflows" on PR kunchenguid#145. The .gitignore and .ignore changes in the working tree are local graft-cache artifacts and must not be committed

* no-mistakes(ci): Removed stray graft ignore artifacts: restored .gitignore to base content and deleted .ignore, which does not exist on base. PR diff vs base is now exactly AGENTS.md, README.md, internal/pool/clone_identity_jj_test.go, internal/pool/pool.go, internal/pool/pool_test.go. graft/ stays ignored by the repo-local info/exclude. No product or test changes. go build and internal/pool tests pass. CI, Nix flake and Require no-mistakes are action_required with 0 jobs: they wait for a maintainer to approve fork workflow runs on kunchenguid#145. No code fault

* no-mistakes(ci): Fixed Greptile ci-4 (clone identity is out of scope). The changes are left uncommitted in the working tree so the executor can make one forward commit. I did no rebase, reset, amend or force-push, and I did not push. What I removed (clone-identity work from PR 145): 1. internal/pool/pool.go: restored to the base version (38f8192). This removes acquisitionCommonGitDir, the otherClone/unverifiedClone skip in acquire, and the clone-identity capacity error. The reclaim commits never changed pool.go. 2. internal/pool/clone_identity_jj_test.go: deleted (git rm). It held only clone-identity jj acquire tests. 3. internal/pool/pool_test.go: removed assertCloneCommonDir, TestAcquire_CloneIdentity, TestAcquire_CloneIdentityCapacity, TestAcquire_CloneIdentitySymlinkAlias, TestAcquire_CloneIdentityCaseAlias, TestAcquire_CloneIdentityUnreadableCandidate and TestRelease_CloneIdentityExistingState. Also removed the vcs import, which nothing else uses. 4. AGENTS.md: the "Acquire reuses a slot only when..." line is back to the base text. 5. README.md: the reuse flow diagram is back to the base text, and the "Clone-correct reuse" bullet is gone. What I kept (reclaim work): - The per-worktree root resolution in destroy.go and prune.go, and the fix that keeps the root when fetch fails. - Their tests: TestDestroyPoolRemovesWorktreesOwnedByDifferentClones, TestDestroyPoolRefusesUnattributableWorktreePerPath, TestPruneRemovesWorktreesOwnedByDifferentClones, TestWorktreePruneContextResolverKeepsRootWhenFetchFails, and the updated executeDestroy tests. - Their docs: the AGENTS.md prune/destroy line and the README prune/destroy paragraphs. - The shared test helper setupSharedClonePool, because the reclaim tests need it. I changed only its comment. acquireDisposableFromEachClone does not need clone identity: clone B gets a new slot because clone A's slot is still reserved. The diff against base 38f8192 now touches only AGENTS.md, README.md, internal/pool/destroy.go, internal/pool/prune.go, internal/pool/pool_test.go and internal/pool/worktree_path_test.go. .gitignore and .ignore are not in it. The separation was clean, with no conflicts. Checks run on macOS: - go build ./... passed. - go vet ./... passed. - GOOS=windows go build ./... and GOOS=windows go vet ./... passed. - gofmt -l printed nothing. - go test ./... -count=1 passed in every package. - All reclaim tests ran and passed (verbose run). Gap: I could not run the real-jj tests. jj is not on PATH on this machine, and the workspace rules do not let me install it, so 23 jj tests skipped. The jj tests I deleted covered clone identity only. No jj code path changed in this round

* Restore upstream workflow exemption after merge

Keep the PR diff scoped to foreign-slot reclaim by restoring the
kunchenguid exemption already present on upstream main.

* fix(pool): avoid resolving markerless destroy targets

Keep damaged slots out of per-path repository resolution so destroy cannot
fetch an unrelated repository enclosing the pool. Restore real Git removal
refusal coverage for state and owner-reservation recovery.

---------

Co-authored-by: Kun Chen <[email protected]>

* feat: add opt-in branch creation to treehouse get (kunchenguid#150)

* feat(get): create branches on acquisition

Add an opt-in branch flag so agents can commit on a named branch immediately. Preserve hook output and quarantine unsafe slots when branch creation fails.

* fix(get): quarantine failed branch hook output

Inspect recycled slots after branch creation fails so ignored hook files cannot leak into the next acquisition. Keep clean branch-name collisions reusable and cover the rejecting hook path.

* no-mistakes(review): Preserve branch-failure diagnostics and hook-modified seeds

* no-mistakes(review): Keep recycled slots reusable and limit checkout diagnostics

* no-mistakes(review): Preserve checkout diagnostics and validate branch base before handoff

* no-mistakes(review): Report checkout hook diagnostics without changing lease output

* no-mistakes(review): Remove hook-bypassing detach retry

* no-mistakes(review): Restore ordinary detach hook failure reporting

* no-mistakes(document): Clarify branch acquisition and return documentation

* no-mistakes(ci): The Windows test failure came from hook detection relying on Unix executable permission bits. Git for Windows can run the reference-transaction hook even though those bits are not exposed, so the failed branch creation removed a slot that should have been quarantined. Hook detection now treats a regular hook file as runnable on Windows. The two targeted reference-transaction tests pass locally, and the project cross-compiles for Windows. The failing scenario has not been rerun on Windows

* no-mistakes(ci): Fixed the branch-name collision race: when branch creation fails before checkout, a post-checkout hook’s presence no longer quarantines an otherwise clean slot. Reference-transaction hook output remains protected. Added a regression that creates the collision after the initial check and confirms a max_trees=1 pool remains usable. Gated Unix-shell hook fixtures on Windows; non-hook branch coverage remains enabled. Relevant Go packages passed locally, and their tests cross-compiled for Windows. The tests were not executed on Windows

* feat(get): create branches on acquisition

Add an opt-in branch flag so agents can commit on a named branch immediately. Preserve hook output and quarantine unsafe slots when branch creation fails.

* no-mistakes(review): Restore detach errors and remove unused output inspection

* no-mistakes(review): Preserve checkout hook stderr in branch failure diagnostics

* no-mistakes(review): Restore failed Git command output behavior

* no-mistakes(document): Clarify branch collision and base-name guidance

* docs: trim agent guide and preserve design notes (kunchenguid#152)

* docs: trim AGENTS.md to every-session rules, move design notes to docs/design.md

AGENTS.md: 123 lines / 5177 words / 35817 bytes -> 48 lines / 469 words / 3305 bytes.
The Key Design Decisions and Contribution Gate maintainer detail moved verbatim
(em dashes normalized, README links re-rooted) to docs/design.md.

* no-mistakes(document): Correct pruning documentation and pass lint

* no-mistakes(ci): Updated AGENTS.md to distinguish confirmed dirty returns from fail-closed reuse and cleanup, and to document the inspected, named-destroy path for recovered quarantined slots. git diff --check and go test ./... passed

* feat(fileclone): add opt-in APFS sharing for fresh Git worktrees (kunchenguid#153)

* feat: add opt-in APFS sharing for fresh Git slots

* no-mistakes(document): Correct APFS metadata guidance and consolidate config documentation

* no-mistakes(ci): Fixed the Windows test failure by making the tracked test asset binary, preventing Git CRLF conversion from changing its checkout bytes. Reproduced the failure before the fix and passed the APFS CLI tests with CRLF conversion enabled afterward. Related package tests and the Windows build passed

* no-mistakes(ci): Made APFS sharing check configured Git hook paths explicitly for both checkout and reference-transaction hooks, and replaced the hardcoded hook separator with filepath.Join. Added end-to-end tests for absolute and relative hooksPath settings. The configured-hook test also passed before the change because Git’s existing path resolution respected hooksPath. Relevant tests and the Windows build pass

* fix: resolve effective Git hooks before APFS sharing

* no-mistakes(document): Clarify APFS sharing documentation and verify lint

* chore(main): release 3.0.0 (kunchenguid#117)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* fix(pool): adopt pre-3.0 state instead of quarantining it as recovered (kunchenguid#156)

* fix(pool): adopt pre-3.0 state on upgrade and free slots 3.0.0 wrongly quarantined

treehouse 3.0.0 treated every valid pre-3.0 state file as untrusted: its
first run leased every worktree in every pool as "recovered: state file was
corrupt or truncated; verify before reuse", so idle slots were never reused
and each new get created a fresh slot instead. The regression came from the
seed-inventory integrity check added in 0e87c62 (kunchenguid#129), which quarantined any
state without the new version and HMAC key.

Pre-3.0 releases never seeded ignored files, so unversioned state with no
treehouse-state.key beside it is now adopted as is on the first run: idle
slots stay available and leases keep their holders. Unversioned state beside
a key was rewritten by an older binary after 3.0 ran and stays quarantined.

Pools that 3.0.0 already rewrote recover on their own. A slot that was idle
or in use before the upgrade is relabeled "quarantined by the 3.0.0 upgrade"
and returns to the pool as soon as the next status or get proves it detached,
clean, merged into its base, and free of running processes; until then it
stays leased. A slot that was leased before the upgrade is relabeled "leased
before the 3.0.0 upgrade" and is never released automatically. Both can be
returned with `treehouse return`. Genuinely corrupt or truncated state is
still quarantined as before.

State is now written as version 5 so a version-4 file is known to come from
3.0.0; treehouse 3.0.0 refuses to read version-5 state rather than
misreading it.

* no-mistakes(review): Keep 3.0.0-quarantined slots leased until explicitly returned

* no-mistakes(review): Treat all 3.0.0-relabeled slots alike; skip them in return --all

* no-mistakes(review): Return recovered slots only by name, never automatically

* no-mistakes(review): Refuse recovered slots under lock in return --all

* no-mistakes(review): Adopt unversioned 2.x rewrites beside key; fix stale return docs

* no-mistakes(review): Document adoption of 2.x rewrites beside key in README

* no-mistakes(review): Rewrite stale return --all recovered-slot skip bullet in README

* no-mistakes(document): Fix stale recovered-slot release doc comments

* no-mistakes(ci): The only failing check is Greptile Review, which raised two findings. Both are fixed with documentation edits only; no Go code changed. - **ci-1 (lost seed inventory after a 2.x rewrite):** Per your decision, I made no code change and documented this as a known limitation. README.md (Recovering missing pool state) and docs/design.md already described the case. Both now label it "known limitation" and state the outcome plainly: if a still-running 2.x binary rewrites the state after 3.x seeded `.worktreeinclude` files into a slot, the record of those files is lost. A later reset won't remove them, so they stay in the slot when it is reused. - **ci-2 (AGENTS.md out of date on recovered slots):** AGENTS.md said to remove a recovered slot with `destroy <path> --include-leased --yes`. I replaced that invariant line with one matching docs/design.md: only a named `return <path>` releases a recovered slot (it warns that seeded files may remain), `destroy <path> --include-leased --yes` removes it instead, and `return --all` skips it. I kept it to one line. I didn't run tests or the linter because the change only touches three Markdown files (one line each)

* chore(main): release 3.0.1 (kunchenguid#157)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* feat(pool): automatically free safe recovered slots (kunchenguid#159)

* fix: auto-recover provably safe quarantined slots

Treehouse 3.0.2 recovers idle, clean, landed Git slots automatically. Untracked files are moved to retained backups; unsafe recoveries remain quarantined with status guidance.

* no-mistakes(review): Run safe recovery on every locked pool command

* no-mistakes(review): Block recovery on submodule edits; name partial backup path

* no-mistakes(review): Reuse one derived backup folder per recovered slot

* no-mistakes(review): Refuse symlinked backups; name backups on state-write failure

* no-mistakes(review): Drop backup naming from state-write errors; document backup path

* no-mistakes(document): Correct stale recovery guidance and verify lint

* no-mistakes(document): Clarify recovered lease guidance and stale return comments

* no-mistakes(review): Keep recovery backup folders owner-only before moving files

* no-mistakes(review): Keep recovered Windows slots with untracked files leased

* no-mistakes(document): Clarify recovery backup guidance and stale comments

* no-mistakes(review): Keep recovered slots with index-hidden tracked edits leased

* no-mistakes(review): Check index-hidden edits inside submodules before freeing slots

* no-mistakes(document): Clarify recovered-slot guidance and pass lint checks

* no-mistakes(document): Clarify recovered-slot documentation and backup comment

* no-mistakes(document): Clarify ordinary lease behavior in README

* no-mistakes(ci): Fixed all three Greptile findings: recovery Git operations now go through internal/vcs; modified or untracked initialized submodules keep recovered slots leased with a specific status reason; backup moves cannot overwrite an occupied destination. Added behavioral tests, passed go test ./... and the Windows build, and replied to each Greptile comment

* chore(main): release 3.1.0 (kunchenguid#160)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* fix(vcs): check recovered HEAD containment with a single rev-list walk (kunchenguid#164)

* fix(pool): check recovered HEAD containment with one rev-list walk

Recovery runs under the state lock before every pool command, and 3.1.0
checked HEAD against each remote-tracking ref with its own merge-base call.
With thousands of remote refs and an unpushed slot HEAD, status/get/return
took ~40 minutes and blocked every other treehouse command (kunchenguid#163).

Ask one question instead: is any commit reachable from HEAD but from no
remote-tracking ref and not from the verified base branch? HEAD is contained
exactly when rev-list succeeds and prints nothing, so the containment answer
is unchanged and git errors still keep the slot quarantined.

* no-mistakes(ci): Added the regression test from the Greptile finding. It lives in internal/vcs/gitvcs/recovery_test.go and is called TestRecoveryHeadContainedGitCallsDoNotGrowWithRemoteRefs. Production code was not changed. The test builds two repos where HEAD has a commit that isn't pushed: one repo has 1 remote-tracking ref and the other has 200, all pointing at main. It creates the 200 refs with a single `git update-ref --stdin` call. It then puts a fake `git` shell script first on PATH, which writes one log line per call and then runs the real git, and calls RecoveryHeadContained(repo, "main") in each repo. The test fails if HEAD is reported as contained, or if the number of git processes differs between the two repos. There are no timing checks, and the test is skipped on Windows because the wrapper is a POSIX shell script. Verification: `go test ./internal/vcs/gitvcs/ -count=1` passes, and so do all the existing RecoveryHeadContained tests. `gofmt -l` reports nothing and `GOOS=windows go vet` is clean. I also swapped in the old per-ref recovery.go from base commit c099281 for one run, then restored it: the new test failed with 'git processes: 5 with 1 remote ref, 204 with 200; want the same count'. So the test catches the old per-ref slowdown

* chore(main): release 3.1.1 (kunchenguid#166)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* fix: add /v3 major version suffix to module path (kunchenguid#167)

Restore Go module path to github.com/kunchenguid/treehouse/v3 so go install @latest delivers the current major (fixes kunchenguid#62).

Mechanical rename across go.mod, all in-repo imports, and the README install line.

* chore(main): release 3.1.2 (kunchenguid#168)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Niko Lehtovirta <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Andrew Smith <[email protected]>
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