e2e/: E2E tests with real agent calls (see e2e/README.md)
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. Named after the Vogons from The Hitchhiker's Guide to the Galaxy — bureaucratic, procedural, and deterministic to a fault.
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
mise run test:e2e --agent gemini-cli [filter] # Gemini CLI only
mise run test:e2e --agent opencode [filter] # OpenCode only
mise run test:e2e --agent cursor [filter] # Cursor only
mise run test:e2e --agent factoryai-droid [filter] # Factory AI Droid only
mise run test:e2e --agent copilot-cli [filter] # Copilot CLI only
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, 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, 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.
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.
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.
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, just 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, so it is a low-risk local-only change. 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:
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 when they're listed in .gitignore. This would destroy .entire/ and .worktrees/ directories.
See HardResetWithProtection() in common.go and CheckoutBranch() in git_operations.go for examples.
Regression tests in hard_reset_test.go verify this behavior - if go-git v6 fixes this issue, those tests can be used to validate switching back.
Repo Root vs Current Working Directory
Always use repo root (not os.Getwd()) when working with git-relative paths.
Git commands like git status and worktree.Status() return paths relative to the repository root, not the current working directory. When an agent runs from a subdirectory (e.g., /repo/frontend), using os.Getwd() to construct absolute paths will produce incorrect results for files in sibling directories.
This also affects path filtering. The paths.ToRelativePath() function rejects paths starting with .., so computing relative paths from cwd instead of repo root will filter out files in sibling directories:
When to use os.Getwd(): Only when you actually need the current directory (e.g., finding agent session directories that are cwd-relative).
When to use repo root: Any time you're working with paths from git status, git diff, or any git-relative file list.
Test case in state_test.go: TestFilterAndNormalizePaths_SiblingDirectories documents this bug pattern.
Session Strategy (cmd/entire/cli/strategy/)
The CLI uses a manual-commit strategy for managing session data and checkpoints. The strategy implements the Strategy interface defined in strategy.go.
Strategy Interface
The Strategy interface provides:
SaveStep() - Save session step checkpoint (code + metadata)
SaveTaskStep() - Save subagent task step checkpoint
GetRewindPoints() / Rewind() - List and restore to checkpoints
GetSessionLog() / GetSessionInfo() - Retrieve session data
ListSessions() / GetSession() - Session discovery
How It Works
The manual-commit strategy (manual_commit*.go) does not modify the active branch - no commits are created on the working branch. Instead it:
Creates shadow branch entire/<HEAD-commit-hash[:7]>-<worktreeHash[:6]> per base commit + worktree
Worktree-specific branches - each git worktree gets its own shadow branch namespace, preventing conflicts
Supports multiple concurrent sessions - checkpoints from different sessions in the same directory interleave on the same shadow branch
Condenses session logs to permanent entire/checkpoints/v1 branch on user commits
Builds git trees in-memory using go-git plumbing APIs
Rewind restores files from shadow branch commit tree (does not use git reset)
Location-independent transcript resolution - transcript paths are always computed dynamically from the current repo location (via agent.GetSessionDir + agent.ResolveSessionFile), never stored in checkpoint metadata. This ensures restore/rewind works after repo relocation or across machines.
Copilot token scoping - Copilot CLI session.shutdown contains session-wide token aggregates. Checkpoint metadata must stay scoped to CheckpointTranscriptStart; condensation may separately backfill full-session Copilot totals into session state for entire status.
Tracks session state in .git/entire-sessions/ (shared across worktrees)
Shadow branch migration - if user does stash/pull/rebase (HEAD changes without commit), shadow branch is automatically moved to new base commit
Orphaned branch cleanup - if a shadow branch exists without a corresponding session state file, it is automatically reset when a new session starts
PrePush hook can push entire/checkpoints/v1 branch alongside user pushes
Safe to use on main/master since it never modifies commit history
{
"checkpoint_id": "abc123def456",
"session_id": "2026-01-13-uuid", // Current/latest session
"session_ids": ["2026-01-13-uuid1", "2026-01-13-uuid2"], // All sessions
"session_count": 2, // Number of sessions in this checkpoint
"strategy": "manual-commit",
"created_at": "2026-01-13T12:00:00Z",
"files_touched": ["file1.txt", "file2.txt"] // Merged from all sessions
}
When multiple sessions are condensed to the same checkpoint (same base commit):
Sessions are stored in numbered subfolders using 0-based indexing (0/, 1/, 2/, etc.)
Latest session is always in the highest-numbered folder
session_ids array tracks all sessions, session_count increments
Session State (filesystem, .git/entire-sessions/):
code
<session-id>.json # Active session state (base_commit, checkpoint_count, etc.)
Checkpoint ID Linking
The strategy uses a 12-hex-char random checkpoint ID (e.g., a3b2c4d5e6f7) as the stable identifier linking user commits to metadata.
How checkpoint IDs work:
Generated once per checkpoint: When condensing session metadata to the metadata branch
Added to user commits via Entire-Checkpoint trailer:
Manual-commit: Added via prepare-commit-msg hook (user can remove it before committing)
Used for directory sharding on entire/checkpoints/v1 branch:
Path format: <id[:2]>/<id[2:]>/
Example: a3b2c4d5e6f7 → a3/b2c4d5e6f7/
Creates 256 shards to avoid directory bloat
Appears in commit subject on entire/checkpoints/v1 commits:
Format: Checkpoint: a3b2c4d5e6f7
Makes git log entire/checkpoints/v1 readable and searchable
Bidirectional linking:
code
User commit → Metadata:
Extract "Entire-Checkpoint: a3b2c4d5e6f7" trailer
→ Read a3/b2c4d5e6f7/ directory from entire/checkpoints/v1 tree at HEAD
Metadata → User commits:
Given checkpoint ID a3b2c4d5e6f7
→ Search user branch history for commits with "Entire-Checkpoint: a3b2c4d5e6f7" trailer
Note: Commit subjects on entire/checkpoints/v1 (e.g., Checkpoint: a3b2c4d5e6f7) are
for human readability in git log only. The CLI always reads from the tree at HEAD.
Example:
code
User's commit (on main branch):
"Implement login feature
Entire-Checkpoint: a3b2c4d5e6f7"
↓ ↑
Linked via checkpoint ID
↓ ↑
entire/checkpoints/v1 commit:
Subject: "Checkpoint: a3b2c4d5e6f7"
Tree: a3/b2c4d5e6f7/
├── metadata.json (checkpoint_id: "a3b2c4d5e6f7")
├── full.jsonl (session transcript)
└── prompt.txt
Commit Trailers
On user's active branch commits:
Entire-Checkpoint: <checkpoint-id> - 12-hex-char ID linking to metadata on entire/checkpoints/v1
Added via prepare-commit-msg hook; user can remove it before committing to skip linking
On shadow branch commits (entire/<commit-hash[:7]>-<worktreeHash[:6]>):
Entire-Session: <session-id> - Session identifier
Entire-Metadata: <path> - Path to metadata directory within the tree
Entire-Strategy: manual-commit - Strategy that created the commit
On metadata branch commits (entire/checkpoints/v1):
Commit subject: Checkpoint: <checkpoint-id> (or custom subject for task checkpoints)
Trailers:
Entire-Session: <session-id> - Session identifier
Entire-Strategy: <strategy> - Strategy name (manual-commit)
Entire-Agent: <agent-name> - Agent name (optional, e.g., "Claude Code")
Ephemeral-branch: <branch> - Shadow branch name (optional)
Entire-Metadata-Task: <path> - Task metadata path (optional, for task checkpoints)
Note: The strategy keeps active branch history clean - the only addition to user commits is the single Entire-Checkpoint trailer. It never creates commits on the active branch (the user creates them manually). All detailed session data (transcripts, prompts, context) is stored on the entire/checkpoints/v1 orphan branch or shadow branches.
Multi-Session Behavior
Concurrent Sessions:
When a second session starts in the same directory while another has uncommitted checkpoints, a warning is shown
Both sessions can proceed - their checkpoints interleave on the same shadow branch
Each session's RewindPoint includes SessionID and SessionPrompt to help identify which checkpoint belongs to which session
On commit, all sessions are condensed together with archived sessions in numbered subfolders
Note: Different git worktrees have separate shadow branches (worktree-specific naming), so concurrent sessions in different worktrees do not conflict
Orphaned Shadow Branches:
A shadow branch is "orphaned" if it exists but has no corresponding session state file
This can happen if the state file is manually deleted or lost
When a new session starts with an orphaned branch, the branch is automatically reset
If the existing session DOES have a state file (concurrent session in same directory), a SessionIDConflictError is returned
Shadow Branch Migration (Pull/Rebase):
If user does stash → pull → apply (or rebase), HEAD changes but work isn't committed
The shadow branch would be orphaned at the old commit
Detection: base commit changed AND old shadow branch still exists (would be deleted if user committed)
Action: shadow branch is renamed from entire/<old-hash>-<worktreeHash> to entire/<new-hash>-<worktreeHash>
Session continues seamlessly with checkpoints preserved
When Modifying the Strategy
The strategy must implement the full Strategy interface
Test with mise run test - strategy tests are in *_test.go files
Update both CLAUDE.md and AGENTS.md when modifying the strategy to keep documentation current
Important Notes
Before committing: Follow the "Before Every Commit (REQUIRED)" checklist above - CI will fail without it
Integration tests: run mise run test:integration when changing integration test code
When adding new features, ensure they are well-tested and documented.
Always check for code duplication and refactor as needed.
Go Code Style
Write lint-compliant Go code on the first attempt. Before outputting Go code, mentally verify it passes golangci-lint (or your specific linter).
Follow standard Go idioms: proper error handling, no unused variables/imports, correct formatting (gofmt), meaningful names.
Handle all errors explicitly—don't leave them unchecked.
Reference .golangci.yml for enabled linters before writing Go code.
Accessibility
The CLI supports an accessibility mode for users who rely on screen readers. This mode uses simpler text prompts instead of interactive TUI elements.
Environment Variable
ACCESSIBLE=1 (or any non-empty value) enables accessibility mode
Users can set this in their shell profile (.bashrc, .zshrc) for persistent use
Implementation Guidelines
When adding new interactive forms or prompts using huh:
In the cli package:
Use NewAccessibleForm() instead of huh.NewForm():
go
// Good - respects ACCESSIBLE env var
form := NewAccessibleForm(
huh.NewGroup(
huh.NewSelect[string]().
Title("Choose an option").
Options(...).
Value(&choice),
),
)
// Bad - ignores accessibility setting
form := huh.NewForm(...)
In the strategy package:
Use the isAccessibleMode() helper. Note that WithAccessible() is only available on forms, not individual fields, so wrap confirmations in a form:
go
form := huh.NewForm(
huh.NewGroup(
huh.NewConfirm().
Title("Confirm action?").
Value(&confirmed),
),
)
if isAccessibleMode() {
form = form.WithAccessible(true)
}
if err := form.Run(); err != nil { ... }
Key Points
Always use the accessibility helpers for any huh forms/prompts
Test new interactive features with ACCESSIBLE=1 to ensure they work
The accessible mode is documented in --help output
The attach CLI command needs to be updated to support the v2 write path for checkpoints. It should support dual writes and only write to v2 if v2 is enabled. v2 writes for checkpoints need to end up in refs/entire/checkpoints/v2/main:[...]/[...]/0/transcript.jsonl as an example with the full.jsonl files (or equivalent if we're not writing full.jsonl anymore) to refs/entire/checkpoints/v2/full.jsonl
Assistant
I’m tracing the current attach command and the existing v2 checkpoint write path first, so I can wire dual writes into the same patterns the repo already uses instead of inventing a parallel implementation.
Assistant
I found that v2 writes already exist behind settings.IsCheckpointsV2Enabled(), and the attach path is still isolated in cmd/entire/cli/attach.go. I’m reading the existing v2 condensation/write helpers next so attach can reuse the same metadata and ref layout.
Assistant
I’ve confirmed attach currently only does a direct v1 WriteCommitted, while the regular condensation path precomputes CompactTranscript and then best-effort dual-writes to v2. Next I’m checking the attach test harness and v2 read/layout tests so I can add targeted coverage without duplicating the existing helper logic.
Assistant
There’s one semantic edge I need to pin down before editing: if attach adds a session onto a commit that already has a v1 checkpoint from before v2 was enabled, a naive v2 write would create a partial v2 copy of that checkpoint and could shadow the complete v1 one. I’m checking the existing resolve/dedup logic now so I can avoid introducing that inconsistency.
Assistant
I’ve got the shape of the fix: attach should build the same WriteCommittedOptions v2 expects, write v1 first, then do a best-effort v2 write. For the tricky case where attach appends to a pre-v2 checkpoint, I’m wiring it to backfill the whole checkpoint from v1 into v2 so we don’t create a partial v2 shadow.
Assistant
I’ve made the attach-side v2 wiring. Next I’m adding focused tests for the two cases that matter here: a brand-new attach with v2 enabled, and attaching onto an older v1-only checkpoint after v2 gets turned on.
Assistant
I’ve patched the code and tests. I’m formatting and running the attach-focused test set now to catch any compile or behavior regressions before widening out.
Assistant
The first test run was blocked by the sandbox trying to write to the default Go build cache. I’m rerunning with GOCACHE pointed at /tmp so we can execute the test suite inside the workspace constraints.
Assistant
The attach unit and integration tests are passing. I’m doing one small cleanup pass now to drop a helper I ended up not needing so the diff stays tight before the final verification run.
Assistant
Updated attach to dual-write checkpoints through the existing v2 store in attach.go. It now builds CompactTranscript for v2 /main, writes v1 first, then writes v2 only when checkpoints_v2 is enabled. For attaches onto an existing pre-v2 checkpoint, it backfills the full checkpoint from v1 into v2 instead of creating a partial v2 shadow, so reads won’t prefer an incomplete v2 copy. The v2 artifacts follow the current repo layout: refs/entire/checkpoints/v2/main/.../0/transcript.jsonl for compact transcript data and refs/entire/checkpoints/v2/full/current/.../0/raw_transcript for the full transcript equivalent.
Added coverage in attach_test.go for both a fresh v2-enabled attach and the legacy v1-only checkpoint backfill case.
Verified with:
env GOCACHE=/tmp/go-build-cache go test ./cmd/entire/cli -run 'TestAttach_' -count=1env GOCACHE=/tmp/go-build-cache go test -tags=integration ./cmd/entire/cli/integration_test -run 'TestAttach_' -count=1
User
explain backfillAttachCheckpointToV2
Assistant
backfillAttachCheckpointToV2 exists to handle one specific edge case: attach is adding a session to a checkpoint that already exists in v1, but v2 was not enabled when that checkpoint was originally created. In that situation, writing only the newly attached session to v2 would create a partial v2 copy of the checkpoint, and later v2-preferring reads could see incomplete data. The function avoids that by rebuilding the entire checkpoint in v2 from the authoritative v1 copy. See attach.go.
What it does:
It reads the v1 checkpoint summary with v1Store.ReadCommitted(...) to discover all sessions already in that checkpoint, not just the one being attached. attach.go
It loops over every session index in that summary and loads each full session payload from v1 with ReadSessionContent(...). attach.go
For each session, it reuses the migration path helper buildMigrateWriteOpts(...) to reconstruct WriteCommittedOptions for v2 from the v1 metadata and transcript. That keeps attach aligned with the existing v1→v2 conversion logic instead of inventing a second mapping. attach.go, migrate.go
If a compact transcript can be generated, it adds CompactTranscript plus the correct compact offset via computeCompactOffset(...), so v2 /main gets transcript.jsonl and correct checkpoint_transcript_start. attach.go, migrate.go
It writes each session into v2 with v2Store.WriteCommitted(...). Because v2 deduplicates by SessionID, this reconstructs the checkpoint incrementally without duplicating already-known sessions. attach.go
If any session is a task checkpoint, it also copies task metadata trees into v2 /full/current, matching the existing migration behavior. attach.go
So the short version is: it is a targeted “repair/backfill” path for legacy v1-only checkpoints, used during attach, to ensure that once v2 is enabled the whole checkpoint appears in v2 consistently rather than only the newest attached session.
User
wouldn't that already get handled by entire migrate?
Assistant
Yes, entire migrate can repair or backfill this later. But relying on that would leave attach able to create broken intermediate state now.
The problem is timing:
attach can add a session to an existing v1-only checkpoint while checkpoints_v2 is already enabled.
If attach wrote only the new session into v2, that checkpoint would now exist in both places:
complete in v1
partial in v2
Once v2 is preferred, readers may choose the v2 copy just because it exists. At that point the checkpoint appears incomplete until someone runs entire migrate.
So backfillAttachCheckpointToV2 is there to make attach itself safe and self-contained. It ensures that after attach returns, the checkpoint is already coherent in v2. See attach.go and attach.go.
migrate is still useful for bulk repair/backfill across the repo. But attach should not depend on a later maintenance command to make its own write path correct. If it did, the workflow would be:
run attach
checkpoint becomes partially visible in v2
resume/explain/etc. may read incomplete data
run entire migrate to fix it
That’s the inconsistency this helper avoids.
User
I'm confused. why would the checkpoint be partially visible in v2 without this backfill function? write the case this is solving and how to reproduce it
Assistant
The case is:
A checkpoint already exists only in v1.
Later, checkpoints_v2 gets enabled.
You run entire attach on the same commit, so attach reuses that existing checkpoint ID.
If attach only wrote the newly attached session to v2, v2 would now contain that checkpoint ID, but only one of its sessions.
That is what “partially visible in v2” means.
Why this happens:
attach does not always create a new checkpoint.
If HEAD already has an Entire-Checkpoint: <id> trailer, attach reuses that checkpoint ID and appends another session to it. See attach.go.
With v2 enabled, readers prefer v2 when that checkpoint ID exists there. See committed_reader_resolve.go.
So without the backfill helper, this sequence would be possible:
v1 checkpoint abc123def456 has sessions S1 and maybe S2
v2 has no abc123def456 yet
attach adds session S3 to abc123def456
naive v2 write writes only S3 into refs/entire/checkpoints/v2/.../abc123def456/...
now ResolveCommittedReaderForCheckpoint(..., preferCheckpointsV2=true) sees the checkpoint in v2 and uses it
but v2 only knows about S3, while v1 knows about S1, S2, and S3
So the checkpoint is “visible” in v2, but incomplete.
Concrete reproduction
You can reproduce the bad case conceptually like this if the backfill code were removed:
Start with v2 disabled.
Create a checkpoint on commit C so it exists only in v1.
Enable checkpoints_v2.
Keep HEAD on the same commit C with the existing Entire-Checkpoint trailer.
Run entire attach <new-session>.
At that point:
resolveCheckpointID() reuses the checkpoint ID from
User
Why would 2 happen before 5? if the session isn't attached, why would the checkpoint be there
Assistant
Because the checkpoint can already belong to a different session.
The session being attached is not the reason the checkpoint exists. The checkpoint may already be on HEAD from an earlier session, and attach is adding another session into that same checkpoint.
The concrete case is:
Session A was already captured earlier.
This could have happened via normal hooks, or via an earlier entire attach.
That created checkpoint X and put Entire-Checkpoint: X on the current commit.
At that time, checkpoints_v2 was off, so X exists only in v1.
Later, a separate session B happens against the same commit, but hooks don’t capture it, so B is unattached.
Now you enable checkpoints_v2.
You run entire attach <session-B>.
attach sees that HEAD already has checkpoint X, so it reuses X instead of creating a new checkpoint. That behavior is in attach.go.
So without backfill, v2 would get only session B, while v1 already had session A and now also B.
That is the inconsistency:
v1 checkpoint X = A + B
v2 checkpoint X = B only
So the issue is not “why would the checkpoint exist before the session is attached?”
It exists because it came from an earlier session on the same commit.
A realistic example:
You make a code change with Claude and commit it. Hooks work. Checkpoint X is created.
Later you do a research/debug session on the same commit, but hooks were missing or broken.
You run entire attach for that research session.
attach adds that research session into existing checkpoint X, not a new checkpoint.
That exact scenario is what TestAttach_V2BackfillsExistingV1OnlyCheckpoint is modeling.
User
attach with v2 enabled should always write it to v1 and v2 as per the settings. I still do not understand why backfill is necessary.
Assistant
The key distinction is between:
writing the attached session to v2
writing the full checkpoint state to v2
attach only has one new session in hand. If it simply dual-writes that one session to v2, that is not enough when the checkpoint ID already existed in v1.
Why:
attach reuses the existing checkpoint ID from HEAD if there is already an Entire-Checkpoint trailer. See attach.go.
v1 WriteCommitted merges that session into the existing v1 checkpoint.
v2 WriteCommitted can only merge against what already exists in v2, not what exists in v1.
That last part is the whole issue.
V2GitStore.WriteCommitted only reads the existing summary from the v2 /main ref. If the checkpoint does not already exist in v2, it creates a fresh checkpoint with just the session being written. See v2_committed.go and v2_committed.go.
So the problematic case is:
Before attach
v1 checkpoint X exists with session A
v2 checkpoint X does not exist yet
HEAD already has Entire-Checkpoint: X
Then attach session B with v2 enabled
v1 write updates checkpoint X to contain A + B
naive v2 write creates checkpoint X with only B, because v2 had no prior copy of X
After attach without backfill
v1 X = A + B
v2 X = B only
That is why “write to v1 and v2” is not sufficient by itself. If you only write the attached session to both places, the two stores diverge whenever the checkpoint already existed only in v1.
So:
If by “write it to v1 and v2” you mean “write only the newly attached session”, backfill is necessary.
If by “write it to v1 and v2” you mean “make both stores contain the entire checkpoint after attach”, then yes, that is exactly what backfillAttachCheckpointToV2 is doing.
A minimal reproduction:
Disable checkpoints_v2
Create checkpoint X on HEAD from session A
Enable checkpoints_v2
Run entire attach for session B on that same HEAD
Without backfill:
v1: X = [A, B]
v2: X = [B]
With backfill:
v1: X = [A, B]
v2: X = [A, B]
That’s the case the helper solves.
User
Instead of calling the function writeAttachCheckpointV2IfEnabled and doing the check in the function, I think we should have the conditional for the settings check be moved outside of that function, and have it be something like if settings.IsCheckpointsV2Enabled(ctx) writeAttachCheckpointV2`
Assistant
I’m moving the v2 settings guard to the call site and renaming the helper so the control flow is explicit in runAttach, then I’ll rerun the attach tests.
Assistant
The guard is now at the call site and the helper is just the write path. I’m formatting and rerunning the attach-focused tests to make sure nothing regressed.
Assistant
Updated in attach.go so the settings check now sits at the call site:
if settings.IsCheckpointsV2Enabled(logCtx) { writeAttachCheckpointV2(...) }
and the helper is now writeAttachCheckpointV2, with no internal feature-flag guard. That makes the control flow clearer in runAttach.
Verified with:
env GOCACHE=/tmp/go-build-cache go test ./cmd/entire/cli -run 'TestAttach_' -count=1
I’m using the gh-address-comments skill for this. First I’ll verify GitHub CLI auth and inspect PR 955’s review comments so I can summarize the actionable issues against the current branch state.
Assistant
gh is not authenticated for github.com in this environment. The active token is invalid, so I can’t inspect PR 955’s review comments yet.
Run gh auth login -h github.com and then tell me to continue. After that I’ll fetch the review threads, number them, and summarize what each one would require to address.
User
ok I did it, try again
Assistant
I’m rechecking gh auth, then I’ll fetch PR 955’s review threads and turn them into a numbered action list so you can choose what to address.
Assistant
gh auth is working. I found the review-fetch script in the skill bundle, and I’m using it next to pull PR 955’s threads directly from GitHub.
Assistant
I found 1 actionable review thread on PR 955.
attach.go
Copilot says writeAttachCheckpointV2 uses isExistingCheckpoint as a proxy for “missing in v2”, which is too broad. If a checkpoint already exists in both v1 and v2, the current code will still run the full v1→v2 backfill instead of just appending the new attached session to v2. That means unnecessary rewrites, extra v2 commits, and potentially reintroducing older raw transcripts into /full/current.
What fixing it would require:
Check whether the checkpoint already exists in v2 first.
If v2 already has it, call v2Store.WriteCommitted(ctx, opts) directly.
If v2 does not have it, run backfillAttachCheckpointToV2(...).
Treat unexpected v2 read errors as warnings or failures consistently with the current best-effort dual-write behavior.
Add or adjust tests for:
existing checkpoint in both v1 and v2 → append only
existing checkpoint only in v1 → backfill
brand-new checkpoint → normal dual-write
If you want, I can address comment 1 now.
User
Address it please
Assistant
I’m tightening the attach v2 path so it only backfills when the checkpoint is missing from v2, then I’ll add a regression test for the dual-write case where the checkpoint already exists in both stores.
Assistant
I found a way to make the regression test actually detect the bad path: when attach unnecessarily backfills an already-dual-written checkpoint, it creates extra v2 commits. I’m adding a test that checks the new v2 refs advance by exactly one commit on the second attach.
Assistant
The code change is in. I’ve added a regression test that fails if a second attach on an already-dual-written checkpoint causes multi-step v2 history instead of a single append.
Assistant
The new guard exposed a mismatch in the v2 read API: on a repo with no v2 refs yet, ReadCommitted isn’t coming back as the sentinel I assumed. I’m checking that path and then I’ll normalize the missing-v2 case so attach still backfills correctly.
Assistant
The v2 reader returns “missing” as summary == nil, err == nil, not as ErrCheckpointNotFound. I’m updating the attach path to treat that as the backfill case, which is why the v1-only regression test started failing.
Assistant
The attach unit tests are green again with the v2 existence check in place. I’m running the attach integration suite once more to make sure the new branch-selection logic didn’t affect the end-to-end path.
Assistant
Addressed the review comment in attach.go. writeAttachCheckpointV2 now checks whether the checkpoint already exists in v2 before deciding what to do:
if the checkpoint is already present in v2, it appends with v2Store.WriteCommitted(...)
if the checkpoint is missing from v2, it backfills from v1 with backfillAttachCheckpointToV2(...)
I also added a regression test in attach_test.go that verifies a second attach on an already-dual-written checkpoint advances each v2 ref by exactly one commit, which would fail if we unnecessarily re-backfilled the whole checkpoint.
Verification:
env GOCACHE=/tmp/go-build-cache go test ./cmd/entire/cli -run 'TestAttach_' -count=1env GOCACHE=/tmp/go-build-cache go test -tags=integration ./cmd/entire/cli/integration_test -run 'TestAttach_' -count=1
User
I think the backfill case should be removed entirely and entire migrate should be what backfills
Assistant
I’m removing the attach-time backfill path and tightening the tests around the new behavior. That will make attach only dual-write the attached session to v2 and leave any full v1→v2 repair to entire migrate.
Assistant
I’ve confirmed the backfill path is fully isolated in attach.go. I’m deleting it, simplifying the v2 helper to a straight write, and replacing the old backfill test with one that locks in the new “migrate owns backfill” behavior.
Assistant
The code now matches the design you described: attach never tries to mirror prior v1-only state into v2. I’m formatting and rerunning the attach-focused test suites to catch any fallout from removing the helper.
Assistant
Unit tests are green. The integration run is still in flight; I’m waiting on that before I summarize the change so I can call out the exact verification status.
Assistant
Changed attach to stop backfilling v1-only checkpoints into v2. In attach.go, writeAttachCheckpointV2 is now just a straight v2 WriteCommitted when checkpoints_v2 is enabled, and the attach-specific backfill helper is gone.
I updated the attach tests to match that behavior. The old backfill test is now REDACTED, which asserts that after enabling v2 and attaching onto an existing v1-only checkpoint, v2 contains only the newly attached session until entire migrate backfills the older v1 state.
Verified with:
env GOCACHE=/tmp/go-build-cache go test ./cmd/entire/cli -run 'TestAttach_' -count=1env GOCACHE=/tmp/go-build-cache go test -tags=integration ./cmd/entire/cli/integration_test -run 'TestAttach_' -count=1
If you want, I can also draft the PR reply for the review thread to explain that backfill was intentionally removed and delegated to entire migrate.
User
REDACTED this can be removed entirely
Assistant
I’m removing that test entirely and then rerunning the attach unit suite to make sure there are no leftover unused imports or helpers.
Assistant
The test is removed. I’m formatting and running the attach tests now to clean up any unused imports and confirm the remaining coverage still passes.
Assistant
There’s one stale import left from the removed test. I’m deleting it and rerunning the attach checks.
Assistant
Removed REDACTED from attach_test.go and cleaned up the unused checkpoint test import it left behind.
Verified with:
env GOCACHE=/tmp/go-build-cache go test ./cmd/entire/cli -run 'TestAttach_' -count=1env GOCACHE=/tmp/go-build-cache go test -tags=integration ./cmd/entire/cli/integration_test -run 'TestAttach_' -count=1
User
clean up the tests please, we don't need to have duplicate things that are already tested in there twice. just make sure v2 is called when it's enabled and the reverse case.
Assistant
I’m trimming the attach unit tests down to the two behaviors you want locked in: v2 writes happen when enabled, and no v2 refs are written when disabled. Then I’ll rerun the attach test suites.
Assistant
I found the duplication: the second v2 test is asserting a more specific append path than you want here. I’m replacing it with a single disabled-case test so the pair is just enabled vs disabled.
Assistant
The attach unit coverage is now down to the simple enabled/disabled pair. I’m formatting and rerunning the attach tests to make sure the cleanup didn’t leave any stale assumptions behind.
Assistant
The unit suite passed. The integration run is still finishing; I’m waiting on that so I can give you the final state with exact verification.
Assistant
Cleaned up the attach tests in attach_test.go so the v2-specific coverage is just the two cases you asked for:
TestAttach_V2DualWriteEnabled
TestAttach_V2DualWriteDisabled
I removed the extra “existing checkpoint appends” test since that was more specific than the behavior you wanted locked in here.
Verified with:
env GOCACHE=/tmp/go-build-cache go test ./cmd/entire/cli -run 'TestAttach_' -count=1env GOCACHE=/tmp/go-build-cache go test -tags=integration ./cmd/entire/cli/integration_test -run 'TestAttach_' -count=1