I'm seeing "UserPromptSubmit hook timed out after 30s — output discarded. Raise the hook's "timeout" to allow more time." running claude with entire hooks in this folder, any idea why?
Assistant
I'll dig into the hook setup and what the UserPromptSubmit path actually does.
Assistant
scripts/entire-dev is the key — let me look.
Assistant
Two 5-second gaps inside the hook itself. Let me separate compile overhead from the hook's own work and get debug timings.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Compile isn't the problem — the hook itself burns 11s, 9.8s of it in system (syscall/filesystem) time. Let me find where.
Assistant
Two identical ~5.2s gaps, both CPU-burning syscalls. Let me check the repo's ref situation — this repo uses the git-refs checkpoint backend.
Assistant
That's the smell: 3.1 GB .git with 117 packfiles, one of them 2.06 GB. go-git scans pack indexes on object access. Let me confirm.
Assistant
116 packs / 6.3 MB of index — and exactly two ~5.2s gaps, which looks like two repository opens. Let me measure a bare go-git open in this repo.
Assistant
Confirmed.worktree.Status() takes 5.25s (vs git status at 0.013s), and the hook calls it twice. Let me find why go-git is so slow here.
Assistant
e2e/ holds 19,134 files out of 22,515 in the worktree — while only 1,367 are tracked. Let me see what's accumulating there.
Assistant
e2e/artifacts/ = 19,071 files / 114 MB of accumulated test artifacts. Let me confirm how it's ignored and whether go-git honors it.
Assistant
e2e/artifacts/is ignored (.gitignore:53), yet go-git still spends 5.2s. Let me isolate which part of go-git's Status is burning the time.
Assistant
15,364 directories under e2e/artifacts. Let me confirm that's what go-git is walking.
Assistant
Decisive: 1.75s of that 2.8s is go-git walking 15,364 ignored e2e/artifacts directories to find zero patterns. Let me verify the fix by temporarily moving the dir aside (same filesystem, restored unconditionally).
Assistant
Cleaning up my probe, then pinpointing the code path.
Assistant
Confirmed the whole chain. Cleanup verified — my probe dir is gone and e2e/artifacts is restored (45 dirs).
What's happening
Your e2e/artifacts/ directory has grown to 19,071 files across 15,364 directories (114 MB, 45 canary runs going back to May). It's correctly gitignored (.gitignore:53) — but go-git doesn't skip it.
Measured in your repo right now:
operation
time
git status --porcelain (CLI)
0.013s
go-git worktree.Status()
5.25s
gitignore.ReadPatterns alone
2.81s — of which 1.75s is descending e2e/artifacts to find 0 patterns
go-git Status() with artifacts moved aside
0.065s (80× faster)
go-git's Worktree.Status() recursively walks every directory looking for nested .gitignore files before it can apply ignore rules, then walks the tree again for untracked files. 15,364 throwaway directories get fully traversed twice.
Then the UserPromptSubmit hook calls it twice — DetectFileChanges (cmd/entire/cli/state.go:277) and getUntrackedFilesForState (cmd/entire/cli/state.go:448), each opening the repo independently. That's the two ~5.2s gaps I see in the debug log:
End-to-end the hook takes ~11.4s of which 9.8s is system (syscall) time — pure directory walking.
Why it tips over 30s rather than just being slow: this repo has "local_dev": true, so hooks run via scripts/entire-dev, which does go buildthengo run on every invocation. Warm that's ~1s. But your last commit (773db0d34) bumped Go 1.26.4 → 1.26.5, which invalidates the entire build cache — the first hook after that rebuilds the whole dependency tree. 11s of tree-walking plus a cold Go rebuild clears 30s easily. I didn't measure the cold rebuild since it'd mean wiping your build cache.
Merged 2026-07-30 — and it targets exactly the function I measured. Let me see the diff and whether we already have it.
Assistant
alpha.5 was tagged 2026-07-29 11:36; the PR was opened at 17:12 that day and merged the next. So we don't have it. But I want to check whether it actually fixes our case — let me benchmark against real go-git main.
Assistant
Newest tag is still alpha.5 — the fix is unreleased, main-only. Now let me measure it against your actual repo.
Assistant
Baseline reproduced outside our CLI. Now the same probe against go-git main with #2284 merged.
Assistant
Real 2.1× win on your repo. Let me verify the structural limitation that remains — whether a root .gitignore entry prunes the walk at all.
Assistant
Pruning worked there. But our pattern is nested (e2e/artifacts/, not artifacts/). Let me test that exact shape.
Assistant
Root cause isolated. Same 3000 dirs: top-level pattern big/ → 0ms (pruned); nested pattern e2e/artifacts/ → 121ms (full descent). Let me verify the implied workaround.
Assistant
Workaround confirmed in isolation. Now the decisive test — on your real repo, with no dependency change at all.
Assistant
Repo is clean — all temp files removed.
What the PR does
go-git#2284 (merged 2026-07-30) makes ReadPatterns call ReadDir first and open .gitignore only when it's actually in the listing, instead of blindly attempting to open <dir>/.gitignore and <dir>/.git/info/exclude in every directory. It also scopes .git/info/exclude to the walk root, matching reference git.
It's real and it helps us — that's the exact function I measured at 2.26s. We don't have it:alpha.5 was tagged 2026-07-29 11:36, the PR was opened at 17:12 the same day. alpha.5 is still the newest tag, so it's main-only.
I benchmarked both against your actual repo:
ReadPatterns
Worktree.Status()
alpha.5 (what we use)
2.26s
5.24s
go-git main @ cf4d91c7 (#2284)
0.85s
2.47s
A genuine 2.1×. It would take the hook from ~11.4s to ~6s — under the 30s timeout, but still ~190× slower than git status.
But it doesn't fix our actual bug
Chasing this turned up the real defect, which #2284 leaves untouched. ReadPatterns recurses with ReadPatterns(fs, append(path, fi.Name())) — it never passes the accumulated patterns down. Each recursive call rebuilds ps from only that directory's own ignore files. So the prune check NewMatcher(ps).Match(...) can only ever match patterns from the current directory, not inherited ones.
Consequence: an ignore rule prunes the walk only if its target is a direct child of the .gitignore that declares it. Same 3,000-directory tree, on go-git main:
root .gitignore = big/ → 0ms, pruned correctly
root .gitignore = e2e/artifacts/ → 121ms, full descent into all 3,000 dirs
Reference git treats both identically. Ours is the second shape — e2e/artifacts/ at .gitignore:53 is one level too deep to ever prune, which is why go-git walks all 15,364 directories. The PR author flags this as unfixed:
User
/copy
copy
User
let's do 1+2 now in a new branch. This way we can work on a go-git fix and still have the setup to validate it helps since the artifacts are still gathering
Assistant
Doing both. Branch first, then let me read the full picture in state.go.
Assistant
Now let me understand the two Status() call sites and who calls them.
Assistant
getUntrackedFilesForState has two different callers (pre-prompt vs pre-task), so those aren't the pair. Let me trace what the UserPromptSubmit hook actually calls.
Assistant
There are perf spans on this path. Let me get exact attribution rather than infer.
Assistant
Both call sites confirmed on the TurnStart path, in different packages:
gap 1 → getUntrackedFilesForState (state.go:453), via CapturePrePromptState
gap 2 → calculatePromptAttributionAtStart (manual_commit_hooks.go:2501)
Starting with fix 1.
Assistant
Git semantics preserved, artifacts still in place for validating a future go-git fix. Now fix 2 — let me read both call sites in full.
Assistant
gitrepo is imported by both cli and strategy and only depends on paths — the natural home, and it's already the single source of truth for opening repos. Let me check its imports and the v6 API shape.
Assistant
Now the shared status helper.
Assistant
Now wire up the two call sites.
Assistant
Now the strategy-side call site.
Assistant
Now install the cache on the TurnStart path — the window I verified the worktree can't change in.
Assistant
Build's clean. Now a test for the cache.
Assistant
testutil imports gitrepo, so I'll use an external test package to avoid the cycle.
Assistant
All pass. Now the real end-to-end measurement on the actual hook.
Assistant
Hook is 11.36s → 0.91s. Second Status is now a cache hit (5.18s → 0.015s). Running the required checks.
Assistant
Lint clean on the formatted tree. Now the full test suite.
Assistant
Canary passed (59 + 4 tests). Let me confirm the unit and integration phases explicitly, since the tail scrolled past them.
Assistant
All green: 8,534 unit + 448 integration + 63 canary, all exit 0. Final verification of the actual fix state:
Assistant
Artifacts grew to 15,742 subdirs during the test run and the hook stayed at 0.9s — the fix holds as they accumulate. Final diff review:
Assistant
Both fixes are in on soph/gitignore-status-perf, committed as 6ddce4747.
Results
Hook wall time on your repo: 11.36s → 0.91s
code
before after
0.000 turn-start 0.000 turn-start
5.257 ApplyTransition 0.123 ApplyTransition
0.000 phase transition 0.000 phase transition
5.184 initialized shadow 0.015 initialized shadow ← cache hit
Fix 1 — .gitignore placement
Moved the rule to e2e/.gitignore as artifacts/ so it's a direct child of its declaring .gitignore, which is the shape go-git can actually prune on. Left a comment in the root .gitignore explaining why it isn't there, since it looks like an accident otherwise. Git reports the directory as ignored either way (e2e/.gitignore:10).
Fix 2 — gitrepo.Status
New cmd/entire/cli/gitrepo/status.go. gitrepo was the right home — both cli and strategy already import it, it only depends on paths, and it's already the single source of truth for opening repos.
gitrepo.Status(ctx, repo) memoizes when the context carries a cache from WithStatusCache, keyed on worktree root (the two callers open the repo independently, so a pointer key wouldn't match). handleLifecycleTurnStart installs the cache.
I scoped the cache to TurnStart deliberately rather than all hooks: TurnStart fires before the agent acts and only writes under .entire/ and .git/ (both ignored/invisible to git status), so the status provably can't change mid-hook. Post-agent hooks like TurnEnd would be unsafe, so DetectFileChanges is untouched. That constraint is documented on WithStatusCache.
Four tests in an external gitrepo_test package (testutil imports gitrepo, so in-package would cycle). The memoization test proves reuse by mutating the worktree between calls — a recomputed walk would see the new file.
Verification
mise run fmt && mise run lint clean (one errcheck fix on a comma-ok assertion, re-linted after formatting), then 8,534 unit + 448 integration + 63 canary, all exit 0. Artifacts grew to 15,742 subdirs during the run and the hook stayed at 0.9s.
Note on the go-git side
Your setup for validating a go-git fix is intact — artifacts still accumulating, and the pathological shape is reproducible on demand by moving the rule back to the root .gitignore. The reproducer is minimal: 3,000 dirs under a nested-pattern-ignored directory, 0ms vs 121ms on main.
Worth noting #2284's benchmark wouldn't catch this — its tree uses root-level ignore files, exactly the case that already prunes. Want me to open the upstream issue with that reproducer?
User
simplify
/simplify
Assistant
I'll gather the diff, then run the four cleanup reviews in parallel.
Assistant
Scope is main...HEAD, working tree clean. Launching the four reviews in parallel.
Assistant
All four reviews are running in the background. Waiting for them to complete before applying anything.
Assistant
The four reviews are running concurrently — I'll apply fixes once all four report back. No need for me to touch the same files in the meantime.
Assistant
Simplification review is in with 7 findings — including two real defects in my own test file (a stale function name in a doc comment, and a test that can't fail for the regression it names). Waiting on the remaining three before I dedup and apply.
Assistant
Altitude review is a significant one — it found in-repo precedent (ephemeral.go:1116, manual_commit_hooks.go:2550) where the team already concluded go-git's Status() is the wrong tool, plus an existing forbidigo mechanism for enforcing exactly this. Still waiting on reuse and efficiency before I dedup.
Assistant
Reuse review found that initRepoWithFile already exists at gitrepo/repository_test.go:262 — my external test package and its import-cycle workaround were unnecessary. One agent left.
Assistant
The efficiency agent died with the previous process. Let me run that angle myself — it's a bounded set of checks.
Assistant
Efficiency angle checked myself: all calculatePromptAttributionAtStart calls share the cache (same ctx), and repo.Worktree() re-parses config on every call including cache hits — minor, and moot if the cache goes. Three remaining Status() call sites confirmed at rewind.go:1094, state.go:278, strategy/common.go:1192.
Let me look at the existing test helper before rewriting.
Assistant
Now applying. Test file first — into package gitrepo using the existing helper.
Assistant
Now simplifying status.go — drop the error caching, the unreachable nil check, and the redundant doc paragraph.
Assistant
Now migrating the three remaining call sites so the "single entry point" claim is actually true.
Assistant
Both already import gitrepo and have ctx in scope. Now the forbidigo rule to enforce the convention.
Assistant
Rule added and lint is clean — but I must verify the rule actually fires, otherwise it's decoration.
Assistant
Rule fires correctly, state.go restored. Now the documentation the conventions need to survive.
Assistant
Now the full suite, since I touched rewind.go, state.go, and strategy/common.go.
Assistant
All green, hook still fast. Final diff review:
Assistant
Cleanup applied and committed as 45406d520. Three of four agents reported; the efficiency agent died with a process restart, so I ran that angle myself.
Fixed
Simplification
Dropped statusResult — it existed only to memoize errors, which both callers treat as "skip". Now caches successes only.
Removed the unreachable cache == nil half of the type-assertion guard.
Trimmed the doc block paragraph that restated the function's own comment.
Reuse — the strongest single finding: initRepoWithFile already existed at gitrepo/repository_test.go:262. My external gitrepo_test package, its testutil import, the import-cycle justification comment, and a duplicated repo-setup helper all existed only because I didn't look. Tests moved into package gitrepo (matching both sibling test files) and folded into one table-driven test. Net −203/+57 lines.
Two real defects in my own test file
A doc comment naming TestStatus_CachePrunesIgnoredSubtreeRule, a function that doesn't exist.
That test claimed to guard the .gitignore placement but only asserted go-git honors a nested .gitignore — which passes identically with the rule in either location. It could not fail for the regression it named. Deleted rather than left as false assurance.
Altitude — my package doc claimed Status was "the single entry point" while three call sites bypassed it. I made the claim true instead of weakening it:
Migrated DetectFileChanges, checkCanRewindWithWarning, checkResetSafety. Behavior-preserving: with no cache in ctx, gitrepo.Statusisworktree.Status(), and none of those paths install one — so DetectFileChanges on the post-agent TurnEnd path still sees fresh state.
Added a forbidigo rule alongside the existing Reset/Checkout ones. I verified it fires rather than assuming — reintroducing a bare call reports at state.go:278.
Documented both conventions in CLAUDE.md under Git Operations.
Re-verified: 8,534 unit + 448 integration pass, lint clean after fmt, hook at 0.76s.
Skipped — and it's the finding you should weigh
User
no, we are also maintaining go-git and the idea is to fix it properly there. I'd rather have a summary of the issue again so I can start working on that repo in a new clean session next
Assistant
Good — that's the right fix. Let me nail down the specifics so the handoff is accurate, including whether fixing ReadPatterns alone is even sufficient.
Assistant
Defect confirmed on current main. Now — is fixing ReadPatterns even sufficient? Only 2.26s of the 5.25s was ReadPatterns. Let me find the rest.
Assistant
Key distinction: the diff walk gets the full union of patterns, so it prunes correctly regardless of placement. So where's the other ~3s? Let me check Status() itself.
Assistant
Let me profile precisely, on a synthetic repo reproducing the nested-pattern case — this is the number that matters for scoping the go-git fix.
Assistant
The profile is decisive — 100% of Status()'s CPU is inside collectIgnorePatterns → ReadPatterns; the diff walk doesn't register at all, because its IgnoreMatcher gets the full union and prunes correctly. Let me check the one edge case that could complicate the fix: negation patterns.
Assistant
Confirmed the key semantic: git does not re-include a file under an excluded directory, so pruning excluded dirs is exactly correct git behavior — the fix widens the existing prune rather than introducing new risk. Let me put the handoff somewhere durable.
User
[Request interrupted by user for tool use]
User
can you just post it here in the chat, no need to put it in a file
for _, fi := range fis {
if fi.IsDir() && fi.Name() != gitDir {
if NewMatcher(ps).Match(append(path, fi.Name()), true) {
continue // prune
}
subps, err = ReadPatterns(fs, append(path, fi.Name())) // ← ps not passed
...
}
}
The recursive call doesn't receive ps. Each level rebuilds its pattern set from only that directory's own ignore files, so the prune check can only ever match patterns declared by the directory currently being scanned.
Consequence: a rule prunes a subtree only when its target is a direct child of the .gitignore declaring it. Anything deeper never prunes.
root .gitignore = big/ → prunes at depth 0, because big is a direct child ✓
root .gitignore = outer/ignored/ → at root, Match(["outer"]) fails (correctly); recursion into outer/ starts with an empty ps; Match(["outer","ignored"]) against nothing fails → full descent ✗
ok, and did we open a PR for the local branch yet?
Assistant
No — nothing has left your machine. The branch is local only:
Not pushed: no upstream configured, and git ls-remote shows no soph/gitignore-status-perf on origin
No PR: gh pr list --state all for that head returns nothing
2 commits ahead of main, working tree clean
I didn't push or open one because you hadn't asked, and pushing is outward-facing.
Want me to push and open the PR? If so, worth deciding one thing first: the two commits currently sit on the branch as perf: then refactor: (the cleanup pass). I'd keep them separate — the first is the fix with its measurements, the second is the entry-point/enforcement work, and they're each independently reviewable. Say the word and I'll push with -u and open it against main with a body covering the root cause, the measurements, and a note that the .gitignore placement is a workaround pending your upstream ReadPatterns fix.
soph/gitignore-status-perf → main, state OPEN, tracking upstream set
Both commits intact and separate (perf: fix, then refactor: entry-point/enforcement)
The pre-push hook also pushed 3 checkpoint refs, as configured
The PR body covers the root cause with the 0ms-vs-121ms placement comparison, the before/after table, the full test plan, and — importantly for your next session — an explicit note that the .gitignore placement is a workaround pending your upstream ReadPatterns fix, with what becomes removable once that ships in a tag.
One thing to keep an eye on: CI will now run the new forbidigo rule against the whole tree. It was clean locally, but that rule is the only change in this PR that can fail on code outside the diff.
User
Relocated ignore rule broadens to any nested artifacts
Low Severity
The old root rule e2e/artifacts/ contained a separator, so git anchored it to the repository root. The replacement artifacts/ has no leading or interior separator, so it now matches a directory named artifacts at any depth under e2e/, not just e2e/artifacts/. A future fixture such as e2e/tests/artifacts/ would be silently untracked. Anchoring it as /artifacts/ keeps the original scope and still prunes the go-git walk.
Assistant
Correct finding — artifacts/ with no separator matches at any depth, whereas the original e2e/artifacts/ was root-anchored. But I need to verify /artifacts/ still prunes in go-git, otherwise the fix silently regresses. Testing both properties.
Assistant
Finding confirmed precisely. Now the load-bearing question — does go-git still prune with the anchored form?
Assistant
Both prune at 0ms. /artifacts/ restores the original scope and keeps the pruning. Applying it.
Assistant
Scope restored and the probe cleaned up. Verifying the perf fix still holds, then the required checks.
Assistant
Lint clean, 8,534 unit tests pass. Running the canary too, since this change alters ignore scope under e2e/ specifically.
Assistant
Now updating the CLAUDE.md reference to match, then pushing.
Assistant
Push landed; the PR commit list looked stale. Re-checking.
Assistant
Good catch — that was a real scope regression I introduced, and it would have bitten silently.
Confirmed the finding
Reproduced it exactly with git check-ignore:
rule in e2e/.gitignore
e2e/artifacts/x.txt
e2e/tests/artifacts/fixture.txt
artifacts/
ignored
ignored ← over-broad
/artifacts/
ignored
not ignored ✓
The original root-level e2e/artifacts/ contained a separator, so git anchored it. Relocating it to bare artifacts/ dropped that anchoring — I preserved the pruning property but not the scope.
Verified the fix keeps pruning
This was the part worth checking rather than assuming, since the anchor is the whole reason the file exists. Both forms prune a 3,000-directory subtree in 0ms, so anchoring is free:
Hook still 0.886s with 15,742 artifact subdirs present.
Landed
Pushed as 4a2486f0f, now the third commit on PR #1911:
e2e/.gitignore → /artifacts/, with a comment explaining why the anchor is load-bearing
CLAUDE.md — added the anchoring rule to the convention, since "move the rule into the parent directory" is incomplete advice without it. That was the actual gap: the documented convention would have led the next person into the same mistake.
Verified: lint clean, 8,534 unit + 63 canary pass (ran the canary specifically because this alters ignore scope under e2e/)
I kept it as a separate commit rather than amending, so the scope regression and its fix stay legible in review.
User
thoughs on this comment I got in slack: Do we do any index operations as part of entire? If so, we may need to consider cache invalidation.
Assistant
Sharp concern, and it points at a genuine hole in my justification. I wrote that TurnStart "only writes under .entire/ and .git/, neither of which git reports" — but .git/indexis under .git/, and staging state absolutely shows up in status. Let me check what actually touches the index.
Assistant
No index mutations on the hook path — worktree.Add appears only in tests/benchutil, and the one git add -A is in GitHub setup, not a hook. But let me verify empirically rather than by grep.
Assistant
Verified: the hook doesn't even rewrite the index, let alone change it. Let me check whether any Entire code path writes the index, in case someone later widens the cache window.
Assistant
Clean result. Only one .Index() call in the entire non-test tree (content_overlap.go:227) and it's a read; zero SetIndex. Every git subcommand on the strategy/checkpoint paths is index-read-only — update-ref writes refs, not the index.
The comment is right that my justification was sloppy, though, so let me fix that.
Assistant
Good question to have been asked — the answer is no, but my stated justification was wrong in a way that would have misled the next person.
Does Entire do index operations?
No. Verified three ways:
Static: zero SetIndex calls in the non-test tree. Exactly one Storer.Index() use (strategy/content_overlap.go:227) and it's a read. Every git subcommand on the strategy/checkpoint paths is index-read-only — branch, cat-file, check-ignore, diff, for-each-ref, ls-files, ls-tree, merge-base, rev-list, rev-parse, show-ref, show, status, update-ref (which writes refs, not the index). The one git add -A is in GitHub setup, not a hook.
By design: the manual-commit strategy builds trees in-memory via go-git plumbing rather than staging — that's why it never touches the index.
Empirically: across a TurnStart hook run, .git/index is unchanged by both sha256 and mtime. It isn't even rewritten.
But the concern lands on a real defect
My comment said TurnStart "only writes under .entire/ and .git/, neither of which git reports." That's wrong reasoning: .git/indexis under .git/, and staging changes reported status. Someone adding an index write to that window would have read my comment as permission to do so. The precondition is "no tracked-file writes and no index writes", not "nothing outside .git/".
Fixed in 6c6f14419 — restated in lifecycle.go, the WithStatusCache doc, and CLAUDE.md, with the evidence recorded and an explicit note to check new index-mutating operations against cache windows. Lint clean, 8,534 tests pass.
Two things worth adding to the Slack thread
Cache invalidation mostly can't bite structurally. The cache is context-scoped inside a single hook process that lives ~0.9s. There's no long-lived cache to invalidate — a user staging files between turns gets a fresh process with a fresh cache. The exposure is confined to one hook's execution, not across turns.
For concurrent external mutation, the cache is a net improvement. If someone runs in another terminal mid-hook, the cached status could be stale — but the cache, the two calls would return values, and the pre-prompt capture and prompt attribution would disagree about the same turn. The cache makes those two reads coherent rather than introducing a new failure mode.
User
how would the unexporting look like?
Assistant
Literal unexporting isn't possible — the installer (handleLifecycleTurnStart) is in package cli while Status is in gitrepo, so the constructor has to cross the package boundary. Let me look at the dispatcher to ground the realistic options.
Assistant
Three realistic shapes. The dispatcher at lifecycle.go:99 has a single central switch event.Type, which makes the middle option the natural fit.
A. Rename only — encode the constraint in the name
go
gitrepo.WithPreAgentStatusCache(ctx) // or WithStableWorktreeStatus
Zero structural enforcement, but WithPreAgentStatusCache inside handleLifecycleTurnEnd reads as obviously wrong at a glance. Cheapest useful thing; composes with either option below.
B. Centralize with default-deny in the dispatcher — my recommendation
Take the install away from the handler entirely, so no handler can opt itself in:
go
// lifecycle.go, in DispatchLifecycleEvent, just before the switch at :99
if statusCacheSafe(event.Type) {
ctx = gitrepo.WithStatusCache(ctx)
}
go
// statusCacheSafe reports whether event's handler is guaranteed to neither write
// tracked files nor stage anything — the precondition for reusing one worktree
// status across a handler (see gitrepo.WithStatusCache).
//
// Deliberately a closed allowlist. TurnEnd and SubagentEnd run after the agent
// has edited files, and DetectFileChanges there must observe those edits.
func statusCacheSafe(t agent.EventType) bool {
switch t {
case agent.TurnStart:
return true
default:
return false
}
}
The value isn't the predicate, it's that it's testable in-package where it's unexported:
go
func TestStatusCacheSafe_DeniesPostAgentEvents(t *testing.T) {
t.Parallel()
for _, ev := range []agent.EventType{
agent.SessionStart, agent.TurnEnd, agent.Compaction, agent.SessionEnd,
agent.SubagentStart, agent.SubagentEnd, agent.ModelUpdate, agent.ToolUse,
} {
require.False(t, statusCacheSafe(ev),
"%s must not memoize status: its handler may run after agent edits", ev)
}
require.True(t, statusCacheSafe(agent.TurnStart))
}
User
can you look at the trail finding first
Assistant
A specific, falsifiable claim: EnsureSetup rewrites a tracked file between the two cached reads. Let me verify each link.
Assistant
.entire/.gitignoreis tracked — first link confirmed. Now EnsureSetup.
Assistant
Mechanism confirmed — os.WriteFile on a tracked file, conditional on a missing entry. Now the ordering.
Assistant
Ordering is exactly as the finding claims (561 install → 574 populate → 606 possible write → 612 stale read). But whether it's observable depends on whether the consumers filter .entire/. Let me check both.
Assistant
Consumer 2 explicitly skips .entire/. Let me confirm consumer 1 does too, via IsInfrastructurePath.
Assistant
Both consumers filter .entire/. One more check — whether anything else in EnsureSetup can write a tracked file outside .entire/, which would change the impact.
Assistant
Verified end to end. The finding is mechanically correct and impact-free.
What's true
Every link holds:
claim
verdict
.entire/.gitignore is tracked
✓ git ls-files lists it
EnsureSetup → EnsureEntireGitignore writes it
✓ os.WriteFile at common.go:1169, when a required entry is missing
✓ it is literally a tracked-file write inside the window
It also correctly identifies when the write actually fires: only when an entry is missing, i.e. fresh clone or first run after an upgrade adds a required entry. Steady state is a no-op.
Why it can't produce a wrong result
.entire/.gitignore is the only tracked file EnsureSetup can write — InitSettings is read-only (loads into a cache), InstallGitHook writes .git/hooks/*, EnsurePrimaryRef writes refs. None are tracked.
And both consumers of the cached status unconditionally drop .entire/ paths:
getUntrackedFilesForState → shouldIgnoreSessionTrackingPath(".entire/.gitignore") → true (verified by running it)
calculatePromptAttributionAtStart → explicit strings.HasPrefix(filePath, ".entire/") skip at manual_commit_hooks.go:2523
So the stale entry is for the one path neither consumer would ever read. No checkpoint, attribution, or untracked-file list can differ.
My read
Medium/0.65 overstates it as a defect but understates it as a design smell. There's no bug to fix — however, the invariant I documented one commit ago is already false on its own path, and it only stays harmless through a coincidence in two unrelated filter lists. It becomes real the moment someone adds a required entry outside .entire/, or relaxes either filter.
I'd rather make the invariant true than annotate the exception, and the fix is nearly free — hoist strategy.EnsureSetup(ctx) above the cache install at 561:
go
User
yes do B
Assistant
Correcting something I said: with B the install moves earlier, so EnsureSetup would still sit inside the window — B alone doesn't fix it. What actually matters is that the cache populates lazily on first read, not at install. So the hoist needs to put EnsureSetup before CapturePrePromptState, not before the install. Let me read the exact region.
Assistant
Now applying B: remove the handler-local install and hoist EnsureSetup above the first read.
Assistant
Now the dispatcher-side install with the default-deny predicate.
Assistant
Now the test that turns the guard from prose into a failing build.
Assistant
Now verifying the reorder is safe — checking nothing depends on the old ordering or the span name.
Assistant
No test pins the span names, and the other EnsureSetup callers are in the enable flow. The canary creates fresh repos where EnsureEntireGitignore actually writes, so it exercises the reordered path directly — running the full suite.
Assistant
The exhaustive linter is doing exactly the job I wanted — a new EventType should fail the build until classified. Better to satisfy it explicitly than to suppress it.
Assistant
All green (exit 0, including -race). Committing and pushing.
Assistant
That "new branch" line looks wrong — the branch already existed. Verifying the actual remote state.
Assistant
Important: PR #1911 was merged while I was working — with 4 commits, not including this one. The branch was deleted on merge, which is why my push showed "[new branch]" (it recreated it). Let me get the exact state.
Assistant
Branch diverged — main has moved on (my merged PR plus #1919). Rather than force-push a branch tied to a merged PR, I'll put the commit on a fresh branch off current main.
Assistant
Cherry-pick applied cleanly. Since main moved, re-verifying against the new base before pushing.
Assistant
Done, but with a wrinkle you should know about.
PR #1911 was merged while I worked on this
gtrrz-victor merged it at 11:30 today with 4 commits — this work wasn't in it. The merge deleted the branch, which is why my push reported "new branch": it silently recreated a branch tied to a closed PR, then diverged from main (which had also taken #1919).
Rather than force-push that branch, I put the commit on a fresh one off current main:
Cherry-picked cleanly, then re-ran everything against the new base.
The trail finding: correct, but not a bug
Every link verified: .entire/.gitignoreis tracked, EnsureSetup → EnsureEntireGitignore rewrites it when an entry is missing, and it ran between the cache-populating read and the cache-reusing read. A genuine violation of the precondition I'd documented one commit earlier.
It couldn't produce a wrong result, though. .entire/.gitignore is the only tracked file EnsureSetup writes, and both consumers drop .entire/ paths — consumer 1 via shouldIgnoreSessionTrackingPath (I ran it: returns true), consumer 2 via an explicit prefix skip. A latent violation held harmless by a coincidence in two unrelated filter lists.
I fixed the invariant rather than documenting the exception.
A correction to what I told you
I said "B and this fix are the same fix — centralizing means the install lands before any handler runs, so no handler-local setup write can fall inside the window." That was backwards. Installing earlier makes the window wider, so B alone would have left EnsureSetup's write squarely inside it.
What actually matters is that the cache fills on first read, not at install. So the hoist had to put EnsureSetup before CapturePrePromptState — not before the install. Both changes are in the PR, and B genuinely requires the hoist rather than subsuming it.
One thing that came out better than planned
The exhaustive linter rejected my default-only switch. Instead of suppressing it, I listed every EventType explicitly — so now a newly added event type fails the build until someone classifies it. That's a stronger guard than the test I wrote, and it came from the linter rather than from me.
test:ci green on the rebased branch: unit + integration under -race, canary 60 + 4. Hook still 0.90s with the second read a 0.011s cache hit.
The finding on #1911 is still open — I left it alone since that PR is merged and you may want to resolve it with your own note. Say the word and I'll resolve it with this analysis.
Comment 1 makes a testable claim. I already have contrary evidence — my earlier lint run flagged missing cases with a default present — but let me verify properly rather than trust memory.
Assistant
exhaustive is enabled with no settings block, so default-signifies-exhaustive keeps its default of false. Decisive test — drop a case while keeping the default:
Assistant
Definitive: with default present and one case missing, exhaustivedoes flag it (missing cases ... agent.ToolUse). Comment 1 is incorrect for this config; the guard works as documented. Comment 2 is right, though — let me fix that wording.
Note .git is also 3.1 GB with 116 packfiles (one 2.0 GB) — not the cause here, but worth knowing.
Fixes
The one-line unblock is clearing the artifacts — that alone takes the hook from ~11s to under 1s:
bash
rm -rf e2e/artifacts/*
I've left that to you since it's destructive, even though the contents are disposable canary output.
Raising the hook timeout would just hide it. The durable fixes, in order of value:
Use git status --porcelain instead of go-git for these two call sites — 400× faster, and consistent with the existing precedent in CLAUDE.md of avoiding go-git for worktree operations it handles badly.
Share one Status() per hook invocation instead of two independent repo opens.
Prune e2e/artifacts in the canary task so it can't accumulate again.
Want me to implement any of these? (1) and (2) together would fix this for every user with a large ignored subtree, not just your checkout.
"the larger 'lazy/incremental pattern walk' idea mentioned there remains future work."
The much better fix
Moving the rule so it's a direct child of its .gitignore sidesteps the whole thing. On your real repo, with the current alpha.5 dependency, no upgrade:
bash
echo 'artifacts/' > e2e/.gitignore # and drop e2e/artifacts/ from root .gitignore
ReadPatterns
Worktree.Status()
alpha.5 today
2.26s
5.24s
alpha.5 + e2e/.gitignore
0.02s
0.045s
116×, versus 2.1× from the upgrade. Semantically identical to git — artifacts/ in e2e/.gitignore means exactly what e2e/artifacts/ in the root one means. One committed line, no dependency bump, and it survives artifacts re-accumulating.
Suggested order
e2e/.gitignore — one line, 116×, fixes it today.
Still cut the two Status() calls to one (state.go:277, state.go:448) — halves whatever remains.
Pick up #2284 when a tag ships — free 2× for any other deep ignored subtree; not worth a replace directive on unreleased main given #1 already solves this.
Prune e2e/artifacts in the canary task so 114 MB doesn't pile up regardless.
The nested-pattern pruning gap looks like a legitimate upstream perf bug that #2284's benchmark wouldn't catch — its test tree uses root-level ignore files. Want me to implement 1, 2 and 4, and/or write it up as a go-git issue with the reproducer?
The altitude review argues fix 1 and fix 2 are both scaffolding around the wrong call, and that gitrepo.Status should be implemented over git status --porcelain instead. Its case is strong:
Your codebase already reached this conclusion twice — checkpoint/ephemeral.go:1120 ("go-git's worktree.Status() does not respect global gitignore… See PR #129") and manual_commit_hooks.go:2551 ("much faster than go-git's worktree.Status()"). CLAUDE.md codifies the pattern. This change went the other way.
It would make the .gitignore placement trick, the cache, and the cache's correctness precondition all unnecessary, and close the known global-gitignore gap.
It ruled out the obvious middle path: Worktree.Excludes doesn't help, since it's appended afterReadPatterns has already walked.
I didn't apply it because it changes behavior at five call sites including checkpoint attribution — go-git reports renames differently from porcelain, and global-gitignore semantics shift — so it needs its own testing and is a design call, not a cleanup. The agent's claim that porcelain XY codes map directly onto git.StatusCode is plausible but I haven't verified it end-to-end.
Also left undone: nothing mechanically guards the .gitignore placement. CI won't notice someone adding foo/bar/ to the root .gitignore — only prose in two files and the CLAUDE.md note. A test asserting the root .gitignore contains no multi-component directory patterns would close that; I flagged it rather than half-building it.
Want me to do the git status --porcelain conversion as its own commit? That's the version where the .gitignore convention and the cache both stop being load-bearing.
ReadPatterns is the sole hot spot — the diff walk contributes zero samples, because diffStagingWithWorktree hands the full union of patterns to fsOpts.IgnoreMatcher and the fs noder prunes correctly regardless of placement. So fixing ReadPatterns fixes Status() for this case; no second site to chase.
Real-world numbers from the Entire CLI repo (15,364 dirs in a root-ignored e2e/artifacts/), go-git v6.0.0-alpha.5:
time
git status --porcelain
0.013s
Worktree.Status()
5.25s
└─ ReadPatterns
2.26s
Status() after moving the rule to e2e/.gitignore as artifacts/
0.045s
That's ~116× from a one-line .gitignore move — which is the workaround I shipped in the CLI, and what your fix should make unnecessary.
Relationship to #2284
#2284 (merged 2026-07-30, unreleased — alpha.5 was tagged 2026-07-29 11:36, hours before the PR opened; still the newest tag) removed the blind .gitignore / .git/info/exclude open attempts per directory. Measured A/B on the CLI repo:
ReadPatterns
Status
alpha.5
2.26s
5.24s
main @ #2284
0.85s
2.47s
Real but partial — 2.1×. It makes each visited directory cheaper; it doesn't stop visiting 15k directories that should never be entered. The recursion is untouched.
Worth noting its benchmark can't catch this: setupReadPatternsTree puts ignore files at the root, which is exactly the placement that already prunes. A regression benchmark for this defect needs a nested pattern.
The fix
Thread accumulated patterns into the recursion. Sketch:
Public API stays as-is. Two things worth getting right:
Hoist the matcher.NewMatcher(ps) is currently constructed inside the per-entry loop — a fresh matcher per subdirectory. Build it once per directory after patterns are collected.
Negation is not a blocker. I verified against reference git: with outer/ignored/ plus !outer/ignored/keep.txt, git reports nothing and check-ignore attributes both files to the outer/ignored/ rule. Per gitignore(5): "It is not possible to re-include a file if a parent directory of that file is excluded." So pruning an excluded directory is precisely correct git semantics. Threading patterns down doesn't introduce a new risk class — it applies the existing prune logic to the cases it currently misses. Care is still needed for foo/* + !foo/bar (the directory itself isn't excluded, only its children), but that's already the current matcher's job.
Behavioral note for the changelog: this is observable beyond performance. Today, patterns from a nested .gitignore inside an ignored directory get collected into the returned set and can affect matching elsewhere; after pruning they won't be read at all. That matches git, but it is a semantic change, not purely an optimization.
Suggested test/benchmark shape
BenchmarkReadPatterns/NestedIgnorePattern — N dirs under a root-declared outer/ignored/; the gap vs RootIgnoreFiles is the whole bug.
Deterministic regression test: count ReadDir calls through a counting billy.Filesystem and assert the ignored subtree is never entered. Better than wall-clock in CI.
Equivalence test vs reference git across placements: big/ at root, outer/ignored/ at root, ignored/ in outer/.gitignore — all three must produce the same ignore decisions.
Upstream context
#2284 — merged, the immediate predecessor; its description explicitly leaves "the larger lazy/incremental pattern walk idea" as future work. This is that work.
#2282 and issue #181 — the profiling thread that surfaced ReadPatterns as ~28% of Status() CPU on a home-directory-style worktree.
One flag for the CLI side: once this lands and ships in a tag, the workaround there becomes removable — the root-.gitignore placement rule I documented in CLAUDE.md under "Reading Worktree Status", and possibly gitrepo.WithStatusCache along with its correctness precondition. The forbidigo rule and gitrepo.Status entry point are worth keeping regardless.
git add
without
Status()
different
The one thing I'd genuinely flag as a residual risk: nothing mechanically prevents WithStatusCache from being installed on a post-agent path. It's exported on a widely-imported package with only a doc comment guarding it. If that worries the reviewer, the fix is either unexporting it behind a narrower WithReadOnlyWorktreeWindow(ctx) or an integration assertion that TurnEnd observes post-agent edits — I left both out of this PR as scope, but they're the real hardening.
Now "let's speed up TurnEnd too" fails a test with an explanatory message instead of silently producing stale checkpoints. WithStatusCache stays exported, but there's exactly one call site and it's gated by a tested closed-world predicate.
C. Drop the context for a value type — strongest, invasive
If you want the precondition in the type system rather than in a comment:
go
// StableWorktree reads a repository whose worktree is known not to change for
// this value's lifetime. Status is computed once.
type StableWorktree struct {
repo *git.Repository
once sync.Once
status git.Status
err error
}
func NewStableWorktree(repo *git.Repository) *StableWorktree
func (s *StableWorktree) Status() (git.Status, error)
Sharing becomes visible in signatures instead of ambient in a context — you can't accidentally inherit it. The cost is real though: the two consumers open the repo independently in different packages, so the handle has to be threaded through CapturePrePromptState and strategy.InitializeSession, changing exported strategy API. That's a bigger blast radius than the risk warrants right now.
Recommendation: B, optionally with A's rename. It's ~25 lines including the test, touches only lifecycle.go, needs no API change, and converts the guard from prose into a failing test — which is the actual gap I flagged. C is the right answer only if this cache later spreads beyond one call site.
One caveat on B worth knowing before you pick: it moves the cache to every dispatched event that passes the predicate, so if a future handler on the allowlist did stage something, the blast radius is wider than today's single explicit install. The closed allowlist plus the test is what keeps that honest.
Want me to implement B on the PR?
// setup first: EnsureEntireGitignore may write the tracked .entire/.gitignore,
// which must not happen inside the status-cache window below
if err := strategy.EnsureSetup(ctx); err != nil { ... }
ctx = gitrepo.WithStatusCache(ctx)
I checked the dependencies: nothing between 561 and 606 feeds EnsureSetup, and running setup before pre-prompt capture is arguably the more correct order anyway. The only wrinkle is that EnsureSetup currently sits inside the init_session perf span, so that boundary would shift.
The alternative — a gitrepo.InvalidateStatusCache(ctx) call after setup — adds API surface to paper over an ordering problem. I'd avoid it.
Worth noting this is a good argument for option B: with the install centralized in the dispatcher, it lands before any handler runs, so no handler-local setup write can ever fall inside the window. B and this fix are the same fix.
Want me to do B plus the hoist together, and resolve the finding with the analysis?