AGENTS.md instructions for /Users/muskanpaliwal/Work/open-source/entire/cli/refactor-git-metadata-traversal
When learning new concepts, my aim is to build solid gut level intuition with concrete examples. Give me alternative views / perspective on the concept. Go for a comprehensive response, I don't mind details. Whenever you're explaining a difficult concept (like a formula), give concrete (simple) examples to help me understand. Also I would prefer if you ask questions or give problems to me check understanding (I don't want to learn passively, I know real understanding happens when you do exercises)
Code Comments
Prefer self-explanatory code. Add a comment only for a non-obvious invariant, constraint, safety reason, protocol quirk, or public contract that clearer code cannot express.
Keep comments short and explain why the logic is necessary. Do not narrate obvious operations or restate the code.
Never put agent names, task names or IDs, ticket IDs, phase or step labels, session notes, implementation chronology, or review/process metadata in source comments or doc comments.
Keep planning, tracking, and handoff context in issues, commits, pull requests, or local coordination files, not production code.
Remove stale or process-oriented comments when touching nearby code.
--- project-doc ---
Entire - CLI
This repo contains the CLI for Entire.
Architecture
CLI built with github.com/spf13/cobra and github.com/charmbracelet/huh
Key Directories
Commands (cmd/)
entire/: Main CLI entry point. Also home to kubectl-style external-command resolution (entire <name> → entire-<name> on PATH) — see External Commands.
entire/cli: CLI utilities and helpers (Cobra commands, helpers, group roots)
entire/cli/commands: actual command implementations
entire/cli/agent: agent implementations (Claude Code, Gemini CLI, OpenCode, Cursor, Factory AI Droid, Copilot CLI, Pi) - see Agent Integration Checklist and Agent Implementation Guide
entire/cli/strategy: strategy implementation (manual-commit) - see section below
entire/cli/checkpoint: checkpoint storage abstractions (ephemeral and persistent)
e2e/: E2E tests with real agent calls (see e2e/README.md)
Command Layout
The visible CLI is organized around a set of noun groups plus a small set of
top-level verbs. The groups are the canonical home for each verb. Newer
experimental command families are discoverable through entire labs and
their canonical paths are always runnable.
Experimental commands are gated by a build-time visibility flag (the
cmd/entire/cli/experimental package): they are shown — grouped under an
"Experimental commands:" help section — in developer and nightly builds, and
hidden in stable release builds. Visibility is toggled by experimental.Visible
(default "true"), which GoReleaser stamps "false" only on stable tags
(.Prerelease empty); nightly (vX.Y.Z-nightly.*) and local builds leave it at
the default. Register a command as experimental with experimental.Register(parent, child) instead of parent.AddCommand(child). Gating only controls visibility —
the commands are always runnable in every build.
session (alias: sessions): list, info, tokens, stop, attach, adopt, resume, current.
resume with a branch arg switches to it and resumes its session; with no arg
it opens an interactive picker of stopped sessions (across all worktrees),
resolving each to its branch and pointing at the owning worktree when the
branch is checked out elsewhere. Resume keeps an existing local session log
as-is by default (--force overwrites it from the checkpoint).
adopt moves an active session from another repo or worktree into the current
worktree and resets target-local checkpoint bookkeeping so future commits link
to the adopted session from the new location.
checkpoint (aliases: cp, checkpoints): list, explain, tokens, search.
explain also takes --repo <owner/name>, the drill-down for a cross-repo
search hit: it reads the checkpoint from that repo's entire-api cell over
HTTP (/repos/{repo_id}/checkpoints/{id} plus .../transcript/raw) rather
than fetching git objects, so a foreign checkpoint never enters this repo's
object store, ref namespace, or tokens profile. It needs a full checkpoint
ID and a pushed checkpoint; --commit, --session, --search-all, and
--generate are rejected with it, and naming the current repo is a no-op
that falls through to the local path. See checkpoint_api_reader.go
(apiCheckpointReader, which implements the two checkpoint reader tiers and
deliberately not Writer) and explain_repo.go.
agent: bare opens the interactive agent selector, plus list, add, remove
configure: bare prints help and a hint pointing at entire agent; flags
manage non-agent settings (telemetry, git-hook installation mode, strategy
options, summary provider). Agent CRUD lives under entire agent.
auth: login, logout, status, contexts, use, plus
token (prints the active control-plane bearer to stdout for scripting/curl;
honors ENTIRE_TOKEN, else the refreshed active-context login JWT).
also takes (e.g. , ), which instead mints a
jurisdictional identity token (RFC 8693 exchange, ,
) for that jurisdiction's entire-api cells (e.g.
), which reject the control-plane
bearer; it exchanges when set (deriving the environment from the
env token's ), else the active login. shows the caller's
home jurisdiction so the slug is discoverable.
takes (revoke every session on the active core, not just the
current one) and (log out of every saved login)
Experimental commands (gated by the build-time visibility flag above — visible
and grouped under "Experimental commands:" in developer/nightly builds, hidden
in stable releases, always runnable): tokens, import, review,
investigate, blame, why, experts, runner, and checkpoint policy.
tokens is also advertised through entire labs.
Top-level lifecycle and standalone commands: enable, disable, status,
login, logout, clean, version, dispatch, activity, help,
configure, agent-help, api, search. search is the canonical
spelling (visible in every build, grouped with Sessions & Checkpoints);
checkpoint search stays a working alias of the same command.
api is an authenticated passthrough to Entire's HTTP APIs (gh-style): it
attaches the right bearer and dials the right host so callers don't plumb auth
themselves. --to core (default) hits the control plane; --to cell hits an
entire-api cell. --jurisdiction <slug> (e.g. us, eu) targets a specific
jurisdiction's cell instead of the caller's home cell and implies --to cell
(cell routing + identity-token exchange live in auth.NewEntireAPICellClient
via auth.CellTarget). {owner}/{repo}/{repo_id} in the path are filled
from the current repo's origin remote. It is an escape hatch, so it is absent
from agent-help's curated listing but stays in entire help and agent-help's
footer — an agent that needs raw access must find it rather than hand-roll curl
with a token.
agent-help renders machine-readable, agent-facing usage live from the Cobra
command tree (so it always matches the installed binary): bare prints a curated
"when to use entire" map; agent-help <command> drills into one command's
current flags; --json emits structured output. It is the single source of
truth the first-turn context injection and the --agent-help-skill skill point
agents at, instead of enumerating a surface that goes stale.
Where agent-facing text goes
What you have
Where it goes
A new command
agentHelpClassification in agent_help_cmd.go — one entry, keyed by command path, carrying audience and listed
"When to use this at all" advice for agents
agentHelpGuidance — never cobra Short/Long
A fact humans need too (e.g. "this output is not stable")
cobra Long. Human help is a reference, not a lecture: whoever typed --help already chose the command
A per-task command recommendation
agent-help, which is pulled on demand. Never the first-turn injection, which carries only invariants true on every turn
Flag it; don't decide it. Whether a command is listed, and whether it is
read-only / task-driven / user-owned, are product judgment calls — they change
what agents do unprompted in every user's repo. Take the safe default
(unlisted, user-owned), then say in the PR what you picked and why so a human
can move it. Never quietly promote a command into the listing or into
read-only.
CI enforces the mechanical parts, so trust these rather than re-deriving them:
every advertised top-level command and every child of a listed group is
classified; a read-only group contains no writing subcommand; guidance text
never appears in a command's Short/Long.
Hidden commands opt into being advertised here by setting
Annotations[agentHelpAnnotation] = "true" (e.g. trail). Because agent-help
renders live and lists non-hidden commands, the experimental commands appear in
agent-help in developer/nightly builds and are absent in stable releases — the
advertised surface is build-dependent, matching what entire help shows.
No-channel agents (Cursor, Copilot CLI, Factory Droid, MCP hosts — no
context-injection channel and no agent-help skill template) reach it without an
active push. All of them can discover it passively: it is visible in entire help, the entire status footer points at it, and entire status --json
exposes it as the agent_help field. On top of that, Factory AI Droid (which is
banner-only) gets the pointer appended to its SessionStart hook banner, and
MCP-host agents can launch the hidden entire mcp stdio server, which exposes
agent_help and entire_status as MCP tools using the same live rendering.
Enabling a no-channel agent with --agent-help-skill reports the skill
unsupported and points the agent at this passive path instead.
Cobra-native aliases (no hint): sessions → session, cp/checkpoints →
checkpoint.
Hidden infrastructure commands: hooks, trail,
curl-bash-post-install, __send_analytics, __sweep_sessions, mcp (MCP
stdio server for MCP-host agents).
Diagnostic subcommands live alongside doctor.go as doctor_logs.go and
doctor_bundle.go. Group roots and noun-group children live in files
named <noun>_group.go and <noun>_<verb>.go respectively.
Tech Stack
Language: Go 1.26.x
Build tool: mise, go modules
Linting: golangci-lint
Development
Running Tests
bash
mise run test
Running Integration Tests
bash
mise run test:integration
Running All Tests (CI)
bash
mise run test:ci
This runs unit tests, integration tests, and the E2E canary (Vogon agent) in sequence. Integration tests use the //go:build integration build tag and are located in cmd/entire/cli/integration_test/.
Running E2E Canary Tests (Vogon Agent)
The Vogon agent is a deterministic fake agent that exercises the full E2E test suite without making any API calls.
bash
mise run test:e2e:canary # Run all E2E tests with the Vogon agent
mise run test:e2e:canary TestFoo # Run a specific test
Runs as part of test:ci — canary failures block merges
No API calls, no cost — safe to run freely, unlike real agent E2E tests
If a canary test fails, the bug is in the CLI or test infrastructure, not in an agent
Located in e2e/vogon/ (binary) and cmd/entire/cli/agent/vogon/ (Agent interface)
The binary parses prompts via regex, creates/modifies/deletes files, and fires lifecycle hooks
IMPORTANT: When changing E2E test prompt wording, the Vogon binary (e2e/vogon/main.go) parses prompts with hardcoded regexes. New phrasing may not match existing patterns — always run mise run test:e2e:canary after changing prompt text and fix Vogon's parsing if tests fail.
Running E2E Tests (Only When Explicitly Requested)
IMPORTANT: Do NOT run E2E tests proactively. E2E tests make real API calls to agents, which consume tokens and cost money. Only run them when the user explicitly asks for E2E testing.
bash
mise run test:e2e [filter] # All agents, filtered
mise run test:e2e --agent claude-code [filter] # Claude Code only as an example here, replace `claude-code` with other agents to run tests for those agents
E2E tests:
Use the //go:build e2e build tag
Located in e2e/tests/
See e2e/README.md for full documentation (structure, debugging, adding agents)
Test real agent interactions (Claude Code, Gemini CLI, OpenCode, Cursor, Factory AI Droid, Copilot CLI, Pi, or Vogon creating files, committing, etc.)
Validate checkpoint scenarios documented in docs/architecture/checkpoint-scenarios.md
Support multiple agents via E2E_AGENT env var (claude-code, gemini, opencode, cursor, factoryai-droid, copilot-cli, pi, vogon)
Environment variables:
E2E_AGENT - Agent to test with (default: claude-code)
E2E_CLAUDE_MODEL - Claude model to use (default: haiku for cost efficiency)
E2E_TIMEOUT - Timeout per prompt (default: 2m)
Test Parallelization
Always use t.Parallel() in tests. Every top-level test function and subtest should call t.Parallel() unless it modifies process-global state (e.g., os.Chdir()).
Exception: Tests that modify process-global state cannot be parallelized. This includes os.Chdir()/t.Chdir() and os.Setenv()/t.Setenv() — Go's test framework will panic if these are used after t.Parallel().
Git in Tests
Tests that touch git state must use an isolated temp repo — never the real repo CWD.
Many handlers (lifecycle, strategy, hooks) resolve the git repo from CWD via OpenRepository, GetGitCommonDir, DetectFileChanges, etc. Without isolation, tests can create session state files, shadow branches, or other artifacts in the real .git/ directory.
Use the testutil helpers:
go
tmpDir := t.TempDir()
testutil.InitRepo(t, tmpDir) // git init + user config + disable GPG
testutil.WriteFile(t, tmpDir, "f.txt", "init") // create a file
testutil.GitAdd(t, tmpDir, "f.txt") // stage it
testutil.GitCommit(t, tmpDir, "init") // commit (needs at least one commit for HEAD)
t.Chdir(tmpDir) // redirect CWD-based git resolution
testutil.InitRepo configures user.name, user.email, and disables GPG signing — safe for CI environments without global git config.
Prefer testutil.InitRepo() over direct git.PlainInit() in tests. When a test in this repo needs an initialized repository, use testutil.InitRepo(t, dir) unless the test specifically needs lower-level initialization behavior that the helper cannot provide. Do not call git.PlainInit() directly and then create commits or run CLI git operations without also reproducing the helper's repo-local config.
Do NOT shell out to git init/git commit directly without setting user config and --no-gpg-sign, and do NOT run lifecycle/strategy handlers from the real repo CWD in tests.
Config/Cache/Keyring Isolation in Tests
Tests must never read or write the developer's real ~/.config/entire
(contexts.json, version_check.json), ~/.cache/entire (nodes.json,
cluster_cores.json, api_discovery.json), or OS keychain. The developer may be
using entire for real while tests run.
Single resolver: internal/entireclient/userdirs is the only place
that resolves the per-user config dir (userdirs.Config():
$ENTIRE_CONFIG_DIR else ~/.config/entire) and cache dir
(userdirs.Cache(): $XDG_CACHE_HOME/entire else ~/.cache/entire).
Never derive these paths anywhere else.
In-process safety net: userdirs and the tokenstore default backend
detect go test (via internal/testdirs) and fall back to a throwaway
per-process temp directory when their env override is unset. The fallback
is shared across tests in one process — for per-test isolation still set
t.Setenv("ENTIRE_CONFIG_DIR", t.TempDir()) and
tokenstore.UseFileBackendForTesting(...).
Spawned binaries are NOT covered: testing.Testing() is false in a
subprocess. The integration and e2e TestMains set ENTIRE_CONFIG_DIR,
XDG_CACHE_HOME, ENTIRE_TOKEN_STORE=file, ENTIRE_TOKEN_STORE_PATH, and
ENTIRE_TEST_AUTH_STORE_FILE process-wide so every spawned entire (and
every agent-invoked hook) inherits isolation. Any new harness that spawns
the real binary must do the same.
Legacy auth store: auth.NewStore() talks straight to the zalando
keyring; packages whose tests can reach it need keyring.MockInit() in
TestMain (see cmd/entire/cli/global_test.go) — the testdirs fallback
does not cover it in-process.
Spawning subprocesses in tests (TTY detection)
Tests that spawn the real entire or git binary need the child to be non-interactive so prompts don't hang on a developer terminal.
interactive.CanPromptInteractively() resolves in this order:
ENTIRE_TEST_TTY=1 → force interactive ON (any other non-empty value → force OFF).
testing.Testing() → false. In-process go test runs are non-interactive by default; no per-test t.Setenv("ENTIRE_TEST_TTY", "0") is needed.
/dev/tty probe, plus its terminal mode → a terminal held in raw mode
(canonical input off) belongs to a full-screen TUI that spawned us, not to a
shell we can prompt: TUI git clients (lazygit, gitui, tig) run git commit
as a child while owning the screen, so the hook inherits a /dev/tty it
must not prompt on. Fails open when the mode can't be read. See
interactive/rawmode_unix.go for the rationale.
For subprocesses spawning the real entire binary (e2e, integration tests, entire calling itself from a hook), prefer execx.NonInteractive over env-var plumbing:
execx.NonInteractive puts the child in a new session with no controlling terminal (Setsid on Unix, DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP on Windows), so the child's /dev/tty probe fails naturally. No env var required.
interactive.UnderTest() returns true when testing.Testing() or ENTIRE_TEST_TTY is set — use it where code needs to skip a real-terminal operation even if CanPromptInteractively() returns true (e.g., reading from /dev/tty directly inside askConfirmTTY).
Linting and Formatting
bash
mise run fmt && mise run lint
mise run fmt can rewrite files. Treat mise run fmt && mise run lint as a single verification sequence: if formatting changes anything, run lint again on the formatted tree rather than assuming a previous lint result still applies.
Before Every Commit (REQUIRED)
CI will fail if you skip these steps:
bash
mise run check
Equivalent expanded form:
bash
mise run fmt # Format code (CI enforces gofmt)
mise run lint # Lint check (CI enforces golangci-lint)
mise run test:ci # Run all tests (unit + integration)
mise run check runs the three commands above.
Safety note: do not treat a clean mise run lint result as final unless it was run after the most recent mise run fmt pass.
Before Any Push Or Remote Code Update (REQUIRED)
Before pushing commits or otherwise sending code changes to any remote, run mise run lint on the current tree and ensure it passes. If mise run fmt changed files, rerun mise run lint on the formatted tree before pushing.
Common CI failures from skipping this:
gofmt formatting differences → run mise run fmt
Lint errors → run mise run lint and fix issues
Test failures → run mise run test and fix
Code Duplication Prevention
Before implementing Go code, use /go:discover-related to find existing utilities and patterns that might be reusable.
Check for duplication:
bash
mise run dup # Comprehensive check (threshold 50) with summary
mise run dup:staged # Check only staged files
mise run lint # Normal lint includes dupl at threshold 75 (new issues only)
mise run lint:full # All issues at threshold 75
Tiered thresholds:
75 tokens (lint/CI) - Blocks on serious duplication (~20+ lines)
Check if a helper already exists in common.go or nearby utility files
If not, consider extracting the duplicated logic to a shared helper
If duplication is intentional (e.g., test setup), add a //nolint:dupl comment with explanation
Code Patterns
Error Handling
The CLI uses a specific pattern for error output to avoid duplication between Cobra and main.go.
How it works:
root.go sets SilenceErrors: true globally - Cobra never prints errors
main.go prints errors to stderr, unless the error is a SilentError
Commands return NewSilentError(err) when they've already printed a custom message
When to use SilentError:
Use NewSilentError() when you want to print a custom, user-friendly error message instead of the raw error:
go
// In a command's RunE function:
if _, err := paths.WorktreeRoot(); err != nil {
cmd.SilenceUsage = true // Don't show usage for prerequisite errors
fmt.Fprintln(cmd.ErrOrStderr(), "Not a git repository. Please run 'entire enable' from within a git repository.")
return NewSilentError(errors.New("not a git repository"))
}
When NOT to use SilentError:
For normal errors where the default error message is sufficient, return the error directly. main.go will print it:
go
// Normal error - main.go will print "unknown strategy: foo"
return fmt.Errorf("unknown strategy: %s", name)
Key files:
errors.go - Defines SilentError type and NewSilentError() constructor
root.go - Sets SilenceErrors: true on root command
main.go - Checks for SilentError before printing
Settings
All settings access should go through the settings package (cmd/entire/cli/settings/).
Why a separate package:
The settings package exists to avoid import cycles. The cli package imports strategy, so strategy cannot import cli. The settings package provides shared settings loading that both can use.
Usage:
go
import "github.com/entireio/cli/cmd/entire/cli/settings"
// Load full settings object
s, err := settings.Load()
if err != nil {
// handle error
}
if s.Enabled {
// ...
}
// Or use convenience functions
if settings.IsSummarizeEnabled() {
// ...
}
Do NOT:
Read .entire/settings.json or .entire/settings.local.json directly with os.ReadFile
Duplicate settings parsing logic in other packages
Create new settings helpers without adding them to the settings package
Key files:
settings/settings.go - EntireSettings struct, Load(), and helper methods
config.go - Higher-level config functions that use settings (for cli package consumers)
Logging vs User Output
Internal/debug logging: Use logging.Debug/Info/Warn/Error(ctx, msg, attrs...) from cmd/entire/cli/logging/. Writes to .entire/logs/.
Enabling debug/perf logs locally: Prefer adding "log_level": "DEBUG" to .entire/settings.local.json when you need detailed hook/perf logs. This file is gitignored. ENTIRE_LOG_LEVEL=debug also works and takes precedence.
User-facing output: Use fmt.Fprint*(cmd.OutOrStdout(), ...) or cmd.ErrOrStderr().
Don't use fmt.Print* for operational messages (checkpoint saves, hook invocations, strategy decisions) - those should use the logging package.
Privacy: Don't log user content (prompts, file contents, commit messages). Log only operational metadata (IDs, counts, paths, durations).
Git Operations
We use github.com/go-git/go-git for most git operations, but with important exceptions:
Opening Repositories - Always Use gitrepo
Never call git.Open, git.PlainOpen, or git.PlainOpenWithOptions directly.
cmd/entire/cli/gitrepo is the single source of truth for opening a
repository. Use gitrepo.OpenCurrent(ctx) for the current worktree or
gitrepo.OpenPath(root) for a specific worktree root. Both funnel through
openPathWithAlternates, which is the only place that opens a *git.Repository.
Routing every open through gitrepo guarantees two behaviours no ad-hoc
git.PlainOpen call gets right:
Object alternates are rewritten to absolute paths so shared clones resolve
their objects (PlainOpen cannot follow relative/absolute alternates).
Reftable repositories are detected and opened through the git-CLI-backed
reference storer (reftableStorer). A direct git.PlainOpen on a reftable
repo fails outright with unknown extension: refstorage, because go-git's
filesystem storer cannot read the reftable backend. The reftable storer also
re-approves the objectformat (sha1/sha256) and worktreeconfig extensions
that go-git verifies at open time.
If a code path opens a repo with a bare go-git call, it silently breaks on
reftable and sha256 repositories. Reviewers should flag any new
git.PlainOpen*/git.Open outside gitrepo. Key files: gitrepo/repository.go
(open entry points) and gitrepo/reftable.go (reftableStorer).
Reading Worktree Status - Always Use gitrepo.Status
Never call go-git's worktree.Status() directly. Use
gitrepo.Status(ctx, repo); a forbidigo rule in .golangci.yaml enforces
this, and gitrepo/status.go is the only sanctioned call site.
Worktree.Status() walks the worktree, so its cost scales with working-set size
rather than with the size of the change being inspected, which makes it the most
expensive git read on the hook paths. Avoid calling it more than once per hook.
Do not memoize it either: a context-scoped cache was tried and removed, because
the write-free window it required cost more to maintain than the walk saved (see
git log on gitrepo/status.go for the measurements). The turn-start hook
currently walks twice — CapturePrePromptState and the strategy's prompt
attribution each read their own status.
Agent-hook capture paths must use gitrepo.StatusWithBudget instead: it bounds
the walk with a wall-clock budget (gitrepo.StatusWalkBudget) because go-git's walk is
not context-cancellable and a pathological worktree (e.g. a stray git init in
$HOME) otherwise leaves the hook process grinding for hours after the agent's
own hook timeout fires. On breach it returns an error wrapping
gitrepo.ErrStatusBudgetExceeded — hook callers warn and continue with
transcript-derived data (capture is fail-open; new-file detection is skipped for
the turn via the pre-prompt/pre-task UntrackedScanSkipped marker) — and a
process-local latch makes every later StatusWithBudget call in the same hook
process fail fast rather than re-entering the walk. The first-checkpoint
git status subprocess in the checkpoint store is bounded by the same
StatusWalkBudget (a killed child, not an abandoned goroutine) and reports the
same sentinel; the lifecycle handlers warn-and-skip the checkpoint on it. Turn
end persists whether the turn degraded (SessionState.CaptureDegradedAt — set
on breach, cleared by the next healthy turn) so entire status surfaces the
degradation instead of it living only in .entire/logs. Paths
where a user is actively waiting on a command (review, rewind, and
session adopt via detectFileChangesUnbounded) keep the unbounded
gitrepo.Status.
git status Is a Write - Always Pass --no-optional-locks
Every git status Entire runs must pass --no-optional-locks. A guard test
(TestGitStatusCallSitesPassNoOptionalLocks in cmd/entire/cli/gitrepo/) fails the build on
any call site that omits it.
git status is not a read. It refreshes the index's stat cache and, whenever any
entry is stale, writes the result back: builtin/commit.c takes
.git/index.lock for the duration of the whole worktree walk, then renames a
fresh index over .git/index (tempfile.c, rename(2)). The gate is
use_optional_locks(), and --no-optional-locks is literally setenv( GIT_OPTIONAL_LOCKS, "0") — so the flag also propagates to child git processes,
and GIT_OPTIONAL_LOCKS=0 in the environment is an equivalent user-side
mitigation. Output is byte-identical either way. The write fires on
mtime-moved-but-content-identical files — the ordinary aftermath of an agent
turn, a formatter, or an editor save — not on content edits.
That refresh is git working as designed, and running git status is not itself
a mistake. The reason we always drop the write is that Entire never benefits
from it: every call site reads the porcelain output once and discards it, so
the stat-cache update is a cost with no return.
Three consequences, all observed in the field (issue #2111):
A repo-deleting commit. The rename replaces .git/index with a new inode.
On a filesystem where rename-over-existing is not atomic against a concurrent
lookup — Docker Desktop / virtiofs bind mounts, measured at 9.9% of opens
during continuous replacement versus 0 on ext4 — a concurrent reader gets
ENOENT. Git silently treats ENOENT on the index, and only ENOENT, as an
empty index (every other errno calls die_errno), so a git commit landing
in that window records the empty tree with exit code 0 and no warning: a commit
that deletes every tracked file. Recovery is git reset --mixed HEAD~1.
The user's own git add failing with Unable to create '.git/index.lock': File exists while Entire holds the lock across its walk.
A permanently stale index.lock when a budget (StatusWalkBudget)
SIGKILLs the child mid-walk, breaking every later git add/git commit until
someone removes the file by hand.
Passing the flag does not make the hazard go away, and must not be described
as if it did. On an affected filesystem any concurrent git status opens the
same window: the user's own, another tool's, a file watcher's — and in
particular N agents working the same repo, each running its own hooks, which
is precisely the workflow Entire encourages. Our share is the one write that is
both unnecessary and asynchronous to the human's terminal, so it is the one that
can land between someone's git add and their git commit. For the writers we
do not control, the mitigation is GIT_OPTIONAL_LOCKS=0 in the environment
(devcontainers: containerEnv), which covers every git process in the session.
Related: any git subprocess that can run inside a git hook and names its target
with cmd.Dir or -C must also set cmd.Env = gitrepo.EnvWithoutRepoOverrides()
(gitrepo/env.go). Git exports GIT_DIR / GIT_WORK_TREE / GIT_INDEX_FILE to
hooks and those take precedence over cmd.Dir, so a bare exec.Command
silently operates on the hook's repo. Deliberately not applied to user-invoked
commands that act on the current directory (status, doctor, review): there
a GIT_DIR the user exported is an instruction, not contamination.
This exact producer was diagnosed once before (ENT-242, Feb 2026) and lost: the
fix was closed unmerged on the premise that git status --porcelain -z "reads
without rewriting", which is false, and it would have grown the number of
index-rewriting call sites from one to eleven. That is why the guard test exists
rather than a comment.
go-git v5 Bugs - Use CLI Instead
Do NOT use go-git v5 for checkout or reset --hard operations.
go-git v5 has a bug where worktree.Reset() with git.HardReset and worktree.Checkout() incorrectly delete untracked directories even
Local coordination documents titled “Thermo-Nuclear Review: Consolidating Git Metadata Traversal” and “Git Metadata Traversal Consolidation — Implementation Plan” contain the completed walkthrough and proposed execution sequence. Find and read both, but independently verify them rather than treating them as authoritative.
All material design findings in the walkthrough were discussed and accepted, and the user explicitly approved implementation. No production implementation has been made.
The latest upstream/main was fetched immediately before this handoff. The branch is 0 commits ahead and 26 commits behind upstream/main. It has only the two untracked coordination Markdown files above. The fast-forward itself has not been performed.
Earlier inspection found fragmented ownership: gitrepo, paths, session, checkpoint, strategy, settings, status, review, investigate, trail, setup/cleanup, and Codex-related code independently interpret .git, commondir, or worktree identity.
Session owns a single-entry CWD-keyed common-directory cache; checkpoint owns a separate worktree-root-keyed cache. The accepted direction is to remove both after their Git subprocess traversal is replaced. Retain the existing worktree-root discovery cache.
The reviewed structural direction is a focused resolver inside the existing gitrepo ownership boundary. It should expose physical Git facts for one explicit worktree root: the per-worktree Git directory, common Git directory, and optional linked-worktree identity. It should not expose a layout taxonomy or Codex policy.
Worktree identity should come from the relationship between the resolved per-worktree Git directory and common-dir/worktrees/, using physical identity only for equality checks while preserving cleaned absolute lexical paths in returned values.
I’m starting with a read-only audit before touching the branch. I’ll use the thermo-nuclear review skill for the structural assessment, the using-entire skill to separate checkpoint-backed intent from commit evidence and code inference, and the browse skill for the linked PR discussion and current CI state. I’ll also read both local coordination documents and verify every important claim against the current repository.
Assistant
The review skill sets a deliberately high bar: this should delete concepts and ownership drift, not merely centralize identical helpers behind wrappers. The Entire workflow also requires provenance checks before inference, so I’m first inventorying the worktree, instructions, documents, branch/upstream state, and checkpoint availability without modifying anything.
Assistant
The headless-browser binary named by the browse skill is not installed, so I’m using read-only GitHub/web access instead; I will not post or mutate anything. The repository instructions are present as AGENTS.md → CLAUDE.md, and I’ve now read that file, CONTRIBUTING.md, both coordination documents, and the local Codex configuration. The prescribed /go:discover-related facility is not exposed in this environment, so I’ll explicitly use code search plus git/checkpoint history as the documented fallback.
Assistant
GitHub’s unauthenticated page cache is stale enough to label the merged PR as open, so I’m verifying through the read-only API instead. That request is still waiting on network/auth; meanwhile, no repository files have been changed and the worktree remains at the stated pre-refresh point.
Assistant
The first changed assumption is now concrete: after a fresh fetch, the branch is 0 ahead and 30—not 26—commits behind current upstream/main (486de6900, merged August 31). The fast-forward remains structurally safe: HEAD is an ancestor, there are no tracked local edits, neither untracked coordination filename exists upstream, and upstream’s overlap is limited to settings hardening and deletion of dead rewind machinery in strategy/common.go; I’m auditing those exact diffs before deciding whether to proceed.
User
what's happening here?
Assistant
I’m still in the required independent-review gate; I have not edited or fast-forwarded the branch yet.
What I’ve established:
Fresh GitHub/API verification: PR #2052 is merged, its relevant checks passed, and the two cited comments say exactly what the handoff claims.
Fresh fetch: the branch is now 30 commits behind upstream/main, not 26, and 0 ahead.
Fast-forward is safe: HEAD is an ancestor of current main, there are no tracked local changes, and upstream does not contain either untracked coordination document.
Current main has not implemented this consolidation. Its only overlap is security hardening in settings.go and deletion of dead rewind code in strategy/common.go; both can be preserved.
The duplication is real and broader than one helper: current main still has separate .git/commondir parsing, two common-dir caches, marker-based worktree-ID parsing, and independent traversal in status, settings, review, trail, checkpoint, strategy, session, and Codex.
Entire history was checked. The relevant cache checkpoints are unavailable locally, so their rationale is commit-message evidence; the submodule worktree test checkpoint is available but contains metadata only, not a design transcript.
/go:discover-related is unavailable here, so I’m using the instructed fallback: exhaustive code search plus git/checkpoint history.
Current-main core tests, lint, integration tests, canaries, Windows, and Codex hook tests are green. One paid Cursor E2E job on current main failed; it is outside this work and I will not run paid E2E.
The review currently supports proceeding. I’m finishing the sensitive boundary audit—repository-opening fallback, Codex moved-registration behavior, symlink identity/lock deduplication, and which remaining Git queries are genuinely semantic. Then I’ll give the explicit verdict, fast-forward, and implement if no blocker appears.
Assistant
Independent review verdict: proceed.
The consolidation is still necessary, and the relationship-based, deletion-oriented design remains the cleanest structural move. Current main still lets multiple packages answer the same physical question differently; adding wrappers or preserving either common-dir cache would keep the ownership defect alive. The focused gitrepo facts value—GitDir, CommonDir, WorktreeID—is the smallest adequate abstraction.
Changed or sharpened assumptions from current main:
The branch is 30 commits behind, not 26.
strategy/common.go is already 191 lines smaller because upstream removed dead rewind machinery. The metadata resolver still remains there and should be deleted.
settings.go gained important symlink/TOCTOU hardening. Its metadata migration must be surgical and leave that logic untouched.
The current-main CI core is healthy; one unrelated paid Cursor E2E job failed. I will neither treat that as caused by this work nor run paid E2E.
A few raw common-dir Git queries must remain: session-adopt’s combined arbitrary-path validation, manual session repository-equality checks, and trail reuse’s repository/branch validation. The physical-only calls in checkpoint, state storage, settings, status, review manifests, shallow-file lookup, setup/cleanup, and ordinary trail paths should migrate.
OpenPath needs an explicit validated bare-repository route. A missing/malformed worktree registration must never reach PlainOpen merely because an alternates probe also failed.
Codex moved-registration behavior is compatible with the facts resolver because backlink validation remains Codex-owned: valid metadata can resolve, then Codex can deliberately refuse ownership promotion and stay worktree-local.
There is no import-cycle blocker: gitrepo already depends only on paths; session/checkpoint/settings/strategy can depend on gitrepo without reversing that edge. Same-package gitrepo tests must keep local fixture helpers because testutil imports gitrepo.
Physical canonicalization must remain narrow. Resolver output stays lexical; worktree-ID derivation and multi-lock dedup/order use physical identity. A failed safety-critical identity check must error.
No hot-hook path needs an added Git process. Explicit-root checkpoint paths will lose common-dir forks; CWD entry points reuse the existing cached worktree-root discovery.
I found no stale implementation, conflicting upstream owner, incompatible security change, or behavior requirement that should stop the work. I’m now fast-forwarding with , after recording hashes of both untracked documents, then I’ll re-check them and begin the canonical resolver/tests.
Assistant
The fast-forward completed cleanly to 486de6900. Both coordination files retained byte-for-byte identical SHA-256 hashes and remain the only untracked files. I’m taking a focused test/line-count baseline now, then the first implementation slice will be the resolver and its real-Git/malformed-layout specification before migrating any consumer.
Assistant
The baseline’s first attempt was blocked only by sandbox access to the configured Go build cache; rerunning with that permission is progressing normally. gitrepo, paths, session, and checkpoint have passed so far; the larger strategy/settings/Codex packages are still finishing.
Assistant
The canonical resolver and its first executable specification are in place. The test matrix is intentionally using real Git for valid layouts (normal, linked, .bare, arbitrary bare backing store, separate Git dir, submodules, relative pointers, aliases, and moved registrations) and handmade fixtures only for malformed metadata. That focused test run is still executing; no consumer migration has started yet.
Assistant
You handed me a deliberately large review-and-implementation task, and I’m partway through it—not stuck or silently publishing anything.
So far I’ve independently verified the PR/comments, branch history, current consumers, and relevant CI; found the branch was actually 30 commits behind (not 26); confirmed upstream had not already done the consolidation; preserved both untracked coordination documents; and fast-forwarded safely. The review verdict is that the consolidation still makes sense.
I’ve begun the local implementation: the canonical gitrepo metadata resolver and its real-Git layout tests are in place and passing. I’m now restructuring repository opening around it before migrating the remaining consumers and deleting the duplicate caches/parsers. The worktree currently contains unfinished local edits, so I have not committed, pushed, opened a PR, or run paid E2E tests.
Assistant
The first implementation slice is intentionally tightening a dangerous boundary: malformed worktree metadata must not accidentally fall through to a different repository-opening path. I’m checking that change now before touching the many callers, because preserving that failure classification is one of the main safety constraints.
User
continue
User
continue
Assistant
Continuing from the safe point. The formatter completed and no test process was left running; the next concrete issue is updating repository-opening tests for the new facts-based boundary, then I’ll run the whole gitrepo package before migrating consumers.
Assistant
The repository-opening slice now passes the full gitrepo test suite, including new proofs that a real bare repository still opens, a separate Git directory is not misclassified as bare, and malformed .git metadata cannot downgrade to a fallback open.
I’m moving to the deletion-oriented part now: inventorying every remaining parser/cache call site and replacing each according to its caller-owned error policy.
Assistant
The first broad migration is now structurally in place: the old worktree-ID marker parser is deleted, both common-directory caches are deleted, and the known settings/review/investigate/trail/strategy/session/checkpoint callers now resolve explicit-root facts directly while keeping their local fail-open or fail-closed behavior.
I haven’t claimed it compiles yet; I’m finishing the remaining local parsers and then I’ll use compiler failures to catch missed imports/call sites.
Assistant
The first compile/test sweep is still running across the touched packages. That’s expected for this repository-sized set; once it returns I’ll treat failures as migration evidence rather than papering over them, especially around old cache-clearing test setup and caller-specific diagnostics.
Assistant
The focused tests caught a real error-classification regression at the repository boundary: outside a repository, callers historically saw fs.ErrNotExist; my new “possible bare repository” route had preserved the message but lost that machine-readable classification. I’m fixing the boundary itself so both the bare check and the original missing-metadata cause remain visible, instead of special-casing settings.
Assistant
The regression fix is confirmed by the isolated gitrepo and settings trust tests. The complete focused suite is still running; this pass covers all touched ownership areas plus the root CLI package, so it is the first meaningful end-to-end check of caller policies after cache/parser deletion.
Assistant
I’ve added operation-level process accounting using Git’s own Trace2 event stream. It measures complete representative operations rather than merely inspecting the resolver source, and encodes the historical-to-current counts for session construction, checkpoint queueing, prepare-commit-msg, status, and Codex discovery. I’m running it now to validate the expected counts against reality.
Assistant
The subprocess-count test has taken far longer than expected, which indicates one measured operation is blocking rather than a normal test-cost issue. I’m going to collect its current output and, if necessary, terminate only that test process; I won’t let a diagnostic test sit indefinitely.
Assistant
The trace did exactly what it was meant to do and corrected two assumptions:
prepare-commit-msg still runs one --git-common-dir query for repository-identity comparison. That is a genuine semantic safety check explicitly retained by the design, not duplicate filesystem traversal. Total Git processes fall from 4 to 2.
status has two existing semantic git log reads, so its correct total is 3, down from 4—not 1.
The other measured results matched immediately: session construction 2→1, checkpoint queue 1→0, and Codex discovery stays 1→1. I’m updating the assertions to distinguish retained semantic Git queries from forbidden metadata traversal.
Assistant
The structural diff is currently 497 insertions and 1,011 deletions across tracked files before counting the three new resolver/guard/operation test files, so the consolidation is genuinely deletion-oriented. The touched package suite is running again after the physical lock-identity change; no new subprocess or network work was introduced by that change.
Assistant
The only failure in the non-cached strategy run was a macOS /var versus /private/var assertion in the new alias test; the implementation correctly canonicalized both to one lock, and the corrected physical-path assertion now passes.
The root CLI package run is taking unusually long at the tool boundary again. I’m collecting the result now; the tests themselves have previously completed quickly once output was returned.
Assistant
Continuing from the implementation closeout: the canonical resolver and consumer migrations are in place. I’m checking whether the last fail-open/fail-closed regression tests landed, then I’ll finish the thermo-nuclear diff audit, run the repository-required checks, and update the local implementation document with exact evidence.
Assistant
The last policy tests did land. They now prove two important boundaries: required checkpoint/session metadata errors fail closed, optional redaction state still fails open, and repairing metadata is observed immediately—there is no hidden cache to clear. I found two closeout nits before running lint: one portable test-path issue and one avoidable test-global.
Assistant
Formatting is clean. The focused tests hit a sandbox restriction on the configured Go build cache, so I reran the same read/compile/test command with the requested cache access; it is still running. No code failure has been reported yet.
Assistant
Focused packages and operation-level tests pass. The measured hook-path deltas are now executable assertions: session construction 2→1 Git processes, checkpoint queue 1→0, prepare-commit-msg 4→2, status 4→3, and Codex discovery unchanged at 1; the remaining prepare-hook common-dir query is explicitly classified as repository-identity semantics, not filesystem traversal.
Assistant
Lint completed and found 21 mechanical issues, not behavioral failures. Most are expected fallout from deleting wrappers: missing contextual wrapping at new package boundaries, one obsolete test helper, and stale suppressions. I’m correcting those without changing caller policy or resolver behavior, then I’ll rerun formatting and lint in the required order.
Assistant
Lint is now clean after formatting. I’m at the strict maintainability pass now: reviewing the actual diff for hidden policy changes, duplicated seams, symlink identity mistakes, and accidental giant-file growth before trusting the broader CI run.
Assistant
The strict pass still supports the design. No import cycle, layout taxonomy, compatibility wrapper, or new production Git-open call appeared; the canonical module is 169-ish focused lines and the former owners shrink. The advisory 50-token duplication scan reports the repository’s existing 904 findings, but none in the new resolver/guard; the required 75-token lint threshold remains clean. I’m starting the full repository mise run check now (format, lint, unit, integration, and deterministic Vogon canary only).
Assistant
Full verification has completed formatting and lint successfully (0 issues). The race-enabled integration-tag test sweep is still running; early packages are passing and there is no failure output so far.
Assistant
The full race-enabled suite is still active and quiet, which is normal for the larger integration packages. I’m continuing to monitor it; no paid real-agent E2E command has been run.
Assistant
The full check found a real regression in two trail-worktree tests: the command printed macOS’s physical /private/var/... spelling instead of the caller-visible lexical /var/... spelling. This validates the review’s lexical-output constraint. The resolver itself preserves its explicit input; the trail caller was feeding it the physically spelled root returned by Git. I’m fixing that caller boundary so identity remains physical while script-visible output stays lexical.
Assistant
The lexical-path regression is fixed at the trail caller boundary, not by canonicalizing resolver output. Both previously failing worktree-creation tests now pass, including exact script-visible /var/... spelling, and the subprocess-count assertions remain unchanged. I’m rerunning the full required check from a freshly formatted tree.
Assistant
Second full check has formatting and lint clean again. The race-enabled repository suite is still running; cached early packages passed and no new failure has appeared.
Assistant
The race-enabled unit and integration sweep now passes across the repository, including the two fixed trail tests. The deterministic Vogon canary has started as the final mise run check stage; this is the allowed fake-agent suite, not paid E2E.
Assistant
The complete required check now passes: formatting, lint, race-enabled unit/integration tests, 56/56 Vogon canary cases, and 4/4 deterministic external-agent canary cases. I’m collecting final structural and branch evidence next, then I’ll write that exact status into the local implementation plan.
Assistant
One branch-state assumption changed during the long verification run: the local upstream/main ref advanced by four commits after the initial fast-forward, so the branch is now 4 commits behind again. I’m pausing document finalization to inspect those commits for overlap; I will only fast-forward if they are non-conflicting and preserve the completed changes.
Assistant
The four upstream commits are one merge plus three documentation/test-harness cleanups for the removed rewind command. They touch nine files outside this change, with no overlap in tracked or untracked paths and no material effect on the resolver design. The coordination-file hashes are still intact, so I’m safely fast-forwarding again before the final verification record.
Assistant
The final structural numbers now meet the accepted budget: session/state.go −76 lines, strategy/common.go −23, settings.go −3, status.go −24, both old cache/parser modules deleted, and total production Go is +557/−593 (net −36) including the new 185-line canonical module. I’m recording the implementation and proof in the local plan now.
Assistant
The final post-fast-forward check has formatting and lint clean (0 issues) and is running the race-enabled repository suite. This is the definitive verification run that will be recorded in the implementation document.
Assistant
The final race suite remains active with no failure output. I’m continuing to monitor through the deterministic canary stage; the worktree has not been committed or published.
Assistant
Still running quietly in the largest root package. The prior definitive run took roughly three minutes, so this duration is expected; there is still no failure signal.
Assistant
The post-fast-forward full run hit a strategy-package failure after the root and integration packages passed, but the tool truncated the specific failing test from the very large log. The immediately preceding full run passed this same package. I’m rerunning the strategy package alone with race and no cache to determine whether this is a real regression or an unrelated flake before updating the proof record.
Assistant
The isolated no-cache race rerun of ./cmd/entire/cli/strategy passes (39.749s), so the truncated failure was non-reproducing. I’m running the complete check once more to obtain a clean post-fast-forward gate; the document will record both the transient failure and this isolation result rather than hiding it.
Assistant
The complete race-enabled suite now passes again, including strategy (40.044s), confirming the prior strategy failure did not reproduce. The final deterministic canary is running now.
Assistant
The definitive post-fast-forward gate is clean: all race-enabled packages, Vogon 56/56, and deterministic external-agent 4/4 passed. I recorded the one non-reproducing strategy failure and its isolated pass in the plan. I’m doing the final branch/diff/symbol audit now; no further code changes are planned.
Assistant
One proof item was still only implicit: the ownership guard passed, but I had not shown that it actually trips. I’m doing a controlled mutation check now—temporarily adding one forbidden .git inspection, confirming the guard fails, removing the probe with a patch, and confirming the unchanged final tree passes again.
Assistant
The controlled mutation behaved correctly: the guard failed at the injected .git inspection with the ownership diagnostic, the probe was removed, and the focused guard test passed again. The final tree is restored; I’m checking its status one last time.
Assistant
Independent review verdict: the consolidation remains necessary, and the relationship-based, deletion-oriented design is correct.
Changed assumptions:
Branch was initially 30 commits behind, not 26.
upstream/main advanced another four unrelated documentation commits during validation.
Both safe fast-forwards preserved the coordination documents.
Branch and upstream/main now match at 879c755712031a84d3080efab4fb48f0e12fa0e4 (0 0 ahead/behind).
/go:discover-related was unavailable; code search plus Git/Entire history was used instead.
No upstream change had implemented or conflicted with this design.
Implemented:
Added the explicit-root, subprocess-free metadata.go.
Canonical facts are GitDir, CommonDir, and WorktreeID, with lexical paths preserved and physical identity used only where required.
Migrated all filesystem-metadata consumers.
Deleted both common-directory caches, old traversal helpers, worktree marker parsing, mutexes, cache tests, and wrappers.
Hardened gitrepo.OpenPath against unsafe fallback after metadata validation failure.
Added real-Git layout coverage, caller-policy tests, physical alias lock/store tests, operation-level process counting, and an AST ownership guard.
Proved the guard rejects a deliberately injected .git parser, then restored and re-ran it successfully.
Retained only semantic --git-common-dir queries for session adoption, repository equality, and trail worktree validation.
Subprocess evidence:
Operation
Before → after
Session store construction
2 → 1
Checkpoint queue
1 → 0
Prepare-commit-msg
4 → 2
Status
4 → 3
Codex discovery
1 → 1
Production Go totals are +557/-593, net -36 lines. session/state.go, strategy/common.go, , and all became smaller.
User
commit then changes
Assistant
I’m using the commit skill because you explicitly asked to commit the completed changes. I’ll inspect the final diff and repository status, stage only this implementation—including the two coordination documents unless the skill/repo guidance says otherwise—and create a conventional commit without pushing.
Assistant
The repository’s implementation plan explicitly marks the two coordination documents as local-only unless separately requested, so I’ll leave those untracked. I’m doing the final commit audit now and will stage only the implementation and tests.
Assistant
The final audit is clean: the branch still exactly matches upstream/main before these changes, git diff --check passes, and the scope is limited to the consolidation. I’m staging the CLI implementation now; both Markdown coordination files will remain untracked.
Assistant
Staged implementation and tests; coordination documents remain untracked.
Committing the staged consolidation with that message now. I’ll verify the resulting commit and confirm that only the two local coordination documents remain untracked.
repo: control-plane repository lifecycle — create, list, get, delete,
clone, plus the mirror and visibility subtrees. Git content operations
(log, diff, …) are intentionally out of scope. The mirror subtree is
server-side (create, list, get, remove, collaborators) with one
exception: mirror use repoints the current clone's git remote at a mirror
(local git config only — it creates nothing server-side). Interactively it
picks among the repo's placements and asks whether to replace the remote
(preserving the old URL under --upstream) or add a separate one;
non-interactively it repoints --remote directly. Both use and clone
choose a placement through the shared selectPlacement picker.
grant: manage access grants and org membership — org, project, and repo
each support add / list / remove
The accepted API is fixed and explicit-root: no CWD lookup, Git subprocess, cache, context parameter, resolver options, environment interpretation, symlink-canonicalized public output, or compatibility flags.
Resolver failures are all-or-error. Callers retain their existing fail-open, warning, fallback, or fail-closed policy; do not silently turn validation failures into a different repository-open path.
Worktree metadata resolution and opening a bare repository are distinct operations. A bare container is not a worktree, although gitrepo.OpenPath may still support deliberately opening a validated bare repository.
Genuine Git queries must remain Git queries. Consolidate filesystem metadata traversal, not branch/ref/object/config semantics.
Before doing any implementation:
First perform an extensive independent review and discuss/assess the current state. You own that review; this handoff only supplies starting context and accepted constraints.
Find the right repository from the current directory, a parent directory, or the usual workspace.
Read the local agent and repository instructions completely.
Use the thermo-nuclear-code-quality-review skill. Use Entire checkpoint/history tooling where available to distinguish checkpoint-backed intent, commit-message evidence, and inference from code.
Recheck the branch, worktree, current upstream/main, linked PR/comments, relevant CI state, recent commits, and current consumers. Safely account for the branch being 26 commits behind before editing.
Verify that a fast-forward will preserve the two untracked coordination documents and that upstream has not already implemented or materially changed this design. Stop if the branch has gained commits, has overlapping tracked changes, or the task has become stale or conflicting.
Decide independently whether consolidation remains necessary, whether the relationship-based and deletion-oriented direction is correct, and whether a smaller or cleaner structural move now exists.
Call out stale assumptions, import-cycle risks, hot-hook-path subprocess changes, error-semantic changes, symlink and moved-registration behavior, giant-file growth, and anything that should stop the work.
The repository instructions mention a go:discover-related workflow before Go implementation. If that facility is unavailable, state that and use code search plus history as the fallback rather than inventing or installing a tool.
Task:
If the independent review still supports the work, safely fast-forward the branch and implement the accepted consolidation in small, reviewable stages.
Add one focused canonical metadata module within gitrepo. Prefer a small facts value such as GitDir, CommonDir, and WorktreeID over a GitLayout enum or taxonomy.
Resolve directory-form and gitfile-form .git metadata, relative gitdir pointers, missing and relative commondir files, separate Git directories, linked worktrees, and linked submodules. Validate required metadata directories and return contextual errors.
Derive WorktreeID from the physical relationship between GitDir’s parent and CommonDir/worktrees. Do not use .git, .bare, or /modules/ string-marker branches.
Preserve lexical absolute output paths. Use physical canonicalization only at comparison, containment, deduplication, or locking boundaries that require identity.
Migrate every former filesystem-metadata consumer to the canonical resolver while preserving its existing user-facing policy and diagnostics.
Delete the session and checkpoint common-directory caches, their mutexes, clearing logic and cache-behavior tests, duplicate traversal functions, old worktree-ID path parsing, and temporary migration wrappers. Do not leave thin pass-through compatibility abstractions.
Make session state, checkpoint, strategy common, settings, and status modules smaller. The result should show net structural simplification and preferably net production-code deletion.
Add a source guard that prevents new independent parsing of .git, gitdir:, or commondir outside the canonical owner, with narrowly documented exceptions only where unavoidable.
Prove at the operation level that hot hook paths gain no Git subprocesses and preferably lose the common-dir subprocesses removed with the caches.
Non-goals and constraints:
Do not broaden this into hook-writer hardening, settings reserialization, unrelated cleanup, or changes to Codex diagnostics, warnings, trust, backlink, ownership, or installation semantics.
Do not reintroduce automatic writes from one worktree into another checkout.
Do not add resolver option flags for validation, symlink handling, environment handling, or backlink policy.
Do not create a new generic facade package.
Do not call git.Open, git.PlainOpen, or git.PlainOpenWithOptions outside the established gitrepo opening boundary.
Preserve upstream security and error-classification changes, especially recent path and symlink confinement and WorktreeRoot behavior.
Do not run paid real-agent E2E tests unless the user explicitly asks. The deterministic Vogon canary is allowed if relevant.
Do not push, merge, create or close issues or PRs, label, or post public comments unless explicitly told.
Validation:
Use real Git-created fixtures for valid layouts and small handmade fixtures only for malformed metadata.
Cover normal checkouts, conventional linked worktrees, .bare/worktrees layouts, standard bare repositories with linked worktrees, separate Git directories, ordinary submodules, linked submodules, relative gitdir and commondir, symlink aliases, moved registrations, and broken registrations.
Prove former consumers agree on common directory and worktree identity.
Prove errors remain caller-owned and that failed metadata resolution cannot silently downgrade to an unsafe repository-open fallback.
Prove physical aliases deduplicate lock and state identity where required without changing displayed or persisted lexical paths.
Run focused package tests during development, then repository formatting, lint, unit and integration checks required by local instructions. Do not run paid E2E.
Report exact commands and results, production line-count or deletion evidence, subprocess-count evidence, and any unverified edge case.
Output:
Start with the independent review verdict and any changed assumptions from current upstream/main.
If the design still holds, implement it rather than returning only another plan.
Keep changes scoped and explain any deviation from the accepted implementation document.
Update the local implementation document with exact status and proof so a later session can resume.
Do not push, merge, create or close issues or PRs, label, or post public comments unless explicitly told.
--ff-only
settings.go
status.go
Validation:
Final mise run check: passed.
Race-enabled unit and integration packages: passed.
Lint: 0 issues.
Vogon canary: 56/56 passed.
Deterministic external-agent canary: 4/4 passed.
mise run dup: completed; 904 existing advisory findings, none in the new resolver or guard.
git diff --check: passed.
No paid real-agent E2E ran.
One strategy race-suite failure occurred in an intermediate full run with its test name truncated; an immediate isolated no-cache rerun passed, and the subsequent complete check passed.
The full implementation record is in GIT_METADATA_TRAVERSAL_IMPLEMENTATION_PLAN.md. The changes remain uncommitted and unpushed.