AGENTS.md instructions for /Users/muskanpaliwal/Work/open-source/entire/cli/remove-stale-agent-rewind-code
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)
I’m using the browse skill to inspect PR #2187’s follow-up section and using-entire to recover the branch’s historical intent before changing code. I’ll turn the follow-up into a tracked task, implement it, and verify the relevant tests.
Assistant
The local browser helper isn’t installed, so I’m falling back to GitHub’s PR data. Entire is enabled and has checkpoint history; the worktree also has a pre-existing .entire/settings.json modification, which I’ll preserve. Beads couldn’t open its workspace database inside the sandbox, so I’m requesting the narrow permission needed to create and manage this task.
Assistant
The follow-up is concrete: remove stale rewind-era comments in Claude Code, Codex, and OpenCode integrations, update the security-contract test explanations, and delete the dead exported claudecode.FindCheckpointUUID API if its only remaining uses are tests. I’m checking the exact call graph and the checkpoint-backed intent before editing; the go:discover-related helper named by the repo instructions isn’t available in this session, so I’ll do the equivalent repository-wide symbol/pattern search directly.
Assistant
The code confirms the stale wording maps to today’s resume/log-restoration path: WriteSession restores a checkpoint transcript so the native agent can resume it, and session IDs from checkpoint metadata are validated before ResolveSessionFile. The historical checkpoint itself isn’t present in this clone, so that part is inferred from current call sites plus the recorded commit/PR descriptions. I’ll keep this follow-up narrow: remove the dead Claude Code wrapper and its integration assertion, while preserving the separately tested transcript primitives.
Assistant
The edit now removes every stale rewind reference named in the follow-up, and the deleted wrapper has no remaining call sites. I’m running focused agent-package and integration coverage first, then the repository formatting/lint sequence.
Assistant
Focused tests pass. Formatting is clean; lint’s local checks ran, but the Go lint stage was blocked by sandboxed cache access and its online schema fetch, so I’m rerunning the same lint command with the required access.
Assistant
The implementation and lint checks pass. Since this is a completed code change, I’m applying the repository’s commit skill next; it will preserve the unrelated .entire/settings.json edit and stage only the six follow-up files. The repo requires the full pre-commit mise run check, so I’ll run that before creating the checkpoint commit.
Assistant
The full pre-commit check is still running its race-enabled integration suite; formatting and all lint stages have already passed with zero issues. No real-agent E2E tests are being run—only the repository’s deterministic CI/canary path.
Assistant
The race-enabled suite is quiet but still active, which is normal for this repository’s aggregate test command. I’m continuing to wait for the definitive exit status rather than treating partial package output as success.
Assistant
The full check found one unrelated integration failure: TestExternalCommand_SigintReachesPlugin never observed its helper reach “ready” before the harness killed it. All changed agent packages and the targeted Claude helper integration test passed. I’m rerunning that single signal test to distinguish a transient harness failure from a reproducible branch problem.
Assistant
The second full mise run check passed end to end: formatting, zero lint issues, race-enabled unit/integration tests, Vogon 56/56, and Roger-Roger 4/4. I’m doing the final staged-diff audit now; the earlier signal-test failure passed both its isolated retry and this full rerun.
Removed dead ClaudeCodeAgent.FindCheckpointUUID and its integration assertion.
Replaced stale rewind terminology across Claude Code, Codex, OpenCode, and security-contract comments.
Preserved the separately tested transcript primitive.
mise run check passes completely.
Left .entire/settings.json unstaged and untouched.
Six files are staged. Proposed commit:
refactor(agent): remove stale rewind code
Should I commit it?
User
yupp
Assistant
Committing the staged six-file follow-up as refactor(agent): remove stale rewind code. The unrelated .entire/settings.json change will remain unstaged.
Assistant
Committed as 17c0809ff:
refactor(agent): remove stale rewind code
Full mise run check passed. The unrelated .entire/settings.json modification remains unstaged.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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). token
also takes --jurisdiction <slug> (e.g. us, eu), which instead mints a
jurisdictional identity token (RFC 8693 exchange, scope=openid,
aud=<jurisdiction host>) for that jurisdiction's entire-api cells (e.g.
https://aws-us-east-2.api.entire.io/api/v1), which reject the control-plane
bearer; it exchanges ENTIRE_TOKEN when set (deriving the environment from the
env token's aud), else the active login. auth status shows the caller's
home jurisdiction so the slug is discoverable. logout
takes --everywhere (revoke every session on the active core, not just the
current one) and --all-contexts (log out of every saved login)
doctor: bare runs the scan-and-fix flow, plus trace, logs, bundle
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
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
.entire Must Be a Directory
<worktree-root>/.entire is either absent or a real directory. A regular file, a
symlink — including a symlink pointing at a perfectly good directory — a
FIFO, a socket, or a device is a broken repo, and a command that would read or
write through the path stops instead.
The entries directly inside it must be regular files or directories. That is
an allowlist, not a list of known-bad types: Entire only ever creates files and
directories under .entire, so anything else arrived some other way and a mode
bit nobody has considered yet is refused by default. A symlinked
.entire/metadata redirects transcripts; a symlinked .entire/settings.local.json
redirects the file that names the command Entire executes at pre-push; a FIFO in
either place hangs the read instead. The scan is one level deep, and
fs.ModeIrregular is its one deliberate exception — see the entry-scan
mechanics below.
paths.ValidateEntireDirAt(worktreeRoot) / paths.RequireEntireDir(ctx)
(paths/entiredir.go) are the only implementation. The stat is Lstat, not
Stat, which is the whole point: .entire holds session metadata, transcripts,
and the redaction settings that decide what may be committed, so a path someone
else owns the far end of is not one we write through. Absent is fine (Entire is
not enabled yet, or enable is about to create it). A stat error other than
"not exist" is a failure — it is not evidence the invariant is violated, but it
is not evidence it holds either, and the caller's next move is to write there.
Not memoized, deliberately: the Lstat and the one-level listing are free next
to the git rev-parse that precedes them, and a cached "it was fine" is stale in
a long-lived entire mcp.
Four failure conditions, each identified positively.ErrEntireDirNotDirectory
(the path exists and is the wrong type), ErrEntireDirUnsupportedEntry (an entry
directly inside it is neither a regular file nor a directory), ErrEntireDirUnreadable (Lstat or the
directory listing failed, so nothing is known about the path), and
ErrRepositoryUnresolved (the worktree root would not resolve, so there is no
path to inspect yet). Callers print a remedy, and the remedies are different
things: replace the path, replace the entry, fix ownership/permissions, fix git.
Match them with errors.Is and give an unmatched error no remedy — an else
branch is how a filesystem EACCES came to be answered with advice about
safe.directory, printed directly under a line that already said "permission
denied". writeEntireDirRemedy and writeEntireDirDiagnosis (doctor's
labelled variant: BROKEN / UNREADABLE / UNVERIFIED) both take the error as a
parameter so every branch is reachable in a test; staging a genuinely
unreadable .entire is impractical, since removing execute permission on the
repo root breaks worktree-root discovery first and exercises the wrong branch.
An unsupported entry and a wrong-typed .entire share doctor's BROKEN heading:
to the reader they are one condition — something replaced a path Entire owns —
differing only in which path and what to put back.
ErrEntireDirNotDirectory is not reused for an unsupported entry, even though
both remedies are "replace it". .entire/settings.json is not required to be a
directory, so telling someone it is not one names the wrong problem. The entry
remedy says "replace it with a real file or directory"; the .entire remedy says
"replace it with a real directory", and TestEntireDirRemedyMatchesTheCondition
asserts neither branch prints the other's phrase.
Entry-scan mechanics.validateEntireDirEntries does one os.ReadDir and
passes each DirEntry.Type() to unsupportedEntryType, with no Lstat of its
own — the type comes from the directory read where the platform reports one,
and where it does not, os.ReadDir does the Lstat internally, skipping an
entry that vanished between the read and the stat. DirEntry.Type() is
therefore never unresolved, and Type() == 0 means a regular file, not unknown
(direntType returns ^FileMode(0) for unknown, which sets every bit including
ModeSymlink, so even a leak would fail closed). Adding an Lstat here
reintroduces that race, which matters because .entire/tmp and
.entire/metadata/<session> churn under concurrent hooks. The entries are
checked beforeReadDir's error, because os.ReadDir returns what it
managed to read alongside a partial-read error and an unsupported entry among
those is a positive finding — a stronger statement than "the listing failed". One
error names the first offender in ReadDir's sorted order (so the message is
deterministic) and counts the rest, rather than one error per entry: the remedy
is identical for all of them, and a user who reruns the command once per planted
entry is paying for our formatting.
fs.ModeIrregular is tolerated, and that is the one place the allowlist
bends. Windows overloads the bit: Go maps every reparse tag it has no category
for onto it (the default arm of fileStat.mode in os/types_windows.go),
which lands NTFS directory junctions and OneDrive Files On-Demand placeholders
in the same bucket, indistinguishable from a DirEntry. Refusing the bucket
would hard-fail every command in a repo inside a synced folder, with a remedy the
user cannot act on, and the placeholder arrives with nobody attacking anything.
The junction it would also catch cannot arrive by checkout — git has no
tree-object mode for one — so planting it already requires local code execution,
at which point this check is not what stands in the way. The bit is masked
out of the type, not matched against it — mode.Type() &^ fs.ModeIrregular
must equal 0 or fs.ModeDir — because Windows does not hand it over alone:
ModeDir is withheld only for a name-surrogate reparse tag, and the cloud
tags are not surrogates, so a placeholder directory arrives as
ModeDir|ModeIrregular while a junction (a surrogate) arrives as
ModeIrregular by itself. .entire's own entries are mostly directories, so an
exact match on the bare bit would reject metadata, logs, and tmp in exactly
the synced folder the tolerance exists for. Masking does not soften the rest of
the field: anything carrying a rejected type is rejected whatever else it
carries, ModeIrregular included.
The comparison is against the whole type field, never IsRegular/IsDir.
Those examine single bits (IsDir is mode&ModeDir != 0), so an allowlist
keyed on them lets a rejected type in by also setting an accepted bit:
ModeDir|ModeSymlink and ModeDir|ModeNamedPipe both satisfy IsDir, and so
does the all-bits-set unknown mode above — which is what made the "even a leak
would fail closed" claim false until it was fixed. An allowlist a rejected type
can enter by setting an extra bit is not an allowlist.
TestUnsupportedEntryType pins each combination. Distinguishing junction from
placeholder would mean reading the reparse tag through a
Windows-only syscall (FindFirstFile, then Reserved0 & 0x20000000 for the
name-surrogate tags); that is the upgrade path if junctions ever become worth
catching.
A settings file is never read through a link, and the settings reader enforces
that itself.readConfined (settings/settings.go) — the chokepoint every
settings read funnels through, including LoadFromFile, LoadProjectRaw,
LoadLocalRaw, and clone preferences — Lstats the entry through its own
os.Root handle and refuses a symlink outright, wrapping
paths.ErrEntireDirUnsupportedEntry via the shared paths.SymlinkedEntryError
(the symlink-specific message builder, which names the link target; the entry
scan reaches it through unsupportedEntryError and describes other types with
describeMode).
This is deliberately redundant with the .entire entry scan, because the two
cover different callers: the scan hangs off the root pre-run and
LoadEntireSettings, while eighteen files call settings.Load directly —
strategy/hooks.go, manual_commit_hooks.go, checkpoint/remote/*, review/*,
investigate/* — and reach settings without ever passing the pre-run.
os.Root confinement is not the invariant, and was not sufficient. Measured
against readConfined before the change: an absolute target (even one pointing
inside .entire) and an escaping relative target were refused, but as path escapes from parent, naming neither cause nor fix; and two shapes got through:
The dangling case was the worse of the two: every caller reads ENOENT as
"absent", so a planted link made Entire ignore the project's settings without
saying anything. Do not "simplify" the Lstat away on the grounds that
os.OpenRoot already confines the read — it confines it, which is a different
property from refusing a link.
Writes are already safe and need no equivalent: jsonutil.WriteFileAtomic
finishes with os.Rename over the target, which replaces a symlink rather
than writing through it.
Non-goals, deliberately. The scan is not recursive — walking deeper would
traverse every session's transcripts on every command, and the checkpoint writer
already skips symlinks as it walks the metadata directory. It does not look at
permissions or ownership, only at type. Relocating .entire/logs and
.entire/tmp out of the worktree is a separate change; until then, redirecting
them with a symlink is refused rather than supported,